~jhonnyc/cgmail/jonathanc-branch

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
import urllib2 
import time
import thread

from lib import feedparser
from lib.common import *
from lib.accountmanager import AccountManager
from notifier import Notifier

from lib.pop3 import *
from lib.imap import *

class BaseChecker:
	def __init__(self, account_id, set_status_cb):
		self.account_id = account_id
		self.set_status_cb = set_status_cb

		self.checking = False
		self.notifier = Notifier()

	def reset(self): 
		"""
		After this method is invoked, the checer must consider
		all mails as not notified
		"""
		raise NotImplementedError()
	
	def notify_error(self, error, text, f):
		self.notifier.notify(error, text, msec = 10000, 
			buttons = False, error = True, force = f)
	
	def notify_msg(self, mailbox, count, mails):
		subject_i18n = _(u"<b>Subject:</b>")
		author_i18n = _(u"<b>From:</b>")
		message = u""
		total = 0
		mailboxname = _("<b>Box:</b> %s") % mailbox
		total += count
		for author, subject in mails:
			try:
				author = unicode(author, "utf-8")
			except UnicodeDecodeError:
				author = unicode(author, "latin-1", "replace")
			except:
				pass
			try:
				subject = unicode(subject, "utf-8")
			except UnicodeDecodeError:
				subject = unicode(subject, "latin-1", "replace")
			except:
				pass
			try:
				message += u"%s %s\n%s %s\n%s\n\n" % \
					(subject_i18n, subject,
					author_i18n, author, mailboxname)
			except:
				message += u"%s %s\n%s %s\n%s\n\n" % \
					(subject_i18n, _("Unknown"),
					author_i18n, _("Unknown"), mailboxname)
		if total > 1:
			title = _("There are %s new mails") % total
		else:
			title = _("There is a new mail")

		self.set_status_cb(self.account_id, count, title, message)
		
	def check(self): 
		"""
		Must return a list of 3 elements. First element must
		be the mailbox name, second the message count into mailbox, 
		third element a list of tuple. Each
		tuple must contain the from and subject field of the email
		Example:
			["test@gmail.com", 2, [ ["Test Mailer <test@domain.com>", "This is the subject"], 
					["Second <sec@test.com>", "Second Subject"] ]]
		"""
		raise NotImplementedError()
	
	def update_info(self, account):
		"""
		This method receive an account dic and update checker info
		using account values
		"""
		raise NotImplementedError()

class GmailChecker(BaseChecker):
	def __init__(self, account_id, status_cb, user, password):
		self.username = user
		self.password = password
		self.notified = []
		BaseChecker.__init__(self, account_id, status_cb)
	
	def reset(self):
		self.notified = []

	def getfeed(self):
		ah = urllib2.HTTPBasicAuthHandler()
		ah.add_password('New mail feed', GMAIL_URL, \
					self.username, self.password)
		op = urllib2.build_opener(ah)
		urllib2.install_opener(op)
		res = urllib2.urlopen(GMAIL_ATOM_URL)
		return ''.join(res.readlines())
	
	def update_info(self, account):
		self.username = account["username"]
		self.password = account["password"]
	
	def check(self):
		"""
		Check for new mails.
		"""
		# prevent recalling
		if self.checking: return
		self.checking = True

		print "checking gmail account %s ..." % self.username

		try:
			feed = self.getfeed()
		except urllib2.HTTPError, e:
			if str(e) == "HTTP Error 401: Unauthorized":
				msg = _("Invalid username or password! Please check your settings!")
			else:
				msg = str(e)
			
			error = _("Gmail Error on account %s") % self.username
			self.notify_error(error, msg, True)
			self.checking = False
			return
		except Exception, e:
			print "Warning:", e
			self.notify_error(error, msg, False)
			self.checking = False
			return

		print "...done"

		try:
			atom = feedparser.parse(feed)
		except Exception, detail:
			print "Warning: Exception while parsing gmail feeds", detail
			self.notify_error(_("Gmail Warning"), _("Exception while parsing gmail feeds", False))
			self.checking = False
			return

		count = len(atom.entries)
		
		mailbox = "%s@gmail.com" % self.username
		mails = []

		if count == 0:
			self.checking = False
			#return mailbox, 0, mails
			return

		if count < MAX_NOTIFIED_MAILS:
			loop = count
		else:
			loop = MAX_NOTIFIED_MAILS
		
		mustnotify = False

		for i in xrange(loop):
			link = atom.entries[i].link
			tmp = link[link.find("message_id"):]
			message_id =  tmp[:tmp.find("&")].split("=")[1]

			if message_id not in self.notified:
				mustnotify = True
				self.notified.append(message_id)
				title  = atom.entries[i].title
				author = atom.entries[i].author
				mails.append([author, title])
		
		if not mustnotify:
			self.notify_msg(mailbox, count, [])
		else:
			self.notify_msg(mailbox, count, mails)

		self.checking = False

