8aad3eae5fbbd15f47446a9ae6185aa0b814a922
[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 (and result
741                  (car (setq result (nnimap-parse-response))))
742         ;; Select the last instance of the message in the group.
743         (and (setq article
744                    (car (last (assoc "SEARCH" (cdr result)))))
745              (string-to-number article))))))
746
747 (defun nnimap-delete-article (articles)
748   (with-current-buffer (nnimap-buffer)
749     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
750                     (nnimap-article-ranges articles))
751     (cond
752      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
753       (nnimap-command "UID EXPUNGE %s"
754                       (nnimap-article-ranges articles))
755       t)
756      (nnimap-expunge
757       (nnimap-command "EXPUNGE")
758       t)
759      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
760                                 "server doesn't support UIDPLUS, so we won't "
761                                 "delete this article now"))))))
762
763 (deffoo nnimap-request-scan (&optional group server)
764   (when (and (nnimap-possibly-change-group nil server)
765              nnimap-inbox
766              nnimap-split-methods)
767     (message "nnimap %s splitting mail..." server)
768     (nnimap-split-incoming-mail)))
769
770 (defun nnimap-marks-to-flags (marks)
771   (let (flags flag)
772     (dolist (mark marks)
773       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
774         (push flag flags)))
775     flags))
776
777 (deffoo nnimap-request-set-mark (group actions &optional server)
778   (when (nnimap-possibly-change-group group server)
779     (let (sequence)
780       (with-current-buffer (nnimap-buffer)
781         (erase-buffer)
782         ;; Just send all the STORE commands without waiting for
783         ;; response.  If they're successful, they're successful.
784         (dolist (action actions)
785           (destructuring-bind (range action marks) action
786             (let ((flags (nnimap-marks-to-flags marks)))
787               (when flags
788                 (setq sequence (nnimap-send-command
789                                 "UID STORE %s %sFLAGS.SILENT (%s)"
790                                 (nnimap-article-ranges range)
791                                 (if (eq action 'del)
792                                     "-"
793                                   "+")
794                                 (mapconcat #'identity flags " ")))))))
795         ;; Wait for the last command to complete to avoid later
796         ;; syncronisation problems with the stream.
797         (when sequence
798           (nnimap-wait-for-response sequence))))))
799
800 (deffoo nnimap-request-accept-article (group &optional server last)
801   (when (nnimap-possibly-change-group nil server)
802     (nnmail-check-syntax)
803     (let ((message-id (message-field-value "message-id"))
804           sequence message)
805       (nnimap-add-cr)
806       (setq message (buffer-string))
807       (with-current-buffer (nnimap-buffer)
808         (setq sequence (nnimap-send-command
809                         "APPEND %S {%d}" (utf7-encode group t)
810                         (length message)))
811         (process-send-string (get-buffer-process (current-buffer)) message)
812         (process-send-string (get-buffer-process (current-buffer))
813                              (if (nnimap-newlinep nnimap-object)
814                                  "\n"
815                                "\r\n"))
816         (let ((result (nnimap-get-response sequence)))
817           (if (not (car result))
818               (progn
819                 (message "%s" (nnheader-get-report-string 'nnimap))
820                 nil)
821             (cons group
822                   (nnimap-find-article-by-message-id group message-id))))))))
823
824 (defun nnimap-add-cr ()
825   (goto-char (point-min))
826   (while (re-search-forward "\r?\n" nil t)
827     (replace-match "\r\n" t t)))
828
829 (defun nnimap-get-groups ()
830   (let ((result (nnimap-command "LIST \"\" \"*\""))
831         groups)
832     (when (car result)
833       (dolist (line (cdr result))
834         (when (and (equal (car line) "LIST")
835                    (not (and (caadr line)
836                              (string-match "noselect" (caadr line)))))
837           (push (car (last line)) groups)))
838       (nreverse groups))))
839
840 (deffoo nnimap-request-list (&optional server)
841   (nnimap-possibly-change-group nil server)
842   (with-current-buffer nntp-server-buffer
843     (erase-buffer)
844     (let ((groups
845            (with-current-buffer (nnimap-buffer)
846              (nnimap-get-groups)))
847           sequences responses)
848       (when groups
849         (with-current-buffer (nnimap-buffer)
850           (setf (nnimap-group nnimap-object) nil)
851           (dolist (group groups)
852             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
853                         group)
854                   sequences))
855           (nnimap-wait-for-response (caar sequences))
856           (setq responses
857                 (nnimap-get-responses (mapcar #'car sequences))))
858         (dolist (response responses)
859           (let* ((sequence (car response))
860                  (response (cadr response))
861                  (group (cadr (assoc sequence sequences))))
862             (when (and group
863                        (equal (caar response) "OK"))
864               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
865                     highest exists)
866                 (dolist (elem response)
867                   (when (equal (cadr elem) "EXISTS")
868                     (setq exists (string-to-number (car elem)))))
869                 (when uidnext
870                   (setq highest (1- (string-to-number (car uidnext)))))
871                 (cond
872                  ((null highest)
873                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
874                  ((zerop exists)
875                   ;; Empty group.
876                   (insert (format "%S %d %d y\n"
877                                   (utf7-decode group t) highest (1+ highest))))
878                  (t
879                   ;; Return the widest possible range.
880                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
881                                   (or highest exists)))))))))
882         t))))
883
884 (deffoo nnimap-retrieve-group-data-early (server infos)
885   (when (nnimap-possibly-change-group nil server)
886     (with-current-buffer (nnimap-buffer)
887       ;; QRESYNC handling isn't implemented.
888       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
889             marks groups sequences)
890         ;; Go through the infos and gather the data needed to know
891         ;; what and how to request the data.
892         (dolist (info infos)
893           (setq marks (gnus-info-marks info))
894           (push (list (gnus-group-real-name (gnus-info-group info))
895                       (cdr (assq 'active marks))
896                       (cdr (assq 'uid marks)))
897                 groups))
898         ;; Then request the data.
899         (erase-buffer)
900         (setf (nnimap-group nnimap-object) nil)
901         (dolist (elem groups)
902           (if (and qresyncp
903                    (nth 2 elem))
904               (push
905                (list 'qresync
906                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
907                                           (car elem)
908                                           (car (nth 2 elem))
909                                           (cdr (nth 2 elem)))
910                      nil
911                      (car elem))
912                sequences)
913             (let ((start
914                    (if (nth 1 elem)
915                        ;; Fetch the last 100 flags.
916                        (max 1 (- (cdr (nth 1 elem)) 100))
917                      1)))
918               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
919                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
920                           start
921                           (car elem))
922                     sequences)))
923           ;; Some servers apparently can't have many outstanding
924           ;; commands, so throttle them.
925           (when (and (not nnimap-streaming)
926                      (car sequences))
927             (nnimap-wait-for-response (caar sequences))))
928         sequences))))
929
930 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
931   (when (and sequences
932              (nnimap-possibly-change-group nil server))
933     (with-current-buffer (nnimap-buffer)
934       ;; Wait for the final data to trickle in.
935       (when (nnimap-wait-for-response (cadar sequences))
936         ;; Now we should have all the data we need, no matter whether
937         ;; we're QRESYNCING, fetching all the flags from scratch, or
938         ;; just fetching the last 100 flags per group.
939         (nnimap-update-infos (nnimap-flags-to-marks
940                               (nnimap-parse-flags
941                                (nreverse sequences)))
942                              infos)
943         ;; Finally, just return something resembling an active file in
944         ;; the nntp buffer, so that the agent can save the info, too.
945         (with-current-buffer nntp-server-buffer
946           (erase-buffer)
947           (dolist (info infos)
948             (let* ((group (gnus-info-group info))
949                    (active (gnus-active group)))
950               (when active
951                 (insert (format "%S %d %d y\n"
952                                 (gnus-group-real-name group)
953                                 (cdr active)
954                                 (car active)))))))))))
955
956 (defun nnimap-update-infos (flags infos)
957   (dolist (info infos)
958     (let ((group (gnus-group-real-name (gnus-info-group info))))
959       (nnimap-update-info info (cdr (assoc group flags))))))
960
961 (defun nnimap-update-info (info marks)
962   (when marks
963     (destructuring-bind (existing flags high low uidnext start-article
964                                   permanent-flags) marks
965       (let ((group (gnus-info-group info))
966             (completep (and start-article
967                             (= start-article 1))))
968         (when uidnext
969           (setq high (1- uidnext)))
970         ;; First set the active ranges based on high/low.
971         (if (or completep
972                 (not (gnus-active group)))
973             (gnus-set-active group
974                              (cond
975                               ((and low high)
976                                (cons low high))
977                               (uidnext
978                                ;; No articles in this group.
979                                (cons uidnext (1- uidnext)))
980                               (start-article
981                                (cons start-article (1- start-article)))
982                               (t
983                                ;; No articles and no uidnext.
984                                nil)))
985           (gnus-set-active
986            group
987            (cons (car (gnus-active group))
988                  (or high (1- uidnext)))))
989         (when (and (not high)
990                    uidnext)
991           (setq high (1- uidnext)))
992         ;; Then update the list of read articles.
993         (let* ((unread
994                 (gnus-compress-sequence
995                  (gnus-set-difference
996                   (gnus-set-difference
997                    existing
998                    (cdr (assoc '%Seen flags)))
999                   (cdr (assoc '%Flagged flags)))))
1000                (read (gnus-range-difference
1001                       (cons start-article high) unread)))
1002           (when (> start-article 1)
1003             (setq read
1004                   (gnus-range-nconcat
1005                    (if (> start-article 1)
1006                        (gnus-sorted-range-intersection
1007                         (cons 1 (1- start-article))
1008                         (gnus-info-read info))
1009                      (gnus-info-read info))
1010                    read)))
1011           (gnus-info-set-read info read)
1012           ;; Update the marks.
1013           (setq marks (gnus-info-marks info))
1014           ;; Note the active level for the next run-through.
1015           (let ((active (assq 'active marks)))
1016             (if active
1017                 (setcdr active (gnus-active group))
1018               (push (cons 'active (gnus-active group)) marks)))
1019           (dolist (type (cdr nnimap-mark-alist))
1020             (let ((old-marks (assoc (car type) marks))
1021                   (new-marks
1022                    (gnus-compress-sequence
1023                     (cdr (or (assoc (caddr type) flags)     ; %Flagged
1024                              (assoc (intern (cadr type) obarray) flags)
1025                              (assoc (cadr type) flags)))))) ; "\Flagged"
1026               (setq marks (delq old-marks marks))
1027               (pop old-marks)
1028               (when (and old-marks
1029                          (> start-article 1))
1030                 (setq old-marks (gnus-range-difference
1031                                  old-marks
1032                                  (cons start-article high)))
1033                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1034               (when new-marks
1035                 (push (cons (car type) new-marks) marks)))
1036             (gnus-info-set-marks info marks t)
1037             (nnimap-store-info info (gnus-active group))))))))
1038
1039 (defun nnimap-store-info (info active)
1040   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1041          (entry (assoc group nnimap-current-infos)))
1042     (if entry
1043         (setcdr entry (list info active))
1044       (push (list group info active) nnimap-current-infos))))
1045
1046 (defun nnimap-flags-to-marks (groups)
1047   (let (data group totalp uidnext articles start-article mark permanent-flags)
1048     (dolist (elem groups)
1049       (setq group (car elem)
1050             uidnext (nth 1 elem)
1051             start-article (nth 2 elem)
1052             permanent-flags (nth 3 elem)
1053             articles (nthcdr 4 elem))
1054       (let ((high (caar articles))
1055             marks low existing)
1056         (dolist (article articles)
1057           (setq low (car article))
1058           (push (car article) existing)
1059           (dolist (flag (cdr article))
1060             (setq mark (assoc flag marks))
1061             (if (not mark)
1062                 (push (list flag (car article)) marks)
1063               (setcdr mark (cons (car article) (cdr mark))))))
1064         (push (list group existing marks high low uidnext start-article
1065                     permanent-flags)
1066               data)))
1067     data))
1068
1069 (defun nnimap-parse-flags (sequences)
1070   (goto-char (point-min))
1071   ;; Change \Delete etc to %Delete, so that the reader can read it.
1072   (subst-char-in-region (point-min) (point-max)
1073                         ?\\ ?% t)
1074   (let (start end articles groups uidnext elems permanent-flags)
1075     (dolist (elem sequences)
1076       (destructuring-bind (group-sequence flag-sequence totalp group) elem
1077         (setq start (point))
1078         ;; The EXAMINE was successful.
1079         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1080                    (progn
1081                      (forward-line 1)
1082                      (setq end (point))
1083                      (goto-char start)
1084                      (setq permanent-flags
1085                            (and (search-forward "PERMANENTFLAGS "
1086                                                  (or end (point-min)) t)
1087                                 (read (current-buffer))))
1088                      (goto-char start)
1089                      (setq uidnext
1090                            (and (search-forward "UIDNEXT "
1091                                                  (or end (point-min)) t)
1092                                 (read (current-buffer))))
1093                      (goto-char end)
1094                      (forward-line -1))
1095                    ;; The UID FETCH FLAGS was successful.
1096                    (search-forward (format "\n%d OK " flag-sequence) nil t))
1097           (setq start (point))
1098           (goto-char end)
1099           (while (search-forward " FETCH " start t)
1100             (setq elems (read (current-buffer)))
1101             (push (cons (cadr (memq 'UID elems))
1102                         (cadr (memq 'FLAGS elems)))
1103                   articles))
1104           (push (nconc (list group uidnext totalp permanent-flags) articles)
1105                 groups)
1106           (setq articles nil))))
1107     groups))
1108
1109 (defun nnimap-find-process-buffer (buffer)
1110   (cadr (assoc buffer nnimap-connection-alist)))
1111
1112 (deffoo nnimap-request-post (&optional server)
1113   (setq nnimap-status-string "Read-only server")
1114   nil)
1115
1116 (defun nnimap-possibly-change-group (group server)
1117   (let ((open-result t))
1118     (when (and server
1119                (not (nnimap-server-opened server)))
1120       (setq open-result (nnimap-open-server server)))
1121     (cond
1122      ((not open-result)
1123       nil)
1124      ((not group)
1125       t)
1126      (t
1127       (with-current-buffer (nnimap-buffer)
1128         (if (equal group (nnimap-group nnimap-object))
1129             t
1130           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1131             (when (car result)
1132               (setf (nnimap-group nnimap-object) group
1133                     (nnimap-select-result nnimap-object) result)
1134               result))))))))
1135
1136 (defun nnimap-find-connection (buffer)
1137   "Find the connection delivering to BUFFER."
1138   (let ((entry (assoc buffer nnimap-connection-alist)))
1139     (when entry
1140       (if (and (buffer-name (cadr entry))
1141                (get-buffer-process (cadr entry))
1142                (memq (process-status (get-buffer-process (cadr entry)))
1143                      '(open run)))
1144           (get-buffer-process (cadr entry))
1145         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1146         nil))))
1147
1148 (defvar nnimap-sequence 0)
1149
1150 (defun nnimap-send-command (&rest args)
1151   (process-send-string
1152    (get-buffer-process (current-buffer))
1153    (nnimap-log-command
1154     (format "%d %s%s\n"
1155             (incf nnimap-sequence)
1156             (apply #'format args)
1157             (if (nnimap-newlinep nnimap-object)
1158                 ""
1159               "\r"))))
1160   nnimap-sequence)
1161
1162 (defun nnimap-log-command (command)
1163   (with-current-buffer (get-buffer-create "*imap log*")
1164     (goto-char (point-max))
1165     (insert (format-time-string "%H:%M:%S") " " command))
1166   command)
1167
1168 (defun nnimap-command (&rest args)
1169   (erase-buffer)
1170   (setf (nnimap-last-command-time nnimap-object) (current-time))
1171   (let* ((sequence (apply #'nnimap-send-command args))
1172          (response (nnimap-get-response sequence)))
1173     (if (equal (caar response) "OK")
1174         (cons t response)
1175       (nnheader-report 'nnimap "%s"
1176                        (mapconcat (lambda (a)
1177                                     (format "%s" a))
1178                                   (car response) " "))
1179       nil)))
1180
1181 (defun nnimap-get-response (sequence)
1182   (nnimap-wait-for-response sequence)
1183   (nnimap-parse-response))
1184
1185 (defun nnimap-wait-for-connection ()
1186   (let ((process (get-buffer-process (current-buffer))))
1187     (goto-char (point-min))
1188     (while (and (memq (process-status process)
1189                       '(open run))
1190                 (not (re-search-forward "^\\* .*\n" nil t)))
1191       (nnheader-accept-process-output process)
1192       (goto-char (point-min)))
1193     (forward-line -1)
1194     (and (looking-at "\\* \\([A-Z0-9]+\\)")
1195          (match-string 1))))
1196
1197 (defun nnimap-wait-for-response (sequence &optional messagep)
1198   (let ((process (get-buffer-process (current-buffer)))
1199         openp)
1200     (goto-char (point-max))
1201     (while (and (setq openp (memq (process-status process)
1202                                   '(open run)))
1203                 (not (re-search-backward
1204                       (format "^%d .*\n" sequence)
1205                       (if nnimap-streaming
1206                           (max (point-min) (- (point) 500))
1207                         (point-min))
1208                       t)))
1209       (when messagep
1210         (message "Read %dKB" (/ (buffer-size) 1000)))
1211       (nnheader-accept-process-output process)
1212       (goto-char (point-max)))
1213     openp))
1214
1215 (defun nnimap-parse-response ()
1216   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1217         result)
1218     (dolist (line lines)
1219       (push (cdr (nnimap-parse-line line)) result))
1220     ;; Return the OK/error code first, and then all the "continuation
1221     ;; lines" afterwards.
1222     (cons (pop result)
1223           (nreverse result))))
1224
1225 ;; Parse an IMAP response line lightly.  They look like
1226 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1227 ;; the lines into a list of strings and lists of string.
1228 (defun nnimap-parse-line (line)
1229   (let (char result)
1230     (with-temp-buffer
1231       (insert line)
1232       (goto-char (point-min))
1233       (while (not (eobp))
1234         (if (eql (setq char (following-char)) ? )
1235             (forward-char 1)
1236           (push
1237            (cond
1238             ((eql char ?\[)
1239              (split-string (buffer-substring
1240                             (1+ (point))
1241                             (1- (search-forward "]" (line-end-position) 'move)))))
1242             ((eql char ?\()
1243              (split-string (buffer-substring
1244                             (1+ (point))
1245                             (1- (search-forward ")" (line-end-position) 'move)))))
1246             ((eql char ?\")
1247              (forward-char 1)
1248              (buffer-substring
1249               (point)
1250               (1- (or (search-forward "\"" (line-end-position) 'move)
1251                       (point)))))
1252             (t
1253              (buffer-substring (point) (if (search-forward " " nil t)
1254                                            (1- (point))
1255                                          (goto-char (point-max))))))
1256            result)))
1257       (nreverse result))))
1258
1259 (defun nnimap-last-response-string ()
1260   (save-excursion
1261     (forward-line 1)
1262     (let ((end (point)))
1263       (forward-line -1)
1264       (when (not (bobp))
1265         (forward-line -1)
1266         (while (and (not (bobp))
1267                     (eql (following-char) ?*))
1268           (forward-line -1))
1269         (unless (eql (following-char) ?*)
1270           (forward-line 1)))
1271       (buffer-substring (point) end))))
1272
1273 (defun nnimap-get-responses (sequences)
1274   (let (responses)
1275     (dolist (sequence sequences)
1276       (goto-char (point-min))
1277       (when (re-search-forward (format "^%d " sequence) nil t)
1278         (push (list sequence (nnimap-parse-response))
1279               responses)))
1280     responses))
1281
1282 (defvar nnimap-incoming-split-list nil)
1283
1284 (defun nnimap-fetch-inbox (articles)
1285   (erase-buffer)
1286   (nnimap-wait-for-response
1287    (nnimap-send-command
1288     "UID FETCH %s %s"
1289     (nnimap-article-ranges articles)
1290     (format "(UID %s%s)"
1291             (format
1292              (if (nnimap-ver4-p)
1293                  "BODY.PEEK[HEADER] BODY.PEEK"
1294                "RFC822.PEEK"))
1295             (if nnimap-split-download-body-default
1296                 "[]"
1297               "[1]")))
1298    t))
1299
1300 (defun nnimap-split-incoming-mail ()
1301   (with-current-buffer (nnimap-buffer)
1302     (let ((nnimap-incoming-split-list nil)
1303           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1304                                     nnmail-split-methods
1305                                   nnimap-split-methods))
1306           (nnmail-inhibit-default-split-group t)
1307           (groups (nnimap-get-groups))
1308           new-articles)
1309       (erase-buffer)
1310       (nnimap-command "SELECT %S" nnimap-inbox)
1311       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1312       (when new-articles
1313         (nnimap-fetch-inbox new-articles)
1314         (nnimap-transform-split-mail)
1315         (nnheader-ms-strip-cr)
1316         (nnmail-cache-open)
1317         (nnmail-split-incoming (current-buffer)
1318                                #'nnimap-save-mail-spec
1319                                nil nil
1320                                #'nnimap-dummy-active-number
1321                                #'nnimap-save-mail-spec)
1322         (when nnimap-incoming-split-list
1323           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1324                 sequences junk-articles)
1325             ;; Create any groups that doesn't already exist on the
1326             ;; server first.
1327             (dolist (spec specs)
1328               (when (and (not (member (car spec) groups))
1329                          (not (eq (car spec) 'junk)))
1330                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1331             ;; Then copy over all the messages.
1332             (erase-buffer)
1333             (dolist (spec specs)
1334               (let ((group (car spec))
1335                     (ranges (cdr spec)))
1336                 (if (eq group 'junk)
1337                     (setq junk-articles ranges)
1338                   (push (list (nnimap-send-command
1339                                "UID COPY %s %S"
1340                                (nnimap-article-ranges ranges)
1341                                (utf7-encode group t))
1342                               ranges)
1343                         sequences))))
1344             ;; Wait for the last COPY response...
1345             (when sequences
1346               (nnimap-wait-for-response (caar sequences))
1347               ;; And then mark the successful copy actions as deleted,
1348               ;; and possibly expunge them.
1349               (nnimap-mark-and-expunge-incoming
1350                (nnimap-parse-copied-articles sequences)))
1351             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1352
1353 (defun nnimap-mark-and-expunge-incoming (range)
1354   (when range
1355     (setq range (nnimap-article-ranges range))
1356     (erase-buffer)
1357     (let ((sequence
1358            (nnimap-send-command
1359             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1360       (cond
1361        ;; If the server supports it, we now delete the message we have
1362        ;; just copied over.
1363        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1364         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1365        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1366        ;; user has configured it.
1367        (nnimap-expunge
1368         (setq sequence (nnimap-send-command "EXPUNGE"))))
1369       (nnimap-wait-for-response sequence))))
1370
1371 (defun nnimap-parse-copied-articles (sequences)
1372   (let (sequence copied range)
1373     (goto-char (point-min))
1374     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1375       (setq sequence (string-to-number (match-string 1)))
1376       (when (setq range (cadr (assq sequence sequences)))
1377         (push (gnus-uncompress-range range) copied)))
1378     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1379
1380 (defun nnimap-new-articles (flags)
1381   (let (new)
1382     (dolist (elem flags)
1383       (when (or (null (cdr elem))
1384                 (and (not (memq '%Deleted (cdr elem)))
1385                      (not (memq '%Seen (cdr elem)))))
1386         (push (car elem) new)))
1387     (gnus-compress-sequence (nreverse new))))
1388
1389 (defun nnimap-make-split-specs (list)
1390   (let ((specs nil)
1391         entry)
1392     (dolist (elem list)
1393       (destructuring-bind (article spec) elem
1394         (dolist (group (delete nil (mapcar #'car spec)))
1395           (unless (setq entry (assoc group specs))
1396             (push (setq entry (list group)) specs))
1397           (setcdr entry (cons article (cdr entry))))))
1398     (dolist (entry specs)
1399       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1400     specs))
1401
1402 (defun nnimap-transform-split-mail ()
1403   (goto-char (point-min))
1404   (let (article bytes)
1405     (block nil
1406       (while (not (eobp))
1407         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1408           (delete-region (point) (progn (forward-line 1) (point)))
1409           (when (eobp)
1410             (return)))
1411         (setq article (match-string 1)
1412               bytes (nnimap-get-length))
1413         (delete-region (line-beginning-position) (line-end-position))
1414         ;; Insert MMDF separator, and a way to remember what this
1415         ;; article UID is.
1416         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1417         (forward-char (1+ bytes))
1418         (setq bytes (nnimap-get-length))
1419         (delete-region (line-beginning-position) (line-end-position))
1420         (forward-char (1+ bytes))
1421         (delete-region (line-beginning-position) (line-end-position))))))
1422
1423 (defun nnimap-dummy-active-number (group &optional server)
1424   1)
1425
1426 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1427   (let (article)
1428     (goto-char (point-min))
1429     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1430         (error "Invalid nnimap mail")
1431       (setq article (string-to-number (match-string 1))))
1432     (push (list article
1433                 (if (eq group-art 'junk)
1434                     (list (cons 'junk 1))
1435                   group-art))
1436           nnimap-incoming-split-list)))
1437
1438 (provide 'nnimap)
1439
1440 ;;; nnimap.el ends here