summaryrefslogtreecommitdiff
path: root/alot/db/attachment.py
blob: 0ebe6fc98946bbf11746bb4e596ebb5c9529daba (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
# 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 os
import tempfile
import email.charset as charset
from copy import deepcopy

from ..helper import guess_mimetype

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

def _humanize_size(size):
    """Create a nice human readable representation of the given number
    (understood as bytes) using the "KiB" and "MiB" suffixes to indicate
    kibibytes and mebibytes. A kibibyte is defined as 1024 bytes (as opposed to
    a kilobyte which is 1000 bytes) and a mibibyte is 1024**2 bytes (as opposed
    to a megabyte which is 1000**2 bytes).

    :param size: the number to convert
    :type size: int
    :returns: the human readable representation of size
    :rtype: str
    """
    for factor, format_string in ((1, '%i'),
                                  (1024, '%iKiB'),
                                  (1024 * 1024, '%.1fMiB')):
        if size / factor < 1024:
            return format_string % (size / factor)
    return format_string % (size / factor)



class Attachment:
    """represents a mail attachment"""

    def __init__(self, emailpart):
        """
        :param emailpart: a non-multipart email that is the attachment
        :type emailpart: :class:`email.message.Message`
        """
        self.part = emailpart

    def __str__(self):
        return '%s:%s (%s)' % (self.get_content_type(),
                               self.get_filename(),
                               _humanize_size(self.get_size()))

    def get_filename(self):
        """
        return name of attached file.
        If the content-disposition header contains no file name,
        this returns `None`
        """
        fname = self.part.get_filename()
        if fname:
            return os.path.basename(fname)
        return None

    def get_content_type(self):
        """mime type of the attachment part"""
        ctype = self.part.get_content_type()
        # replace underspecified mime description by a better guess
        if ctype in ['octet/stream', 'application/octet-stream',
                     'application/octetstream']:
            ctype = guess_mimetype(self.get_data())
        return ctype

    def get_size(self):
        """returns attachments size in bytes"""
        return len(self.part.get_payload())

    def save(self, path):
        """
        save the attachment to disk. Uses :meth:`~get_filename` in case path
        is a directory
        """
        filename = self.get_filename()
        path = os.path.expanduser(path)
        if os.path.isdir(path):
            if filename:
                basename = os.path.basename(filename)
                file_ = open(os.path.join(path, basename), "wb")
            else:
                file_ = tempfile.NamedTemporaryFile(delete=False, dir=path)
        else:
            file_ = open(path, "wb")  # this throws IOErrors for invalid path
        self.write(file_)
        file_.close()
        return file_.name

    def write(self, fhandle):
        """writes content to a given filehandle"""
        fhandle.write(self.get_data())

    def get_data(self):
        """return data blob from wrapped file"""
        return self.part.get_payload(decode=True)

    def get_mime_representation(self):
        """returns mime part that constitutes this attachment"""
        part = deepcopy(self.part)
        part.set_param('maxlinelen', '78', header='Content-Disposition')
        return part