2001-11-16 Simon Josefsson <jas@extundo.com>
[gnus] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
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 (eval-when-compile
29   (require 'cl)
30   (require 'imap)
31   (eval-when-compile (defvar display-time-mail-function)))
32 (eval-and-compile
33   (autoload 'pop3-movemail "pop3")
34   (autoload 'pop3-get-message-count "pop3")
35   (autoload 'nnheader-cancel-timer "nnheader")
36   (autoload 'nnheader-run-at-time "nnheader"))
37 (require 'format-spec)
38 (require 'mm-util)
39 (require 'message) ;; for `message-directory'
40
41 (defgroup mail-source nil
42   "The mail-fetching library."
43   :version "21.1"
44   :group 'gnus)
45
46 ;; Define these at compile time to avoid dragging in imap always.
47 (defconst mail-source-imap-authenticators
48   (eval-when-compile
49     (mapcar (lambda (a)
50               (list 'const (car a)))
51      imap-authenticator-alist)))
52 (defconst mail-source-imap-streams
53   (eval-when-compile
54     (mapcar (lambda (a)
55               (list 'const (car a)))
56      imap-stream-alist)))
57
58 (defcustom mail-sources nil
59   "*Where the mail backends will look for incoming mail.
60 This variable is a list of mail source specifiers.
61 See Info node `(gnus)Mail Source Specifiers'."
62   :group 'mail-source
63   :type `(repeat
64           (choice :format "%[Value Menu%] %v"
65                   :value (file)
66                   (cons :tag "Spool file"
67                         (const :format "" file)
68                         (checklist :tag "Options" :greedy t
69                                    (group :inline t
70                                           (const :format "" :value :path)
71                                           file)))
72                   (cons :tag "Several files in a directory"
73                         (const :format "" directory)
74                         (checklist :tag "Options" :greedy t
75                                    (group :inline t
76                                           (const :format "" :value :path)
77                                           (directory :tag "Path"))
78                                    (group :inline t
79                                           (const :format "" :value :suffix)
80                                           (string :tag "Suffix"))
81                                    (group :inline t
82                                           (const :format "" :value :predicate)
83                                           (function :tag "Predicate"))
84                                    (group :inline t
85                                           (const :format "" :value :prescript)
86                                           (string :tag "Prescript"))
87                                    (group :inline t
88                                           (const :format "" :value :postscript)
89                                           (string :tag "Postscript"))
90                                    (group :inline t
91                                           (const :format "" :value :plugged)
92                                           (boolean :tag "Plugged"))))
93                   (cons :tag "POP3 server"
94                         (const :format "" pop)
95                         (checklist :tag "Options" :greedy t
96                                    (group :inline t
97                                           (const :format "" :value :server)
98                                           (string :tag "Server"))
99                                    (group :inline t
100                                           (const :format "" :value :port)
101                                           (choice :tag "Port"
102                                                   :value "pop3"
103                                                   (number :format "%v")
104                                                   (string :format "%v")))
105                                    (group :inline t
106                                           (const :format "" :value :user)
107                                           (string :tag "User"))
108                                    (group :inline t
109                                           (const :format "" :value :password)
110                                           (string :tag "Password"))
111                                    (group :inline t
112                                           (const :format "" :value :program)
113                                           (string :tag "Program"))
114                                    (group :inline t
115                                           (const :format "" :value :prescript)
116                                           (string :tag "Prescript"))
117                                    (group :inline t
118                                           (const :format "" :value :postscript)
119                                           (string :tag "Postscript"))
120                                    (group :inline t
121                                           (const :format "" :value :function)
122                                           (function :tag "Function"))
123                                    (group :inline t
124                                           (const :format ""
125                                                  :value :authentication)
126                                           (choice :tag "Authentication"
127                                                   :value apop
128                                                   (const password)
129                                                   (const apop)))
130                                    (group :inline t
131                                           (const :format "" :value :plugged)
132                                           (boolean :tag "Plugged"))))
133                   (cons :tag "Maildir (qmail, postfix...)"
134                         (const :format "" maildir)
135                         (checklist :tag "Options" :greedy t
136                                    (group :inline t
137                                           (const :format "" :value :path)
138                                           (directory :tag "Path"))
139                                    (group :inline t
140                                           (const :format "" :value :plugged)
141                                           (boolean :tag "Plugged"))))
142                   (cons :tag "IMAP server"
143                         (const :format "" imap)
144                         (checklist :tag "Options" :greedy t
145                                    (group :inline t
146                                           (const :format "" :value :server)
147                                           (string :tag "Server"))
148                                    (group :inline t
149                                           (const :format "" :value :port)
150                                           (choice :tag "Port"
151                                                   :value 143
152                                                   number string))
153                                    (group :inline t
154                                           (const :format "" :value :user)
155                                           (string :tag "User"))
156                                    (group :inline t
157                                           (const :format "" :value :password)
158                                           (string :tag "Password"))
159                                    (group :inline t
160                                           (const :format "" :value :stream)
161                                           (choice :tag "Stream"
162                                                   :value network
163                                                   ,@mail-source-imap-streams))
164                                    (group :inline t
165                                           (const :format "" :value :program)
166                                           (string :tag "Program"))
167                                    (group :inline t
168                                           (const :format ""
169                                                  :value :authenticator)
170                                           (choice :tag "Authenticator"
171                                                   :value login
172                                                   ,@mail-source-imap-authenticators))
173                                    (group :inline t
174                                           (const :format "" :value :mailbox)
175                                           (string :tag "Mailbox"
176                                                   :value "INBOX"))
177                                    (group :inline t
178                                           (const :format "" :value :predicate)
179                                           (string :tag "Predicate"
180                                                   :value "UNSEEN UNDELETED"))
181                                    (group :inline t
182                                           (const :format "" :value :fetchflag)
183                                           (string :tag "Fetchflag"
184                                                   :value  "\\Deleted"))
185                                    (group :inline t
186                                           (const :format ""
187                                                  :value :dontexpunge)
188                                           (boolean :tag "Dontexpunge"))
189                                    (group :inline t
190                                           (const :format "" :value :plugged)
191                                           (boolean :tag "Plugged"))))
192                   (cons :tag "Webmail server"
193                         (const :format "" webmail)
194                         (checklist :tag "Options" :greedy t
195                                    (group :inline t
196                                          (const :format "" :value :subtype)
197                                          ;; Should be generated from
198                                          ;; `webmail-type-definition', but we
199                                          ;; can't require webmail without W3.
200                                          (choice :tag "Subtype"
201                                                  :value hotmail
202                                                  (const hotmail)
203                                                  (const yahoo)
204                                                  (const netaddress)
205                                                  (const netscape)
206                                                  (const my-deja)))
207                                    (group :inline t
208                                           (const :format "" :value :user)
209                                           (string :tag "User"))
210                                    (group :inline t
211                                           (const :format "" :value :password)
212                                           (string :tag "Password"))
213                                    (group :inline t
214                                           (const :format ""
215                                                  :value :dontexpunge)
216                                           (boolean :tag "Dontexpunge"))
217                                    (group :inline t
218                                           (const :format "" :value :plugged)
219                                           (boolean :tag "Plugged")))))))
220
221 (defcustom mail-source-primary-source nil
222   "*Primary source for incoming mail.
223 If non-nil, this maildrop will be checked periodically for new mail."
224   :group 'mail-source
225   :type 'sexp)
226
227 (defcustom mail-source-flash t
228   "*If non-nil, flash periodically when mail is available."
229   :group 'mail-source
230   :type 'boolean)
231
232 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
233   "File where mail will be stored while processing it."
234   :group 'mail-source
235   :type 'file)
236
237 (defcustom mail-source-directory message-directory
238   "Directory where files (if any) will be stored."
239   :group 'mail-source
240   :type 'directory)
241
242 (defcustom mail-source-default-file-modes 384
243   "Set the mode bits of all new mail files to this integer."
244   :group 'mail-source
245   :type 'integer)
246
247 (defcustom mail-source-delete-incoming nil
248   "*If non-nil, delete incoming files after handling."
249   :group 'mail-source
250   :type 'boolean)
251
252 (defcustom mail-source-incoming-file-prefix "Incoming"
253   "Prefix for file name for storing incoming mail"
254   :group 'mail-source
255   :type 'string)
256
257 (defcustom mail-source-report-new-mail-interval 5
258   "Interval in minutes between checks for new mail."
259   :group 'mail-source
260   :type 'number)
261
262 (defcustom mail-source-idle-time-delay 5
263   "Number of idle seconds to wait before checking for new mail."
264   :group 'mail-source
265   :type 'number)
266
267 (defcustom mail-source-movemail-program nil
268   "If non-nil, name of program for fetching new mail."
269   :group 'mail-source
270   :type '(choice (const nil) string))
271
272 ;;; Internal variables.
273
274 (defvar mail-source-string ""
275   "A dynamically bound string that says what the current mail source is.")
276
277 (defvar mail-source-new-mail-available nil
278   "Flag indicating when new mail is available.")
279
280 (eval-and-compile
281   (defvar mail-source-common-keyword-map
282     '((:plugged))
283     "Mapping from keywords to default values.
284 Common keywords should be listed here.")
285
286   (defvar mail-source-keyword-map
287     '((file
288        (:prescript)
289        (:prescript-delay)
290        (:postscript)
291        (:path (or (getenv "MAIL")
292                   (expand-file-name (user-login-name) rmail-spool-directory))))
293       (directory
294        (:path)
295        (:suffix ".spool")
296        (:predicate identity))
297       (pop
298        (:prescript)
299        (:prescript-delay)
300        (:postscript)
301        (:server (getenv "MAILHOST"))
302        (:port 110)
303        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
304        (:program)
305        (:function)
306        (:password)
307        (:authentication password))
308       (maildir
309        (:path (or (getenv "MAILDIR") "~/Maildir/"))
310        (:subdirs ("new" "cur"))
311        (:function))
312       (imap
313        (:server (getenv "MAILHOST"))
314        (:port)
315        (:stream)
316        (:program)
317        (:authentication)
318        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
319        (:password)
320        (:mailbox "INBOX")
321        (:predicate "UNSEEN UNDELETED")
322        (:fetchflag "\\Deleted")
323        (:dontexpunge))
324       (webmail
325        (:subtype hotmail)
326        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
327        (:password)
328        (:dontexpunge)
329        (:authentication password)))
330     "Mapping from keywords to default values.
331 All keywords that can be used must be listed here."))
332
333 (defvar mail-source-fetcher-alist
334   '((file mail-source-fetch-file)
335     (directory mail-source-fetch-directory)
336     (pop mail-source-fetch-pop)
337     (maildir mail-source-fetch-maildir)
338     (imap mail-source-fetch-imap)
339     (webmail mail-source-fetch-webmail))
340   "A mapping from source type to fetcher function.")
341
342 (defvar mail-source-password-cache nil)
343
344 (defvar mail-source-plugged t)
345
346 ;;; Functions
347
348 (eval-and-compile
349   (defun mail-source-strip-keyword (keyword)
350     "Strip the leading colon off the KEYWORD."
351     (intern (substring (symbol-name keyword) 1))))
352
353 (eval-and-compile
354   (defun mail-source-bind-1 (type)
355     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
356            default bind)
357       (while (setq default (pop defaults))
358         (push (list (mail-source-strip-keyword (car default))
359                     nil)
360               bind))
361       bind)))
362
363 (defmacro mail-source-bind (type-source &rest body)
364   "Return a `let' form that binds all variables in source TYPE.
365 TYPE-SOURCE is a list where the first element is the TYPE, and
366 the second variable is the SOURCE.
367 At run time, the mail source specifier SOURCE will be inspected,
368 and the variables will be set according to it.  Variables not
369 specified will be given default values.
370
371 After this is done, BODY will be executed in the scope
372 of the `let' form.
373
374 The variables bound and their default values are described by
375 the `mail-source-keyword-map' variable."
376   `(let ,(mail-source-bind-1 (car type-source))
377      (mail-source-set-1 ,(cadr type-source))
378      ,@body))
379
380 (put 'mail-source-bind 'lisp-indent-function 1)
381 (put 'mail-source-bind 'edebug-form-spec '(form body))
382
383 (defun mail-source-set-1 (source)
384   (let* ((type (pop source))
385          (defaults (cdr (assq type mail-source-keyword-map)))
386          default value keyword)
387     (while (setq default (pop defaults))
388       (set (mail-source-strip-keyword (setq keyword (car default)))
389            (if (setq value (plist-get source keyword))
390                (mail-source-value value)
391              (mail-source-value (cadr default)))))))
392
393 (eval-and-compile
394   (defun mail-source-bind-common-1 ()
395     (let* ((defaults mail-source-common-keyword-map)
396            default bind)
397       (while (setq default (pop defaults))
398         (push (list (mail-source-strip-keyword (car default))
399                     nil)
400               bind))
401       bind)))
402
403 (defun mail-source-set-common-1 (source)
404   (let* ((type (pop source))
405          (defaults mail-source-common-keyword-map)
406          (defaults-1 (cdr (assq type mail-source-keyword-map)))
407          default value keyword)
408     (while (setq default (pop defaults))
409       (set (mail-source-strip-keyword (setq keyword (car default)))
410            (if (setq value (plist-get source keyword))
411                (mail-source-value value)
412              (if (setq value (assq  keyword defaults-1))
413                  (mail-source-value (cadr value))
414                (mail-source-value (cadr default))))))))
415
416 (defmacro mail-source-bind-common (source &rest body)
417   "Return a `let' form that binds all common variables.
418 See `mail-source-bind'."
419   `(let ,(mail-source-bind-common-1)
420      (mail-source-set-common-1 source)
421      ,@body))
422
423 (put 'mail-source-bind-common 'lisp-indent-function 1)
424 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
425
426 (defun mail-source-value (value)
427   "Return the value of VALUE."
428   (cond
429    ;; String
430    ((stringp value)
431     value)
432    ;; Function
433    ((and (listp value)
434          (functionp (car value)))
435     (eval value))
436    ;; Just return the value.
437    (t
438     value)))
439
440 (defun mail-source-fetch (source callback)
441   "Fetch mail from SOURCE and call CALLBACK zero or more times.
442 CALLBACK will be called with the name of the file where (some of)
443 the mail from SOURCE is put.
444 Return the number of files that were found."
445   (mail-source-bind-common source
446     (if (or mail-source-plugged plugged)
447         (save-excursion
448           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
449                 (found 0))
450             (unless function
451               (error "%S is an invalid mail source specification" source))
452             ;; If there's anything in the crash box, we do it first.
453             (when (file-exists-p mail-source-crash-box)
454               (message "Processing mail from %s..." mail-source-crash-box)
455               (setq found (mail-source-callback
456                            callback mail-source-crash-box)))
457             (+ found
458                (if (or debug-on-quit debug-on-error)
459                    (funcall function source callback)
460                  (condition-case err
461                      (funcall function source callback)
462                    (error
463                     (unless (yes-or-no-p
464                              (format "Mail source error (%s).  Continue? " err))
465                       (error "Cannot get new mail"))
466                     0)))))))))
467
468 (defun mail-source-make-complex-temp-name (prefix)
469   (let ((newname (make-temp-name prefix))
470         (newprefix prefix))
471     (while (file-exists-p newname)
472       (setq newprefix (concat newprefix "x"))
473       (setq newname (make-temp-name newprefix)))
474     newname))
475
476 (defun mail-source-callback (callback info)
477   "Call CALLBACK on the mail file, and then remove the mail file.
478 Pass INFO on to CALLBACK."
479   (if (or (not (file-exists-p mail-source-crash-box))
480           (zerop (nth 7 (file-attributes mail-source-crash-box))))
481       (progn
482         (when (file-exists-p mail-source-crash-box)
483           (delete-file mail-source-crash-box))
484         0)
485     (prog1
486         (funcall callback mail-source-crash-box info)
487       (when (file-exists-p mail-source-crash-box)
488         ;; Delete or move the incoming mail out of the way.
489         (if mail-source-delete-incoming
490             (delete-file mail-source-crash-box)
491           (let ((incoming
492                  (mail-source-make-complex-temp-name
493                   (expand-file-name
494                    mail-source-incoming-file-prefix
495                    mail-source-directory))))
496             (unless (file-exists-p (file-name-directory incoming))
497               (make-directory (file-name-directory incoming) t))
498             (rename-file mail-source-crash-box incoming t)))))))
499
500 (defun mail-source-movemail (from to)
501   "Move FROM to TO using movemail."
502   (if (not (file-writable-p to))
503       (error "Can't write to crash box %s.  Not moving mail" to)
504     (let ((to (file-truename (expand-file-name to)))
505           errors result)
506       (setq to (file-truename to)
507             from (file-truename from))
508       ;; Set TO if have not already done so, and rename or copy
509       ;; the file FROM to TO if and as appropriate.
510       (cond
511        ((file-exists-p to)
512         ;; The crash box exists already.
513         t)
514        ((not (file-exists-p from))
515         ;; There is no inbox.
516         (setq to nil))
517        ((zerop (nth 7 (file-attributes from)))
518         ;; Empty file.
519         (setq to nil))
520        (t
521         ;; If getting from mail spool directory, use movemail to move
522         ;; rather than just renaming, so as to interlock with the
523         ;; mailer.
524         (unwind-protect
525             (save-excursion
526               (setq errors (generate-new-buffer " *mail source loss*"))
527               (let ((default-directory "/"))
528                 (setq result
529                       (apply
530                        'call-process
531                        (append
532                         (list
533                          (or mail-source-movemail-program
534                              (expand-file-name "movemail" exec-directory))
535                          nil errors nil from to)))))
536               (when (file-exists-p to)
537                 (set-file-modes to mail-source-default-file-modes))
538               (if (and (or (not (buffer-modified-p errors))
539                            (zerop (buffer-size errors)))
540                        (zerop result))
541                   ;; No output => movemail won.
542                   t
543                 (set-buffer errors)
544                 ;; There may be a warning about older revisions.  We
545                 ;; ignore that.
546                 (goto-char (point-min))
547                 (if (search-forward "older revision" nil t)
548                     t
549                   ;; Probably a real error.
550                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
551                   (goto-char (point-max))
552                   (skip-chars-backward " \t")
553                   (delete-region (point) (point-max))
554                   (goto-char (point-min))
555                   (when (looking-at "movemail: ")
556                     (delete-region (point-min) (match-end 0)))
557                   ;; Result may be a signal description string.
558                   (unless (yes-or-no-p
559                            (format "movemail: %s (%s return).  Continue? "
560                                    (buffer-string) result))
561                     (error "%s" (buffer-string)))
562                   (setq to nil)))))))
563       (when (and errors
564                  (buffer-name errors))
565         (kill-buffer errors))
566       ;; Return whether we moved successfully or not.
567       to)))
568
569 (defun mail-source-movemail-and-remove (from to)
570   "Move FROM to TO using movemail, then remove FROM if empty."
571   (or (not (mail-source-movemail from to))
572       (not (zerop (nth 7 (file-attributes from))))
573       (delete-file from)))
574
575 (defvar mail-source-read-passwd nil)
576 (defun mail-source-read-passwd (prompt &rest args)
577   "Read a password using PROMPT.
578 If ARGS, PROMPT is used as an argument to `format'."
579   (let ((prompt
580          (if args
581              (apply 'format prompt args)
582            prompt)))
583     (unless mail-source-read-passwd
584       (if (or (fboundp 'read-passwd) (load "passwd" t))
585           (setq mail-source-read-passwd 'read-passwd)
586         (unless (fboundp 'ange-ftp-read-passwd)
587           (autoload 'ange-ftp-read-passwd "ange-ftp"))
588         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
589     (funcall mail-source-read-passwd prompt)))
590
591 (defun mail-source-fetch-with-program (program)
592   (zerop (call-process shell-file-name nil nil nil
593                        shell-command-switch program)))
594
595 (defun mail-source-run-script (script spec &optional delay)
596   (when script
597     (if (and (symbolp script) (fboundp script))
598         (funcall script)
599       (mail-source-call-script
600        (format-spec script spec))))
601   (when delay
602     (sleep-for delay)))
603
604 (defun mail-source-call-script (script)
605   (let ((background nil))
606     (when (string-match "& *$" script)
607       (setq script (substring script 0 (match-beginning 0))
608             background 0))
609     (call-process shell-file-name nil background nil
610                   shell-command-switch script)))
611
612 ;;;
613 ;;; Different fetchers
614 ;;;
615
616 (defun mail-source-fetch-file (source callback)
617   "Fetcher for single-file sources."
618   (mail-source-bind (file source)
619     (mail-source-run-script
620      prescript (format-spec-make ?t mail-source-crash-box)
621      prescript-delay)
622     (let ((mail-source-string (format "file:%s" path)))
623       (if (mail-source-movemail path mail-source-crash-box)
624           (prog1
625               (mail-source-callback callback path)
626             (mail-source-run-script
627              postscript (format-spec-make ?t mail-source-crash-box)))
628         0))))
629
630 (defun mail-source-fetch-directory (source callback)
631   "Fetcher for directory sources."
632   (mail-source-bind (directory source)
633     (let ((found 0)
634           (mail-source-string (format "directory:%s" path)))
635       (dolist (file (directory-files
636                      path t (concat (regexp-quote suffix) "$")))
637         (when (and (file-regular-p file)
638                    (funcall predicate file)
639                    (mail-source-movemail file mail-source-crash-box))
640           (incf found (mail-source-callback callback file))))
641       found)))
642
643 (defun mail-source-fetch-pop (source callback)
644   "Fetcher for single-file sources."
645   (mail-source-bind (pop source)
646     (mail-source-run-script
647      prescript
648      (format-spec-make ?p password ?t mail-source-crash-box
649                        ?s server ?P port ?u user)
650      prescript-delay)
651     (let ((from (format "%s:%s:%s" server user port))
652           (mail-source-string (format "pop:%s@%s" user server))
653           result)
654       (when (eq authentication 'password)
655         (setq password
656               (or password
657                   (cdr (assoc from mail-source-password-cache))
658                   (mail-source-read-passwd
659                    (format "Password for %s at %s: " user server)))))
660       (when server
661         (setenv "MAILHOST" server))
662       (setq result
663             (cond
664              (program
665               (mail-source-fetch-with-program
666                (format-spec
667                 program
668                 (format-spec-make ?p password ?t mail-source-crash-box
669                                   ?s server ?P port ?u user))))
670              (function
671               (funcall function mail-source-crash-box))
672              ;; The default is to use pop3.el.
673              (t
674               (let ((pop3-password password)
675                     (pop3-maildrop user)
676                     (pop3-mailhost server)
677                     (pop3-port port)
678                     (pop3-authentication-scheme
679                      (if (eq authentication 'apop) 'apop 'pass)))
680                 (if (or debug-on-quit debug-on-error)
681                     (save-excursion (pop3-movemail mail-source-crash-box))
682                   (condition-case err
683                       (save-excursion (pop3-movemail mail-source-crash-box))
684                     (error
685                      ;; We nix out the password in case the error
686                      ;; was because of a wrong password being given.
687                      (setq mail-source-password-cache
688                            (delq (assoc from mail-source-password-cache)
689                                  mail-source-password-cache))
690                      (signal (car err) (cdr err)))))))))
691       (if result
692           (progn
693             (when (eq authentication 'password)
694               (unless (assoc from mail-source-password-cache)
695                 (push (cons from password) mail-source-password-cache)))
696             (prog1
697                 (mail-source-callback callback server)
698               ;; Update display-time's mail flag, if relevant.
699               (if (equal source mail-source-primary-source)
700                   (setq mail-source-new-mail-available nil))
701               (mail-source-run-script
702                postscript
703                (format-spec-make ?p password ?t mail-source-crash-box
704                                  ?s server ?P port ?u user))))
705         ;; We nix out the password in case the error
706         ;; was because of a wrong password being given.
707         (setq mail-source-password-cache
708               (delq (assoc from mail-source-password-cache)
709                     mail-source-password-cache))
710         0))))
711
712 (defun mail-source-check-pop (source)
713   "Check whether there is new mail."
714   (mail-source-bind (pop source)
715     (let ((from (format "%s:%s:%s" server user port))
716           (mail-source-string (format "pop:%s@%s" user server))
717           result)
718       (when (eq authentication 'password)
719         (setq password
720               (or password
721                   (cdr (assoc from mail-source-password-cache))
722                   (mail-source-read-passwd
723                    (format "Password for %s at %s: " user server))))
724         (unless (assoc from mail-source-password-cache)
725           (push (cons from password) mail-source-password-cache)))
726       (when server
727         (setenv "MAILHOST" server))
728       (setq result
729             (cond
730              ;; No easy way to check whether mail is waiting for these.
731              (program)
732              (function)
733              ;; The default is to use pop3.el.
734              (t
735               (let ((pop3-password password)
736                     (pop3-maildrop user)
737                     (pop3-mailhost server)
738                     (pop3-port port)
739                     (pop3-authentication-scheme
740                      (if (eq authentication 'apop) 'apop 'pass)))
741                 (if (or debug-on-quit debug-on-error)
742                     (save-excursion (pop3-get-message-count))
743                   (condition-case err
744                       (save-excursion (pop3-get-message-count))
745                     (error
746                      ;; We nix out the password in case the error
747                      ;; was because of a wrong password being given.
748                      (setq mail-source-password-cache
749                            (delq (assoc from mail-source-password-cache)
750                                  mail-source-password-cache))
751                      (signal (car err) (cdr err)))))))))
752       (if result
753           ;; Inform display-time that we have new mail.
754           (setq mail-source-new-mail-available (> result 0))
755         ;; We nix out the password in case the error
756         ;; was because of a wrong password being given.
757         (setq mail-source-password-cache
758               (delq (assoc from mail-source-password-cache)
759                     mail-source-password-cache)))
760       result)))
761
762 (defun mail-source-new-mail-p ()
763   "Handler for `display-time' to indicate when new mail is available."
764   ;; Flash (ie. ring the visible bell) if mail is available.
765   (if (and mail-source-flash mail-source-new-mail-available)
766       (let ((visible-bell t))
767         (ding)))
768   ;; Only report flag setting; flag is updated on a different schedule.
769   mail-source-new-mail-available)
770
771
772 (defvar mail-source-report-new-mail nil)
773 (defvar mail-source-report-new-mail-timer nil)
774 (defvar mail-source-report-new-mail-idle-timer nil)
775
776 (eval-when-compile
777   (if (featurep 'xemacs)
778       (require 'itimer)
779     (require 'timer)))
780
781 (defun mail-source-start-idle-timer ()
782   ;; Start our idle timer if necessary, so we delay the check until the
783   ;; user isn't typing.
784   (unless mail-source-report-new-mail-idle-timer
785     (setq mail-source-report-new-mail-idle-timer
786           (run-with-idle-timer
787            mail-source-idle-time-delay
788            nil
789            (lambda ()
790              (unwind-protect
791                  (mail-source-check-pop mail-source-primary-source)
792                (setq mail-source-report-new-mail-idle-timer nil)))))
793     ;; Since idle timers created when Emacs is already in the idle
794     ;; state don't get activated until Emacs _next_ becomes idle, we
795     ;; need to force our timer to be considered active now.  We do
796     ;; this by being naughty and poking the timer internals directly
797     ;; (element 0 of the vector is nil if the timer is active).
798     (aset mail-source-report-new-mail-idle-timer 0 nil)))
799
800 (defun mail-source-report-new-mail (arg)
801   "Toggle whether to report when new mail is available.
802 This only works when `display-time' is enabled."
803   (interactive "P")
804   (if (not mail-source-primary-source)
805       (error "Need to set `mail-source-primary-source' to check for new mail"))
806   (let ((on (if (null arg)
807                 (not mail-source-report-new-mail)
808               (> (prefix-numeric-value arg) 0))))
809     (setq mail-source-report-new-mail on)
810     (and mail-source-report-new-mail-timer
811          (nnheader-cancel-timer mail-source-report-new-mail-timer))
812     (and mail-source-report-new-mail-idle-timer
813          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
814     (setq mail-source-report-new-mail-timer nil)
815     (setq mail-source-report-new-mail-idle-timer nil)
816     (if on
817         (progn
818           (require 'time)
819           ;; display-time-mail-function is an Emacs 21 feature.
820           (setq display-time-mail-function #'mail-source-new-mail-p)
821           ;; Set up the main timer.
822           (setq mail-source-report-new-mail-timer
823                 (nnheader-run-at-time
824                  (* 60 mail-source-report-new-mail-interval)
825                  (* 60 mail-source-report-new-mail-interval)
826                  #'mail-source-start-idle-timer))
827           ;; When you get new mail, clear "Mail" from the mode line.
828           (add-hook 'nnmail-post-get-new-mail-hook
829                     'display-time-event-handler)
830           (message "Mail check enabled"))
831       (setq display-time-mail-function nil)
832       (remove-hook 'nnmail-post-get-new-mail-hook
833                    'display-time-event-handler)
834       (message "Mail check disabled"))))
835
836 (defun mail-source-fetch-maildir (source callback)
837   "Fetcher for maildir sources."
838   (mail-source-bind (maildir source)
839     (let ((found 0)
840           mail-source-string)
841       (unless (string-match "/$" path)
842         (setq path (concat path "/")))
843       (dolist (subdir subdirs)
844         (when (file-directory-p (concat path subdir))
845           (setq mail-source-string (format "maildir:%s%s" path subdir))
846           (dolist (file (directory-files (concat path subdir) t))
847             (when (and (not (file-directory-p file))
848                        (not (if function
849                                 (funcall function file mail-source-crash-box)
850                               (let ((coding-system-for-write
851                                      mm-text-coding-system)
852                                     (coding-system-for-read
853                                      mm-text-coding-system))
854                                 (with-temp-file mail-source-crash-box
855                                   (insert-file-contents file)
856                                   (goto-char (point-min))
857 ;;;                               ;; Unix mail format
858 ;;;                               (unless (looking-at "\n*From ")
859 ;;;                                 (insert "From maildir "
860 ;;;                                         (current-time-string) "\n"))
861 ;;;                               (while (re-search-forward "^From " nil t)
862 ;;;                                 (replace-match ">From "))
863 ;;;                               (goto-char (point-max))
864 ;;;                               (insert "\n\n")
865                                   ;; MMDF mail format
866                                   (insert "\001\001\001\001\n"))
867                                 (delete-file file)))))
868               (incf found (mail-source-callback callback file))))))
869       found)))
870
871 (eval-and-compile
872   (autoload 'imap-open "imap")
873   (autoload 'imap-authenticate "imap")
874   (autoload 'imap-mailbox-select "imap")
875   (autoload 'imap-mailbox-unselect "imap")
876   (autoload 'imap-mailbox-close "imap")
877   (autoload 'imap-search "imap")
878   (autoload 'imap-fetch "imap")
879   (autoload 'imap-close "imap")
880   (autoload 'imap-error-text "imap")
881   (autoload 'imap-message-flags-add "imap")
882   (autoload 'imap-list-to-message-set "imap")
883   (autoload 'imap-range-to-message-set "imap")
884   (autoload 'nnheader-ms-strip-cr "nnheader"))
885
886 (defvar mail-source-imap-file-coding-system 'binary
887   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
888
889 (defun mail-source-fetch-imap (source callback)
890   "Fetcher for imap sources."
891   (mail-source-bind (imap source)
892     (let ((from (format "%s:%s:%s" server user port))
893           (found 0)
894           (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
895           (mail-source-string (format "imap:%s:%s" server mailbox))
896           (imap-shell-program (or (list program) imap-shell-program))
897           remove)
898       (if (and (imap-open server port stream authentication buf)
899                (imap-authenticate
900                 user (or (cdr (assoc from mail-source-password-cache))
901                          password) buf)
902                (imap-mailbox-select mailbox nil buf))
903           (let ((coding-system-for-write mail-source-imap-file-coding-system)
904                 str)
905             (with-temp-file mail-source-crash-box
906               ;; Avoid converting 8-bit chars from inserted strings to
907               ;; multibyte.
908               (mm-disable-multibyte)
909               ;; remember password
910               (with-current-buffer buf
911                 (when (or imap-password
912                           (assoc from mail-source-password-cache))
913                   (push (cons from imap-password) mail-source-password-cache)))
914               ;; if predicate is nil, use all uids
915               (dolist (uid (imap-search (or predicate "1:*") buf))
916                 (when (setq str
917                             (if (imap-capability 'IMAP4rev1 buf)
918                                 (caddar (imap-fetch uid "BODY.PEEK[]"
919                                                     'BODYDETAIL nil buf))
920                               (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf)))
921                   (push uid remove)
922                   (insert "From imap " (current-time-string) "\n")
923                   (save-excursion
924                     (insert str "\n\n"))
925                   (while (re-search-forward "^From " nil t)
926                     (replace-match ">From "))
927                   (goto-char (point-max))))
928               (nnheader-ms-strip-cr))
929             (incf found (mail-source-callback callback server))
930             (when (and remove fetchflag)
931               (imap-message-flags-add
932                (imap-range-to-message-set (gnus-compress-sequence remove))
933                fetchflag nil buf))
934             (if dontexpunge
935                 (imap-mailbox-unselect buf)
936               (imap-mailbox-close nil buf))
937             (imap-close buf))
938         (imap-close buf)
939         ;; We nix out the password in case the error
940         ;; was because of a wrong password being given.
941         (setq mail-source-password-cache
942               (delq (assoc from mail-source-password-cache)
943                     mail-source-password-cache))
944         (error (imap-error-text buf)))
945       (kill-buffer buf)
946       found)))
947
948 (eval-and-compile
949   (autoload 'webmail-fetch "webmail"))
950
951 (defun mail-source-fetch-webmail (source callback)
952   "Fetch for webmail source."
953   (mail-source-bind (webmail source)
954     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
955           (webmail-newmail-only dontexpunge)
956           (webmail-move-to-trash-can (not dontexpunge)))
957       (when (eq authentication 'password)
958         (setq password
959               (or password
960                   (cdr (assoc (format "webmail:%s:%s" subtype user)
961                               mail-source-password-cache))
962                   (mail-source-read-passwd
963                    (format "Password for %s at %s: " user subtype))))
964         (when (and password
965                    (not (assoc (format "webmail:%s:%s" subtype user)
966                                mail-source-password-cache)))
967           (push (cons (format "webmail:%s:%s" subtype user) password)
968                 mail-source-password-cache)))
969       (webmail-fetch mail-source-crash-box subtype user password)
970       (mail-source-callback callback (symbol-name subtype)))))
971
972 (provide 'mail-source)
973
974 ;;; mail-source.el ends here