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