]> git.notmuchmail.org Git - notmuch/blobdiff - notmuch-index-message.cc
notmuch-index-message: Avoid crashing when a message has no references.
[notmuch] / notmuch-index-message.cc
index cf99e6e43d7762e25fa812f307ab3cf65d452827..a0faf442dbf9ef1c04910046e3560c90df50f7a8 100644 (file)
 #include <errno.h>
 #include <time.h>
 
+#include <iostream>
+
 #include <gmime/gmime.h>
 
+#include <xapian.h>
+
+using namespace std;
+
 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
 
 /* These prefix values are specifically chosen to be compatible
@@ -61,6 +67,15 @@ prefix_t BOOLEAN_PREFIX[] = {
     { "ref", "R" }
 };
 
+/* Similarly, these value numbers are also chosen to be sup
+ * compatible. */
+
+typedef enum {
+    NOTMUCH_VALUE_MESSAGE_ID = 0,
+    NOTMUCH_VALUE_THREAD = 1,
+    NOTMUCH_VALUE_DATE = 2
+} notmuch_value_t;
+
 static const char *
 find_prefix (const char *name)
 {
@@ -80,48 +95,73 @@ find_prefix (const char *name)
 int TERM_COMBINED = 0;
 
 static void
-print_term (const char *prefix_name, const char *value)
+add_term (Xapian::Document doc,
+         const char *prefix_name,
+         const char *value)
 {
     const char *prefix;
+    char *term;
 
     if (value == NULL)
        return;
 
     prefix = find_prefix (prefix_name);
 
-    if (TERM_COMBINED)
-       printf ("\"%s%s\", ", prefix, value);
-    else
-       printf ("[\"%s\", \"%s\"], ", value, prefix);
+    term = g_strdup_printf ("%s%s", prefix, value);
+
+    doc.add_term (term);
+
+    g_free (term);
+}
+
+static void
+gen_terms (Xapian::TermGenerator term_gen,
+          const char *prefix_name,
+          const char *text)
+{
+    const char *prefix;
+
+    if (text == NULL)
+       return;
+
+    prefix = find_prefix (prefix_name);
+
+    term_gen.index_text (text, 1, prefix);
 }
 
 static void
-add_address_name (InternetAddress *address, const char *prefix_name)
+gen_terms_address_name (Xapian::TermGenerator term_gen,
+                       InternetAddress *address,
+                       const char *prefix_name)
 {
     const char *name;
 
     name = internet_address_get_name (address);
 
     if (name)
-       print_term (prefix_name, name);
+       gen_terms (term_gen, prefix_name, name);
 }
 
 static void
-add_address_names (InternetAddressList *addresses, const char *address_type)
+gen_terms_address_names (Xapian::TermGenerator term_gen,
+                        InternetAddressList *addresses,
+                        const char *address_type)
 {
     int i;
     InternetAddress *address;
 
     for (i = 0; i < internet_address_list_length (addresses); i++) {
        address = internet_address_list_get_address (addresses, i);
-       add_address_name (address, address_type);
-       add_address_name (address, "name");
-       add_address_name (address, "body");
+       gen_terms_address_name (term_gen, address, address_type);
+       gen_terms_address_name (term_gen, address, "name");
+       gen_terms_address_name (term_gen, address, "body");
     }
 }
 
 static void
-add_address_addr (InternetAddress *address, const char *prefix_name)
+add_term_address_addr (Xapian::Document doc,
+                      InternetAddress *address,
+                      const char *prefix_name)
 {
     InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
     const char *addr;
@@ -129,46 +169,178 @@ add_address_addr (InternetAddress *address, const char *prefix_name)
     addr = internet_address_mailbox_get_addr (mailbox);
 
     if (addr)
-       print_term (prefix_name, addr);
+       add_term (doc, prefix_name, addr);
 }
 
 static void
-add_address_addrs (InternetAddressList *addresses, const char *address_type)
+add_terms_address_addrs (Xapian::Document doc,
+                        InternetAddressList *addresses,
+                        const char *address_type)
 {
     int i;
     InternetAddress *address;
 
     for (i = 0; i < internet_address_list_length (addresses); i++) {
        address = internet_address_list_get_address (addresses, i);
-       add_address_addr (address, address_type);
-       add_address_addr (address, "email");
+       add_term_address_addr (doc, address, address_type);
+       add_term_address_addr (doc, address, "email");
     }
 }
 
-int
-main (int argc, char **argv)
+static const char *
+skip_re_in_subject (const char *subject)
+{
+    const char *s = subject;
+
+    while (*s) {
+       while (*s && isspace (*s))
+           s++;
+       if (strncasecmp (s, "re:", 3) == 0)
+           s += 3;
+       else
+           break;
+    }
+
+    return s;
+}
+
+/* Add a term for each message-id in the References header of the
+ * message. */
+static void
+add_terms_references (Xapian::Document doc,
+                     GMimeMessage *message)
+{
+    const char *refs, *end, *next;
+    char *term;
+
+    refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
+
+    if (refs == NULL)
+       return;
+
+    while (*refs) {
+       while (*refs && isspace (*refs))
+           refs++;
+       if (*refs == '<')
+           refs++;
+       end = refs;
+       while (*end && !isspace (*end))
+           end++;
+       next = end;
+       end--;
+       if (end > refs && *end == '>')
+           end--;
+       if (end > refs) {
+           term = g_strndup (refs, end - refs + 1);
+           add_term (doc, "ref", term);
+           g_free (term);
+       }
+       refs = next;
+    }
+}
+
+/* Generate terms for the body of a message, given the filename of the
+ * message and the offset at which the headers of the message end,
+ * (and hence the body begins). */
+static void
+gen_terms_body (Xapian::TermGenerator term_gen,
+               const char * filename,
+               gint64 body_offset)
 {
+    GIOChannel *channel;
+    GIOStatus gio_status;
+    GError *error = NULL;
+    char *p, *body_line = NULL, *prev_line = NULL;
+
+    channel = g_io_channel_new_file (filename, "r", &error);
+    if (channel == NULL) {
+       fprintf (stderr, "Error: %s\n", error->message);
+       exit (1);
+    }
+
+    gio_status = g_io_channel_seek_position (channel, body_offset,
+                                            G_SEEK_SET, &error);
+    if (gio_status != G_IO_STATUS_NORMAL) {
+       fprintf (stderr, "Error: %s\n", error->message);
+       exit (1);
+    }
+
+    while (1) {
+       if (body_line)
+           g_free (body_line);
+
+       gio_status = g_io_channel_read_line (channel, &body_line,
+                                            NULL, NULL, &error);
+       if (gio_status == G_IO_STATUS_EOF)
+           break;
+       if (gio_status != G_IO_STATUS_NORMAL) {
+           fprintf (stderr, "Error: %s\n", error->message);
+           exit (1);
+       }
+
+       if (strlen (body_line) == 0)
+           continue;
+
+       /* If the line looks like it might be introducing a quote,
+        * save it until we see if the next line begins a quote. */
+       p = body_line + strlen (body_line) - 1;
+       while (p > body_line and isspace (*p))
+           p--;
+       if (*p == ':') {
+           prev_line = body_line;
+           body_line = NULL;
+           continue;
+       }
+
+       /* Skip quoted lines, (and previous lines that introduced them) */
+       if (body_line[0] == '>') {
+           if (prev_line) {
+               g_free (prev_line);
+               prev_line = NULL;
+           }
+           continue;
+       }
+
+       /* Now that we're not looking at a quote we can add the prev_line */
+       if (prev_line) {
+           gen_terms (term_gen, "body", prev_line);
+           g_free (prev_line);
+           prev_line = NULL;
+       }
+
+       /* Skip signatures */
+       /* XXX: Should only do this if "near" the end of the message. */
+       if (strncmp (body_line, "-- ", 3) == 0)
+           break;
+
+       gen_terms (term_gen, "body", body_line);
+    }
+
+    if (body_line)
+       g_free (body_line);
+
+    g_io_channel_close (channel);
+}
+
+static void
+index_file (Xapian::WritableDatabase db,
+           Xapian::TermGenerator term_gen,
+           const char *filename)
+{
+    Xapian::Document doc;
+
     GMimeStream *stream;
     GMimeParser *parser;
     GMimeMessage *message;
     InternetAddressList *addresses;
 
-    const char *filename;
     FILE *file;
 
     const char *value, *from;
 
     time_t time;
     struct tm gm_time_tm;
-    char time_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
-
-    if (argc < 2) {
-       fprintf (stderr, "Usage: %s <mail-message>\n",
-                argv[0]);
-       exit (1);
-    }
-
-    filename = argv[1];
+    char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
 
     file = fopen (filename, "r");
     if (! file) {
@@ -176,68 +348,139 @@ main (int argc, char **argv)
        exit (1);
     }
 
-    g_mime_init (0);
-
     stream = g_mime_stream_file_new (file);
 
     parser = g_mime_parser_new_with_stream (stream);
 
     message = g_mime_parser_construct_message (parser);
 
-    printf ("text is:\n[");
+    doc = Xapian::Document ();
+
+    doc.set_data (filename);
+
+    term_gen.set_stemmer (Xapian::Stem ("english"));
+
+    term_gen.set_document (doc);
+
     from = g_mime_message_get_sender (message);
     addresses = internet_address_list_parse_string (from);
 
-    add_address_names (addresses, "from_name");
+    gen_terms_address_names (term_gen, addresses, "from_name");
 
-    add_address_names (g_mime_message_get_all_recipients (message),
-                      "to_name");
+    addresses = g_mime_message_get_all_recipients (message);
+    gen_terms_address_names (term_gen, addresses, "to_name");
 
     value = g_mime_message_get_subject (message);
-    print_term ("subject", value);
-    print_term ("body", value);
+    value = skip_re_in_subject (value);
+    gen_terms (term_gen, "subject", value);
+    gen_terms (term_gen, "body", value);
 
-    printf ("]\nterms is:\n[");
+    gen_terms_body (term_gen, filename,
+                   g_mime_parser_get_headers_end (parser));
 
-    TERM_COMBINED = 1;
+    add_terms_references (doc, message);
 
     from = g_mime_message_get_sender (message);
     addresses = internet_address_list_parse_string (from);
 
-    add_address_addrs (addresses, "from_email");
+    add_terms_address_addrs (doc, addresses, "from_email");
 
-    add_address_addrs (g_mime_message_get_all_recipients (message),
-                      "to_email");
+    add_terms_address_addrs (doc,
+                            g_mime_message_get_all_recipients (message),
+                            "to_email");
 
     g_mime_message_get_date (message, &time, NULL);
 
     gmtime_r (&time, &gm_time_tm);
 
-    if (strftime (time_str, sizeof (time_str),
+    if (strftime (date_str, sizeof (date_str),
                  "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
        fprintf (stderr, "Internal error formatting time\n");
        exit (1);
     }
 
-    print_term ("date", time_str);
+    add_term (doc, "date", date_str);
 
-    print_term ("label", "inbox");
-    print_term ("label", "unread");
-    print_term ("type", "mail");
+    add_term (doc, "label", "inbox");
+    add_term (doc, "label", "unread");
+    add_term (doc, "type", "mail");
+    add_term (doc, "source_id", "1");
 
     value = g_mime_message_get_message_id (message);
-    print_term ("msgid", value);
+    add_term (doc, "msgid", value);
+    add_term (doc, "thread", value);
 
-    print_term ("source_id", "1");
+    doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, value);
+    doc.add_value (NOTMUCH_VALUE_THREAD, value);
 
-    value = g_mime_message_get_message_id (message);
-    print_term ("thread", value);
+    doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
 
-    printf ("]\n");
+    db.add_document (doc);
 
     g_object_unref (message);
     g_object_unref (parser);
     g_object_unref (stream);
+}
+
+static void
+usage (const char *argv0)
+{
+    fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
+    fprintf (stderr, "\n");
+    fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
+    fprintf (stderr, "one file per line.");
+}
+
+int
+main (int argc, char **argv)
+{
+    const char *database_path;
+    char *filename;
+    GIOChannel *channel;
+    GIOStatus gio_status;
+    GError *error = NULL;
+
+    if (argc < 2) {
+       usage (argv[0]);
+       exit (1);
+    }
+
+    database_path = argv[1];
+
+    g_mime_init (0);
+
+    try {
+       Xapian::WritableDatabase db;
+       Xapian::TermGenerator term_gen;
+
+       db = Xapian::WritableDatabase (database_path,
+                                      Xapian::DB_CREATE_OR_OPEN);
+
+       term_gen = Xapian::TermGenerator ();
+
+       channel = g_io_channel_unix_new (fileno (stdin));
+
+       while (1) {
+           gio_status = g_io_channel_read_line (channel, &filename,
+                                                NULL, NULL, &error);
+           if (gio_status == G_IO_STATUS_EOF)
+               break;
+           if (gio_status != G_IO_STATUS_NORMAL) {
+               fprintf (stderr, "An error occurred reading from stdin: %s\n",
+                        error->message);
+               exit (1);
+           }
+
+           g_strchomp (filename);
+           index_file (db, term_gen, filename);
+
+           g_free (filename);
+       }
+
+    } catch (const Xapian::Error &error) {
+       cerr << "A Xapian exception occurred: " << error.get_msg () << endl;
+       exit (1);
+    }
 
     return 0;
 }