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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
|
# Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com>
# Copyright © 2018 Dylan Baker
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
import argparse
import logging
import mailcap
import os
import subprocess
import tempfile
import email
import email.policy
from email.utils import getaddresses, parseaddr
from email.message import Message
import urwid
from io import BytesIO
from . import Command, registerCommand
from .globals import ExternalCommand
from .globals import FlushCommand
from .globals import ComposeCommand
from .globals import MoveCommand
from .globals import CommandCanceled
from .common import RetagPromptCommand
from .envelope import SendCommand
from ..completion.contacts import ContactsCompleter
from ..completion.path import PathCompleter
from ..db.envelope import Envelope
from ..db.attachment import Attachment
from ..db.errors import DatabaseROError
from ..settings.const import settings
from ..helper import formataddr
from ..helper import parse_mailcap_nametemplate
from ..helper import split_commandstring
from ..utils import argparse as cargparse
MODE = 'thread'
def ensure_unique_address(recipients):
"""
clean up a list of name,address pairs so that
no address appears multiple times.
"""
res = dict()
for name, address in email.utils.getaddresses(recipients):
res[address] = name
logging.debug(res)
urecipients = [formataddr((n, a)) for a, n in res.items()]
return sorted(urecipients)
def clear_my_address(my_account, value):
"""return recipient header without the addresses in my_account
:param my_account: my account
:type my_account: :class:`Account`
:param value: a list of recipient or sender strings (with or without
real names as taken from email headers)
:type value: list(str)
:returns: a new, potentially shortend list
:rtype: list(str)
"""
new_value = []
for name, address in email.utils.getaddresses(value):
if not my_account.matches_address(address):
new_value.append(formataddr((name, address)))
return new_value
def determine_sender(mail, action='reply'):
"""
Inspect a given mail to reply/forward/bounce and find the most appropriate
account to act from and construct a suitable From-Header to use.
:param mail: the email to inspect
:type mail: `email.message.Message`
:param action: intended use case: one of "reply", "forward" or "bounce"
:type action: str
"""
assert action in ['reply', 'forward', 'bounce']
# get accounts
my_accounts = settings.get_accounts()
assert my_accounts, 'no accounts set!'
# extract list of addresses to check for my address
# X-Envelope-To and Envelope-To are used to store the recipient address
# if not included in other fields
# Process the headers in order of importance: if a mail was sent with
# account X, with account Y in e.g. CC or delivered-to, make sure that
# account X is the one selected and not account Y.
candidate_headers = settings.get("reply_account_header_priority")
for candidate_header in candidate_headers:
candidate_addresses = getaddresses(mail.get_all(candidate_header, []))
logging.debug('candidate addresses: %s', candidate_addresses)
# pick the most important account that has an address in candidates
# and use that account's realname and the address found here
for account in my_accounts:
for seen_name, seen_address in candidate_addresses:
if account.matches_address(seen_address):
if settings.get(action + '_force_realname'):
realname = account.realname
else:
realname = seen_name
if settings.get(action + '_force_address'):
address = str(account.address)
else:
address = seen_address
logging.debug('using realname: "%s"', realname)
logging.debug('using address: %s', address)
from_value = formataddr((realname, address))
return from_value, account
# revert to default account if nothing found
account = my_accounts[0]
realname = account.realname
address = account.address
logging.debug('using realname: "%s"', realname)
logging.debug('using address: %s', address)
from_value = formataddr((realname, str(address)))
return from_value, account
@registerCommand(MODE, 'reply', arguments=[
(['--all'], {'action': 'store_true', 'help': 'reply to all'}),
(['--list'], {'action': cargparse.BooleanAction, 'default': None,
'dest': 'listreply', 'help': 'reply to list'}),
(['--spawn'], {'action': cargparse.BooleanAction, 'default': None,
'help': 'open editor in new window'})])
class ReplyCommand(Command):
"""reply to message"""
repeatable = True
def __init__(self, message=None, all=False, listreply=None, spawn=None,
**kwargs):
"""
:param message: message to reply to (defaults to selected message)
:type message: `alot.db.message.Message`
:param all: group reply; copies recipients from Bcc/Cc/To to the reply
:type all: bool
:param listreply: reply to list; autodetect if unset and enabled in
config
:type listreply: bool
:param spawn: force spawning of editor in a new terminal
:type spawn: bool
"""
self.message = message
self.groupreply = all
self.listreply = listreply
self.force_spawn = spawn
Command.__init__(self, **kwargs)
async def apply(self, ui):
# get message to reply to if not given in constructor
if not self.message:
self.message = ui.current_buffer.get_selected_message()
mail = self.message.get_email()
# set body text
name, address = parseaddr(mail['From'])
timestamp = self.message.date
qf = settings.get_hook('reply_prefix')
if qf:
quotestring = qf(name, address, timestamp,
message=mail, ui=ui, dbm=ui.dbman)
else:
quotestring = 'Quoting %s (%s)\n' % (name or address, timestamp)
mailcontent = quotestring
quotehook = settings.get_hook('text_quote')
if quotehook:
mailcontent += quotehook(self.message.get_body_text())
else:
quote_prefix = settings.get('quote_prefix')
for line in self.message.get_body_text().splitlines():
mailcontent += quote_prefix + line + '\n'
envelope = Envelope(bodytext=mailcontent, replied=self.message)
# copy subject
subject = mail.get('Subject', '')
reply_subject_hook = settings.get_hook('reply_subject')
if reply_subject_hook:
subject = reply_subject_hook(subject)
else:
rsp = settings.get('reply_subject_prefix')
if not subject.lower().startswith(('re:', rsp.lower())):
subject = rsp + subject
envelope.add('Subject', subject)
# Auto-detect ML
auto_replyto_mailinglist = settings.get('auto_replyto_mailinglist')
if mail['List-Id'] and self.listreply is None:
# mail['List-Id'] is need to enable reply-to-list
self.listreply = auto_replyto_mailinglist
elif mail['List-Id'] and self.listreply is True:
self.listreply = True
elif self.listreply is False:
# In this case we only need the sender
self.listreply = False
# set From-header and sending account
try:
from_header, account = determine_sender(mail, 'reply')
except AssertionError as e:
ui.notify(str(e), priority='error')
return
envelope.add('From', from_header)
envelope.account = account
# set To
sender = mail['Reply-To'] or mail['From']
sender_address = parseaddr(sender)[1]
cc = []
# check if reply is to self sent message
if account.matches_address(sender_address):
recipients = mail.get_all('To', [])
emsg = 'Replying to own message, set recipients to: %s' \
% recipients
logging.debug(emsg)
else:
recipients = [sender]
if self.groupreply:
# make sure that our own address is not included
# if the message was self-sent, then our address is not included
MFT = mail.get_all('Mail-Followup-To', [])
followupto = clear_my_address(account, MFT)
if followupto and settings.get('honor_followup_to'):
logging.debug('honor followup to: %s', ', '.join(followupto))
recipients = followupto
# since Mail-Followup-To was set, ignore the Cc header
else:
if sender != mail['From']:
recipients.append(mail['From'])
# append To addresses if not replying to self sent message
if not account.matches_address(sender_address):
cleared = clear_my_address(account,
mail.get_all('To', []))
recipients.extend(cleared)
# copy cc for group-replies
if 'Cc' in mail:
cc = clear_my_address(account, mail.get_all('Cc', []))
envelope.add('Cc', ', '.join(cc))
to = ', '.join(ensure_unique_address(recipients))
logging.debug('reply to: %s', to)
if self.listreply:
# To choose the target of the reply --list
# Reply-To is standart reply target RFC 2822:, RFC 1036: 2.2.1
# X-BeenThere is needed by sourceforge ML also winehq
# X-Mailing-List is also standart and is used by git-send-mail
to = mail['Reply-To'] or mail['X-BeenThere'] or mail['X-Mailing-List']
# Some mail server (gmail) will not resend you own mail, so you
# have to deal with the one in sent
if to is None:
to = mail['To']
logging.debug('mail list reply to: %s', to)
# Cleaning the 'To' in this case
if envelope.get('To') is not None:
envelope.__delitem__('To')
# Finally setup the 'To' header
envelope.add('To', to)
# if any of the recipients is a mailinglist that we are subscribed to,
# set Mail-Followup-To header so that duplicates are avoided
if settings.get('followup_to'):
# to and cc are already cleared of our own address
allrecipients = [to] + cc
lists = settings.get('mailinglists')
# check if any recipient address matches a known mailing list
if any(addr in lists for n, addr in getaddresses(allrecipients)):
followupto = ', '.join(allrecipients)
logging.debug('mail followup to: %s', followupto)
envelope.add('Mail-Followup-To', followupto)
# set In-Reply-To header
envelope.add('In-Reply-To', '<%s>' % self.message.id)
# set References header
old_references = mail.get('References', '')
if old_references:
old_references = old_references.split()
references = old_references[-8:]
if len(old_references) > 8:
references = old_references[:1] + references
references.append('<%s>' % self.message.id)
envelope.add('References', ' '.join(references))
else:
envelope.add('References', '<%s>' % self.message.id)
# continue to compose
encrypt = mail.get_content_subtype() == 'encrypted'
await ui.apply_command(ComposeCommand(envelope=envelope,
spawn=self.force_spawn,
encrypt=encrypt))
@registerCommand(MODE, 'forward', arguments=[
(['--attach'], {'action': 'store_true', 'help': 'attach original mail'}),
(['--spawn'], {'action': cargparse.BooleanAction, 'default': None,
'help': 'open editor in new window'})])
class ForwardCommand(Command):
"""forward message"""
repeatable = True
def __init__(self, message=None, attach=True, spawn=None, **kwargs):
"""
:param message: message to forward (defaults to selected message)
:type message: `alot.db.message.Message`
:param attach: attach original mail instead of inline quoting its body
:type attach: bool
:param spawn: force spawning of editor in a new terminal
:type spawn: bool
"""
self.message = message
self.inline = not attach
self.force_spawn = spawn
Command.__init__(self, **kwargs)
async def apply(self, ui):
# get message to forward if not given in constructor
if not self.message:
self.message = ui.current_buffer.get_selected_message()
mail = self.message.get_email()
envelope = Envelope(passed=self.message)
if self.inline: # inline mode
# set body text
name, address = self.message.get_author()
timestamp = self.message.date
qf = settings.get_hook('forward_prefix')
if qf:
quote = qf(name, address, timestamp,
message=mail, ui=ui, dbm=ui.dbman)
else:
quote = 'Forwarded message from %s (%s):\n' % (
name or address, timestamp)
mailcontent = quote
quotehook = settings.get_hook('text_quote')
if quotehook:
mailcontent += quotehook(self.message.get_body_text())
else:
quote_prefix = settings.get('quote_prefix')
for line in self.message.get_body_text().splitlines():
mailcontent += quote_prefix + line + '\n'
envelope.body = mailcontent
for a in self.message.iter_attachments():
envelope.attach(a)
else: # attach original mode
# attach original msg
original_mail = Message()
original_mail.set_type('message/rfc822')
original_mail['Content-Disposition'] = 'attachment'
original_mail.set_payload(mail.as_string(policy=email.policy.SMTP))
envelope.attach(Attachment(original_mail))
# copy subject
subject = mail.get('Subject', '')
subject = 'Fwd: ' + subject
forward_subject_hook = settings.get_hook('forward_subject')
if forward_subject_hook:
subject = forward_subject_hook(subject)
else:
fsp = settings.get('forward_subject_prefix')
if not subject.startswith(('Fwd:', fsp)):
subject = fsp + subject
envelope.add('Subject', subject)
# set From-header and sending account
try:
from_header, account = determine_sender(mail, 'reply')
except AssertionError as e:
ui.notify(str(e), priority='error')
return
envelope.add('From', from_header)
envelope.account = account
# continue to compose
await ui.apply_command(ComposeCommand(envelope=envelope,
spawn=self.force_spawn))
@registerCommand(MODE, 'bounce')
class BounceMailCommand(Command):
"""directly re-send selected message"""
repeatable = True
def __init__(self, message=None, **kwargs):
"""
:param message: message to bounce (defaults to selected message)
:type message: `alot.db.message.Message`
"""
self.message = message
Command.__init__(self, **kwargs)
async def apply(self, ui):
# get mail to bounce
if not self.message:
self.message = ui.current_buffer.get_selected_message()
mail = self.message.get_email()
# look if this makes sense: do we have any accounts set up?
my_accounts = settings.get_accounts()
if not my_accounts:
ui.notify('no accounts set', priority='error')
return
# remove "Resent-*" headers if already present
del mail['Resent-From']
del mail['Resent-To']
del mail['Resent-Cc']
del mail['Resent-Date']
del mail['Resent-Message-ID']
# set Resent-From-header and sending account
try:
resent_from_header, account = determine_sender(mail, 'bounce')
except AssertionError as e:
ui.notify(str(e), priority='error')
return
mail['Resent-From'] = resent_from_header
# set Reset-To
allbooks = not settings.get('complete_matching_abook_only')
logging.debug('allbooks: %s', allbooks)
if account is not None:
abooks = settings.get_addressbooks(order=[account],
append_remaining=allbooks)
logging.debug(abooks)
completer = ContactsCompleter(abooks)
else:
completer = None
to = await ui.prompt('To', completer=completer,
history=ui.recipienthistory)
if to is None:
raise CommandCanceled()
mail['Resent-To'] = to.strip(' \t\n,')
logging.debug("bouncing mail")
logging.debug(mail.__class__)
await ui.apply_command(SendCommand(mail=mail))
@registerCommand(MODE, 'editnew', arguments=[
(['--spawn'], {'action': cargparse.BooleanAction, 'default': None,
'help': 'open editor in new window'})])
class EditNewCommand(Command):
"""edit message in as new"""
def __init__(self, message=None, spawn=None, **kwargs):
"""
:param message: message to reply to (defaults to selected message)
:type message: `alot.db.message.Message`
:param spawn: force spawning of editor in a new terminal
:type spawn: bool
"""
self.message = message
self.force_spawn = spawn
Command.__init__(self, **kwargs)
async def apply(self, ui):
if not self.message:
self.message = ui.current_buffer.get_selected_message()
# copy most tags to the envelope
tags = set(self.message.get_tags())
tags.difference_update({'inbox', 'sent', 'draft', 'killed', 'replied',
'signed', 'encrypted', 'unread', 'attachment'})
# set body text
mailcontent = self.message.get_body_text()
envelope = Envelope(bodytext=mailcontent, tags=tags)
# copy selected headers
to_copy = ['Subject', 'From', 'To', 'Cc', 'Bcc', 'In-Reply-To',
'References']
for key in to_copy:
if key in self.message.headers:
value = self.message.headers[key][0]
envelope.add(key, value)
# copy attachments
for b in self.message.iter_attachments():
envelope.attach(b)
await ui.apply_command(ComposeCommand(envelope=envelope,
spawn=self.force_spawn,
omit_signature=True))
@registerCommand(
MODE, 'togglesource', help='display message source',
forced={'raw': 'toggle'},
arguments=[(['query'], {'help': 'query used to filter messages to affect',
'nargs': '*'})])
@registerCommand(
MODE, 'toggleheaders', help='display all headers',
forced={'all_headers': 'toggle'},
arguments=[(['query'], {'help': 'query used to filter messages to affect',
'nargs': '*'})])
@registerCommand(
MODE, 'indent', help='change message/reply indentation',
arguments=[(['indent'], {'action': cargparse.ValidatedStoreAction,
'validator': cargparse.is_int_or_pm})])
@registerCommand(
MODE, 'fold', help='change message folding level',
arguments=[(['fold'], {'action': cargparse.ValidatedStoreAction,
'validator': cargparse.is_int_or_pm})])
class ChangeDisplaymodeCommand(Command):
repeatable = True
def __init__(self, query=None, raw=None, all_headers=None,
indent=None, fold = None, **kwargs):
"""
:param query: notmuch query string used to filter messages to affect
:type query: str
:param raw: display raw message text.
:type raw: True, False, 'toggle' or None
:param all_headers: show all headers (only visible if not in raw mode)
:type all_headers: True, False, 'toggle' or None
:param indent: message/reply indentation
:type indent: '+', '-', or int
:param fold: message fold level
:type indent: '+', '-', or int
"""
self.query = None
if query:
self.query = ' '.join(query)
self.raw = raw
self.all_headers = all_headers
self.indent = indent
self.fold = fold
Command.__init__(self, **kwargs)
def apply(self, ui):
tbuffer = ui.current_buffer
# set message/reply indentation if changed
if self.indent is not None:
if self.indent == '+':
newindent = tbuffer._indent_width + 1
elif self.indent == '-':
newindent = tbuffer._indent_width - 1
else:
# argparse validation guarantees that self.indent
# can be cast to an integer
newindent = int(self.indent)
# make sure indent remains non-negative
tbuffer._indent_width = max(newindent, 0)
tbuffer.rebuild()
ui.update()
logging.debug('matching lines %s...', self.query)
if self.query is None:
msg_wgts = [tbuffer.get_selected_message_widget()]
else:
msg_wgts = list(tbuffer.message_widgets())
if self.query != '*':
def matches(msgt):
msg = msgt.get_message()
return msg.matches(self.query)
msg_wgts = [m for m in msg_wgts if matches(m)]
for m in msg_wgts:
# determine new display values for this message
if self.raw == 'toggle':
tbuffer.focus_selected_message()
raw = not m.display_source if self.raw == 'toggle' else self.raw
all_headers = not m.display_all_headers \
if self.all_headers == 'toggle' else self.all_headers
tbuffer.focus_selected_message()
# set new values in messagetree obj
if raw is not None:
m.display_source = raw
if all_headers is not None:
m.display_all_headers = all_headers
if self.fold is not None:
if self.fold == '+':
m.foldlevel += 1
elif self.fold == '-':
m.foldlevel -= 1
else:
m.foldlevel = int(self.fold)
@registerCommand(MODE, 'pipeto', arguments=[
(['cmd'], {'help': 'shellcommand to pipe to', 'nargs': '+'}),
(['--all'], {'action': 'store_true', 'help': 'pass all messages'}),
(['--format'], {'help': 'output format', 'default': 'raw',
'choices': ['raw', 'decoded', 'id', 'filepath']}),
(['--separately'], {'action': 'store_true',
'help': 'call command once for each message'}),
(['--background'], {'action': 'store_true',
'help': 'don\'t stop the interface'}),
(['--add_tags'], {'action': 'store_true',
'help': 'add \'Tags\' header to the message'}),
(['--shell'], {'action': 'store_true',
'help': 'let the shell interpret the command'}),
(['--notify_stdout'], {'action': 'store_true',
'help': 'display cmd\'s stdout as notification'}),
])
class PipeCommand(Command):
"""pipe message(s) to stdin of a shellcommand"""
repeatable = True
def __init__(self, cmd, all=False, separately=False, background=False,
shell=False, notify_stdout=False, format='raw',
add_tags=False, noop_msg='no command specified',
confirm_msg='', done_msg=None, **kwargs):
"""
:param cmd: shellcommand to open
:type cmd: str or list of str
:param all: pipe all, not only selected message
:type all: bool
:param separately: call command once per message
:type separately: bool
:param background: do not suspend the interface
:type background: bool
:param shell: let the shell interpret the command
:type shell: bool
:param notify_stdout: display command\'s stdout as notification message
:type notify_stdout: bool
:param format: what to pipe to the processes stdin. one of:
'raw': message content as is,
'decoded': message content, decoded quoted printable,
'id': message ids, separated by newlines,
'filepath': paths to message files on disk
:type format: str
:param add_tags: add 'Tags' header to the message
:type add_tags: bool
:param noop_msg: error notification to show if `cmd` is empty
:type noop_msg: str
:param confirm_msg: confirmation question to ask (continues directly if
unset)
:type confirm_msg: str
:param done_msg: notification message to show upon success
:type done_msg: str
"""
Command.__init__(self, **kwargs)
if isinstance(cmd, str):
cmd = split_commandstring(cmd)
self.cmd = cmd
self.whole_thread = all
self.separately = separately
self.background = background
self.shell = shell
self.notify_stdout = notify_stdout
self.output_format = format
self.add_tags = add_tags
self.noop_msg = noop_msg
self.confirm_msg = confirm_msg
self.done_msg = done_msg
async def apply(self, ui):
# abort if command unset
if not self.cmd:
ui.notify(self.noop_msg, priority='error')
return
# get messages to pipe
if self.whole_thread:
thread = ui.current_buffer.thread
if not thread:
return
to_print = thread.messages.values()
else:
to_print = [ui.current_buffer.get_selected_message()]
# ask for confirmation if needed
if self.confirm_msg:
if (await ui.choice(self.confirm_msg, select='yes',
cancel='no')) == 'no':
return
# prepare message sources
pipe_data = []
logging.debug('PIPETO format')
logging.debug(self.output_format)
if self.output_format == 'id':
pipe_data = [e.id.encode('utf-8') for e in to_print]
separator = b'\n'
elif self.output_format == 'filepath':
pipe_data = [e.filename for e in to_print]
separator = b'\n'
else:
separator = b'\n\n'
for msg in to_print:
if self.output_format == 'raw':
msg_data = msg.as_bytes()
elif self.output_format == 'decoded':
# XXX HACK: filter out content-transfer-encoding, since we are writing out
# the decoder version
# should be properly handled elsewhere (where? how?)
headers = filter(lambda i: i[0].lower() != 'content-transfer-encoding', msg.headers.items())
headertext = '\n'.join([key + ': ' + val for key, val in headers])
bodytext = msg.get_body_text()
msgtext = '%s\n\n%s' % (headertext, bodytext)
msg_data = msgtext.encode('utf-8')
if self.add_tags:
tags = 'Tags: ' + ','.join(msg.get_tags()) + '\n'
msg_data = tags.encode('utf-8') + msg_data
pipe_data.append(msg_data)
if not self.separately:
pipe_data = [separator.join(pipe_data)]
if self.shell:
self.cmd = [' '.join(self.cmd)]
# do the monkey
for d in pipe_data:
if self.background:
logging.debug('call in background: %s', self.cmd)
proc = subprocess.Popen(self.cmd,
shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate(d)
if self.notify_stdout:
ui.notify(out, block = True)
else:
with ui.paused():
logging.debug('call: %s', self.cmd)
# if proc.stdout is defined later calls to communicate
# seem to be non-blocking!
proc = subprocess.Popen(self.cmd, shell=True,
stdin=subprocess.PIPE,
# stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate(d)
if err:
ui.notify(err, priority='error')
return
# display 'done' message
if self.done_msg:
ui.notify(self.done_msg)
@registerCommand(MODE, 'print', arguments=[
(['--all'], {'action': 'store_true', 'help': 'print all messages'}),
(['--raw'], {'action': 'store_true', 'help': 'pass raw mail string'}),
(['--separately'], {'action': 'store_true',
'help': 'call print command once for each message'}),
(['--add_tags'], {'action': 'store_true',
'help': 'add \'Tags\' header to the message'}),
])
class PrintCommand(PipeCommand):
"""print message(s)"""
repeatable = True
def __init__(self, all=False, separately=False, raw=False, add_tags=False,
**kwargs):
"""
:param all: print all, not only selected messages
:type all: bool
:param separately: call print command once per message
:type separately: bool
:param raw: pipe raw message string to print command
:type raw: bool
:param add_tags: add 'Tags' header to the message
:type add_tags: bool
"""
# get print command
cmd = settings.get('print_cmd') or ''
# set up notification strings
if all:
confirm_msg = 'print all messages in thread?'
ok_msg = 'printed thread using %s' % cmd
else:
confirm_msg = 'print selected message?'
ok_msg = 'printed message using %s' % cmd
# no print cmd set
noop_msg = 'no print command specified. Set "print_cmd" in the '\
'global section.'
PipeCommand.__init__(self, [cmd], all=all, separately=separately,
background=True,
shell=False,
format='raw' if raw else 'decoded',
add_tags=add_tags,
noop_msg=noop_msg, confirm_msg=confirm_msg,
done_msg=ok_msg, **kwargs)
@registerCommand(MODE, 'save', arguments=[
(['--all'], {'action': 'store_true', 'help': 'save all attachments'}),
(['path'], {'nargs': '?', 'help': 'path to save to'})])
class SaveAttachmentCommand(Command):
"""save attachment(s)"""
def __init__(self, all=False, path=None, **kwargs):
"""
:param all: save all, not only selected attachment
:type all: bool
:param path: path to write to. if `all` is set, this must be a
directory.
:type path: str
"""
Command.__init__(self, **kwargs)
self.all = all
self.path = path
async def apply(self, ui):
pcomplete = PathCompleter()
savedir = settings.get('attachment_prefix', '~')
if self.all:
msg = ui.current_buffer.get_selected_message()
if not self.path:
self.path = await ui.prompt('save attachments to',
text=os.path.join(savedir, ''),
completer=pcomplete)
if self.path:
if os.path.isdir(os.path.expanduser(self.path)):
for a in msg.iter_attachments():
dest = a.save(self.path)
name = a.get_filename()
if name:
ui.notify('saved %s as: %s' % (name, dest))
else:
ui.notify('saved attachment as: %s' % dest)
else:
ui.notify('not a directory: %s' % self.path,
priority='error')
else:
raise CommandCanceled()
else: # save focussed attachment
attachment = ui.current_buffer.get_selected_attachment()
if attachment is not None:
filename = attachment.get_filename()
if not self.path:
msg = 'save attachment (%s) to ' % filename
initialtext = os.path.join(savedir, filename)
self.path = await ui.prompt(msg,
completer=pcomplete,
text=initialtext)
if self.path:
try:
dest = attachment.save(self.path)
ui.notify('saved attachment as: %s' % dest)
except (IOError, OSError) as e:
ui.notify(str(e), priority='error')
else:
raise CommandCanceled()
class OpenAttachmentCommand(Command):
"""displays an attachment according to mailcap"""
def __init__(self, attachment, **kwargs):
"""
:param attachment: attachment to open
:type attachment: :class:`~alot.db.attachment.Attachment`
"""
Command.__init__(self, **kwargs)
self.attachment = attachment
async def apply(self, ui):
logging.info('open attachment')
mimetype = self.attachment.get_content_type()
# returns pair of preliminary command string and entry dict containing
# more info. We only use the dict and construct the command ourselves
_, entry = settings.mailcap_find_match(mimetype)
if entry:
afterwards = None # callback, will rm tempfile if used
handler_stdin = None
tempfile_name = None
handler_raw_commandstring = entry['view']
# read parameter
part = self.attachment.get_mime_representation()
parms = tuple('='.join(p) for p in part.get_params())
# in case the mailcap defined command contains no '%s',
# we pipe the files content to the handling command via stdin
if '%s' in handler_raw_commandstring:
nametemplate = entry.get('nametemplate', '%s')
prefix, suffix = parse_mailcap_nametemplate(nametemplate)
fn_hook = settings.get_hook('sanitize_attachment_filename')
if fn_hook:
# get filename
filename = self.attachment.get_filename()
prefix, suffix = fn_hook(filename, prefix, suffix)
with tempfile.NamedTemporaryFile(delete=False, prefix=prefix,
suffix=suffix) as tmpfile:
tempfile_name = tmpfile.name
self.attachment.write(tmpfile)
def afterwards():
os.unlink(tempfile_name)
else:
handler_stdin = BytesIO()
self.attachment.write(handler_stdin)
# create handler command list
handler_cmd = mailcap.subst(handler_raw_commandstring, mimetype,
filename=tempfile_name, plist=parms)
handler_cmdlist = split_commandstring(handler_cmd)
# 'needsterminal' makes handler overtake the terminal
# XXX: could this be repalced with "'needsterminal' not in entry"?
overtakes = entry.get('needsterminal') is None
await ui.apply_command(ExternalCommand(handler_cmdlist,
stdin=handler_stdin,
on_success=afterwards,
thread=overtakes))
else:
ui.notify('unknown mime type')
@registerCommand(
MODE, 'move', help='move focus in current buffer',
arguments=[
(['movement'],
{'nargs': argparse.REMAINDER,
'help': '''up, down, [half]page up, [half]page down, first, last, \
parent, first reply, last reply, \
next sibling, previous sibling, next, previous, \
next NOTMUCH_QUERY, previous NOTMUCH_QUERY'''})])
class MoveFocusCommand(MoveCommand):
def apply(self, ui):
logging.debug(self.movement)
tbuffer = ui.current_buffer
if self.movement == 'parent':
tbuffer.focus_parent()
elif self.movement == 'first reply':
tbuffer.focus_first_reply()
elif self.movement == 'last reply':
tbuffer.focus_last_reply()
elif self.movement == 'next sibling':
tbuffer.focus_next_sibling()
elif self.movement == 'previous sibling':
tbuffer.focus_prev_sibling()
elif self.movement == 'next':
tbuffer.focus_next()
elif self.movement == 'previous':
tbuffer.focus_prev()
elif self.movement.startswith('next '):
query = self.movement[5:].strip()
tbuffer.focus_next_matching(query)
elif self.movement.startswith('previous '):
query = self.movement[9:].strip()
tbuffer.focus_prev_matching(query)
elif self.movement.startswith('first '):
query = self.movement[5:].strip()
tbuffer.focus_first_matching(query)
elif self.movement.startswith('last '):
query = self.movement[9:].strip()
tbuffer.focus_last_matching(query)
elif self.movement.startswith('thread'):
tbuffer.focus_thread_widget()
elif self.movement.startswith('msg'):
tbuffer.focus_msg_widget()
elif self.movement.startswith('toggle'):
tbuffer.focus_toggle()
else:
super().apply(ui)
# TODO add 'next matching' if threadbuffer stores the original query
# TODO: add next by date..
@registerCommand(MODE, 'select')
class ThreadSelectCommand(Command):
"""select focussed element:
- if it is a message summary, toggle visibility of the message;
- if it is an attachment line, open the attachment"""
async def apply(self, ui):
attachment = ui.current_buffer.get_selected_attachment()
if attachment is not None:
logging.info('open attachment')
await ui.apply_command(OpenAttachmentCommand(attachment))
else:
ui.current_buffer.focus_toggle()
RetagPromptCommand = registerCommand(MODE, 'retagprompt')(RetagPromptCommand)
@registerCommand(
MODE, 'tag', forced={'action': 'add'},
arguments=[
(['--all'], {'action': 'store_true',
'help': 'tag all messages in thread'}),
(['--no-flush'], {'action': 'store_false', 'dest': 'flush',
'help': 'postpone a writeout to the index'}),
(['tags'], {'help': 'comma separated list of tags'})],
help='add tags to message(s)',
)
@registerCommand(
MODE, 'retag', forced={'action': 'set'},
arguments=[
(['--all'], {'action': 'store_true',
'help': 'tag all messages in thread'}),
(['--no-flush'], {'action': 'store_false', 'dest': 'flush',
'help': 'postpone a writeout to the index'}),
(['tags'], {'help': 'comma separated list of tags'})],
help='set message(s) tags.',
)
@registerCommand(
MODE, 'untag', forced={'action': 'remove'},
arguments=[
(['--all'], {'action': 'store_true',
'help': 'tag all messages in thread'}),
(['--no-flush'], {'action': 'store_false', 'dest': 'flush',
'help': 'postpone a writeout to the index'}),
(['tags'], {'help': 'comma separated list of tags'})],
help='remove tags from message(s)',
)
@registerCommand(
MODE, 'toggletags', forced={'action': 'toggle'},
arguments=[
(['--all'], {'action': 'store_true',
'help': 'tag all messages in thread'}),
(['--no-flush'], {'action': 'store_false', 'dest': 'flush',
'help': 'postpone a writeout to the index'}),
(['tags'], {'help': 'comma separated list of tags'})],
help='flip presence of tags on message(s)',
)
class TagCommand(Command):
"""manipulate message tags"""
repeatable = True
def __init__(self, tags='', action='add', all=False, flush=True,
**kwargs):
"""
:param tags: comma separated list of tagstrings to set
:type tags: str
:param action: adds tags if 'add', removes them if 'remove', adds tags
and removes all other if 'set' or toggle individually if
'toggle'
:type action: str
:param all: tag all messages in thread
:type all: bool
:param flush: immediately write out to the index
:type flush: bool
"""
self.tagsstring = tags
self.all = all
self.action = action
self.flush = flush
Command.__init__(self, **kwargs)
async def apply(self, ui):
if self.all:
messages = ui.current_buffer.thread.messages.values()
else:
messages = [ui.current_buffer.get_selected_message()]
tags = frozenset(filter(None, self.tagsstring.split(',')))
try:
for m in messages:
if self.action == 'add':
m.add_tags(tags)
if self.action == 'set':
m.add_tags(tags, remove_rest=True)
elif self.action == 'remove':
m.remove_tags(tags)
elif self.action == 'toggle':
to_remove = set()
to_add = ()
for t in tags:
if t in m.get_tags():
to_remove.add(t)
else:
to_add.add(t)
m.remove_tags(to_remove)
m.add_tags(to_add)
except DatabaseROError:
ui.notify('index in read-only mode', priority='error')
return
# flush index
if self.flush:
await ui.apply_command(FlushCommand())
|