*** empty log message ***
[gnus] / lisp / gnus-cache.el
1 ;;; gnus-cache.el --- cache interface for Gnus
2 ;; Copyright (C) 1995,96 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: news
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 ;;; Code:
26
27 (require 'gnus)
28 (eval-when-compile (require 'cl))
29
30 (defvar gnus-cache-directory
31   (concat (file-name-as-directory gnus-article-save-directory) "cache/")
32   "*The directory where cached articles will be stored.")
33
34 (defvar gnus-cache-active-file 
35   (concat (file-name-as-directory gnus-cache-directory) "active")
36   "*The cache active file.")
37
38 (defvar gnus-cache-enter-articles '(ticked dormant)
39   "*Classes of articles to enter into the cache.")
40
41 (defvar gnus-cache-remove-articles '(read)
42   "*Classes of articles to remove from the cache.")
43
44 (defvar gnus-uncacheable-groups nil
45   "*Groups that match this regexp will not be cached.
46
47 If you want to avoid caching your nnml groups, you could set this
48 variable to \"^nnml\".")
49
50 \f
51
52 ;;; Internal variables.
53
54 (defvar gnus-cache-buffer nil)
55 (defvar gnus-cache-active-hashtb nil)
56 (defvar gnus-cache-active-altered nil)
57
58 (eval-and-compile
59   (autoload 'nnml-generate-nov-databases-1 "nnml")
60   (autoload 'nnvirtual-find-group-art "nnvirtual"))
61
62 \f
63
64 ;;; Functions called from Gnus.
65
66 (defun gnus-cache-open ()
67   "Initialize the cache."
68   (gnus-cache-read-active))
69
70 (defun gnus-cache-close ()
71   "Shut down the cache."
72   (gnus-cache-write-active)
73   (gnus-cache-save-buffers)
74   (setq gnus-cache-active-hashtb nil))
75
76 (defun gnus-cache-save-buffers ()
77   ;; save the overview buffer if it exists and has been modified
78   ;; delete empty cache subdirectories
79   (if (null gnus-cache-buffer)
80       ()
81     (let ((buffer (cdr gnus-cache-buffer))
82           (overview-file (gnus-cache-file-name
83                           (car gnus-cache-buffer) ".overview")))
84       ;; write the overview only if it was modified
85       (if (buffer-modified-p buffer)
86           (save-excursion
87             (set-buffer buffer)
88             (if (> (buffer-size) 0)
89                 ;; non-empty overview, write it out
90                 (progn
91                   (gnus-make-directory (file-name-directory overview-file))
92                   (write-region (point-min) (point-max)
93                                 overview-file nil 'quietly))
94               ;; empty overview file, remove it
95               (and (file-exists-p overview-file)
96                    (delete-file overview-file))
97               ;; if possible, remove group's cache subdirectory
98               (condition-case nil
99                   ;; FIXME: we can detect the error type and warn the user
100                   ;; of any inconsistencies (articles w/o nov entries?).
101                   ;; for now, just be conservative...delete only if safe -- sj
102                   (delete-directory (file-name-directory overview-file))
103                 (error nil)))))
104       ;; kill the buffer, it's either unmodified or saved
105       (gnus-kill-buffer buffer)
106       (setq gnus-cache-buffer nil))))
107
108 (defun gnus-cache-possibly-enter-article 
109   (group article headers ticked dormant unread &optional force)
110   (when (and (or force (not (eq gnus-use-cache 'passive)))
111              (vectorp headers)) ; This might be a dummy article.
112     ;; If this is a virtual group, we find the real group.
113     (when (gnus-virtual-group-p group)
114       (let ((result (nnvirtual-find-group-art group article)))
115         (setq group (car result)
116               article (cdr result)
117               headers (copy-sequence headers))
118         (aset headers 0 article)))
119     (let ((number (mail-header-number headers))
120           file dir)
121       (when (and (> number 0)           ; Reffed article.
122                  (or (not gnus-uncacheable-groups)
123                      (not (string-match gnus-uncacheable-groups group)))
124                  (or force
125                      (gnus-cache-member-of-class
126                       gnus-cache-enter-articles ticked dormant unread))
127                  (not (file-exists-p (setq file (gnus-cache-file-name
128                                                  group article)))))
129         ;; Possibly create the cache directory.
130         (or (file-exists-p (setq dir (file-name-directory file)))
131             (gnus-make-directory dir))
132         ;; Save the article in the cache.
133         (if (file-exists-p file)
134             t                           ; The article already is saved.
135           (let ((gnus-use-cache nil))
136             (gnus-summary-select-article))
137           (save-excursion
138             (set-buffer gnus-original-article-buffer)
139             (when (> (buffer-size) 0)
140               (write-region (point-min) (point-max) file nil 'quiet)
141               (gnus-cache-change-buffer group)
142               (set-buffer (cdr gnus-cache-buffer))
143               (goto-char (point-max))
144               (forward-line -1)
145               (while (condition-case ()
146                          (and (not (bobp))
147                               (> (read (current-buffer)) number))
148                        (error
149                         ;; The line was malformed, so we just remove it!!
150                         (gnus-delete-line)
151                         t))
152                 (forward-line -1))
153               (if (bobp) 
154                   (if (not (eobp))
155                       (progn
156                         (beginning-of-line)
157                         (if (< (read (current-buffer)) number)
158                             (forward-line 1)))
159                     (beginning-of-line))
160                 (forward-line 1))
161               (beginning-of-line)
162               ;; [number subject from date id references chars lines xref]
163               (insert (format "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n"
164                               (mail-header-number headers)
165                               (mail-header-subject headers)
166                               (mail-header-from headers)
167                               (mail-header-date headers)
168                               (mail-header-id headers)
169                               (or (mail-header-references headers) "")
170                               (or (mail-header-chars headers) "")
171                               (or (mail-header-lines headers) "")
172                               (or (mail-header-xref headers) "")))
173               ;; Update the active info.
174               (set-buffer gnus-summary-buffer)
175               (gnus-cache-update-active group number)
176               (push number gnus-newsgroup-cached))
177             t))))))
178
179 (defun gnus-cache-enter-remove-article (article)
180   "Mark ARTICLE for later possible removal."
181   (push article gnus-cache-removable-articles))
182
183 (defun gnus-cache-possibly-remove-articles ()
184   "Possibly remove some of the removable articles."
185   (if (not (gnus-virtual-group-p gnus-newsgroup-name))
186       (gnus-cache-possibly-remove-articles-1)
187     (let ((arts gnus-cache-removable-articles)
188           ga)
189       (while arts
190         (setq ga (nnvirtual-find-group-art gnus-newsgroup-name (pop arts)))
191         (let ((gnus-cache-removable-articles (list (cdr ga)))
192               (gnus-newsgroup-name (car ga)))
193           (gnus-cache-possibly-remove-articles-1))))
194     (setq gnus-cache-removable-articles nil)))
195
196 (defun gnus-cache-possibly-remove-articles-1 ()
197   "Possibly remove some of the removable articles."
198   (unless (eq gnus-use-cache 'passive)
199     (let ((articles gnus-cache-removable-articles)
200           (cache-articles gnus-newsgroup-cached)
201           article)
202       (gnus-cache-change-buffer gnus-newsgroup-name)
203       (while articles
204         (if (memq (setq article (pop articles)) cache-articles)
205             ;; The article was in the cache, so we see whether we are
206             ;; supposed to remove it from the cache.
207             (gnus-cache-possibly-remove-article
208              article (memq article gnus-newsgroup-marked)
209              (memq article gnus-newsgroup-dormant)
210              (or (memq article gnus-newsgroup-unreads)
211                  (memq article gnus-newsgroup-unselected))))))
212     ;; The overview file might have been modified, save it
213     ;; safe because we're only called at group exit anyway.
214     (gnus-cache-save-buffers)))
215
216 (defun gnus-cache-request-article (article group)
217   "Retrieve ARTICLE in GROUP from the cache."
218   (let ((file (gnus-cache-file-name group article))
219         (buffer-read-only nil))
220     (when (file-exists-p file)
221       (erase-buffer)
222       (gnus-kill-all-overlays)
223       (insert-file-contents file)
224       t)))
225
226 (defun gnus-cache-possibly-alter-active (group active)
227   "Alter the ACTIVE info for GROUP to reflect the articles in the cache."
228   (let ((cache-active (gnus-gethash group gnus-cache-active-hashtb)))
229     (and cache-active 
230          (< (car cache-active) (car active))
231          (setcar active (car cache-active)))
232     (and cache-active
233          (> (cdr cache-active) (cdr active))
234          (setcdr active (cdr cache-active)))))
235
236 (defun gnus-cache-retrieve-headers (articles group &optional fetch-old)
237   "Retrieve the headers for ARTICLES in GROUP."
238   (let* ((cached 
239           (setq gnus-newsgroup-cached (gnus-cache-articles-in-group group)))
240          (articles (gnus-sorted-complement articles cached))
241          (cache-file (gnus-cache-file-name group ".overview"))
242          type)
243     ;; We first retrieve all the headers that we don't have in 
244     ;; the cache.
245     (let ((gnus-use-cache nil))
246       (setq type (and articles 
247                       (gnus-retrieve-headers articles group fetch-old))))
248     (gnus-cache-save-buffers)
249     ;; Then we insert the cached headers.
250     (save-excursion
251       (cond
252        ((not (file-exists-p cache-file))
253         ;; There are no cached headers.
254         type)
255        ((null type)
256         ;; There were no uncached headers (or retrieval was 
257         ;; unsuccessful), so we use the cached headers exclusively.
258         (set-buffer nntp-server-buffer)
259         (erase-buffer)
260         (insert-file-contents cache-file)
261         'nov)
262        ((eq type 'nov)
263         ;; We have both cached and uncached NOV headers, so we
264         ;; braid them.
265         (gnus-cache-braid-nov group cached)
266         type)
267        (t
268         ;; We braid HEADs.
269         (gnus-cache-braid-heads group cached)
270         type)))))
271
272 (defun gnus-cache-enter-article (&optional n)
273   "Enter the next N articles into the cache.
274 If not given a prefix, use the process marked articles instead.
275 Returns the list of articles entered."
276   (interactive "P")
277   (gnus-set-global-variables)
278   (let ((articles (gnus-summary-work-articles n))
279         article out)
280     (while articles
281       (setq article (pop articles))
282       (when (gnus-cache-possibly-enter-article 
283              gnus-newsgroup-name article (gnus-summary-article-header article)
284              nil nil nil t)
285         (push article out))
286       (gnus-summary-remove-process-mark article)
287       (gnus-summary-update-secondary-mark article))
288     (gnus-summary-position-point)
289     (nreverse out)))
290
291 (defun gnus-cache-remove-article (n)
292   "Remove the next N articles from the cache.
293 If not given a prefix, use the process marked articles instead.
294 Returns the list of articles removed."
295   (interactive "P")
296   (gnus-set-global-variables)
297   (let ((articles (gnus-summary-work-articles n))
298         article out)
299     (while articles
300       (setq article (pop articles))
301       (when (gnus-cache-possibly-remove-article article nil nil nil t)
302         (push article out))
303       (gnus-summary-remove-process-mark article)
304       (gnus-summary-update-secondary-mark article))
305     (gnus-summary-position-point)
306     (nreverse out)))
307
308 (defun gnus-cached-article-p (article)
309   "Say whether ARTICLE is cached in the current group."
310   (memq article gnus-newsgroup-cached))
311
312 ;;; Internal functions.
313
314 (defun gnus-cache-change-buffer (group)
315   (and gnus-cache-buffer
316        ;; See if the current group's overview cache has been loaded.
317        (or (string= group (car gnus-cache-buffer))
318            ;; Another overview cache is current, save it.
319            (gnus-cache-save-buffers)))
320   ;; if gnus-cache buffer is nil, create it
321   (or gnus-cache-buffer
322       ;; Create cache buffer
323       (save-excursion
324         (setq gnus-cache-buffer
325               (cons group
326                     (set-buffer (get-buffer-create " *gnus-cache-overview*"))))
327         (buffer-disable-undo (current-buffer))
328         ;; Insert the contents of this group's cache overview.
329         (erase-buffer)
330         (let ((file (gnus-cache-file-name group ".overview")))
331           (and (file-exists-p file)
332                (insert-file-contents file)))
333         ;; We have a fresh (empty/just loaded) buffer, 
334         ;; mark it as unmodified to save a redundant write later.
335         (set-buffer-modified-p nil))))
336
337 ;; Return whether an article is a member of a class.
338 (defun gnus-cache-member-of-class (class ticked dormant unread)
339   (or (and ticked (memq 'ticked class))
340       (and dormant (memq 'dormant class))
341       (and unread (memq 'unread class))
342       (and (not unread) (memq 'read class))))
343
344 (defun gnus-cache-file-name (group article)
345   (concat (file-name-as-directory gnus-cache-directory)
346           (file-name-as-directory
347            (if (gnus-use-long-file-name 'not-cache)
348                group 
349              (let ((group (concat group "")))
350                (if (string-match ":" group)
351                    (aset group (match-beginning 0) ?/))
352                (nnheader-replace-chars-in-string group ?. ?/))))
353           (if (stringp article) article (int-to-string article))))
354
355 (defun gnus-cache-possibly-remove-article 
356   (article ticked dormant unread &optional force)
357   "Possibly remove ARTICLE from the cache."
358   (let ((file (gnus-cache-file-name gnus-newsgroup-name article)))
359     (when (and (file-exists-p file)
360                (or force
361                    (gnus-cache-member-of-class
362                     gnus-cache-remove-articles ticked dormant unread)))
363       (save-excursion
364         (delete-file file)
365         (set-buffer (cdr gnus-cache-buffer))
366         (goto-char (point-min))
367         (if (or (looking-at (concat (int-to-string article) "\t"))
368                 (search-forward (concat "\n" (int-to-string article) "\t")
369                                 (point-max) t))
370             (delete-region (progn (beginning-of-line) (point))
371                            (progn (forward-line 1) (point)))))
372       (setq gnus-newsgroup-cached
373             (delq article gnus-newsgroup-cached))
374       t)))
375
376 (defun gnus-cache-articles-in-group (group)
377   "Return a sorted list of cached articles in GROUP."
378   (let ((dir (file-name-directory (gnus-cache-file-name group 1)))
379         articles)
380     (when (file-exists-p dir)
381       (sort (mapcar (lambda (name) (string-to-int name)) 
382                     (directory-files dir nil "^[0-9]+$" t))
383             '<))))
384
385 (defun gnus-cache-braid-nov (group cached)
386   (let ((cache-buf (get-buffer-create " *gnus-cache*"))
387         beg end)
388     (gnus-cache-save-buffers)
389     (save-excursion
390       (set-buffer cache-buf)
391       (buffer-disable-undo (current-buffer))
392       (erase-buffer)
393       (insert-file-contents (gnus-cache-file-name group ".overview"))
394       (goto-char (point-min))
395       (insert "\n")
396       (goto-char (point-min)))
397     (set-buffer nntp-server-buffer)
398     (goto-char (point-min))
399     (while cached
400       (while (and (not (eobp))
401                   (< (read (current-buffer)) (car cached)))
402         (forward-line 1))
403       (beginning-of-line)
404       (save-excursion
405         (set-buffer cache-buf)
406         (if (search-forward (concat "\n" (int-to-string (car cached)) "\t")
407                             nil t)
408             (setq beg (progn (beginning-of-line) (point))
409                   end (progn (end-of-line) (point)))
410           (setq beg nil)))
411       (if beg (progn (insert-buffer-substring cache-buf beg end)
412                      (insert "\n")))
413       (setq cached (cdr cached)))
414     (kill-buffer cache-buf)))
415
416 (defun gnus-cache-braid-heads (group cached)
417   (let ((cache-buf (get-buffer-create " *gnus-cache*")))
418     (save-excursion
419       (set-buffer cache-buf)
420       (buffer-disable-undo (current-buffer))
421       (erase-buffer))
422     (set-buffer nntp-server-buffer)
423     (goto-char (point-min))
424     (while cached
425       (while (and (not (eobp))
426                   (looking-at "2.. +\\([0-9]+\\) ")
427                   (< (progn (goto-char (match-beginning 1))
428                             (read (current-buffer)))
429                      (car cached)))
430         (search-forward "\n.\n" nil 'move))
431       (beginning-of-line)
432       (save-excursion
433         (set-buffer cache-buf)
434         (erase-buffer)
435         (insert-file-contents (gnus-cache-file-name group (car cached)))
436         (goto-char (point-min))
437         (insert "220 " (int-to-string (car cached)) " Article retrieved.\n")
438         (search-forward "\n\n" nil 'move)
439         (delete-region (point) (point-max))
440         (forward-char -1)
441         (insert "."))
442       (insert-buffer-substring cache-buf)
443       (setq cached (cdr cached)))
444     (kill-buffer cache-buf)))
445
446 ;;;###autoload
447 (defun gnus-jog-cache ()
448   "Go through all groups and put the articles into the cache."
449   (interactive)
450   (let ((gnus-mark-article-hook nil)
451         (gnus-expert-user t)
452         (nnmail-spool-file nil)
453         (gnus-use-dribble-file nil)
454         (gnus-novice-user nil)
455         (gnus-large-newsgroup nil))
456     ;; Start Gnus.
457     (gnus)
458     ;; Go through all groups...
459     (gnus-group-mark-buffer)
460     (gnus-group-universal-argument 
461      nil nil 
462      (lambda ()
463        (gnus-summary-read-group nil nil t)
464        ;; ... and enter the articles into the cache.
465        (when (eq major-mode 'gnus-summary-mode)
466          (gnus-uu-mark-buffer)
467          (gnus-cache-enter-article)
468          (kill-buffer (current-buffer)))))))
469
470 (defun gnus-cache-read-active (&optional force)
471   "Read the cache active file."
472   (if (not (and (file-exists-p gnus-cache-active-file)
473                 (or force (not gnus-cache-active-hashtb))))
474       ;; There is no active file, so we generate one.
475       (gnus-cache-generate-active)
476     ;; We simply read the active file.
477     (save-excursion
478       (gnus-set-work-buffer)
479       (insert-file-contents gnus-cache-active-file)
480       (gnus-active-to-gnus-format
481        nil (setq gnus-cache-active-hashtb 
482                  (gnus-make-hashtable 
483                   (count-lines (point-min) (point-max)))))
484       (setq gnus-cache-active-altered nil))))
485        
486 (defun gnus-cache-write-active (&optional force)
487   "Write the active hashtb to the active file."
488   (when (or force
489             (and gnus-cache-active-hashtb
490                  gnus-cache-active-altered))
491     (save-excursion
492       (gnus-set-work-buffer)
493       (mapatoms
494        (lambda (sym)
495          (when (and sym (boundp sym))
496            (insert (format "%s %d %d y\n"
497                            (symbol-name sym) (cdr (symbol-value sym))
498                            (car (symbol-value sym))))))
499        gnus-cache-active-hashtb)
500       (gnus-make-directory (file-name-directory gnus-cache-active-file))
501       (write-region 
502        (point-min) (point-max) gnus-cache-active-file nil 'silent))
503     ;; Mark the active hashtb as unaltered.
504     (setq gnus-cache-active-altered nil)))
505
506 (defun gnus-cache-update-active (group number &optional low)
507   "Update the upper bound of the active info of GROUP to NUMBER.
508 If LOW, update the lower bound instead."
509   (let ((active (gnus-gethash group gnus-cache-active-hashtb)))
510     (if (null active)
511         ;; We just create a new active entry for this group.
512         (gnus-sethash group (cons number number) gnus-cache-active-hashtb)
513       ;; Update the lower or upper bound.
514       (if low
515           (setcar active number)
516         (setcdr active number))
517       ;; Mark the active hashtb as altered.
518       (setq gnus-cache-active-altered t))))
519
520 ;;;###autoload
521 (defun gnus-cache-generate-active (&optional directory)
522   "Generate the cache active file."
523   (interactive)
524   (let* ((top (null directory))
525          (directory (expand-file-name (or directory gnus-cache-directory)))
526          (files (directory-files directory 'full))
527          (group 
528           (if top
529               ""
530             (string-match 
531              (concat "^" (file-name-as-directory
532                           (expand-file-name gnus-cache-directory)))
533              (directory-file-name directory))
534             (nnheader-replace-chars-in-string 
535              (substring (directory-file-name directory) (match-end 0))
536              ?/ ?.)))
537          nums alphs)
538     (when top
539       (gnus-message 5 "Generating the cache active file...")
540       (setq gnus-cache-active-hashtb (gnus-make-hashtable 123)))
541     ;; Separate articles from all other files and directories.
542     (while files
543       (if (string-match "^[0-9]+$" (file-name-nondirectory (car files)))
544           (push (string-to-int (file-name-nondirectory (pop files))) nums)
545         (push (pop files) alphs)))
546     ;; If we have nums, then this is probably a valid group.
547     (setq nums (sort nums '<))
548     (if nums
549         (gnus-sethash group (cons (car nums) (gnus-last-element nums))
550                       gnus-cache-active-hashtb))
551     ;; Go through all the other files.
552     (while alphs
553       (when (and (file-directory-p (car alphs))
554                  (not (string-match "^\\.\\.?$"
555                                     (file-name-nondirectory (car alphs)))))
556         ;; We descend directories.
557         (gnus-cache-generate-active (car alphs)))
558       (setq alphs (cdr alphs)))
559     ;; Write the new active file.
560     (when top
561       (gnus-cache-write-active t)
562       (gnus-message 5 "Generating the cache active file...done"))))
563
564 ;;;###autoload
565 (defun gnus-cache-generate-nov-databases (dir)
566   "Generate NOV files recursively starting in DIR."
567   (interactive (list gnus-cache-directory))
568   (gnus-cache-close)
569   (let ((nnml-generate-active-function 'identity))
570     (nnml-generate-nov-databases-1 dir)))
571
572 (provide 'gnus-cache)
573               
574 ;;; gnus-cache.el ends here