]> rtime.felk.cvut.cz Git - notmuch.git/blob - notmuch-search.c
47aa97902e69e4aec23773a020a742cab948f858
[notmuch.git] / notmuch-search.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22 #include "sprinter.h"
23 #include "string-util.h"
24
25 typedef enum {
26     OUTPUT_SUMMARY      = 1 << 0,
27     OUTPUT_THREADS      = 1 << 1,
28     OUTPUT_MESSAGES     = 1 << 2,
29     OUTPUT_FILES        = 1 << 3,
30     OUTPUT_TAGS         = 1 << 4,
31     OUTPUT_SENDER       = 1 << 5,
32     OUTPUT_RECIPIENTS   = 1 << 6,
33 } output_t;
34
35 #define OUTPUT_ADDRESS_FLAGS (OUTPUT_SENDER | OUTPUT_RECIPIENTS)
36
37 typedef enum {
38     FILTER_BY_NAMEADDR = 0,
39     FILTER_BY_NAME,
40     FILTER_BY_ADDR,
41     FILTER_BY_ADDRFOLD,
42     FILTER_BY_NAMEADDRFOLD,
43 } filter_by_t;
44
45 typedef struct {
46     sprinter_t *format;
47     notmuch_query_t *query;
48     notmuch_sort_t sort;
49     output_t output;
50     int offset;
51     int limit;
52     int dupe;
53     filter_by_t filter_by;
54 } search_options_t;
55
56 typedef struct {
57     const char *name;
58     const char *addr;
59 } mailbox_t;
60
61 /* Return two stable query strings that identify exactly the matched
62  * and unmatched messages currently in thread.  If there are no
63  * matched or unmatched messages, the returned buffers will be
64  * NULL. */
65 static int
66 get_thread_query (notmuch_thread_t *thread,
67                   char **matched_out, char **unmatched_out)
68 {
69     notmuch_messages_t *messages;
70     char *escaped = NULL;
71     size_t escaped_len = 0;
72
73     *matched_out = *unmatched_out = NULL;
74
75     for (messages = notmuch_thread_get_messages (thread);
76          notmuch_messages_valid (messages);
77          notmuch_messages_move_to_next (messages))
78     {
79         notmuch_message_t *message = notmuch_messages_get (messages);
80         const char *mid = notmuch_message_get_message_id (message);
81         /* Determine which query buffer to extend */
82         char **buf = notmuch_message_get_flag (
83             message, NOTMUCH_MESSAGE_FLAG_MATCH) ? matched_out : unmatched_out;
84         /* Add this message's id: query.  Since "id" is an exclusive
85          * prefix, it is implicitly 'or'd together, so we only need to
86          * join queries with a space. */
87         if (make_boolean_term (thread, "id", mid, &escaped, &escaped_len) < 0)
88             return -1;
89         if (*buf)
90             *buf = talloc_asprintf_append_buffer (*buf, " %s", escaped);
91         else
92             *buf = talloc_strdup (thread, escaped);
93         if (!*buf)
94             return -1;
95     }
96     talloc_free (escaped);
97     return 0;
98 }
99
100 static int
101 do_search_threads (search_options_t *opt)
102 {
103     notmuch_thread_t *thread;
104     notmuch_threads_t *threads;
105     notmuch_tags_t *tags;
106     sprinter_t *format = opt->format;
107     time_t date;
108     int i;
109
110     if (opt->offset < 0) {
111         opt->offset += notmuch_query_count_threads (opt->query);
112         if (opt->offset < 0)
113             opt->offset = 0;
114     }
115
116     threads = notmuch_query_search_threads (opt->query);
117     if (threads == NULL)
118         return 1;
119
120     format->begin_list (format);
121
122     for (i = 0;
123          notmuch_threads_valid (threads) && (opt->limit < 0 || i < opt->offset + opt->limit);
124          notmuch_threads_move_to_next (threads), i++)
125     {
126         thread = notmuch_threads_get (threads);
127
128         if (i < opt->offset) {
129             notmuch_thread_destroy (thread);
130             continue;
131         }
132
133         if (opt->output == OUTPUT_THREADS) {
134             format->set_prefix (format, "thread");
135             format->string (format,
136                             notmuch_thread_get_thread_id (thread));
137             format->separator (format);
138         } else { /* output == OUTPUT_SUMMARY */
139             void *ctx_quote = talloc_new (thread);
140             const char *authors = notmuch_thread_get_authors (thread);
141             const char *subject = notmuch_thread_get_subject (thread);
142             const char *thread_id = notmuch_thread_get_thread_id (thread);
143             int matched = notmuch_thread_get_matched_messages (thread);
144             int total = notmuch_thread_get_total_messages (thread);
145             const char *relative_date = NULL;
146             notmuch_bool_t first_tag = TRUE;
147
148             format->begin_map (format);
149
150             if (opt->sort == NOTMUCH_SORT_OLDEST_FIRST)
151                 date = notmuch_thread_get_oldest_date (thread);
152             else
153                 date = notmuch_thread_get_newest_date (thread);
154
155             relative_date = notmuch_time_relative_date (ctx_quote, date);
156
157             if (format->is_text_printer) {
158                 /* Special case for the text formatter */
159                 printf ("thread:%s %12s [%d/%d] %s; %s (",
160                         thread_id,
161                         relative_date,
162                         matched,
163                         total,
164                         sanitize_string (ctx_quote, authors),
165                         sanitize_string (ctx_quote, subject));
166             } else { /* Structured Output */
167                 format->map_key (format, "thread");
168                 format->string (format, thread_id);
169                 format->map_key (format, "timestamp");
170                 format->integer (format, date);
171                 format->map_key (format, "date_relative");
172                 format->string (format, relative_date);
173                 format->map_key (format, "matched");
174                 format->integer (format, matched);
175                 format->map_key (format, "total");
176                 format->integer (format, total);
177                 format->map_key (format, "authors");
178                 format->string (format, authors);
179                 format->map_key (format, "subject");
180                 format->string (format, subject);
181                 if (notmuch_format_version >= 2) {
182                     char *matched_query, *unmatched_query;
183                     if (get_thread_query (thread, &matched_query,
184                                           &unmatched_query) < 0) {
185                         fprintf (stderr, "Out of memory\n");
186                         return 1;
187                     }
188                     format->map_key (format, "query");
189                     format->begin_list (format);
190                     if (matched_query)
191                         format->string (format, matched_query);
192                     else
193                         format->null (format);
194                     if (unmatched_query)
195                         format->string (format, unmatched_query);
196                     else
197                         format->null (format);
198                     format->end (format);
199                 }
200             }
201
202             talloc_free (ctx_quote);
203
204             format->map_key (format, "tags");
205             format->begin_list (format);
206
207             for (tags = notmuch_thread_get_tags (thread);
208                  notmuch_tags_valid (tags);
209                  notmuch_tags_move_to_next (tags))
210             {
211                 const char *tag = notmuch_tags_get (tags);
212
213                 if (format->is_text_printer) {
214                   /* Special case for the text formatter */
215                     if (first_tag)
216                         first_tag = FALSE;
217                     else
218                         fputc (' ', stdout);
219                     fputs (tag, stdout);
220                 } else { /* Structured Output */
221                     format->string (format, tag);
222                 }
223             }
224
225             if (format->is_text_printer)
226                 printf (")");
227
228             format->end (format);
229             format->end (format);
230             format->separator (format);
231         }
232
233         notmuch_thread_destroy (thread);
234     }
235
236     format->end (format);
237
238     return 0;
239 }
240
241 /* Returns TRUE iff name and/or addr is considered duplicite. */
242 static notmuch_bool_t
243 check_duplicite (const search_options_t *opt, GHashTable *addrs, const char *name, const char *addr)
244 {
245     notmuch_bool_t duplicite;
246     char *key;
247
248     if (opt->filter_by == FILTER_BY_ADDRFOLD ||
249         opt->filter_by == FILTER_BY_NAMEADDRFOLD) {
250         gchar *folded = g_utf8_casefold (addr, -1);
251         addr = talloc_strdup (opt->format, folded);
252         g_free (folded);
253     }
254     switch (opt->filter_by) {
255     case FILTER_BY_NAMEADDR:
256     case FILTER_BY_NAMEADDRFOLD:
257         key = talloc_asprintf (opt->format, "%s <%s>", name, addr);
258         break;
259     case FILTER_BY_NAME:
260         key = talloc_strdup (opt->format, name); /* !name results in !key */
261         break;
262     case FILTER_BY_ADDR:
263     case FILTER_BY_ADDRFOLD:
264         key = talloc_strdup (opt->format, addr);
265         break;
266     default:
267         INTERNAL_ERROR("invalid --filter-by flags");
268     }
269
270     if (opt->filter_by == FILTER_BY_ADDRFOLD ||
271         opt->filter_by == FILTER_BY_NAMEADDRFOLD)
272         talloc_free ((char*)addr);
273
274     if (! key)
275         return FALSE;
276
277     duplicite = g_hash_table_lookup_extended (addrs, key, NULL, NULL);
278
279     if (! duplicite)
280         g_hash_table_insert (addrs, key, NULL);
281     else
282         talloc_free (key);
283
284     return duplicite;
285 }
286
287 static void
288 print_mailbox (const search_options_t *opt, const mailbox_t *mailbox)
289 {
290     const char *name = mailbox->name;
291     const char *addr = mailbox->addr;
292
293     if (opt->format->is_text_printer) {
294         char *mailbox_str;
295
296         if (name && *name)
297             mailbox_str = talloc_asprintf (opt->format, "%s <%s>", name, addr);
298         else
299             mailbox_str = talloc_strdup (opt->format, addr);
300
301         if (! mailbox_str) {
302             fprintf (stderr, "Error: out of memory\n");
303             return;
304         }
305         opt->format->string (opt->format, mailbox_str);
306         opt->format->separator (opt->format);
307
308         talloc_free (mailbox_str);
309     } else {
310         opt->format->begin_map (opt->format);
311         opt->format->map_key (opt->format, "name");
312         opt->format->string (opt->format, name);
313         opt->format->map_key (opt->format, "address");
314         opt->format->string (opt->format, addr);
315         opt->format->end (opt->format);
316         opt->format->separator (opt->format);
317     }
318 }
319
320 static void
321 process_address_list (const search_options_t *opt, GHashTable *addrs,
322                       InternetAddressList *list)
323 {
324     InternetAddress *address;
325     int i;
326
327     for (i = 0; i < internet_address_list_length (list); i++) {
328         address = internet_address_list_get_address (list, i);
329         if (INTERNET_ADDRESS_IS_GROUP (address)) {
330             InternetAddressGroup *group;
331             InternetAddressList *group_list;
332
333             group = INTERNET_ADDRESS_GROUP (address);
334             group_list = internet_address_group_get_members (group);
335             if (group_list == NULL)
336                 continue;
337
338             process_address_list (opt, addrs, group_list);
339         } else {
340             InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
341             mailbox_t mbx = {
342                 .name = internet_address_get_name (address),
343                 .addr = internet_address_mailbox_get_addr (mailbox),
344             };
345
346             if (check_duplicite (opt, addrs, mbx.name, mbx.addr))
347                 continue;
348
349             print_mailbox (opt, &mbx);
350         }
351     }
352 }
353
354 static void
355 process_address_header (const search_options_t *opt, GHashTable *addrs, const char *value)
356 {
357     InternetAddressList *list;
358
359     if (value == NULL)
360         return;
361
362     list = internet_address_list_parse_string (value);
363     if (list == NULL)
364         return;
365
366     process_address_list (opt, addrs, list);
367 }
368
369 static void
370 _my_talloc_free_for_g_hash (void *ptr)
371 {
372     talloc_free (ptr);
373 }
374
375 static int
376 do_search_messages (search_options_t *opt)
377 {
378     notmuch_message_t *message;
379     notmuch_messages_t *messages;
380     notmuch_filenames_t *filenames;
381     sprinter_t *format = opt->format;
382     GHashTable *addresses = NULL;
383     int i;
384
385     if (opt->output & OUTPUT_ADDRESS_FLAGS)
386         addresses = g_hash_table_new_full (g_str_hash, g_str_equal,
387                                            _my_talloc_free_for_g_hash, NULL);
388
389     if (opt->offset < 0) {
390         opt->offset += notmuch_query_count_messages (opt->query);
391         if (opt->offset < 0)
392             opt->offset = 0;
393     }
394
395     messages = notmuch_query_search_messages (opt->query);
396     if (messages == NULL)
397         return 1;
398
399     format->begin_list (format);
400
401     for (i = 0;
402          notmuch_messages_valid (messages) && (opt->limit < 0 || i < opt->offset + opt->limit);
403          notmuch_messages_move_to_next (messages), i++)
404     {
405         if (i < opt->offset)
406             continue;
407
408         message = notmuch_messages_get (messages);
409
410         if (opt->output == OUTPUT_FILES) {
411             int j;
412             filenames = notmuch_message_get_filenames (message);
413
414             for (j = 1;
415                  notmuch_filenames_valid (filenames);
416                  notmuch_filenames_move_to_next (filenames), j++)
417             {
418                 if (opt->dupe < 0 || opt->dupe == j) {
419                     format->string (format, notmuch_filenames_get (filenames));
420                     format->separator (format);
421                 }
422             }
423             
424             notmuch_filenames_destroy( filenames );
425
426         } else if (opt->output == OUTPUT_MESSAGES) {
427             format->set_prefix (format, "id");
428             format->string (format,
429                             notmuch_message_get_message_id (message));
430             format->separator (format);
431         } else {
432             if (opt->output & OUTPUT_SENDER) {
433                 const char *addrs;
434
435                 addrs = notmuch_message_get_header (message, "from");
436                 process_address_header (opt, addresses, addrs);
437             }
438
439             if (opt->output & OUTPUT_RECIPIENTS) {
440                 const char *hdrs[] = { "to", "cc", "bcc" };
441                 const char *addrs;
442                 size_t j;
443
444                 for (j = 0; j < ARRAY_SIZE (hdrs); j++) {
445                     addrs = notmuch_message_get_header (message, hdrs[j]);
446                     process_address_header (opt, addresses, addrs);
447                 }
448             }
449         }
450
451         notmuch_message_destroy (message);
452     }
453
454     if (addresses)
455         g_hash_table_unref (addresses);
456
457     notmuch_messages_destroy (messages);
458
459     format->end (format);
460
461     return 0;
462 }
463
464 static int
465 do_search_tags (notmuch_database_t *notmuch,
466                 const search_options_t *opt)
467 {
468     notmuch_messages_t *messages = NULL;
469     notmuch_tags_t *tags;
470     const char *tag;
471     sprinter_t *format = opt->format;
472     notmuch_query_t *query = opt->query;
473
474     /* should the following only special case if no excluded terms
475      * specified? */
476
477     /* Special-case query of "*" for better performance. */
478     if (strcmp (notmuch_query_get_query_string (query), "*") == 0) {
479         tags = notmuch_database_get_all_tags (notmuch);
480     } else {
481         messages = notmuch_query_search_messages (query);
482         if (messages == NULL)
483             return 1;
484
485         tags = notmuch_messages_collect_tags (messages);
486     }
487     if (tags == NULL)
488         return 1;
489
490     format->begin_list (format);
491
492     for (;
493          notmuch_tags_valid (tags);
494          notmuch_tags_move_to_next (tags))
495     {
496         tag = notmuch_tags_get (tags);
497
498         format->string (format, tag);
499         format->separator (format);
500
501     }
502
503     notmuch_tags_destroy (tags);
504
505     if (messages)
506         notmuch_messages_destroy (messages);
507
508     format->end (format);
509
510     return 0;
511 }
512
513 int
514 notmuch_search_command (notmuch_config_t *config, int argc, char *argv[])
515 {
516     notmuch_database_t *notmuch;
517     search_options_t opt = {
518         .sort = NOTMUCH_SORT_NEWEST_FIRST,
519         .output = 0,
520         .offset = 0,
521         .limit = -1, /* unlimited */
522         .dupe = -1,
523         .filter_by = FILTER_BY_NAMEADDR,
524     };
525     char *query_str;
526     int opt_index, ret;
527     notmuch_exclude_t exclude = NOTMUCH_EXCLUDE_TRUE;
528     unsigned int i;
529
530     enum {
531         NOTMUCH_FORMAT_JSON,
532         NOTMUCH_FORMAT_TEXT,
533         NOTMUCH_FORMAT_TEXT0,
534         NOTMUCH_FORMAT_SEXP
535     } format_sel = NOTMUCH_FORMAT_TEXT;
536
537     notmuch_opt_desc_t options[] = {
538         { NOTMUCH_OPT_KEYWORD, &opt.sort, "sort", 's',
539           (notmuch_keyword_t []){ { "oldest-first", NOTMUCH_SORT_OLDEST_FIRST },
540                                   { "newest-first", NOTMUCH_SORT_NEWEST_FIRST },
541                                   { 0, 0 } } },
542         { NOTMUCH_OPT_KEYWORD, &format_sel, "format", 'f',
543           (notmuch_keyword_t []){ { "json", NOTMUCH_FORMAT_JSON },
544                                   { "sexp", NOTMUCH_FORMAT_SEXP },
545                                   { "text", NOTMUCH_FORMAT_TEXT },
546                                   { "text0", NOTMUCH_FORMAT_TEXT0 },
547                                   { 0, 0 } } },
548         { NOTMUCH_OPT_INT, &notmuch_format_version, "format-version", 0, 0 },
549         { NOTMUCH_OPT_KEYWORD_FLAGS, &opt.output, "output", 'o',
550           (notmuch_keyword_t []){ { "summary", OUTPUT_SUMMARY },
551                                   { "threads", OUTPUT_THREADS },
552                                   { "messages", OUTPUT_MESSAGES },
553                                   { "sender", OUTPUT_SENDER },
554                                   { "recipients", OUTPUT_RECIPIENTS },
555                                   { "files", OUTPUT_FILES },
556                                   { "tags", OUTPUT_TAGS },
557                                   { 0, 0 } } },
558         { NOTMUCH_OPT_KEYWORD, &exclude, "exclude", 'x',
559           (notmuch_keyword_t []){ { "true", NOTMUCH_EXCLUDE_TRUE },
560                                   { "false", NOTMUCH_EXCLUDE_FALSE },
561                                   { "flag", NOTMUCH_EXCLUDE_FLAG },
562                                   { "all", NOTMUCH_EXCLUDE_ALL },
563                                   { 0, 0 } } },
564         { NOTMUCH_OPT_INT, &opt.offset, "offset", 'O', 0 },
565         { NOTMUCH_OPT_INT, &opt.limit, "limit", 'L', 0  },
566         { NOTMUCH_OPT_INT, &opt.dupe, "duplicate", 'D', 0  },
567         { NOTMUCH_OPT_KEYWORD, &opt.filter_by, "filter-by", 'b',
568           (notmuch_keyword_t []){ { "nameaddr", FILTER_BY_NAMEADDR },
569                                   { "name", FILTER_BY_NAME },
570                                   { "addr", FILTER_BY_ADDR },
571                                   { "addrfold", FILTER_BY_ADDRFOLD },
572                                   { "nameaddrfold", FILTER_BY_NAMEADDRFOLD },
573                                   { 0, 0 } } },
574         { 0, 0, 0, 0, 0 }
575     };
576
577     opt_index = parse_arguments (argc, argv, options, 1);
578     if (opt_index < 0)
579         return EXIT_FAILURE;
580
581     if (! opt.output)
582         opt.output = OUTPUT_SUMMARY;
583
584     if (opt.filter_by && !(opt.output & OUTPUT_ADDRESS_FLAGS)) {
585         fprintf (stderr, "Error: --filter-by can only be used with address output.\n");
586         return EXIT_FAILURE;
587     }
588
589     switch (format_sel) {
590     case NOTMUCH_FORMAT_TEXT:
591         opt.format = sprinter_text_create (config, stdout);
592         break;
593     case NOTMUCH_FORMAT_TEXT0:
594         if (opt.output == OUTPUT_SUMMARY) {
595             fprintf (stderr, "Error: --format=text0 is not compatible with --output=summary.\n");
596             return EXIT_FAILURE;
597         }
598         opt.format = sprinter_text0_create (config, stdout);
599         break;
600     case NOTMUCH_FORMAT_JSON:
601         opt.format = sprinter_json_create (config, stdout);
602         break;
603     case NOTMUCH_FORMAT_SEXP:
604         opt.format = sprinter_sexp_create (config, stdout);
605         break;
606     default:
607         /* this should never happen */
608         INTERNAL_ERROR("no output format selected");
609     }
610
611     notmuch_exit_if_unsupported_format ();
612
613     if (notmuch_database_open (notmuch_config_get_database_path (config),
614                                NOTMUCH_DATABASE_MODE_READ_ONLY, &notmuch))
615         return EXIT_FAILURE;
616
617     query_str = query_string_from_args (notmuch, argc-opt_index, argv+opt_index);
618     if (query_str == NULL) {
619         fprintf (stderr, "Out of memory.\n");
620         return EXIT_FAILURE;
621     }
622     if (*query_str == '\0') {
623         fprintf (stderr, "Error: notmuch search requires at least one search term.\n");
624         return EXIT_FAILURE;
625     }
626
627     opt.query = notmuch_query_create (notmuch, query_str);
628     if (opt.query == NULL) {
629         fprintf (stderr, "Out of memory\n");
630         return EXIT_FAILURE;
631     }
632
633     notmuch_query_set_sort (opt.query, opt.sort);
634
635     if (exclude == NOTMUCH_EXCLUDE_FLAG && opt.output != OUTPUT_SUMMARY) {
636         /* If we are not doing summary output there is nowhere to
637          * print the excluded flag so fall back on including the
638          * excluded messages. */
639         fprintf (stderr, "Warning: this output format cannot flag excluded messages.\n");
640         exclude = NOTMUCH_EXCLUDE_FALSE;
641     }
642
643     if (exclude != NOTMUCH_EXCLUDE_FALSE) {
644         const char **search_exclude_tags;
645         size_t search_exclude_tags_length;
646
647         search_exclude_tags = notmuch_config_get_search_exclude_tags
648             (config, &search_exclude_tags_length);
649         for (i = 0; i < search_exclude_tags_length; i++)
650             notmuch_query_add_tag_exclude (opt.query, search_exclude_tags[i]);
651         notmuch_query_set_omit_excluded (opt.query, exclude);
652     }
653
654     if (opt.output == OUTPUT_SUMMARY ||
655         opt.output == OUTPUT_THREADS)
656         ret = do_search_threads (&opt);
657     else if (opt.output == OUTPUT_MESSAGES ||
658              opt.output == OUTPUT_FILES ||
659              (opt.output & OUTPUT_ADDRESS_FLAGS && !(opt.output & ~OUTPUT_ADDRESS_FLAGS)))
660         ret = do_search_messages (&opt);
661     else if (opt.output == OUTPUT_TAGS)
662         ret = do_search_tags (notmuch, &opt);
663     else {
664         fprintf (stderr, "Error: the combination of outputs is not supported.\n");
665         ret = 1;
666     }
667
668     notmuch_query_destroy (opt.query);
669     notmuch_database_destroy (notmuch);
670
671     talloc_free (opt.format);
672
673     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
674 }