]> git.notmuchmail.org Git - notmuch/blob - lib/thread.cc
lib/thread: refactor in_reply_to test
[notmuch] / lib / thread.cc
1 /* thread.cc - Results of thread-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 https://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 #include <glib.h> /* GHashTable */
26
27 #ifdef DEBUG_THREADING
28 #define THREAD_DEBUG(format, ...) fprintf(stderr, format " (%s).\n", ##__VA_ARGS__, __location__)
29 #else
30 #define THREAD_DEBUG(format, ...) do {} while (0) /* ignored */
31 #endif
32
33 #define EMPTY_STRING(s) ((s)[0] == '\0')
34
35 struct _notmuch_thread {
36     notmuch_database_t *notmuch;
37     char *thread_id;
38     char *subject;
39     GHashTable *authors_hash;
40     GPtrArray *authors_array;
41     GHashTable *matched_authors_hash;
42     GPtrArray *matched_authors_array;
43     char *authors;
44     GHashTable *tags;
45
46     /* All messages, oldest first. */
47     notmuch_message_list_t *message_list;
48     /* Top-level messages, oldest first. */
49     notmuch_message_list_t *toplevel_list;
50
51     GHashTable *message_hash;
52     int total_messages;
53     int total_files;
54     int matched_messages;
55     time_t oldest;
56     time_t newest;
57 };
58
59 static int
60 _notmuch_thread_destructor (notmuch_thread_t *thread)
61 {
62     g_hash_table_unref (thread->authors_hash);
63     g_hash_table_unref (thread->matched_authors_hash);
64     g_hash_table_unref (thread->tags);
65     g_hash_table_unref (thread->message_hash);
66
67     if (thread->authors_array) {
68         g_ptr_array_free (thread->authors_array, true);
69         thread->authors_array = NULL;
70     }
71
72     if (thread->matched_authors_array) {
73         g_ptr_array_free (thread->matched_authors_array, true);
74         thread->matched_authors_array = NULL;
75     }
76
77     return 0;
78 }
79
80 /* Add each author of the thread to the thread's authors_hash and to
81  * the thread's authors_array. */
82 static void
83 _thread_add_author (notmuch_thread_t *thread,
84                     const char *author)
85 {
86     char *author_copy;
87
88     if (author == NULL)
89         return;
90
91     if (g_hash_table_lookup_extended (thread->authors_hash,
92                                       author, NULL, NULL))
93         return;
94
95     author_copy = talloc_strdup (thread, author);
96
97     g_hash_table_insert (thread->authors_hash, author_copy, NULL);
98
99     g_ptr_array_add (thread->authors_array, author_copy);
100 }
101
102 /* Add each matched author of the thread to the thread's
103  * matched_authors_hash and to the thread's matched_authors_array. */
104 static void
105 _thread_add_matched_author (notmuch_thread_t *thread,
106                             const char *author)
107 {
108     char *author_copy;
109
110     if (author == NULL)
111         return;
112
113     if (g_hash_table_lookup_extended (thread->matched_authors_hash,
114                                       author, NULL, NULL))
115         return;
116
117     author_copy = talloc_strdup (thread, author);
118
119     g_hash_table_insert (thread->matched_authors_hash, author_copy, NULL);
120
121     g_ptr_array_add (thread->matched_authors_array, author_copy);
122 }
123
124 /* Construct an authors string from matched_authors_array and
125  * authors_array. The string contains matched authors first, then
126  * non-matched authors (with the two groups separated by '|'). Within
127  * each group, authors are listed in date order. */
128 static void
129 _resolve_thread_authors_string (notmuch_thread_t *thread)
130 {
131     unsigned int i;
132     char *author;
133     int first_non_matched_author = 1;
134
135     /* First, list all matched authors in date order. */
136     for (i = 0; i < thread->matched_authors_array->len; i++) {
137         author = (char *) g_ptr_array_index (thread->matched_authors_array, i);
138         if (thread->authors)
139             thread->authors = talloc_asprintf (thread, "%s, %s",
140                                                thread->authors,
141                                                author);
142         else
143             thread->authors = author;
144     }
145
146     /* Next, append any non-matched authors that haven't already appeared. */
147     for (i = 0; i < thread->authors_array->len; i++) {
148         author = (char *) g_ptr_array_index (thread->authors_array, i);
149         if (g_hash_table_lookup_extended (thread->matched_authors_hash,
150                                           author, NULL, NULL))
151             continue;
152         if (first_non_matched_author) {
153             thread->authors = talloc_asprintf (thread, "%s| %s",
154                                                thread->authors,
155                                                author);
156         } else {
157             thread->authors = talloc_asprintf (thread, "%s, %s",
158                                                thread->authors,
159                                                author);
160         }
161
162         first_non_matched_author = 0;
163     }
164
165     g_ptr_array_free (thread->authors_array, true);
166     thread->authors_array = NULL;
167     g_ptr_array_free (thread->matched_authors_array, true);
168     thread->matched_authors_array = NULL;
169
170     if (!thread->authors)
171         thread->authors = talloc_strdup(thread, "");
172 }
173
174 /* clean up the ugly "Lastname, Firstname" format that some mail systems
175  * (most notably, Exchange) are creating to be "Firstname Lastname"
176  * To make sure that we don't change other potential situations where a
177  * comma is in the name, we check that we match one of these patterns
178  * "Last, First" <first.last@company.com>
179  * "Last, First MI" <first.mi.last@company.com>
180  */
181 static char *
182 _thread_cleanup_author (notmuch_thread_t *thread,
183                         const char *author, const char *from)
184 {
185     char *clean_author,*test_author;
186     const char *comma;
187     char *blank;
188     int fname,lname;
189
190     if (author == NULL)
191         return NULL;
192     clean_author = talloc_strdup(thread, author);
193     if (clean_author == NULL)
194         return NULL;
195     /* check if there's a comma in the name and that there's a
196      * component of the name behind it (so the name doesn't end with
197      * the comma - in which case the string that strchr finds is just
198      * one character long ",\0").
199      * Otherwise just return the copy of the original author name that
200      * we just made*/
201     comma = strchr(author,',');
202     if (comma && strlen(comma) > 1) {
203         /* let's assemble what we think is the correct name */
204         lname = comma - author;
205
206         /* Skip all the spaces after the comma */
207         fname = strlen(author) - lname - 1;
208         comma += 1;
209         while (*comma == ' ') {
210             fname -= 1;
211             comma += 1;
212         }
213         strncpy(clean_author, comma, fname);
214
215         *(clean_author+fname) = ' ';
216         strncpy(clean_author + fname + 1, author, lname);
217         *(clean_author+fname+1+lname) = '\0';
218         /* make a temporary copy and see if it matches the email */
219         test_author = talloc_strdup(thread,clean_author);
220
221         blank=strchr(test_author,' ');
222         while (blank != NULL) {
223             *blank = '.';
224             blank=strchr(test_author,' ');
225         }
226         if (strcasestr(from, test_author) == NULL)
227             /* we didn't identify this as part of the email address
228             * so let's punt and return the original author */
229             strcpy (clean_author, author);
230     }
231     return clean_author;
232 }
233
234 /* Add 'message' as a message that belongs to 'thread'.
235  *
236  * The 'thread' will talloc_steal the 'message' and hold onto a
237  * reference to it.
238  */
239 static void
240 _thread_add_message (notmuch_thread_t *thread,
241                      notmuch_message_t *message,
242                      notmuch_string_list_t *exclude_terms,
243                      notmuch_exclude_t omit_exclude)
244 {
245     notmuch_tags_t *tags;
246     const char *tag;
247     InternetAddressList *list = NULL;
248     InternetAddress *address;
249     const char *from, *author;
250     char *clean_author;
251     bool message_excluded = false;
252
253     if (omit_exclude != NOTMUCH_EXCLUDE_FALSE) {
254         for (tags = notmuch_message_get_tags (message);
255              notmuch_tags_valid (tags);
256              notmuch_tags_move_to_next (tags))
257         {
258             tag = notmuch_tags_get (tags);
259             /* Is message excluded? */
260             for (notmuch_string_node_t *term = exclude_terms->head;
261                  term != NULL;
262                  term = term->next)
263             {
264                 /* Check for an empty string, and then ignore initial 'K'. */
265                 if (*(term->string) && strcmp(tag, (term->string + 1)) == 0) {
266                     message_excluded = true;
267                     break;
268                 }
269             }
270         }
271     }
272
273     if (message_excluded && omit_exclude == NOTMUCH_EXCLUDE_ALL)
274         return;
275
276     _notmuch_message_list_add_message (thread->message_list,
277                                        talloc_steal (thread, message));
278     thread->total_messages++;
279     thread->total_files += notmuch_message_count_files (message);
280
281     g_hash_table_insert (thread->message_hash,
282                          xstrdup (notmuch_message_get_message_id (message)),
283                          message);
284
285     from = notmuch_message_get_header (message, "from");
286     if (from)
287         list = internet_address_list_parse_string (from);
288
289     if (list) {
290         address = internet_address_list_get_address (list, 0);
291         if (address) {
292             author = internet_address_get_name (address);
293             /* We treat quoted empty names as if they were empty. */
294             if (author == NULL || author[0] == '\0') {
295                 InternetAddressMailbox *mailbox;
296                 mailbox = INTERNET_ADDRESS_MAILBOX (address);
297                 author = internet_address_mailbox_get_addr (mailbox);
298             }
299             clean_author = _thread_cleanup_author (thread, author, from);
300             _thread_add_author (thread, clean_author);
301             _notmuch_message_set_author (message, clean_author);
302         }
303         g_object_unref (G_OBJECT (list));
304     }
305
306     if (! thread->subject) {
307         const char *subject;
308         subject = notmuch_message_get_header (message, "subject");
309         thread->subject = talloc_strdup (thread, subject ? subject : "");
310     }
311
312     for (tags = notmuch_message_get_tags (message);
313          notmuch_tags_valid (tags);
314          notmuch_tags_move_to_next (tags))
315     {
316         tag = notmuch_tags_get (tags);
317         g_hash_table_insert (thread->tags, xstrdup (tag), NULL);
318     }
319
320     /* Mark excluded messages. */
321     if (message_excluded)
322         notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED, true);
323 }
324
325 static void
326 _thread_set_subject_from_message (notmuch_thread_t *thread,
327                                   notmuch_message_t *message)
328 {
329     const char *subject;
330     const char *cleaned_subject;
331
332     subject = notmuch_message_get_header (message, "subject");
333     if (! subject)
334         return;
335
336     if ((strncasecmp (subject, "Re: ", 4) == 0) ||
337         (strncasecmp (subject, "Aw: ", 4) == 0) ||
338         (strncasecmp (subject, "Vs: ", 4) == 0) ||
339         (strncasecmp (subject, "Sv: ", 4) == 0)) {
340
341         cleaned_subject = talloc_strndup (thread,
342                                           subject + 4,
343                                           strlen(subject) - 4);
344     } else {
345         cleaned_subject = talloc_strdup (thread, subject);
346     }
347
348     if (! EMPTY_STRING(cleaned_subject)) {
349         if (thread->subject)
350             talloc_free (thread->subject);
351
352         thread->subject = talloc_strdup (thread, cleaned_subject);
353     }
354 }
355
356 /* Add a message to this thread which is known to match the original
357  * search specification. The 'sort' parameter controls whether the
358  * oldest or newest matching subject is applied to the thread as a
359  * whole. */
360 static void
361 _thread_add_matched_message (notmuch_thread_t *thread,
362                              notmuch_message_t *message,
363                              notmuch_sort_t sort)
364 {
365     time_t date;
366     notmuch_message_t *hashed_message;
367
368     date = notmuch_message_get_date (message);
369
370     if (date < thread->oldest || ! thread->matched_messages) {
371         thread->oldest = date;
372         if (sort == NOTMUCH_SORT_OLDEST_FIRST)
373             _thread_set_subject_from_message (thread, message);
374     }
375
376     if (date > thread->newest || ! thread->matched_messages) {
377         thread->newest = date;
378         const char *cur_subject = notmuch_thread_get_subject(thread);
379         if (sort != NOTMUCH_SORT_OLDEST_FIRST || EMPTY_STRING(cur_subject))
380             _thread_set_subject_from_message (thread, message);
381     }
382
383     if (!notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_EXCLUDED))
384         thread->matched_messages++;
385
386     if (g_hash_table_lookup_extended (thread->message_hash,
387                             notmuch_message_get_message_id (message), NULL,
388                             (void **) &hashed_message)) {
389         notmuch_message_set_flag (hashed_message,
390                                   NOTMUCH_MESSAGE_FLAG_MATCH, 1);
391     }
392
393     _thread_add_matched_author (thread, _notmuch_message_get_author (hashed_message));
394 }
395
396 static bool
397 _parent_via_in_reply_to (notmuch_thread_t *thread, notmuch_message_t *message) {
398     notmuch_message_t *parent;
399     const char *in_reply_to;
400
401     in_reply_to = _notmuch_message_get_in_reply_to (message);
402     THREAD_DEBUG("checking message = %s in_reply_to=%s\n",
403                  notmuch_message_get_message_id (message), in_reply_to);
404
405     if (in_reply_to && strlen (in_reply_to) &&
406         g_hash_table_lookup_extended (thread->message_hash,
407                                       in_reply_to, NULL,
408                                       (void **) &parent)) {
409         _notmuch_message_add_reply (parent, message);
410         return true;
411     } else {
412         return false;
413     }
414 }
415
416 static void
417 _resolve_thread_relationships (notmuch_thread_t *thread)
418 {
419     notmuch_message_node_t *node, *first_node;
420     notmuch_message_t *message;
421
422     first_node = thread->message_list->head;
423     if (! first_node)
424         return;
425
426     for (node = first_node->next; node; node = node->next) {
427         message = node->message;
428         if (! _parent_via_in_reply_to (thread, message))
429             _notmuch_message_list_add_message (thread->toplevel_list, message);
430     }
431
432     /*
433      * if we reach the end of the list without finding a top-level
434      * message, that means the thread is a cycle (or set of cycles)
435      * and any message can be considered top-level.  Choose the oldest
436      * message, which happens to be first in our list.
437      */
438     if (first_node) {
439         message = first_node->message;
440         if (_notmuch_message_list_empty(thread->toplevel_list) ||
441             ! _parent_via_in_reply_to (thread, message)) {
442             _notmuch_message_list_add_message (thread->toplevel_list, message);
443         }
444     }
445
446     /* XXX this could be made conditional on messages being inserted
447      * (out of order) in later passes
448      */
449     thread->toplevel_list = _notmuch_message_sort_subtrees (thread, thread->toplevel_list);
450
451
452     /* XXX: After scanning through the entire list looking for parents
453      * via "In-Reply-To", we should do a second pass that looks at the
454      * list of messages IDs in the "References" header instead. (And
455      * for this the parent would be the "deepest" message of all the
456      * messages found in the "References" list.)
457      *
458      * Doing this will allow messages and sub-threads to be positioned
459      * correctly in the thread even when an intermediate message is
460      * missing from the thread.
461      */
462 }
463
464 /* Create a new notmuch_thread_t object by finding the thread
465  * containing the message with the given doc ID, treating any messages
466  * contained in match_set as "matched".  Remove all messages in the
467  * thread from match_set.
468  *
469  * Creating the thread will perform a database search to get all
470  * messages belonging to the thread and will get the first subject
471  * line, the total count of messages, and all authors in the thread.
472  * Each message in the thread is checked against match_set to allow
473  * for a separate count of matched messages, and to allow a viewer to
474  * display these messages differently.
475  *
476  * Here, 'ctx' is talloc context for the resulting thread object.
477  *
478  * This function returns NULL in the case of any error.
479  */
480 notmuch_thread_t *
481 _notmuch_thread_create (void *ctx,
482                         notmuch_database_t *notmuch,
483                         unsigned int seed_doc_id,
484                         notmuch_doc_id_set_t *match_set,
485                         notmuch_string_list_t *exclude_terms,
486                         notmuch_exclude_t omit_excluded,
487                         notmuch_sort_t sort)
488 {
489     void *local = talloc_new (ctx);
490     notmuch_thread_t *thread = NULL;
491     notmuch_message_t *seed_message;
492     const char *thread_id;
493     char *thread_id_query_string;
494     notmuch_query_t *thread_id_query;
495
496     notmuch_messages_t *messages;
497     notmuch_message_t *message;
498     notmuch_status_t status;
499
500     seed_message = _notmuch_message_create (local, notmuch, seed_doc_id, NULL);
501     if (! seed_message)
502         INTERNAL_ERROR ("Thread seed message %u does not exist", seed_doc_id);
503
504     thread_id = notmuch_message_get_thread_id (seed_message);
505     thread_id_query_string = talloc_asprintf (local, "thread:%s", thread_id);
506     if (unlikely (thread_id_query_string == NULL))
507         goto DONE;
508
509     thread_id_query = talloc_steal (
510         local, notmuch_query_create (notmuch, thread_id_query_string));
511     if (unlikely (thread_id_query == NULL))
512         goto DONE;
513
514     thread = talloc (local, notmuch_thread_t);
515     if (unlikely (thread == NULL))
516         goto DONE;
517
518     talloc_set_destructor (thread, _notmuch_thread_destructor);
519
520     thread->notmuch = notmuch;
521     thread->thread_id = talloc_strdup (thread, thread_id);
522     thread->subject = NULL;
523     thread->authors_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
524                                                   NULL, NULL);
525     thread->authors_array = g_ptr_array_new ();
526     thread->matched_authors_hash = g_hash_table_new_full (g_str_hash,
527                                                           g_str_equal,
528                                                           NULL, NULL);
529     thread->matched_authors_array = g_ptr_array_new ();
530     thread->authors = NULL;
531     thread->tags = g_hash_table_new_full (g_str_hash, g_str_equal,
532                                           free, NULL);
533
534     thread->message_list = _notmuch_message_list_create (thread);
535     thread->toplevel_list = _notmuch_message_list_create (thread);
536     if (unlikely (thread->message_list == NULL ||
537                   thread->toplevel_list == NULL)) {
538         thread = NULL;
539         goto DONE;
540     }
541
542     thread->message_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
543                                                   free, NULL);
544
545     thread->total_messages = 0;
546     thread->total_files = 0;
547     thread->matched_messages = 0;
548     thread->oldest = 0;
549     thread->newest = 0;
550
551     /* We use oldest-first order unconditionally here to obtain the
552      * proper author ordering for the thread. The 'sort' parameter
553      * passed to this function is used only to indicate whether the
554      * oldest or newest subject is desired. */
555     notmuch_query_set_sort (thread_id_query, NOTMUCH_SORT_OLDEST_FIRST);
556
557     status = notmuch_query_search_messages (thread_id_query, &messages);
558     if (status)
559         goto DONE;
560
561     for (;
562          notmuch_messages_valid (messages);
563          notmuch_messages_move_to_next (messages))
564     {
565         unsigned int doc_id;
566
567         message = notmuch_messages_get (messages);
568         doc_id = _notmuch_message_get_doc_id (message);
569         if (doc_id == seed_doc_id)
570             message = seed_message;
571
572         _thread_add_message (thread, message, exclude_terms, omit_excluded);
573
574         if ( _notmuch_doc_id_set_contains (match_set, doc_id)) {
575             _notmuch_doc_id_set_remove (match_set, doc_id);
576             _thread_add_matched_message (thread, message, sort);
577         }
578
579         _notmuch_message_close (message);
580     }
581
582     _resolve_thread_authors_string (thread);
583
584     _resolve_thread_relationships (thread);
585
586     /* Commit to returning thread. */
587     (void) talloc_steal (ctx, thread);
588
589   DONE:
590     talloc_free (local);
591     return thread;
592 }
593
594 notmuch_messages_t *
595 notmuch_thread_get_toplevel_messages (notmuch_thread_t *thread)
596 {
597     return _notmuch_messages_create (thread->toplevel_list);
598 }
599
600 notmuch_messages_t *
601 notmuch_thread_get_messages (notmuch_thread_t *thread)
602 {
603     return _notmuch_messages_create (thread->message_list);
604 }
605
606 const char *
607 notmuch_thread_get_thread_id (notmuch_thread_t *thread)
608 {
609     return thread->thread_id;
610 }
611
612 int
613 notmuch_thread_get_total_messages (notmuch_thread_t *thread)
614 {
615     return thread->total_messages;
616 }
617
618 int
619 notmuch_thread_get_total_files (notmuch_thread_t *thread)
620 {
621     return thread->total_files;
622 }
623
624 int
625 notmuch_thread_get_matched_messages (notmuch_thread_t *thread)
626 {
627     return thread->matched_messages;
628 }
629
630 const char *
631 notmuch_thread_get_authors (notmuch_thread_t *thread)
632 {
633     return thread->authors;
634 }
635
636 const char *
637 notmuch_thread_get_subject (notmuch_thread_t *thread)
638 {
639     return thread->subject;
640 }
641
642 time_t
643 notmuch_thread_get_oldest_date (notmuch_thread_t *thread)
644 {
645     return thread->oldest;
646 }
647
648 time_t
649 notmuch_thread_get_newest_date (notmuch_thread_t *thread)
650 {
651     return thread->newest;
652 }
653
654 notmuch_tags_t *
655 notmuch_thread_get_tags (notmuch_thread_t *thread)
656 {
657     notmuch_string_list_t *tags;
658     GList *keys, *l;
659
660     tags = _notmuch_string_list_create (thread);
661     if (unlikely (tags == NULL))
662         return NULL;
663
664     keys = g_hash_table_get_keys (thread->tags);
665
666     for (l = keys; l; l = l->next)
667         _notmuch_string_list_append (tags, (char *) l->data);
668
669     g_list_free (keys);
670
671     _notmuch_string_list_sort (tags);
672
673     return _notmuch_tags_create (thread, tags);
674 }
675
676 void
677 notmuch_thread_destroy (notmuch_thread_t *thread)
678 {
679     talloc_free (thread);
680 }