summaryrefslogtreecommitdiff
path: root/alot/db/utils.py
blob: 020f51d0cf61d626308a104fb583fbf38c0d4541 (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
# encoding=utf-8
# Copyright (C) 2011-2012  Patrick Totzke <patricktotzke@gmail.com>
# Copyright © 2017 Dylan Baker <dylan@pnwbakers.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
import os
import email
import email.charset as charset
import email.policy
import email.utils
import tempfile
import logging
import mailcap

from .. import helper
from ..settings.const import settings
from ..helper import string_sanitize
from ..helper import parse_mailcap_nametemplate
from ..helper import split_commandstring

charset.add_charset('utf-8', charset.QP, charset.QP, 'utf-8')

def render_part(part, field_key='copiousoutput'):
    """
    renders a non-multipart email part into displayable plaintext by piping its
    payload through an external script. The handler itself is determined by
    the mailcap entry for this part's ctype.
    """
    ctype = part.get_content_type()
    raw_payload = remove_cte(part)
    rendered_payload = None
    # get mime handler
    _, entry = settings.mailcap_find_match(ctype, key=field_key)
    if entry is not None:
        tempfile_name = None
        stdin = None
        handler_raw_commandstring = entry['view']
        # 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:
            # open tempfile, respect mailcaps nametemplate
            nametemplate = entry.get('nametemplate', '%s')
            prefix, suffix = parse_mailcap_nametemplate(nametemplate)
            with tempfile.NamedTemporaryFile(
                    delete=False, prefix=prefix, suffix=suffix) \
                    as tmpfile:
                tmpfile.write(raw_payload)
                tempfile_name = tmpfile.name
        else:
            stdin = raw_payload

        # read parameter, create handler command
        parms = tuple('='.join(p) for p in part.get_params())

        # create and call external command
        cmd = mailcap.subst(entry['view'], ctype,
                            filename=tempfile_name, plist=parms)
        logging.debug('command: %s', cmd)
        logging.debug('parms: %s', str(parms))
        cmdlist = split_commandstring(cmd)
        # call handler
        stdout, _, _ = helper.call_cmd(cmdlist, stdin=stdin)
        if stdout:
            rendered_payload = stdout

        # remove tempfile
        if tempfile_name:
            os.unlink(tempfile_name)

    return rendered_payload


def remove_cte(part, as_string=False):
    """Interpret MIME-part according to it's Content-Transfer-Encodings.

    This returns the payload of `part` as string or bytestring for display, or
    to be passed to an external program. In the raw file the payload may be
    encoded, e.g. in base64, quoted-printable, 7bit, or 8bit. This method will
    look for one of the above Content-Transfer-Encoding header and interpret
    the payload accordingly.

    Incorrect header values (common in spam messages) will be interpreted as
    lenient as possible and will result in INFO-level debug messages.

    ..Note:: All this may be depricated in favour of
             `email.contentmanager.raw_data_manager` (v3.6+)

    :param email.message.EmailMessage part: The part to decode
    :param bool as_string: If true return a str, otherwise return bytes
    :returns: The mail with any Content-Transfer-Encoding removed
    :rtype: Union[str, bytes]
    """
    payload = part.get_payload(decode = True)
    if as_string:
        enc = part.get_content_charset('ascii')
        if enc.startswith('windows-'):
            enc = enc.replace('windows-', 'cp', 1)

        try:
            payload = payload.decode(enc, errors = 'backslashreplace')
        except LookupError:
            # enc is unknown;
            # fall back to guessing the correct encoding using libmagic
            payload = helper.try_decode(payload)
        except UnicodeDecodeError as emsg:
            # the mail contains chars that are not enc-encoded.
            # libmagic works better than just ignoring those
            logging.debug('Decoding failure: {}'.format(emsg))
            payload = helper.try_decode(payload)

    return payload

MISSING_HTML_MSG = ("This message contains a text/html part that was not "
                    "rendered due to a missing mailcap entry. "
                    "Please refer to item 5 in our FAQ: "
                    "http://alot.rtfd.io/en/latest/faq.html")


def extract_body(mail):
    """Returns a string view of a Message.

    This consults :ref:`prefer_plaintext <prefer-plaintext>`
    to determine if a "text/plain" alternative is preferred over a "text/html"
    part.

    :param mail: the mail to use
    :type mail: :class:`email.message.EmailMessage`
    :returns: The combined text of any parts to be used
    :rtype: str
    """

    if settings.get('prefer_plaintext'):
        preferencelist = ('plain', 'html')
    else:
        preferencelist = ('html', 'plain')

    body_part = mail.get_body(preferencelist)
    if body_part is None:  # if no part matching preferredlist was found
        return ""

    displaystring = ""

    if body_part.get_content_type() == 'text/plain':
        displaystring = string_sanitize(remove_cte(body_part, as_string=True))
    else:
        rendered_payload = render_part(body_part)
        if rendered_payload:  # handler had output
            displaystring = string_sanitize(rendered_payload)
        else:
            if body_part.get_content_type() == 'text/html':
                displaystring = MISSING_HTML_MSG
    return displaystring


def formataddr(pair):
    """ this is the inverse of email.utils.parseaddr:
    other than email.utils.formataddr, this
    - *will not* re-encode unicode strings, and
    - *will* re-introduce quotes around real names containing commas
    """
    name, address = pair
    if not name:
        return address
    elif ',' in name:
        name = "\"" + name + "\""
    return "{0} <{1}>".format(name, address)



def is_subdir_of(subpath, superpath):
    # make both absolute
    superpath = os.path.realpath(superpath)
    subpath = os.path.realpath(subpath)

    # return true, if the common prefix of both is equal to directory
    # e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
    return os.path.commonprefix([subpath, superpath]) == superpath


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 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)