241dc7de8939c7e96c8ac79dc7a77801d7a52221
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Simon Josefsson <simon@josefsson.org>
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; nnimap interfaces Gnus with IMAP servers.
26
27 ;;; Code:
28
29 (eval-and-compile
30   (require 'nnheader))
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'nnheader)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnoo)
39 (require 'netrc)
40 (require 'utf7)
41 (require 'parse-time)
42
43 (autoload 'auth-source-forget-user-or-password "auth-source")
44 (autoload 'auth-source-user-or-password "auth-source")
45
46 (nnoo-declare nnimap)
47
48 (defvoo nnimap-address nil
49   "The address of the IMAP server.")
50
51 (defvoo nnimap-server-port nil
52   "The IMAP port used.
53 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
54 it will default to `imap'.")
55
56 (defvoo nnimap-stream 'ssl
57   "How nnimap will talk to the IMAP server.
58 Values are `ssl', `network', `starttls' or `shell'.")
59
60 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
61                                  (if (listp imap-shell-program)
62                                      (car imap-shell-program)
63                                    imap-shell-program)
64                                "ssh %s imapd"))
65
66 (defvoo nnimap-inbox nil
67   "The mail box where incoming mail arrives and should be split out of.")
68
69 (defvoo nnimap-split-methods nil
70   "How mail is split.
71 Uses the same syntax as nnmail-split-methods")
72
73 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
74                         "Emacs 24.1")
75
76 (defvoo nnimap-authenticator nil
77   "How nnimap authenticate itself to the server.
78 Possible choices are nil (use default methods) or `anonymous'.")
79
80 (defvoo nnimap-expunge t
81   "If non-nil, expunge articles after deleting them.
82 This is always done if the server supports UID EXPUNGE, but it's
83 not done by default on servers that doesn't support that command.")
84
85 (defvoo nnimap-streaming t
86   "If non-nil, try to use streaming commands with IMAP servers.
87 Switching this off will make nnimap slower, but it helps with
88 some servers.")
89
90 (defvoo nnimap-connection-alist nil)
91
92 (defvoo nnimap-current-infos nil)
93
94 (defvoo nnimap-fetch-partial-articles nil
95   "If non-nil, Gnus will fetch partial articles.
96 If t, nnimap will fetch only the first part.  If a string, it
97 will fetch all parts that have types that match that string.  A
98 likely value would be \"text/\" to automatically fetch all
99 textual parts.")
100
101 (defvar nnimap-process nil)
102
103 (defvar nnimap-status-string "")
104
105 (defvar nnimap-split-download-body-default nil
106   "Internal variable with default value for `nnimap-split-download-body'.")
107
108 (defvar nnimap-keepalive-timer nil)
109 (defvar nnimap-process-buffers nil)
110
111 (defstruct nnimap
112   group process commands capabilities select-result newlinep server
113   last-command-time greeting)
114
115 (defvar nnimap-object nil)
116
117 (defvar nnimap-mark-alist
118   '((read "\\Seen" %Seen)
119     (tick "\\Flagged" %Flagged)
120     (reply "\\Answered" %Answered)
121     (expire "gnus-expire")
122     (dormant "gnus-dormant")
123     (score "gnus-score")
124     (save "gnus-save")
125     (download "gnus-download")
126     (forward "gnus-forward")))
127
128 (defun nnimap-buffer ()
129   (nnimap-find-process-buffer nntp-server-buffer))
130
131 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
132   (with-current-buffer nntp-server-buffer
133     (erase-buffer)
134     (when (nnimap-possibly-change-group group server)
135       (with-current-buffer (nnimap-buffer)
136         (erase-buffer)
137         (nnimap-wait-for-response
138          (nnimap-send-command
139           "UID FETCH %s %s"
140           (nnimap-article-ranges (gnus-compress-sequence articles))
141           (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
142                   (format
143                    (if (nnimap-ver4-p)
144                        "BODY.PEEK[HEADER.FIELDS %s]"
145                      "RFC822.HEADER.LINES %s")
146                    (append '(Subject From Date Message-Id
147                                      References In-Reply-To Xref)
148                            nnmail-extra-headers))))
149          t)
150         (nnimap-transform-headers))
151       (insert-buffer-substring
152        (nnimap-find-process-buffer (current-buffer))))
153     'headers))
154
155 (defun nnimap-transform-headers ()
156   (goto-char (point-min))
157   (let (article bytes lines size string)
158     (block nil
159       (while (not (eobp))
160         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
161           (delete-region (point) (progn (forward-line 1) (point)))
162           (when (eobp)
163             (return)))
164         (setq article (match-string 1))
165         ;; Unfold quoted {number} strings.
166         (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
167                                   (1+ (line-end-position)) t)
168           (setq size (string-to-number (match-string 1)))
169           (delete-region (+ (match-beginning 0) 2) (point))
170           (setq string (delete-region (point) (+ (point) size)))
171           (insert (format "%S" string)))
172         (setq bytes (nnimap-get-length)
173               lines nil)
174         (beginning-of-line)
175         (setq size
176               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
177                                       (line-end-position)
178                                       t)
179                    (match-string 1)))
180         (beginning-of-line)
181         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
182           (let ((structure (ignore-errors
183                              (read (current-buffer)))))
184             (while (and (consp structure)
185                         (not (stringp (car structure))))
186               (setq structure (car structure)))
187             (setq lines (nth 7 structure))))
188         (delete-region (line-beginning-position) (line-end-position))
189         (insert (format "211 %s Article retrieved." article))
190         (forward-line 1)
191         (when size
192           (insert (format "Chars: %s\n" size)))
193         (when lines
194           (insert (format "Lines: %s\n" lines)))
195         (re-search-forward "^\r$")
196         (delete-region (line-beginning-position) (line-end-position))
197         (insert ".")
198         (forward-line 1)))))
199
200 (defun nnimap-get-length ()
201   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
202        (string-to-number (match-string 1))))
203
204 (defun nnimap-article-ranges (ranges)
205   (let (result)
206     (cond
207      ((numberp ranges)
208       (number-to-string ranges))
209      ((numberp (cdr ranges))
210       (format "%d:%d" (car ranges) (cdr ranges)))
211      (t
212       (dolist (elem ranges)
213         (push
214          (if (consp elem)
215              (format "%d:%d" (car elem) (cdr elem))
216            (number-to-string elem))
217          result))
218       (mapconcat #'identity (nreverse result) ",")))))
219
220 (deffoo nnimap-open-server (server &optional defs)
221   (if (nnimap-server-opened server)
222       t
223     (unless (assq 'nnimap-address defs)
224       (setq defs (append defs (list (list 'nnimap-address server)))))
225     (nnoo-change-server 'nnimap server defs)
226     (or (nnimap-find-connection nntp-server-buffer)
227         (nnimap-open-connection nntp-server-buffer))))
228
229 (defun nnimap-make-process-buffer (buffer)
230   (with-current-buffer
231       (generate-new-buffer (format "*nnimap %s %s %s*"
232                                    nnimap-address nnimap-server-port
233                                    (gnus-buffer-exists-p buffer)))
234     (mm-disable-multibyte)
235     (buffer-disable-undo)
236     (gnus-add-buffer)
237     (set (make-local-variable 'after-change-functions) nil)
238     (set (make-local-variable 'nnimap-object)
239          (make-nnimap :server (nnoo-current-server 'nnimap)))
240     (push (list buffer (current-buffer)) nnimap-connection-alist)
241     (push (current-buffer) nnimap-process-buffers)
242     (current-buffer)))
243
244 (defun nnimap-open-shell-stream (name buffer host port)
245   (let ((process-connection-type nil))
246     (start-process name buffer shell-file-name
247                    shell-command-switch
248                    (format-spec
249                     nnimap-shell-program
250                     (format-spec-make
251                      ?s host
252                      ?p port)))))
253
254 (defun nnimap-credentials (address ports &optional inhibit-create)
255   (let (port credentials)
256     ;; Request the credentials from all ports, but only query on the
257     ;; last port if all the previous ones have failed.
258     (while (and (null credentials)
259                 (setq port (pop ports)))
260       (setq credentials
261             (auth-source-user-or-password
262              '("login" "password") address port nil
263              (if inhibit-create
264                  nil
265                (null ports)))))
266     credentials))
267
268 (defun nnimap-keepalive ()
269   (let ((now (current-time)))
270     (dolist (buffer nnimap-process-buffers)
271       (when (buffer-name buffer)
272         (with-current-buffer buffer
273           (when (and nnimap-object
274                      (nnimap-last-command-time nnimap-object)
275                      (> (time-to-seconds
276                          (time-subtract
277                           now
278                           (nnimap-last-command-time nnimap-object)))
279                         ;; More than five minutes since the last command.
280                         (* 5 60)))
281             (nnimap-send-command "NOOP")))))))
282
283 (defun nnimap-open-connection (buffer)
284   (unless nnimap-keepalive-timer
285     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
286                                               'nnimap-keepalive)))
287   (block nil
288     (with-current-buffer (nnimap-make-process-buffer buffer)
289       (let* ((coding-system-for-read 'binary)
290              (coding-system-for-write 'binary)
291              (port nil)
292              (ports
293               (cond
294                ((eq nnimap-stream 'network)
295                 (open-network-stream
296                  "*nnimap*" (current-buffer) nnimap-address
297                  (setq port
298                        (or nnimap-server-port
299                            (if (netrc-find-service-number "imap")
300                                "imap"
301                              "143"))))
302                 '("143" "imap"))
303                ((eq nnimap-stream 'shell)
304                 (nnimap-open-shell-stream
305                  "*nnimap*" (current-buffer) nnimap-address
306                  (setq port (or nnimap-server-port "imap")))
307                 '("imap"))
308                ((eq nnimap-stream 'starttls)
309                 (starttls-open-stream
310                  "*nnimap*" (current-buffer) nnimap-address
311                  (setq port (or nnimap-server-port "imap")))
312                 '("imap"))
313                ((eq nnimap-stream 'ssl)
314                 (open-tls-stream
315                  "*nnimap*" (current-buffer) nnimap-address
316                  (setq port
317                        (or nnimap-server-port
318                            (if (netrc-find-service-number "imaps")
319                                "imaps"
320                              "993"))))
321                 '("143" "993" "imap" "imaps"))))
322              connection-result login-result credentials)
323         (setf (nnimap-process nnimap-object)
324               (get-buffer-process (current-buffer)))
325         (if (not (and (nnimap-process nnimap-object)
326                       (memq (process-status (nnimap-process nnimap-object))
327                             '(open run))))
328             (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
329                              nnimap-address port nnimap-stream)
330           (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
331           (if (not (setq connection-result (nnimap-wait-for-connection)))
332               (nnheader-report 'nnimap
333                                "%s" (buffer-substring
334                                      (point) (line-end-position)))
335             ;; Store the greeting (for debugging purposes).
336             (setf (nnimap-greeting nnimap-object)
337                   (buffer-substring (line-beginning-position)
338                                     (line-end-position)))
339             ;; Store the capabilities.
340             (setf (nnimap-capabilities nnimap-object)
341                   (mapcar
342                    #'upcase
343                    (nnimap-find-parameter
344                     "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
345             (when (eq nnimap-stream 'starttls)
346               (nnimap-command "STARTTLS")
347               (starttls-negotiate (nnimap-process nnimap-object)))
348             (when nnimap-server-port
349               (push (format "%s" nnimap-server-port) ports))
350             (unless (equal connection-result "PREAUTH")
351               (if (not (setq credentials
352                              (if (eq nnimap-authenticator 'anonymous)
353                                  (list "anonymous"
354                                        (message-make-address))
355                                (or
356                                 ;; First look for the credentials based
357                                 ;; on the virtual server name.
358                                 (nnimap-credentials
359                                  (nnoo-current-server 'nnimap) ports t)
360                                 ;; Then look them up based on the
361                                 ;; physical address.
362                                 (nnimap-credentials nnimap-address ports)))))
363                   (setq nnimap-object nil)
364                 (setq login-result (nnimap-command "LOGIN %S %S"
365                                                    (car credentials)
366                                                    (cadr credentials)))
367                 (unless (car login-result)
368                   ;; If the login failed, then forget the credentials
369                   ;; that are now possibly cached.
370                   (dolist (host (list (nnoo-current-server 'nnimap)
371                                       nnimap-address))
372                     (dolist (port ports)
373                       (dolist (element '("login" "password"))
374                         (auth-source-forget-user-or-password
375                          element host port))))
376                   (delete-process (nnimap-process nnimap-object))
377                   (setq nnimap-object nil))))
378             (when nnimap-object
379               (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
380                 (nnimap-command "ENABLE QRESYNC"))
381               t)))))))
382
383 (defun nnimap-find-parameter (parameter elems)
384   (let (result)
385     (dolist (elem elems)
386       (cond
387        ((equal (car elem) parameter)
388         (setq result (cdr elem)))
389        ((and (equal (car elem) "OK")
390              (consp (cadr elem))
391              (equal (caadr elem) parameter))
392         (setq result (cdr (cadr elem))))))
393     result))
394
395 (deffoo nnimap-close-server (&optional server)
396   t)
397
398 (deffoo nnimap-request-close ()
399   t)
400
401 (deffoo nnimap-server-opened (&optional server)
402   (and (nnoo-current-server-p 'nnimap server)
403        nntp-server-buffer
404        (gnus-buffer-live-p nntp-server-buffer)
405        (nnimap-find-connection nntp-server-buffer)))
406
407 (deffoo nnimap-status-message (&optional server)
408   nnimap-status-string)
409
410 (deffoo nnimap-request-article (article &optional group server to-buffer)
411   (with-current-buffer nntp-server-buffer
412     (let ((result (nnimap-possibly-change-group group server))
413           parts structure)
414       (when (stringp article)
415         (setq article (nnimap-find-article-by-message-id group article)))
416       (when (and result
417                  article)
418         (erase-buffer)
419         (with-current-buffer (nnimap-buffer)
420           (erase-buffer)
421           (when nnimap-fetch-partial-articles
422             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
423             (goto-char (point-min))
424             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
425               (setq structure (ignore-errors
426                                 (let ((start (point)))
427                                   (forward-sexp 1)
428                                   (downcase-region start (point))
429                                   (goto-char (point))
430                                   (read (current-buffer))))
431                     parts (nnimap-find-wanted-parts structure))))
432           (when (if parts
433                     (nnimap-get-partial-article article parts structure)
434                   (nnimap-get-whole-article article))
435             (let ((buffer (current-buffer)))
436               (with-current-buffer (or to-buffer nntp-server-buffer)
437                 (erase-buffer)
438                 (insert-buffer-substring buffer)
439                 (nnheader-ms-strip-cr)
440                 (cons group article)))))))))
441
442 (defun nnimap-get-whole-article (article)
443   (let ((result
444          (nnimap-command
445           (if (nnimap-ver4-p)
446               "UID FETCH %d BODY.PEEK[]"
447             "UID FETCH %d RFC822.PEEK")
448           article)))
449     ;; Check that we really got an article.
450     (goto-char (point-min))
451     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
452       (setq result nil))
453     (when result
454       ;; Remove any data that may have arrived before the FETCH data.
455       (beginning-of-line)
456       (unless (bobp)
457         (delete-region (point-min) (point)))
458       (let ((bytes (nnimap-get-length)))
459         (delete-region (line-beginning-position)
460                        (progn (forward-line 1) (point)))
461         (goto-char (+ (point) bytes))
462         (delete-region (point) (point-max)))
463       t)))
464
465 (defun nnimap-ver4-p ()
466   (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
467
468 (defun nnimap-get-partial-article (article parts structure)
469   (let ((result
470          (nnimap-command
471           "UID FETCH %d (%s %s)"
472           article
473           (if (nnimap-ver4-p)
474               "BODY.PEEK[HEADER]"
475             "RFC822.HEADER")
476           (if (nnimap-ver4-p)
477               (mapconcat (lambda (part)
478                            (format "BODY.PEEK[%s]" part))
479                          parts " ")
480             (mapconcat (lambda (part)
481                          (format "RFC822.PEEK[%s]" part))
482                        parts " ")))))
483     (when result
484       (nnimap-convert-partial-article structure))))
485
486 (defun nnimap-convert-partial-article (structure)
487   ;; First just skip past the headers.
488   (goto-char (point-min))
489   (let ((bytes (nnimap-get-length))
490         id parts)
491     ;; Delete "FETCH" line.
492     (delete-region (line-beginning-position)
493                    (progn (forward-line 1) (point)))
494     (goto-char (+ (point) bytes))
495     ;; Collect all the body parts.
496     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
497       (setq id (match-string 1)
498             bytes (nnimap-get-length))
499       (beginning-of-line)
500       (delete-region (point) (progn (forward-line 1) (point)))
501       (push (list id (buffer-substring (point) (+ (point) bytes)))
502             parts)
503       (delete-region (point) (+ (point) bytes)))
504     ;; Delete trailing junk.
505     (delete-region (point) (point-max))
506     ;; Now insert all the parts again where they fit in the structure.
507     (nnimap-insert-partial-structure structure parts)
508     t))
509
510 (defun nnimap-insert-partial-structure (structure parts &optional subp)
511   (let (type boundary)
512     (let ((bstruc structure))
513       (while (consp (car bstruc))
514         (pop bstruc))
515       (setq type (car bstruc))
516       (setq bstruc (car (cdr bstruc)))
517       (when (and (stringp (car bstruc))
518                  (string= (downcase (car bstruc)) "boundary"))
519         (setq boundary (cadr bstruc))))
520     (when subp
521       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
522                       (downcase type) boundary)))
523     (while (not (stringp (car structure)))
524       (insert "\n--" boundary "\n")
525       (if (consp (caar structure))
526           (nnimap-insert-partial-structure (pop structure) parts t)
527         (let ((bit (pop structure)))
528           (insert (format  "Content-type: %s/%s"
529                            (downcase (nth 0 bit))
530                            (downcase (nth 1 bit))))
531           (if (member "CHARSET" (nth 2 bit))
532               (insert (format
533                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
534             (insert "\n"))
535           (insert (format "Content-transfer-encoding: %s\n"
536                           (nth 5 bit)))
537           (insert "\n")
538           (when (assoc (nth 9 bit) parts)
539             (insert (cadr (assoc (nth 9 bit) parts)))))))
540     (insert "\n--" boundary "--\n")))
541
542 (defun nnimap-find-wanted-parts (structure)
543   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
544
545 (defun nnimap-find-wanted-parts-1 (structure prefix)
546   (let ((num 1)
547         parts)
548     (while (consp (car structure))
549       (let ((sub (pop structure)))
550         (if (consp (car sub))
551             (push (nnimap-find-wanted-parts-1
552                    sub (if (string= prefix "")
553                            (number-to-string num)
554                          (format "%s.%s" prefix num)))
555                   parts)
556           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
557                 (id (if (string= prefix "")
558                         (number-to-string num)
559                       (format "%s.%s" prefix num))))
560             (setcar (nthcdr 9 sub) id)
561             (when (if (eq nnimap-fetch-partial-articles t)
562                       (equal id "1")
563                     (string-match nnimap-fetch-partial-articles type))
564               (push id parts))))
565         (incf num)))
566     (nreverse parts)))
567
568 (deffoo nnimap-request-group (group &optional server dont-check info)
569   (let ((result (nnimap-possibly-change-group group server))
570         articles active marks high low)
571     (with-current-buffer nntp-server-buffer
572       (when result
573         (if (and dont-check
574                  (setq active (nth 2 (assoc group nnimap-current-infos))))
575             (insert (format "211 %d %d %d %S\n"
576                             (- (cdr active) (car active))
577                             (car active)
578                             (cdr active)
579                             group))
580           (with-current-buffer (nnimap-buffer)
581             (erase-buffer)
582             (let ((group-sequence
583                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
584                   (flag-sequence
585                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
586               (nnimap-wait-for-response flag-sequence)
587               (setq marks
588                     (nnimap-flags-to-marks
589                      (nnimap-parse-flags
590                       (list (list group-sequence flag-sequence 1 group)))))
591               (when info
592                 (nnimap-update-infos marks (list info)))
593               (goto-char (point-max))
594               (let ((uidnext (nth 5 (car marks))))
595                 (setq high (if uidnext
596                                (1- uidnext)
597                              (nth 3 (car marks)))
598                       low (or (nth 4 (car marks)) uidnext)))))
599           (erase-buffer)
600           (insert
601            (format
602             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
603         t))))
604
605 (deffoo nnimap-request-create-group (group &optional server args)
606   (when (nnimap-possibly-change-group nil server)
607     (with-current-buffer (nnimap-buffer)
608       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
609
610 (deffoo nnimap-request-delete-group (group &optional force server)
611   (when (nnimap-possibly-change-group nil server)
612     (with-current-buffer (nnimap-buffer)
613       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
614
615 (deffoo nnimap-request-expunge-group (group &optional server)
616   (when (nnimap-possibly-change-group group server)
617     (with-current-buffer (nnimap-buffer)
618       (car (nnimap-command "EXPUNGE")))))
619
620 (defun nnimap-get-flags (spec)
621   (let ((articles nil)
622         elems)
623     (with-current-buffer (nnimap-buffer)
624       (erase-buffer)
625       (nnimap-wait-for-response (nnimap-send-command
626                                  "UID FETCH %s FLAGS" spec))
627       (goto-char (point-min))
628       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
629         (setq elems (nnimap-parse-line (match-string 1)))
630         (push (cons (string-to-number (cadr (member "UID" elems)))
631                     (cadr (member "FLAGS" elems)))
632               articles)))
633     (nreverse articles)))
634
635 (deffoo nnimap-close-group (group &optional server)
636   t)
637
638 (deffoo nnimap-request-move-article (article group server accept-form
639                                              &optional last internal-move-group)
640   (with-temp-buffer
641     (when (nnimap-request-article article group server (current-buffer))
642       ;; If the move is internal (on the same server), just do it the easy
643       ;; way.
644       (let ((message-id (message-field-value "message-id")))
645         (if internal-move-group
646             (let ((result
647                    (with-current-buffer (nnimap-buffer)
648                      (nnimap-command "UID COPY %d %S"
649                                      article
650                                      (utf7-encode internal-move-group t)))))
651               (when (car result)
652                 (nnimap-delete-article article)
653                 (cons internal-move-group
654                       (nnimap-find-article-by-message-id
655                        internal-move-group message-id))))
656           ;; Move the article to a different method.
657           (let ((result (eval accept-form)))
658             (when result
659               (nnimap-delete-article article)
660               result)))))))
661
662 (deffoo nnimap-request-expire-articles (articles group &optional server force)
663   (cond
664    ((null articles)
665     nil)
666    ((not (nnimap-possibly-change-group group server))
667     articles)
668    ((and force
669          (eq nnmail-expiry-target 'delete))
670     (unless (nnimap-delete-article (gnus-compress-sequence articles))
671       (message "Article marked for deletion, but not expunged."))
672     nil)
673    (t
674     (let ((deletable-articles
675            (if (or force
676                    (eq nnmail-expiry-wait 'immediate))
677                articles
678              (gnus-sorted-intersection
679               articles
680               (nnimap-find-expired-articles group)))))
681       (if (null deletable-articles)
682           articles
683         (if (eq nnmail-expiry-target 'delete)
684             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
685           (setq deletable-articles
686                 (nnimap-process-expiry-targets
687                  deletable-articles group server)))
688         ;; Return the articles we didn't delete.
689         (gnus-sorted-complement articles deletable-articles))))))
690
691 (defun nnimap-process-expiry-targets (articles group server)
692   (let ((deleted-articles nil))
693     (dolist (article articles)
694       (let ((target nnmail-expiry-target))
695         (with-temp-buffer
696           (when (nnimap-request-article article group server (current-buffer))
697             (message "Expiring article %s:%d" group article)
698             (when (functionp target)
699               (setq target (funcall target group)))
700             (when (and target
701                        (not (eq target 'delete)))
702               (if (or (gnus-request-group target t)
703                       (gnus-request-create-group target))
704                   (nnmail-expiry-target-group target group)
705                 (setq target nil)))
706             (when target
707               (push article deleted-articles))))))
708     ;; Change back to the current group again.
709     (nnimap-possibly-change-group group server)
710     (setq deleted-articles (nreverse deleted-articles))
711     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
712     deleted-articles))
713
714 (defun nnimap-find-expired-articles (group)
715   (let ((cutoff (nnmail-expired-article-p group nil nil)))
716     (with-current-buffer (nnimap-buffer)
717       (let ((result
718              (nnimap-command
719               "UID SEARCH SENTBEFORE %s"
720               (format-time-string
721                (format "%%d-%s-%%Y"
722                        (upcase
723                         (car (rassoc (nth 4 (decode-time cutoff))
724                                      parse-time-months))))
725                cutoff))))
726         (and (car result)
727              (delete 0 (mapcar #'string-to-number
728                                (cdr (assoc "SEARCH" (cdr result))))))))))
729
730
731 (defun nnimap-find-article-by-message-id (group message-id)
732   (with-current-buffer (nnimap-buffer)
733     (erase-buffer)
734     (setf (nnimap-group nnimap-object) nil)
735     (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
736     (let ((sequence
737            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
738           article result)
739       (setq result (nnimap-wait-for-response sequence))
740       (when (car result)
741         ;; Select the last instance of the message in the group.
742         (and (setq article
743                    (car (last (assoc "SEARCH" (cdr result)))))
744              (string-to-number article))))))
745
746 (defun nnimap-delete-article (articles)
747   (with-current-buffer (nnimap-buffer)
748     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
749                     (nnimap-article-ranges articles))
750     (cond
751      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
752       (nnimap-command "UID EXPUNGE %s"
753                       (nnimap-article-ranges articles))
754       t)
755      (nnimap-expunge
756       (nnimap-command "EXPUNGE")
757       t)
758      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
759                                 "server doesn't support UIDPLUS, so we won't "
760                                 "delete this article now"))))))
761
762 (deffoo nnimap-request-scan (&optional group server)
763   (when (and (nnimap-possibly-change-group nil server)
764              nnimap-inbox
765              nnimap-split-methods)
766     (message "nnimap %s splitting mail..." server)
767     (nnimap-split-incoming-mail)))
768
769 (defun nnimap-marks-to-flags (marks)
770   (let (flags flag)
771     (dolist (mark marks)
772       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
773         (push flag flags)))
774     flags))
775
776 (deffoo nnimap-request-set-mark (group actions &optional server)
777   (when (nnimap-possibly-change-group group server)
778     (let (sequence)
779       (with-current-buffer (nnimap-buffer)
780         (erase-buffer)
781         ;; Just send all the STORE commands without waiting for
782         ;; response.  If they're successful, they're successful.
783         (dolist (action actions)
784           (destructuring-bind (range action marks) action
785             (let ((flags (nnimap-marks-to-flags marks)))
786               (when flags
787                 (setq sequence (nnimap-send-command
788                                 "UID STORE %s %sFLAGS.SILENT (%s)"
789                                 (nnimap-article-ranges range)
790                                 (if (eq action 'del)
791                                     "-"
792                                   "+")
793                                 (mapconcat #'identity flags " ")))))))
794         ;; Wait for the last command to complete to avoid later
795         ;; syncronisation problems with the stream.
796         (when sequence
797           (nnimap-wait-for-response sequence))))))
798
799 (deffoo nnimap-request-accept-article (group &optional server last)
800   (when (nnimap-possibly-change-group nil server)
801     (nnmail-check-syntax)
802     (let ((message-id (message-field-value "message-id"))
803           sequence message)
804       (nnimap-add-cr)
805       (setq message (buffer-string))
806       (with-current-buffer (nnimap-buffer)
807         (setq sequence (nnimap-send-command
808                         "APPEND %S {%d}" (utf7-encode group t)
809                         (length message)))
810         (process-send-string (get-buffer-process (current-buffer)) message)
811         (process-send-string (get-buffer-process (current-buffer))
812                              (if (nnimap-newlinep nnimap-object)
813                                  "\n"
814                                "\r\n"))
815         (let ((result (nnimap-get-response sequence)))
816           (if (not (car result))
817               (progn
818                 (message "%s" (nnheader-get-report-string 'nnimap))
819                 nil)
820             (cons group
821                   (nnimap-find-article-by-message-id group message-id))))))))
822
823 (defun nnimap-add-cr ()
824   (goto-char (point-min))
825   (while (re-search-forward "\r?\n" nil t)
826     (replace-match "\r\n" t t)))
827
828 (defun nnimap-get-groups ()
829   (let ((result (nnimap-command "LIST \"\" \"*\""))
830         groups)
831     (when (car result)
832       (dolist (line (cdr result))
833         (when (and (equal (car line) "LIST")
834                    (not (and (caadr line)
835                              (string-match "noselect" (caadr line)))))
836           (push (car (last line)) groups)))
837       (nreverse groups))))
838
839 (deffoo nnimap-request-list (&optional server)
840   (nnimap-possibly-change-group nil server)
841   (with-current-buffer nntp-server-buffer
842     (erase-buffer)
843     (let ((groups
844            (with-current-buffer (nnimap-buffer)
845              (nnimap-get-groups)))
846           sequences responses)
847       (when groups
848         (with-current-buffer (nnimap-buffer)
849           (setf (nnimap-group nnimap-object) nil)
850           (dolist (group groups)
851             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
852                         group)
853                   sequences))
854           (nnimap-wait-for-response (caar sequences))
855           (setq responses
856                 (nnimap-get-responses (mapcar #'car sequences))))
857         (dolist (response responses)
858           (let* ((sequence (car response))
859                  (response (cadr response))
860                  (group (cadr (assoc sequence sequences))))
861             (when (and group
862                        (equal (caar response) "OK"))
863               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
864                     highest exists)
865                 (dolist (elem response)
866                   (when (equal (cadr elem) "EXISTS")
867                     (setq exists (string-to-number (car elem)))))
868                 (when uidnext
869                   (setq highest (1- (string-to-number (car uidnext)))))
870                 (cond
871                  ((null highest)
872                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
873                  ((zerop exists)
874                   ;; Empty group.
875                   (insert (format "%S %d %d y\n"
876                                   (utf7-decode group t) highest (1+ highest))))
877                  (t
878                   ;; Return the widest possible range.
879                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
880                                   (or highest exists)))))))))
881         t))))
882
883 (deffoo nnimap-retrieve-group-data-early (server infos)
884   (when (nnimap-possibly-change-group nil server)
885     (with-current-buffer (nnimap-buffer)
886       ;; QRESYNC handling isn't implemented.
887       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
888             marks groups sequences)
889         ;; Go through the infos and gather the data needed to know
890         ;; what and how to request the data.
891         (dolist (info infos)
892           (setq marks (gnus-info-marks info))
893           (push (list (gnus-group-real-name (gnus-info-group info))
894                       (cdr (assq 'active marks))
895                       (cdr (assq 'uid marks)))
896                 groups))
897         ;; Then request the data.
898         (erase-buffer)
899         (setf (nnimap-group nnimap-object) nil)
900         (dolist (elem groups)
901           (if (and qresyncp
902                    (nth 2 elem))
903               (push
904                (list 'qresync
905                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
906                                           (car elem)
907                                           (car (nth 2 elem))
908                                           (cdr (nth 2 elem)))
909                      nil
910                      (car elem))
911                sequences)
912             (let ((start
913                    (if (nth 1 elem)
914                        ;; Fetch the last 100 flags.
915                        (max 1 (- (cdr (nth 1 elem)) 100))
916                      1)))
917               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
918                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
919                           start
920                           (car elem))
921                     sequences)))
922           ;; Some servers apparently can't have many outstanding
923           ;; commands, so throttle them.
924           (when (and (not nnimap-streaming)
925                      (car sequences))
926             (nnimap-wait-for-response (caar sequences))))
927         sequences))))
928
929 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
930   (when (and sequences
931              (nnimap-possibly-change-group nil server))
932     (with-current-buffer (nnimap-buffer)
933       ;; Wait for the final data to trickle in.
934       (when (nnimap-wait-for-response (cadar sequences))
935         ;; Now we should have all the data we need, no matter whether
936         ;; we're QRESYNCING, fetching all the flags from scratch, or
937         ;; just fetching the last 100 flags per group.
938         (nnimap-update-infos (nnimap-flags-to-marks
939                               (nnimap-parse-flags
940                                (nreverse sequences)))
941                              infos)
942         ;; Finally, just return something resembling an active file in
943         ;; the nntp buffer, so that the agent can save the info, too.
944         (with-current-buffer nntp-server-buffer
945           (erase-buffer)
946           (dolist (info infos)
947             (let* ((group (gnus-info-group info))
948                    (active (gnus-active group)))
949               (when active
950                 (insert (format "%S %d %d y\n"
951                                 (gnus-group-real-name group)
952                                 (cdr active)
953                                 (car active)))))))))))
954
955 (defun nnimap-update-infos (flags infos)
956   (dolist (info infos)
957     (let ((group (gnus-group-real-name (gnus-info-group info))))
958       (nnimap-update-info info (cdr (assoc group flags))))))
959
960 (defun nnimap-update-info (info marks)
961   (when marks
962     (destructuring-bind (existing flags high low uidnext start-article
963                                   permanent-flags) marks
964       (let ((group (gnus-info-group info))
965             (completep (and start-article
966                             (= start-article 1))))
967         (when uidnext
968           (setq high (1- uidnext)))
969         ;; First set the active ranges based on high/low.
970         (if (or completep
971                 (not (gnus-active group)))
972             (gnus-set-active group
973                              (cond
974                               ((and low high)
975                                (cons low high))
976                               (uidnext
977                                ;; No articles in this group.
978                                (cons uidnext (1- uidnext)))
979                               (start-article
980                                (cons start-article (1- start-article)))
981                               (t
982                                ;; No articles and no uidnext.
983                                nil)))
984           (gnus-set-active
985            group
986            (cons (car (gnus-active group))
987                  (or high (1- uidnext)))))
988         (when (and (not high)
989                    uidnext)
990           (setq high (1- uidnext)))
991         ;; Then update the list of read articles.
992         (let* ((unread
993                 (gnus-compress-sequence
994                  (gnus-set-difference
995                   (gnus-set-difference
996                    existing
997                    (cdr (assoc '%Seen flags)))
998                   (cdr (assoc '%Flagged flags)))))
999                (read (gnus-range-difference
1000                       (cons start-article high) unread)))
1001           (when (> start-article 1)
1002             (setq read
1003                   (gnus-range-nconcat
1004                    (if (> start-article 1)
1005                        (gnus-sorted-range-intersection
1006                         (cons 1 (1- start-article))
1007                         (gnus-info-read info))
1008                      (gnus-info-read info))
1009                    read)))
1010           (gnus-info-set-read info read)
1011           ;; Update the marks.
1012           (setq marks (gnus-info-marks info))
1013           ;; Note the active level for the next run-through.
1014           (let ((active (assq 'active marks)))
1015             (if active
1016                 (setcdr active (gnus-active group))
1017               (push (cons 'active (gnus-active group)) marks)))
1018           (dolist (type (cdr nnimap-mark-alist))
1019             (let ((old-marks (assoc (car type) marks))
1020                   (new-marks
1021                    (gnus-compress-sequence
1022                     (cdr (or (assoc (caddr type) flags)     ; %Flagged
1023                              (assoc (intern (cadr type) obarray) flags)
1024                              (assoc (cadr type) flags)))))) ; "\Flagged"
1025               (setq marks (delq old-marks marks))
1026               (pop old-marks)
1027               (when (and old-marks
1028                          (> start-article 1))
1029                 (setq old-marks (gnus-range-difference
1030                                  old-marks
1031                                  (cons start-article high)))
1032                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1033               (when new-marks
1034                 (push (cons (car type) new-marks) marks)))
1035             (gnus-info-set-marks info marks t)
1036             (nnimap-store-info info (gnus-active group))))))))
1037
1038 (defun nnimap-store-info (info active)
1039   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1040          (entry (assoc group nnimap-current-infos)))
1041     (if entry
1042         (setcdr entry (list info active))
1043       (push (list group info active) nnimap-current-infos))))
1044
1045 (defun nnimap-flags-to-marks (groups)
1046   (let (data group totalp uidnext articles start-article mark permanent-flags)
1047     (dolist (elem groups)
1048       (setq group (car elem)
1049             uidnext (nth 1 elem)
1050             start-article (nth 2 elem)
1051             permanent-flags (nth 3 elem)
1052             articles (nthcdr 4 elem))
1053       (let ((high (caar articles))
1054             marks low existing)
1055         (dolist (article articles)
1056           (setq low (car article))
1057           (push (car article) existing)
1058           (dolist (flag (cdr article))
1059             (setq mark (assoc flag marks))
1060             (if (not mark)
1061                 (push (list flag (car article)) marks)
1062               (setcdr mark (cons (car article) (cdr mark))))))
1063         (push (list group existing marks high low uidnext start-article
1064                     permanent-flags)
1065               data)))
1066     data))
1067
1068 (defun nnimap-parse-flags (sequences)
1069   (goto-char (point-min))
1070   ;; Change \Delete etc to %Delete, so that the reader can read it.
1071   (subst-char-in-region (point-min) (point-max)
1072                         ?\\ ?% t)
1073   (let (start end articles groups uidnext elems permanent-flags)
1074     (dolist (elem sequences)
1075       (destructuring-bind (group-sequence flag-sequence totalp group) elem
1076         (setq start (point))
1077         ;; The EXAMINE was successful.
1078         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1079                    (progn
1080                      (forward-line 1)
1081                      (setq end (point))
1082                      (goto-char start)
1083                      (setq permanent-flags
1084                            (and (search-forward "PERMANENTFLAGS "
1085                                                  (or end (point-min)) t)
1086                                 (read (current-buffer))))
1087                      (goto-char start)
1088                      (setq uidnext
1089                            (and (search-forward "UIDNEXT "
1090                                                  (or end (point-min)) t)
1091                                 (read (current-buffer))))
1092                      (goto-char end)
1093                      (forward-line -1))
1094                    ;; The UID FETCH FLAGS was successful.
1095                    (search-forward (format "\n%d OK " flag-sequence) nil t))
1096           (setq start (point))
1097           (goto-char end)
1098           (while (search-forward " FETCH " start t)
1099             (setq elems (read (current-buffer)))
1100             (push (cons (cadr (memq 'UID elems))
1101                         (cadr (memq 'FLAGS elems)))
1102                   articles))
1103           (push (nconc (list group uidnext totalp permanent-flags) articles)
1104                 groups)
1105           (setq articles nil))))
1106     groups))
1107
1108 (defun nnimap-find-process-buffer (buffer)
1109   (cadr (assoc buffer nnimap-connection-alist)))
1110
1111 (deffoo nnimap-request-post (&optional server)
1112   (setq nnimap-status-string "Read-only server")
1113   nil)
1114
1115 (defun nnimap-possibly-change-group (group server)
1116   (let ((open-result t))
1117     (when (and server
1118                (not (nnimap-server-opened server)))
1119       (setq open-result (nnimap-open-server server)))
1120     (cond
1121      ((not open-result)
1122       nil)
1123      ((not group)
1124       t)
1125      (t
1126       (with-current-buffer (nnimap-buffer)
1127         (if (equal group (nnimap-group nnimap-object))
1128             t
1129           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1130             (when (car result)
1131               (setf (nnimap-group nnimap-object) group
1132                     (nnimap-select-result nnimap-object) result)
1133               result))))))))
1134
1135 (defun nnimap-find-connection (buffer)
1136   "Find the connection delivering to BUFFER."
1137   (let ((entry (assoc buffer nnimap-connection-alist)))
1138     (when entry
1139       (if (and (buffer-name (cadr entry))
1140                (get-buffer-process (cadr entry))
1141                (memq (process-status (get-buffer-process (cadr entry)))
1142                      '(open run)))
1143           (get-buffer-process (cadr entry))
1144         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1145         nil))))
1146
1147 (defvar nnimap-sequence 0)
1148
1149 (defun nnimap-send-command (&rest args)
1150   (process-send-string
1151    (get-buffer-process (current-buffer))
1152    (nnimap-log-command
1153     (format "%d %s%s\n"
1154             (incf nnimap-sequence)
1155             (apply #'format args)
1156             (if (nnimap-newlinep nnimap-object)
1157                 ""
1158               "\r"))))
1159   nnimap-sequence)
1160
1161 (defun nnimap-log-command (command)
1162   (with-current-buffer (get-buffer-create "*imap log*")
1163     (goto-char (point-max))
1164     (insert (format-time-string "%H:%M:%S") " " command))
1165   command)
1166
1167 (defun nnimap-command (&rest args)
1168   (erase-buffer)
1169   (setf (nnimap-last-command-time nnimap-object) (current-time))
1170   (let* ((sequence (apply #'nnimap-send-command args))
1171          (response (nnimap-get-response sequence)))
1172     (if (equal (caar response) "OK")
1173         (cons t response)
1174       (nnheader-report 'nnimap "%s"
1175                        (mapconcat (lambda (a)
1176                                     (format "%s" a))
1177                                   (car response) " "))
1178       nil)))
1179
1180 (defun nnimap-get-response (sequence)
1181   (nnimap-wait-for-response sequence)
1182   (nnimap-parse-response))
1183
1184 (defun nnimap-wait-for-connection ()
1185   (let ((process (get-buffer-process (current-buffer))))
1186     (goto-char (point-min))
1187     (while (and (memq (process-status process)
1188                       '(open run))
1189                 (not (re-search-forward "^\\* .*\n" nil t)))
1190       (nnheader-accept-process-output process)
1191       (goto-char (point-min)))
1192     (forward-line -1)
1193     (and (looking-at "\\* \\([A-Z0-9]+\\)")
1194          (match-string 1))))
1195
1196 (defun nnimap-wait-for-response (sequence &optional messagep)
1197   (let ((process (get-buffer-process (current-buffer)))
1198         openp)
1199     (goto-char (point-max))
1200     (while (and (setq openp (memq (process-status process)
1201                                   '(open run)))
1202                 (not (re-search-backward
1203                       (format "^%d .*\n" sequence)
1204                       (if nnimap-streaming
1205                           (max (point-min) (- (point) 500))
1206                         (point-min))
1207                       t)))
1208       (when messagep
1209         (message "Read %dKB" (/ (buffer-size) 1000)))
1210       (nnheader-accept-process-output process)
1211       (goto-char (point-max)))
1212     openp))
1213
1214 (defun nnimap-parse-response ()
1215   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1216         result)
1217     (dolist (line lines)
1218       (push (cdr (nnimap-parse-line line)) result))
1219     ;; Return the OK/error code first, and then all the "continuation
1220     ;; lines" afterwards.
1221     (cons (pop result)
1222           (nreverse result))))
1223
1224 ;; Parse an IMAP response line lightly.  They look like
1225 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1226 ;; the lines into a list of strings and lists of string.
1227 (defun nnimap-parse-line (line)
1228   (let (char result)
1229     (with-temp-buffer
1230       (insert line)
1231       (goto-char (point-min))
1232       (while (not (eobp))
1233         (if (eql (setq char (following-char)) ? )
1234             (forward-char 1)
1235           (push
1236            (cond
1237             ((eql char ?\[)
1238              (split-string (buffer-substring
1239                             (1+ (point))
1240                             (1- (search-forward "]" (line-end-position) 'move)))))
1241             ((eql char ?\()
1242              (split-string (buffer-substring
1243                             (1+ (point))
1244                             (1- (search-forward ")" (line-end-position) 'move)))))
1245             ((eql char ?\")
1246              (forward-char 1)
1247              (buffer-substring
1248               (point)
1249               (1- (or (search-forward "\"" (line-end-position) 'move)
1250                       (point)))))
1251             (t
1252              (buffer-substring (point) (if (search-forward " " nil t)
1253                                            (1- (point))
1254                                          (goto-char (point-max))))))
1255            result)))
1256       (nreverse result))))
1257
1258 (defun nnimap-last-response-string ()
1259   (save-excursion
1260     (forward-line 1)
1261     (let ((end (point)))
1262       (forward-line -1)
1263       (when (not (bobp))
1264         (forward-line -1)
1265         (while (and (not (bobp))
1266                     (eql (following-char) ?*))
1267           (forward-line -1))
1268         (unless (eql (following-char) ?*)
1269           (forward-line 1)))
1270       (buffer-substring (point) end))))
1271
1272 (defun nnimap-get-responses (sequences)
1273   (let (responses)
1274     (dolist (sequence sequences)
1275       (goto-char (point-min))
1276       (when (re-search-forward (format "^%d " sequence) nil t)
1277         (push (list sequence (nnimap-parse-response))
1278               responses)))
1279     responses))
1280
1281 (defvar nnimap-incoming-split-list nil)
1282
1283 (defun nnimap-fetch-inbox (articles)
1284   (erase-buffer)
1285   (nnimap-wait-for-response
1286    (nnimap-send-command
1287     "UID FETCH %s %s"
1288     (nnimap-article-ranges articles)
1289     (format "(UID %s%s)"
1290             (format
1291              (if (nnimap-ver4-p)
1292                  "BODY.PEEK[HEADER] BODY.PEEK"
1293                "RFC822.PEEK"))
1294             (if nnimap-split-download-body-default
1295                 "[]"
1296               "[1]")))
1297    t))
1298
1299 (defun nnimap-split-incoming-mail ()
1300   (with-current-buffer (nnimap-buffer)
1301     (let ((nnimap-incoming-split-list nil)
1302           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1303                                     nnmail-split-methods
1304                                   nnimap-split-methods))
1305           (nnmail-inhibit-default-split-group t)
1306           (groups (nnimap-get-groups))
1307           new-articles)
1308       (erase-buffer)
1309       (nnimap-command "SELECT %S" nnimap-inbox)
1310       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1311       (when new-articles
1312         (nnimap-fetch-inbox new-articles)
1313         (nnimap-transform-split-mail)
1314         (nnheader-ms-strip-cr)
1315         (nnmail-cache-open)
1316         (nnmail-split-incoming (current-buffer)
1317                                #'nnimap-save-mail-spec
1318                                nil nil
1319                                #'nnimap-dummy-active-number
1320                                #'nnimap-save-mail-spec)
1321         (when nnimap-incoming-split-list
1322           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1323                 sequences junk-articles)
1324             ;; Create any groups that doesn't already exist on the
1325             ;; server first.
1326             (dolist (spec specs)
1327               (when (and (not (member (car spec) groups))
1328                          (not (eq (car spec) 'junk)))
1329                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1330             ;; Then copy over all the messages.
1331             (erase-buffer)
1332             (dolist (spec specs)
1333               (let ((group (car spec))
1334                     (ranges (cdr spec)))
1335                 (if (eq group 'junk)
1336                     (setq junk-articles ranges)
1337                   (push (list (nnimap-send-command
1338                                "UID COPY %s %S"
1339                                (nnimap-article-ranges ranges)
1340                                (utf7-encode group t))
1341                               ranges)
1342                         sequences))))
1343             ;; Wait for the last COPY response...
1344             (when sequences
1345               (nnimap-wait-for-response (caar sequences))
1346               ;; And then mark the successful copy actions as deleted,
1347               ;; and possibly expunge them.
1348               (nnimap-mark-and-expunge-incoming
1349                (nnimap-parse-copied-articles sequences)))
1350             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1351
1352 (defun nnimap-mark-and-expunge-incoming (range)
1353   (when range
1354     (setq range (nnimap-article-ranges range))
1355     (erase-buffer)
1356     (let ((sequence
1357            (nnimap-send-command
1358             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1359       (cond
1360        ;; If the server supports it, we now delete the message we have
1361        ;; just copied over.
1362        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1363         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1364        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1365        ;; user has configured it.
1366        (nnimap-expunge
1367         (setq sequence (nnimap-send-command "EXPUNGE"))))
1368       (nnimap-wait-for-response sequence))))
1369
1370 (defun nnimap-parse-copied-articles (sequences)
1371   (let (sequence copied range)
1372     (goto-char (point-min))
1373     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1374       (setq sequence (string-to-number (match-string 1)))
1375       (when (setq range (cadr (assq sequence sequences)))
1376         (push (gnus-uncompress-range range) copied)))
1377     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1378
1379 (defun nnimap-new-articles (flags)
1380   (let (new)
1381     (dolist (elem flags)
1382       (when (or (null (cdr elem))
1383                 (and (not (memq '%Deleted (cdr elem)))
1384                      (not (memq '%Seen (cdr elem)))))
1385         (push (car elem) new)))
1386     (gnus-compress-sequence (nreverse new))))
1387
1388 (defun nnimap-make-split-specs (list)
1389   (let ((specs nil)
1390         entry)
1391     (dolist (elem list)
1392       (destructuring-bind (article spec) elem
1393         (dolist (group (delete nil (mapcar #'car spec)))
1394           (unless (setq entry (assoc group specs))
1395             (push (setq entry (list group)) specs))
1396           (setcdr entry (cons article (cdr entry))))))
1397     (dolist (entry specs)
1398       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1399     specs))
1400
1401 (defun nnimap-transform-split-mail ()
1402   (goto-char (point-min))
1403   (let (article bytes)
1404     (block nil
1405       (while (not (eobp))
1406         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1407           (delete-region (point) (progn (forward-line 1) (point)))
1408           (when (eobp)
1409             (return)))
1410         (setq article (match-string 1)
1411               bytes (nnimap-get-length))
1412         (delete-region (line-beginning-position) (line-end-position))
1413         ;; Insert MMDF separator, and a way to remember what this
1414         ;; article UID is.
1415         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1416         (forward-char (1+ bytes))
1417         (setq bytes (nnimap-get-length))
1418         (delete-region (line-beginning-position) (line-end-position))
1419         (forward-char (1+ bytes))
1420         (delete-region (line-beginning-position) (line-end-position))))))
1421
1422 (defun nnimap-dummy-active-number (group &optional server)
1423   1)
1424
1425 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1426   (let (article)
1427     (goto-char (point-min))
1428     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1429         (error "Invalid nnimap mail")
1430       (setq article (string-to-number (match-string 1))))
1431     (push (list article
1432                 (if (eq group-art 'junk)
1433                     (list (cons 'junk 1))
1434                   group-art))
1435           nnimap-incoming-split-list)))
1436
1437 (provide 'nnimap)
1438
1439 ;;; nnimap.el ends here