File: thunderbird.py

package info (click to toggle)
taskcoach 1.4.1-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 32,496 kB
  • ctags: 17,810
  • sloc: python: 72,170; makefile: 254; ansic: 120; xml: 29; sh: 16
file content (412 lines) | stat: -rw-r--r-- 14,887 bytes parent folder | download
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
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2014 Task Coach developers <developers@taskcoach.org>

Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Task Coach is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from taskcoachlib import persistence, operating_system
from taskcoachlib.thirdparty.ntlm import IMAPNtlmAuthHandler
from taskcoachlib.widgets.password import GetPassword
from taskcoachlib.i18n import _
import os
import stat
import re
import imaplib
import ConfigParser
import wx
import socket
import mailbox


_RX_MAILBOX_MESSAGE = re.compile(r'mailbox-message://(.*)@(.*)/(.*)#((?:-)?\d+)')
_RX_IMAP_MESSAGE = re.compile(r'imap-message://([^@]+)@([^/]+)/(.*)#(\d+)')
_RX_IMAP = re.compile(r'imap://([^@]+)@([^/]+)/fetch%3EUID%3E(?:/|\.)(.*)%3E(\d+)')
_RX_MAILBOX = re.compile(r'mailbox://([^?]+)\?number=(\d+)')


class ThunderbirdError(Exception):
    pass


class ThunderbirdCancelled(ThunderbirdError):
    pass


def unquote(s):
    """Converts %nn sequences into corresponding characters. I
    couldn't find anything in the standard library to do this, but I
    probably didn't search hard enough."""

    rx = re.compile('%([0-9a-fA-F][0-9a-fA-F])')
    mt = rx.search(s)
    while mt:
        s = s[:mt.start(1) - 1] + chr(int(mt.group(1), 16)) + s[mt.end(1):]
        mt = rx.search(s)

    return s


def loadPreferences():
    """Reads Thunderbird's prefs.js file and return a dictionary of
    configuration options."""

    config = {}

    def user_pref(key, value):
        config[key] = value

    for line in file(os.path.join(getDefaultProfileDir(), 'prefs.js'), 'r'):
        if line.startswith('user_pref('):
            # pylint: disable=W0122
            exec line in {'user_pref': user_pref, 'true': True, 'false': False}

    return config


def getThunderbirdDir():
    path = None

    if operating_system.isMac():
        path = os.path.join(os.environ['HOME'], 'Library', 'Thunderbird')
    elif os.name == 'posix':
        path = os.path.join(os.environ['HOME'], '.thunderbird')
        if not os.path.exists(path):
            path = os.path.join(os.environ['HOME'], '.mozilla-thunderbird')
    elif os.name == 'nt':
        if os.environ.has_key('APPDATA'):
            path = os.path.join(os.environ['APPDATA'], 'Thunderbird')
        elif os.environ.has_key('USERPROFILE'):
            path = os.path.join(os.environ['USERPROFILE'], 'Application Data', 'Thunderbird')
    else:
        raise EnvironmentError('Unsupported platform: %s' % os.name)

    if path is None:
        raise ThunderbirdError(_('Could not find Thunderbird data dir'))

    return path

_PORTABLECACHE = None


def getDefaultProfileDir():
    """Returns Thunderbird's default profile directory"""

    global _PORTABLECACHE  # pylint: disable=W0603

    path = getThunderbirdDir()

    # Thunderbird Portable does not have a profiles.ini file, only one
    # profile. And there's only one way to know where it
    # is... Hackish.

    if os.name == 'nt' and not os.path.exists(os.path.join(path, 'profiles.ini')):
        if _PORTABLECACHE is not None:
            return _PORTABLECACHE

        from taskcoachlib.thirdparty import wmi  # pylint: disable=W0404

        for process in wmi.WMI().Win32_Process():
            if process.ExecutablePath and process.ExecutablePath.lower().endswith('thunderbirdportable.exe'):
                _PORTABLECACHE = os.path.join(os.path.split(process.ExecutablePath)[0], 'Data', 'profile')
                break
        else:
            raise ThunderbirdError(_('Could not find Thunderbird profile.'))

        return _PORTABLECACHE

    parser = ConfigParser.RawConfigParser()
    parser.read([os.path.join(path, 'profiles.ini')])

    for section in parser.sections():
        if parser.has_option(section, 'Default') and int(parser.get(section, 'Default')):
            if int(parser.get(section, 'IsRelative')):
                return os.path.join(path, parser.get(section, 'Path'))
            return parser.get(section, 'Path')

    for section in parser.sections():
        if parser.has_option(section, 'Name') and parser.get(section, 'Name') == 'default':
            if int(parser.get(section, 'IsRelative')):
                return os.path.join(path, parser.get(section, 'Path'))
            return parser.get(section, 'Path')

    raise ThunderbirdError(_('No default section in profiles.ini'))


