~m-buck/+junk/gtk-desktop-info

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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# plugin_email.py is a plugin for gnome-desktop-info to display email
# information. It can be used with pop and imap accounts, and supports ssl
#
#  Author: Kaivalagi
# Created: 23/11/2008
from datetime import datetime
from email.header import decode_header
from optparse import OptionParser
from plugin_common import getHTMLText, getTypedValue
import codecs
import fileinput
import imaplib
import logging
import os
import poplib
import re
import shutil
import socket
import traceback


app_name = "gtk-desktop-info"
app_path = os.path.dirname(os.path.abspath(__file__))
module_name = __file__.replace(os.path.dirname (__file__) + "/", "").replace(".pyc","").replace(".py", "")

class EmailData:
    def __init__(self, servername, folder, username, num, sender, subject, recvdate, messageid):
        self.servername = servername
        self.folder = folder
        self.username = username
        self.num = num
        self.sender = sender
        self.subject = subject
        self.recvdate = recvdate
        self.messageid = messageid

    def __cmp__(self, other):
        return cmp(self.getRecvDate(self.recvdate), self.getRecvDate(other.recvdate))

    def getRecvDate(self, recvdate):
        if recvdate is None:
            return datetime.now()
        else:
            return recvdate

class EmailConfig:
    HEADERTEMPLATE = None
    TEMPLATE = None
    CONNECTIONTIMEOUT = 10
    MAILINFO = 0
    FOLDER = "Inbox"

