]> git.notmuchmail.org Git - notmuch/blob - notmuch-show.c
ea465dec7aa65e7385dd8b3e2170da1c1f79d2a7
[notmuch] / notmuch-show.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
23 typedef struct show_format {
24     const char *message_set_start;
25     const char *message_start;
26     void (*message) (const void *ctx,
27                      notmuch_message_t *message,
28                      int indent);
29     const char *header_start;
30     void (*header) (const void *ctx,
31                     notmuch_message_t *message);
32     const char *header_end;
33     const char *body_start;
34     void (*part) (GMimeObject *part,
35                   int *part_count);
36     const char *body_end;
37     const char *message_end;
38     const char *message_set_sep;
39     const char *message_set_end;
40 } show_format_t;
41
42 static void
43 format_message_text (unused (const void *ctx),
44                      notmuch_message_t *message,
45                      int indent);
46 static void
47 format_headers_text (const void *ctx,
48                      notmuch_message_t *message);
49 static void
50 format_part_text (GMimeObject *part,
51                   int *part_count);
52 static const show_format_t format_text = {
53     "",
54         "\fmessage{ ", format_message_text,
55             "\fheader{\n", format_headers_text, "\fheader}\n",
56             "\fbody{\n", format_part_text, "\fbody}\n",
57         "\fmessage}\n", "",
58     ""
59 };
60
61 static void
62 format_message_json (const void *ctx,
63                      notmuch_message_t *message,
64                      unused (int indent));
65 static void
66 format_headers_json (const void *ctx,
67                      notmuch_message_t *message);
68 static void
69 format_part_json (GMimeObject *part,
70                   int *part_count);
71 static const show_format_t format_json = {
72     "[",
73         "{", format_message_json,
74             ", \"headers\": {", format_headers_json, "}",
75             ", \"body\": [", format_part_json, "]",
76         "}", ", ",
77     "]"
78 };
79
80 static void
81 format_message_mbox (const void *ctx,
82                      notmuch_message_t *message,
83                      unused (int indent));
84
85 static const show_format_t format_mbox = {
86     "",
87         "", format_message_mbox,
88             "", NULL, "",
89             "", NULL, "",
90         "", "",
91     ""
92 };
93
94 static const char *
95 _get_tags_as_string (const void *ctx, notmuch_message_t *message)
96 {
97     notmuch_tags_t *tags;
98     int first = 1;
99     const char *tag;
100     char *result;
101
102     result = talloc_strdup (ctx, "");
103     if (result == NULL)
104         return NULL;
105
106     for (tags = notmuch_message_get_tags (message);
107          notmuch_tags_valid (tags);
108          notmuch_tags_move_to_next (tags))
109     {
110         tag = notmuch_tags_get (tags);
111
112         result = talloc_asprintf_append (result, "%s%s",
113                                          first ? "" : " ", tag);
114         first = 0;
115     }
116
117     return result;
118 }
119
120 /* Get a nice, single-line summary of message. */
121 static const char *
122 _get_one_line_summary (const void *ctx, notmuch_message_t *message)
123 {
124     const char *from;
125     time_t date;
126     const char *relative_date;
127     const char *tags;
128
129     from = notmuch_message_get_header (message, "from");
130
131     date = notmuch_message_get_date (message);
132     relative_date = notmuch_time_relative_date (ctx, date);
133
134     tags = _get_tags_as_string (ctx, message);
135
136     return talloc_asprintf (ctx, "%s (%s) (%s)",
137                             from, relative_date, tags);
138 }
139
140 static void
141 format_message_text (unused (const void *ctx), notmuch_message_t *message, int indent)
142 {
143     printf ("id:%s depth:%d match:%d filename:%s\n",
144             notmuch_message_get_message_id (message),
145             indent,
146             notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH),
147             notmuch_message_get_filename (message));
148 }
149
150 static void
151 format_message_json (const void *ctx, notmuch_message_t *message, unused (int indent))
152 {
153     notmuch_tags_t *tags;
154     int first = 1;
155     void *ctx_quote = talloc_new (ctx);
156     time_t date;
157     const char *relative_date;
158
159     date = notmuch_message_get_date (message);
160     relative_date = notmuch_time_relative_date (ctx, date);
161
162     printf ("\"id\": %s, \"match\": %s, \"filename\": %s, \"timestamp\": %ld, \"date_relative\": \"%s\", \"tags\": [",
163             json_quote_str (ctx_quote, notmuch_message_get_message_id (message)),
164             notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH) ? "true" : "false",
165             json_quote_str (ctx_quote, notmuch_message_get_filename (message)),
166             date, relative_date);
167
168     for (tags = notmuch_message_get_tags (message);
169          notmuch_tags_valid (tags);
170          notmuch_tags_move_to_next (tags))
171     {
172          printf("%s%s", first ? "" : ",",
173                json_quote_str (ctx_quote, notmuch_tags_get (tags)));
174          first = 0;
175     }
176     printf("]");
177     talloc_free (ctx_quote);
178 }
179
180 /* Extract just the email address from the contents of a From:
181  * header. */
182 static const char *
183 _extract_email_address (const void *ctx, const char *from)
184 {
185     InternetAddressList *addresses;
186     InternetAddress *address;
187     InternetAddressMailbox *mailbox;
188     const char *email = "MAILER-DAEMON";
189
190     addresses = internet_address_list_parse_string (from);
191
192     /* Bail if there is no address here. */
193     if (addresses == NULL || internet_address_list_length (addresses) < 1)
194         goto DONE;
195
196     /* Otherwise, just use the first address. */
197     address = internet_address_list_get_address (addresses, 0);
198
199     /* The From header should never contain an address group rather
200      * than a mailbox. So bail if it does. */
201     if (! INTERNET_ADDRESS_IS_MAILBOX (address))
202         goto DONE;
203
204     mailbox = INTERNET_ADDRESS_MAILBOX (address);
205     email = internet_address_mailbox_get_addr (mailbox);
206     email = talloc_strdup (ctx, email);
207
208   DONE:
209     /* XXX: How to free addresses here? */
210     return email;
211    }
212
213 /* Return 1 if 'line' is an mbox From_ line---that is, a line
214  * beginning with zero or more '>' characters followed by the
215  * characters 'F', 'r', 'o', 'm', and space.
216  *
217  * Any characters at all may appear after that in the line.
218  */
219 static int
220 _is_from_line (const char *line)
221 {
222     const char *s = line;
223
224     if (line == NULL)
225         return 0;
226
227     while (*s == '>')
228         s++;
229
230     if (STRNCMP_LITERAL (s, "From ") == 0)
231         return 1;
232     else
233         return 0;
234 }
235
236 /* Print a message in "mboxrd" format as documented, for example,
237  * here:
238  *
239  * http://qmail.org/qmail-manual-html/man5/mbox.html
240  */
241 static void
242 format_message_mbox (const void *ctx,
243                      notmuch_message_t *message,
244                      unused (int indent))
245 {
246     const char *filename;
247     FILE *file;
248     const char *from;
249
250     time_t date;
251     struct tm date_gmtime;
252     char date_asctime[26];
253
254     char *line = NULL;
255     size_t line_size;
256     ssize_t line_len;
257
258     filename = notmuch_message_get_filename (message);
259     file = fopen (filename, "r");
260     if (file == NULL) {
261         fprintf (stderr, "Failed to open %s: %s\n",
262                  filename, strerror (errno));
263         return;
264     }
265
266     from = notmuch_message_get_header (message, "from");
267     from = _extract_email_address (ctx, from);
268
269     date = notmuch_message_get_date (message);
270     gmtime_r (&date, &date_gmtime);
271     asctime_r (&date_gmtime, date_asctime);
272
273     printf ("From %s %s", from, date_asctime);
274
275     while ((line_len = getline (&line, &line_size, file)) != -1 ) {
276         if (_is_from_line (line))
277             putchar ('>');
278         printf ("%s", line);
279     }
280
281     printf ("\n");
282
283     fclose (file);
284 }
285
286 static void
287 format_headers_text (const void *ctx, notmuch_message_t *message)
288 {
289     const char *headers[] = {
290         "Subject", "From", "To", "Cc", "Bcc", "Date"
291     };
292     const char *name, *value;
293     unsigned int i;
294
295     printf ("%s\n", _get_one_line_summary (ctx, message));
296
297     for (i = 0; i < ARRAY_SIZE (headers); i++) {
298         name = headers[i];
299         value = notmuch_message_get_header (message, name);
300         if (value && strlen (value))
301             printf ("%s: %s\n", name, value);
302     }
303 }
304
305 static void
306 format_headers_json (const void *ctx, notmuch_message_t *message)
307 {
308     const char *headers[] = {
309         "Subject", "From", "To", "Cc", "Bcc", "Date"
310     };
311     const char *name, *value;
312     unsigned int i;
313     int first_header = 1;
314     void *ctx_quote = talloc_new (ctx);
315
316     for (i = 0; i < ARRAY_SIZE (headers); i++) {
317         name = headers[i];
318         value = notmuch_message_get_header (message, name);
319         if (value)
320         {
321             if (!first_header)
322                 fputs (", ", stdout);
323             first_header = 0;
324
325             printf ("%s: %s",
326                     json_quote_str (ctx_quote, name),
327                     json_quote_str (ctx_quote, value));
328         }
329     }
330
331     talloc_free (ctx_quote);
332 }
333
334 static void
335 show_part_content (GMimeObject *part, GMimeStream *stream_out)
336 {
337     GMimeStream *stream_filter = NULL;
338     GMimeDataWrapper *wrapper;
339     const char *charset;
340
341     charset = g_mime_object_get_content_type_parameter (part, "charset");
342
343     if (stream_out) {
344         stream_filter = g_mime_stream_filter_new (stream_out);
345         g_mime_stream_filter_add(GMIME_STREAM_FILTER (stream_filter),
346                                  g_mime_filter_crlf_new (FALSE, FALSE));
347         if (charset) {
348             GMimeFilter *charset_filter;
349             charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
350             /* This result can be NULL for things like "unknown-8bit".
351              * Don't set a NULL filter as that makes GMime print
352              * annoying assertion-failure messages on stderr. */
353             if (charset_filter)
354                 g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
355                                           charset_filter);
356         }
357     }
358
359     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
360     if (wrapper && stream_filter)
361         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
362     if (stream_filter)
363         g_object_unref(stream_filter);
364 }
365
366 static void
367 format_part_text (GMimeObject *part, int *part_count)
368 {
369     GMimeContentDisposition *disposition;
370     GMimeContentType *content_type;
371
372     disposition = g_mime_object_get_content_disposition (part);
373     if (disposition &&
374         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
375     {
376         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
377         content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
378
379         printf ("\fattachment{ ID: %d, Content-type: %s\n",
380                 *part_count,
381                 g_mime_content_type_to_string (content_type));
382         printf ("Attachment: %s (%s)\n", filename,
383                 g_mime_content_type_to_string (content_type));
384
385         if (g_mime_content_type_is_type (content_type, "text", "*") &&
386             !g_mime_content_type_is_type (content_type, "text", "html"))
387         {
388             GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
389             g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
390             show_part_content (part, stream_stdout);
391             g_object_unref(stream_stdout);
392         }
393
394         printf ("\fattachment}\n");
395
396         return;
397     }
398
399     content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
400
401     printf ("\fpart{ ID: %d, Content-type: %s\n",
402             *part_count,
403             g_mime_content_type_to_string (content_type));
404
405     if (g_mime_content_type_is_type (content_type, "text", "*") &&
406         !g_mime_content_type_is_type (content_type, "text", "html"))
407     {
408         GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
409         g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
410         show_part_content (part, stream_stdout);
411         g_object_unref(stream_stdout);
412     }
413     else
414     {
415         printf ("Non-text part: %s\n",
416                 g_mime_content_type_to_string (content_type));
417     }
418
419     printf ("\fpart}\n");
420 }
421
422 static void
423 format_part_json (GMimeObject *part, int *part_count)
424 {
425     GMimeContentType *content_type;
426     GMimeContentDisposition *disposition;
427     void *ctx = talloc_new (NULL);
428     GMimeStream *stream_memory = g_mime_stream_mem_new ();
429     GByteArray *part_content;
430
431     content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
432
433     if (*part_count > 1)
434         fputs (", ", stdout);
435
436     printf ("{\"id\": %d, \"content-type\": %s",
437             *part_count,
438             json_quote_str (ctx, g_mime_content_type_to_string (content_type)));
439
440     disposition = g_mime_object_get_content_disposition (part);
441     if (disposition &&
442         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
443     {
444         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
445
446         printf (", \"filename\": %s", json_quote_str (ctx, filename));
447     }
448
449     if (g_mime_content_type_is_type (content_type, "text", "*") &&
450         !g_mime_content_type_is_type (content_type, "text", "html"))
451     {
452         show_part_content (part, stream_memory);
453         part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
454
455         printf (", \"content\": %s", json_quote_chararray (ctx, (char *) part_content->data, part_content->len));
456     }
457
458     fputs ("}", stdout);
459
460     talloc_free (ctx);
461     if (stream_memory)
462         g_object_unref (stream_memory);
463 }
464
465 static void
466 show_message (void *ctx, const show_format_t *format, notmuch_message_t *message, int indent)
467 {
468     fputs (format->message_start, stdout);
469     if (format->message)
470         format->message(ctx, message, indent);
471
472     fputs (format->header_start, stdout);
473     if (format->header)
474         format->header(ctx, message);
475     fputs (format->header_end, stdout);
476
477     fputs (format->body_start, stdout);
478     if (format->part)
479         show_message_body (notmuch_message_get_filename (message), format->part);
480     fputs (format->body_end, stdout);
481
482     fputs (format->message_end, stdout);
483 }
484
485
486 static void
487 show_messages (void *ctx, const show_format_t *format, notmuch_messages_t *messages, int indent,
488                notmuch_bool_t entire_thread)
489 {
490     notmuch_message_t *message;
491     notmuch_bool_t match;
492     int first_set = 1;
493     int next_indent;
494
495     fputs (format->message_set_start, stdout);
496
497     for (;
498          notmuch_messages_valid (messages);
499          notmuch_messages_move_to_next (messages))
500     {
501         if (!first_set)
502             fputs (format->message_set_sep, stdout);
503         first_set = 0;
504
505         fputs (format->message_set_start, stdout);
506
507         message = notmuch_messages_get (messages);
508
509         match = notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH);
510
511         next_indent = indent;
512
513         if (match || entire_thread) {
514             show_message (ctx, format, message, indent);
515             next_indent = indent + 1;
516
517             fputs (format->message_set_sep, stdout);
518         }
519
520         show_messages (ctx, format, notmuch_message_get_replies (message),
521                        next_indent, entire_thread);
522
523         notmuch_message_destroy (message);
524
525         fputs (format->message_set_end, stdout);
526     }
527
528     fputs (format->message_set_end, stdout);
529 }
530
531 int
532 notmuch_show_command (void *ctx, unused (int argc), unused (char *argv[]))
533 {
534     notmuch_config_t *config;
535     notmuch_database_t *notmuch;
536     notmuch_query_t *query;
537     notmuch_threads_t *threads;
538     notmuch_thread_t *thread;
539     notmuch_messages_t *messages;
540     char *query_string;
541     char *opt;
542     const show_format_t *format = &format_text;
543     int entire_thread = 0;
544     int i;
545     int first_toplevel = 1;
546
547     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
548         if (strcmp (argv[i], "--") == 0) {
549             i++;
550             break;
551         }
552         if (STRNCMP_LITERAL (argv[i], "--format=") == 0) {
553             opt = argv[i] + sizeof ("--format=") - 1;
554             if (strcmp (opt, "text") == 0) {
555                 format = &format_text;
556             } else if (strcmp (opt, "json") == 0) {
557                 format = &format_json;
558                 entire_thread = 1;
559             } else if (strcmp (opt, "mbox") == 0) {
560                 format = &format_mbox;
561             } else {
562                 fprintf (stderr, "Invalid value for --format: %s\n", opt);
563                 return 1;
564             }
565         } else if (STRNCMP_LITERAL (argv[i], "--entire-thread") == 0) {
566             entire_thread = 1;
567         } else {
568             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
569             return 1;
570         }
571     }
572
573     argc -= i;
574     argv += i;
575
576     config = notmuch_config_open (ctx, NULL, NULL);
577     if (config == NULL)
578         return 1;
579
580     query_string = query_string_from_args (ctx, argc, argv);
581     if (query_string == NULL) {
582         fprintf (stderr, "Out of memory\n");
583         return 1;
584     }
585
586     if (*query_string == '\0') {
587         fprintf (stderr, "Error: notmuch show requires at least one search term.\n");
588         return 1;
589     }
590
591     notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
592                                      NOTMUCH_DATABASE_MODE_READ_ONLY);
593     if (notmuch == NULL)
594         return 1;
595
596     query = notmuch_query_create (notmuch, query_string);
597     if (query == NULL) {
598         fprintf (stderr, "Out of memory\n");
599         return 1;
600     }
601
602     fputs (format->message_set_start, stdout);
603
604     for (threads = notmuch_query_search_threads (query);
605          notmuch_threads_valid (threads);
606          notmuch_threads_move_to_next (threads))
607     {
608         thread = notmuch_threads_get (threads);
609
610         messages = notmuch_thread_get_toplevel_messages (thread);
611
612         if (messages == NULL)
613             INTERNAL_ERROR ("Thread %s has no toplevel messages.\n",
614                             notmuch_thread_get_thread_id (thread));
615
616         if (!first_toplevel)
617             fputs (format->message_set_sep, stdout);
618         first_toplevel = 0;
619
620         show_messages (ctx, format, messages, 0, entire_thread);
621
622         notmuch_thread_destroy (thread);
623
624     }
625
626     fputs (format->message_set_end, stdout);
627
628     notmuch_query_destroy (query);
629     notmuch_database_close (notmuch);
630
631     return 0;
632 }
633
634 int
635 notmuch_part_command (void *ctx, unused (int argc), unused (char *argv[]))
636 {
637         notmuch_config_t *config;
638         notmuch_database_t *notmuch;
639         notmuch_query_t *query;
640         notmuch_messages_t *messages;
641         notmuch_message_t *message;
642         char *query_string;
643         int i;
644         int part = 0;
645
646         for (i = 0; i < argc && argv[i][0] == '-'; i++) {
647                 if (strcmp (argv[i], "--") == 0) {
648                         i++;
649                         break;
650                 }
651                 if (STRNCMP_LITERAL (argv[i], "--part=") == 0) {
652                         part = atoi(argv[i] + sizeof ("--part=") - 1);
653                 } else {
654                         fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
655                         return 1;
656                 }
657         }
658
659         argc -= i;
660         argv += i;
661
662         config = notmuch_config_open (ctx, NULL, NULL);
663         if (config == NULL)
664                 return 1;
665
666         query_string = query_string_from_args (ctx, argc, argv);
667         if (query_string == NULL) {
668                 fprintf (stderr, "Out of memory\n");
669                 return 1;
670         }
671
672         if (*query_string == '\0') {
673                 fprintf (stderr, "Error: notmuch part requires at least one search term.\n");
674                 return 1;
675         }
676
677         notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
678                                          NOTMUCH_DATABASE_MODE_READ_ONLY);
679         if (notmuch == NULL)
680                 return 1;
681
682         query = notmuch_query_create (notmuch, query_string);
683         if (query == NULL) {
684                 fprintf (stderr, "Out of memory\n");
685                 return 1;
686         }
687
688         if (notmuch_query_count_messages (query) != 1) {
689                 fprintf (stderr, "Error: search term did not match precisely one message.\n");
690                 return 1;
691         }
692
693         messages = notmuch_query_search_messages (query);
694         message = notmuch_messages_get (messages);
695
696         if (message == NULL) {
697                 fprintf (stderr, "Error: cannot find matching message.\n");
698                 return 1;
699         }
700
701         show_one_part (notmuch_message_get_filename (message), part);
702
703         notmuch_query_destroy (query);
704         notmuch_database_close (notmuch);
705
706         return 0;
707 }