]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
notmuch-index-message: Use local-part of email addres in lieu of name.
[notmuch] / notmuch-index-message.cc
1 /*
2  * Copyright © 2009 Carl Worth
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see http://www.gnu.org/licenses/ .
16  *
17  * Author: Carl Worth <cworth@cworth.org>
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24 #include <time.h>
25
26 #include <iostream>
27
28 #include <gmime/gmime.h>
29
30 #include <xapian.h>
31
32 using namespace std;
33
34 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
35
36 /* Xapian complains if we provide a term longer than this. */
37 #define NOTMUCH_MAX_TERM 245
38
39 /* These prefix values are specifically chosen to be compatible
40  * with sup, (http://sup.rubyforge.org), written by
41  * William Morgan <wmorgan-sup@masanjin.net>, and released
42  * under the GNU GPL v2.
43  */
44
45 typedef struct {
46     const char *name;
47     const char *prefix;
48 } prefix_t;
49
50 prefix_t NORMAL_PREFIX[] = {
51     { "subject", "S" },
52     { "body", "B" },
53     { "from_name", "FN" },
54     { "to_name", "TN" },
55     { "name", "N" },
56     { "attachment", "A" }
57 };
58
59 prefix_t BOOLEAN_PREFIX[] = {
60     { "type", "K" },
61     { "from_email", "FE" },
62     { "to_email", "TE" },
63     { "email", "E" },
64     { "date", "D" },
65     { "label", "L" },
66     { "source_id", "I" },
67     { "attachment_extension", "O" },
68     { "msgid", "Q" },
69     { "thread", "H" },
70     { "ref", "R" }
71 };
72
73 /* Similarly, these value numbers are also chosen to be sup
74  * compatible. */
75
76 typedef enum {
77     NOTMUCH_VALUE_MESSAGE_ID = 0,
78     NOTMUCH_VALUE_THREAD = 1,
79     NOTMUCH_VALUE_DATE = 2
80 } notmuch_value_t;
81
82 static const char *
83 find_prefix (const char *name)
84 {
85     unsigned int i;
86
87     for (i = 0; i < ARRAY_SIZE (NORMAL_PREFIX); i++)
88         if (strcmp (name, NORMAL_PREFIX[i].name) == 0)
89             return NORMAL_PREFIX[i].prefix;
90
91     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX); i++)
92         if (strcmp (name, BOOLEAN_PREFIX[i].name) == 0)
93             return BOOLEAN_PREFIX[i].prefix;
94
95     return "";
96 }
97
98 int TERM_COMBINED = 0;
99
100 static void
101 add_term (Xapian::Document doc,
102           const char *prefix_name,
103           const char *value)
104 {
105     const char *prefix;
106     char *term;
107
108     if (value == NULL)
109         return;
110
111     prefix = find_prefix (prefix_name);
112
113     term = g_strdup_printf ("%s%s", prefix, value);
114
115     if (strlen (term) <= NOTMUCH_MAX_TERM)
116         doc.add_term (term);
117
118     g_free (term);
119 }
120
121 static void
122 gen_terms (Xapian::TermGenerator term_gen,
123            const char *prefix_name,
124            const char *text)
125 {
126     const char *prefix;
127
128     if (text == NULL)
129         return;
130
131     prefix = find_prefix (prefix_name);
132
133     term_gen.index_text (text, 1, prefix);
134 }
135
136 static void
137 gen_terms_address_name (Xapian::TermGenerator term_gen,
138                         InternetAddress *address,
139                         const char *prefix_name)
140 {
141     const char *name;
142     int own_name = 0;
143
144     name = internet_address_get_name (address);
145
146     /* In the absence of a name, we'll strip the part before the @
147      * from the address. */
148     if (! name) {
149         InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
150         const char *addr = internet_address_mailbox_get_addr (mailbox);
151         const char *at;
152
153         at = strchr (addr, '@');
154         if (at) {
155             name = strndup (addr, at - addr);
156             own_name = 1;
157         }
158     }
159
160     if (name)
161         gen_terms (term_gen, prefix_name, name);
162
163     if (own_name)
164         free ((void *) name);
165 }
166
167 static void
168 gen_terms_address_names (Xapian::TermGenerator term_gen,
169                          InternetAddressList *addresses,
170                          const char *address_type)
171 {
172     int i;
173     InternetAddress *address;
174
175     for (i = 0; i < internet_address_list_length (addresses); i++) {
176         address = internet_address_list_get_address (addresses, i);
177         gen_terms_address_name (term_gen, address, address_type);
178         gen_terms_address_name (term_gen, address, "name");
179         gen_terms_address_name (term_gen, address, "body");
180     }
181 }
182
183 static void
184 add_term_address_addr (Xapian::Document doc,
185                        InternetAddress *address,
186                        const char *prefix_name)
187 {
188     InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
189     const char *addr;
190
191     addr = internet_address_mailbox_get_addr (mailbox);
192
193     if (addr)
194         add_term (doc, prefix_name, addr);
195 }
196
197 static void
198 add_terms_address_addrs (Xapian::Document doc,
199                          InternetAddressList *addresses,
200                          const char *address_type)
201 {
202     int i;
203     InternetAddress *address;
204
205     for (i = 0; i < internet_address_list_length (addresses); i++) {
206         address = internet_address_list_get_address (addresses, i);
207         add_term_address_addr (doc, address, address_type);
208         add_term_address_addr (doc, address, "email");
209     }
210 }
211
212 static const char *
213 skip_re_in_subject (const char *subject)
214 {
215     const char *s = subject;
216
217     while (*s) {
218         while (*s && isspace (*s))
219             s++;
220         if (strncasecmp (s, "re:", 3) == 0)
221             s += 3;
222         else
223             break;
224     }
225
226     return s;
227 }
228
229 static void
230 find_messages_by_term (Xapian::Database db,
231                        const char *prefix_name,
232                        const char *value,
233                        Xapian::PostingIterator *begin,
234                        Xapian::PostingIterator *end)
235 {
236     Xapian::PostingIterator i;
237     char *term;
238
239     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
240
241     *begin = db.postlist_begin (term);
242
243     if (end)
244         *end = db.postlist_end (term);
245
246     free (term);
247 }
248
249 Xapian::Document
250 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
251 {
252     return db.get_document (docid);
253 }
254
255 Xapian::Document
256 find_message_by_message_id (Xapian::Database db, const char *message_id)
257 {
258     Xapian::PostingIterator i, end;
259
260     find_messages_by_term (db, "msgid", message_id, &i, &end);
261
262     if (i != end)
263         return find_message_by_docid (db, *i);
264     else
265         return Xapian::Document ();
266 }
267
268 static void
269 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
270 {
271     string value_string;
272     const char *value;
273
274     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
275     value = value_string.c_str();
276     if (strlen (value))
277         g_hash_table_insert (thread_ids, strdup (value), NULL);
278 }
279
280 static char *
281 find_thread_id (Xapian::Database db,
282                 GPtrArray *parents,
283                 const char *message_id)
284 {
285     Xapian::PostingIterator child, children_end;
286     Xapian::Document doc;
287     GHashTable *thread_ids;
288     GList *keys, *l;
289     GString *result = NULL;
290     unsigned int i;
291     const char *parent_message_id;
292
293     thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
294
295     find_messages_by_term (db, "ref", message_id, &child, &children_end);
296     for ( ; child != children_end; child++) {
297         doc = find_message_by_docid (db, *child);
298         insert_thread_id (thread_ids, doc);
299     }
300
301     for (i = 0; i < parents->len; i++) {
302         parent_message_id = (char *) g_ptr_array_index (parents, i);
303         doc = find_message_by_message_id (db, parent_message_id);
304         insert_thread_id (thread_ids, doc);
305     }
306
307     keys = g_hash_table_get_keys (thread_ids);
308     for (l = keys; l; l = l->next) {
309         char *id = (char *) l->data;
310         if (result == NULL) {
311             result = g_string_new (id);
312         } else {
313             g_string_append_printf (result, ",%s", id);
314         }
315         free (id);
316     }
317
318     if (result)
319         return g_string_free (result, FALSE);
320     else
321         return NULL;
322 }
323
324 /* Add a term for each message-id in the References header of the
325  * message. */
326 static void
327 parse_references (GPtrArray *array,
328                   const char *refs_str)
329 {
330     GMimeReferences *refs, *r;
331     const char *message_id;
332
333     if (refs_str == NULL)
334         return;
335
336     refs = g_mime_references_decode (refs_str);
337
338     for (r = refs; r; r = r->next) {
339         message_id = g_mime_references_get_message_id (r);
340         g_ptr_array_add (array, g_strdup (message_id));
341     }
342
343     g_mime_references_free (refs);
344 }
345
346 /* Given a string representing the body of a message, generate terms
347  * for it, (skipping quoted portions and signatures). */
348 static void
349 gen_terms_body_str (Xapian::TermGenerator term_gen,
350                     char *body)
351 {
352     char *line, *line_end, *next_line;
353
354     if (body == NULL)
355         return;
356
357     next_line = body;
358
359     while (1) {
360         line = next_line;
361         if (*line == '\0')
362             break;
363
364         next_line = strchr (line, '\n');
365         if (next_line == NULL) {
366             next_line = line + strlen (line);
367         }
368         line_end = next_line - 1;
369
370         /* Trim whitespace. */
371         while (*next_line && isspace (*next_line))
372             next_line++;
373
374         /* Skip lines that are quotes. */
375         if (*line == '>')
376             continue;
377
378         /* Also skip lines introducing a quote on the next line. */
379         while (line_end > line && isspace (*line_end))
380             line_end--;
381
382         if (*line_end == ':' && *next_line == '>')
383             continue;
384
385         /* Finally, bail as soon as we see a signature. */
386         /* XXX: Should only do this if "near" the end of the message. */
387         if (strncmp (line, "-- ", 3) == 0 ||
388             strncmp (line, "----------", 10) == 0 ||
389             strncmp (line, "__________", 10) == 0)
390             break;
391
392         *(line_end + 1) = '\0';
393         gen_terms (term_gen, "body", line);
394     }
395 }
396
397
398 /* Callback to generate terms for each mime part of a message. */
399 static void
400 gen_terms_part (GMimeObject *parent,
401                 GMimeObject *part,
402                 gpointer user_data)
403 {
404     Xapian::TermGenerator *term_gen = (Xapian::TermGenerator *) user_data;
405     GMimeStream *stream;
406     GMimeDataWrapper *wrapper;
407     GByteArray *byte_array;
408     char *body;
409
410     if (! GMIME_IS_PART (part)) {
411         fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
412                  g_type_name (G_OBJECT_TYPE (part)));
413         return;
414     }
415
416     byte_array = g_byte_array_new ();
417
418     stream = g_mime_stream_mem_new_with_byte_array (byte_array);
419     g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
420     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
421     g_mime_data_wrapper_write_to_stream (wrapper, stream);
422
423     g_object_unref (stream);
424
425     body = (char *) g_byte_array_free (byte_array, FALSE);
426
427     gen_terms_body_str (*term_gen, body);
428
429     free (body);
430 }
431
432 static void
433 index_file (Xapian::WritableDatabase db,
434             Xapian::TermGenerator term_gen,
435             const char *filename)
436 {
437     Xapian::Document doc;
438
439     GMimeStream *stream;
440     GMimeParser *parser;
441     GMimeMessage *message;
442     InternetAddressList *addresses;
443     GPtrArray *parents;
444
445     FILE *file;
446
447     const char *subject, *refs, *in_reply_to, *from;
448     const char *message_id, *thread_id;
449
450     time_t time;
451     struct tm gm_time_tm;
452     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
453     unsigned int i;
454
455     file = fopen (filename, "r");
456     if (! file) {
457         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
458         exit (1);
459     }
460
461     stream = g_mime_stream_file_new (file);
462
463     parser = g_mime_parser_new_with_stream (stream);
464
465     message = g_mime_parser_construct_message (parser);
466
467     doc = Xapian::Document ();
468
469     doc.set_data (filename);
470
471     term_gen.set_stemmer (Xapian::Stem ("english"));
472
473     term_gen.set_document (doc);
474
475     from = g_mime_message_get_sender (message);
476     addresses = internet_address_list_parse_string (from);
477
478     gen_terms_address_names (term_gen, addresses, "from_name");
479
480     addresses = g_mime_message_get_all_recipients (message);
481     gen_terms_address_names (term_gen, addresses, "to_name");
482
483     subject = g_mime_message_get_subject (message);
484     subject = skip_re_in_subject (subject);
485     gen_terms (term_gen, "subject", subject);
486     gen_terms (term_gen, "body", subject);
487
488     g_mime_message_foreach (message, gen_terms_part, &term_gen);
489
490     parents = g_ptr_array_new ();
491
492     refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
493     parse_references (parents, refs);
494
495     in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
496                                             "in-reply-to");
497     parse_references (parents, in_reply_to);
498
499     for (i = 0; i < parents->len; i++)
500         add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
501
502     message_id = g_mime_message_get_message_id (message);
503
504     thread_id = find_thread_id (db, parents, message_id);
505
506     for (i = 0; i < parents->len; i++)
507         g_free (g_ptr_array_index (parents, i));
508     g_ptr_array_free (parents, TRUE);
509
510     from = g_mime_message_get_sender (message);
511     addresses = internet_address_list_parse_string (from);
512
513     add_terms_address_addrs (doc, addresses, "from_email");
514
515     add_terms_address_addrs (doc,
516                              g_mime_message_get_all_recipients (message),
517                              "to_email");
518
519     g_mime_message_get_date (message, &time, NULL);
520
521     gmtime_r (&time, &gm_time_tm);
522
523     if (strftime (date_str, sizeof (date_str),
524                   "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
525         fprintf (stderr, "Internal error formatting time\n");
526         exit (1);
527     }
528
529     add_term (doc, "date", date_str);
530
531     add_term (doc, "label", "inbox");
532     add_term (doc, "label", "unread");
533     add_term (doc, "type", "mail");
534     add_term (doc, "source_id", "1");
535
536     add_term (doc, "msgid", message_id);
537     doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
538
539     if (thread_id) {
540         add_term (doc, "thread", thread_id);
541         doc.add_value (NOTMUCH_VALUE_THREAD, thread_id);
542         free ((void *) thread_id);
543     } else {
544         /* If not referenced thread, use the message ID */
545         add_term (doc, "thread", message_id);
546         doc.add_value (NOTMUCH_VALUE_THREAD, message_id);
547     }
548
549     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
550
551     db.add_document (doc);
552
553     g_object_unref (message);
554     g_object_unref (parser);
555     g_object_unref (stream);
556 }
557
558 static void
559 usage (const char *argv0)
560 {
561     fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
562     fprintf (stderr, "\n");
563     fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
564     fprintf (stderr, "one file per line.");
565 }
566
567 int
568 main (int argc, char **argv)
569 {
570     const char *database_path;
571     char *filename;
572     GIOChannel *channel;
573     GIOStatus gio_status;
574     GError *error = NULL;
575
576     if (argc < 2) {
577         usage (argv[0]);
578         exit (1);
579     }
580
581     database_path = argv[1];
582
583     g_mime_init (0);
584
585     try {
586         Xapian::WritableDatabase db;
587         Xapian::TermGenerator term_gen;
588
589         db = Xapian::WritableDatabase (database_path,
590                                        Xapian::DB_CREATE_OR_OPEN);
591
592         term_gen = Xapian::TermGenerator ();
593
594         channel = g_io_channel_unix_new (fileno (stdin));
595
596         while (1) {
597             gio_status = g_io_channel_read_line (channel, &filename,
598                                                  NULL, NULL, &error);
599             if (gio_status == G_IO_STATUS_EOF)
600                 break;
601             if (gio_status != G_IO_STATUS_NORMAL) {
602                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
603                          error->message);
604                 exit (1);
605             }
606
607             g_strchomp (filename);
608             index_file (db, term_gen, filename);
609
610             g_free (filename);
611         }
612
613     } catch (const Xapian::Error &error) {
614         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
615         exit (1);
616     }
617
618     return 0;
619 }