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