Synch with Gnus.
[elisp/gnus.git-] / lisp / gnus-soup.el
1 ;;; gnus-soup.el --- SOUP packet writing support for Gnus
2 ;; Copyright (C) 1995,96,97,98,99 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 ?u
71   "*Soup encoding type.
72 `u' is USENET 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         ;; Put the article in a buffer.
144         (set-buffer tmp-buf)
145         (when (gnus-request-article-this-buffer
146                (car articles) gnus-newsgroup-name)
147           (setq headers (nnheader-parse-head t))
148           (save-restriction
149             (message-narrow-to-head)
150             (message-remove-header gnus-soup-ignored-headers t))
151           (gnus-soup-store gnus-soup-directory prefix headers
152                            gnus-soup-encoding-type
153                            gnus-soup-index-type)
154           (gnus-soup-area-set-number
155            area (1+ (or (gnus-soup-area-number area) 0))))
156         ;; Mark article as read.
157         (set-buffer gnus-summary-buffer)
158         (gnus-summary-remove-process-mark (car articles))
159         (gnus-summary-mark-as-read (car articles) gnus-souped-mark)
160         (setq articles (cdr articles)))
161       (kill-buffer tmp-buf))
162     (gnus-soup-save-areas)
163     (gnus-set-mode-line 'summary)))
164
165 (defun gnus-soup-pack-packet ()
166   "Make a SOUP packet from the SOUP areas."
167   (interactive)
168   (gnus-soup-read-areas)
169   (if (file-exists-p gnus-soup-directory)
170       (if (directory-files gnus-soup-directory nil "\\.MSG$")
171           (gnus-soup-pack gnus-soup-directory gnus-soup-packer)
172         (message "No files to pack."))
173     (message "No such directory: %s" gnus-soup-directory)))
174
175 (defun gnus-group-brew-soup (n)
176   "Make a soup packet from the current group.
177 Uses the process/prefix convention."
178   (interactive "P")
179   (let ((groups (gnus-group-process-prefix n)))
180     (while groups
181       (gnus-group-remove-mark (car groups))
182       (gnus-soup-group-brew (car groups) t)
183       (setq groups (cdr groups)))
184     (gnus-soup-save-areas)))
185
186 (defun gnus-brew-soup (&optional level)
187   "Go through all groups on LEVEL or less and make a soup packet."
188   (interactive "P")
189   (let ((level (or level gnus-level-subscribed))
190         (newsrc (cdr gnus-newsrc-alist)))
191     (while newsrc
192       (when (<= (nth 1 (car newsrc)) level)
193         (gnus-soup-group-brew (caar newsrc) t))
194       (setq newsrc (cdr newsrc)))
195     (gnus-soup-save-areas)))
196
197 ;;;###autoload
198 (defun gnus-batch-brew-soup ()
199   "Brew a SOUP packet from groups mention on the command line.
200 Will use the remaining command line arguments as regular expressions
201 for matching on group names.
202
203 For instance, if you want to brew on all the nnml groups, as well as
204 groups with \"emacs\" in the name, you could say something like:
205
206 $ emacs -batch -f gnus-batch-brew-soup ^nnml \".*emacs.*\"
207
208 Note -- this function hasn't been implemented yet."
209   (interactive)
210   nil)
211
212 ;;; Internal Functions:
213
214 ;; Store the current buffer.
215 (defun gnus-soup-store (directory prefix headers format index)
216   ;; Create the directory, if needed.
217   (gnus-make-directory directory)
218   (let* ((msg-buf (nnheader-find-file-noselect
219                    (concat directory prefix ".MSG")))
220          (idx-buf (if (= index ?n)
221                       nil
222                     (nnheader-find-file-noselect
223                      (concat directory prefix ".IDX"))))
224          (article-buf (current-buffer))
225          from head-line beg type)
226     (setq gnus-soup-buffers (cons msg-buf (delq msg-buf gnus-soup-buffers)))
227     (buffer-disable-undo msg-buf)
228     (when idx-buf
229       (push idx-buf gnus-soup-buffers)
230       (buffer-disable-undo idx-buf))
231     (save-excursion
232       ;; Make sure the last char in the buffer is a newline.
233       (goto-char (point-max))
234       (unless (= (current-column) 0)
235         (insert "\n"))
236       ;; Find the "from".
237       (goto-char (point-min))
238       (setq from
239             (gnus-mail-strip-quoted-names
240              (or (mail-fetch-field "from")
241                  (mail-fetch-field "really-from")
242                  (mail-fetch-field "sender"))))
243       (goto-char (point-min))
244       ;; Depending on what encoding is supposed to be used, we make
245       ;; a soup header.
246       (setq head-line
247             (cond
248              ((or (= gnus-soup-encoding-type ?u)
249                   (= gnus-soup-encoding-type ?n)) ;;Gnus back compatibility.
250               (format "#! rnews %d\n" (buffer-size)))
251              ((= gnus-soup-encoding-type ?m)
252               (while (search-forward "\nFrom " nil t)
253                 (replace-match "\n>From " t t))
254               (concat "From " (or from "unknown")
255                       " " (current-time-string) "\n"))
256              ((= gnus-soup-encoding-type ?M)
257               "\^a\^a\^a\^a\n")
258              (t (error "Unsupported type: %c" gnus-soup-encoding-type))))
259       ;; Insert the soup header and the article in the MSG buf.
260       (set-buffer msg-buf)
261       (goto-char (point-max))
262       (insert head-line)
263       (setq beg (point))
264       (insert-buffer-substring article-buf)
265       ;; Insert the index in the IDX buf.
266       (cond ((= index ?c)
267              (set-buffer idx-buf)
268              (gnus-soup-insert-idx beg headers))
269             ((/= index ?n)
270              (error "Unknown index type: %c" type)))
271       ;; Return the MSG buf.
272       msg-buf)))
273
274 (defun gnus-soup-group-brew (group &optional not-all)
275   "Enter GROUP and add all articles to a SOUP package.
276 If NOT-ALL, don't pack ticked articles."
277   (let ((gnus-expert-user t)
278         (gnus-large-newsgroup nil)
279         (entry (gnus-gethash group gnus-newsrc-hashtb)))
280     (when (or (null entry)
281               (eq (car entry) t)
282               (and (car entry)
283                    (> (car entry) 0))
284               (and (not not-all)
285                    (gnus-range-length (cdr (assq 'tick (gnus-info-marks
286                                                         (nth 2 entry)))))))
287       (when (gnus-summary-read-group group nil t)
288         (setq gnus-newsgroup-processable
289               (reverse
290                (if (not not-all)
291                    (append gnus-newsgroup-marked gnus-newsgroup-unreads)
292                  gnus-newsgroup-unreads)))
293         (gnus-soup-add-article nil)
294         (gnus-summary-exit)))))
295
296 (defun gnus-soup-insert-idx (offset header)
297   ;; [number subject from date id references chars lines xref]
298   (goto-char (point-max))
299   (insert
300    (format "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t\t\n"
301            offset
302            (or (mail-header-subject header) "(none)")
303            (or (mail-header-from header) "(nobody)")
304            (or (mail-header-date header) "")
305            (or (mail-header-id header)
306                (concat "soup-dummy-id-"
307                        (mapconcat
308                         (lambda (time) (int-to-string time))
309                         (current-time) "-")))
310            (or (mail-header-references header) "")
311            (or (mail-header-chars header) 0)
312            (or (mail-header-lines header) "0"))))
313
314 (defun gnus-soup-save-areas ()
315   "Write all SOUP buffers."
316   (interactive)
317   (gnus-soup-write-areas)
318   (save-excursion
319     (let (buf)
320       (while gnus-soup-buffers
321         (setq buf (car gnus-soup-buffers)
322               gnus-soup-buffers (cdr gnus-soup-buffers))
323         (if (not (buffer-name buf))
324             ()
325           (set-buffer buf)
326           (when (buffer-modified-p)
327             (save-buffer))
328           (kill-buffer (current-buffer)))))
329     (gnus-soup-write-prefixes)))
330
331 (defun gnus-soup-write-prefixes ()
332   (let ((prefixes gnus-soup-last-prefix)
333         prefix)
334     (save-excursion
335       (gnus-set-work-buffer)
336       (while (setq prefix (pop prefixes))
337         (erase-buffer)
338         (insert (format "(setq gnus-soup-prev-prefix %d)\n" (cdr prefix)))
339         (gnus-write-buffer-as-coding-system
340          nnheader-text-coding-system
341          (concat (car prefix) gnus-soup-prefix-file))))))
342
343 (defun gnus-soup-pack (dir packer)
344   (let* ((files (mapconcat 'identity
345                            '("AREAS" "*.MSG" "*.IDX" "INFO"
346                              "LIST" "REPLIES" "COMMANDS" "ERRORS")
347                            " "))
348          (packer (if (< (string-match "%s" packer)
349                         (string-match "%d" packer))
350                      (format packer files
351                              (string-to-int (gnus-soup-unique-prefix dir)))
352                    (format packer
353                            (string-to-int (gnus-soup-unique-prefix dir))
354                            files)))
355          (dir (expand-file-name dir)))
356     (gnus-make-directory dir)
357     (setq gnus-soup-areas nil)
358     (gnus-message 4 "Packing %s..." packer)
359     (if (zerop (call-process shell-file-name
360                              nil nil nil shell-command-switch
361                              (concat "cd " dir " ; " packer)))
362         (progn
363           (call-process shell-file-name nil nil nil shell-command-switch
364                         (concat "cd " dir " ; rm " files))
365           (gnus-message 4 "Packing...done" packer))
366       (error "Couldn't pack packet"))))
367
368 (defun gnus-soup-parse-areas (file)
369   "Parse soup area file FILE.
370 The result is a of vectors, each containing one entry from the AREA file.
371 The vector contain five strings,
372   [prefix name encoding description number]
373 though the two last may be nil if they are missing."
374   (let (areas)
375     (when (file-exists-p file)
376       (save-excursion
377         (set-buffer (nnheader-find-file-noselect file 'force))
378         (buffer-disable-undo)
379         (goto-char (point-min))
380         (while (not (eobp))
381           (push (vector (gnus-soup-field)
382                         (gnus-soup-field)
383                         (gnus-soup-field)
384                         (and (eq (preceding-char) ?\t)
385                              (gnus-soup-field))
386                         (and (eq (preceding-char) ?\t)
387                              (string-to-int (gnus-soup-field))))
388                 areas)
389           (when (eq (preceding-char) ?\t)
390             (beginning-of-line 2)))
391         (kill-buffer (current-buffer))))
392     areas))
393
394 (defun gnus-soup-parse-replies (file)
395   "Parse soup REPLIES file FILE.
396 The result is a of vectors, each containing one entry from the REPLIES
397 file.  The vector contain three strings, [prefix name encoding]."
398   (let (replies)
399     (save-excursion
400       (set-buffer (nnheader-find-file-noselect file))
401       (buffer-disable-undo)
402       (goto-char (point-min))
403       (while (not (eobp))
404         (push (vector (gnus-soup-field) (gnus-soup-field)
405                       (gnus-soup-field))
406               replies)
407         (when (eq (preceding-char) ?\t)
408           (beginning-of-line 2)))
409       (kill-buffer (current-buffer)))
410     replies))
411
412 (defun gnus-soup-field ()
413   (prog1
414       (buffer-substring (point) (progn (skip-chars-forward "^\t\n") (point)))
415     (forward-char 1)))
416
417 (defun gnus-soup-read-areas ()
418   (or gnus-soup-areas
419       (setq gnus-soup-areas
420             (gnus-soup-parse-areas (concat gnus-soup-directory "AREAS")))))
421
422 (defun gnus-soup-write-areas ()
423   "Write the AREAS file."
424   (interactive)
425   (when gnus-soup-areas
426     (with-temp-file (concat gnus-soup-directory "AREAS")
427       (let ((areas gnus-soup-areas)
428             area)
429         (while (setq area (pop areas))
430           (insert
431            (format
432             "%s\t%s\t%s%s\n"
433             (gnus-soup-area-prefix area)
434             (gnus-soup-area-name area)
435             (gnus-soup-area-encoding area)
436             (if (or (gnus-soup-area-description area)
437                     (gnus-soup-area-number area))
438                 (concat "\t" (or (gnus-soup-area-description
439                                   area) "")
440                         (if (gnus-soup-area-number area)
441                             (concat "\t" (int-to-string
442                                           (gnus-soup-area-number area)))
443                           "")) ""))))))))
444
445 (defun gnus-soup-write-replies (dir areas)
446   "Write a REPLIES file in DIR containing AREAS."
447   (with-temp-file (concat dir "REPLIES")
448     (let (area)
449       (while (setq area (pop areas))
450         (insert (format "%s\t%s\t%s\n"
451                         (gnus-soup-reply-prefix area)
452                         (gnus-soup-reply-kind area)
453                         (gnus-soup-reply-encoding area)))))))
454
455 (defun gnus-soup-area (group)
456   (gnus-soup-read-areas)
457   (let ((areas gnus-soup-areas)
458         (real-group (gnus-group-real-name group))
459         area result)
460     (while areas
461       (setq area (car areas)
462             areas (cdr areas))
463       (when (equal (gnus-soup-area-name area) real-group)
464         (setq result area)))
465     (unless result
466       (setq result
467             (vector (gnus-soup-unique-prefix)
468                     real-group
469                     (format "%c%c%c"
470                             gnus-soup-encoding-type
471                             gnus-soup-index-type
472                             (if (gnus-member-of-valid 'mail group) ?m ?n))
473                     nil nil)
474             gnus-soup-areas (cons result gnus-soup-areas)))
475     result))
476
477 (defun gnus-soup-unique-prefix (&optional dir)
478   (let* ((dir (file-name-as-directory (or dir gnus-soup-directory)))
479          (entry (assoc dir gnus-soup-last-prefix))
480          gnus-soup-prev-prefix)
481     (if entry
482         ()
483       (when (file-exists-p (concat dir gnus-soup-prefix-file))
484         (ignore-errors
485           (load (concat dir gnus-soup-prefix-file) nil t t)))
486       (push (setq entry (cons dir (or gnus-soup-prev-prefix 0)))
487             gnus-soup-last-prefix))
488     (setcdr entry (1+ (cdr entry)))
489     (gnus-soup-write-prefixes)
490     (int-to-string (cdr entry))))
491
492 (defun gnus-soup-unpack-packet (dir unpacker packet)
493   "Unpack PACKET into DIR using UNPACKER.
494 Return whether the unpacking was successful."
495   (gnus-make-directory dir)
496   (gnus-message 4 "Unpacking: %s" (format unpacker packet))
497   (prog1
498       (zerop (call-process
499               shell-file-name nil nil nil shell-command-switch
500               (format "cd %s ; %s" (expand-file-name dir)
501                       (format unpacker packet))))
502     (gnus-message 4 "Unpacking...done")))
503
504 (defun gnus-soup-send-packet (packet)
505   (gnus-soup-unpack-packet
506    gnus-soup-replies-directory gnus-soup-unpacker packet)
507   (let ((replies (gnus-soup-parse-replies
508                   (concat gnus-soup-replies-directory "REPLIES"))))
509     (save-excursion
510       (while replies
511         (let* ((msg-file (concat gnus-soup-replies-directory
512                                  (gnus-soup-reply-prefix (car replies))
513                                  ".MSG"))
514                (msg-buf (and (file-exists-p msg-file)
515                              (nnheader-find-file-noselect msg-file)))
516                (tmp-buf (gnus-get-buffer-create " *soup send*"))
517                beg end)
518           (cond
519            ((and (/= (gnus-soup-encoding-format
520                       (gnus-soup-reply-encoding (car replies)))
521                      ?u)
522                  (/= (gnus-soup-encoding-format
523                       (gnus-soup-reply-encoding (car replies)))
524                      ?n)) ;; Gnus back compatibility.
525             (error "Unsupported encoding"))
526            ((null msg-buf)
527             t)
528            (t
529             (buffer-disable-undo msg-buf)
530             (set-buffer msg-buf)
531             (goto-char (point-min))
532             (while (not (eobp))
533               (unless (looking-at "#! *rnews +\\([0-9]+\\)")
534                 (error "Bad header"))
535               (forward-line 1)
536               (setq beg (point)
537                     end (+ (point) (string-to-int
538                                     (buffer-substring
539                                      (match-beginning 1) (match-end 1)))))
540               (switch-to-buffer tmp-buf)
541               (erase-buffer)
542               (insert-buffer-substring msg-buf beg end)
543               (goto-char (point-min))
544               (search-forward "\n\n")
545               (forward-char -1)
546               (insert mail-header-separator)
547               (setq message-user-agent (gnus-extended-version))
548               (cond
549                ((string= (gnus-soup-reply-kind (car replies)) "news")
550                 (gnus-message 5 "Sending news message to %s..."
551                               (mail-fetch-field "newsgroups"))
552                 (sit-for 1)
553                 (let ((message-syntax-checks
554                        'dont-check-for-anything-just-trust-me))
555                   (funcall message-send-news-function)))
556                ((string= (gnus-soup-reply-kind (car replies)) "mail")
557                 (gnus-message 5 "Sending mail to %s..."
558                               (mail-fetch-field "to"))
559                 (sit-for 1)
560                 (message-send-mail))
561                (t
562                 (error "Unknown reply kind")))
563               (set-buffer msg-buf)
564               (goto-char end))
565             (delete-file (buffer-file-name))
566             (kill-buffer msg-buf)
567             (kill-buffer tmp-buf)
568             (gnus-message 4 "Sent packet"))))
569         (setq replies (cdr replies)))
570       t)))
571
572 (provide 'gnus-soup)
573
574 ;;; gnus-soup.el ends here