*** empty log message ***
[gnus] / lisp / gnus-gl.el
1 ;;; gnus-gl.el --- an interface to GroupLens for Gnus
2 ;; Copyright (C) 1995,96 Free Software Foundation, Inc.
3
4 ;; Author: Brad Miller <bmiller@cs.umn.edu>
5 ;; Keywords: news, score
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; GroupLens software and documentation is copyright (c) 1995 by Paul
28 ;; Resnick (Massachusetts Institute of Technology); Brad Miller, John
29 ;; Riedl, Jon Herlocker, and Joseph Konstan (University of Minnesota),
30 ;; and David Maltz (Carnegie-Mellon University).
31 ;;
32 ;; Permission to use, copy, modify, and distribute this documentation
33 ;; for non-commercial and commercial purposes without fee is hereby
34 ;; granted provided that this copyright notice and permission notice
35 ;; appears in all copies and that the names of the individuals and
36 ;; institutions holding this copyright are not used in advertising or
37 ;; publicity pertaining to this software without specific, written
38 ;; prior permission.  The copyright holders make no representations
39 ;; about the suitability of this software and documentation for any
40 ;; purpose.  It is provided ``as is'' without express or implied
41 ;; warranty.
42 ;;
43 ;; The copyright holders request that they be notified of
44 ;; modifications of this code.  Please send electronic mail to
45 ;; grouplens@cs.umn.edu for more information or to announce derived
46 ;; works.  
47 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
48 ;; Author: Brad Miller
49 ;;
50 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
51 ;;
52 ;; User Documentation:
53 ;; To use GroupLens you must load this file.
54 ;; You must also register a pseudonym with the Better Bit Bureau.
55 ;; http://www.cs.umn.edu/Research/GroupLens
56 ;;
57 ;;    ---------------- For your .emacs or .gnus file ----------------
58 ;;
59 ;; As of version 2.5, grouplens now works as a minor mode of 
60 ;; gnus-summary-mode.  To get make that work you just need a couple of
61 ;; hooks.
62 ;; (setq gnus-use-grouplens t)
63 ;; (setq grouplens-pseudonym "")
64 ;; (setq grouplens-bbb-host "grouplens.cs.umn.edu")
65 ;;
66 ;; (setq gnus-summary-default-score 0)
67 ;;
68 ;;                              USING GROUPLENS
69 ;; How do I Rate an article??
70 ;;   Before you type n to go to the next article, hit a number from 1-5
71 ;;   Type r in the summary buffer and you will be prompted.
72 ;;   Note that when you're in grouplens-minor-mode 'r' maskes the
73 ;;   usual reply binding for 'r'
74 ;;
75 ;; What if, Gasp, I find a bug???
76 ;; Please type M-x gnus-gl-submit-bug-report.  This will set up a
77 ;; mail buffer with the  state of variables and buffers that will help
78 ;; me debug the problem.  A short description up front would help too!
79 ;; 
80 ;; How do I display the prediction for an aritcle:
81 ;;  If you set the gnus-summary-line-format as shown above, the score
82 ;;  (prediction) will be shown automatically.
83 ;;
84 ;; 
85 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
86 ;; Programmer  Notes 
87 ;; 10/9/95
88 ;; gnus-scores-articles contains the articles
89 ;; When scoring is done, the call tree looks something like:
90 ;; gnus-possibly-score-headers
91 ;;  ==> gnus-score-headers
92 ;;      ==> gnus-score-load-file
93 ;;          ==> get-all-mids  (from the eval form)
94 ;;
95 ;; it would be nice to have one that gets called after all the other
96 ;; headers have been scored.
97 ;; we may want a variable gnus-grouplens-scale-factor
98 ;; and gnus-grouplens-offset  this would probably be either -3 or 0
99 ;; to make the scores centered around zero or not.
100 ;; Notes 10/12/95
101 ;; According to Lars, Norse god of gnus, the simple way to insert a
102 ;; call to an external function is to have a function added to the
103 ;; variable gnus-score-find-files-function  This new function
104 ;; gnus-grouplens-score-alist will return a core alist that
105 ;; has (("message-id" ("<message-id-xxxx>" score) ("<message-id-xxxy>" score))
106 ;; This seems like it would be pretty inefficient, though workable.
107 ;;
108 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
109 ;;  TODO
110 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
111 ;;
112 ;; 3. Add some more ways to rate messages
113 ;; 4. Better error handling for token timeouts.
114 ;;
115 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
116 ;; bugs
117 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
118 ;; 
119
120 ;;; Code:
121
122 (require 'gnus-score)
123 (require 'cl)
124
125 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
126 ;;;; User variables
127 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
128
129 (defvar gnus-summary-grouplens-line-format
130   "%U%R%z%l%I%(%[%4L: %-20,20n%]%) %s\n"
131   "*The line format spec in summary GroupLens mode buffers.")
132
133 (defvar grouplens-pseudonym ""
134   "User's pseudonym.  This pseudonym is obtained during the registration process")
135
136 (defvar grouplens-bbb-host "grouplens.cs.umn.edu"
137   "Host where the bbbd is running" )
138
139 (defvar grouplens-bbb-port 9000 
140   "Port where the bbbd is listening" )
141
142 (defvar grouplens-newsgroups 
143   '("comp.lang.c++" "rec.humor" "rec.food.recipes" "comp.groupware"
144     "mn.general" "rec.arts.movies" "rec.arts.movies.current-films"
145     "comp.lang.java" "comp.os.linux.announce" "comp.os.linux.misc"
146     "comp.os.linux.development.apps" "comp.os.linux.development.system")
147   "*Groups that are part of the GroupLens experiment.")
148
149 (defvar grouplens-prediction-display 'prediction-spot
150   "valid values are: 
151       prediction-spot -- an * corresponding to the prediction between 1 and 5, 
152       confidence-interval -- a numeric confidence interval
153       prediction-bar --  |#####     | the longer the bar, the better the article,
154       confidence-bar --  |  -----   } the prediction is in the middle of the bar,
155       confidence-spot -- )  *       | the spot gets bigger with more confidence,
156       prediction-num  --   plain-old numeric value,
157       confidence-plus-minus  -- prediction +/i confidence")
158
159 (defvar grouplens-score-offset 0
160   "Offset the prediction by this value.  
161 Setting this variable to -2 would have the following effect on
162 GroupLens scores:
163
164    1   -->   -2
165    2   -->   -1
166    3   -->    0
167    4   -->    1
168    5   -->    2
169    
170 The reason is that a user might want to do this is to combine
171 GroupLens predictions with scores calculated by other score methods.")
172
173 (defvar grouplens-score-scale-factor 1
174   "This variable allows the user to magnify the effect of GroupLens scores. 
175 The scale factor is applied after the offset.")
176
177 (defvar gnus-grouplens-override-scoring 'override
178   "Tell Grouplens to override the normal Gnus scoring mechanism.  
179 GroupLens scores can be combined with gnus scores in one of three ways.
180 'override -- just use grouplens predictions for grouplens groups
181 'combine  -- combine grouplens scores with gnus scores
182 'separate -- treat grouplens scores completely separate from gnus")
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.
215 If this times out 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 (bbb-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 bbb-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     (bbb-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 bbb-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 (string-to-number (buffer-substring  
440                                       (match-beginning 2) 
441                                       (match-end 2)))))
442     (if (> tpred 0)
443         (round (* 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 (defvar gnus-tmp-score)
461 (defun bbb-grouplens-score (header)
462   (if (eq gnus-grouplens-override-scoring 'separate)
463       (bbb-grouplens-other-score 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 gnus-tmp-score)
468            (low (car (cdr hashent)))
469            (high (car (cdr (cdr hashent)))))
470       (aset rate-string 0 ?|) 
471       (aset rate-string 11 ?|)
472       (unless (member grouplens-current-group grouplens-newsgroups)
473         (unless (equal grouplens-prediction-display 'prediction-num)
474           (cond ((< iscore 0)
475                  (setq iscore 1))
476                 ((> iscore 5)
477                  (setq iscore 5))))
478         (setq low 0) 
479         (setq high 0))
480       (if (and (bbb-valid-score iscore) 
481                (not (null mid)))
482           (cond 
483            ;; prediction-spot
484            ((equal grouplens-prediction-display 'prediction-spot)
485             (setq rate-string (bbb-fmt-prediction-spot rate-string iscore)))
486            ;; confidence-interval
487            ((equal grouplens-prediction-display 'confidence-interval)
488             (setq rate-string (bbb-fmt-confidence-interval iscore low high)))
489            ;; prediction-bar
490            ((equal grouplens-prediction-display 'prediction-bar)
491             (setq rate-string (bbb-fmt-prediction-bar rate-string iscore)))
492            ;; confidence-bar
493            ((equal grouplens-prediction-display 'confidence-bar)
494             (setq rate-string (format "|   %4.2f   |" iscore)))
495            ;; confidence-spot
496            ((equal grouplens-prediction-display 'confidence-spot)
497             (setq rate-string (format "|   %4.2f   |" iscore)))
498            ;; prediction-num
499            ((equal grouplens-prediction-display 'prediction-num)
500             (setq rate-string (bbb-fmt-prediction-num iscore)))
501            ;; confidence-plus-minus
502            ((equal grouplens-prediction-display 'confidence-plus-minus)
503             (setq rate-string (bbb-fmt-confidence-plus-minus iscore low high))
504             )
505            (t (gnus-message 3 "Invalid prediction display type")))
506         (aset rate-string 5 ?N) (aset rate-string 6 ?A))
507       rate-string)))
508
509 ;;
510 ;; Gnus user format function that doesn't depend on
511 ;; bbb-build-mid-scores-alist being used as the score function, but is
512 ;; instead called from gnus-select-group-hook. -- LAB
513 (defun bbb-grouplens-other-score (header)
514   (if (not (member grouplens-current-group grouplens-newsgroups))
515       ;; Return an empty string
516       ""
517     (let* ((rate-string (make-string 12 ? ))
518            (mid (aref header (nth 1 (assoc "message-id" gnus-header-index))))
519            (hashent (gethash mid grouplens-current-hashtable))
520            (pred (or (nth 0 hashent) 0))
521            (low (nth 1 hashent))
522            (high (nth 2 hashent)))
523       ;; Init rate-string
524       (aset rate-string 0 ?|) 
525       (aset rate-string 11 ?|)
526       (unless (equal grouplens-prediction-display 'prediction-num)
527         (cond ((< pred 0)
528                (setq pred 1))
529               ((> pred 5)
530                (setq pred 5))))
531       ;; If no entry in BBB hash mark rate string as NA and return
532       (cond 
533        ((null hashent) 
534         (aset rate-string 5 ?N) 
535         (aset rate-string 6 ?A)
536         rate-string)
537
538        ((equal grouplens-prediction-display 'prediction-spot)
539         (bbb-fmt-prediction-spot rate-string pred))
540        
541        ((equal grouplens-prediction-display 'confidence-interval)
542         (bbb-fmt-confidence-interval pred low high))
543        
544        ((equal grouplens-prediction-display 'prediction-bar)
545         (bbb-fmt-prediction-bar rate-string pred))
546
547        ((equal grouplens-prediction-display 'confidence-bar)
548         (format "|   %4.2f   |" pred))
549
550        ((equal grouplens-prediction-display 'confidence-spot)
551         (format "|   %4.2f   |" pred))
552        
553        ((equal grouplens-prediction-display 'prediction-num)
554         (bbb-fmt-prediction-num pred))
555        
556        ((equal grouplens-prediction-display 'confidence-plus-minus)
557         (bbb-fmt-confidence-plus-minus pred low high))
558        
559        (t 
560         (gnus-message 3 "Invalid prediction display type")
561         (aset rate-string 0 ?|) 
562         (aset rate-string 11 ?|)
563         rate-string)))))
564
565 (defun bbb-valid-score (score)
566   (or (equal grouplens-prediction-display 'prediction-num)
567       (and (>= score grplens-minrating)
568            (<= score grplens-maxrating))))
569
570 (defun bbb-requires-confidence (format-type)
571   (or (equal format-type 'confidence-plus-minus)
572       (equal format-type 'confidence-spot)
573       (equal format-type 'confidence-interval)))
574
575 (defun bbb-have-confidence (clow chigh)
576   (not (or (null clow)
577            (null chigh))))
578
579 (defun bbb-fmt-prediction-spot (rate-string score)
580   (aset rate-string
581         (round (* (/ (- score grplens-minrating) grplens-rating-range)
582                   (+ (- grplens-predstringsize 4) 1.49)))
583         ?*)
584   rate-string)
585
586 (defun bbb-fmt-confidence-interval (score low high)
587   (if (bbb-have-confidence low high)
588       (format "|%4.2f-%4.2f |" low high)
589     (bbb-fmt-prediction-num score)))
590
591 (defun bbb-fmt-confidence-plus-minus (score low high)
592   (if (bbb-have-confidence low high)
593       (format "|%3.1f+/-%4.2f|" score (/ (- high low) 2.0))
594     (bbb-fmt-prediction-num score)))
595
596 (defun bbb-fmt-prediction-bar (rate-string score)
597   (let* ((i 1) 
598          (step (/ grplens-rating-range (- grplens-predstringsize 4)))
599          (half-step (/ step 2))
600          (loc (- grplens-minrating half-step)))
601     (while (< i (- grplens-predstringsize 2))
602       (if (> score loc)
603           (aset rate-string i ?#)
604         (aset rate-string i ? ))
605       (setq i (+ i 1))
606       (setq loc (+ loc step)))
607     )
608   rate-string)
609
610 (defun bbb-fmt-prediction-num (score)
611   (format "|   %4.2f   |" score))
612
613 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
614 ;;;;       Put Ratings
615 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
616
617 ;; The message-id for the current article can be found in
618 ;; (aref gnus-current-headers (nth 1 (assoc "message-id" gnus-header-index)))
619
620 (defun bbb-put-ratings ()
621   (if (and grouplens-rating-alist 
622            (member gnus-newsgroup-name grouplens-newsgroups))
623       (let ((bbb-process (bbb-connect-to-bbbd grouplens-bbb-host 
624                                           grouplens-bbb-port))
625             (rate-command (bbb-build-rate-command grouplens-rating-alist)))
626         (if bbb-process
627             (save-excursion 
628               (set-buffer (process-buffer bbb-process))
629               (gnus-message 5 "Sending Ratings...")
630               (bbb-send-command bbb-process rate-command)
631               (if (bbb-read-response bbb-process)
632                   (setq grouplens-rating-alist nil)
633                 (gnus-message 1 
634                               "Token timed out: call bbb-login and quit again")
635                 (ding))
636               (gnus-message 5 "Sending Ratings...Done"))
637           (gnus-message 3 "No BBB connection")))
638     (setq grouplens-rating-alist nil)))
639
640 (defun bbb-build-rate-command (rate-alist)
641   (let (this
642         (cmd (concat "putratings " grouplens-bbb-token 
643                      " " grouplens-current-group " \r\n")))
644     (while rate-alist
645       (setq this (car rate-alist)
646             cmd (concat cmd (car this) " :rating=" (cadr this) ".00"
647                         " :time=" (cddr this) "\r\n")
648             rate-alist (cdr rate-alist)))
649     (concat cmd ".\r\n")))
650
651 ;; Interactive rating functions.
652 (defun bbb-summary-rate-article (rating &optional midin)
653   (interactive "nRating: ")
654   (when (member gnus-newsgroup-name grouplens-newsgroups)
655     (let ((mid (or midin (bbb-get-current-id))))
656       (if (and rating 
657                (>= rating grplens-minrating) 
658                (<= rating grplens-maxrating)
659                mid)
660           (let ((oldrating (assoc mid grouplens-rating-alist)))
661             (if oldrating
662                 (setcdr oldrating (cons rating 0))
663               (push `(,mid . (,rating . 0)) grouplens-rating-alist))
664             (gnus-summary-mark-article nil (int-to-string rating)))     
665         (gnus-message 3 "Invalid rating")))))
666
667 (defun grouplens-next-unread-article (rating)
668   "Select unread article after current one."
669   (interactive "P")
670   (if rating (bbb-summary-rate-article rating))
671   (gnus-summary-next-unread-article))
672
673 (defun grouplens-best-unread-article (rating)
674   "Select unread article after current one."
675   (interactive "P")
676   (if rating (bbb-summary-rate-article rating))
677   (gnus-summary-best-unread-article))
678
679 (defun grouplens-summary-catchup-and-exit (rating)
680    "Mark all articles not marked as unread in this newsgroup as read, 
681     then exit.   If prefix argument ALL is non-nil, all articles are 
682     marked as read."
683    (interactive "P")
684    (if rating
685        (bbb-summary-rate-article rating))
686    (if (numberp rating)
687        (gnus-summary-catchup-and-exit)
688      (gnus-summary-catchup-and-exit rating)))
689
690 (defun grouplens-score-thread (score)
691   "Raise the score of the articles in the current thread with SCORE."
692   (interactive "nRating: ")
693   (let (e)
694     (save-excursion
695       (let ((articles (gnus-summary-articles-in-thread)))
696         (while articles
697           (gnus-summary-goto-subject (car articles))
698           (gnus-set-global-variables)
699           (bbb-summary-rate-article score
700                                     (mail-header-id 
701                                      (gnus-summary-article-header 
702                                       (car articles))))
703           (setq articles (cdr articles))))
704       (setq e (point)))
705     (let ((gnus-summary-check-current t))
706       (or (zerop (gnus-summary-next-subject 1 t))
707           (goto-char e))))
708   (gnus-summary-recenter)
709   (gnus-summary-position-point)
710   (gnus-set-mode-line 'summary))
711
712
713 (defun bbb-get-current-id ()
714   (if gnus-current-headers
715       (aref gnus-current-headers 
716             (nth 1 (assoc "message-id" gnus-header-index)))
717     (gnus-message 3 "You must select an article before you rate it")))
718
719 (defun bbb-grouplens-group-p (group)
720   "Say whether GROUP is a GroupLens group."
721   (if (member group grouplens-newsgroups) " (GroupLens Enhanced)" ""))
722
723 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
724 ;;          TIME SPENT READING
725 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
726 (defvar grouplens-current-starting-time nil)
727
728 (defun grouplens-start-timer ()
729   (setq grouplens-current-starting-time (current-time)))
730
731 (defun grouplens-elapsed-time ()
732   (let ((et (bbb-time-float (current-time))))
733     (- et (bbb-time-float grouplens-current-starting-time))))
734
735 (defun bbb-time-float (timeval)
736   (+ (* (car timeval) 65536) 
737         (cadr timeval)))
738
739 (defun grouplens-do-time ()
740   (when (member gnus-newsgroup-name grouplens-newsgroups)
741     (when grouplens-previous-article
742       (let ((elapsed-time (grouplens-elapsed-time))
743             (oldrating (assoc grouplens-previous-article 
744                               grouplens-rating-alist)))
745         (if (not oldrating)
746             (push `(,grouplens-previous-article . (0 . ,elapsed-time))
747                   grouplens-rating-alist)
748           (setcdr oldrating (cons (cadr oldrating) elapsed-time)))))
749     (grouplens-start-timer)
750     (setq grouplens-previous-article (bbb-get-current-id))))
751
752 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
753 ;;          BUG REPORTING
754 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
755
756 (defconst gnus-gl-version "gnus-gl.el 2.12")
757 (defconst gnus-gl-maintainer-address "grouplens-bug@cs.umn.edu")
758 (defun gnus-gl-submit-bug-report ()
759   "Submit via mail a bug report on gnus-gl"
760   (interactive)
761   (require 'reporter)
762   (reporter-submit-bug-report gnus-gl-maintainer-address
763                               (concat "gnus-gl.el " gnus-gl-version)
764                               (list 'grouplens-pseudonym
765                                     'grouplens-bbb-host
766                                     'grouplens-bbb-port
767                                     'grouplens-newsgroups
768                                     'grouplens-bbb-token
769                                     'grouplens-bbb-process
770                                     'grouplens-current-group
771                                     'grouplens-previous-article
772                                     'grouplens-mid-list
773                                     'bbb-alist)
774                               nil
775                               'gnus-gl-get-trace))
776
777 (defun gnus-gl-get-trace ()
778   "Insert the contents of the BBBD trace buffer"
779   (if grouplens-bbb-buffer (insert-buffer grouplens-bbb-buffer)))
780
781 ;;;
782 ;;; Additions to make gnus-grouplens-mode  Warning Warning!!
783 ;;;      This version of the gnus-grouplens-mode does
784 ;;;      not work with gnus-5.x.  The "old" way of
785 ;;;      setting up GroupLens still works however.
786 ;;;
787 (defvar gnus-grouplens-mode nil
788   "Minor mode for providing a GroupLens interface in Gnus summary buffers.")
789
790 (defvar gnus-grouplens-mode-map nil)
791
792 (unless gnus-grouplens-mode-map
793   (setq gnus-grouplens-mode-map (make-keymap))
794   (gnus-define-keys
795    gnus-grouplens-mode-map
796    "n" grouplens-next-unread-article
797    "r" bbb-summary-rate-article
798    "k" grouplens-score-thread
799    "c" grouplens-summary-catchup-and-exit
800    "," grouplens-best-unread-article))
801
802 (defun gnus-grouplens-make-menu-bar ()
803   (unless (boundp 'gnus-grouplens-menu)
804     (easy-menu-define
805      gnus-grouplens-menu gnus-grouplens-mode-map ""
806      '("GroupLens"
807        ["Login" bbb-login t]
808        ["Rate" bbb-summary-rate-article t]
809        ["Next article" grouplens-next-unread-article t]
810        ["Best article" grouplens-best-unread-article t]
811        ["Raise thread" grouplens-score-thread t]
812        ["Report bugs" gnus-gl-submit-bug-report t]))))
813
814 (defun gnus-grouplens-mode (&optional arg)
815   "Minor mode for providing a GroupLens interface in Gnus summary buffers."
816   (interactive "P")
817   (when (and (eq major-mode 'gnus-summary-mode)
818              (member gnus-newsgroup-name grouplens-newsgroups))
819     (make-local-variable 'gnus-grouplens-mode)
820     (setq gnus-grouplens-mode 
821           (if (null arg) (not gnus-grouplens-mode)
822             (> (prefix-numeric-value arg) 0)))
823     (when gnus-grouplens-mode
824       (if (not (fboundp 'make-local-hook))
825           (add-hook 'gnus-select-article-hook 'grouplens-do-time)
826         (make-local-hook 'gnus-select-article-hook)
827         (add-hook 'gnus-select-article-hook 'grouplens-do-time nil 'local))
828       (if (not (fboundp 'make-local-hook))
829           (add-hook 'gnus-exit-group-hook 'bbb-put-ratings)
830         (make-local-hook 'gnus-exit-group-hook)
831         (add-hook 'gnus-exit-group-hook 'bbb-put-ratings nil 'local))
832       (make-local-variable 'gnus-score-find-score-files-function)
833       (cond ((eq gnus-grouplens-override-scoring 'combine)
834              ;; either add bbb-buld-mid-scores-alist to a list
835              ;; or make a list
836              (if (listp gnus-score-find-score-files-function)
837                  (setq gnus-score-find-score-files-function 
838                    (append 'bbb-build-mid-scores-alist      
839                            gnus-score-find-score-files-function ))
840                (setq gnus-score-find-score-files-function 
841                      (list gnus-score-find-score-files-function 
842                            'bbb-build-mid-scores-alist))))
843              ;; leave the gnus-score-find-score-files variable alone
844             ((eq gnus-grouplens-override-scoring 'separate)
845              (add-hook 'gnus-select-group-hook 
846                        '(lambda() 
847                           (bbb-build-mid-scores-alist gnus-newsgroup-name))))
848             ;; default is to override
849             (t (setq gnus-score-find-score-files-function 
850                      'bbb-build-mid-scores-alist)))
851       (make-local-variable 'gnus-summary-line-format)
852       (setq gnus-summary-line-format 
853             gnus-summary-grouplens-line-format)
854       (make-local-variable 'gnus-summary-line-format-spec)
855       (setq gnus-summary-line-format-spec nil)
856
857       ;; Set up the menu.
858       (when (and menu-bar-mode
859                  (gnus-visual-p 'grouplens-menu 'menu))
860         (gnus-grouplens-make-menu-bar))
861       (unless (assq 'gnus-grouplens-mode minor-mode-alist)
862         (push '(gnus-grouplens-mode " GroupLens") minor-mode-alist))
863       (unless (assq 'gnus-grouplens-mode minor-mode-map-alist)
864         (push (cons 'gnus-grouplens-mode gnus-grouplens-mode-map)
865               minor-mode-map-alist))
866       (run-hooks 'gnus-grouplens-mode-hook))))
867
868 (provide 'gnus-gl)
869
870 ;;; gnus-gl.el ends here