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