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