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