summaryrefslogtreecommitdiff
path: root/alot/commands/envelope.py
blob: aa1ae0dac3f8621eeae20fc8bec05cbdf87088f7 (plain)
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
import os
import re
import glob
import logging
import email
import tempfile
from email import Charset
from twisted.internet import defer

from alot.commands import Command, registerCommand
from alot import settings
from alot import helper
from alot.message import decode_header
from alot.message import encode_header
from alot.message import extract_headers
from alot.message import extract_body
from alot.commands.globals import EditCommand
from alot.commands.globals import BufferCloseCommand
from alot.commands.globals import EnvelopeOpenCommand


MODE = 'envelope'


@registerCommand(MODE, 'attach', help='attach files to the mail', arguments=[
    (['path'], {'help':'file(s) to attach (accepts wildcads)'})])
class EnvelopeAttachCommand(Command):
    def __init__(self, path=None, mail=None, **kwargs):
        Command.__init__(self, **kwargs)
        self.mail = mail
        self.path = path

    def apply(self, ui):
        msg = self.mail
        if not msg:
            msg = ui.current_buffer.get_email()

        if self.path:
            files = filter(os.path.isfile,
                           glob.glob(os.path.expanduser(self.path)))
            if not files:
                ui.notify('no matches, abort')
                return
        else:
            ui.notify('no files specified, abort')

        logging.info("attaching: %s" % files)
        for path in files:
            helper.attach(path, msg)

        if not self.mail:  # set the envelope msg iff we got it from there
            ui.current_buffer.set_email(msg)


@registerCommand(MODE, 'refine', help='prompt to change the value of a header',
                 arguments=[
    (['key'], {'help':'header to refine'})])
class EnvelopeRefineCommand(Command):
    def __init__(self, key='', **kwargs):
        Command.__init__(self, **kwargs)
        self.key = key

    def apply(self, ui):
        mail = ui.current_buffer.get_email()
        value = decode_header(mail.get(self.key, ''))
        ui.commandprompt('set %s %s' % (self.key, value))


@registerCommand(MODE, 'send', help='sends mail')
class EnvelopeSendCommand(Command):
    @defer.inlineCallbacks
    def apply(self, ui):
        envelope = ui.current_buffer
        mail = envelope.get_email()
        frm = decode_header(mail.get('From'))
        sname, saddr = email.Utils.parseaddr(frm)
        account = ui.accountman.get_account_by_address(saddr)
        if account:
            # attach signature file if present
            if account.signature:
                sig = os.path.expanduser(account.signature)
                if os.path.isfile(sig):
                    if account.signature_filename:
                        name = account.signature_filename
                    else:
                        name = None
                    helper.attach(sig, mail, filename=name)
                else:
                    ui.notify('could not locate signature: %s' % sig,
                              priority='error')
                    if (yield ui.choice('send without signature',
                                        select='yes', cancel='no')) == 'no':
                        return

            clearme = ui.notify('sending..', timeout=-1, block=False)
            reason = account.send_mail(mail)
            ui.clear_notify([clearme])
            if not reason:  # sucessfully send mail
                cmd = BufferCloseCommand(buffer=envelope)
                ui.apply_command(cmd)
                ui.notify('mail send successful')
            else:
                ui.notify('failed to send: %s' % reason, priority='error')
        else:
            ui.notify('failed to send: no account set up for %s' % saddr,
                      priority='error')


