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