class ThunderbirdMailboxReader(object):
    """Extracts an e-mail from a Thunderbird file. Behaves like a
    stream object to read this e-mail."""

    def __init__(self, url):
        """url is the internal reference to the mail, as collected
        through drag-n-drop."""

        mt = _RX_MAILBOX_MESSAGE.search(url)
        if mt is None:
            raise ThunderbirdError(_('Malformed Thunderbird internal ID:\n%s. Please file a bug report.') % url)

        self.url = url

        # The url has the form
        # mailbox-message://<username>@<hostname>//<filename>#<id>. Or
        # so I hope.

        config = loadPreferences()

        self.user = unquote(mt.group(1))
        self.server = unquote(mt.group(2))
        self.path = unquote(mt.group(3)).split('/')
        self.offset = long(mt.group(4))

        for i in xrange(200):
            base = 'mail.server.server%d' % i
            if config.has_key('%s.userName' % base):
                if config['%s.userName' % base] == self.user and config['%s.hostname' % base] == self.server:
                    # First try the relative path.
                    if config.has_key('%s.directory-rel' % base):
                        path = config['%s.directory-rel' % base]
                        if path.startswith('[ProfD]'):
                            path = os.path.join(getDefaultProfileDir(), path[7:])
                        self.filename = os.path.join(path, *tuple(self.path))
                        if os.path.exists(self.filename):
                            break
                        else:
                            self.filename = os.path.join(config['%s.directory' % base], *tuple(self.path))
                            if os.path.exists(self.filename):
                                break
        else:
            raise ThunderbirdError(_('Could not find directory for ID\n%s.\nPlease file a bug report.') % url)

        self.fp = file(self.filename, 'rb')
        if self.offset >= 0:
            self.fp.seek(self.offset)
        else:
            self.fp.seek(self.offset, os.SEEK_END)

        self.done = False

    def read(self):
        """Buffer-like read() method"""

        if self.done:
            return ''

        lines = []

        # In theory, the message ends with a single dot. As always, in
        # theory, theory is like practice but in practice...

        starting = True

        for line in self.fp:
            if not starting:
                if line.startswith('From '):
                    break
            lines.append(line)
            starting = False

        self.done = True
        return ''.join(lines)

    def __iter__(self):
        class Iterator(object):
            def __init__(self, fp):
                self.fp = fp

            def __iter__(self):
                return self

            def next(self):
                line = self.fp.readline()
                if line.strip() == '.':
                    raise StopIteration
                return line

        return Iterator(self.fp)

    def saveToFile(self, fp):
        fp.write(self.read())