@registerCommand(MODE, 'reedit', help='edit currently open mail')
class EnvelopeEditCommand(Command):
    def __init__(self, mail=None, **kwargs):
        self.mail = mail
        self.openNew = (mail != None)
        Command.__init__(self, **kwargs)

    def apply(self, ui):
        Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
        if not self.mail:
            self.mail = ui.current_buffer.get_email()

        #determine editable headers
        edit_headers = set(settings.config.getstringlist('general',
                                                    'edit_headers_whitelist'))
        if '*' in edit_headers:
            edit_headers = set(self.mail.keys())
        blacklist = set(settings.config.getstringlist('general',
                                                  'edit_headers_blacklist'))
        if '*' in blacklist:
            blacklist = set(self.mail.keys())
        ui.logger.debug('BLACKLIST: %s' % blacklist)
        self.edit_headers = edit_headers - blacklist
        ui.logger.info('editable headers: %s' % blacklist)

        def openEnvelopeFromTmpfile():
            # This parses the input from the tempfile.
            # we do this ourselves here because we want to be able to
            # just type utf-8 encoded stuff into the tempfile and let alot
            # worry about encodings.

            # get input
            f = open(tf.name)
            enc = settings.config.get('general', 'editor_writes_encoding')
            editor_input = f.read().decode(enc)
            if self.edit_headers:
                headertext, bodytext = editor_input.split('\n\n', 1)
            else:
                headertext = ''
                bodytext = editor_input

            # call post-edit translate hook
            translate = settings.hooks.get('post_edit_translate')
            if translate:
                bodytext = translate(bodytext, ui=ui, dbm=ui.dbman,
                                     aman=ui.accountman, log=ui.logger,
                                     config=settings.config)

            # go through multiline, utf-8 encoded headers
            key = value = None
            for line in headertext.splitlines():
                if re.match('[a-zA-Z0-9_-]+:', line):  # new k/v pair
                    if key and value:  # save old one from stack
                        del self.mail[key]  # ensure unique values in mails
                        self.mail[key] = encode_header(key, value)  # save
                    key, value = line.strip().split(':', 1)  # parse new pair
                elif key and value:  # append new line without key prefix
                    value += line
            if key and value:  # save last one if present
                del self.mail[key]
                self.mail[key] = encode_header(key, value)

            if self.mail.is_multipart():
                for part in self.mail.walk():
                    if part.get_content_maintype() == 'text':
                        if 'Content-Transfer-Encoding' in part:
                            del(part['Content-Transfer-Encoding'])
                        part.set_payload(bodytext, 'utf-8')
                        break

            f.close()
            os.unlink(tf.name)
            if self.openNew:
                ui.apply_command(EnvelopeOpenCommand(mail=self.mail))
            else:
                ui.current_buffer.set_email(self.mail)

        # decode header
        headertext = extract_headers(self.mail, self.edit_headers)

        bodytext = extract_body(self.mail)

        # call pre-edit translate hook
        translate = settings.hooks.get('pre_edit_translate')
        if translate:
            bodytext = translate(bodytext, ui=ui, dbm=ui.dbman,
                                 aman=ui.accountman, log=ui.logger,
                                 config=settings.config)

        #write stuff to tempfile
        tf = tempfile.NamedTemporaryFile(delete=False)
        content = bodytext
        if headertext:
            content = '%s\n\n%s' % (headertext, content)
        tf.write(content.encode('utf-8'))
        tf.flush()
        tf.close()
        cmd = EditCommand(tf.name, on_success=openEnvelopeFromTmpfile,
                          refocus=False)
        ui.apply_command(cmd)


@registerCommand(MODE, 'set', help='set header value', arguments=[
    (['--append'], {'action': 'store_true', 'help':'keep previous value'}),
    (['key'], {'help':'header to refine'}),
    (['value'], {'nargs':'+', 'help':'value'})])
class EnvelopeSetCommand(Command):
    def __init__(self, key, value, append=False, **kwargs):
        self.key = key
        self.value = encode_header(key, ' '.join(value))
        self.append = append
        Command.__init__(self, **kwargs)

    def apply(self, ui):
        envelope = ui.current_buffer
        mail = envelope.get_email()
        if not self.append:
            del(mail[self.key])
        mail[self.key] = self.value
        envelope.set_email(mail)
        envelope.rebuild()


@registerCommand(MODE, 'unset', help='remove header field', arguments=[
    (['key'], {'help':'header to refine'})])
class EnvelopeSetCommand(Command):
    def __init__(self, key, **kwargs):
        self.key = key
        Command.__init__(self, **kwargs)

    def apply(self, ui):
        mail = ui.current_buffer.get_email()
        del(mail[self.key])
        ui.current_buffer.set_email(mail)


@registerCommand(MODE, 'toggleheaders',
                help='toggle display of all headers')
class ToggleHeaderCommand(Command):
    def apply(self, ui):
        ui.current_buffer.header_wgt.toggle_all()