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