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