class ThunderbirdImapReader(object):
    def __init__(self, url):
        mt = _RX_IMAP.search(url)
        if mt is None:
            mt = _RX_IMAP_MESSAGE.search(url)
            if mt is None:
                raise ThunderbirdError(_('Unrecognized URL scheme: "%s"') % url)

        self.url = url

        self.user = unquote(mt.group(1))
        self.server = mt.group(2) 
        port = None
        if ':' in self.server:
            self.server, port = self.server.split(':')
            port = int(port)
        self.box = mt.group(3)
        self.uid = int(mt.group(4))

        config = loadPreferences()

        stype = None
        # We iterate over a maximum of 100 mailservers. You'd think that
        # mailservers would be numbered consecutively, but apparently
        # that is not always the case, so we cannot assume that because
        # serverX does not exist, serverX+1 won't either. 
        for serverIndex in range(100): 
            name = 'mail.server.server%d' % serverIndex
            if config.has_key(name + '.hostname') and \
                self.__equal_servers(config[name + '.hostname'], self.server) \
                and config[name + '.type'] == 'imap':
                if config.has_key(name + '.port'):
                    port = int(config[name + '.port'])
                if config.has_key(name + '.socketType'):
                    stype = config[name + '.socketType']
                break
        self.ssl = (stype == 3)

        if self.server in ('imap.google.com', 'imap.googlemail.com'):
            # When dragging mail from Thunderbird that uses Gmail via IMAP the
            # server reported is imap.google.com, but for a direct connection we
            # need to connect with imap.gmail.com:
            self.server = 'imap.gmail.com'
        elif config.has_key(name + '.realhostname'):
            self.server = config[name + '.realhostname']
        self.port = port or {True: 993, False: 143}[self.ssl]
        
    @staticmethod
    def __equal_servers(server1, server2):
        ''' Return whether the servers are the same. '''
        gmail_servers = ('imap.gmail.com', 'imap.google.com', 
                         'imap.googlemail.com')
        if server1 in gmail_servers and server2 in gmail_servers:
            return True
        else:
            return server1 == server2

    def _getMail(self):
        ''' Retrieve the email message from the IMAP server as specified by
            the dropped URL. '''
        imap_class = imaplib.IMAP4_SSL if self.ssl else imaplib.IMAP4
        try:
            imap = imap_class(self.server, self.port)
        except socket.gaierror, reason:
            error_message = _('Could not open an IMAP connection to '
                              '%(server)s:%(port)s\nto retrieve Thunderbird '
                              'email message:\n%(reason)s') % \
                              dict(server=self.server, port=self.port, 
                                   reason=reason)
            raise ThunderbirdError(error_message)

        password_domain = '%s:%d' % (self.server, self.port)
        pwd = GetPassword(password_domain, self.user)
        if pwd is None:
            raise ThunderbirdCancelled('User canceled')

        while True:
            try:
                if 'AUTH=CRAM-MD5' in imap.capabilities:
                    response, dummy = imap.login_cram_md5(str(self.user), 
                                                          str(pwd))
                elif 'AUTH=NTLM' in imap.capabilities:
                    domain = wx.GetTextFromUser( \
                        _('Please enter the domain for user %s') % self.user)
                    domain_username = '\\'.join([domain.upper(), 
                                                 str(self.user)])
                    response, dummy_parameters = imap.authenticate('NTLM', 
                        IMAPNtlmAuthHandler.IMAPNtlmAuthHandler( \
                            domain_username, str(pwd)))
                else:
                    response, dummy_parameters = imap.login(self.user, pwd)
            except imap.error, reason:
                response = 'KO'
                error_message, = reason.args

            if response == 'OK':
                break

            pwd = GetPassword(password_domain, self.user, reset=True)
            if pwd is None:
                raise ThunderbirdCancelled('User canceled')

        # Two possibilities for separator...

        response, dummy_parameters = imap.select(self.box)

        if response != 'OK':
            response, dummy_parameters = imap.select(self.box.replace('/', '.'))
            if response != 'OK':
                raise ThunderbirdError(_('Could not select inbox "%s"\n(%s)') \
                                       % (self.box, response))

        response, parameters = imap.uid('FETCH', str(self.uid), '(RFC822)')

        if response != 'OK':
            raise ThunderbirdError(_('No such mail: %d') % self.uid)

        return parameters[0][1]

    def saveToFile(self, fp):
        fp.write(self._getMail())


class ThunderbirdLocalMailboxReader(object):
    ''' Reads email from a local Thunderbird mailbox. '''
    def __init__(self, url):
        self.url = url
        
    def _getMail(self):
        match = _RX_MAILBOX.match(self.url)
        if match is None:
            raise ThunderbirdError(_('Unrecognized URL scheme: "%s"') % self.url)
        path = unquote(match.group(1))
        # Note that the number= part of the URL is not the message key, but
        # rather an offset in the mbox file.
        offset = int(match.group(2))
        # So we skip the first offset bytes before reading the contents:
        with file(path, 'rb') as mbox:
            mbox.seek(offset)
            contents = mbox.read(4 * 1024 * 1024)  # Assume message size <= 4MB
        # Then we get a filename for a temporary file...
        filename = persistence.get_temp_file()
        # And save the remaining contents of the original mbox file: 
        with file(filename, 'wb') as tmpmbox:
            tmpmbox.write(contents)
        # Now we can open the temporary mbox file...
        mb = mailbox.mbox(filename)
        # And the message we look for should be the first one:
        return mb.get_string(0)
        
    def saveToFile(self, fp):
        fp.write(self._getMail())
    

def getMail(id_):
    if id_.startswith('mailbox-message://'):
        reader = ThunderbirdMailboxReader(id_)
    elif id_.startswith('imap'):
        reader = ThunderbirdImapReader(id_)
    elif id_.startswith('mailbox:'):
        reader = ThunderbirdLocalMailboxReader(id_)
    else:
        raise TypeError('Not supported: %s' % id_)

    filename = persistence.get_temp_file(suffix='.eml')
    reader.saveToFile(file(filename, 'wb'))

    if os.name == 'nt':
        os.chmod(filename, stat.S_IREAD)

    return filename