]> git.notmuchmail.org Git - notmuch/blob - notmuch-index-message.cc
notmuch-index-message: Read message filenames from stdin
[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 add_terms_references (Xapian::Document doc,
211                       GMimeMessage *message)
212 {
213     const char *refs, *end, *next;
214     char *term;
215
216     refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
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             term = g_strndup (refs, end - refs + 1);
232             add_term (doc, "ref", term);
233             g_free (term);
234         }
235         refs = next;
236     }
237 }
238
239 /* Generate terms for the body of a message, given the filename of the
240  * message and the offset at which the headers of the message end,
241  * (and hence the body begins). */
242 static void
243 gen_terms_body (Xapian::TermGenerator term_gen,
244                 const char * filename,
245                 gint64 body_offset)
246 {
247     GIOChannel *channel;
248     GIOStatus gio_status;
249     GError *error = NULL;
250     char *p, *body_line = NULL, *prev_line = NULL;
251
252     channel = g_io_channel_new_file (filename, "r", &error);
253     if (channel == NULL) {
254         fprintf (stderr, "Error: %s\n", error->message);
255         exit (1);
256     }
257
258     gio_status = g_io_channel_seek_position (channel, body_offset,
259                                              G_SEEK_SET, &error);
260     if (gio_status != G_IO_STATUS_NORMAL) {
261         fprintf (stderr, "Error: %s\n", error->message);
262         exit (1);
263     }
264
265     while (1) {
266         if (body_line)
267             g_free (body_line);
268
269         gio_status = g_io_channel_read_line (channel, &body_line,
270                                              NULL, NULL, &error);
271         if (gio_status == G_IO_STATUS_EOF)
272             break;
273         if (gio_status != G_IO_STATUS_NORMAL) {
274             fprintf (stderr, "Error: %s\n", error->message);
275             exit (1);
276         }
277
278         if (strlen (body_line) == 0)
279             continue;
280
281         /* If the line looks like it might be introducing a quote,
282          * save it until we see if the next line begins a quote. */
283         p = body_line + strlen (body_line) - 1;
284         while (p > body_line and isspace (*p))
285             p--;
286         if (*p == ':') {
287             prev_line = body_line;
288             body_line = NULL;
289             continue;
290         }
291
292         /* Skip quoted lines, (and previous lines that introduced them) */
293         if (body_line[0] == '>') {
294             if (prev_line) {
295                 g_free (prev_line);
296                 prev_line = NULL;
297             }
298             continue;
299         }
300
301         /* Now that we're not looking at a quote we can add the prev_line */
302         if (prev_line) {
303             gen_terms (term_gen, "body", prev_line);
304             g_free (prev_line);
305             prev_line = NULL;
306         }
307
308         /* Skip signatures */
309         /* XXX: Should only do this if "near" the end of the message. */
310         if (strncmp (body_line, "-- ", 3) == 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
334     FILE *file;
335
336     const char *value, *from;
337
338     time_t time;
339     struct tm gm_time_tm;
340     char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
341
342     file = fopen (filename, "r");
343     if (! file) {
344         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
345         exit (1);
346     }
347
348     stream = g_mime_stream_file_new (file);
349
350     parser = g_mime_parser_new_with_stream (stream);
351
352     message = g_mime_parser_construct_message (parser);
353
354     doc = Xapian::Document ();
355
356     doc.set_data (filename);
357
358     term_gen.set_stemmer (Xapian::Stem ("english"));
359
360     term_gen.set_document (doc);
361
362     from = g_mime_message_get_sender (message);
363     addresses = internet_address_list_parse_string (from);
364
365     gen_terms_address_names (term_gen, addresses, "from_name");
366
367     addresses = g_mime_message_get_all_recipients (message);
368     gen_terms_address_names (term_gen, addresses, "to_name");
369
370     value = g_mime_message_get_subject (message);
371     value = skip_re_in_subject (value);
372     gen_terms (term_gen, "subject", value);
373     gen_terms (term_gen, "body", value);
374
375     gen_terms_body (term_gen, filename,
376                     g_mime_parser_get_headers_end (parser));
377
378     add_terms_references (doc, message);
379
380     from = g_mime_message_get_sender (message);
381     addresses = internet_address_list_parse_string (from);
382
383     add_terms_address_addrs (doc, addresses, "from_email");
384
385     add_terms_address_addrs (doc,
386                              g_mime_message_get_all_recipients (message),
387                              "to_email");
388
389     g_mime_message_get_date (message, &time, NULL);
390
391     gmtime_r (&time, &gm_time_tm);
392
393     if (strftime (date_str, sizeof (date_str),
394                   "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
395         fprintf (stderr, "Internal error formatting time\n");
396         exit (1);
397     }
398
399     add_term (doc, "date", date_str);
400
401     add_term (doc, "label", "inbox");
402     add_term (doc, "label", "unread");
403     add_term (doc, "type", "mail");
404     add_term (doc, "source_id", "1");
405
406     value = g_mime_message_get_message_id (message);
407     add_term (doc, "msgid", value);
408     add_term (doc, "thread", value);
409
410     doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, value);
411     doc.add_value (NOTMUCH_VALUE_THREAD, value);
412
413     doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
414
415     db.add_document (doc);
416
417     g_object_unref (message);
418     g_object_unref (parser);
419     g_object_unref (stream);
420 }
421
422 static void
423 usage (const char *argv0)
424 {
425     fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
426     fprintf (stderr, "\n");
427     fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
428     fprintf (stderr, "one file per line.");
429 }
430
431 int
432 main (int argc, char **argv)
433 {
434     const char *database_path;
435     char *filename;
436     GIOChannel *channel;
437     GIOStatus gio_status;
438     GError *error = NULL;
439
440     if (argc < 2) {
441         usage (argv[0]);
442         exit (1);
443     }
444
445     database_path = argv[1];
446
447     g_mime_init (0);
448
449     try {
450         Xapian::WritableDatabase db;
451         Xapian::TermGenerator term_gen;
452
453         db = Xapian::WritableDatabase (database_path,
454                                        Xapian::DB_CREATE_OR_OPEN);
455
456         term_gen = Xapian::TermGenerator ();
457
458         channel = g_io_channel_unix_new (fileno (stdin));
459
460         while (1) {
461             gio_status = g_io_channel_read_line (channel, &filename,
462                                                  NULL, NULL, &error);
463             if (gio_status == G_IO_STATUS_EOF)
464                 break;
465             if (gio_status != G_IO_STATUS_NORMAL) {
466                 fprintf (stderr, "An error occurred reading from stdin: %s\n",
467                          error->message);
468                 exit (1);
469             }
470
471             g_strchomp (filename);
472             index_file (db, term_gen, filename);
473
474             g_free (filename);
475         }
476
477     } catch (const Xapian::Error &error) {
478         cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
479         exit (1);
480     }
481
482     return 0;
483 }