class Output:

    IMAP_SEARCH_OPTION = "UNSEEN" # "RECENT"
    POP_FETCH_OPTION = "TOP" # "RETR"

    emaillist = []
    logger = None
    options = None

    def __init__(self, options):
        self.options = options
        self.logger = logging.getLogger(app_name+"."+module_name)
        self.loadConfigData()

    def loadConfigData(self):
        try:
            self.config = EmailConfig()

            if self.options.config != None:
                # load the config based on options passed in from the main app
                configfilepath = self.options.config
            else:
                # load plugin config from home directory of the user
                configfilepath = os.path.join(os.path.expanduser('~'), ".config/"+app_name+"/"+module_name+".config")

            if os.path.exists(configfilepath):

                self.logger.info("Loading config settings from \"%s\""%configfilepath)

                for line in fileinput.input(os.path.expanduser(configfilepath)):
                    line = line.strip()
                    if len(line) > 0 and line[0:1] != "#": # ignore commented lines or empty ones

                        name = line.split("=")[0].strip().upper() # config setting name on the left of =
                        value = line.split("=")[1].split("#")[0].strip() # config value on the right of = (minus any trailing comments)

                        if len(value) > 0:
                            if name == "HEADERTEMPLATE":
                                self.config.HEADERTEMPLATE = getTypedValue(value, "string")
                            elif name == "TEMPLATE":
                                self.config.TEMPLATE = getTypedValue(value, "string")
                            elif name == "CONNECTIONTIMEOUT":
                                self.config.CONNECTIONTIMEOUT = getTypedValue(value, "integer")
                            elif name == "MAILINFO":
                                self.config.MAILINFO = getTypedValue(value, "integer")
                            elif name == "FOLDER":
                                self.config.FOLDER = getTypedValue(value, "string")
                            else:
                                self.logger.error("Unknown option in config file: " + name)
            else:
                self.logger.info("Config data file %s not found, using defaults and setting up config file for next time" % configfilepath)

                userconfigpath = os.path.join(os.path.expanduser('~'), ".config/"+app_name+"/")
                configsource = os.path.join(app_path, "config/"+module_name+".config")

                if os.path.exists(userconfigpath) == False:
                    os.makedirs(userconfigpath)

                shutil.copy(configsource, configfilepath)

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())

    def getTemplateList(self,template):

        templatelist = []

        for template_part in template.split("{"):
            if template_part != "":
                for template_part in template_part.split("}"):
                    if template_part != "":
                        templatelist.append(u""+template_part)

        return templatelist

    def getOutputData(self,servertype,servername,port,folder,ssl,username,password,connectiontimeout,mailinfo):
        try:
            output = u""

            socket.setdefaulttimeout(connectiontimeout)

            if servertype == "POP":
                count = self.getPOPEmailData(servername,port,folder,ssl,username,password,mailinfo)
            elif servertype == "IMAP":
                count = self.getIMAPEmailData(servername,port,folder,ssl,username,password,mailinfo)
            else:
                if self.config.VERBOSE == True:
                    self.logger.error("Unknown server type of %s requested"%servertype)

            if count == -1:
                output = "?"
            elif count == 0:
                output = "0"
            else:

                if mailinfo > 0:

                    output = "%s New"%count

                    counter = 0
                    self.emaillist.sort(reverse=True)
                    for emaildata in self.emaillist:
                        counter = counter + 1
                        if mailinfo >= counter:
                            output = output + "\n<br>%s. %s: \"%s\""%(counter,emaildata.sender,emaildata.subject)
                else:
                    output = str(count)

            return output

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
            return "?"

    def getTemplateItemOutput(self, template_text):

        # keys to template data
        SERVERTYPE_KEY = "servertype"
        SERVERNAME_KEY = "servername"
        PORT_KEY = "port"
        FOLDER_KEY = "folder"
        SSL_KEY= "ssl"
        USERNAME_KEY = "username"
        PASSWORD_KEY = "password"
        CONNECTION_TIMEOUT_KEY = "connectiontimeout"
        MAILINFO_KEY = "mailinfo"

        servertype = None
        servername = None
        port = None
        folder = self.config.FOLDER
        ssl = None
        username = None
        password = None
        connectiontimeout = self.config.CONNECTIONTIMEOUT
        mailinfo = self.config.MAILINFO

        for option in template_text.split('--'):
            if len(option) == 0 or option.isspace():
                continue

            # not using split here...it can't assign both key and value in one call, this should be faster
            x = option.find('=')
            if (x != -1):
                key = option[:x].strip()
                value = option[x + 1:].strip()
                if value == "":
                    value = None
            else:
                key = option.strip()
                value = None

            try:
                if key == SERVERTYPE_KEY:
                    servertype = getTypedValue(value, "string")
                elif key == SERVERNAME_KEY:
                    servername = getTypedValue(value, "string")
                elif key == PORT_KEY:
                    port = getTypedValue(value, "integer")
                elif key == FOLDER_KEY:
                    folder = getTypedValue(value, "string")
                elif key == SSL_KEY:
                    ssl = True
                elif key == USERNAME_KEY:
                    username = getTypedValue(value, "string")
                elif key == PASSWORD_KEY:
                    password = getTypedValue(value, "string")
                elif key == CONNECTION_TIMEOUT_KEY:
                    connectiontimeout = getTypedValue(value, "integer")
                elif key == MAILINFO_KEY:
                    mailinfo = getTypedValue(value, "integer")
                else:
                    self.logger.error("Unknown template option: " + option)

            except (TypeError, ValueError):
                self.logger.error("Cannot convert option argument to number: " + option)
                return u""

        if servername != None:
            output = self.getOutputData(servertype,servername,port,folder,ssl,username,password,connectiontimeout,mailinfo)
            output = getHTMLText(output)
            return output
        else:
            self.logger.error("Template item does not have servername defined")
            return u""


    def getOutputFromTemplate(self, template):
        output = u""
        end = False
        a = 0

        # a and b are indexes in the template string
        # moving from left to right the string is processed
        # b is index of the opening bracket and a of the closing bracket
        # everything between b and a is a template that needs to be parsed
        while not end:
            b = template.find('[', a)

            if b == -1:
                b = len(template)
                end = True

            # if there is something between a and b, append it straight to output
            if b > a:
                output += template[a : b]
                # check for the escape char (if we are not at the end)
                if template[b - 1] == '\\' and not end:
                    # if its there, replace it by the bracket
                    output = output[:-1] + '['
                    # skip the bracket in the input string and continue from the beginning
                    a = b + 1
                    continue

            if end:
                break

            a = template.find(']', b)

            if a == -1:
                self.logger.error("Missing terminal bracket (]) for a template item")
                return u""

            # if there is some template text...
            if a > b + 1:
                output += self.getTemplateItemOutput(template[b + 1 : a])

            a = a + 1

        return output

    def getEmailData(self,servername,folder,username,num,lines):

        try:
            self.logger.info("Processing email data to determine 'From', 'Subject' and 'Received Date'")

            sender = None
            subject = None
            recvdate = None
            messageid = None

            for line in lines:
                if sender is None and line.find("From: ") >= 0:
                    text = line.replace("From: ","").strip("\r ")
                    try:
                        text = self.decodeHeader(text)
                    except Exception, e:
                        sender = text
                        self.logger.error("getEmailData:Unexpected error when decoding sender:" + e.__str__()+"\n"+traceback.format_exc())
                    sender = re.sub('<.*?@.*?>','',text).strip().lstrip('"').rstrip('"') # remove trailing email in <>
                elif subject is None and line.find("Subject: ") >= 0:
                    text = line.replace("Subject: ","").strip("\r\" ")
                    try:
                        subject = self.decodeHeader(text)
                    except Exception, e:
                        subject = text
                        self.logger.error("getEmailData:Unexpected error when decoding subject:" + e.__str__()+"\n"+traceback.format_exc())
                elif recvdate is None and line.find("Date: ") >= 0:
                    text = line.replace("Date: ","").strip("\r ")
                    try:
                        text = re.match(r"(.*\s)(\d{1,2}\s\w{3}\s\d{4}\s\d{1,2}:\d{1,2}:\d{1,2})(\s.*)"," "+text+" ").group(2) # intentional space at the front and back of text to allow for groups when missing
                        recvdate = datetime.strptime(text,"%d %b %Y %H:%M:%S") # convert to proper datetime
                    except Exception, e:
                        recvdate = datetime.now()
                        self.logger.error("getEmailData:Unexpected error when converting recieve date to datetime:" + e.__str__()+"\n"+traceback.format_exc())
                elif messageid is None and line.find("Message-ID: ") >= 0:
                    text = line.replace("Message-ID: ","").strip("\r ")
                    messageid = text

                if sender is not None and \
                   subject is not None and \
                   recvdate is not None and \
                   messageid is not None:
                    break

            if subject is None:
                subject = ""

            emaildata = EmailData(servername, folder, username, num, sender, subject, recvdate, messageid)

            return emaildata

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
            return None

    def getPOPEmailData(self,servername,port,folder,ssl,username,password,mailinfo):

        try:

            self.logger.info("Logging on to POP server: "+ servername)

            if port == None:
                if ssl == True:
                    pop = poplib.POP3_SSL(servername)
                else:
                    pop = poplib.POP3(servername)
            else:
                if ssl == True:
                    pop = poplib.POP3_SSL(servername, port)
                else:
                    pop = poplib.POP3(servername, port)

            pop.user(username)
            pop.pass_(password)

            self.logger.info("Getting message count from POP server: "+ servername)

            count = len(pop.list()[1])

            if count > 0 and mailinfo > 0:

                self.logger.info("Extracting message data from POP server \"%s\""%servername)

                self.emaillist = []

                for num in range(count):

                    if self.POP_FETCH_OPTION == "TOP":
                        lines = pop.top(num+1,1)[1]
                    else:
                        lines = pop.retr(num+1,1)[1] #more robust but sets message as seen!

                    emaildata = self.getEmailData(servername,folder,username,num,lines)

                    if emaildata is not None:
                        self.emaillist.append(emaildata)

            self.logger.info("Logging off from POP server: "+ servername)

            pop.quit()

            return count

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
            return -1

    def getIMAPEmailData(self,servername,port,folder,ssl,username,password,mailinfo):

        try:

            self.logger.info("Logging on to IMAP server: "+ servername)

            if port == None:
                if ssl == True:
                    imap = imaplib.IMAP4_SSL(servername)
                else:
                    imap = imaplib.IMAP4(servername)
            else:
                if ssl == True:
                    imap = imaplib.IMAP4_SSL(servername, port)
                else:
                    imap = imaplib.IMAP4(servername, port)

            imap.login(username, password)

            self.logger.info("Searching for new mail on IMAP server \"%s\" in folder \"%s\""%(servername,folder))

            imap.select(folder)
            typ, data = imap.search(None, self.IMAP_SEARCH_OPTION)
            for item in data:
                if item == '':
                    data.remove(item)

            if len(data) > 0:
                nums = data[0].split()
                count = (len(nums))
            else:
                count = 0

            if count > 0 and mailinfo > 0:

                self.logger.info("Extracting message data for IMAP server: "+ servername)

                self.emaillist = []

                for num in nums:
                    typ, message = imap.fetch(num, '(BODY.PEEK[HEADER])')
                    lines = message[0][1].split("\n") # grab the content we want and split out lines

                    emaildata = self.getEmailData(servername,folder,username,num,lines)

                    if emaildata is not None:
                        self.emaillist.append(emaildata)

            self.logger.info("Logging of from IMAP server: "+ servername)

            imap.close()
            imap.logout()
            imap.shutdown()

            return count

        except Exception, e:
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
            return -1

    def getOutput(self):

        if self.options.noheader == True:
            headertemplatefilepath = app_path+"/templates/nullheader.template"
            self.logger.info("Using custom header template file '%s'"%headertemplatefilepath)
        elif self.options.headertemplate != None and os.path.exists(os.path.expanduser(self.options.headertemplate)) == True:
            headertemplatefilepath = self.options.headertemplate
            self.logger.info("Using custom header template file '%s'"%headertemplatefilepath)
        elif self.config.HEADERTEMPLATE != None and os.path.exists(os.path.expanduser(self.config.HEADERTEMPLATE)) == True:
            headertemplatefilepath = self.config.HEADERTEMPLATE
            self.logger.info("Using custom header template file '%s'"%headertemplatefilepath)
        else:
            headertemplatefilepath = app_path+"/templates/emailheader.template"
            self.logger.info("Using default header template")

        #load the file
        try:
            inputfile = codecs.open(os.path.expanduser(headertemplatefilepath), encoding='utf-8')
        except Exception, e:
            self.logger.error("Error loading header template file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
            headertemplate = inputfile.read()
        finally:
            inputfile.close()

        if self.options.template != None:
            templatefilepath = self.options.template
            self.logger.info("Using custom template file '%s'"%templatefilepath)
        elif self.config.TEMPLATE != None and os.path.exists(os.path.expanduser(self.config.TEMPLATE)) == True:
            templatefilepath = self.config.TEMPLATE
            self.logger.info("Using custom template file '%s'"%templatefilepath)
        else:
            templatefilepath = app_path+"/templates/email.template"
            self.logger.info("Using default template")

        # load the file
        try:
            inputfile = codecs.open(os.path.expanduser(templatefilepath), encoding='utf-8')
        except Exception, e:
            self.logger.error("Error loading template file: " + e.__str__()+"\n"+traceback.format_exc())
        else:
            template = inputfile.read()
        finally:
            inputfile.close()

        output = headertemplate
        output = output + self.getOutputFromTemplate(template)

        return output.encode("utf-8")

    def decodeHeader(self,header_text):

        text,encoding = decode_header(header_text)[0]
        if encoding:
            try:
                return text.decode(encoding)
            except: # fallback on decode error to windows encoding as this may be introduced by sloppy mail clients
                return text.decode('cp1252')
        else:
            return text

def getHTML(options):
    output = Output(options)
    html = output.getOutput()
    del output
    return html

# to enable testing in isolation
if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("--noheader", dest="noheader", default=False, action="store_true", help=u"Turn off header output. This will override any header template setting to be nothing")
    parser.add_option("--headertemplate", dest="headertemplate", type="string", metavar="FILE", help=u"Override the header template for the plugin, default or config based template ignored.")
    parser.add_option("--template", dest="template", type="string", metavar="FILE", help=u"Override the template for the plugin, default or config based template ignored.")
    parser.add_option("--verbose", dest="verbose", default=False, action="store_true", help=u"Outputs verbose info to the terminal")
    parser.add_option("--version", dest="version", default=False, action="store_true", help=u"Displays the version of the script.")
    parser.add_option("--logfile", dest="logfile", type="string", metavar="FILE", help=u"If a filepath is set, the script logs to the filepath.")

    (options, args) = parser.parse_args()

    output = Output(options)
    html = output.getOutput()
    del output
    print html