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