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