2001-10-01 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 ;;; Internal variables.
268
269 (defvar mail-source-string ""
270   "A dynamically bound string that says what the current mail source is.")
271
272 (defvar mail-source-new-mail-available nil
273   "Flag indicating when new mail is available.")
274
275 (eval-and-compile
276   (defvar mail-source-common-keyword-map
277     '((:plugged))
278     "Mapping from keywords to default values.
279 Common keywords should be listed here.")
280
281   (defvar mail-source-keyword-map
282     '((file
283        (:prescript)
284        (:prescript-delay)
285        (:postscript)
286        (:path (or (getenv "MAIL")
287                   (expand-file-name (user-login-name) rmail-spool-directory))))
288       (directory
289        (:path)
290        (:suffix ".spool")
291        (:predicate identity))
292       (pop
293        (:prescript)
294        (:prescript-delay)
295        (:postscript)
296        (:server (getenv "MAILHOST"))
297        (:port 110)
298        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
299        (:program)
300        (:function)
301        (:password)
302        (:authentication password))
303       (maildir
304        (:path (or (getenv "MAILDIR") "~/Maildir/"))
305        (:subdirs ("new" "cur"))
306        (:function))
307       (imap
308        (:server (getenv "MAILHOST"))
309        (:port)
310        (:stream)
311        (:program)
312        (:authentication)
313        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
314        (:password)
315        (:mailbox "INBOX")
316        (:predicate "UNSEEN UNDELETED")
317        (:fetchflag "\\Deleted")
318        (:dontexpunge))
319       (webmail
320        (:subtype hotmail)
321        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
322        (:password)
323        (:dontexpunge)
324        (:authentication password)))
325     "Mapping from keywords to default values.
326 All keywords that can be used must be listed here."))
327
328 (defvar mail-source-fetcher-alist
329   '((file mail-source-fetch-file)
330     (directory mail-source-fetch-directory)
331     (pop mail-source-fetch-pop)
332     (maildir mail-source-fetch-maildir)
333     (imap mail-source-fetch-imap)
334     (webmail mail-source-fetch-webmail))
335   "A mapping from source type to fetcher function.")
336
337 (defvar mail-source-password-cache nil)
338
339 (defvar mail-source-plugged t)
340
341 ;;; Functions
342
343 (eval-and-compile
344   (defun mail-source-strip-keyword (keyword)
345     "Strip the leading colon off the KEYWORD."
346     (intern (substring (symbol-name keyword) 1))))
347
348 (eval-and-compile
349   (defun mail-source-bind-1 (type)
350     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
351            default bind)
352       (while (setq default (pop defaults))
353         (push (list (mail-source-strip-keyword (car default))
354                     nil)
355               bind))
356       bind)))
357
358 (defmacro mail-source-bind (type-source &rest body)
359   "Return a `let' form that binds all variables in source TYPE.
360 TYPE-SOURCE is a list where the first element is the TYPE, and
361 the second variable is the SOURCE.
362 At run time, the mail source specifier SOURCE will be inspected,
363 and the variables will be set according to it.  Variables not
364 specified will be given default values.
365
366 After this is done, BODY will be executed in the scope
367 of the `let' form.
368
369 The variables bound and their default values are described by
370 the `mail-source-keyword-map' variable."
371   `(let ,(mail-source-bind-1 (car type-source))
372      (mail-source-set-1 ,(cadr type-source))
373      ,@body))
374
375 (put 'mail-source-bind 'lisp-indent-function 1)
376 (put 'mail-source-bind 'edebug-form-spec '(form body))
377
378 (defun mail-source-set-1 (source)
379   (let* ((type (pop source))
380          (defaults (cdr (assq type mail-source-keyword-map)))
381          default value keyword)
382     (while (setq default (pop defaults))
383       (set (mail-source-strip-keyword (setq keyword (car default)))
384            (if (setq value (plist-get source keyword))
385                (mail-source-value value)
386              (mail-source-value (cadr default)))))))
387
388 (eval-and-compile
389   (defun mail-source-bind-common-1 ()
390     (let* ((defaults mail-source-common-keyword-map)
391            default bind)
392       (while (setq default (pop defaults))
393         (push (list (mail-source-strip-keyword (car default))
394                     nil)
395               bind))
396       bind)))
397
398 (defun mail-source-set-common-1 (source)
399   (let* ((type (pop source))
400          (defaults mail-source-common-keyword-map)
401          (defaults-1 (cdr (assq type mail-source-keyword-map)))
402          default value keyword)
403     (while (setq default (pop defaults))
404       (set (mail-source-strip-keyword (setq keyword (car default)))
405            (if (setq value (plist-get source keyword))
406                (mail-source-value value)
407              (if (setq value (assq  keyword defaults-1))
408                  (mail-source-value (cadr value))
409                (mail-source-value (cadr default))))))))
410
411 (defmacro mail-source-bind-common (source &rest body)
412   "Return a `let' form that binds all common variables.
413 See `mail-source-bind'."
414   `(let ,(mail-source-bind-common-1)
415      (mail-source-set-common-1 source)
416      ,@body))
417
418 (put 'mail-source-bind-common 'lisp-indent-function 1)
419 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
420
421 (defun mail-source-value (value)
422   "Return the value of VALUE."
423   (cond
424    ;; String
425    ((stringp value)
426     value)
427    ;; Function
428    ((and (listp value)
429          (functionp (car value)))
430     (eval value))
431    ;; Just return the value.
432    (t
433     value)))
434
435 (defun mail-source-fetch (source callback)
436   "Fetch mail from SOURCE and call CALLBACK zero or more times.
437 CALLBACK will be called with the name of the file where (some of)
438 the mail from SOURCE is put.
439 Return the number of files that were found."
440   (mail-source-bind-common source
441     (if (or mail-source-plugged plugged)
442         (save-excursion
443           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
444                 (found 0))
445             (unless function
446               (error "%S is an invalid mail source specification" source))
447             ;; If there's anything in the crash box, we do it first.
448             (when (file-exists-p mail-source-crash-box)
449               (message "Processing mail from %s..." mail-source-crash-box)
450               (setq found (mail-source-callback
451                            callback mail-source-crash-box)))
452             (+ found
453                (condition-case err
454                    (funcall function source callback)
455                  (error
456                   (unless (yes-or-no-p
457                            (format "Mail source error (%s).  Continue? " err))
458                     (error "Cannot get new mail"))
459                   0))))))))
460
461 (defun mail-source-make-complex-temp-name (prefix)
462   (let ((newname (make-temp-name prefix))
463         (newprefix prefix))
464     (while (file-exists-p newname)
465       (setq newprefix (concat newprefix "x"))
466       (setq newname (make-temp-name newprefix)))
467     newname))
468
469 (defun mail-source-callback (callback info)
470   "Call CALLBACK on the mail file, and then remove the mail file.
471 Pass INFO on to CALLBACK."
472   (if (or (not (file-exists-p mail-source-crash-box))
473           (zerop (nth 7 (file-attributes mail-source-crash-box))))
474       (progn
475         (when (file-exists-p mail-source-crash-box)
476           (delete-file mail-source-crash-box))
477         0)
478     (prog1
479         (funcall callback mail-source-crash-box info)
480       (when (file-exists-p mail-source-crash-box)
481         ;; Delete or move the incoming mail out of the way.
482         (if mail-source-delete-incoming
483             (delete-file mail-source-crash-box)
484           (let ((incoming
485                  (mail-source-make-complex-temp-name
486                   (expand-file-name
487                    mail-source-incoming-file-prefix
488                    mail-source-directory))))
489             (unless (file-exists-p (file-name-directory incoming))
490               (make-directory (file-name-directory incoming) t))
491             (rename-file mail-source-crash-box incoming t)))))))
492
493 (defun mail-source-movemail (from to)
494   "Move FROM to TO using movemail."
495   (if (not (file-writable-p to))
496       (error "Can't write to crash box %s.  Not moving mail" to)
497     (let ((to (file-truename (expand-file-name to)))
498           errors result)
499       (setq to (file-truename to)
500             from (file-truename from))
501       ;; Set TO if have not already done so, and rename or copy
502       ;; the file FROM to TO if and as appropriate.
503       (cond
504        ((file-exists-p to)
505         ;; The crash box exists already.
506         t)
507        ((not (file-exists-p from))
508         ;; There is no inbox.
509         (setq to nil))
510        ((zerop (nth 7 (file-attributes from)))
511         ;; Empty file.
512         (setq to nil))
513        (t
514         ;; If getting from mail spool directory, use movemail to move
515         ;; rather than just renaming, so as to interlock with the
516         ;; mailer.
517         (unwind-protect
518             (save-excursion
519               (setq errors (generate-new-buffer " *mail source loss*"))
520               (let ((default-directory "/"))
521                 (setq result
522                       (apply
523                        'call-process
524                        (append
525                         (list
526                          (expand-file-name "movemail" exec-directory)
527                          nil errors nil from to)))))
528               (when (file-exists-p to)
529                 (set-file-modes to mail-source-default-file-modes))
530               (if (and (or (not (buffer-modified-p errors))
531                            (zerop (buffer-size errors)))
532                        (zerop result))
533                   ;; No output => movemail won.
534                   t
535                 (set-buffer errors)
536                 ;; There may be a warning about older revisions.  We
537                 ;; ignore that.
538                 (goto-char (point-min))
539                 (if (search-forward "older revision" nil t)
540                     t
541                   ;; Probably a real error.
542                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
543                   (goto-char (point-max))
544                   (skip-chars-backward " \t")
545                   (delete-region (point) (point-max))
546                   (goto-char (point-min))
547                   (when (looking-at "movemail: ")
548                     (delete-region (point-min) (match-end 0)))
549                   ;; Result may be a signal description string.
550                   (unless (yes-or-no-p
551                            (format "movemail: %s (%s return).  Continue? "
552                                    (buffer-string) result))
553                     (error "%s" (buffer-string)))
554                   (setq to nil)))))))
555       (when (and errors
556                  (buffer-name errors))
557         (kill-buffer errors))
558       ;; Return whether we moved successfully or not.
559       to)))
560
561 (defun mail-source-movemail-and-remove (from to)
562   "Move FROM to TO using movemail, then remove FROM if empty."
563   (or (not (mail-source-movemail from to))
564       (not (zerop (nth 7 (file-attributes from))))
565       (delete-file from)))
566
567 (defvar mail-source-read-passwd nil)
568 (defun mail-source-read-passwd (prompt &rest args)
569   "Read a password using PROMPT.
570 If ARGS, PROMPT is used as an argument to `format'."
571   (let ((prompt
572          (if args
573              (apply 'format prompt args)
574            prompt)))
575     (unless mail-source-read-passwd
576       (if (or (fboundp 'read-passwd) (load "passwd" t))
577           (setq mail-source-read-passwd 'read-passwd)
578         (unless (fboundp 'ange-ftp-read-passwd)
579           (autoload 'ange-ftp-read-passwd "ange-ftp"))
580         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
581     (funcall mail-source-read-passwd prompt)))
582
583 (defun mail-source-fetch-with-program (program)
584   (zerop (call-process shell-file-name nil nil nil
585                        shell-command-switch program)))
586
587 (defun mail-source-run-script (script spec &optional delay)
588   (when script
589     (if (and (symbolp script) (fboundp script))
590         (funcall script)
591       (mail-source-call-script
592        (format-spec script spec))))
593   (when delay
594     (sleep-for delay)))
595
596 (defun mail-source-call-script (script)
597   (let ((background nil))
598     (when (string-match "& *$" script)
599       (setq script (substring script 0 (match-beginning 0))
600             background 0))
601     (call-process shell-file-name nil background nil
602                   shell-command-switch script)))
603
604 ;;;
605 ;;; Different fetchers
606 ;;;
607
608 (defun mail-source-fetch-file (source callback)
609   "Fetcher for single-file sources."
610   (mail-source-bind (file source)
611     (mail-source-run-script
612      prescript (format-spec-make ?t mail-source-crash-box)
613      prescript-delay)
614     (let ((mail-source-string (format "file:%s" path)))
615       (if (mail-source-movemail path mail-source-crash-box)
616           (prog1
617               (mail-source-callback callback path)
618             (mail-source-run-script
619              postscript (format-spec-make ?t mail-source-crash-box)))
620         0))))
621
622 (defun mail-source-fetch-directory (source callback)
623   "Fetcher for directory sources."
624   (mail-source-bind (directory source)
625     (let ((found 0)
626           (mail-source-string (format "directory:%s" path)))
627       (dolist (file (directory-files
628                      path t (concat (regexp-quote suffix) "$")))
629         (when (and (file-regular-p file)
630                    (funcall predicate file)
631                    (mail-source-movemail file mail-source-crash-box))
632           (incf found (mail-source-callback callback file))))
633       found)))
634
635 (defun mail-source-fetch-pop (source callback)
636   "Fetcher for single-file sources."
637   (mail-source-bind (pop source)
638     (mail-source-run-script
639      prescript
640      (format-spec-make ?p password ?t mail-source-crash-box
641                        ?s server ?P port ?u user)
642      prescript-delay)
643     (let ((from (format "%s:%s:%s" server user port))
644           (mail-source-string (format "pop:%s@%s" user server))
645           result)
646       (when (eq authentication 'password)
647         (setq password
648               (or password
649                   (cdr (assoc from mail-source-password-cache))
650                   (mail-source-read-passwd
651                    (format "Password for %s at %s: " user server)))))
652       (when server
653         (setenv "MAILHOST" server))
654       (setq result
655             (cond
656              (program
657               (mail-source-fetch-with-program
658                (format-spec
659                 program
660                 (format-spec-make ?p password ?t mail-source-crash-box
661                                   ?s server ?P port ?u user))))
662              (function
663               (funcall function mail-source-crash-box))
664              ;; The default is to use pop3.el.
665              (t
666               (let ((pop3-password password)
667                     (pop3-maildrop user)
668                     (pop3-mailhost server)
669                     (pop3-port port)
670                     (pop3-authentication-scheme
671                      (if (eq authentication 'apop) 'apop 'pass)))
672                 (condition-case err
673                     (save-excursion (pop3-movemail mail-source-crash-box))
674                   (error
675                    ;; We nix out the password in case the error
676                    ;; was because of a wrong password being given.
677                    (setq mail-source-password-cache
678                          (delq (assoc from mail-source-password-cache)
679                                mail-source-password-cache))
680                    (signal (car err) (cdr err))))))))
681       (if result
682           (progn
683             (when (eq authentication 'password)
684               (unless (assoc from mail-source-password-cache)
685                 (push (cons from password) mail-source-password-cache)))
686             (prog1
687                 (mail-source-callback callback server)
688               ;; Update display-time's mail flag, if relevant.
689               (if (equal source mail-source-primary-source)
690                   (setq mail-source-new-mail-available nil))
691               (mail-source-run-script
692                postscript
693                (format-spec-make ?p password ?t mail-source-crash-box
694                                  ?s server ?P port ?u user))))
695         ;; We nix out the password in case the error
696         ;; was because of a wrong password being given.
697         (setq mail-source-password-cache
698               (delq (assoc from mail-source-password-cache)
699                     mail-source-password-cache))
700         0))))
701
702 (defun mail-source-check-pop (source)
703   "Check whether there is new mail."
704   (mail-source-bind (pop source)
705     (let ((from (format "%s:%s:%s" server user port))
706           (mail-source-string (format "pop:%s@%s" user server))
707           result)
708       (when (eq authentication 'password)
709         (setq password
710               (or password
711                   (cdr (assoc from mail-source-password-cache))
712                   (mail-source-read-passwd
713                    (format "Password for %s at %s: " user server))))
714         (unless (assoc from mail-source-password-cache)
715           (push (cons from password) mail-source-password-cache)))
716       (when server
717         (setenv "MAILHOST" server))
718       (setq result
719             (cond
720              ;; No easy way to check whether mail is waiting for these.
721              (program)
722              (function)
723              ;; The default is to use pop3.el.
724              (t
725               (let ((pop3-password password)
726                     (pop3-maildrop user)
727                     (pop3-mailhost server)
728                     (pop3-port port)
729                     (pop3-authentication-scheme
730                      (if (eq authentication 'apop) 'apop 'pass)))
731                 (condition-case err
732                     (save-excursion (pop3-get-message-count))
733                   (error
734                    ;; We nix out the password in case the error
735                    ;; was because of a wrong password being given.
736                    (setq mail-source-password-cache
737                          (delq (assoc from mail-source-password-cache)
738                                mail-source-password-cache))
739                    (signal (car err) (cdr err))))))))
740       (if result
741           ;; Inform display-time that we have new mail.
742           (setq mail-source-new-mail-available (> result 0))
743         ;; We nix out the password in case the error
744         ;; was because of a wrong password being given.
745         (setq mail-source-password-cache
746               (delq (assoc from mail-source-password-cache)
747                     mail-source-password-cache)))
748       result)))
749
750 (defun mail-source-new-mail-p ()
751   "Handler for `display-time' to indicate when new mail is available."
752   ;; Flash (ie. ring the visible bell) if mail is available.
753   (if (and mail-source-flash mail-source-new-mail-available)
754       (let ((visible-bell t))
755         (ding)))
756   ;; Only report flag setting; flag is updated on a different schedule.
757   mail-source-new-mail-available)
758
759
760 (defvar mail-source-report-new-mail nil)
761 (defvar mail-source-report-new-mail-timer nil)
762 (defvar mail-source-report-new-mail-idle-timer nil)
763
764 (eval-when-compile
765   (if (featurep 'xemacs)
766       (require 'itimer)
767     (require 'timer)))
768
769 (defun mail-source-start-idle-timer ()
770   ;; Start our idle timer if necessary, so we delay the check until the
771   ;; user isn't typing.
772   (unless mail-source-report-new-mail-idle-timer
773     (setq mail-source-report-new-mail-idle-timer
774           (run-with-idle-timer
775            mail-source-idle-time-delay
776            nil
777            (lambda ()
778              (unwind-protect
779                  (mail-source-check-pop mail-source-primary-source)
780                (setq mail-source-report-new-mail-idle-timer nil)))))
781     ;; Since idle timers created when Emacs is already in the idle
782     ;; state don't get activated until Emacs _next_ becomes idle, we
783     ;; need to force our timer to be considered active now.  We do
784     ;; this by being naughty and poking the timer internals directly
785     ;; (element 0 of the vector is nil if the timer is active).
786     (aset mail-source-report-new-mail-idle-timer 0 nil)))
787
788 (defun mail-source-report-new-mail (arg)
789   "Toggle whether to report when new mail is available.
790 This only works when `display-time' is enabled."
791   (interactive "P")
792   (if (not mail-source-primary-source)
793       (error "Need to set `mail-source-primary-source' to check for new mail"))
794   (let ((on (if (null arg)
795                 (not mail-source-report-new-mail)
796               (> (prefix-numeric-value arg) 0))))
797     (setq mail-source-report-new-mail on)
798     (and mail-source-report-new-mail-timer
799          (nnheader-cancel-timer mail-source-report-new-mail-timer))
800     (and mail-source-report-new-mail-idle-timer
801          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
802     (setq mail-source-report-new-mail-timer nil)
803     (setq mail-source-report-new-mail-idle-timer nil)
804     (if on
805         (progn
806           (require 'time)
807           ;; display-time-mail-function is an Emacs 21 feature.
808           (setq display-time-mail-function #'mail-source-new-mail-p)
809           ;; Set up the main timer.
810           (setq mail-source-report-new-mail-timer
811                 (nnheader-run-at-time
812                  (* 60 mail-source-report-new-mail-interval)
813                  (* 60 mail-source-report-new-mail-interval)
814                  #'mail-source-start-idle-timer))
815           ;; When you get new mail, clear "Mail" from the mode line.
816           (add-hook 'nnmail-post-get-new-mail-hook
817                     'display-time-event-handler)
818           (message "Mail check enabled"))
819       (setq display-time-mail-function nil)
820       (remove-hook 'nnmail-post-get-new-mail-hook
821                    'display-time-event-handler)
822       (message "Mail check disabled"))))
823
824 (defun mail-source-fetch-maildir (source callback)
825   "Fetcher for maildir sources."
826   (mail-source-bind (maildir source)
827     (let ((found 0)
828           mail-source-string)
829       (unless (string-match "/$" path)
830         (setq path (concat path "/")))
831       (dolist (subdir subdirs)
832         (when (file-directory-p (concat path subdir))
833           (setq mail-source-string (format "maildir:%s%s" path subdir))
834           (dolist (file (directory-files (concat path subdir) t))
835             (when (and (not (file-directory-p file))
836                        (not (if function
837                                 (funcall function file mail-source-crash-box)
838                               (let ((coding-system-for-write
839                                      mm-text-coding-system)
840                                     (coding-system-for-read
841                                      mm-text-coding-system))
842                                 (with-temp-file mail-source-crash-box
843                                   (insert-file-contents file)
844                                   (goto-char (point-min))
845 ;;;                               ;; Unix mail format
846 ;;;                               (unless (looking-at "\n*From ")
847 ;;;                                 (insert "From maildir "
848 ;;;                                         (current-time-string) "\n"))
849 ;;;                               (while (re-search-forward "^From " nil t)
850 ;;;                                 (replace-match ">From "))
851 ;;;                               (goto-char (point-max))
852 ;;;                               (insert "\n\n")
853                                   ;; MMDF mail format
854                                   (insert "\001\001\001\001\n"))
855                                 (delete-file file)))))
856               (incf found (mail-source-callback callback file))))))
857       found)))
858
859 (eval-and-compile
860   (autoload 'imap-open "imap")
861   (autoload 'imap-authenticate "imap")
862   (autoload 'imap-mailbox-select "imap")
863   (autoload 'imap-mailbox-unselect "imap")
864   (autoload 'imap-mailbox-close "imap")
865   (autoload 'imap-search "imap")
866   (autoload 'imap-fetch "imap")
867   (autoload 'imap-close "imap")
868   (autoload 'imap-error-text "imap")
869   (autoload 'imap-message-flags-add "imap")
870   (autoload 'imap-list-to-message-set "imap")
871   (autoload 'imap-range-to-message-set "imap")
872   (autoload 'nnheader-ms-strip-cr "nnheader"))
873
874 (defvar mail-source-imap-file-coding-system 'binary
875   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
876
877 (defun mail-source-fetch-imap (source callback)
878   "Fetcher for imap sources."
879   (mail-source-bind (imap source)
880     (let ((from (format "%s:%s:%s" server user port))
881           (found 0)
882           (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
883           (mail-source-string (format "imap:%s:%s" server mailbox))
884           (imap-shell-program (or (list program) imap-shell-program))
885           remove)
886       (if (and (imap-open server port stream authentication buf)
887                (imap-authenticate
888                 user (or (cdr (assoc from mail-source-password-cache))
889                          password) buf)
890                (imap-mailbox-select mailbox nil buf))
891           (let ((coding-system-for-write mail-source-imap-file-coding-system)
892                 str)
893             (with-temp-file mail-source-crash-box
894               ;; Avoid converting 8-bit chars from inserted strings to
895               ;; multibyte.
896               (mm-disable-multibyte)
897               ;; remember password
898               (with-current-buffer buf
899                 (when (or imap-password
900                           (assoc from mail-source-password-cache))
901                   (push (cons from imap-password) mail-source-password-cache)))
902               ;; if predicate is nil, use all uids
903               (dolist (uid (imap-search (or predicate "1:*") buf))
904                 (when (setq str (if (imap-capability 'IMAP4rev1 buf)
905                                     (imap-fetch uid "BODY.PEEK[]" 'BODYDETAIL
906                                                 nil buf)
907                             (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf)))
908                   (push uid remove)
909                   (insert "From imap " (current-time-string) "\n")
910                   (save-excursion
911                     (insert str "\n\n"))
912                   (while (re-search-forward "^From " nil t)
913                     (replace-match ">From "))
914                   (goto-char (point-max))))
915               (nnheader-ms-strip-cr))
916             (incf found (mail-source-callback callback server))
917             (when (and remove fetchflag)
918               (imap-message-flags-add
919                (imap-range-to-message-set (gnus-compress-sequence remove))
920                fetchflag nil buf))
921             (if dontexpunge
922                 (imap-mailbox-unselect buf)
923               (imap-mailbox-close buf))
924             (imap-close buf))
925         (imap-close buf)
926         ;; We nix out the password in case the error
927         ;; was because of a wrong password being given.
928         (setq mail-source-password-cache
929               (delq (assoc from mail-source-password-cache)
930                     mail-source-password-cache))
931         (error (imap-error-text buf)))
932       (kill-buffer buf)
933       found)))
934
935 (eval-and-compile
936   (autoload 'webmail-fetch "webmail"))
937
938 (defun mail-source-fetch-webmail (source callback)
939   "Fetch for webmail source."
940   (mail-source-bind (webmail source)
941     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
942           (webmail-newmail-only dontexpunge)
943           (webmail-move-to-trash-can (not dontexpunge)))
944       (when (eq authentication 'password)
945         (setq password
946               (or password
947                   (cdr (assoc (format "webmail:%s:%s" subtype user)
948                               mail-source-password-cache))
949                   (mail-source-read-passwd
950                    (format "Password for %s at %s: " user subtype))))
951         (when (and password
952                    (not (assoc (format "webmail:%s:%s" subtype user)
953                                mail-source-password-cache)))
954           (push (cons (format "webmail:%s:%s" subtype user) password)
955                 mail-source-password-cache)))
956       (webmail-fetch mail-source-crash-box subtype user password)
957       (mail-source-callback callback (symbol-name subtype)))))
958
959 (provide 'mail-source)
960
961 ;;; mail-source.el ends here