Feedback T-gnus 6.16.
[elisp/gnus.git-] / lisp / gnus-soup.el
1 ;;; gnus-soup.el --- SOUP packet writing support for Gnus
2
3 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2002
4 ;;      Free Software Foundation, Inc.
5
6 ;; Author: Per Abrahamsen <abraham@iesd.auc.dk>
7 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;; Keywords: news, mail
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;;; Code:
30
31 (eval-when-compile (require 'cl))
32
33 (require 'gnus)
34 (require 'gnus-art)
35 (require 'message)
36 (require 'gnus-start)
37 (require 'gnus-range)
38
39 ;;; User Variables:
40
41 (defvar gnus-soup-directory (nnheader-concat gnus-home-directory "SoupBrew/")
42   "*Directory containing an unpacked SOUP packet.")
43
44 (defvar gnus-soup-replies-directory
45   (nnheader-concat gnus-soup-directory "SoupReplies/")
46   "*Directory where Gnus will do processing of replies.")
47
48 (defvar gnus-soup-prefix-file "gnus-prefix"
49   "*Name of the file where Gnus stores the last used prefix.")
50
51 (defvar gnus-soup-packer "tar cf - %s | gzip > $HOME/Soupout%d.tgz"
52   "Format string command for packing a SOUP packet.
53 The SOUP files will be inserted where the %s is in the string.
54 This string MUST contain both %s and %d.  The file number will be
55 inserted where %d appears.")
56
57 (defvar gnus-soup-unpacker "gunzip -c %s | tar xvf -"
58   "*Format string command for unpacking a SOUP packet.
59 The SOUP packet file name will be inserted at the %s.")
60
61 (defvar gnus-soup-packet-directory gnus-home-directory
62   "*Where gnus-soup will look for REPLIES packets.")
63
64 (defvar gnus-soup-packet-regexp "Soupin"
65   "*Regular expression matching SOUP REPLIES packets in `gnus-soup-packet-directory'.")
66
67 (defvar gnus-soup-ignored-headers "^Xref:"
68   "*Regexp to match headers to be removed when brewing SOUP packets.")
69
70 ;;; Internal Variables:
71
72 (defvar gnus-soup-encoding-type ?u
73   "*Soup encoding type.
74 `u' is USENET news format, `m' is Unix mbox format, and `M' is MMDF mailbox
75 format.")
76
77 (defvar gnus-soup-index-type ?c
78   "*Soup index type.
79 `n' means no index file and `c' means standard Cnews overview
80 format.")
81
82 (defvar gnus-soup-areas nil)
83 (defvar gnus-soup-last-prefix nil)
84 (defvar gnus-soup-prev-prefix nil)
85 (defvar gnus-soup-buffers nil)
86
87 ;;; Access macros:
88
89 (defmacro gnus-soup-area-prefix (area)
90   `(aref ,area 0))
91 (defmacro gnus-soup-set-area-prefix (area prefix)
92   `(aset ,area 0 ,prefix))
93 (defmacro gnus-soup-area-name (area)
94   `(aref ,area 1))
95 (defmacro gnus-soup-area-encoding (area)
96   `(aref ,area 2))
97 (defmacro gnus-soup-area-description (area)
98   `(aref ,area 3))
99 (defmacro gnus-soup-area-number (area)
100   `(aref ,area 4))
101 (defmacro gnus-soup-area-set-number (area value)
102   `(aset ,area 4 ,value))
103
104 (defmacro gnus-soup-encoding-format (encoding)
105   `(aref ,encoding 0))
106 (defmacro gnus-soup-encoding-index (encoding)
107   `(aref ,encoding 1))
108 (defmacro gnus-soup-encoding-kind (encoding)
109   `(aref ,encoding 2))
110
111 (defmacro gnus-soup-reply-prefix (reply)
112   `(aref ,reply 0))
113 (defmacro gnus-soup-reply-kind (reply)
114   `(aref ,reply 1))
115 (defmacro gnus-soup-reply-encoding (reply)
116   `(aref ,reply 2))
117
118 ;;; Commands:
119
120 (defun gnus-soup-send-replies ()
121   "Unpack and send all replies in the reply packet."
122   (interactive)
123   (let ((packets (directory-files
124                   gnus-soup-packet-directory t gnus-soup-packet-regexp)))
125     (while packets
126       (when (gnus-soup-send-packet (car packets))
127         (delete-file (car packets)))
128       (setq packets (cdr packets)))))
129
130 (defun gnus-soup-add-article (n)
131   "Add the current article to SOUP packet.
132 If N is a positive number, add the N next articles.
133 If N is a negative number, add the N previous articles.
134 If N is nil and any articles have been marked with the process mark,
135 move those articles instead."
136   (interactive "P")
137   (let* ((articles (gnus-summary-work-articles n))
138          (tmp-buf (gnus-get-buffer-create "*soup work*"))
139          (area (gnus-soup-area gnus-newsgroup-name))
140          (prefix (gnus-soup-area-prefix area))
141          headers)
142     (buffer-disable-undo tmp-buf)
143     (save-excursion
144       (while articles
145         ;; Put the article in a buffer.
146         (set-buffer tmp-buf)
147         (when (gnus-request-article-this-buffer
148                (car articles) gnus-newsgroup-name)
149           (setq headers (nnheader-parse-head t))
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-mark-as-read (car articles) gnus-souped-mark))
161         (gnus-summary-remove-process-mark (car articles))
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   (if (file-exists-p gnus-soup-directory)
172       (if (directory-files gnus-soup-directory nil "\\.MSG$")
173           (gnus-soup-pack gnus-soup-directory gnus-soup-packer)
174         (message "No files to pack."))
175     (message "No such directory: %s" gnus-soup-directory)))
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              ((or (= gnus-soup-encoding-type ?u)
251                   (= gnus-soup-encoding-type ?n)) ;;Gnus back compatibility.
252               (format "#! rnews %d\n" (buffer-size)))
253              ((= gnus-soup-encoding-type ?m)
254               (while (search-forward "\nFrom " nil t)
255                 (replace-match "\n>From " t t))
256               (concat "From " (or from "unknown")
257                       " " (current-time-string) "\n"))
258              ((= gnus-soup-encoding-type ?M)
259               "\^a\^a\^a\^a\n")
260              (t (error "Unsupported type: %c" gnus-soup-encoding-type))))
261       ;; Insert the soup header and the article in the MSG buf.
262       (set-buffer msg-buf)
263       (goto-char (point-max))
264       (insert head-line)
265       (setq beg (point))
266       (insert-buffer-substring article-buf)
267       ;; Insert the index in the IDX buf.
268       (cond ((= index ?c)
269              (set-buffer idx-buf)
270              (gnus-soup-insert-idx beg headers))
271             ((/= index ?n)
272              (error "Unknown index type: %c" type)))
273       ;; Return the MSG buf.
274       msg-buf)))
275
276 (defun gnus-soup-group-brew (group &optional not-all)
277   "Enter GROUP and add all articles to a SOUP package.
278 If NOT-ALL, don't pack ticked articles."
279   (let ((gnus-expert-user t)
280         (gnus-large-newsgroup nil)
281         (entry (gnus-gethash group gnus-newsrc-hashtb)))
282     (when (or (null entry)
283               (eq (car entry) t)
284               (and (car entry)
285                    (> (car entry) 0))
286               (and (not not-all)
287                    (gnus-range-length (cdr (assq 'tick (gnus-info-marks
288                                                         (nth 2 entry)))))))
289       (when (gnus-summary-read-group group nil t)
290         (setq gnus-newsgroup-processable
291               (reverse
292                (if (not not-all)
293                    (append gnus-newsgroup-marked gnus-newsgroup-unreads)
294                  gnus-newsgroup-unreads)))
295         (gnus-soup-add-article nil)
296         (gnus-summary-exit)))))
297
298 (defun gnus-soup-insert-idx (offset header)
299   ;; [number subject from date id references chars lines xref]
300   (goto-char (point-max))
301   (insert
302    (format "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t\t\n"
303            offset
304            (or (mail-header-subject header) "(none)")
305            (or (mail-header-from header) "(nobody)")
306            (or (mail-header-date header) "")
307            (or (mail-header-id header)
308                (concat "soup-dummy-id-"
309                        (mapconcat
310                         (lambda (time) (int-to-string time))
311                         (current-time) "-")))
312            (or (mail-header-references header) "")
313            (or (mail-header-chars header) 0)
314            (or (mail-header-lines header) "0"))))
315
316 (defun gnus-soup-save-areas ()
317   "Write all SOUP buffers."
318   (interactive)
319   (gnus-soup-write-areas)
320   (save-excursion
321     (let (buf)
322       (while gnus-soup-buffers
323         (setq buf (car gnus-soup-buffers)
324               gnus-soup-buffers (cdr gnus-soup-buffers))
325         (if (not (buffer-name buf))
326             ()
327           (set-buffer buf)
328           (when (buffer-modified-p)
329             (save-buffer))
330           (kill-buffer (current-buffer)))))
331     (gnus-soup-write-prefixes)))
332
333 (defun gnus-soup-write-prefixes ()
334   (let ((prefixes gnus-soup-last-prefix)
335         prefix)
336     (save-excursion
337       (gnus-set-work-buffer)
338       (while (setq prefix (pop prefixes))
339         (erase-buffer)
340         (insert (format "(setq gnus-soup-prev-prefix %d)\n" (cdr prefix)))
341         (gnus-write-buffer-as-coding-system
342          nnheader-text-coding-system
343          (concat (car prefix) gnus-soup-prefix-file))))))
344
345 (defun gnus-soup-pack (dir packer)
346   (let* ((files (mapconcat 'identity
347                            '("AREAS" "*.MSG" "*.IDX" "INFO"
348                              "LIST" "REPLIES" "COMMANDS" "ERRORS")
349                            " "))
350          (packer (if (< (string-match "%s" packer)
351                         (string-match "%d" packer))
352                      (format packer files
353                              (string-to-int (gnus-soup-unique-prefix dir)))
354                    (format packer
355                            (string-to-int (gnus-soup-unique-prefix dir))
356                            files)))
357          (dir (expand-file-name dir)))
358     (gnus-make-directory dir)
359     (setq gnus-soup-areas nil)
360     (gnus-message 4 "Packing %s..." packer)
361     (if (eq 0 (call-process shell-file-name
362                             nil nil nil shell-command-switch
363                             (concat "cd " dir " ; " packer)))
364         (progn
365           (call-process shell-file-name nil nil nil shell-command-switch
366                         (concat "cd " dir " ; rm " files))
367           (gnus-message 4 "Packing...done" packer))
368       (error "Couldn't pack packet"))))
369
370 (defun gnus-soup-parse-areas (file)
371   "Parse soup area file FILE.
372 The result is a of vectors, each containing one entry from the AREA file.
373 The vector contain five strings,
374   [prefix name encoding description number]
375 though the two last may be nil if they are missing."
376   (let (areas)
377     (when (file-exists-p file)
378       (save-excursion
379         (set-buffer (nnheader-find-file-noselect file 'force))
380         (buffer-disable-undo)
381         (goto-char (point-min))
382         (while (not (eobp))
383           (push (vector (gnus-soup-field)
384                         (gnus-soup-field)
385                         (gnus-soup-field)
386                         (and (eq (preceding-char) ?\t)
387                              (gnus-soup-field))
388                         (and (eq (preceding-char) ?\t)
389                              (string-to-int (gnus-soup-field))))
390                 areas)
391           (when (eq (preceding-char) ?\t)
392             (beginning-of-line 2)))
393         (kill-buffer (current-buffer))))
394     areas))
395
396 (defun gnus-soup-parse-replies (file)
397   "Parse soup REPLIES file FILE.
398 The result is a of vectors, each containing one entry from the REPLIES
399 file.  The vector contain three strings, [prefix name encoding]."
400   (let (replies)
401     (save-excursion
402       (set-buffer (nnheader-find-file-noselect file))
403       (buffer-disable-undo)
404       (goto-char (point-min))
405       (while (not (eobp))
406         (push (vector (gnus-soup-field) (gnus-soup-field)
407                       (gnus-soup-field))
408               replies)
409         (when (eq (preceding-char) ?\t)
410           (beginning-of-line 2)))
411       (kill-buffer (current-buffer)))
412     replies))
413
414 (defun gnus-soup-field ()
415   (prog1
416       (buffer-substring (point) (progn (skip-chars-forward "^\t\n") (point)))
417     (forward-char 1)))
418
419 (defun gnus-soup-read-areas ()
420   (or gnus-soup-areas
421       (setq gnus-soup-areas
422             (gnus-soup-parse-areas (concat gnus-soup-directory "AREAS")))))
423
424 (defun gnus-soup-write-areas ()
425   "Write the AREAS file."
426   (interactive)
427   (when gnus-soup-areas
428     (with-temp-file (concat gnus-soup-directory "AREAS")
429       (let ((areas gnus-soup-areas)
430             area)
431         (while (setq area (pop areas))
432           (insert
433            (format
434             "%s\t%s\t%s%s\n"
435             (gnus-soup-area-prefix area)
436             (gnus-soup-area-name area)
437             (gnus-soup-area-encoding area)
438             (if (or (gnus-soup-area-description area)
439                     (gnus-soup-area-number area))
440                 (concat "\t" (or (gnus-soup-area-description
441                                   area) "")
442                         (if (gnus-soup-area-number area)
443                             (concat "\t" (int-to-string
444                                           (gnus-soup-area-number area)))
445                           "")) ""))))))))
446
447 (defun gnus-soup-write-replies (dir areas)
448   "Write a REPLIES file in DIR containing AREAS."
449   (with-temp-file (concat dir "REPLIES")
450     (let (area)
451       (while (setq area (pop areas))
452         (insert (format "%s\t%s\t%s\n"
453                         (gnus-soup-reply-prefix area)
454                         (gnus-soup-reply-kind area)
455                         (gnus-soup-reply-encoding area)))))))
456
457 (defun gnus-soup-area (group)
458   (gnus-soup-read-areas)
459   (let ((areas gnus-soup-areas)
460         (real-group (gnus-group-real-name group))
461         area result)
462     (while areas
463       (setq area (car areas)
464             areas (cdr areas))
465       (when (equal (gnus-soup-area-name area) real-group)
466         (setq result area)))
467     (unless result
468       (setq result
469             (vector (gnus-soup-unique-prefix)
470                     real-group
471                     (format "%c%c%c"
472                             gnus-soup-encoding-type
473                             gnus-soup-index-type
474                             (if (gnus-member-of-valid 'mail group) ?m ?n))
475                     nil nil)
476             gnus-soup-areas (cons result gnus-soup-areas)))
477     result))
478
479 (defun gnus-soup-unique-prefix (&optional dir)
480   (let* ((dir (file-name-as-directory (or dir gnus-soup-directory)))
481          (entry (assoc dir gnus-soup-last-prefix))
482          gnus-soup-prev-prefix)
483     (if entry
484         ()
485       (when (file-exists-p (concat dir gnus-soup-prefix-file))
486         (ignore-errors
487           (load (concat dir gnus-soup-prefix-file) nil t t)))
488       (push (setq entry (cons dir (or gnus-soup-prev-prefix 0)))
489             gnus-soup-last-prefix))
490     (setcdr entry (1+ (cdr entry)))
491     (gnus-soup-write-prefixes)
492     (int-to-string (cdr entry))))
493
494 (defun gnus-soup-unpack-packet (dir unpacker packet)
495   "Unpack PACKET into DIR using UNPACKER.
496 Return whether the unpacking was successful."
497   (gnus-make-directory dir)
498   (gnus-message 4 "Unpacking: %s" (format unpacker packet))
499   (prog1
500       (eq 0 (call-process
501              shell-file-name nil nil nil shell-command-switch
502              (format "cd %s ; %s" (expand-file-name dir)
503                      (format unpacker packet))))
504     (gnus-message 4 "Unpacking...done")))
505
506 (defun gnus-soup-send-packet (packet)
507   (gnus-soup-unpack-packet
508    gnus-soup-replies-directory gnus-soup-unpacker packet)
509   (let ((replies (gnus-soup-parse-replies
510                   (concat gnus-soup-replies-directory "REPLIES"))))
511     (save-excursion
512       (while replies
513         (let* ((msg-file (concat gnus-soup-replies-directory
514                                  (gnus-soup-reply-prefix (car replies))
515                                  ".MSG"))
516                (msg-buf (and (file-exists-p msg-file)
517                              (nnheader-find-file-noselect msg-file)))
518                (tmp-buf (gnus-get-buffer-create " *soup send*"))
519                beg end)
520           (cond
521            ((and (/= (gnus-soup-encoding-format
522                       (gnus-soup-reply-encoding (car replies)))
523                      ?u)
524                  (/= (gnus-soup-encoding-format
525                       (gnus-soup-reply-encoding (car replies)))
526                      ?n)) ;; Gnus back compatibility.
527             (error "Unsupported encoding"))
528            ((null msg-buf)
529             t)
530            (t
531             (buffer-disable-undo msg-buf)
532             (set-buffer msg-buf)
533             (goto-char (point-min))
534             (while (not (eobp))
535               (unless (looking-at "#! *rnews +\\([0-9]+\\)")
536                 (error "Bad header"))
537               (forward-line 1)
538               (setq beg (point)
539                     end (+ (point) (string-to-int
540                                     (buffer-substring
541                                      (match-beginning 1) (match-end 1)))))
542               (switch-to-buffer tmp-buf)
543               (erase-buffer)
544               (set-buffer-multibyte nil)
545               (insert-buffer-substring msg-buf beg end)
546               (cond
547                ((string= (gnus-soup-reply-kind (car replies)) "news")
548                 (gnus-message 5 "Sending news message to %s..."
549                               (mail-fetch-field "newsgroups"))
550                 (sit-for 1)
551                 (let ((message-syntax-checks
552                        'dont-check-for-anything-just-trust-me)
553                       (method (if (functionp message-post-method)
554                                   (funcall message-post-method)
555                                 message-post-method))
556                       result)
557                   (run-hooks 'message-send-news-hook)
558                   (gnus-open-server method)
559                   (message "Sending news via %s..."
560                            (gnus-server-string method))
561                   (unless (let ((mail-header-separator ""))
562                             (gnus-request-post method))
563                     (message "Couldn't send message via news: %s"
564                              (nnheader-get-report (car method))))))
565                ((string= (gnus-soup-reply-kind (car replies)) "mail")
566                 (gnus-message 5 "Sending mail to %s..."
567                               (mail-fetch-field "to"))
568                 (sit-for 1)
569                 (let ((mail-header-separator ""))
570                   (mm-with-unibyte-current-buffer
571                    (funcall (or message-send-mail-real-function
572                                 message-send-mail-function)))))
573                (t
574                 (error "Unknown reply kind")))
575               (set-buffer msg-buf)
576               (goto-char end))
577             (delete-file (buffer-file-name))
578             (kill-buffer msg-buf)
579             (kill-buffer tmp-buf)
580             (gnus-message 4 "Sent packet"))))
581         (setq replies (cdr replies)))
582       t)))
583
584 (provide 'gnus-soup)
585
586 ;;; gnus-soup.el ends here