1;;; notmuch-maildir-fcc.el --- inserting using a fcc handler  -*- lexical-binding: t -*-
2
3;; Copyright © Jesse Rosenthal
4;;
5;; This file is part of Notmuch.
6;;
7;; Notmuch is free software: you can redistribute it and/or modify it
8;; under the terms of the GNU General Public License as published by
9;; the Free Software Foundation, either version 3 of the License, or
10;; (at your option) any later version.
11;;
12;; Notmuch is distributed in the hope that it will be useful, but
13;; WITHOUT ANY WARRANTY; without even the implied warranty of
14;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15;; General Public License for more details.
16;;
17;; You should have received a copy of the GNU General Public License
18;; along with Notmuch.  If not, see <https://www.gnu.org/licenses/>.
19;;
20;; Authors: Jesse Rosenthal <jrosenthal@jhu.edu>
21
22;;; Code:
23
24(require 'seq)
25
26(require 'message)
27
28(require 'notmuch-lib)
29
30(defvar notmuch-maildir-fcc-count 0)
31
32;;; Options
33
34(defcustom notmuch-fcc-dirs "sent"
35  "Determines the Fcc Header which says where to save outgoing mail.
36
37Three types of values are permitted:
38
39- nil: no Fcc header is added,
40
41- a string: the value of `notmuch-fcc-dirs' is the Fcc header to
42  be used.
43
44- an alist: the folder is chosen based on the From address of
45  the current message according to an alist mapping regular
46  expressions to folders or nil:
47
48     ((\"Sebastian@SSpaeth.de\" . \"privat\")
49      (\"spaetz@sspaeth.de\" . \"OUTBOX.OSS\")
50      (\".*\" . \"defaultinbox\"))
51
52  If none of the regular expressions match the From address, or
53  if the cdr of the matching entry is nil, then no Fcc header
54  will be added.
55
56If `notmuch-maildir-use-notmuch-insert' is set (the default) then
57the header should be of the form \"folder +tag1 -tag2\" where
58folder is the folder (relative to the notmuch mailstore) to store
59the message in, and tag1 and tag2 are tag changes to apply to the
60stored message. This string is split using `split-string-and-unquote',
61so a folder name containing spaces can be specified by
62quoting each space with an immediately preceding backslash
63or surrounding the entire folder name in double quotes.
64
65If `notmuch-maildir-use-notmuch-insert' is nil then the Fcc
66header should be the directory where the message should be
67saved. A relative directory will be understood to specify a
68directory within the notmuch mail store, (as set by the
69database.path option in the notmuch configuration file).
70
71In all cases you will be prompted to create the folder or
72directory if it does not exist yet when sending a mail."
73
74  :type '(choice
75	  (const :tag "No FCC header" nil)
76	  (string :tag "A single folder")
77	  (repeat :tag "A folder based on the From header"
78		  (cons regexp (choice (const :tag "No FCC header" nil)
79				       (string :tag "Folder")))))
80  :require 'notmuch-fcc-initialization
81  :group 'notmuch-send)
82
83(defcustom notmuch-maildir-use-notmuch-insert t
84  "Should fcc use notmuch insert instead of simple fcc."
85  :type '(choice :tag "Fcc Method"
86		 (const :tag "Use notmuch insert" t)
87		 (const :tag "Use simple fcc" nil))
88  :group 'notmuch-send)
89
90;;; Functions which set up the fcc header in the message buffer.
91
92(defun notmuch-fcc-header-setup ()
93  "Add an Fcc header to the current message buffer.
94
95If the Fcc header is already set, then keep it as-is.
96Otherwise set it according to `notmuch-fcc-dirs'."
97  (let ((subdir
98	 (cond
99	  ((or (not notmuch-fcc-dirs)
100	       (message-field-value "Fcc"))
101	   ;; Nothing set or an existing header.
102	   nil)
103	  ((stringp notmuch-fcc-dirs)
104	   notmuch-fcc-dirs)
105	  ((and (listp notmuch-fcc-dirs)
106		(stringp (car notmuch-fcc-dirs)))
107	   ;; Old style - no longer works.
108	   (error "Invalid `notmuch-fcc-dirs' setting (old style)"))
109	  ((listp notmuch-fcc-dirs)
110	   (if-let ((match (seq-some (let ((from (message-field-value "From")))
111				       (pcase-lambda (`(,regexp . ,folder))
112					 (and (string-match-p regexp from)
113					      (cons t folder))))
114				     notmuch-fcc-dirs)))
115               (cdr match)
116             (message "No Fcc header added.")
117	     nil))
118	  (t
119	   (error "Invalid `notmuch-fcc-dirs' setting (neither string nor list)")))))
120    (when subdir
121      (if notmuch-maildir-use-notmuch-insert
122	  (notmuch-maildir-add-notmuch-insert-style-fcc-header subdir)
123	(notmuch-maildir-add-file-style-fcc-header subdir)))))
124
125(defun notmuch-maildir-add-notmuch-insert-style-fcc-header (subdir)
126  ;; Notmuch insert does not accept absolute paths, so check the user
127  ;; really want this header inserted.
128  (when (or (not (= (elt subdir 0) ?/))
129	    (y-or-n-p (format "Fcc header %s is an absolute path %s %s" subdir
130			      "and notmuch insert is requested."
131			      "Insert header anyway? ")))
132    (message-add-header (concat "Fcc: " subdir))))
133
134(defun notmuch-maildir-add-file-style-fcc-header (subdir)
135  (message-add-header
136   (concat "Fcc: "
137	   (file-truename
138	    ;; If the resulting directory is not an absolute path,
139	    ;; prepend the standard notmuch database path.
140	    (if (= (elt subdir 0) ?/)
141		subdir
142	      (concat (notmuch-database-path) "/" subdir))))))
143
144;;; Functions for saving a message using either method.
145
146(defmacro with-temporary-notmuch-message-buffer (&rest body)
147  "Set-up a temporary copy of the current message-mode buffer."
148  `(let ((case-fold-search t)
149	 (buf (current-buffer))
150	 (mml-externalize-attachments message-fcc-externalize-attachments))
151     (with-current-buffer (get-buffer-create " *message temp*")
152       (erase-buffer)
153       (insert-buffer-substring buf)
154       ,@body)))
155
156(defun notmuch-maildir-setup-message-for-saving ()
157  "Setup message for saving.
158
159This should be called on a temporary copy.
160This is taken from the function message-do-fcc."
161  (message-encode-message-body)
162  (save-restriction
163    (message-narrow-to-headers)
164    (mail-encode-encoded-word-buffer))
165  (goto-char (point-min))
166  (when (re-search-forward
167	 (concat "^" (regexp-quote mail-header-separator) "$")
168	 nil t)
169    (replace-match "" t t )))
170
171(defun notmuch-maildir-message-do-fcc ()
172  "Process Fcc headers in the current buffer.
173
174This is a rearranged version of message mode's message-do-fcc."
175  (let (files file)
176    (save-excursion
177      (save-restriction
178	(message-narrow-to-headers)
179	(setq file (message-fetch-field "fcc" t)))
180      (when file
181	(with-temporary-notmuch-message-buffer
182	 (save-restriction
183	   (message-narrow-to-headers)
184	   (while (setq file (message-fetch-field "fcc" t))
185	     (push file files)
186	     (message-remove-header "fcc" nil t)))
187	 (notmuch-maildir-setup-message-for-saving)
188	 ;; Process FCC operations.
189	 (mapc #'notmuch-fcc-handler files)
190	 (kill-buffer (current-buffer)))))))
191
192(defun notmuch-fcc-handler (fcc-header)
193  "Store message with notmuch insert or normal (file) fcc.
194
195If `notmuch-maildir-use-notmuch-insert' is set then store the
196message using notmuch insert. Otherwise store the message using
197normal fcc."
198  (message "Doing Fcc...")
199  (if notmuch-maildir-use-notmuch-insert
200      (notmuch-maildir-fcc-with-notmuch-insert fcc-header)
201    (notmuch-maildir-fcc-file-fcc fcc-header))
202  (message "Doing Fcc...done"))
203
204;;; Functions for saving a message using notmuch insert.
205
206(defun notmuch-maildir-notmuch-insert-current-buffer (folder &optional create tags)
207  "Use notmuch insert to put the current buffer in the database.
208
209This inserts the current buffer as a message into the notmuch
210database in folder FOLDER. If CREATE is non-nil it will supply
211the --create-folder flag to create the folder if necessary. TAGS
212should be a list of tag changes to apply to the inserted message."
213  (apply 'notmuch-call-notmuch-process
214	 :stdin-string (buffer-string) "insert"
215	 (append (and create (list "--create-folder"))
216		 (list (concat "--folder=" folder))
217		 tags)))
218
219(defun notmuch-maildir-fcc-with-notmuch-insert (fcc-header &optional create)
220  "Store message with notmuch insert.
221
222The fcc-header should be of the form \"folder +tag1 -tag2\" where
223folder is the folder (relative to the notmuch mailstore) to store
224the message in, and tag1 and tag2 are tag changes to apply to the
225stored message. This string is split using `split-string-and-unquote',
226so a folder name containing spaces can be specified by
227quoting each space with an immediately preceding backslash
228or surrounding the entire folder name in double quotes.
229
230If CREATE is non-nil then create the folder if necessary."
231  (pcase-let ((`(,folder . ,tags)
232	       (split-string-and-unquote fcc-header)))
233    (condition-case nil
234	(notmuch-maildir-notmuch-insert-current-buffer folder create tags)
235      ;; Since there are many reasons notmuch insert could fail, e.g.,
236      ;; locked database, non-existent folder (which could be due to a
237      ;; typo, or just the user want a new folder, let the user decide
238      ;; how to deal with it.
239      (error
240       (let ((response (read-char-choice "Insert failed: \
241\(r)etry, (c)reate folder, (i)gnore, or (e)dit the header? " '(?r ?c ?i ?e))))
242	 (cl-case response
243	   (?r (notmuch-maildir-fcc-with-notmuch-insert fcc-header))
244	   (?c (notmuch-maildir-fcc-with-notmuch-insert fcc-header t))
245	   (?i t)
246	   (?e (notmuch-maildir-fcc-with-notmuch-insert
247		(read-from-minibuffer "Fcc header: " fcc-header)))))))))
248
249;;; Functions for saving a message using file fcc.
250
251(defun notmuch-maildir-fcc-host-fixer (hostname)
252  (replace-regexp-in-string "/\\|:"
253			    (lambda (s)
254			      (cond ((string-equal s "/") "\\057")
255				    ((string-equal s ":") "\\072")
256				    (t s)))
257			    hostname
258			    t
259			    t))
260
261(defun notmuch-maildir-fcc-make-uniq-maildir-id ()
262  (let* ((ftime (float-time))
263	 (microseconds (mod (* 1000000 ftime) 1000000))
264	 (hostname (notmuch-maildir-fcc-host-fixer (system-name))))
265    (cl-incf notmuch-maildir-fcc-count)
266    (format "%d.%d_%d_%d.%s"
267	    ftime
268	    (emacs-pid)
269	    microseconds
270	    notmuch-maildir-fcc-count
271	    hostname)))
272
273(defun notmuch-maildir-fcc-dir-is-maildir-p (dir)
274  (and (file-exists-p (concat dir "/cur/"))
275       (file-exists-p (concat dir "/new/"))
276       (file-exists-p (concat dir "/tmp/"))))
277
278(defun notmuch-maildir-fcc-create-maildir (path)
279  (cond ((or (not (file-exists-p path)) (file-directory-p path))
280	 (make-directory (concat path "/cur/") t)
281	 (make-directory (concat path "/new/") t)
282	 (make-directory (concat path "/tmp/") t))
283	((file-regular-p path)
284	 (error "%s is a file. Can't create maildir." path))
285	(t
286	 (error "I don't know how to create a maildir here"))))
287
288(defun notmuch-maildir-fcc-save-buffer-to-tmp (destdir)
289  "Returns the msg id of the message written to the temp directory
290if successful, nil if not."
291  (let ((msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
292    (while (file-exists-p (concat destdir "/tmp/" msg-id))
293      (setq msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
294    (cond ((notmuch-maildir-fcc-dir-is-maildir-p destdir)
295	   (write-file (concat destdir "/tmp/" msg-id))
296	   msg-id)
297	  (t
298	   (error "Can't write to %s. Not a maildir." destdir)))))
299
300(defun notmuch-maildir-fcc-move-tmp-to-new (destdir msg-id)
301  (add-name-to-file
302   (concat destdir "/tmp/" msg-id)
303   (concat destdir "/new/" msg-id ":2,")))
304
305(defun notmuch-maildir-fcc-move-tmp-to-cur (destdir msg-id &optional mark-seen)
306  (add-name-to-file
307   (concat destdir "/tmp/" msg-id)
308   (concat destdir "/cur/" msg-id ":2," (and mark-seen "S"))))
309
310(defun notmuch-maildir-fcc-file-fcc (fcc-header)
311  "Write the message to the file specified by FCC-HEADER.
312
313If that fails, then offer the user a chance to correct the header
314or filesystem."
315  (if (notmuch-maildir-fcc-dir-is-maildir-p fcc-header)
316      (notmuch-maildir-fcc-write-buffer-to-maildir fcc-header t)
317    ;; The fcc-header is not a valid maildir see if the user wants to
318    ;; fix it in some way.
319    (let* ((prompt (format "Fcc %s is not a maildir: \
320\(r)etry, (c)reate folder, (i)gnore, or (e)dit the header? " fcc-header))
321	   (response (read-char-choice prompt '(?r ?c ?i ?e))))
322      (cl-case response
323	(?r (notmuch-maildir-fcc-file-fcc fcc-header))
324	(?c (if (file-writable-p fcc-header)
325		(notmuch-maildir-fcc-create-maildir fcc-header)
326	      (message "No permission to create %s." fcc-header)
327	      (sit-for 2))
328	    (notmuch-maildir-fcc-file-fcc fcc-header))
329	(?i t)
330	(?e (notmuch-maildir-fcc-file-fcc
331	     (read-from-minibuffer "Fcc header: " fcc-header)))))))
332
333(defun notmuch-maildir-fcc-write-buffer-to-maildir (destdir &optional mark-seen)
334  "Write the current buffer to maildir destdir.
335
336If mark-seen is non-nil, then write it to \"cur/\", and mark it
337as read, otherwise write it to \"new/\". Return t if successful,
338and nil otherwise."
339  (let ((orig-buffer (buffer-name)))
340    (with-temp-buffer
341      (insert-buffer-substring orig-buffer)
342      (catch 'link-error
343	(let ((msg-id (notmuch-maildir-fcc-save-buffer-to-tmp destdir)))
344	  (when msg-id
345	    (condition-case nil
346		(if mark-seen
347		    (notmuch-maildir-fcc-move-tmp-to-cur destdir msg-id t)
348		  (notmuch-maildir-fcc-move-tmp-to-new destdir msg-id))
349	      (file-already-exists
350	       (throw 'link-error nil))))
351	  (delete-file (concat destdir "/tmp/" msg-id))))
352      t)))
353
354;;; _
355
356(provide 'notmuch-maildir-fcc)
357
358;;; notmuch-maildir-fcc.el ends here
359