]> git.notmuchmail.org Git - notmuch/blob - message.cc
notmuch.el: Implement visual feedback for add/remove tags.
[notmuch] / message.cc
1 /* message.cc - Results of message-based searches from a notmuch database
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-private.h"
22 #include "database-private.h"
23
24 #include <gmime/gmime.h>
25
26 #include <xapian.h>
27
28 struct _notmuch_message {
29     notmuch_database_t *notmuch;
30     Xapian::docid doc_id;
31     int frozen;
32     char *message_id;
33     char *thread_id;
34     char *filename;
35     notmuch_message_file_t *message_file;
36     Xapian::Document doc;
37 };
38
39 /* "128 bits of thread-id ought to be enough for anybody" */
40 #define NOTMUCH_THREAD_ID_BITS   128
41 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
42 typedef struct _thread_id {
43     char str[NOTMUCH_THREAD_ID_DIGITS + 1];
44 } thread_id_t;
45
46 /* We end up having to call the destructor explicitly because we had
47  * to use "placement new" in order to initialize C++ objects within a
48  * block that we allocated with talloc. So C++ is making talloc
49  * slightly less simple to use, (we wouldn't need
50  * talloc_set_destructor at all otherwise).
51  */
52 static int
53 _notmuch_message_destructor (notmuch_message_t *message)
54 {
55     message->doc.~Document ();
56
57     return 0;
58 }
59
60 /* Create a new notmuch_message_t object for an existing document in
61  * the database.
62  *
63  * Here, 'talloc owner' is an optional talloc context to which the new
64  * message will belong. This allows for the caller to not bother
65  * calling notmuch_message_destroy on the message, and no that all
66  * memory will be reclaimed with 'talloc_owner' is free. The caller
67  * still can call notmuch_message_destroy when finished with the
68  * message if desired.
69  *
70  * The 'talloc_owner' argument can also be NULL, in which case the
71  * caller *is* responsible for calling notmuch_message_destroy.
72  *
73  * If no document exists in the database with document ID of 'doc_id'
74  * then this function returns NULL and optionally sets *status to
75  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
76  *
77  * This function can also fail to due lack of available memory,
78  * returning NULL and optionally setting *status to
79  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
80  *
81  * The caller can pass NULL for status if uninterested in
82  * distinguishing these two cases.
83  */
84 notmuch_message_t *
85 _notmuch_message_create (const void *talloc_owner,
86                          notmuch_database_t *notmuch,
87                          unsigned int doc_id,
88                          notmuch_private_status_t *status)
89 {
90     notmuch_message_t *message;
91
92     if (status)
93         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
94
95     message = talloc (talloc_owner, notmuch_message_t);
96     if (unlikely (message == NULL)) {
97         if (status)
98             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
99         return NULL;
100     }
101
102     message->notmuch = notmuch;
103     message->doc_id = doc_id;
104
105     message->frozen = 0;
106
107     /* Each of these will be lazily created as needed. */
108     message->message_id = NULL;
109     message->thread_id = NULL;
110     message->filename = NULL;
111     message->message_file = NULL;
112
113     /* This is C++'s creepy "placement new", which is really just an
114      * ugly way to call a constructor for a pre-allocated object. So
115      * it's really not an error to not be checking for OUT_OF_MEMORY
116      * here, since this "new" isn't actually allocating memory. This
117      * is language-design comedy of the wrong kind. */
118
119     new (&message->doc) Xapian::Document;
120
121     talloc_set_destructor (message, _notmuch_message_destructor);
122
123     try {
124         message->doc = notmuch->xapian_db->get_document (doc_id);
125     } catch (const Xapian::DocNotFoundError &error) {
126         talloc_free (message);
127         if (status)
128             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
129         return NULL;
130     }
131
132     return message;
133 }
134
135 /* Create a new notmuch_message_t object for a specific message ID,
136  * (which may or may not already exist in the databas).
137  *
138  * Here, 'talloc owner' is an optional talloc context to which the new
139  * message will belong. This allows for the caller to not bother
140  * calling notmuch_message_destroy on the message, and no that all
141  * memory will be reclaimed with 'talloc_owner' is free. The caller
142  * still can call notmuch_message_destroy when finished with the
143  * message if desired.
144  *
145  * The 'talloc_owner' argument can also be NULL, in which case the
146  * caller *is* responsible for calling notmuch_message_destroy.
147  *
148  * If there is already a document with message ID 'message_id' in the
149  * database, then the returned message can be used to query/modify the
150  * document. Otherwise, a new document will be inserted into the
151  * database before this function returns, (and *status will be set
152  * to NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND).
153  *
154  * If an error occurs, this function will return NULL and *status
155  * will be set as appropriate. (The status pointer argument must
156  * not be NULL.)
157  */
158 notmuch_message_t *
159 _notmuch_message_create_for_message_id (const void *talloc_owner,
160                                         notmuch_database_t *notmuch,
161                                         const char *message_id,
162                                         notmuch_private_status_t *status_ret)
163 {
164     notmuch_message_t *message;
165     Xapian::Document doc;
166     unsigned int doc_id;
167     char *term;
168
169     *status_ret = NOTMUCH_PRIVATE_STATUS_SUCCESS;
170
171     message = notmuch_database_find_message (notmuch, message_id);
172     if (message)
173         return talloc_steal (talloc_owner, message);
174
175     term = talloc_asprintf (NULL, "%s%s",
176                             _find_prefix ("id"), message_id);
177     if (term == NULL) {
178         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
179         return NULL;
180     }
181
182     try {
183         doc.add_term (term);
184         talloc_free (term);
185
186         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
187
188         doc_id = notmuch->xapian_db->add_document (doc);
189     } catch (const Xapian::Error &error) {
190         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
191         return NULL;
192     }
193
194     message = _notmuch_message_create (talloc_owner, notmuch,
195                                        doc_id, status_ret);
196
197     /* We want to inform the caller that we had to create a new
198      * document. */
199     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
200         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
201
202     return message;
203 }
204
205 const char *
206 notmuch_message_get_message_id (notmuch_message_t *message)
207 {
208     Xapian::TermIterator i;
209
210     if (message->message_id)
211         return message->message_id;
212
213     i = message->doc.termlist_begin ();
214     i.skip_to (_find_prefix ("id"));
215
216     if (i == message->doc.termlist_end ())
217         INTERNAL_ERROR ("Message with document ID of %d has no message ID.\n",
218                         message->doc_id);
219
220     message->message_id = talloc_strdup (message, (*i).c_str () + 1);
221
222 #if DEBUG_DATABASE_SANITY
223     i++;
224
225     if (i != message->doc.termlist_end () &&
226         strncmp ((*i).c_str (), _find_prefix ("id"),
227                  strlen (_find_prefix ("id"))) == 0)
228     {
229         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate message IDs",
230                         message->doc_id);
231     }
232 #endif
233
234     return message->message_id;
235 }
236
237 static void
238 _notmuch_message_ensure_message_file (notmuch_message_t *message)
239 {
240     const char *filename;
241
242     if (message->message_file)
243         return;
244
245     filename = notmuch_message_get_filename (message);
246     if (unlikely (filename == NULL))
247         return;
248
249     message->message_file = _notmuch_message_file_open_ctx (message, filename);
250 }
251
252 const char *
253 notmuch_message_get_header (notmuch_message_t *message, const char *header)
254 {
255     _notmuch_message_ensure_message_file (message);
256     if (message->message_file == NULL)
257         return NULL;
258
259     return notmuch_message_file_get_header (message->message_file, header);
260 }
261
262 const char *
263 notmuch_message_get_all_headers (notmuch_message_t *message)
264 {
265     _notmuch_message_ensure_message_file (message);
266     if (message->message_file == NULL)
267         return NULL;
268
269     return notmuch_message_file_get_all_headers (message->message_file);
270 }
271
272 size_t
273 notmuch_message_get_header_size (notmuch_message_t *message)
274 {
275     _notmuch_message_ensure_message_file (message);
276     if (message->message_file == NULL)
277         return 0;
278
279     return notmuch_message_file_get_header_size (message->message_file);
280
281 }
282
283 const char *
284 notmuch_message_get_thread_id (notmuch_message_t *message)
285 {
286     Xapian::TermIterator i;
287
288     if (message->thread_id)
289         return message->thread_id;
290
291     i = message->doc.termlist_begin ();
292     i.skip_to (_find_prefix ("thread"));
293
294     if (i == message->doc.termlist_end ())
295         INTERNAL_ERROR ("Message with document ID of %d has no thread ID.\n",
296                         message->doc_id);
297
298     message->thread_id = talloc_strdup (message, (*i).c_str () + 1);
299
300 #if DEBUG_DATABASE_SANITY
301     i++;
302
303     if (i != message->doc.termlist_end () &&
304         strncmp ((*i).c_str (), _find_prefix ("thread"),
305                  strlen (_find_prefix ("thread"))) == 0)
306     {
307         INTERNAL_ERROR ("Message %s has duplicate thread IDs: %s and %s\n",
308                         notmuch_message_get_message_id (message),
309                         message->thread_id,
310                         (*i).c_str () + 1);
311     }
312 #endif
313
314     return message->thread_id;
315 }
316
317 /* Set the filename for 'message' to 'filename'.
318  *
319  * XXX: We should still figure out if we think it's important to store
320  * multiple filenames for email messages with identical message IDs.
321  *
322  * This change will not be reflected in the database until the next
323  * call to _notmuch_message_set_sync. */
324 void
325 _notmuch_message_set_filename (notmuch_message_t *message,
326                                const char *filename)
327 {
328     const char *s;
329     const char *db_path;
330     unsigned int db_path_len;
331
332     if (message->filename) {
333         talloc_free (message->filename);
334         message->filename = NULL;
335     }
336
337     if (filename == NULL)
338         INTERNAL_ERROR ("Message filename cannot be NULL.");
339
340     s = filename;
341
342     db_path = notmuch_database_get_path (message->notmuch);
343     db_path_len = strlen (db_path);
344
345     if (*s == '/' && strncmp (s, db_path, db_path_len) == 0
346         && strlen (s) > db_path_len)
347     {
348         s += db_path_len + 1;
349     }
350
351     message->doc.set_data (s);
352 }
353
354 const char *
355 notmuch_message_get_filename (notmuch_message_t *message)
356 {
357     std::string filename_str;
358     const char *db_path;
359
360     if (message->filename)
361         return message->filename;
362
363     filename_str = message->doc.get_data ();
364     db_path = notmuch_database_get_path (message->notmuch);
365
366     if (filename_str[0] != '/')
367         message->filename = talloc_asprintf (message, "%s/%s", db_path,
368                                              filename_str.c_str ());
369     else
370         message->filename = talloc_strdup (message, filename_str.c_str ());
371
372     return message->filename;
373 }
374
375 time_t
376 notmuch_message_get_date (notmuch_message_t *message)
377 {
378     std::string value;
379
380     try {
381         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
382     } catch (Xapian::Error &error) {
383         INTERNAL_ERROR ("Failed to read timestamp value from document.");
384         return 0;
385     }
386
387     return Xapian::sortable_unserialise (value);
388 }
389
390 notmuch_tags_t *
391 notmuch_message_get_tags (notmuch_message_t *message)
392 {
393     const char *prefix = _find_prefix ("tag");
394     Xapian::TermIterator i, end;
395     notmuch_tags_t *tags;
396     std::string tag;
397
398     /* Currently this iteration is written with the assumption that
399      * "tag" has a single-character prefix. */
400     assert (strlen (prefix) == 1);
401
402     tags = _notmuch_tags_create (message);
403     if (unlikely (tags == NULL))
404         return NULL;
405
406     i = message->doc.termlist_begin ();
407     end = message->doc.termlist_end ();
408
409     i.skip_to (prefix);
410
411     while (1) {
412         tag = *i;
413
414         if (tag.empty () || tag[0] != *prefix)
415             break;
416
417         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
418
419         i++;
420     }
421
422     _notmuch_tags_prepare_iterator (tags);
423
424     return tags;
425 }
426
427 void
428 _notmuch_message_set_date (notmuch_message_t *message,
429                            const char *date)
430 {
431     time_t time_value;
432
433     time_value = g_mime_utils_header_decode_date (date, NULL);
434
435     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
436                             Xapian::sortable_serialise (time_value));
437 }
438
439 static void
440 thread_id_generate (thread_id_t *thread_id)
441 {
442     static int seeded = 0;
443     FILE *dev_random;
444     uint32_t value;
445     char *s;
446     int i;
447
448     if (! seeded) {
449         dev_random = fopen ("/dev/random", "r");
450         if (dev_random == NULL) {
451             srand (time (NULL));
452         } else {
453             fread ((void *) &value, sizeof (value), 1, dev_random);
454             srand (value);
455             fclose (dev_random);
456         }
457         seeded = 1;
458     }
459
460     s = thread_id->str;
461     for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
462         value = rand ();
463         sprintf (s, "%08x", value);
464         s += 8;
465     }
466 }
467
468 void
469 _notmuch_message_ensure_thread_id (notmuch_message_t *message)
470 {
471     /* If not part of any existing thread, generate a new thread_id. */
472     thread_id_t thread_id;
473
474     thread_id_generate (&thread_id);
475     _notmuch_message_add_term (message, "thread", thread_id.str);
476 }
477
478 /* Synchronize changes made to message->doc out into the database. */
479 void
480 _notmuch_message_sync (notmuch_message_t *message)
481 {
482     Xapian::WritableDatabase *db = message->notmuch->xapian_db;
483
484     db->replace_document (message->doc_id, message->doc);
485 }
486
487 /* Add a name:value term to 'message', (the actual term will be
488  * encoded by prefixing the value with a short prefix). See
489  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
490  * names to prefix values.
491  *
492  * This change will not be reflected in the database until the next
493  * call to _notmuch_message_set_sync. */
494 notmuch_private_status_t
495 _notmuch_message_add_term (notmuch_message_t *message,
496                            const char *prefix_name,
497                            const char *value)
498 {
499
500     char *term;
501
502     if (value == NULL)
503         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
504
505     term = talloc_asprintf (message, "%s%s",
506                             _find_prefix (prefix_name), value);
507
508     if (strlen (term) > NOTMUCH_TERM_MAX)
509         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
510
511     message->doc.add_term (term);
512
513     talloc_free (term);
514
515     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
516 }
517
518 /* Parse 'text' and add a term to 'message' for each parsed word. Each
519  * term will be added both prefixed (if prefix_name is not NULL) and
520  * also unprefixed). */
521 notmuch_private_status_t
522 _notmuch_message_gen_terms (notmuch_message_t *message,
523                             const char *prefix_name,
524                             const char *text)
525 {
526     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
527
528     if (text == NULL)
529         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
530
531     term_gen->set_document (message->doc);
532
533     if (prefix_name) {
534         const char *prefix = _find_prefix (prefix_name);
535
536         term_gen->index_text (text, 1, prefix);
537     }
538
539     term_gen->index_text (text);
540
541     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
542 }
543
544 /* Remove a name:value term from 'message', (the actual term will be
545  * encoded by prefixing the value with a short prefix). See
546  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
547  * names to prefix values.
548  *
549  * This change will not be reflected in the database until the next
550  * call to _notmuch_message_set_sync. */
551 notmuch_private_status_t
552 _notmuch_message_remove_term (notmuch_message_t *message,
553                               const char *prefix_name,
554                               const char *value)
555 {
556     char *term;
557
558     if (value == NULL)
559         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
560
561     term = talloc_asprintf (message, "%s%s",
562                             _find_prefix (prefix_name), value);
563
564     if (strlen (term) > NOTMUCH_TERM_MAX)
565         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
566
567     try {
568         message->doc.remove_term (term);
569     } catch (const Xapian::InvalidArgumentError) {
570         /* We'll let the philosopher's try to wrestle with the
571          * question of whether failing to remove that which was not
572          * there in the first place is failure. For us, we'll silently
573          * consider it all good. */
574     }
575
576     talloc_free (term);
577
578     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
579 }
580
581 notmuch_status_t
582 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
583 {
584     notmuch_private_status_t status;
585
586     if (tag == NULL)
587         return NOTMUCH_STATUS_NULL_POINTER;
588
589     if (strlen (tag) > NOTMUCH_TAG_MAX)
590         return NOTMUCH_STATUS_TAG_TOO_LONG;
591
592     status = _notmuch_message_add_term (message, "tag", tag);
593     if (status) {
594         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
595                         status);
596     }
597
598     if (! message->frozen)
599         _notmuch_message_sync (message);
600
601     return NOTMUCH_STATUS_SUCCESS;
602 }
603
604 notmuch_status_t
605 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
606 {
607     notmuch_private_status_t status;
608
609     if (tag == NULL)
610         return NOTMUCH_STATUS_NULL_POINTER;
611
612     if (strlen (tag) > NOTMUCH_TAG_MAX)
613         return NOTMUCH_STATUS_TAG_TOO_LONG;
614
615     status = _notmuch_message_remove_term (message, "tag", tag);
616     if (status) {
617         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
618                         status);
619     }
620
621     if (! message->frozen)
622         _notmuch_message_sync (message);
623
624     return NOTMUCH_STATUS_SUCCESS;
625 }
626
627 void
628 notmuch_message_remove_all_tags (notmuch_message_t *message)
629 {
630     notmuch_private_status_t status;
631     notmuch_tags_t *tags;
632     const char *tag;
633
634     for (tags = notmuch_message_get_tags (message);
635          notmuch_tags_has_more (tags);
636          notmuch_tags_advance (tags))
637     {
638         tag = notmuch_tags_get (tags);
639
640         status = _notmuch_message_remove_term (message, "tag", tag);
641         if (status) {
642             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
643                             status);
644         }
645     }
646
647     if (! message->frozen)
648         _notmuch_message_sync (message);
649 }
650
651 void
652 notmuch_message_freeze (notmuch_message_t *message)
653 {
654     message->frozen++;
655 }
656
657 notmuch_status_t
658 notmuch_message_thaw (notmuch_message_t *message)
659 {
660     if (message->frozen > 0) {
661         message->frozen--;
662         if (message->frozen == 0)
663             _notmuch_message_sync (message);
664         return NOTMUCH_STATUS_SUCCESS;
665     } else {
666         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
667     }
668 }
669
670 void
671 notmuch_message_destroy (notmuch_message_t *message)
672 {
673     talloc_free (message);
674 }