summaryrefslogtreecommitdiff
path: root/alot/mail/attachment.py
blob: 5c993a68cc8becb919d3d9b4cc1e77ab2547a152 (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
# 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.path

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

    data         = None
    content_type = None
    filename     = None
    params       = None

    def __init__(self, data, ctype, filename, params):
        self.data         = data
        self.content_type = ctype
        self.params       = params

        # make sure the filename is a relative path
        # that does not go upwards
        filename = os.path.normpath(filename)
        if filename.startswith('/') or filename.startswith('..'):
            raise ValueError('Dangerous attachment filename: %s' % filename)

        self.filename = filename

    def __str__(self):
        ret = self.content_type
        if self.filename:
            ret += ':' + self.filename
        ret += ' (%s)' % _humanize_size(len(self.data))

        return ret