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