*** empty log message ***
[gnus] / lisp / gnus-gl.el
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;; GroupLens software and documentation is copyright (c) 1995 by Paul
3 ;; Resnick (Massachusetts Institute of Technology); Brad Miller, John
4 ;; Riedl, Jon Herlocker, and Joseph Konstan (University of Minnesota),
5 ;; and David Maltz (Carnegie-Mellon University).
6 ;;
7 ;; Permission to use, copy, modify, and distribute this documentation
8 ;; for non-commercial and commercial purposes without fee is hereby
9 ;; granted provided that this copyright notice and permission notice
10 ;; appears in all copies and that the names of the individuals and
11 ;; institutions holding this copyright are not used in advertising or
12 ;; publicity pertaining to this software without specific, written
13 ;; prior permission.  The copyright holders make no representations
14 ;; about the suitability of this software and documentation for any
15 ;; purpose.  It is provided ``as is'' without express or implied
16 ;; warranty.
17 ;;
18 ;; The copyright holders request that they be notified of
19 ;; modifications of this code.  Please send electronic mail to
20 ;; grouplens@cs.umn.edu for more information or to announce derived
21 ;; works.  
22 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
23 ;; Author: Brad Miller
24 ;;
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;
27 ;; User Documentation:
28 ;; To use GroupLens you must load this file.
29 ;; You must also register a pseudonym with the Better Bit Bureau.
30 ;; http://www.cs.umn.edu/Research/GroupLens
31 ;;
32 ;;    ---------------- For your .emacs or .gnus file ----------------
33 ;;
34 ;; As of version 2.5, grouplens now works as a minor mode of 
35 ;; gnus-summary-mode.  To get make that work you just need a couple of
36 ;; hooks.
37 ;; In addition, there are a few gnus-*-hooks that need to be set:
38 ;; (add-hook 'gnus-startup-hook 'bbb-login)
39 ;; (add-hook 'gnus-summary-mode-hook 'gnus-grouplens-mode)
40 ;;
41 ;; If you want to see grouplens scores using our format you might want to
42 ;; add a %uG to the gnus-summary-line-format.  For example, I use:
43 ;; (setq gnus-summary-line-format "%U%R%uG%I%(%[%4L: %-20,20uB%]%) %s\n")
44 ;; The above format also assumes that you are using gnus-bbdb  You can
45 ;; just as easily ad %uG to whatever format string you use.  Or add
46 ;; a %i to just see a simple numeric version of the predictions that
47 ;; uses less space on the summary line.  If you use %uG you have several
48 ;; choices for how things look.  See the doc string for the
49 ;; grouplens-prediction-display variable.
50 ;; (setq grouplens-prediction-display 'prediction-bar)
51 ;;
52 ;; If you use %uI on your group-line-format you will get (GroupLens Enhanced)
53 ;; after the names of newsgroups supported by GroupLens.
54 ;; (setq gnus-group-line-format "%M%S%p%5y: %(%g%) %uI\n")
55 ;;
56 ;; (setq gnus-summary-default-score 0)
57 ;;
58 ;; In addition there are some GroupLens user variables to set
59 ;; (setq grouplens-pseudonym "foobar")
60 ;; If you are using a bbb other than twain.cs.umn.edu you will need to
61 ;; set the grouplens-bbb-host variable, and possibly the
62 ;; grouplens-bbb-port variable. 
63 ;;
64 ;;(setq grouplens-newsgroups '("comp.lang.c++" "rec.humor" "rec.food.recipes"))
65 ;; This sets up the groups for which you will get predictions and ratings.
66 ;;
67 ;;                              USING GROUPLENS
68 ;; How do I Rate an article??
69 ;;   Before you type n to go to the next article, hit a number from 1-5
70 ;;   Type r in the summary buffer and you will be prompted.
71 ;;   Note that when you're in grouplens-minor-mode 'r' maskes the
72 ;;   usual reply binding for 'r'
73 ;;
74 ;; What if, Gasp, I find a bug???
75 ;; Please type M-x gnus-gl-submit-bug-report.  This will set up a
76 ;; mail buffer with the  state of variables and buffers that will help
77 ;; me debug the problem.  A short description up front would help too!
78 ;; 
79 ;; How do I display the prediction for an aritcle:
80 ;;  If you set the gnus-summary-line-format as shown above, the score
81 ;;  (prediction) will be shown automatically.
82 ;;
83 ;; 
84 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
85 ;; Programmer  Notes 
86 ;; 10/9/95
87 ;; gnus-scores-articles contains the articles
88 ;; When scoring is done, the call tree looks something like:
89 ;; gnus-possibly-score-headers
90 ;;  ==> gnus-score-headers
91 ;;      ==> gnus-score-load-file
92 ;;          ==> get-all-mids  (from the eval form)
93 ;;
94 ;; it would be nice to have one that gets called after all the other
95 ;; headers have been scored.
96 ;; we may want a variable gnus-grouplens-scale-factor
97 ;; and gnus-grouplens-offset  this would probably be either -3 or 0
98 ;; to make the scores centered around zero or not.
99 ;; Notes 10/12/95
100 ;; According to Lars, Norse god of gnus, the simple way to insert a
101 ;; call to an external function is to have a function added to the
102 ;; variable gnus-score-find-files-function  This new function
103 ;; gnus-grouplens-score-alist will return a core alist that
104 ;; has (("message-id" ("<message-id-xxxx>" score) ("<message-id-xxxy>" score))
105 ;; This seems like it would be pretty inefficient, though workable.
106 ;;
107 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
108 ;;  TODO
109 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
110 ;;
111 ;; 3. Add some more ways to rate messages
112 ;; 4. Better error handling for token timeouts.
113 ;;
114 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
115 ;; bugs
116 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
117 ;; 
118
119 (require 'gnus-score)
120 (eval-and-compile (require 'cl))
121
122 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
123 ;;;; User variables
124 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
125
126 (defvar gnus-summary-grouplens-line-format
127   "%U%R%z%l%I%(%[%4L: %-20,20n%]%) %s\n"
128   "*The line format spec in summary GroupLens mode buffers.")
129
130 (defvar gnus-summary-grouplens-lab-line-format
131   "%U%R%z%uL%I%(%[%4L: %-20,20n%]%) %s\n"
132   "*The line format spec in summary GroupLens mode buffers.")
133
134 (defvar grouplens-pseudonym ""
135   "User's pseudonym.  This pseudonym is obtained during the registration 
136 process")
137
138 (defvar grouplens-bbb-host "grouplens.cs.umn.edu"
139   "Host where the bbbd is running" )
140
141 (defvar grouplens-bbb-port 9000 
142   "Port where the bbbd is listening" )
143
144 (defvar grouplens-newsgroups 
145   '("comp.lang.c++" "rec.humor" "rec.food.recipes" "comp.groupware"
146     "mn.general" "rec.arts.movies" "rec.arts.movies.current-films"
147     "comp.lang.java" "comp.os.linux.announce" "comp.os.linux.misc"
148     "comp.os.linux.development.apps" "comp.os.linux.development.system")
149   "*Groups that are part of the GroupLens experiment.")
150
151 (defvar grouplens-prediction-display 'prediction-spot
152   "valid values are: 
153       prediction-spot -- an * corresponding to the prediction between 1 and 5, 
154       confidence-interval -- a numeric confidence interval
155       prediction-bar --  |#####     | the longer the bar, the better the article,
156       confidence-bar --  |  -----   } the prediction is in the middle of the bar,
157       confidence-spot -- )  *       | the spot gets bigger with more confidence,
158       prediction-num  --   plain-old numeric value,
159       confidence-plus-minus  -- prediction +/i confidence")
160
161 (defvar grouplens-score-offset 0
162   "Offset the prediction by this value.  
163 Setting this variable to -2 would have the following effect on grouplens 
164 scores:
165    1   -->   -2
166    2   -->   -1
167    3   -->    0
168    4   -->    1
169    5   -->    2
170    
171 the reason a user might want to do this is to combine grouplens 
172 predictions with scores calculated by other score methods")
173
174 (defvar grouplens-score-scale-factor 1
175   "This variable allow sthe user to magify the effect of grouplens scores. 
176 The scale factor is applied after the offset.")
177
178 (defvar gnus-grouplens-override-scoring t
179   "Tell Grouplens to override the normal Gnus scoring mechanism.  If
180   this variable is non-nill than Grouplens will completely override
181   the normal scoring mechanism of Gnus.  When nil, Grouplens will not
182   override the normal scoring mechanism so both can be used at once.")
183  
184
185 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
186 ;;;; Program global variables
187 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
188 (defvar grouplens-bbb-token "0"
189   "Current session token number")
190
191 (defvar grouplens-bbb-process nil
192   "Process Id of current bbbd network stream process")
193
194 (defvar grouplens-bbb-buffer nil
195   "Buffer associated with the BBBD process")
196
197 (defvar grouplens-rating-alist nil
198   "Current set of  message-id rating pairs")
199
200 (defvar grouplens-current-hashtable (make-hash-table :test 'equal :size 100))
201 ;; this seems like a pretty ugly way to get around the problem, but If 
202 ;; I don't do this, then the compiler complains when I call gethash
203 ;;
204 (eval-when-compile (setq grouplens-current-hashtable 
205                          (make-hash-table :test 'equal :size 100)))
206
207 (defvar grouplens-current-group nil)
208
209 (defvar bbb-mid-list nil)
210
211 (defvar bbb-alist nil)
212
213 (defvar bbb-timeout-secs 10
214   "Number of seconds to wait for some response from the BBB before
215     we give up and assume that something has died..." )
216
217 (defvar grouplens-previous-article nil
218   "message-id of the last article read")
219
220 (defvar bbb-read-point)
221 (defvar bbb-response-point)
222
223 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
224 ;;;;  Utility Functions
225 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
226 (defun bbb-connect-to-bbbd (host port)
227   (unless grouplens-bbb-buffer 
228     (setq grouplens-bbb-buffer 
229           (get-buffer-create (format " *BBBD trace: %s*" host)))
230     (save-excursion
231       (set-buffer grouplens-bbb-buffer)
232       (make-local-variable 'bbb-read-point)
233       (setq bbb-read-point (point-min))))
234   ;; clear the trace buffer of old output
235   (save-excursion
236     (set-buffer grouplens-bbb-buffer)
237     (erase-buffer))
238   ;; open the connection to the server
239   (setq grouplens-bbb-process nil)
240   (catch 'done
241     (condition-case error
242         (setq grouplens-bbb-process 
243               (open-network-stream "BBBD" grouplens-bbb-buffer host port))
244       (error (gnus-message 3 "Error: Failed to connect to BBB")
245              nil))
246     (and (null grouplens-bbb-process) 
247          (throw 'done nil))
248     ;; (set-process-filter grouplens-bbb-process 'bbb-process-filter)
249     (save-excursion
250       (set-buffer grouplens-bbb-buffer)
251       (setq bbb-read-point (point-min))
252       (or (bbb-read-response grouplens-bbb-process)
253           (throw 'done nil))))
254   grouplens-bbb-process)
255
256 ;; (defun bbb-process-filter (process output)
257 ;;   (save-excursion
258 ;;     (set-buffer (bbb-process-buffer process))
259 ;;     (goto-char (point-max))
260 ;;     (insert output)))
261
262 (defun bbb-send-command (process command)
263   (goto-char (point-max))
264   (insert command) 
265   (insert "\r\n")
266   (setq bbb-read-point (point))
267   (setq bbb-response-point (point))
268   (set-marker (process-mark process) (point)) ; process output also comes here
269   (process-send-string process command)
270   (process-send-string process "\r\n"))
271
272 (defun bbb-read-response (process) ; &optional return-response-string)
273   "This function eats the initial response of OK or ERROR from the BBB."
274   (let ((case-fold-search nil)
275          match-end)
276     (goto-char bbb-read-point)
277     (while (and (not (search-forward "\r\n" nil t))
278                 (accept-process-output process bbb-timeout-secs))
279       (goto-char bbb-read-point))
280     (setq match-end (point))
281     (goto-char bbb-read-point)
282     (setq bbb-read-point match-end)
283     (looking-at "OK")))
284
285 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
286 ;;;;       Login Functions
287 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
288 (defun bbb-login ()
289   "return the token number if login is successful, otherwise return nil"
290   (interactive)
291   (setq grouplens-bbb-token nil)
292   (if (not (equal grouplens-pseudonym ""))
293       (let ((bbb-process 
294              (bbb-connect-to-bbbd grouplens-bbb-host grouplens-bbb-port)))
295         (if bbb-process
296             (save-excursion 
297               (set-buffer (process-buffer bbb-process))
298               (bbb-send-command bbb-process 
299                                 (concat "login " grouplens-pseudonym))
300               (if (bbb-read-response bbb-process)
301                   (setq grouplens-bbb-token (bbb-extract-token-number))
302                 (gnus-message 3 "Error: Grouplens login failed")))))
303     (gnus-message 3 "Error: you must set a pseudonym"))
304   grouplens-bbb-token)
305
306 (defun bbb-extract-token-number ()
307   (let ((token-pos (search-forward "token=" nil t) ))
308     (if (looking-at "[0-9]+")
309         (buffer-substring token-pos (match-end 0)))))
310
311 (gnus-add-shutdown 'bbb-logout 'gnus)
312
313 (defun bbb-logout ()
314   "logout of bbb session"
315   (let ((bbb-process 
316          (bbb-connect-to-bbbd grouplens-bbb-host grouplens-bbb-port)))
317     (if bbb-process
318         (save-excursion 
319           (set-buffer (process-buffer bbb-process))
320           (bbb-send-command bbb-process (concat "logout " grouplens-bbb-token))
321           (bbb-read-response bbb-process))
322       nil)))
323
324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
325 ;;;;       Get Predictions
326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
327
328 (defun bbb-build-mid-scores-alist (groupname)
329   "this function can be called as part of the function to return the 
330 list of score files to use. See the gnus variable 
331 gnus-score-find-score-files-function.  
332
333 *Note:*  If you want to use grouplens scores along with calculated scores, 
334 you should see the offset and scale variables.  At this point, I don't 
335 recommend using both scores and grouplens predictions together."
336   (setq grouplens-current-group groupname)
337   (if (member groupname grouplens-newsgroups)
338       (let* ((mid-list (bbb-get-all-mids))
339              (predict-list (bbb-get-predictions mid-list groupname)))
340         (setq grouplens-previous-article nil)
341         ;; scores-alist should be a list of lists:
342         ;;  ((("message-id" ("<mid1>" score1 nil s) ("<mid2> score2 nil s))))
343         ;;`((("message-id" . ,predict-list))) ; Yes, this is the return value
344         (list (list (list (append (list "message-id") predict-list)))))
345     nil))
346
347 (defun bbb-get-predictions (midlist groupname)
348   "Ask the bbb for predictions, and build up the score alist."
349   (if (or (null grouplens-bbb-token)
350           (equal grouplens-bbb-token "0"))
351       (gnus-message 3 "Error: You are not logged in to a BBB")
352     (gnus-message 5 "Fetching Predictions...")
353     (let (predict-list
354           (predict-command (build-predict-command midlist groupname 
355                                                   grouplens-bbb-token))
356           (bbb-process (bbb-connect-to-bbbd grouplens-bbb-host 
357                                             grouplens-bbb-port)))
358       (if bbb-process
359           (save-excursion 
360             (set-buffer (process-buffer bbb-process))
361             (bbb-send-command bbb-process predict-command)
362             (if (bbb-read-response bbb-process)
363                 (setq predict-list (bbb-get-prediction-response bbb-process))
364               (gnus-message 1 "Invalid Token, login and try again")
365               (ding))))
366       (setq bbb-alist predict-list))))
367
368 (defun bbb-get-all-mids ()
369   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
370         (articles gnus-newsgroup-headers)
371         art this)
372     (setq bbb-mid-list nil)
373     (while articles
374       (progn (setq art (car articles)
375                    this (aref art index)
376                    articles (cdr articles))
377              (setq bbb-mid-list (cons this bbb-mid-list))))
378     bbb-mid-list))
379
380 (defun build-predict-command (mlist grpname token)
381   (let ((cmd (concat "getpredictions " token " " grpname "\r\n"))
382         art)
383     (while mlist
384       (setq art (car mlist)
385             cmd (concat cmd art "\r\n")
386             mlist (cdr mlist)))
387     (setq cmd (concat cmd ".\r\n"))
388   cmd))
389
390 (defun bbb-get-prediction-response (process)
391   (let ((case-fold-search nil)
392         match-end)
393     (goto-char bbb-read-point)
394     (while (and (not (search-forward ".\r\n" nil t))
395                 (accept-process-output process bbb-timeout-secs))
396       (goto-char bbb-read-point))
397     (setq match-end (point))
398     (goto-char (+ bbb-response-point 4))  ;; we ought to be right before OK
399     (build-response-alist)))
400
401 ;; build-response-alist assumes that the cursor has been positioned at
402 ;; the first line of the list of mid/rating pairs.  For now we will
403 ;; use a prediction of 99 to signify no prediction.  Ultimately, we
404 ;; should just ignore messages with no predictions.
405 (defun build-response-alist ()
406   (let ((resp nil)
407         (match-end (point)))
408     (setq grouplens-current-hashtable (make-hash-table :test 'equal :size 100))
409     (while
410         (cond ((looking-at "\\(<.*>\\) :nopred=")
411                (push `(,(bbb-get-mid) ,gnus-summary-default-score nil s) resp)
412                (forward-line 1)
413                t)
414               ((looking-at "\\(<.*>\\) :pred=\\([0-9]\.[0-9][0-9]\\) :conflow=\\([0-9]\.[0-9][0-9]\\) :confhigh=\\([0-9]\.[0-9][0-9]\\)")
415                (push `(,(bbb-get-mid) ,(bbb-get-pred) nil s) resp)
416                (cl-puthash (bbb-get-mid)
417                            (list (bbb-get-pred) (bbb-get-confl) (bbb-get-confh))
418                            grouplens-current-hashtable)
419                (forward-line 1)
420                t)
421               ((looking-at "\\(<.*>\\) :pred=\\([0-9]\.[0-9][0-9]\\)")
422                (push `(,(bbb-get-mid) ,(bbb-get-pred) nil s) resp)
423                (cl-puthash (bbb-get-mid)
424                            (list (bbb-get-pred) 0 0)
425                            grouplens-current-hashtable)
426                (forward-line 1)
427                t)
428               (t nil)))
429     resp))
430
431 ;; these two functions assume that there is an active match lying
432 ;; around.  Where the first parenthesized expression is the
433 ;; message-id, and the second is the prediction.  Since gnus assumes
434 ;; that scores are integer values?? we round the prediction.
435 (defun bbb-get-mid ()
436   (buffer-substring (match-beginning 1) (match-end 1)))
437
438 (defun bbb-get-pred ()
439   (let ((tpred (round (string-to-int (buffer-substring  
440                                       (match-beginning 2) 
441                                       (match-end 2))))))
442     (if (> tpred 0)
443         (* grouplens-score-scale-factor (+ grouplens-score-offset  tpred))
444       1)))
445
446 (defun bbb-get-confl ()
447   (string-to-number (buffer-substring (match-beginning 3) (match-end 3))))
448
449 (defun bbb-get-confh ()
450   (string-to-number (buffer-substring (match-beginning 4) (match-end 4))))
451
452 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
453 ;;;;      Prediction Display
454 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
455 (defconst grplens-rating-range 4.0)
456 (defconst grplens-maxrating 5)
457 (defconst grplens-minrating 1)
458 (defconst grplens-predstringsize 12)
459
460 (defalias 'bbb-grouplens-score 'gnus-user-format-function-G)
461
462 (defvar gnus-tmp-score)
463 (defun gnus-user-format-function-G (header)
464   (let* ((rate-string (make-string 12 ? ))
465          (mid (aref header (nth 1 (assoc "message-id" gnus-header-index))))
466          (hashent (gethash mid grouplens-current-hashtable))
467          (iscore (if (string-match "September" gnus-version) 
468                      gnus-tmp-score
469                    score))
470          (low (car (cdr hashent)))
471          (high (car (cdr (cdr hashent)))))
472     (aset rate-string 0 ?|) 
473     (aset rate-string 11 ?|)
474     (unless (member grouplens-current-group grouplens-newsgroups)
475       (unless (equal grouplens-prediction-display 'prediction-num)
476         (cond ((< iscore 0)
477                (setq iscore 1))
478               ((> iscore 5)
479                (setq iscore 5))))
480       (setq low 0) 
481       (setq high 0))
482     (if (and (bbb-valid-score iscore) 
483              (not (null mid)))
484         (cond 
485          ;; prediction-spot
486          ((equal grouplens-prediction-display 'prediction-spot)
487           (setq rate-string (bbb-fmt-prediction-spot rate-string iscore)))
488          ;; confidence-interval
489          ((equal grouplens-prediction-display 'confidence-interval)
490           (setq rate-string (bbb-fmt-confidence-interval iscore low high)))
491          ;; prediction-bar
492          ((equal grouplens-prediction-display 'prediction-bar)
493           (setq rate-string (bbb-fmt-prediction-bar rate-string iscore)))
494          ;; confidence-bar
495          ((equal grouplens-prediction-display 'confidence-bar)
496           (setq rate-string (format "|   %4.2f   |" iscore)))
497          ;; confidence-spot
498          ((equal grouplens-prediction-display 'confidence-spot)
499           (setq rate-string (format "|   %4.2f   |" iscore)))
500          ;; prediction-num
501          ((equal grouplens-prediction-display 'prediction-num)
502           (setq rate-string (bbb-fmt-prediction-num iscore)))
503          ;; confidence-plus-minus
504          ((equal grouplens-prediction-display 'confidence-plus-minus)
505                (setq rate-string (bbb-fmt-confidence-plus-minus iscore low high))
506                )
507          (t (gnus-message 3 "Invalid prediction display type")))
508       (aset rate-string 5 ?N) (aset rate-string 6 ?A))
509     rate-string))
510
511 ;;
512 ;; Gnus user format function that doesn't depend on
513 ;; bbb-build-mid-scores-alist being used as the score function, but is
514 ;; instead called from gnus-select-group-hook. -- LAB
515 (defun gnus-user-format-function-L (header)
516   (if (not (member grouplens-current-group grouplens-newsgroups))
517       ;; Return an empty string
518       ""
519     (let* ((rate-string (make-string 12 ? ))
520            (mid (aref header (nth 1 (assoc "message-id" gnus-header-index))))
521            (hashent (gethash mid grouplens-current-hashtable))
522            (pred (or (nth 0 hashent) 0))
523            (low (nth 1 hashent))
524            (high (nth 2 hashent)))
525       ;; Init rate-string
526       (aset rate-string 0 ?|) 
527       (aset rate-string 11 ?|)
528       (unless (equal grouplens-prediction-display 'prediction-num)
529         (cond ((< pred 0)
530                (setq pred 1))
531               ((> pred 5)
532                (setq pred 5))))
533       ;; If no entry in BBB hash mark rate string as NA and return
534       (cond 
535        ((null hashent) 
536         (aset rate-string 5 ?N) 
537         (aset rate-string 6 ?A)
538         rate-string)
539
540        ((equal grouplens-prediction-display 'prediction-spot)
541         (bbb-fmt-prediction-spot rate-string pred))
542        
543        ((equal grouplens-prediction-display 'confidence-interval)
544         (bbb-fmt-confidence-interval pred low high))
545        
546        ((equal grouplens-prediction-display 'prediction-bar)
547         (bbb-fmt-prediction-bar rate-string pred))
548
549        ((equal grouplens-prediction-display 'confidence-bar)
550         (format "|   %4.2f   |" pred))
551
552        ((equal grouplens-prediction-display 'confidence-spot)
553         (format "|   %4.2f   |" pred))
554        
555        ((equal grouplens-prediction-display 'prediction-num)
556         (bbb-fmt-prediction-num pred))
557        
558        ((equal grouplens-prediction-display 'confidence-plus-minus)
559         (bbb-fmt-confidence-plus-minus pred low high))
560        
561        (t 
562         (gnus-message 3 "Invalid prediction display type")
563         (aset rate-string 0 ?|) 
564         (aset rate-string 11 ?|)
565         rate-string)))))
566
567 (defun bbb-valid-score (score)
568   (or (equal grouplens-prediction-display 'prediction-num)
569       (and (>= score grplens-minrating)
570            (<= score grplens-maxrating))))
571
572 (defun bbb-requires-confidence (format-type)
573   (or (equal format-type 'confidence-plus-minus)
574       (equal format-type 'confidence-spot)
575       (equal format-type 'confidence-interval)))
576
577 (defun bbb-have-confidence (clow chigh)
578   (not (or (null clow)
579            (null chigh))))
580
581 (defun bbb-fmt-prediction-spot (rate-string score)
582   (aset rate-string
583         (round (* (/ (- score grplens-minrating) grplens-rating-range)
584                   (+ (- grplens-predstringsize 4) 1.49)))
585         ?*)
586   rate-string)
587
588 (defun bbb-fmt-confidence-interval (score low high)
589   (if (bbb-have-confidence low high)
590       (format "|%4.2f-%4.2f |" low high)
591     (bbb-fmt-prediction-num score)))
592
593 (defun bbb-fmt-confidence-plus-minus (score low high)
594   (if (bbb-have-confidence low high)
595       (format "|%3.1f+/-%4.2f|" score (/ (- high low) 2.0))
596     (bbb-fmt-prediction-num score)))
597
598 (defun bbb-fmt-prediction-bar (rate-string score)
599   (let* ((i 1) 
600          (step (/ grplens-rating-range (- grplens-predstringsize 4)))
601          (half-step (/ step 2))
602          (loc (- grplens-minrating half-step)))
603     (while (< i (- grplens-predstringsize 2))
604       (if (> score loc)
605           (aset rate-string i ?#)
606         (aset rate-string i ? ))
607       (setq i (+ i 1))
608       (setq loc (+ loc step)))
609     )
610   rate-string)
611
612 (defun bbb-fmt-prediction-num (score)
613   (format "|   %4.2f   |" score))
614
615 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
616 ;;;;       Put Ratings
617 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
618
619 ;; The message-id for the current article can be found in
620 ;; (aref gnus-current-headers (nth 1 (assoc "message-id" gnus-header-index)))
621
622 (defun bbb-put-ratings ()
623   (if (and grouplens-rating-alist 
624            (member gnus-newsgroup-name grouplens-newsgroups))
625       (let ((bbb-process (bbb-connect-to-bbbd grouplens-bbb-host 
626                                           grouplens-bbb-port))
627             (rate-command (build-rate-command grouplens-rating-alist)))
628         (if bbb-process
629             (save-excursion 
630               (set-buffer (process-buffer bbb-process))
631               (gnus-message 5 "Sending Ratings...")
632               (bbb-send-command bbb-process rate-command)
633               (if (bbb-read-response bbb-process)
634                   (setq grouplens-rating-alist nil)
635                 (gnus-message 1 
636                               "Token timed out: call bbb-login and quit again")
637                 (ding))
638               (gnus-message 5 "Sending Ratings...Done"))
639           (gnus-message 3 "No BBB connection")))
640     (setq grouplens-rating-alist nil)))
641
642 (defun build-rate-command (rate-alist)
643   (let (this
644         (cmd (concat "putratings " grouplens-bbb-token 
645                      " " grouplens-current-group " \r\n")))
646     (while rate-alist
647       (setq this (car rate-alist)
648             cmd (concat cmd (car this) " :rating=" (cadr this) ".00"
649                         " :time=" (cddr this) "\r\n")
650             rate-alist (cdr rate-alist)))
651     (concat cmd ".\r\n")))
652
653 ;; Interactive rating functions.
654 (defun bbb-summary-rate-article (rating &optional midin)
655   (interactive "nRating: ")
656   (when (member gnus-newsgroup-name grouplens-newsgroups)
657     (let ((mid (or midin (bbb-get-current-id))))
658       (if (and rating 
659                (>= rating grplens-minrating) 
660                (<= rating grplens-maxrating)
661                mid)
662           (let ((oldrating (assoc mid grouplens-rating-alist)))
663             (if oldrating
664                 (setcdr oldrating (cons rating 0))
665               (push `(,mid . (,rating . 0)) grouplens-rating-alist))
666             (gnus-summary-mark-article nil (int-to-string rating)))     
667         (gnus-message 3 "Invalid rating")))))
668
669 (defun grouplens-next-unread-article (rating)
670   "Select unread article after current one."
671   (interactive "P")
672   (if rating (bbb-summary-rate-article rating))
673   (gnus-summary-next-unread-article))
674
675 (defun grouplens-best-unread-article (rating)
676   "Select unread article after current one."
677   (interactive "P")
678   (if rating (bbb-summary-rate-article rating))
679   (gnus-summary-best-unread-article))
680
681 (defun grouplens-summary-catchup-and-exit (rating)
682    "Mark all articles not marked as unread in this newsgroup as read, 
683     then exit.   If prefix argument ALL is non-nil, all articles are 
684     marked as read."
685    (interactive "P")
686    (if rating
687        (bbb-summary-rate-article rating))
688    (if (numberp rating)
689        (gnus-summary-catchup-and-exit)
690      (gnus-summary-catchup-and-exit rating)))
691
692 (defun grouplens-score-thread (score)
693   "Raise the score of the articles in the current thread with SCORE."
694   (interactive "nRating: ")
695   (let (e)
696     (save-excursion
697       (let ((articles (gnus-summary-articles-in-thread)))
698         (while articles
699           (gnus-summary-goto-subject (car articles))
700           (gnus-set-global-variables)
701           (bbb-summary-rate-article score
702                                     (mail-header-id 
703                                      (gnus-summary-article-header 
704                                       (car articles))))
705           (setq articles (cdr articles))))
706       (setq e (point)))
707     (let ((gnus-summary-check-current t))
708       (or (zerop (gnus-summary-next-subject 1 t))
709           (goto-char e))))
710   (gnus-summary-recenter)
711   (gnus-summary-position-point)
712   (gnus-set-mode-line 'summary))
713
714
715 (defun bbb-get-current-id ()
716   (if gnus-current-headers
717       (aref gnus-current-headers 
718             (nth 1 (assoc "message-id" gnus-header-index)))
719     (gnus-message 3 "You must select an article before you rate it")))
720
721 (defvar gnus-tmp-group)
722 (defun gnus-user-format-function-I (header)
723   (let ((gname (if (string-match "September" gnus-version)
724                    gnus-tmp-group
725                  group)))
726     (if (member gname grouplens-newsgroups) "  (GroupLens Enhanced)" "")))
727
728 (defun bbb-grouplens-group-p (group)
729   "Say whether GROUP is a GroupLens group."
730   (if (member group grouplens-newsgroups) " (GroupLens Enhanced)" ""))
731
732 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
733 ;;          TIME SPENT READING
734 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
735 (defvar grouplens-current-starting-time nil)
736
737 (defun grouplens-start-timer ()
738   (setq grouplens-current-starting-time (current-time)))
739
740 (defun grouplens-elapsed-time ()
741   (let ((et (bbb-time-float (current-time))))
742     (- et (bbb-time-float grouplens-current-starting-time))))
743
744 (defun bbb-time-float (timeval)
745   (+ (* (car timeval) 65536) 
746         (cadr timeval)))
747
748 (defun grouplens-do-time ()
749   (when (member gnus-newsgroup-name grouplens-newsgroups)
750     (when grouplens-previous-article
751       (let ((elapsed-time (grouplens-elapsed-time))
752             (oldrating (assoc grouplens-previous-article 
753                               grouplens-rating-alist)))
754         (if (not oldrating)
755             (push `(,grouplens-previous-article . (0 . ,elapsed-time))
756                   grouplens-rating-alist)
757           (setcdr oldrating (cons (cadr oldrating) elapsed-time)))))
758     (grouplens-start-timer)
759     (setq grouplens-previous-article (bbb-get-current-id))))
760
761 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
762 ;;          BUG REPORTING
763 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
764
765 (defconst gnus-gl-version "gnus-gl.el 2.10")
766 (defconst gnus-gl-maintainer-address "grouplens-bug@cs.umn.edu")
767 (defun gnus-gl-submit-bug-report ()
768   "Submit via mail a bug report on gnus-gl"
769   (interactive)
770   (require 'reporter)
771   (reporter-submit-bug-report gnus-gl-maintainer-address
772                               (concat "gnus-gl.el " gnus-gl-version)
773                               (list 'grouplens-pseudonym
774                                     'grouplens-bbb-host
775                                     'grouplens-bbb-port
776                                     'grouplens-newsgroups
777                                     'grouplens-bbb-token
778                                     'grouplens-bbb-process
779                                     'grouplens-current-group
780                                     'grouplens-previous-article
781                                     'grouplens-mid-list
782                                     'bbb-alist)
783                               nil
784                               'gnus-gl-get-trace))
785
786 (defun gnus-gl-get-trace ()
787   "Insert the contents of the BBBD trace buffer"
788   (if grouplens-bbb-buffer (insert-buffer grouplens-bbb-buffer)))
789
790 ;;;
791 ;;; Additions to make gnus-grouplens-mode  Warning Warning!!
792 ;;;      This version of the gnus-grouplens-mode does
793 ;;;      not work with gnus-5.x.  The "old" way of
794 ;;;      setting up GroupLens still works however.
795 ;;;
796 (defvar gnus-grouplens-mode nil
797   "Minor mode for providing a GroupLens interface in Gnus summary buffers.")
798
799 (defvar gnus-grouplens-mode-map nil)
800
801 (unless gnus-grouplens-mode-map
802   (setq gnus-grouplens-mode-map (make-keymap))
803   (gnus-define-keys
804    gnus-grouplens-mode-map
805    "n" grouplens-next-unread-article
806    "r" bbb-summary-rate-article
807    "k" grouplens-score-thread
808    "c" grouplens-summary-catchup-and-exit
809    "," grouplens-best-unread-article))
810
811 (defun gnus-grouplens-make-menu-bar ()
812   (unless (boundp 'gnus-grouplens-menu)
813     (easy-menu-define
814      gnus-grouplens-menu gnus-grouplens-mode-map ""
815      '("GroupLens"
816        ["Login" bbb-login t]
817        ["Rate" bbb-summary-rate-article t]
818        ["Next article" grouplens-next-unread-article t]
819        ["Best article" grouplens-best-unread-article t]
820        ["Raise thread" grouplens-score-thread t]
821        ["Report bugs" gnus-gl-submit-bug-report t]))))
822
823 (defun gnus-grouplens-mode (&optional arg)
824   "Minor mode for providing a GroupLens interface in Gnus summary buffers."
825   (interactive "P")
826   (when (and (eq major-mode 'gnus-summary-mode)
827              (member gnus-newsgroup-name grouplens-newsgroups))
828     (make-local-variable 'gnus-grouplens-mode)
829     (setq gnus-grouplens-mode 
830           (if (null arg) (not gnus-grouplens-mode)
831             (> (prefix-numeric-value arg) 0)))
832     (when gnus-grouplens-mode
833       (if (not (fboundp 'make-local-hook))
834           (add-hook 'gnus-select-article-hook 'grouplens-do-time)
835         (make-local-hook 'gnus-select-article-hook)
836         (add-hook 'gnus-select-article-hook 'grouplens-do-time nil 'local))
837       (if (not (fboundp 'make-local-hook))
838           (add-hook 'gnus-exit-group-hook 'bbb-put-ratings)
839         (make-local-hook 'gnus-exit-group-hook)
840         (add-hook 'gnus-exit-group-hook 'bbb-put-ratings nil 'local))
841       (make-local-variable 'gnus-score-find-score-files-function)
842       (if gnus-grouplens-override-scoring
843           (setq gnus-score-find-score-files-function 
844                 'bbb-build-mid-scores-alist)
845         (add-hook 'gnus-select-group-hook 
846                   '(lambda() 
847                      (bbb-build-mid-scores-alist gnus-newsgroup-name))))
848       (make-local-variable 'gnus-summary-line-format)
849       (if gnus-grouplens-override-scoring
850         
851           (setq gnus-summary-line-format gnus-summary-grouplens-lab-line-format))
852       (make-local-variable 'gnus-summary-line-format-spec)
853
854       ;; Set up the menu.
855       (when (and menu-bar-mode
856                  (gnus-visual-p 'grouplens-menu 'menu))
857         (gnus-grouplens-make-menu-bar))
858       (unless (assq 'gnus-grouplens-mode minor-mode-alist)
859         (push '(gnus-grouplens-mode " GroupLens") minor-mode-alist))
860       (unless (assq 'gnus-grouplens-mode minor-mode-map-alist)
861         (push (cons 'gnus-grouplens-mode gnus-grouplens-mode-map)
862               minor-mode-map-alist))
863       (run-hooks 'gnus-grouplens-mode-hook))))
864
865 (provide 'gnus-gl)
866
867 ;;; end gnus-gl.el