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