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