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