e12e218e39ef38ff10db6315f05b38f14f1051e3
[gnus] / lisp / nnspool.el
1 ;;; nnspool.el --- spool access for GNU Emacs
2 ;; Copyright (C) 1988,89,90,93,94,95 Free Software Foundation, Inc.
3
4 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'nnheader)
29 (require 'nntp)
30 (require 'timezone)
31
32 (defvar nnspool-inews-program news-inews-program
33   "Program to post news.
34 This is most commonly `inews' or `injnews'.")
35
36 (defvar nnspool-inews-switches '("-h")
37   "Switches for nnspool-request-post to pass to `inews' for posting news.
38 If you are using Cnews, you probably should set this variable to nil.")
39
40 (defvar nnspool-spool-directory (file-name-as-directory news-path)
41   "Local news spool directory.")
42
43 (defvar nnspool-nov-directory (concat nnspool-spool-directory "over.view/")
44   "Local news nov directory.")
45
46 (defvar nnspool-lib-dir "/usr/lib/news/"
47   "Where the local news library files are stored.")
48
49 (defvar nnspool-active-file (concat nnspool-lib-dir "active")
50   "Local news active file.")
51
52 (defvar nnspool-newsgroups-file (concat nnspool-lib-dir "newsgroups")
53   "Local news newsgroups file.")
54
55 (defvar nnspool-distributions-file (concat nnspool-lib-dir "distributions")
56   "Local news distributions file.")
57
58 (defvar nnspool-history-file (concat nnspool-lib-dir "history")
59   "Local news history file.")
60
61 (defvar nnspool-active-times-file (concat nnspool-lib-dir "active.times")
62   "Local news active date file.")
63
64 (defvar nnspool-large-newsgroup 50
65   "The number of the articles which indicates a large newsgroup.
66 If the number of the articles is greater than the value, verbose
67 messages will be shown to indicate the current status.")
68
69 (defvar nnspool-nov-is-evil nil
70   "Non-nil means that nnspool will never return NOV lines instead of headers.")
71
72 (defconst nnspool-sift-nov-with-sed nil
73   "If non-nil, use sed to get the relevant portion from the overview file.
74 If nil, nnspool will load the entire file into a buffer and process it
75 there.")
76
77 (defvar nnspool-rejected-article-hook nil
78   "*A hook that will be run when an article has been rejected by the server.")
79
80 \f
81
82 (defconst nnspool-version "nnspool 2.0"
83   "Version numbers of this version of NNSPOOL.")
84
85 (defvar nnspool-current-directory nil
86   "Current news group directory.")
87
88 (defvar nnspool-current-group nil)
89 (defvar nnspool-status-string "")
90
91 \f
92
93 (defvar nnspool-current-server nil)
94 (defvar nnspool-server-alist nil)
95 (defvar nnspool-server-variables 
96   (list
97    (list 'nnspool-inews-program nnspool-inews-program)
98    (list 'nnspool-inews-switches nnspool-inews-switches)
99    (list 'nnspool-spool-directory nnspool-spool-directory)
100    (list 'nnspool-nov-directory nnspool-nov-directory)
101    (list 'nnspool-lib-dir nnspool-lib-dir)
102    (list 'nnspool-active-file nnspool-active-file)
103    (list 'nnspool-newsgroups-file nnspool-newsgroups-file)
104    (list 'nnspool-distributions-file nnspool-distributions-file)
105    (list 'nnspool-history-file nnspool-history-file)
106    (list 'nnspool-active-times-file nnspool-active-times-file)
107    (list 'nnspool-large-newsgroup nnspool-large-newsgroup)
108    (list 'nnspool-nov-is-evil nnspool-nov-is-evil)
109    (list 'nnspool-sift-nov-with-sed nnspool-sift-nov-with-sed)
110    '(nnspool-current-directory nil)
111    '(nnspool-current-group nil)
112    '(nnspool-status-string "")))
113
114 \f
115 ;;; Interface functions.
116
117 (defun nnspool-retrieve-headers (articles &optional group server fetch-old)
118   "Retrieve the headers of ARTICLES."
119   (save-excursion
120     (set-buffer nntp-server-buffer)
121     (erase-buffer)
122     (when (nnspool-possibly-change-directory group)
123       (let* ((number (length articles))
124              (count 0)
125              (do-message (and (numberp nnspool-large-newsgroup)
126                               (> number nnspool-large-newsgroup)))
127              file beg article ag)
128         (if (and (numberp (car articles))
129                  (nnspool-retrieve-headers-with-nov articles fetch-old))
130             ;; We successfully retrieved the NOV headers.
131             'nov
132           ;; No NOV headers here, so we do it the hard way.
133           (while articles
134             (setq article (pop articles))
135             (if (stringp article)
136                 ;; This is a Message-ID.
137                 (setq ag (nnspool-find-id article)
138                       file (and ag (nnspool-article-pathname 
139                                     (car ag) (cdr ag)))
140                       article (cdr ag))
141               ;; This is an article in the current group.
142               (setq file (nnspool-article-pathname 
143                           nnspool-current-group article)))
144             ;; Insert the head of the article.
145             (when (and file
146                        (file-exists-p file))
147               (insert (format "221 %d Article retrieved.\n" article))
148               (setq beg (point))
149               (nnheader-insert-head file)
150               (goto-char beg)
151               (search-forward "\n\n" nil t)
152               (forward-char -1)
153               (insert ".\n")
154               (delete-region (point) (point-max)))
155             
156             (and do-message
157                  (zerop (% (incf count) 20))
158                  (message "nnspool: Receiving headers... %d%%"
159                           (/ (* count 100) number))))
160           
161           (and do-message
162                (message "nnspool: Receiving headers...done"))
163           
164           ;; Fold continuation lines.
165           (nnheader-fold-continuation-lines)
166           'headers)))))
167
168 (defun nnspool-open-server (server &optional defs)
169   (nnheader-init-server-buffer)
170   (if (equal server nnspool-current-server)
171       t
172     (if nnspool-current-server
173         (setq nnspool-server-alist 
174               (cons (list nnspool-current-server
175                           (nnheader-save-variables nnspool-server-variables))
176                     nnspool-server-alist)))
177     (let ((state (assoc server nnspool-server-alist)))
178       (if state 
179           (progn
180             (nnheader-restore-variables (nth 1 state))
181             (setq nnspool-server-alist (delq state nnspool-server-alist)))
182         (nnheader-set-init-variables nnspool-server-variables defs)))
183     (setq nnspool-current-server server)))
184
185 (defun nnspool-close-server (&optional server)
186   (setq nnspool-current-server nil)
187   t)
188
189 (defun nnspool-server-opened (&optional server)
190   (and (equal server nnspool-current-server)
191        nntp-server-buffer
192        (buffer-name nntp-server-buffer)))
193
194 (defun nnspool-status-message (&optional server)
195   "Return server status response as string."
196   nnspool-status-string)
197
198 (defun nnspool-request-article (id &optional group server buffer)
199   "Select article by message ID (or number)."
200   (nnspool-possibly-change-directory group)
201   (let ((nntp-server-buffer (or buffer nntp-server-buffer))
202         file ag)
203     (if (stringp id)
204         ;; This is a Message-ID.        
205         (when (setq ag (nnspool-find-id id))
206           (setq file (nnspool-article-pathname (car ag) (cdr ag))))
207       (setq file (nnspool-article-pathname nnspool-current-group id)))
208     (and file
209          (file-exists-p file)
210          (not (file-directory-p file))
211          (save-excursion (nnspool-find-file file))
212          ;; We return the article number and group name.
213          (if (numberp id)
214              (cons nnspool-current-group id)
215            ag))))
216             
217 (defun nnspool-request-body (id &optional group server)
218   "Select article body by message ID (or number)."
219   (nnspool-possibly-change-directory group)
220   (if (nnspool-request-article id)
221       (save-excursion
222         (set-buffer nntp-server-buffer)
223         (goto-char (point-min))
224         (if (search-forward "\n\n" nil t)
225             (delete-region (point-min) (point)))
226         t)))
227
228 (defun nnspool-request-head (id &optional group server)
229   "Select article head by message ID (or number)."
230   (nnspool-possibly-change-directory group)
231   (let ((res (nnspool-request-article id)))
232     (when res
233       (save-excursion
234         (set-buffer nntp-server-buffer)
235         (goto-char (point-min))
236         (when (search-forward "\n\n" nil t)
237           (delete-region (1- (point)) (point-max)))))
238     res))
239
240 (defun nnspool-request-group (group &optional server dont-check)
241   "Select news GROUP."
242   (let ((pathname (nnspool-article-pathname group))
243         dir)
244     (if (not (file-directory-p pathname))
245         (progn
246           (setq nnspool-status-string
247                 "Invalid group name (no such directory)")
248           nil)
249       (setq nnspool-current-directory pathname)
250       (setq nnspool-status-string "")
251       (if (not dont-check)
252           (progn
253             (setq dir (directory-files pathname nil "^[0-9]+$" t))
254             ;; yes, completely empty spool directories *are* possible
255             ;; Fix by Sudish Joseph <joseph@cis.ohio-state.edu>
256             (and dir
257                  (setq dir
258                        (sort 
259                         (mapcar
260                          (function
261                           (lambda (name)
262                             (string-to-int name)))
263                          dir)
264                         '<)))
265             (save-excursion
266               (set-buffer nntp-server-buffer)
267               (erase-buffer)
268               (if dir
269                   (insert
270                    (format "211 %d %d %d %s\n" (length dir) (car dir)
271                            (progn (while (cdr dir) (setq dir (cdr dir)))
272                                   (car dir))
273                            group))
274                 (insert (format "211 0 0 0 %s\n" group))))))
275       t)))
276
277 (defun nnspool-close-group (group &optional server)
278   t)
279
280 (defun nnspool-request-list (&optional server)
281   "List active newsgroups."
282   (save-excursion
283     (nnspool-find-file nnspool-active-file)))
284
285 (defun nnspool-request-list-newsgroups (&optional server)
286   "List newsgroups (defined in NNTP2)."
287   (save-excursion
288     (nnspool-find-file nnspool-newsgroups-file)))
289
290 (defun nnspool-request-list-distributions (&optional server)
291   "List distributions (defined in NNTP2)."
292   (save-excursion
293     (nnspool-find-file nnspool-distributions-file)))
294
295 ;; Suggested by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
296 (defun nnspool-request-newgroups (date &optional server)
297   "List groups created after DATE."
298   (if (nnspool-find-file nnspool-active-times-file)
299       (save-excursion
300         ;; Find the last valid line.
301         (goto-char (point-max))
302         (while (and (not (looking-at 
303                           "\\([^ ]+\\) +\\([0-9]+\\)[0-9][0-9][0-9] "))
304                     (zerop (forward-line -1))))
305         (let ((seconds (nnspool-seconds-since-epoch date))
306               groups)
307           ;; Go through lines and add the latest groups to a list.
308           (while (and (looking-at "\\([^ ]+\\) +[0-9]+ ")
309                       (progn
310                         ;; We insert a .0 to make the list reader
311                         ;; interpret the number as a float. It is far
312                         ;; too big to be stored in a lisp integer. 
313                         (goto-char (1- (match-end 0)))
314                         (insert ".0")
315                         (> (progn
316                              (goto-char (match-end 1))
317                              (read (current-buffer)))
318                            seconds))
319                       (setq groups (cons (buffer-substring
320                                           (match-beginning 1) (match-end 1))
321                                          groups))
322                       (zerop (forward-line -1))))
323           (erase-buffer)
324           (while groups
325             (insert (car groups) " 0 0 y\n")
326             (setq groups (cdr groups))))
327         t)
328     nil))
329
330 (defun nnspool-request-post (&optional server)
331   "Post a new news in current buffer."
332   (save-excursion
333     (let* ((process-connection-type nil) ; t bugs out on Solaris
334            (inews-buffer (generate-new-buffer " *nnspool post*"))
335            (proc 
336             (condition-case err
337                 (apply 'start-process "*nnspool inews*" inews-buffer
338                        nnspool-inews-program nnspool-inews-switches)
339               (error
340                (setq nnspool-status-string (format "inews error: %S" err))
341                nil))))
342       (if (not proc)
343           ;; The inews program failed.
344           ()
345         (setq nnspool-status-string "")
346         (set-process-sentinel proc 'nnspool-inews-sentinel)
347         (process-send-region proc (point-min) (point-max))
348         ;; We slap a condition-case around this, because the process may
349         ;; have exited already...
350         (condition-case nil
351             (process-send-eof proc)
352           (error nil))
353         t))))
354
355 (defun nnspool-inews-sentinel (proc status)
356   (save-excursion
357     (set-buffer (process-buffer proc))
358     (goto-char (point-min))
359     (if (or (zerop (buffer-size))
360             (search-forward "spooled" nil t))
361         (kill-buffer (current-buffer))
362       ;; Make status message by folding lines.
363       (while (re-search-forward "[ \t\n]+" nil t)
364         (replace-match " " t t))
365       (setq nnspool-status-string (buffer-string))
366       (message "nnspool: %s" nnspool-status-string)
367       (ding)
368       (run-hooks 'nnspool-rejected-article-hook))))
369
370 \f
371 ;;; Internal functions.
372
373 (defun nnspool-retrieve-headers-with-nov (articles &optional fetch-old)
374   (if (or gnus-nov-is-evil nnspool-nov-is-evil)
375       nil
376     (let ((nov (concat (file-name-as-directory nnspool-nov-directory)
377                        (nnspool-replace-chars-in-string
378                         nnspool-current-group ?. ?/)
379                        "/.overview")))
380       (if (not (file-exists-p nov))
381           ()
382         (save-excursion
383           (set-buffer nntp-server-buffer)
384           (erase-buffer)
385           (if nnspool-sift-nov-with-sed
386               (nnspool-sift-nov-with-sed articles nov)
387             (insert-file-contents nov)
388             (if (and fetch-old
389                      (not (numberp fetch-old)))
390                 t                       ; We want all the headers.
391               ;; First we find the first wanted line.
392               (nnspool-find-nov-line
393                (if fetch-old (max 1 (- (car articles) fetch-old))
394                  (car articles)))
395               (delete-region (point-min) (point))
396               ;; Then we find the last wanted line. 
397               (if (nnspool-find-nov-line 
398                    (progn (while (cdr articles) (setq articles (cdr articles)))
399                           (car articles)))
400                   (forward-line 1))
401               (delete-region (point) (point-max))
402               ;; If the buffer is empty, this wasn't very successful.
403               (not (zerop (buffer-size))))))))))
404
405 (defun nnspool-find-nov-line (article)
406   (let ((max (point-max))
407         (min (goto-char (point-min)))
408         (cur (current-buffer))
409         (prev (point-min))
410         num found)
411     (while (not found)
412       (goto-char (/ (+ max min) 2))
413       (beginning-of-line)
414       (if (or (= (point) prev)
415               (eobp))
416           (setq found t)
417         (setq prev (point))
418         (cond ((> (setq num (read cur)) article)
419                (setq max (point)))
420               ((< num article)
421                (setq min (point)))
422               (t
423                (setq found t)))))
424     (when (not (eq num article))
425       (setq found (point))
426       (forward-line 1)
427       (or (eobp)
428           (= (setq num (read cur)) article)
429           (goto-char found)))
430     (beginning-of-line)
431     (eq num article)))
432     
433
434 (defun nnspool-sift-nov-with-sed (articles file)
435   (let ((first (car articles))
436         (last (progn (while (cdr articles) (setq articles (cdr articles)))
437                      (car articles))))
438     (call-process "awk" nil t nil 
439                   (format "BEGIN {firstmsg=%d; lastmsg=%d;}\n $1 >= firstmsg && $1 <= lastmsg {print;}"
440                           (1- first) (1+ last))
441                   file)))
442
443 ;; Fixed by fdc@cliwe.ping.de (Frank D. Cringle). 
444 ;; Find out what group an article identified by a Message-ID is in.
445 (defun nnspool-find-id (id)
446   (save-excursion
447     (set-buffer (get-buffer-create " *nnspool work*"))
448     (buffer-disable-undo (current-buffer))
449     (erase-buffer)
450     (call-process "grep" nil t nil id nnspool-history-file)
451     (goto-char (point-min))
452     (prog1
453         (if (looking-at "<[^>]+>[ \t]+[-0-9~]+[ \t]+\\([^ /\t\n]+\\)/\\([0-9]+\\)[ \t\n]")
454             (cons (match-string 1) (string-to-int (match-string 2))))
455       (kill-buffer (current-buffer)))))
456
457 (defun nnspool-find-file (file)
458   "Insert FILE in server buffer safely."
459   (set-buffer nntp-server-buffer)
460   (erase-buffer)
461   (condition-case ()
462       (progn (insert-file-contents file) t)
463     (file-error nil)))
464
465 (defun nnspool-possibly-change-directory (group)
466   (if group
467       (let ((pathname (nnspool-article-pathname group)))
468         (if (file-directory-p pathname)
469             (progn
470               (setq nnspool-current-directory pathname)
471               (setq nnspool-current-group group))
472           (setq nnspool-status-string 
473                 (format "No such newsgroup: %s" group))
474           nil))
475     t))
476
477 (defun nnspool-article-pathname (group &optional article)
478   "Find the path for GROUP."
479   (concat 
480    (file-name-as-directory nnspool-spool-directory) 
481    (nnspool-replace-chars-in-string group ?. ?/)
482    "/"
483    (if article (int-to-string article) "")))
484
485 (defun nnspool-replace-chars-in-string (string from to)
486   "Replace characters in STRING from FROM to TO."
487   (let ((string (substring string 0))   ;Copy string.
488         (len (length string))
489         (idx 0))
490     ;; Replace all occurrences of FROM with TO.
491     (while (< idx len)
492       (if (= (aref string idx) from)
493           (aset string idx to))
494       (setq idx (1+ idx)))
495     string))
496
497 (defun nnspool-number-base-10 (num pos)
498   (if (<= pos 0) ""
499     (setcdr num (+ (* (% (car num) 10) 65536) (cdr num)))
500     (apply
501      'concat
502      (reverse
503       (list
504        (char-to-string
505         (aref "0123456789" (% (cdr num) 10)))
506        (progn
507          (setcdr num (/ (cdr num) 10))
508          (setcar num (/ (car num) 10))
509          (nnspool-number-base-10 num (1- pos))))))))
510
511 (defun nnspool-seconds-since-epoch (date)
512   (let* ((tdate (mapcar (lambda (ti) (and ti (string-to-int ti)))
513                         (timezone-parse-date date)))
514          (ttime (mapcar (lambda (ti) (and ti (string-to-int ti)))
515                         (timezone-parse-time
516                          (aref (timezone-parse-date date) 3))))
517          (unix (encode-time (nth 2 ttime) (nth 1 ttime) (nth 0 ttime)
518                             (nth 2 tdate) (nth 1 tdate) (nth 0 tdate) 
519                             (nth 4 tdate))))
520     (+ (* (car unix) 65536.0)
521        (car (cdr unix)))))
522
523 (provide 'nnspool)
524
525 ;;; nnspool.el ends here