2 * Copyright © 2009 Carl Worth
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.
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.
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/ .
17 * Author: Carl Worth <cworth@cworth.org>
28 #include <gmime/gmime.h>
34 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
36 /* Xapian complains if we provide a term longer than this. */
37 #define NOTMUCH_MAX_TERM 245
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.
50 prefix_t NORMAL_PREFIX[] = {
53 { "from_name", "FN" },
59 prefix_t BOOLEAN_PREFIX[] = {
61 { "from_email", "FE" },
67 { "attachment_extension", "O" },
73 /* Similarly, these value numbers are also chosen to be sup
77 NOTMUCH_VALUE_MESSAGE_ID = 0,
78 NOTMUCH_VALUE_THREAD = 1,
79 NOTMUCH_VALUE_DATE = 2
83 find_prefix (const char *name)
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;
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;
98 int TERM_COMBINED = 0;
101 add_term (Xapian::Document doc,
102 const char *prefix_name,
111 prefix = find_prefix (prefix_name);
113 term = g_strdup_printf ("%s%s", prefix, value);
115 if (strlen (term) <= NOTMUCH_MAX_TERM)
122 gen_terms (Xapian::TermGenerator term_gen,
123 const char *prefix_name,
131 prefix = find_prefix (prefix_name);
133 term_gen.index_text (text, 1, prefix);
137 gen_terms_address_name (Xapian::TermGenerator term_gen,
138 InternetAddress *address,
139 const char *prefix_name)
144 name = internet_address_get_name (address);
146 /* In the absence of a name, we'll strip the part before the @
147 * from the address. */
149 InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
150 const char *addr = internet_address_mailbox_get_addr (mailbox);
153 at = strchr (addr, '@');
155 name = strndup (addr, at - addr);
161 gen_terms (term_gen, prefix_name, name);
164 free ((void *) name);
168 gen_terms_address_names (Xapian::TermGenerator term_gen,
169 InternetAddressList *addresses,
170 const char *address_type)
173 InternetAddress *address;
175 for (i = 0; i < internet_address_list_length (addresses); i++) {
176 address = internet_address_list_get_address (addresses, i);
177 gen_terms_address_name (term_gen, address, address_type);
178 gen_terms_address_name (term_gen, address, "name");
179 gen_terms_address_name (term_gen, address, "body");
184 add_term_address_addr (Xapian::Document doc,
185 InternetAddress *address,
186 const char *prefix_name)
188 InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
191 addr = internet_address_mailbox_get_addr (mailbox);
194 add_term (doc, prefix_name, addr);
198 add_terms_address_addrs (Xapian::Document doc,
199 InternetAddressList *addresses,
200 const char *address_type)
203 InternetAddress *address;
205 for (i = 0; i < internet_address_list_length (addresses); i++) {
206 address = internet_address_list_get_address (addresses, i);
207 add_term_address_addr (doc, address, address_type);
208 add_term_address_addr (doc, address, "email");
213 skip_re_in_subject (const char *subject)
215 const char *s = subject;
218 while (*s && isspace (*s))
220 if (strncasecmp (s, "re:", 3) == 0)
230 find_messages_by_term (Xapian::Database db,
231 const char *prefix_name,
233 Xapian::PostingIterator *begin,
234 Xapian::PostingIterator *end)
236 Xapian::PostingIterator i;
239 term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
241 *begin = db.postlist_begin (term);
244 *end = db.postlist_end (term);
250 find_message_by_docid (Xapian::Database db, Xapian::docid docid)
252 return db.get_document (docid);
256 find_message_by_message_id (Xapian::Database db, const char *message_id)
258 Xapian::PostingIterator i, end;
260 find_messages_by_term (db, "msgid", message_id, &i, &end);
263 return find_message_by_docid (db, *i);
265 return Xapian::Document ();
269 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
272 const char *value, *id, *comma;
274 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
275 value = value_string.c_str();
276 if (strlen (value)) {
279 comma = strchr (id, ',');
281 comma = id + strlen (id);
282 g_hash_table_insert (thread_ids,
283 strndup (id, comma - id), NULL);
291 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
292 * given message based on looking into the database for any messages
293 * referenced in parents, and also for any messages in the database
294 * referencing message_id.
296 * Caller should free all strings in the array and the array itself,
297 * (g_ptr_array_free) when done. */
299 find_thread_ids (Xapian::Database db,
301 const char *message_id)
303 Xapian::PostingIterator child, children_end;
304 Xapian::Document doc;
305 GHashTable *thread_ids;
308 const char *parent_message_id;
311 thread_ids = g_hash_table_new (g_str_hash, g_str_equal);
313 find_messages_by_term (db, "ref", message_id, &child, &children_end);
314 for ( ; child != children_end; child++) {
315 doc = find_message_by_docid (db, *child);
316 insert_thread_id (thread_ids, doc);
319 for (i = 0; i < parents->len; i++) {
320 parent_message_id = (char *) g_ptr_array_index (parents, i);
321 doc = find_message_by_message_id (db, parent_message_id);
322 insert_thread_id (thread_ids, doc);
325 result = g_ptr_array_new ();
327 keys = g_hash_table_get_keys (thread_ids);
328 for (l = keys; l; l = l->next) {
329 char *id = (char *) l->data;
330 g_ptr_array_add (result, id);
336 /* Add a term for each message-id in the References header of the
339 parse_references (GPtrArray *array,
340 const char *refs_str)
342 GMimeReferences *refs, *r;
343 const char *message_id;
345 if (refs_str == NULL)
348 refs = g_mime_references_decode (refs_str);
350 for (r = refs; r; r = r->next) {
351 message_id = g_mime_references_get_message_id (r);
352 g_ptr_array_add (array, g_strdup (message_id));
355 g_mime_references_free (refs);
358 /* Given a string representing the body of a message, generate terms
359 * for it, (skipping quoted portions and signatures). */
361 gen_terms_body_str (Xapian::TermGenerator term_gen,
364 char *line, *line_end, *next_line;
376 next_line = strchr (line, '\n');
377 if (next_line == NULL) {
378 next_line = line + strlen (line);
380 line_end = next_line - 1;
382 /* Trim whitespace. */
383 while (*next_line && isspace (*next_line))
386 /* Skip lines that are quotes. */
390 /* Also skip lines introducing a quote on the next line. */
391 if (*line_end == ':' && *next_line == '>')
394 /* Finally, bail as soon as we see a signature. */
395 /* XXX: Should only do this if "near" the end of the message. */
396 if (strncmp (line, "-- ", 3) == 0 ||
397 strncmp (line, "----------", 10) == 0 ||
398 strncmp (line, "__________", 10) == 0)
401 *(line_end + 1) = '\0';
402 gen_terms (term_gen, "body", line);
407 /* Callback to generate terms for each mime part of a message. */
409 gen_terms_part (Xapian::TermGenerator term_gen,
413 GMimeDataWrapper *wrapper;
414 GByteArray *byte_array;
415 GMimeContentDisposition *disposition;
418 if (GMIME_IS_MULTIPART (part)) {
419 GMimeMultipart *multipart = GMIME_MULTIPART (part);
422 for (i = 0; i < g_mime_multipart_get_count (multipart); i++) {
423 if (GMIME_IS_MULTIPART_SIGNED (multipart)) {
424 /* Don't index the signature. */
428 fprintf (stderr, "Warning: Unexpected extra parts of mutlipart/signed. Indexing anyway.\n");
430 gen_terms_part (term_gen,
431 g_mime_multipart_get_part (multipart, i));
436 if (! GMIME_IS_PART (part)) {
437 fprintf (stderr, "Warning: Not indexing unknown mime part: %s.\n",
438 g_type_name (G_OBJECT_TYPE (part)));
442 disposition = g_mime_object_get_content_disposition (GMIME_OBJECT (part));
444 strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
446 add_term (term_gen.get_document (), "label", "attachment");
450 byte_array = g_byte_array_new ();
452 stream = g_mime_stream_mem_new_with_byte_array (byte_array);
453 g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), FALSE);
454 wrapper = g_mime_part_get_content_object (GMIME_PART (part));
455 g_mime_data_wrapper_write_to_stream (wrapper, stream);
457 g_object_unref (stream);
459 g_byte_array_append (byte_array, (guint8 *) "\0", 1);
460 body = (char *) g_byte_array_free (byte_array, FALSE);
462 gen_terms_body_str (term_gen, body);
468 index_file (Xapian::WritableDatabase db,
469 Xapian::TermGenerator term_gen,
470 const char *filename)
472 Xapian::Document doc;
476 GMimeMessage *message;
477 InternetAddressList *addresses;
478 GPtrArray *parents, *thread_ids;
482 const char *subject, *refs, *in_reply_to, *from;
483 const char *message_id;
486 struct tm gm_time_tm;
487 char date_str[16]; /* YYYYMMDDHHMMSS + 1 for Y100k compatibility ;-) */
490 file = fopen (filename, "r");
492 fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
496 stream = g_mime_stream_file_new (file);
498 parser = g_mime_parser_new_with_stream (stream);
500 message = g_mime_parser_construct_message (parser);
502 doc = Xapian::Document ();
504 doc.set_data (filename);
506 term_gen.set_stemmer (Xapian::Stem ("english"));
508 term_gen.set_document (doc);
510 from = g_mime_message_get_sender (message);
511 addresses = internet_address_list_parse_string (from);
513 gen_terms_address_names (term_gen, addresses, "from_name");
515 addresses = g_mime_message_get_all_recipients (message);
516 gen_terms_address_names (term_gen, addresses, "to_name");
518 subject = g_mime_message_get_subject (message);
519 subject = skip_re_in_subject (subject);
520 gen_terms (term_gen, "subject", subject);
521 gen_terms (term_gen, "body", subject);
523 gen_terms_part (term_gen, g_mime_message_get_mime_part (message));
525 parents = g_ptr_array_new ();
527 refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
528 parse_references (parents, refs);
530 in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
532 parse_references (parents, in_reply_to);
534 for (i = 0; i < parents->len; i++)
535 add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
537 message_id = g_mime_message_get_message_id (message);
539 thread_ids = find_thread_ids (db, parents, message_id);
541 for (i = 0; i < parents->len; i++)
542 g_free (g_ptr_array_index (parents, i));
543 g_ptr_array_free (parents, TRUE);
545 from = g_mime_message_get_sender (message);
546 addresses = internet_address_list_parse_string (from);
548 add_terms_address_addrs (doc, addresses, "from_email");
550 add_terms_address_addrs (doc,
551 g_mime_message_get_all_recipients (message),
554 g_mime_message_get_date (message, &time, NULL);
556 gmtime_r (&time, &gm_time_tm);
558 if (strftime (date_str, sizeof (date_str),
559 "%Y%m%d%H%M%S", &gm_time_tm) == 0) {
560 fprintf (stderr, "Internal error formatting time\n");
564 add_term (doc, "date", date_str);
566 add_term (doc, "label", "inbox");
567 add_term (doc, "label", "unread");
568 add_term (doc, "type", "mail");
569 add_term (doc, "source_id", "1");
571 add_term (doc, "msgid", message_id);
572 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
574 if (thread_ids->len) {
579 for (i = 0; i < thread_ids->len; i++) {
580 id = (char *) thread_ids->pdata[i];
582 add_term (doc, "thread", id);
585 thread_id = g_string_new (id);
587 g_string_append_printf (thread_id, ",%s", id);
591 g_ptr_array_free (thread_ids, TRUE);
593 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
595 g_string_free (thread_id, TRUE);
597 /* If not referenced thread, use the message ID */
598 add_term (doc, "thread", message_id);
599 doc.add_value (NOTMUCH_VALUE_THREAD, message_id);
602 doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
604 db.add_document (doc);
606 g_object_unref (message);
607 g_object_unref (parser);
608 g_object_unref (stream);
612 usage (const char *argv0)
614 fprintf (stderr, "Usage: %s <path-to-xapian-database>\n", argv0);
615 fprintf (stderr, "\n");
616 fprintf (stderr, "Messages to be indexed are read from stdnin as absolute filenames\n");
617 fprintf (stderr, "one file per line.");
621 main (int argc, char **argv)
623 const char *database_path;
626 GIOStatus gio_status;
627 GError *error = NULL;
634 database_path = argv[1];
639 Xapian::WritableDatabase db;
640 Xapian::TermGenerator term_gen;
642 db = Xapian::WritableDatabase (database_path,
643 Xapian::DB_CREATE_OR_OPEN);
645 term_gen = Xapian::TermGenerator ();
647 channel = g_io_channel_unix_new (fileno (stdin));
650 gio_status = g_io_channel_read_line (channel, &filename,
652 if (gio_status == G_IO_STATUS_EOF)
654 if (gio_status != G_IO_STATUS_NORMAL) {
655 fprintf (stderr, "An error occurred reading from stdin: %s\n",
660 g_strchomp (filename);
661 index_file (db, term_gen, filename);
666 } catch (const Xapian::Error &error) {
667 cerr << "A Xapian exception occurred: " << error.get_msg () << endl;