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