forked from neomutt/neomutt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutt_notmuch.c
2636 lines (2224 loc) · 64.4 KB
/
mutt_notmuch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file
* NotMuch virtual mailbox type
*
* @authors
* Copyright (C) 2011-2016 Karel Zak <[email protected]>
* Copyright (C) 2016-2017 Richard Russon <[email protected]>
* Copyright (C) 2016 Kevin Velghe <[email protected]>
* Copyright (C) 2017 Bernard 'Guyzmo' Pratz <[email protected]>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* ## Notes
*
* - notmuch uses private Context->data and private Header->data
*
* - all exported functions are usable within notmuch context only
*
* - all functions have to be covered by "ctx->magic == MUTT_NOTMUCH" check
* (it's implemented in get_ctxdata() and init_context() functions).
*
* - exception are nm_nonctx_* functions -- these functions use nm_default_uri
* (or parse URI from another resource)
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <notmuch.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "mutt.h"
#include "mutt_notmuch.h"
#include "body.h"
#include "buffy.h"
#include "context.h"
#include "envelope.h"
#include "globals.h"
#include "header.h"
#include "lib/lib.h"
#include "mailbox.h"
#include "mutt_curses.h"
#include "mx.h"
#include "protos.h"
#include "thread.h"
#include "url.h"
#ifdef LIBNOTMUCH_CHECK_VERSION
#undef LIBNOTMUCH_CHECK_VERSION
#endif
/* @def The definition in <notmuch.h> is broken */
#define LIBNOTMUCH_CHECK_VERSION(_major, _minor, _micro) \
(LIBNOTMUCH_MAJOR_VERSION > (_major) || \
(LIBNOTMUCH_MAJOR_VERSION == (_major) && LIBNOTMUCH_MINOR_VERSION > (_minor)) || \
(LIBNOTMUCH_MAJOR_VERSION == (_major) && LIBNOTMUCH_MINOR_VERSION == (_minor) && \
LIBNOTMUCH_MICRO_VERSION >= (_micro)))
/**
* enum NmQueryType - NotMuch Query Types
*
* Read whole-thread or matching messages only?
*/
enum NmQueryType
{
NM_QUERY_TYPE_MESGS = 1, /**< Default: Messages only */
NM_QUERY_TYPE_THREADS /**< Whole threads */
};
/**
* struct UriTag - Parsed NotMuch-URI arguments
*
* The arguments in a URI are saved in a linked list.
*
* @sa NmCtxData#query_items
*/
struct UriTag
{
char *name;
char *value;
struct UriTag *next;
};
/**
* struct NmHdrTag - NotMuch Mail Header Tags
*
* Keep a linked list of header tags and their transformed values.
* Textual tags can be transformed to symbols to save space.
*
* @sa NmHdrData#tag_list
*/
struct NmHdrTag
{
char *tag;
char *transformed;
struct NmHdrTag *next;
};
/**
* struct NmHdrData - NotMuch data attached to an email
*
* This stores all the NotMuch data associated with an email.
*
* @sa Header#data, MUTT_MBOX
*/
struct NmHdrData
{
char *folder; /**< Location of the email */
char *tags;
char *tags_transformed;
struct NmHdrTag *tag_list;
char *oldpath;
char *virtual_id; /**< Unique NotMuch Id */
int magic; /**< Type of mailbox the email is in */
};
/**
* struct NmCtxData - NotMuch data attached to a context
*
* This stores the global NotMuch data, such as the database connection.
*
* @sa Context#data, NotmuchDBLimit, NM_QUERY_TYPE_MESGS
*/
struct NmCtxData
{
notmuch_database_t *db;
char *db_filename; /**< Filename of the NotMuch database */
char *db_query; /**< Previous query */
int db_limit; /**< Maximum number of results to return */
int query_type; /**< Messages or Threads */
struct UriTag *query_items;
struct Progress progress; /**< A progress bar */
int oldmsgcount;
int ignmsgcount; /**< Ignored messages */
bool noprogress : 1; /**< Don't show the progress bar */
bool longrun : 1; /**< A long-lived action is in progress */
bool trans : 1; /**< Atomic transaction in progress */
bool progress_ready : 1; /**< A progress bar has been initialised */
};
#if 0
/**
* debug_print_filenames - Show a message's filenames
* @param msg NotMuch Message
*
* Print a list of all the filenames associated with a NotMuch message.
*/
static void debug_print_filenames(notmuch_message_t *msg)
{
notmuch_filenames_t *ls = NULL;
const char *id = notmuch_message_get_message_id(msg);
for (ls = notmuch_message_get_filenames(msg);
ls && notmuch_filenames_valid(ls);
notmuch_filenames_move_to_next(ls))
{
mutt_debug (2, "nm: %s: %s\n", id, notmuch_filenames_get(ls));
}
}
/**
* debug_print_tags - Show a message's tags
* @param msg NotMuch Message
*
* Print a list of all the tags associated with a NotMuch message.
*/
static void debug_print_tags(notmuch_message_t *msg)
{
notmuch_tags_t *tags = NULL;
const char *id = notmuch_message_get_message_id(msg);
for (tags = notmuch_message_get_tags(msg);
tags && notmuch_tags_valid(tags);
notmuch_tags_move_to_next(tags))
{
mutt_debug (2, "nm: %s: %s\n", id, notmuch_tags_get(tags));
}
}
#endif
/**
* url_free_tags - Free a list of tags
* @param tags List of tags
*
* Tags are stored as a singly-linked list.
* Free all the strings and the list, itself.
*/
static void url_free_tags(struct UriTag *tags)
{
while (tags)
{
struct UriTag *next = tags->next;
FREE(&tags->name);
FREE(&tags->value);
FREE(&tags);
tags = next;
}
}
/**
* url_parse_query - Extract the tokens from a query URI
* @param[in] url URI to parse
* @param[out] filename Save the filename
* @param[out] tags Save the list of tags
* @retval true Success
* @retval false Error Bad format
*
* Parse a NotMuch URI, such as:
* * notmuch:///path/to/db?query=tag:lkml&limit=1000
* * notmuch://?query=neomutt
*
* Extract the database filename (optional) and any search parameters (tags).
* The tags will be saved in a linked list (#UriTag).
*/
static bool url_parse_query(const char *url, char **filename, struct UriTag **tags)
{
char *p = strstr(url, "://"); /* remote unsupported */
char *e = NULL;
struct UriTag *tag, *last = NULL;
*filename = NULL;
*tags = NULL;
if (!p || !*(p + 3))
return false;
p += 3;
*filename = p;
e = strchr(p, '?');
*filename = e ? (e == p) ? NULL : mutt_substrdup(p, e) : safe_strdup(p);
if (!e)
return true; /* only filename */
if (*filename && (url_pct_decode(*filename) < 0))
goto err;
e++; /* skip '?' */
p = e;
while (p && *p)
{
tag = safe_calloc(1, sizeof(struct UriTag));
if (!*tags)
last = *tags = tag;
else
{
last->next = tag;
last = tag;
}
e = strchr(p, '=');
if (!e)
e = strchr(p, '&');
tag->name = e ? mutt_substrdup(p, e) : safe_strdup(p);
if (!tag->name || (url_pct_decode(tag->name) < 0))
goto err;
if (!e)
break;
p = e + 1;
if (*e == '&')
continue;
e = strchr(p, '&');
tag->value = e ? mutt_substrdup(p, e) : safe_strdup(p);
if (!tag->value || (url_pct_decode(tag->value) < 0))
goto err;
if (!e)
break;
p = e + 1;
}
return true;
err:
FREE(&(*filename));
url_free_tags(*tags);
return false;
}
/**
* free_tag_list - Free a list of tags
* @param tag_list List of tags
*
* Take a nm_hdrtag struct (a singly-linked list) and free the attached strings
* and the list itself.
*/
static void free_tag_list(struct NmHdrTag **tag_list)
{
struct NmHdrTag *tmp = NULL;
while ((tmp = *tag_list) != NULL)
{
*tag_list = tmp->next;
FREE(&tmp->tag);
FREE(&tmp->transformed);
FREE(&tmp);
}
*tag_list = 0;
}
/**
* free_hdrdata - Free header data attached to an email
* @param data Header data
*
* Each email can have an attached nm_hdrdata struct, which contains things
* like the tags (labels). This function frees all the resources and the
* nm_hdrdata struct itself.
*/
static void free_hdrdata(struct NmHdrData *data)
{
if (!data)
return;
mutt_debug(2, "nm: freeing header %p\n", (void *) data);
FREE(&data->folder);
FREE(&data->tags);
FREE(&data->tags_transformed);
free_tag_list(&data->tag_list);
FREE(&data->oldpath);
FREE(&data->virtual_id);
FREE(&data);
}
/**
* free_ctxdata - Free data attached to the context
* @param data A mailbox CONTEXT
*
* The nm_ctxdata struct stores global NotMuch data, such as the connection to
* the database. This function will close the database, free the resources and
* the struct itself.
*/
static void free_ctxdata(struct NmCtxData *data)
{
if (!data)
return;
mutt_debug(1, "nm: freeing context data %p\n", (void *) data);
if (data->db)
#ifdef NOTMUCH_API_3
notmuch_database_destroy(data->db);
#else
notmuch_database_close(data->db);
#endif
data->db = NULL;
FREE(&data->db_filename);
FREE(&data->db_query);
url_free_tags(data->query_items);
FREE(&data);
}
/**
* new_ctxdata - Create a new nm_ctxdata object from a query
* @param uri NotMuch query string
* @retval ptr New nm_ctxdata struct
*
* A new nm_ctxdata struct is created, then the query is parsed and saved
* within it. This should be freed using free_ctxdata().
*/
static struct NmCtxData *new_ctxdata(char *uri)
{
struct NmCtxData *data = NULL;
if (!uri)
return NULL;
data = safe_calloc(1, sizeof(struct NmCtxData));
mutt_debug(1, "nm: initialize context data %p\n", (void *) data);
data->db_limit = NotmuchDBLimit;
if (!url_parse_query(uri, &data->db_filename, &data->query_items))
{
mutt_error(_("failed to parse notmuch uri: %s"), uri);
FREE(&data);
return NULL;
}
return data;
}
/**
* init_context - Add NotMuch data to the Context
* @param ctx A mailbox CONTEXT
* @retval 0 Success
* @retval -1 Error Bad format
*
* Create a new nm_ctxdata struct and add it CONTEXT::data.
* NotMuch-specific data will be stored in this struct.
* This struct can be freed using free_hdrdata().
*/
static int init_context(struct Context *ctx)
{
if (!ctx || (ctx->magic != MUTT_NOTMUCH))
return -1;
if (ctx->data)
return 0;
ctx->data = new_ctxdata(ctx->path);
if (!ctx->data)
return -1;
return 0;
}
static char *header_get_id(struct Header *h)
{
return (h && h->data) ? ((struct NmHdrData *) h->data)->virtual_id : NULL;
}
static char *header_get_fullpath(struct Header *h, char *buf, size_t bufsz)
{
snprintf(buf, bufsz, "%s/%s", nm_header_get_folder(h), h->path);
return buf;
}
static struct NmCtxData *get_ctxdata(struct Context *ctx)
{
if (ctx && (ctx->magic == MUTT_NOTMUCH))
return ctx->data;
return NULL;
}
static int string_to_query_type(const char *str)
{
if (!str)
str = NotmuchQueryType; /* user's default */
if (!str)
return NM_QUERY_TYPE_MESGS; /* hardcoded default */
if (strcmp(str, "threads") == 0)
return NM_QUERY_TYPE_THREADS;
else if (strcmp(str, "messages") == 0)
return NM_QUERY_TYPE_MESGS;
mutt_error(_("failed to parse notmuch query type: %s"), str);
return NM_QUERY_TYPE_MESGS;
}
/**
* query_window_check_timebase - Checks if a given timebase string is valid
* @param[in] timebase: string containing a time base
* @retval true if the given time base is valid
*
* This function returns whether a given timebase string is valid or not,
* which is used to validate the user settable configuration setting:
*
* nm_query_window_timebase
*/
static bool query_window_check_timebase(const char *timebase)
{
if ((strcmp(timebase, "hour") == 0) || (strcmp(timebase, "day") == 0) ||
(strcmp(timebase, "week") == 0) || (strcmp(timebase, "month") == 0) ||
(strcmp(timebase, "year") == 0))
return true;
return false;
}
/**
* query_window_reset - Restore vfolder's search window to its original position
*
* After moving a vfolder search window backward and forward, calling this function
* will reset the search position to its original value, setting to 0 the user settable
* variable:
*
* nm_query_window_current_position
*/
static void query_window_reset(void)
{
mutt_debug(2, "query_window_reset ()\n");
NotmuchQueryWindowCurrentPosition = 0;
}
/**
* windowed_query_from_query - transforms a vfolder search query into a windowed one
* @param[in] query vfolder search string
* @param[out] buf allocated string buffer to receive the modified search query
* @param[in] bufsz allocated maximum size of the buf string buffer
* @retval true Transformed search query is available as a string in buf
* @retval false Search query shall not be transformed
*
* This is where the magic of windowed queries happens. Taking a vfolder search
* query string as parameter, it will use the following two user settings:
*
* - `nm_query_window_duration` and
* - `nm_query_window_timebase`
*
* to amend given vfolder search window. Then using a third parameter:
*
* - `nm_query_window_current_position`
*
* it will generate a proper notmuch `date:` parameter. For example, given a
* duration of `2`, a timebase set to `week` and a position defaulting to `0`,
* it will prepend to the 'tag:inbox' notmuch search query the following string:
*
* - `query`: `tag:inbox`
* - `buf`: `date:2week..now and tag:inbox`
*
* If the position is set to `4`, with `duration=3` and `timebase=month`:
*
* - `query`: `tag:archived`
* - `buf`: `date:12month..9month and tag:archived`
*
* The window won't be applied:
*
* - If the duration of the search query is set to `0` this function will be disabled.
* - If the timebase is invalid, it will show an error message and do nothing.
*
* If there's no search registered in `nm_query_window_current_search` or this is
* a new search, it will reset the window and do the search.
*/
static bool windowed_query_from_query(const char *query, char *buf, size_t bufsz)
{
mutt_debug(2, "nm: windowed_query_from_query (%s)\n", query);
int beg = NotmuchQueryWindowDuration * (NotmuchQueryWindowCurrentPosition + 1);
int end = NotmuchQueryWindowDuration * NotmuchQueryWindowCurrentPosition;
/* if the duration is a non positive integer, disable the window */
if (NotmuchQueryWindowDuration <= 0)
{
query_window_reset();
return false;
}
/* if the query has changed, reset the window position */
if (NotmuchQueryWindowCurrentSearch == NULL ||
(strcmp(query, NotmuchQueryWindowCurrentSearch) != 0))
query_window_reset();
if (!query_window_check_timebase(NotmuchQueryWindowTimebase))
{
mutt_message(_("Invalid nm_query_window_timebase value (valid values are: "
"hour, day, week, month or year)."));
mutt_debug(2, "Invalid nm_query_window_timebase value\n");
return false;
}
if (end == 0)
snprintf(buf, bufsz, "date:%d%s..now and %s", beg,
NotmuchQueryWindowTimebase, NotmuchQueryWindowCurrentSearch);
else
snprintf(buf, bufsz, "date:%d%s..%d%s and %s", beg, NotmuchQueryWindowTimebase,
end, NotmuchQueryWindowTimebase, NotmuchQueryWindowCurrentSearch);
mutt_debug(2, "nm: windowed_query_from_query (%s) -> %s\n", query, buf);
return true;
}
/**
* get_query_string - builds the notmuch vfolder search string
* @param data internal notmuch context
* @param window if true enable application of the window on the search string
* @retval string Containing a notmuch search query
* @retval NULL If none can be generated
*
* This function parses the internal representation of a search, and returns
* a search query string ready to be fed to the notmuch API, given the search
* is valid.
*
* As a note, the window parameter here is here to decide contextually whether
* we want to return a search query with window applied (for the actual search
* result in buffy) or not (for the count in the sidebar). It is not aimed at
* enabling/disabling the feature.
*/
static char *get_query_string(struct NmCtxData *data, int window)
{
mutt_debug(2, "nm: get_query_string(%d)\n", window);
struct UriTag *item = NULL;
if (!data)
return NULL;
if (data->db_query)
return data->db_query;
for (item = data->query_items; item; item = item->next)
{
if (!item->value || !item->name)
continue;
if (strcmp(item->name, "limit") == 0)
{
if (mutt_atoi(item->value, &data->db_limit))
mutt_error(_("failed to parse notmuch limit: %s"), item->value);
}
else if (strcmp(item->name, "type") == 0)
data->query_type = string_to_query_type(item->value);
else if (strcmp(item->name, "query") == 0)
data->db_query = safe_strdup(item->value);
}
if (!data->db_query)
return NULL;
if (!data->query_type)
data->query_type = string_to_query_type(NULL);
if (window)
{
char buf[LONG_STRING];
mutt_str_replace(&NotmuchQueryWindowCurrentSearch, data->db_query);
/* if a date part is defined, do not apply windows (to avoid the risk of
* having a non-intersected date frame). A good improvement would be to
* accept if they intersect
*/
if (!strstr(data->db_query, "date:") &&
windowed_query_from_query(data->db_query, buf, sizeof(buf)))
data->db_query = safe_strdup(buf);
mutt_debug(2, "nm: query (windowed) '%s'\n", data->db_query);
}
else
mutt_debug(2, "nm: query '%s'\n", data->db_query);
return data->db_query;
}
static int get_limit(struct NmCtxData *data)
{
return data ? data->db_limit : 0;
}
static int get_query_type(struct NmCtxData *data)
{
return (data && data->query_type) ? data->query_type : string_to_query_type(NULL);
}
static const char *get_db_filename(struct NmCtxData *data)
{
char *db_filename = NULL;
if (!data)
return NULL;
db_filename = data->db_filename ? data->db_filename : NotmuchDefaultUri;
if (!db_filename)
db_filename = Maildir;
if (!db_filename)
return NULL;
if (strncmp(db_filename, "notmuch://", 10) == 0)
db_filename += 10;
mutt_debug(2, "nm: db filename '%s'\n", db_filename);
return db_filename;
}
static notmuch_database_t *do_database_open(const char *filename, int writable, int verbose)
{
notmuch_database_t *db = NULL;
int ct = 0;
notmuch_status_t st = NOTMUCH_STATUS_SUCCESS;
mutt_debug(1, "nm: db open '%s' %s (timeout %d)\n", filename,
writable ? "[WRITE]" : "[READ]", NotmuchOpenTimeout);
do
{
#ifdef NOTMUCH_API_3
st = notmuch_database_open(filename, writable ? NOTMUCH_DATABASE_MODE_READ_WRITE : NOTMUCH_DATABASE_MODE_READ_ONLY,
&db);
#else
db = notmuch_database_open(filename,
writable ? NOTMUCH_DATABASE_MODE_READ_WRITE :
NOTMUCH_DATABASE_MODE_READ_ONLY);
#endif
if (db || !NotmuchOpenTimeout || ((ct / 2) > NotmuchOpenTimeout))
break;
if (verbose && ct && ((ct % 2) == 0))
mutt_error(_("Waiting for notmuch DB... (%d sec)"), ct / 2);
usleep(500000);
ct++;
} while (true);
if (verbose)
{
if (!db)
mutt_error(_("Cannot open notmuch database: %s: %s"), filename,
st ? notmuch_status_to_string(st) : _("unknown reason"));
else if (ct > 1)
mutt_clear_error();
}
return db;
}
static notmuch_database_t *get_db(struct NmCtxData *data, int writable)
{
if (!data)
return NULL;
if (!data->db)
{
const char *db_filename = get_db_filename(data);
if (db_filename)
data->db = do_database_open(db_filename, writable, true);
}
return data->db;
}
static int release_db(struct NmCtxData *data)
{
if (data && data->db)
{
mutt_debug(1, "nm: db close\n");
#ifdef NOTMUCH_API_3
notmuch_database_destroy(data->db);
#else
notmuch_database_close(data->db);
#endif
data->db = NULL;
data->longrun = false;
return 0;
}
return -1;
}
/**
* db_trans_begin - Start a NotMuch database transaction
* @param data Header data
* @retval <0 error
* @retval 1 new transaction started
* @retval 0 already within transaction
*/
static int db_trans_begin(struct NmCtxData *data)
{
if (!data || !data->db)
return -1;
if (!data->trans)
{
mutt_debug(2, "nm: db trans start\n");
if (notmuch_database_begin_atomic(data->db))
return -1;
data->trans = true;
return 1;
}
return 0;
}
static int db_trans_end(struct NmCtxData *data)
{
if (!data || !data->db)
return -1;
if (data->trans)
{
mutt_debug(2, "nm: db trans end\n");
data->trans = false;
if (notmuch_database_end_atomic(data->db))
return -1;
}
return 0;
}
/**
* is_longrun - Is NotMuch in the middle of a long-running transaction
* @param data Header data
* @retval true if it is
*/
static int is_longrun(struct NmCtxData *data)
{
return data && data->longrun;
}
/**
* get_database_mtime - Get the database modification time
* @param[in] data Struct holding database info
* @param[out] mtime Save the modification time
* @retval 0 Success (result in mtime)
* @retval -1 Error
*
* Get the "mtime" (modification time) of the database file.
* This is the time of the last update.
*/
static int get_database_mtime(struct NmCtxData *data, time_t *mtime)
{
char path[_POSIX_PATH_MAX];
struct stat st;
if (!data)
return -1;
snprintf(path, sizeof(path), "%s/.notmuch/xapian", get_db_filename(data));
mutt_debug(2, "nm: checking '%s' mtime\n", path);
if (stat(path, &st))
return -1;
if (mtime)
*mtime = st.st_mtime;
return 0;
}
static void apply_exclude_tags(notmuch_query_t *query)
{
char *buf = NULL, *p = NULL, *end = NULL, *tag = NULL;
if (!NotmuchExcludeTags || !*NotmuchExcludeTags)
return;
buf = safe_strdup(NotmuchExcludeTags);
for (p = buf; p && *p; p++)
{
if (!tag && isspace(*p))
continue;
if (!tag)
tag = p; /* begin of the tag */
if ((*p == ',') || (*p == ' '))
end = p; /* terminate the tag */
else if (*(p + 1) == '\0')
end = p + 1; /* end of optstr */
if (!tag || !end)
continue;
if (tag >= end)
break;
*end = '\0';
mutt_debug(2, "nm: query exclude tag '%s'\n", tag);
notmuch_query_add_tag_exclude(query, tag);
end = tag = NULL;
}
notmuch_query_set_omit_excluded(query, 1);
FREE(&buf);
}
static notmuch_query_t *get_query(struct NmCtxData *data, int writable)
{
notmuch_database_t *db = NULL;
notmuch_query_t *q = NULL;
const char *str = NULL;
if (!data)
return NULL;
db = get_db(data, writable);
str = get_query_string(data, true);
if (!db || !str)
goto err;
q = notmuch_query_create(db, str);
if (!q)
goto err;
apply_exclude_tags(q);
notmuch_query_set_sort(q, NOTMUCH_SORT_NEWEST_FIRST);
mutt_debug(2, "nm: query successfully initialized (%s)\n", str);
return q;
err:
if (!is_longrun(data))
release_db(data);
return NULL;
}
static void append_str_item(char **str, const char *item, int sep)
{
char *p = NULL;
size_t sz = strlen(item);
size_t ssz = *str ? strlen(*str) : 0;
safe_realloc(str, ssz + ((ssz && sep) ? 1 : 0) + sz + 1);
p = *str + ssz;
if (sep && ssz)
*p++ = sep;
memcpy(p, item, sz + 1);
}
static int update_header_tags(struct Header *h, notmuch_message_t *msg)
{
struct NmHdrData *data = h->data;
notmuch_tags_t *tags = NULL;
char *tstr = NULL, *ttstr = NULL;
struct NmHdrTag *tag_list = NULL, *tmp = NULL;
mutt_debug(2, "nm: tags update requested (%s)\n", data->virtual_id);
for (tags = notmuch_message_get_tags(msg); tags && notmuch_tags_valid(tags);
notmuch_tags_move_to_next(tags))
{
const char *t = notmuch_tags_get(tags);
const char *tt = NULL;
if (!t || !*t)
continue;
tt = hash_find(TagTransforms, t);
if (!tt)
tt = t;
/* tags list contains all tags */
tmp = safe_calloc(1, sizeof(*tmp));
tmp->tag = safe_strdup(t);
tmp->transformed = safe_strdup(tt);
tmp->next = tag_list;
tag_list = tmp;
/* filter out hidden tags */
if (NotmuchHiddenTags)
{
char *p = strstr(NotmuchHiddenTags, t);
size_t xsz = p ? strlen(t) : 0;
if (p && ((p == NotmuchHiddenTags) || (*(p - 1) == ',') || (*(p - 1) == ' ')) &&
((*(p + xsz) == '\0') || (*(p + xsz) == ',') || (*(p + xsz) == ' ')))
continue;
}
/* expand the transformed tag string */
append_str_item(&ttstr, tt, ' ');
/* expand the un-transformed tag string */
append_str_item(&tstr, t, ' ');
}
free_tag_list(&data->tag_list);
data->tag_list = tag_list;
if (data->tags && tstr && (strcmp(data->tags, tstr) == 0))
{
FREE(&tstr);
FREE(&ttstr);
mutt_debug(2, "nm: tags unchanged\n");
return 1;
}
/* free old version */
FREE(&data->tags);
FREE(&data->tags_transformed);
/* new version */
data->tags = tstr;
mutt_debug(2, "nm: new tags: '%s'\n", tstr);
data->tags_transformed = ttstr;
mutt_debug(2, "nm: new tag transforms: '%s'\n", ttstr);
return 0;
}
static int update_message_path(struct Header *h, const char *path)
{
struct NmHdrData *data = h->data;
char *p = NULL;
mutt_debug(2, "nm: path update requested path=%s, (%s)\n", path, data->virtual_id);
p = strrchr(path, '/');
if (p && ((p - path) > 3) &&
((strncmp(p - 3, "cur", 3) == 0) || (strncmp(p - 3, "new", 3) == 0) ||
(strncmp(p - 3, "tmp", 3) == 0)))
{
data->magic = MUTT_MAILDIR;
FREE(&h->path);
FREE(&data->folder);
p -= 3; /* skip subfolder (e.g. "new") */
h->path = safe_strdup(p);
for (; (p > path) && (*(p - 1) == '/'); p--)
;
data->folder = mutt_substrdup(path, p);