]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
f7ea340f977329d5da7354a2a613ec5766259720
[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
143     name = internet_address_get_name (address);
144
145     if (name)
146         gen_terms (term_gen, prefix_name, name);
147 }
148
149 static void
150 gen_terms_address_names (Xapian::TermGenerator term_gen,
151                          InternetAddressList *addresses,
152                          const char *address_type)
153 {
154     int i;
155     InternetAddress *address;
156
157     for (i = 0; i < internet_address_list_length (addresses); i++) {
158         address = internet_address_list_get_address (addresses, i);
159         gen_terms_address_name (term_gen, address, address_type);
160         gen_terms_address_name (term_gen, address, "name");
161         gen_terms_address_name (term_gen, address, "body");
162     }
163 }
164
165 static void
166 add_term_address_addr (Xapian::Document doc,
167                        InternetAddress *address,
168                        const char *prefix_name)
169 {
170     InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
171     const char *addr;
172
173     addr = internet_address_mailbox_get_addr (mailbox);
174
175     if (addr)
176         add_term (doc, prefix_name, addr);
177 }
178
179 static void
180 add_terms_address_addrs (Xapian::Document doc,
181                          InternetAddressList *addresses,
182                          const char *address_type)
183 {
184     int i;
185     InternetAddress *address;
186
187     for (i = 0; i < internet_address_list_length (addresses); i++) {
188         address = internet_address_list_get_address (addresses, i);
189         add_term_address_addr (doc, address, address_type);
190         add_term_address_addr (doc, address, "email");
191     }
192 }
193
194 static const char *
195 skip_re_in_subject (const char *subject)
196 {
197     const char *s = subject;
198
199     while (*s) {
200         while (*s && isspace (*s))
201             s++;
202         if (strncasecmp (s, "re:", 3) == 0)
203             s += 3;
204         else
205             break;
206     }
207
208     return s;
209 }
210
211 static void
212 find_messages_by_term (Xapian::Database db,
213                        const char *prefix_name,
214                        const char *value,
215                        Xapian::PostingIterator *begin,
216                        Xapian::PostingIterator *end)
217 {
218     Xapian::PostingIterator i;
219     char *term;
220
221     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
222
223     *begin = db.postlist_begin (term);
224
225     if (end)
226         *end = db.postlist_end (term);
227
228     free (term);
229 }
230
231 Xapian::Document
232 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
233 {
234     return db.get_document (docid);
235 }
236
237 Xapian::Document
238 find_message_by_message_id (Xapian::Database db, const char *message_id)
239 {
240     Xapian::PostingIterator i, end;
241
242     find_messages_by_term (db, "msgid", message_id, &i, &end);
243
244     if (i != end)
245         return find_message_by_docid (db, *i);
246     else
247         return Xapian::Document ();
248 }
249
250 static void
251 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
252 {
253     string value_string;
254     const char *value;
255
256     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
257     value = value_string.c_str();
258     if (strlen (value))
259         g_hash_table_insert (thread_ids, strdup (value), NULL);
260 }
261
262 static char *
263 find_thread_id (Xapian::Database db,
264                 GPtrArray *parents,
265                 const char *message_id)
266 {
267     Xapian::PostingIterator child, children_end;
268     Xapian::Document doc;
269     GHashTable *thread_ids;
270     GList *keys, *l;
271     GString *result = NULL;
272     unsigned int i;
273     const char *parent_message_id;
274
275     thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
276
277     find_messages_by_term (db, "ref", message_id, &child, &children_end);
278     for ( ; child != children_end; child++) {
279         doc = find_message_by_docid (db, *child);
280         insert_thread_id (thread_ids, doc);
281     }
282
283     for (i = 0; i < parents->len; i++) {
284         parent_message_id = (char *) g_ptr_array_index (parents, i);
285         doc = find_message_by_message_id (db, parent_message_id);
286         insert_thread_id (thread_ids, doc);
287     }
288
289     keys = g_hash_table_get_keys (thread_ids);
290     for (l = keys; l; l = l->next) {
291         char *id = (char *) l->data;
292         if (result == NULL) {
293             result = g_string_new (id);
294         } else {
295             g_string_append_printf (result, ",%s", id);
296         }
297         free (id);
298     }
299
300     if (result)
301         return g_string_free (result, FALSE);
302     else
303         return NULL;
304 }
305
306 /* Add a term for each message-id in the References header of the
307  * message. */
308 static void
309 parse_references (GPtrArray *array,
310                   const char *refs)
311 {
312     const char *end, *next;
313
314     if (refs == NULL)
315         return;
316
317     while (*refs) {
318         while (*refs && isspace (*refs))
319             refs++;
320         if (*refs == '<')
321             refs++;
322         end = refs;
323         while (*end && !isspace (*end))
324             end++;
325         next = end;
326         end--;
327         if (end > refs && *end == '>')
328             end--;
329         if (end > refs) {
330             g_ptr_array_add (array, g_strndup (refs, end - refs + 1));
331         }
332         refs = next;
333     }
334 }
335
336 /* Given a string representing the body of a message, generate terms
337  * for it, (skipping quoted portions and signatures). */
338 static void
339 gen_terms_body_str (Xapian::TermGenerator term_gen,
340                     char *body)
341 {
342     char *line, *line_end, *next_line;
343
344     if (body == NULL)
345         return;
346
347     next_line = body;
348
349     while (1) {
350         line = next_line;
351         if (*line == '\0')
352             break;
353
354         next_line = strchr (line, '\n');
355         if (next_line == NULL) {
356             next_line = line + strlen (line);
357         }
358         line_end = next_line - 1;
359
360         /* Trim whitespace. */
361         while (*next_line && isspace (*next_line))
362             next_line++;
363
364         /* Skip lines that are quotes. */
365         if (*line == '>')
366             continue;
367
368         /* Also skip lines introducing a quote on the next line. */
369         while (line_end > line && isspace (*line_end))
370             line_end--;
371
372         if (*line_end == ':' && *next_line == '>')
373             continue;
374
375         /* Finally, bail as soon as we see a signature. */
376         /* XXX: Should only do this if "near" the end of the message. */
377         if (strncmp (line, "-- ", 3) == 0 ||
378             strncmp (line, "----------", 10) == 0 ||
379             strncmp (line, "__________", 10) == 0)
380             break;
381
382         *(line_end + 1) = '\0';
383         gen_terms (term_gen, "body", line);
384     }
385 }
386
387
388 /* Callback to generate terms for each mime part of a message. */
389 static void
390 gen_terms_part (GMimeObject *parent,
391                 GMimeObject *part,
392                 gpointer user_data)
393 {
394     Xapian::TermGenerator *term_gen = (Xapian::TermGenerator *) user_data;
395     GMimeStream *stream;
396     GMimeDataWrapper *wrapper;
397     GByteArray *byte_array;
398     char *body;
399
400     if (! GMIME_IS_PART (part)) {
401         fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
402                  g_type_name (G_OBJECT_TYPE (part)));
403         return;
404     }
405
406     byte_array = g_byte_array_new ();
407
408     stream = g_mime_stream_mem_new_with_byte_array (byte_array);
409     g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
410     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
411     g_mime_data_wrapper_write_to_stream (wrapper, stream);
412
413     g_object_unref (stream);
414
415     body = (char *) g_byte_array_free (byte_array, FALSE);
416
417     gen_terms_body_str (*term_gen, body);
418
419     free (body);
420 }
421
422 static void
423 index_file (Xapian::WritableDatabase db,
424             Xapian::TermGenerator term_gen,
425             const char *filename)
426 {
427     Xapian::Document doc;
428
429     GMimeStream *stream;
430     GMimeParser *parser;
431     GMimeMessage *message;
432     InternetAddressList *addresses;
433     GPtrArray *parents;
434
435     FILE *file;
436
437     const char *subject, *refs, *in_reply_to, *from;
438     const char *message_id, *thread_id;
439
440     time_t time;
441     struct tm gm_time_tm;
442     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
443     unsigned int i;
444
445     file = fopen (filename, "r");
446     if (! file) {
447         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
448         exit (1);
449     }
450
451     stream = g_mime_stream_file_new (file);
452
453     parser = g_mime_parser_new_with_stream (stream);
454
455     message = g_mime_parser_construct_message (parser);
456
457     doc = Xapian::Document ();
458
459     doc.set_data (filename);
460
461     term_gen.set_stemmer (Xapian::Stem ("english"));
462
463     term_gen.set_document (doc);
464
465     from = g_mime_message_get_sender (message);
466     addresses = internet_address_list_parse_string (from);
467
468     gen_terms_address_names (term_gen, addresses, "from_name");
469
470     addresses = g_mime_message_get_all_recipients (message);
471     gen_terms_address_names (term_gen, addresses, "to_name");
472
473     subject = g_mime_message_get_subject (message);
474     subject = skip_re_in_subject (subject);
475     gen_terms (term_gen, "subject", subject);
476     gen_terms (term_gen, "body", subject);
477
478     g_mime_message_foreach (message, gen_terms_part, &term_gen);
479
480     parents = g_ptr_array_new ();
481
482     refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
483     parse_references (parents, refs);
484
485     in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
486                                             "in-reply-to");
487     parse_references (parents, in_reply_to);
488
489     for (i = 0; i < parents->len; i++)
490         add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
491
492     message_id = g_mime_message_get_message_id (message);
493
494     thread_id = find_thread_id (db, parents, message_id);
495
496     for (i = 0; i < parents->len; i++)
497         g_free (g_ptr_array_index (parents, i));
498     g_ptr_array_free (parents, TRUE);
499
500     from = g_mime_message_get_sender (message);
501     addresses = internet_address_list_parse_string (from);
502
503     add_terms_address_addrs (doc, addresses, "from_email");
504
505     add_terms_address_addrs (doc,
506                              g_mime_message_get_all_recipients (message),
507                              "to_email");
508
509     g_mime_message_get_date (message, &time, NULL);
510
511     gmtime_r (&time, &gm_time_tm);
512
513     if (strftime (date_str, sizeof (date_str),
514                   "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
515         fprintf (stderr, "Internal error formatting time\n");
516         exit (1);
517     }
518
519     add_term (doc, "date", date_str);
520
521     add_term (doc, "label", "inbox");
522     add_term (doc, "label", "unread");
523     add_term (doc, "type", "mail");
524     add_term (doc, "source_id", "1");
525
526     add_term (doc, "msgid", message_id);
527     doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
528
529     if (thread_id) {
530         add_term (doc, "thread", thread_id);
531         doc.add_value (NOTMUCH_VALUE_THREAD, thread_id);
532         free ((void *) thread_id);
533     } else {
534         /* If not referenced thread, use the message ID */
535         add_term (doc, "thread", message_id);
536         doc.add_value (NOTMUCH_VALUE_THREAD, message_id);
537     }
538
539     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
540
541     db.add_document (doc);
542
543     g_object_unref (message);
544     g_object_unref (parser);
545     g_object_unref (stream);
546 }
547
548 static void
549 usage (const char *argv0)
550 {
551     fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
552     fprintf (stderr, "\n");
553     fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
554     fprintf (stderr, "one file per line.");
555 }
556
557 int
558 main (int argc, char **argv)
559 {
560     const char *database_path;
561     char *filename;
562     GIOChannel *channel;
563     GIOStatus gio_status;
564     GError *error = NULL;
565
566     if (argc < 2) {
567         usage (argv[0]);
568         exit (1);
569     }
570
571     database_path = argv[1];
572
573     g_mime_init (0);
574
575     try {
576         Xapian::WritableDatabase db;
577         Xapian::TermGenerator term_gen;
578
579         db = Xapian::WritableDatabase (database_path,
580                                        Xapian::DB_CREATE_OR_OPEN);
581
582         term_gen = Xapian::TermGenerator ();
583
584         channel = g_io_channel_unix_new (fileno (stdin));
585
586         while (1) {
587             gio_status = g_io_channel_read_line (channel, &filename,
588                                                  NULL, NULL, &error);
589             if (gio_status == G_IO_STATUS_EOF)
590                 break;
591             if (gio_status != G_IO_STATUS_NORMAL) {
592                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
593                          error->message);
594                 exit (1);
595             }
596
597             g_strchomp (filename);
598             index_file (db, term_gen, filename);
599
600             g_free (filename);
601         }
602
603     } catch (const Xapian::Error &error) {
604         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
605         exit (1);
606     }
607
608     return 0;
609 }