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