class POP3Checker(BaseChecker):
	def __init__(self, account_id, status_cb, username, password, server, port, ssl):
		self.username = username
		self.server = server
		self.port = port
		
		self.notified = []

		self.popbox = PopBox(username, password, server, port, ssl)

		BaseChecker.__init__(self, account_id, status_cb)
					
	def reset(self):
		self.notified = []
	
	def update_info(self, account):
		username = account["username"]
		password = account["password"]
		ssl = account["ssl"]
		self.server = account["server"]
		self.port = account["port"]
		ssl = False
		if account.has_key("ssl"):
			if account["ssl"] == "1":
				ssl = True
			elif account["ssl"] == "0":
				ssl = False
		del self.popbox
		self.popbox = PopBox(username, password, self.server, self.port, ssl)
	
	def check(self):
		# prevent recalling
		if self.checking: return
		self.checking = True

		mailbox = "%s@%s" % (self.username, self.server)
		
		print "checking pop3 account %s@%s ..." % (self.username, self.server)
		try:
			# each mail in mail: [subject, from, msgid]
			mails = self.popbox.get_mails()
		except PopBoxConnectionError:
			err = _("POP3 Error")
			msg = _("Error while connecting to %s on port %s") % (self.server, 
										self.port)
			self.notify_error(error, msg, False)
			self.checking = False
			return
		except PopBoxAuthError:
			err = _("POP3 Auth Error")
			msg = _("Invalid Username or password for account %s@%s") % (self.username, 
										self.server)
			self.notify_error(error, msg, True)
			self.checking = False
			return

		count = len(mails)
		returnlist = []

		if count == 0:
			self.checking = False
			return
			#return mailbox, 0, returnlist

		if count < MAX_NOTIFIED_MAILS:
			loop = count
		else:
			loop = MAX_NOTIFIED_MAILS

		tmp = 0
		
		mustnotify = False
		mails.reverse()
		for mail in mails:
			msgid = mail[2]
			if msgid not in self.notified:
				if tmp <= loop:
					try:
						subject = mail[0]
						author = mail[1]
						returnlist.append([author, subject])
					except:
						print "Warning: pop3checker cannot display the message"
					tmp += 1
				self.notified.append(msgid)
				mustnotify = True

		print "...done"
		if not mustnotify:
			self.notify_msg(mailbox, count, [])
		else:
			self.notify_msg(mailbox, count, mails)

		self.checking = False

class IMAPChecker(BaseChecker):
	def __init__(self, account_id, status_cb, username, password, 
			server, port, ssl, 
			use_default_mbox, mbox_dir = None):
		self.username = username
		self.server = server
		self.port = port
		self.use_default_mbox = use_default_mbox
		self.mbox_dir = mbox_dir
		
		self.notified = []

		self.imapbox = ImapBox(username, password, 
						server, port, ssl,
						use_default_mbox, mbox_dir)

		BaseChecker.__init__(self, account_id, status_cb)
					
	def reset(self):
		self.notified = []
	
	def update_info(self, account):
		self.username = account["username"]
		password = account["password"]
		ssl = account["ssl"]
		self.server = account["server"]
		self.port = account["port"]
		ssl = False
		if account.has_key("ssl"):
			if account["ssl"] == "1":
				ssl = True
			elif account["ssl"] == "0":
				ssl = False
		mbox_dir = None
		if account["use_default_mbox"] == "1":
			use_default_mbox = True
		else:
			use_default_mbox = False
			mbox_dir = account["mbox"]
			
		del self.imapbox
		self.imapbox = ImapBox(self.username, password, 
						self.server, self.port, ssl,
						use_default_mbox, mbox_dir)

	def check(self):
		# prevent recalling
		if self.checking: return
		self.checking = True

		mailbox = "%s@%s" % (self.username, self.server)
		
		print "checking imap account %s@%s ..." % (self.username, self.server)
		try:
			# each mail in mail: [subject, from, msgid]
			mails = self.imapbox.get_mails()
		except ImapBoxConnectionError:
			err = _("IMAP Error")
			msg = _("Error while connecting to %s on port %s") % (self.server, 
										self.port)
			self.notify_error(error, msg, False)
			self.checking = False
			return
		except ImapBoxAuthError:
			err = _("IMAP Auth Error")
			msg = _("Invalid Username or password for account %s@%s") % (self.username, 
										self.server)
			
			self.notify_error(error, msg, True)
			self.checking = False
			return

		count = len(mails)
		returnlist = []

		if count == 0:
			return mailbox, 0, returnlist

		if count < MAX_NOTIFIED_MAILS:
			loop = count
		else:
			loop = MAX_NOTIFIED_MAILS

		tmp = 0
		
		mustnotify = False
		mails.reverse()
		for mail in mails:
			msgid = mail[2]
			if msgid not in self.notified:
				if tmp <= loop:
					try:
						subject = mail[0]
						author = mail[1]
						returnlist.append([author, subject])
					except:
						print "Warning: imapchecker cannot display the message"
					tmp += 1
				self.notified.append(msgid)
				mustnotify = True

		print "...done"
		if not mustnotify:
			self.notify_msg(mailbox, count, [])
		else:
			self.notify_msg(mailbox, count, returnlist)

		self.checking = False
		
