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