]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
b8fa205b9cc474d5fc11d795d308f9933ae15007
[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 /* These prefix values are specifically chosen to be compatible
37  * with sup, (http://sup.rubyforge.org), written by
38  * William Morgan <wmorgan-sup@masanjin.net>, and released
39  * under the GNU GPL v2.
40  */
41
42 typedef struct {
43     const char *name;
44     const char *prefix;
45 } prefix_t;
46
47 prefix_t NORMAL_PREFIX[] = {
48     { "subject", "S" },
49     { "body", "B" },
50     { "from_name", "FN" },
51     { "to_name", "TN" },
52     { "name", "N" },
53     { "attachment", "A" }
54 };
55
56 prefix_t BOOLEAN_PREFIX[] = {
57     { "type", "K" },
58     { "from_email", "FE" },
59     { "to_email", "TE" },
60     { "email", "E" },
61     { "date", "D" },
62     { "label", "L" },
63     { "source_id", "I" },
64     { "attachment_extension", "O" },
65     { "msgid", "Q" },
66     { "thread", "H" },
67     { "ref", "R" }
68 };
69
70 /* Similarly, these value numbers are also chosen to be sup
71  * compatible. */
72
73 typedef enum {
74     NOTMUCH_VALUE_MESSAGE_ID = 0,
75     NOTMUCH_VALUE_THREAD = 1,
76     NOTMUCH_VALUE_DATE = 2
77 } notmuch_value_t;
78
79 static const char *
80 find_prefix (const char *name)
81 {
82     unsigned int i;
83
84     for (i = 0; i < ARRAY_SIZE (NORMAL_PREFIX); i++)
85         if (strcmp (name, NORMAL_PREFIX[i].name) == 0)
86             return NORMAL_PREFIX[i].prefix;
87
88     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX); i++)
89         if (strcmp (name, BOOLEAN_PREFIX[i].name) == 0)
90             return BOOLEAN_PREFIX[i].prefix;
91
92     return "";
93 }
94
95 int TERM_COMBINED = 0;
96
97 static void
98 add_term (Xapian::Document doc,
99           const char *prefix_name,
100           const char *value)
101 {
102     const char *prefix;
103     char *term;
104
105     if (value == NULL)
106         return;
107
108     prefix = find_prefix (prefix_name);
109
110     term = g_strdup_printf ("%s%s", prefix, value);
111
112     doc.add_term (term);
113
114     g_free (term);
115 }
116
117 static void
118 gen_terms (Xapian::TermGenerator term_gen,
119            const char *prefix_name,
120            const char *text)
121 {
122     const char *prefix;
123
124     if (text == NULL)
125         return;
126
127     prefix = find_prefix (prefix_name);
128
129     term_gen.index_text (text, 1, prefix);
130 }
131
132 static void
133 gen_terms_address_name (Xapian::TermGenerator term_gen,
134                         InternetAddress *address,
135                         const char *prefix_name)
136 {
137     const char *name;
138
139     name = internet_address_get_name (address);
140
141     if (name)
142         gen_terms (term_gen, prefix_name, name);
143 }
144
145 static void
146 gen_terms_address_names (Xapian::TermGenerator term_gen,
147                          InternetAddressList *addresses,
148                          const char *address_type)
149 {
150     int i;
151     InternetAddress *address;
152
153     for (i = 0; i < internet_address_list_length (addresses); i++) {
154         address = internet_address_list_get_address (addresses, i);
155         gen_terms_address_name (term_gen, address, address_type);
156         gen_terms_address_name (term_gen, address, "name");
157         gen_terms_address_name (term_gen, address, "body");
158     }
159 }
160
161 static void
162 add_term_address_addr (Xapian::Document doc,
163                        InternetAddress *address,
164                        const char *prefix_name)
165 {
166     InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
167     const char *addr;
168
169     addr = internet_address_mailbox_get_addr (mailbox);
170
171     if (addr)
172         add_term (doc, prefix_name, addr);
173 }
174
175 static void
176 add_terms_address_addrs (Xapian::Document doc,
177                          InternetAddressList *addresses,
178                          const char *address_type)
179 {
180     int i;
181     InternetAddress *address;
182
183     for (i = 0; i < internet_address_list_length (addresses); i++) {
184         address = internet_address_list_get_address (addresses, i);
185         add_term_address_addr (doc, address, address_type);
186         add_term_address_addr (doc, address, "email");
187     }
188 }
189
190 static const char *
191 skip_re_in_subject (const char *subject)
192 {
193     const char *s = subject;
194
195     while (*s) {
196         while (*s && isspace (*s))
197             s++;
198         if (strncasecmp (s, "re:", 3) == 0)
199             s += 3;
200         else
201             break;
202     }
203
204     return s;
205 }
206
207 /* Add a term for each message-id in the References header of the
208  * message. */
209 static void
210 parse_references (GPtrArray *array,
211                   const char *refs)
212 {
213     const char *end, *next;
214
215     if (refs == NULL)
216         return;
217
218     while (*refs) {
219         while (*refs && isspace (*refs))
220             refs++;
221         if (*refs == '<')
222             refs++;
223         end = refs;
224         while (*end && !isspace (*end))
225             end++;
226         next = end;
227         end--;
228         if (end > refs && *end == '>')
229             end--;
230         if (end > refs) {
231             g_ptr_array_add (array, g_strndup (refs, end - refs + 1));
232         }
233         refs = next;
234     }
235 }
236
237 /* Generate terms for the body of a message, given the filename of the
238  * message and the offset at which the headers of the message end,
239  * (and hence the body begins). */
240 static void
241 gen_terms_body (Xapian::TermGenerator term_gen,
242                 const char * filename,
243                 gint64 body_offset)
244 {
245     GIOChannel *channel;
246     GIOStatus gio_status;
247     GError *error = NULL;
248     char *p, *body_line = NULL, *prev_line = NULL;
249
250     channel = g_io_channel_new_file (filename, "r", &error);
251     if (channel == NULL) {
252         fprintf (stderr, "Error: %s\n", error->message);
253         exit (1);
254     }
255
256     gio_status = g_io_channel_seek_position (channel, body_offset,
257                                              G_SEEK_SET, &error);
258     if (gio_status != G_IO_STATUS_NORMAL) {
259         fprintf (stderr, "Error: %s\n", error->message);
260         exit (1);
261     }
262
263     while (1) {
264         if (body_line)
265             g_free (body_line);
266
267         gio_status = g_io_channel_read_line (channel, &body_line,
268                                              NULL, NULL, &error);
269         if (gio_status == G_IO_STATUS_EOF)
270             break;
271         if (gio_status != G_IO_STATUS_NORMAL) {
272             fprintf (stderr, "Error: %s\n", error->message);
273             exit (1);
274         }
275
276         if (strlen (body_line) == 0)
277             continue;
278
279         /* If the line looks like it might be introducing a quote,
280          * save it until we see if the next line begins a quote. */
281         p = body_line + strlen (body_line) - 1;
282         while (p > body_line and isspace (*p))
283             p--;
284         if (*p == ':') {
285             prev_line = body_line;
286             body_line = NULL;
287             continue;
288         }
289
290         /* Skip quoted lines, (and previous lines that introduced them) */
291         if (body_line[0] == '>') {
292             if (prev_line) {
293                 g_free (prev_line);
294                 prev_line = NULL;
295             }
296             continue;
297         }
298
299         /* Now that we're not looking at a quote we can add the prev_line */
300         if (prev_line) {
301             gen_terms (term_gen, "body", prev_line);
302             g_free (prev_line);
303             prev_line = NULL;
304         }
305
306         /* Skip signatures */
307         /* XXX: Should only do this if "near" the end of the message. */
308         if (strncmp (body_line, "-- ", 3) == 0 ||
309             strncmp (body_line, "----------", 10) == 0 ||
310             strncmp (body_line, "__________", 10) == 0)
311             break;
312
313         gen_terms (term_gen, "body", body_line);
314     }
315
316     if (body_line)
317         g_free (body_line);
318
319     g_io_channel_close (channel);
320 }
321
322 static void
323 index_file (Xapian::WritableDatabase db,
324             Xapian::TermGenerator term_gen,
325             const char *filename)
326 {
327     Xapian::Document doc;
328
329     GMimeStream *stream;
330     GMimeParser *parser;
331     GMimeMessage *message;
332     InternetAddressList *addresses;
333     GPtrArray *parents;
334
335     FILE *file;
336
337     const char *value, *from;
338
339     time_t time;
340     struct tm gm_time_tm;
341     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
342     unsigned int i;
343
344     file = fopen (filename, "r");
345     if (! file) {
346         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
347         exit (1);
348     }
349
350     stream = g_mime_stream_file_new (file);
351
352     parser = g_mime_parser_new_with_stream (stream);
353
354     message = g_mime_parser_construct_message (parser);
355
356     doc = Xapian::Document ();
357
358     doc.set_data (filename);
359
360     term_gen.set_stemmer (Xapian::Stem ("english"));
361
362     term_gen.set_document (doc);
363
364     from = g_mime_message_get_sender (message);
365     addresses = internet_address_list_parse_string (from);
366
367     gen_terms_address_names (term_gen, addresses, "from_name");
368
369     addresses = g_mime_message_get_all_recipients (message);
370     gen_terms_address_names (term_gen, addresses, "to_name");
371
372     value = g_mime_message_get_subject (message);
373     value = skip_re_in_subject (value);
374     gen_terms (term_gen, "subject", value);
375     gen_terms (term_gen, "body", value);
376
377     gen_terms_body (term_gen, filename,
378                     g_mime_parser_get_headers_end (parser));
379
380     parents = g_ptr_array_new ();
381
382     value = g_mime_object_get_header (GMIME_OBJECT (message), "references");
383     parse_references (parents, value);
384
385     value = g_mime_object_get_header (GMIME_OBJECT (message), "in-reply-to");
386     parse_references (parents, value);
387
388     for (i = 0; i < parents->len; i++)
389         add_term (doc, "ref", (const char *) g_ptr_array_index (parents, i));
390
391     for (i = 0; i < parents->len; i++)
392         g_free (g_ptr_array_index (parents, i));
393     g_ptr_array_free (parents, TRUE);
394
395     from = g_mime_message_get_sender (message);
396     addresses = internet_address_list_parse_string (from);
397
398     add_terms_address_addrs (doc, addresses, "from_email");
399
400     add_terms_address_addrs (doc,
401                              g_mime_message_get_all_recipients (message),
402                              "to_email");
403
404     g_mime_message_get_date (message, &time, NULL);
405
406     gmtime_r (&time, &gm_time_tm);
407
408     if (strftime (date_str, sizeof (date_str),
409                   "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
410         fprintf (stderr, "Internal error formatting time\n");
411         exit (1);
412     }
413
414     add_term (doc, "date", date_str);
415
416     add_term (doc, "label", "inbox");
417     add_term (doc, "label", "unread");
418     add_term (doc, "type", "mail");
419     add_term (doc, "source_id", "1");
420
421     value = g_mime_message_get_message_id (message);
422     add_term (doc, "msgid", value);
423     add_term (doc, "thread", value);
424
425     doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, value);
426     doc.add_value (NOTMUCH_VALUE_THREAD, value);
427
428     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
429
430     db.add_document (doc);
431
432     g_object_unref (message);
433     g_object_unref (parser);
434     g_object_unref (stream);
435 }
436
437 static void
438 usage (const char *argv0)
439 {
440     fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
441     fprintf (stderr, "\n");
442     fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
443     fprintf (stderr, "one file per line.");
444 }
445
446 int
447 main (int argc, char **argv)
448 {
449     const char *database_path;
450     char *filename;
451     GIOChannel *channel;
452     GIOStatus gio_status;
453     GError *error = NULL;
454
455     if (argc < 2) {
456         usage (argv[0]);
457         exit (1);
458     }
459
460     database_path = argv[1];
461
462     g_mime_init (0);
463
464     try {
465         Xapian::WritableDatabase db;
466         Xapian::TermGenerator term_gen;
467
468         db = Xapian::WritableDatabase (database_path,
469                                        Xapian::DB_CREATE_OR_OPEN);
470
471         term_gen = Xapian::TermGenerator ();
472
473         channel = g_io_channel_unix_new (fileno (stdin));
474
475         while (1) {
476             gio_status = g_io_channel_read_line (channel, &filename,
477                                                  NULL, NULL, &error);
478             if (gio_status == G_IO_STATUS_EOF)
479                 break;
480             if (gio_status != G_IO_STATUS_NORMAL) {
481                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
482                          error->message);
483                 exit (1);
484             }
485
486             g_strchomp (filename);
487             index_file (db, term_gen, filename);
488
489             g_free (filename);
490         }
491
492     } catch (const Xapian::Error &error) {
493         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
494         exit (1);
495     }
496
497     return 0;
498 }