Importing pgnus-0.18.
[elisp/gnus.git-] / lisp / gnus-soup.el
1 ;;; gnus-soup.el --- SOUP packet writing support for Gnus
2 ;; Copyright (C) 1995,96,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Per Abrahamsen <abraham@iesd.auc.dk>
5 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail
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 the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (require 'gnus)
32 (require 'gnus-art)
33 (require 'message)
34 (require 'gnus-start)
35 (require 'gnus-range)
36
37 ;;; User Variables:
38
39 (defvar gnus-soup-directory (nnheader-concat gnus-home-directory "SoupBrew/")
40   "*Directory containing an unpacked SOUP packet.")
41
42 (defvar gnus-soup-replies-directory
43   (nnheader-concat gnus-soup-directory "SoupReplies/")
44   "*Directory where Gnus will do processing of replies.")
45
46 (defvar gnus-soup-prefix-file "gnus-prefix"
47   "*Name of the file where Gnus stores the last used prefix.")
48
49 (defvar gnus-soup-packer "tar cf - %s | gzip > $HOME/Soupout%d.tgz"
50   "Format string command for packing a SOUP packet.
51 The SOUP files will be inserted where the %s is in the string.
52 This string MUST contain both %s and %d.  The file number will be
53 inserted where %d appears.")
54
55 (defvar gnus-soup-unpacker "gunzip -c %s | tar xvf -"
56   "*Format string command for unpacking a SOUP packet.
57 The SOUP packet file name will be inserted at the %s.")
58
59 (defvar gnus-soup-packet-directory gnus-home-directory
60   "*Where gnus-soup will look for REPLIES packets.")
61
62 (defvar gnus-soup-packet-regexp "Soupin"
63   "*Regular expression matching SOUP REPLIES packets in `gnus-soup-packet-directory'.")
64
65 (defvar gnus-soup-ignored-headers "^Xref:"
66   "*Regexp to match headers to be removed when brewing SOUP packets.")
67
68 ;;; Internal Variables:
69
70 (defvar gnus-soup-encoding-type ?n
71   "*Soup encoding type.
72 `n' is news format, `m' is Unix mbox format, and `M' is MMDF mailbox
73 format.")
74
75 (defvar gnus-soup-index-type ?c
76   "*Soup index type.
77 `n' means no index file and `c' means standard Cnews overview
78 format.")
79
80 (defvar gnus-soup-areas nil)
81 (defvar gnus-soup-last-prefix nil)
82 (defvar gnus-soup-prev-prefix nil)
83 (defvar gnus-soup-buffers nil)
84
85 ;;; Access macros:
86
87 (defmacro gnus-soup-area-prefix (area)
88   `(aref ,area 0))
89 (defmacro gnus-soup-set-area-prefix (area prefix)
90   `(aset ,area 0 ,prefix))
91 (defmacro gnus-soup-area-name (area)
92   `(aref ,area 1))
93 (defmacro gnus-soup-area-encoding (area)
94   `(aref ,area 2))
95 (defmacro gnus-soup-area-description (area)
96   `(aref ,area 3))
97 (defmacro gnus-soup-area-number (area)
98   `(aref ,area 4))
99 (defmacro gnus-soup-area-set-number (area value)
100   `(aset ,area 4 ,value))
101
102 (defmacro gnus-soup-encoding-format (encoding)
103   `(aref ,encoding 0))
104 (defmacro gnus-soup-encoding-index (encoding)
105   `(aref ,encoding 1))
106 (defmacro gnus-soup-encoding-kind (encoding)
107   `(aref ,encoding 2))
108
109 (defmacro gnus-soup-reply-prefix (reply)
110   `(aref ,reply 0))
111 (defmacro gnus-soup-reply-kind (reply)
112   `(aref ,reply 1))
113 (defmacro gnus-soup-reply-encoding (reply)
114   `(aref ,reply 2))
115
116 ;;; Commands:
117
118 (defun gnus-soup-send-replies ()
119   "Unpack and send all replies in the reply packet."
120   (interactive)
121   (let ((packets (directory-files
122                   gnus-soup-packet-directory t gnus-soup-packet-regexp)))
123     (while packets
124       (when (gnus-soup-send-packet (car packets))
125         (delete-file (car packets)))
126       (setq packets (cdr packets)))))
127
128 (defun gnus-soup-add-article (n)
129   "Add the current article to SOUP packet.
130 If N is a positive number, add the N next articles.
131 If N is a negative number, add the N previous articles.
132 If N is nil and any articles have been marked with the process mark,
133 move those articles instead."
134   (interactive "P")
135   (let* ((articles (gnus-summary-work-articles n))
136          (tmp-buf (gnus-get-buffer-create "*soup work*"))
137          (area (gnus-soup-area gnus-newsgroup-name))
138          (prefix (gnus-soup-area-prefix area))
139          headers)
140     (buffer-disable-undo tmp-buf)
141     (save-excursion
142       (while articles
143         ;; Find the header of the article.
144         (set-buffer gnus-summary-buffer)
145         (when (setq headers (gnus-summary-article-header (car articles)))
146           ;; Put the article in a buffer.
147           (set-buffer tmp-buf)
148           (when (gnus-request-article-this-buffer
149                  (car articles) gnus-newsgroup-name)
150             (save-restriction
151               (message-narrow-to-head)
152               (message-remove-header gnus-soup-ignored-headers t))
153             (gnus-soup-store gnus-soup-directory prefix headers
154                              gnus-soup-encoding-type
155                              gnus-soup-index-type)
156             (gnus-soup-area-set-number
157              area (1+ (or (gnus-soup-area-number area) 0)))))
158         ;; Mark article as read.
159         (set-buffer gnus-summary-buffer)
160         (gnus-summary-remove-process-mark (car articles))
161         (gnus-summary-mark-as-read (car articles) gnus-souped-mark)
162         (setq articles (cdr articles)))
163       (kill-buffer tmp-buf))
164     (gnus-soup-save-areas)
165     (gnus-set-mode-line 'summary)))
166
167 (defun gnus-soup-pack-packet ()
168   "Make a SOUP packet from the SOUP areas."
169   (interactive)
170   (gnus-soup-read-areas)
171   (unless (file-exists-p gnus-soup-directory)
172     (message "No such directory: %s" gnus-soup-directory))
173   (when (null (directory-files gnus-soup-directory nil "\\.MSG$"))
174     (message "No files to pack."))
175   (gnus-soup-pack gnus-soup-directory gnus-soup-packer))
176
177 (defun gnus-group-brew-soup (n)
178   "Make a soup packet from the current group.
179 Uses the process/prefix convention."
180   (interactive "P")
181   (let ((groups (gnus-group-process-prefix n)))
182     (while groups
183       (gnus-group-remove-mark (car groups))
184       (gnus-soup-group-brew (car groups) t)
185       (setq groups (cdr groups)))
186     (gnus-soup-save-areas)))
187
188 (defun gnus-brew-soup (&optional level)
189   "Go through all groups on LEVEL or less and make a soup packet."
190   (interactive "P")
191   (let ((level (or level gnus-level-subscribed))
192         (newsrc (cdr gnus-newsrc-alist)))
193     (while newsrc
194       (when (<= (nth 1 (car newsrc)) level)
195         (gnus-soup-group-brew (caar newsrc) t))
196       (setq newsrc (cdr newsrc)))
197     (gnus-soup-save-areas)))
198
199 ;;;###autoload
200 (defun gnus-batch-brew-soup ()
201   "Brew a SOUP packet from groups mention on the command line.
202 Will use the remaining command line arguments as regular expressions
203 for matching on group names.
204
205 For instance, if you want to brew on all the nnml groups, as well as
206 groups with \"emacs\" in the name, you could say something like:
207
208 $ emacs -batch -f gnus-batch-brew-soup ^nnml \".*emacs.*\"
209
210 Note -- this function hasn't been implemented yet."
211   (interactive)
212   nil)
213
214 ;;; Internal Functions:
215
216 ;; Store the current buffer.
217 (defun gnus-soup-store (directory prefix headers format index)
218   ;; Create the directory, if needed.
219   (gnus-make-directory directory)
220   (let* ((msg-buf (nnheader-find-file-noselect
221                    (concat directory prefix ".MSG")))
222          (idx-buf (if (= index ?n)
223                       nil
224                     (nnheader-find-file-noselect
225                      (concat directory prefix ".IDX"))))
226          (article-buf (current-buffer))
227          from head-line beg type)
228     (setq gnus-soup-buffers (cons msg-buf (delq msg-buf gnus-soup-buffers)))
229     (buffer-disable-undo msg-buf)
230     (when idx-buf
231       (push idx-buf gnus-soup-buffers)
232       (buffer-disable-undo idx-buf))
233     (save-excursion
234       ;; Make sure the last char in the buffer is a newline.
235       (goto-char (point-max))
236       (unless (= (current-column) 0)
237         (insert "\n"))
238       ;; Find the "from".
239       (goto-char (point-min))
240       (setq from
241             (gnus-mail-strip-quoted-names
242              (or (mail-fetch-field "from")
243                  (mail-fetch-field "really-from")
244                  (mail-fetch-field "sender"))))
245       (goto-char (point-min))
246       ;; Depending on what encoding is supposed to be used, we make
247       ;; a soup header.
248       (setq head-line
249             (cond
250              ((= gnus-soup-encoding-type ?n)
251               (format "#! rnews %d\n" (buffer-size)))
252              ((= gnus-soup-encoding-type ?m)
253               (while (search-forward "\nFrom " nil t)
254                 (replace-match "\n>From " t t))
255               (concat "From " (or from "unknown")
256                       " " (current-time-string) "\n"))
257              ((= gnus-soup-encoding-type ?M)
258               "\^a\^a\^a\^a\n")
259              (t (error "Unsupported type: %c" gnus-soup-encoding-type))))
260       ;; Insert the soup header and the article in the MSG buf.
261       (set-buffer msg-buf)
262       (goto-char (point-max))
263       (insert head-line)
264       (setq beg (point))
265       (insert-buffer-substring article-buf)
266       ;; Insert the index in the IDX buf.
267       (cond ((= index ?c)
268              (set-buffer idx-buf)
269              (gnus-soup-insert-idx beg headers))
270             ((/= index ?n)
271              (error "Unknown index type: %c" type)))
272       ;; Return the MSG buf.
273       msg-buf)))
274
275 (defun gnus-soup-group-brew (group &optional not-all)
276   "Enter GROUP and add all articles to a SOUP package.
277 If NOT-ALL, don't pack ticked articles."
278   (let ((gnus-expert-user t)
279         (gnus-large-newsgroup nil)
280         (entry (gnus-gethash group gnus-newsrc-hashtb)))
281     (when (or (null entry)
282               (eq (car entry) t)
283               (and (car entry)
284                    (> (car entry) 0))
285               (and (not not-all)
286                    (gnus-range-length (cdr (assq 'tick (gnus-info-marks
287                                                         (nth 2 entry)))))))
288       (when (gnus-summary-read-group group nil t)
289         (setq gnus-newsgroup-processable
290               (reverse
291                (if (not not-all)
292                    (append gnus-newsgroup-marked gnus-newsgroup-unreads)
293                  gnus-newsgroup-unreads)))
294         (gnus-soup-add-article nil)
295         (gnus-summary-exit)))))
296
297 (defun gnus-soup-insert-idx (offset header)
298   ;; [number subject from date id references chars lines xref]
299   (goto-char (point-max))
300   (insert
301    (format "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t\t\n"
302            offset
303            (or (mail-header-subject header) "(none)")
304            (or (mail-header-from header) "(nobody)")
305            (or (mail-header-date header) "")
306            (or (mail-header-id header)
307                (concat "soup-dummy-id-"
308                        (mapconcat
309                         (lambda (time) (int-to-string time))
310                         (current-time) "-")))
311            (or (mail-header-references header) "")
312            (or (mail-header-chars header) 0)
313            (or (mail-header-lines header) "0"))))
314
315 (defun gnus-soup-save-areas ()
316   "Write all SOUP buffers."
317   (interactive)
318   (gnus-soup-write-areas)
319   (save-excursion
320     (let (buf)
321       (while gnus-soup-buffers
322         (setq buf (car gnus-soup-buffers)
323               gnus-soup-buffers (cdr gnus-soup-buffers))
324         (if (not (buffer-name buf))
325             ()
326           (set-buffer buf)
327           (when (buffer-modified-p)
328             (save-buffer))
329           (kill-buffer (current-buffer)))))
330     (gnus-soup-write-prefixes)))
331
332 (defun gnus-soup-write-prefixes ()
333   (let ((prefixes gnus-soup-last-prefix)
334         prefix)
335     (save-excursion
336       (gnus-set-work-buffer)
337       (while (setq prefix (pop prefixes))
338         (erase-buffer)
339         (insert (format "(setq gnus-soup-prev-prefix %d)\n" (cdr prefix)))
340         (gnus-write-buffer (concat (car prefix) gnus-soup-prefix-file))))))
341
342 (defun gnus-soup-pack (dir packer)
343   (let* ((files (mapconcat 'identity
344                            '("AREAS" "*.MSG" "*.IDX" "INFO"
345                              "LIST" "REPLIES" "COMMANDS" "ERRORS")
346                            " "))
347          (packer (if (< (string-match "%s" packer)
348                         (string-match "%d" packer))
349                      (format packer files
350                              (string-to-int (gnus-soup-unique-prefix dir)))
351                    (format packer
352                            (string-to-int (gnus-soup-unique-prefix dir))
353                            files)))
354          (dir (expand-file-name dir)))
355     (gnus-make-directory dir)
356     (setq gnus-soup-areas nil)
357     (gnus-message 4 "Packing %s..." packer)
358     (if (zerop (call-process shell-file-name
359                              nil nil nil shell-command-switch
360                              (concat "cd " dir " ; " packer)))
361         (progn
362           (call-process shell-file-name nil nil nil shell-command-switch
363                         (concat "cd " dir " ; rm " files))
364           (gnus-message 4 "Packing...done" packer))
365       (error "Couldn't pack packet"))))
366
367 (defun gnus-soup-parse-areas (file)
368   "Parse soup area file FILE.
369 The result is a of vectors, each containing one entry from the AREA file.
370 The vector contain five strings,
371   [prefix name encoding description number]
372 though the two last may be nil if they are missing."
373   (let (areas)
374     (when (file-exists-p file)
375       (save-excursion
376         (set-buffer (nnheader-find-file-noselect file 'force))
377         (buffer-disable-undo (current-buffer))
378         (goto-char (point-min))
379         (while (not (eobp))
380           (push (vector (gnus-soup-field)
381                         (gnus-soup-field)
382                         (gnus-soup-field)
383                         (and (eq (preceding-char) ?\t)
384                              (gnus-soup-field))
385                         (and (eq (preceding-char) ?\t)
386                              (string-to-int (gnus-soup-field))))
387                 areas)
388           (when (eq (preceding-char) ?\t)
389             (beginning-of-line 2)))
390         (kill-buffer (current-buffer))))
391     areas))
392
393 (defun gnus-soup-parse-replies (file)
394   "Parse soup REPLIES file FILE.
395 The result is a of vectors, each containing one entry from the REPLIES
396 file.  The vector contain three strings, [prefix name encoding]."
397   (let (replies)
398     (save-excursion
399       (set-buffer (nnheader-find-file-noselect file))
400       (buffer-disable-undo (current-buffer))
401       (goto-char (point-min))
402       (while (not (eobp))
403         (push (vector (gnus-soup-field) (gnus-soup-field)
404                       (gnus-soup-field))
405               replies)
406         (when (eq (preceding-char) ?\t)
407           (beginning-of-line 2)))
408       (kill-buffer (current-buffer)))
409     replies))
410
411 (defun gnus-soup-field ()
412   (prog1
413       (buffer-substring (point) (progn (skip-chars-forward "^\t\n") (point)))
414     (forward-char 1)))
415
416 (defun gnus-soup-read-areas ()
417   (or gnus-soup-areas
418       (setq gnus-soup-areas
419             (gnus-soup-parse-areas (concat gnus-soup-directory "AREAS")))))
420
421 (defun gnus-soup-write-areas ()
422   "Write the AREAS file."
423   (interactive)
424   (when gnus-soup-areas
425     (with-temp-file (concat gnus-soup-directory "AREAS")
426       (let ((areas gnus-soup-areas)
427             area)
428         (while (setq area (pop areas))
429           (insert
430            (format
431             "%s\t%s\t%s%s\n"
432             (gnus-soup-area-prefix area)
433             (gnus-soup-area-name area)
434             (gnus-soup-area-encoding area)
435             (if (or (gnus-soup-area-description area)
436                     (gnus-soup-area-number area))
437                 (concat "\t" (or (gnus-soup-area-description
438                                   area) "")
439                         (if (gnus-soup-area-number area)
440                             (concat "\t" (int-to-string
441                                           (gnus-soup-area-number area)))
442                           "")) ""))))))))
443
444 (defun gnus-soup-write-replies (dir areas)
445   "Write a REPLIES file in DIR containing AREAS."
446   (with-temp-file (concat dir "REPLIES")
447     (let (area)
448       (while (setq area (pop areas))
449         (insert (format "%s\t%s\t%s\n"
450                         (gnus-soup-reply-prefix area)
451                         (gnus-soup-reply-kind area)
452                         (gnus-soup-reply-encoding area)))))))
453
454 (defun gnus-soup-area (group)
455   (gnus-soup-read-areas)
456   (let ((areas gnus-soup-areas)
457         (real-group (gnus-group-real-name group))
458         area result)
459     (while areas
460       (setq area (car areas)
461             areas (cdr areas))
462       (when (equal (gnus-soup-area-name area) real-group)
463         (setq result area)))
464     (unless result
465       (setq result
466             (vector (gnus-soup-unique-prefix)
467                     real-group
468                     (format "%c%c%c"
469                             gnus-soup-encoding-type
470                             gnus-soup-index-type
471                             (if (gnus-member-of-valid 'mail group) ?m ?n))
472                     nil nil)
473             gnus-soup-areas (cons result gnus-soup-areas)))
474     result))
475
476 (defun gnus-soup-unique-prefix (&optional dir)
477   (let* ((dir (file-name-as-directory (or dir gnus-soup-directory)))
478          (entry (assoc dir gnus-soup-last-prefix))
479          gnus-soup-prev-prefix)
480     (if entry
481         ()
482       (when (file-exists-p (concat dir gnus-soup-prefix-file))
483         (ignore-errors
484           (load (concat dir gnus-soup-prefix-file) nil t t)))
485       (push (setq entry (cons dir (or gnus-soup-prev-prefix 0)))
486             gnus-soup-last-prefix))
487     (setcdr entry (1+ (cdr entry)))
488     (gnus-soup-write-prefixes)
489     (int-to-string (cdr entry))))
490
491 (defun gnus-soup-unpack-packet (dir unpacker packet)
492   "Unpack PACKET into DIR using UNPACKER.
493 Return whether the unpacking was successful."
494   (gnus-make-directory dir)
495   (gnus-message 4 "Unpacking: %s" (format unpacker packet))
496   (prog1
497       (zerop (call-process
498               shell-file-name nil nil nil shell-command-switch
499               (format "cd %s ; %s" (expand-file-name dir)
500                       (format unpacker packet))))
501     (gnus-message 4 "Unpacking...done")))
502
503 (defun gnus-soup-send-packet (packet)
504   (gnus-soup-unpack-packet
505    gnus-soup-replies-directory gnus-soup-unpacker packet)
506   (let ((replies (gnus-soup-parse-replies
507                   (concat gnus-soup-replies-directory "REPLIES"))))
508     (save-excursion
509       (while replies
510         (let* ((msg-file (concat gnus-soup-replies-directory
511                                  (gnus-soup-reply-prefix (car replies))
512                                  ".MSG"))
513                (msg-buf (and (file-exists-p msg-file)
514                              (nnheader-find-file-noselect msg-file)))
515                (tmp-buf (gnus-get-buffer-create " *soup send*"))
516                beg end)
517           (cond
518            ((/= (gnus-soup-encoding-format
519                  (gnus-soup-reply-encoding (car replies)))
520                 ?n)
521             (error "Unsupported encoding"))
522            ((null msg-buf)
523             t)
524            (t
525             (buffer-disable-undo msg-buf)
526             (set-buffer msg-buf)
527             (goto-char (point-min))
528             (while (not (eobp))
529               (unless (looking-at "#! *rnews +\\([0-9]+\\)")
530                 (error "Bad header"))
531               (forward-line 1)
532               (setq beg (point)
533                     end (+ (point) (string-to-int
534                                     (buffer-substring
535                                      (match-beginning 1) (match-end 1)))))
536               (switch-to-buffer tmp-buf)
537               (erase-buffer)
538               (insert-buffer-substring msg-buf beg end)
539               (goto-char (point-min))
540               (search-forward "\n\n")
541               (forward-char -1)
542               (insert mail-header-separator)
543               (setq message-newsreader (setq message-mailer
544                                              (gnus-extended-version)))
545               (cond
546                ((string= (gnus-soup-reply-kind (car replies)) "news")
547                 (gnus-message 5 "Sending news message to %s..."
548                               (mail-fetch-field "newsgroups"))
549                 (sit-for 1)
550                 (let ((message-syntax-checks
551                        'dont-check-for-anything-just-trust-me))
552                   (funcall message-send-news-function)))
553                ((string= (gnus-soup-reply-kind (car replies)) "mail")
554                 (gnus-message 5 "Sending mail to %s..."
555                               (mail-fetch-field "to"))
556                 (sit-for 1)
557                 (message-send-mail))
558                (t
559                 (error "Unknown reply kind")))
560               (set-buffer msg-buf)
561               (goto-char end))
562             (delete-file (buffer-file-name))
563             (kill-buffer msg-buf)
564             (kill-buffer tmp-buf)
565             (gnus-message 4 "Sent packet"))))
566         (setq replies (cdr replies)))
567       t)))
568
569 (provide 'gnus-soup)
570
571 ;;; gnus-soup.el ends here