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