class Checker:

	def __init__(self):
		self.notifier = Notifier()
		self.checkers = {} # account_id: checker, messages_count
		self.checking = False
		self.status_cbs = []
	
	def add_status_cb(self, cb):
		self.status_cbs.append(cb)
	
	def remove_status_cb(self,cb):
		self.status_cbs.remove(cb)

	def set_no_accounts_cb(self, cb):
		self.no_accounts_cb = cb

	def init_checkers(self, no_accounts_cb):
		"""
		Build checkers list.
		"""
		#self.checkers = []
		
		am = AccountManager().get_manager()
		accounts = am.get_accounts_dicts()
		if accounts is None or len(accounts) == 0:
			self.checkers = {}
			if no_accounts_cb is not None:
				no_accounts_cb()
			# nothing more to do
			return

		
		id_list = []
		for account in accounts:
			id_list.append(account["id"])

			needed_keys = ["type", "username", "password", "enabled"]
			has_needed = True
			for k in needed_keys:
				if not account.has_key(k):
					print "Warnig: bad configration"
					has_needed = False
					break

			if not has_needed: continue

			if account["enabled"] == "0":
				# we no more want this checker
				if self.checkers.has_key(account["id"]):
					del self.checkers[account["id"]]
				continue

			if account["id"] in self.checkers.keys():
				# We already have a checker for this account
				checker, msg_count = self.checkers[account["id"]]
				checker.update_info(account)
				continue

			if account["type"] == "gmail":
				tmp = GmailChecker(account["id"], self.set_status,
							account["username"], 
							account["password"])
				self.checkers[account["id"]] = [tmp, 0]
			elif account["type"] == "pop3" or account["type"] == "imap":
				user = account["username"]
				passw = account["password"]
				if not account.has_key("server"):
					print "Warnig: bad configration"
					continue
				server = account["server"]
				ssl = False
				if account.has_key("ssl"):
					if account["ssl"] == "1":
						ssl = True
					elif account["ssl"] == "0":
						ssl = False
				if account["type"] == "pop3":
					port = 110 # default pop3 port
					if account.has_key("port"):
						port = account["port"]

					tmp = POP3Checker(account["id"], self.set_status,
							user, passw, server, port, ssl)
				else:
					port = 143 # default imap port
					if account.has_key("port"):
						port = account["port"]
					#imap
					if account["use_default_mbox"] == "1":

						tmp = IMAPChecker(account["id"], self.set_status,
								user, passw, 
								server, port, ssl, True)
					else:
						mbox = account["mbox"]
						tmp = IMAPChecker(user, passw, 
								server, port, 
								ssl, False, mbox)
				self.checkers[account["id"]] = [tmp, 0]
			else:
				print "Error: unrecognized account type"
		
		# remove checker if the account no more exist
		for id in self.checkers.keys():
			if id not in id_list:
				del self.checkers[id]

		
	def reset(self):
		for account_id, values in self.checkers.iteritems():
			checker = values[0]
			checker.reset()
	
	def set_status(self, account_id, messages_count, title, message):
		"""
		This method is only called by BaseChecker
		"""
		checker, msgs = self.checkers[account_id]
		self.checkers[account_id] = [checker, messages_count]

		total = 0
		for checker, count in self.checkers.values():
			total += count

		if message != "":
			self.notifier.notify(title, message, msec = 10000)
		
			for cb in self.status_cbs:
				cb(total, title, message)
		else:
			# only update count
			for cb in self.status_cbs:
				cb(total, None, None)

	
	def check(self):
		
		self.init_checkers(None)

		mailslists = []
		for account_id, values in self.checkers.iteritems():
			checker = values[0]
			thread.start_new_thread(checker.check, ())
		
	
if __name__ == "__main__":
	c = Checker()
	c.check()