]> git.notmuchmail.org Git - notmuch/blob - lib/thread.cc
Simple attempt to display author names in a friendlier way
[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 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 <xapian.h>
25
26 #include <gmime/gmime.h>
27 #include <glib.h> /* GHashTable */
28
29 struct _notmuch_thread {
30     notmuch_database_t *notmuch;
31     char *thread_id;
32     char *subject;
33     GHashTable *authors_hash;
34     char *authors;
35     char *nonmatched_authors;
36     GHashTable *tags;
37
38     notmuch_message_list_t *message_list;
39     GHashTable *message_hash;
40     int total_messages;
41     int matched_messages;
42     time_t oldest;
43     time_t newest;
44 };
45
46 static int
47 _notmuch_thread_destructor (notmuch_thread_t *thread)
48 {
49     g_hash_table_unref (thread->authors_hash);
50     g_hash_table_unref (thread->tags);
51     g_hash_table_unref (thread->message_hash);
52
53     return 0;
54 }
55
56 static void
57 _thread_add_author (notmuch_thread_t *thread,
58                     const char *author)
59 {
60     if (author == NULL)
61         return;
62
63     if (g_hash_table_lookup_extended (thread->authors_hash,
64                                       author, NULL, NULL))
65         return;
66
67     g_hash_table_insert (thread->authors_hash, xstrdup (author), NULL);
68
69     if (thread->authors)
70         thread->authors = talloc_asprintf (thread, "%s, %s",
71                                            thread->authors,
72                                            author);
73     else
74         thread->authors = talloc_strdup (thread, author);
75 }
76
77 /*
78  * move authors of matched messages in the thread to
79  * the front of the authors list, but keep them in
80  * existing order within their group
81  */
82 static void
83 _thread_move_matched_author (notmuch_thread_t *thread,
84                              const char *author)
85 {
86     char *authors_copy;
87     char *current_author;
88     char *last_pipe,*next_pipe;
89     int idx,nm_start,author_len,authors_len;
90
91     if (thread->authors == NULL || author == NULL)
92         return;
93     if (thread->nonmatched_authors == NULL)
94         thread->nonmatched_authors = thread->authors;
95     author_len = strlen(author);
96     authors_len = strlen(thread->authors);
97     if (author_len == authors_len) {
98         /* just one author */
99         thread->nonmatched_authors += author_len;
100         return;
101     }
102     current_author = strcasestr(thread->authors, author);
103     if (current_author == NULL)
104         return;
105     /* how far inside the nonmatched authors is our author? */
106     idx = current_author - thread->nonmatched_authors;
107     if (idx < 0) {
108         /* already among matched authors */
109         return;
110     }
111     /* are there any authors in the list after our author? */
112     if (thread->nonmatched_authors + author_len < thread->authors + authors_len) {
113         /* we have to make changes, so let's get a temp copy */
114         authors_copy = talloc_strdup(thread,thread->authors);
115         /* nm_start is the offset into where the non-matched authors start */
116         nm_start = thread->nonmatched_authors - thread->authors;
117         /* copy this author and add the "| " - the if clause above tells us there's more */
118         strncpy(thread->nonmatched_authors,author,author_len);
119         strncpy(thread->nonmatched_authors+author_len,"| ",2);
120         thread->nonmatched_authors += author_len+2;
121         if (idx > 0) {
122           /* we are actually moving authors around, not just changing the separator
123            * first copy the authors that came BEFORE our author */
124           strncpy(thread->nonmatched_authors, authors_copy+nm_start, idx-2);
125           /* finally, if there are authors AFTER our author, copy those */
126           if(author_len+nm_start+idx < authors_len) {
127             strncpy(thread->nonmatched_authors + idx - 2,", ",2);
128             strncpy(thread->nonmatched_authors + idx, authors_copy+nm_start + idx + author_len + 2,
129                     authors_len - (nm_start + idx + author_len + 2));
130           }
131         }
132         /* finally let's make sure there's just one '|' in the authors string */
133         last_pipe = strchr(thread->authors,'|');
134         while (last_pipe) {
135             next_pipe = strchr(last_pipe+1,'|');
136             if (next_pipe)
137                 *last_pipe = ',';
138             last_pipe = next_pipe;
139         }
140     } else {
141         thread->nonmatched_authors += author_len;
142         /* so now all authors are matched - let's remove the '|' */
143         last_pipe = strchr(thread->authors,'|');
144         if (last_pipe)
145             *last_pipe = ',';
146     }
147     return;
148 }
149
150 /* clean up the uggly "Lastname, Firstname" format that some mail systems
151  * (most notably, Exchange) are creating to be "Firstname Lastname"
152  * To make sure that we don't change other potential situations where a
153  * comma is in the name, we check that we match one of these patterns
154  * "Last, First" <first.last@company.com>
155  * "Last, First MI" <first.mi.last@company.com>
156  */
157 char *
158 _thread_cleanup_author (notmuch_thread_t *thread,
159                         const char *author, const char *from)
160 {
161     char *clean_author,*test_author;
162     const char *comma;
163     char *blank;
164     int fname,lname;
165
166     clean_author = talloc_strdup(thread, author);
167     if (clean_author == NULL)
168         return NULL;
169     comma = strchr(author,',');
170     if (comma) {
171         /* let's assemble what we think is the correct name */
172         lname = comma - author;
173         fname = strlen(author) - lname - 2;
174         strncpy(clean_author, comma + 2, fname);
175         *(clean_author+fname) = ' ';
176         strncpy(clean_author + fname + 1, author, lname);
177         *(clean_author+fname+1+lname) = '\0';
178         /* make a temporary copy and see if it matches the email */
179         test_author = talloc_strdup(thread,clean_author);
180
181         blank=strchr(test_author,' ');
182         while (blank != NULL) {
183             *blank = '.';
184             blank=strchr(test_author,' ');
185         }
186         if (strcasestr(from, test_author) == NULL)
187             /* we didn't identify this as part of the email address
188             * so let's punt and return the original author */
189             strcpy (clean_author, author);
190
191     }
192     return clean_author;
193 }
194
195 /* Add 'message' as a message that belongs to 'thread'.
196  *
197  * The 'thread' will talloc_steal the 'message' and hold onto a
198  * reference to it.
199  */
200 static void
201 _thread_add_message (notmuch_thread_t *thread,
202                      notmuch_message_t *message)
203 {
204     notmuch_tags_t *tags;
205     const char *tag;
206     InternetAddressList *list = NULL;
207     InternetAddress *address;
208     const char *from, *author;
209     char *clean_author;
210
211     _notmuch_message_list_add_message (thread->message_list,
212                                        talloc_steal (thread, message));
213     thread->total_messages++;
214
215     g_hash_table_insert (thread->message_hash,
216                          xstrdup (notmuch_message_get_message_id (message)),
217                          message);
218
219     from = notmuch_message_get_header (message, "from");
220     if (from)
221         list = internet_address_list_parse_string (from);
222
223     if (list) {
224         address = internet_address_list_get_address (list, 0);
225         if (address) {
226             author = internet_address_get_name (address);
227             if (author == NULL) {
228                 InternetAddressMailbox *mailbox;
229                 mailbox = INTERNET_ADDRESS_MAILBOX (address);
230                 author = internet_address_mailbox_get_addr (mailbox);
231             }
232             clean_author = _thread_cleanup_author (thread, author, from);
233             _thread_add_author (thread, clean_author);
234             notmuch_message_set_author (message, clean_author);
235         }
236         g_object_unref (G_OBJECT (list));
237     }
238
239     if (! thread->subject) {
240         const char *subject;
241         subject = notmuch_message_get_header (message, "subject");
242         thread->subject = talloc_strdup (thread, subject ? subject : "");
243     }
244
245     for (tags = notmuch_message_get_tags (message);
246          notmuch_tags_valid (tags);
247          notmuch_tags_move_to_next (tags))
248     {
249         tag = notmuch_tags_get (tags);
250         g_hash_table_insert (thread->tags, xstrdup (tag), NULL);
251     }
252 }
253
254 static void
255 _thread_set_subject_from_message (notmuch_thread_t *thread,
256                                   notmuch_message_t *message)
257 {
258     const char *subject;
259     const char *cleaned_subject;
260
261     subject = notmuch_message_get_header (message, "subject");
262     if (! subject)
263         return;
264
265     if ((strncasecmp (subject, "Re: ", 4) == 0) ||
266         (strncasecmp (subject, "Aw: ", 4) == 0) ||
267         (strncasecmp (subject, "Vs: ", 4) == 0) ||
268         (strncasecmp (subject, "Sv: ", 4) == 0)) {
269
270         cleaned_subject = talloc_strndup (thread,
271                                           subject + 4,
272                                           strlen(subject) - 4);
273     } else {
274         cleaned_subject = talloc_strdup (thread, subject);
275     }
276
277     if (thread->subject)
278         talloc_free (thread->subject);
279
280     thread->subject = talloc_strdup (thread, cleaned_subject);
281 }
282
283 static void
284 _thread_add_matched_message (notmuch_thread_t *thread,
285                              notmuch_message_t *message,
286                              notmuch_sort_t sort)
287 {
288     time_t date;
289     notmuch_message_t *hashed_message;
290
291     date = notmuch_message_get_date (message);
292
293     if (date < thread->oldest || ! thread->matched_messages)
294         thread->oldest = date;
295
296     if (date > thread->newest || ! thread->matched_messages)
297         thread->newest = date;
298
299     thread->matched_messages++;
300
301     if (g_hash_table_lookup_extended (thread->message_hash,
302                             notmuch_message_get_message_id (message), NULL,
303                             (void **) &hashed_message)) {
304         notmuch_message_set_flag (hashed_message,
305                                   NOTMUCH_MESSAGE_FLAG_MATCH, 1);
306     }
307     _thread_move_matched_author (thread,notmuch_message_get_author(hashed_message));
308
309     if ((sort == NOTMUCH_SORT_OLDEST_FIRST && date <= thread->newest) ||
310         (sort != NOTMUCH_SORT_OLDEST_FIRST && date == thread->newest))
311     {
312         _thread_set_subject_from_message (thread, message);
313     }
314 }
315
316 static void
317 _resolve_thread_relationships (unused (notmuch_thread_t *thread))
318 {
319     notmuch_message_node_t **prev, *node;
320     notmuch_message_t *message, *parent;
321     const char *in_reply_to;
322
323     prev = &thread->message_list->head;
324     while ((node = *prev)) {
325         message = node->message;
326         in_reply_to = _notmuch_message_get_in_reply_to (message);
327         if (in_reply_to && strlen (in_reply_to) &&
328             g_hash_table_lookup_extended (thread->message_hash,
329                                           in_reply_to, NULL,
330                                           (void **) &parent))
331         {
332             *prev = node->next;
333             if (thread->message_list->tail == &node->next)
334                 thread->message_list->tail = prev;
335             node->next = NULL;
336             _notmuch_message_add_reply (parent, node);
337         } else {
338             prev = &((*prev)->next);
339         }
340     }
341
342     /* XXX: After scanning through the entire list looking for parents
343      * via "In-Reply-To", we should do a second pass that looks at the
344      * list of messages IDs in the "References" header instead. (And
345      * for this the parent would be the "deepest" message of all the
346      * messages found in the "References" list.)
347      *
348      * Doing this will allow messages and sub-threads to be positioned
349      * correctly in the thread even when an intermediate message is
350      * missing from the thread.
351      */
352 }
353
354 /* Create a new notmuch_thread_t object for the given thread ID,
355  * treating any messages matching 'query_string' as "matched".
356  *
357  * Creating the thread will trigger two database searches. The first
358  * is for all messages belonging to the thread, (to get the first
359  * subject line, the total count of messages, and all authors). The
360  * second search is for all messages that are in the thread and that
361  * also match the given query_string. This is to allow for a separate
362  * count of matched messages, and to allow a viewer to display these
363  * messages differently.
364  *
365  * Here, 'ctx' is talloc context for the resulting thread object.
366  *
367  * This function returns NULL in the case of any error.
368  */
369 notmuch_thread_t *
370 _notmuch_thread_create (void *ctx,
371                         notmuch_database_t *notmuch,
372                         const char *thread_id,
373                         const char *query_string,
374                         notmuch_sort_t sort)
375 {
376     notmuch_thread_t *thread;
377     const char *thread_id_query_string;
378     notmuch_query_t *thread_id_query;
379
380     notmuch_messages_t *messages;
381     notmuch_message_t *message;
382     notmuch_bool_t matched_is_subset_of_thread;
383
384     thread_id_query_string = talloc_asprintf (ctx, "thread:%s", thread_id);
385     if (unlikely (query_string == NULL))
386         return NULL;
387
388     /* Under normal circumstances we need to do two database
389      * queries. One is for the thread itself (thread_id_query_string)
390      * and the second is to determine which messages in that thread
391      * match the original query (matched_query_string).
392      *
393      * But under two circumstances, we use only the
394      * thread_id_query_string:
395      *
396      *  1. If the original query_string *is* just the thread
397      *     specification.
398      *
399      *  2. If the original query_string matches all messages ("" or
400      *     "*").
401      *
402      * In either of these cases, we can be more efficient by running
403      * just the thread_id query (since we know all messages in the
404      * thread will match the query_string).
405      *
406      * Beyond the performance advantage, in the second case, it's
407      * important to not try to create a concatenated query because our
408      * parser handles "" and "*" as special cases and will not do the
409      * right thing with a query string of "* and thread:<foo>".
410      **/
411     matched_is_subset_of_thread = 1;
412     if (strcmp (query_string, thread_id_query_string) == 0 ||
413         strcmp (query_string, "") == 0 ||
414         strcmp (query_string, "*") == 0)
415     {
416         matched_is_subset_of_thread = 0;
417     }
418
419     thread_id_query = notmuch_query_create (notmuch, thread_id_query_string);
420     if (unlikely (thread_id_query == NULL))
421         return NULL;
422
423     thread = talloc (ctx, notmuch_thread_t);
424     if (unlikely (thread == NULL))
425         return NULL;
426
427     talloc_set_destructor (thread, _notmuch_thread_destructor);
428
429     thread->notmuch = notmuch;
430     thread->thread_id = talloc_strdup (thread, thread_id);
431     thread->subject = NULL;
432     thread->authors_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
433                                                   free, NULL);
434     thread->authors = NULL;
435     thread->nonmatched_authors = NULL;
436     thread->tags = g_hash_table_new_full (g_str_hash, g_str_equal,
437                                           free, NULL);
438
439     thread->message_list = _notmuch_message_list_create (thread);
440     if (unlikely (thread->message_list == NULL))
441         return NULL;
442
443     thread->message_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
444                                                   free, NULL);
445
446     thread->total_messages = 0;
447     thread->matched_messages = 0;
448     thread->oldest = 0;
449     thread->newest = 0;
450
451     notmuch_query_set_sort (thread_id_query, NOTMUCH_SORT_OLDEST_FIRST);
452
453     for (messages = notmuch_query_search_messages (thread_id_query);
454          notmuch_messages_valid (messages);
455          notmuch_messages_move_to_next (messages))
456     {
457         message = notmuch_messages_get (messages);
458
459         _thread_add_message (thread, message);
460
461         if (! matched_is_subset_of_thread)
462             _thread_add_matched_message (thread, message, sort);
463
464         _notmuch_message_close (message);
465     }
466
467     notmuch_query_destroy (thread_id_query);
468
469     if (matched_is_subset_of_thread)
470     {
471         const char *matched_query_string;
472         notmuch_query_t *matched_query;
473
474         matched_query_string = talloc_asprintf (ctx, "%s AND (%s)",
475                                                 thread_id_query_string,
476                                                 query_string);
477         if (unlikely (matched_query_string == NULL))
478             return NULL;
479
480         matched_query = notmuch_query_create (notmuch, matched_query_string);
481         if (unlikely (matched_query == NULL))
482             return NULL;
483
484         for (messages = notmuch_query_search_messages (matched_query);
485              notmuch_messages_valid (messages);
486              notmuch_messages_move_to_next (messages))
487         {
488             message = notmuch_messages_get (messages);
489             _thread_add_matched_message (thread, message, sort);
490             _notmuch_message_close (message);
491         }
492
493         notmuch_query_destroy (matched_query);
494     }
495
496     _resolve_thread_relationships (thread);
497
498     return thread;
499 }
500
501 notmuch_messages_t *
502 notmuch_thread_get_toplevel_messages (notmuch_thread_t *thread)
503 {
504     return _notmuch_messages_create (thread->message_list);
505 }
506
507 const char *
508 notmuch_thread_get_thread_id (notmuch_thread_t *thread)
509 {
510     return thread->thread_id;
511 }
512
513 int
514 notmuch_thread_get_total_messages (notmuch_thread_t *thread)
515 {
516     return thread->total_messages;
517 }
518
519 int
520 notmuch_thread_get_matched_messages (notmuch_thread_t *thread)
521 {
522     return thread->matched_messages;
523 }
524
525 const char *
526 notmuch_thread_get_authors (notmuch_thread_t *thread)
527 {
528     return thread->authors;
529 }
530
531 const char *
532 notmuch_thread_get_subject (notmuch_thread_t *thread)
533 {
534     return thread->subject;
535 }
536
537 time_t
538 notmuch_thread_get_oldest_date (notmuch_thread_t *thread)
539 {
540     return thread->oldest;
541 }
542
543 time_t
544 notmuch_thread_get_newest_date (notmuch_thread_t *thread)
545 {
546     return thread->newest;
547 }
548
549 notmuch_tags_t *
550 notmuch_thread_get_tags (notmuch_thread_t *thread)
551 {
552     notmuch_tags_t *tags;
553     GList *keys, *l;
554
555     tags = _notmuch_tags_create (thread);
556     if (unlikely (tags == NULL))
557         return NULL;
558
559     keys = g_hash_table_get_keys (thread->tags);
560
561     for (l = keys; l; l = l->next)
562         _notmuch_tags_add_tag (tags, (char *) l->data);
563
564     g_list_free (keys);
565
566     _notmuch_tags_prepare_iterator (tags);
567
568     return tags;
569 }
570
571 void
572 notmuch_thread_destroy (notmuch_thread_t *thread)
573 {
574     talloc_free (thread);
575 }