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