| 7 | |
| 8 | |
| 9 | class Notifier(object): |
| 10 | |
| 11 | class NotificationClient(object): |
| 12 | |
| 13 | def __init__(self, gather, timestamp): |
| 14 | self.gather = gather |
| 15 | self.timestamp = timestamp |
| 16 | |
| 17 | def run(self): |
| 18 | self.timestamp = self.gather(self.timestamp) |
| 19 | |
| 20 | def __init__(self, profile): |
| 21 | self._logger = logging.getLogger(__name__) |
| 22 | self.q = Queue.Queue() |
| 23 | self.profile = profile |
| 24 | self.notifiers = [] |
| 25 | |
| 26 | if 'gmail_address' in profile and 'gmail_password' in profile: |
| 27 | self.notifiers.append(self.NotificationClient( |
| 28 | self.handleEmailNotifications, None)) |
| 29 | else: |
| 30 | self._logger.warning('gmail_address or gmail_password not set ' + |
| 31 | 'in profile, Gmail notifier will not be used') |
| 32 | |
| 33 | sched = BackgroundScheduler(timezone="UTC", daemon=True) |
| 34 | sched.start() |
| 35 | sched.add_job(self.gather, 'interval', seconds=30) |
| 36 | atexit.register(lambda: sched.shutdown(wait=False)) |
| 37 | |
| 38 | def gather(self): |
| 39 | [client.run() for client in self.notifiers] |
| 40 | |
| 41 | def handleEmailNotifications(self, lastDate): |
| 42 | """Places new Gmail notifications in the Notifier's queue.""" |
| 43 | emails = Gmail.fetchUnreadEmails(self.profile, since=lastDate) |
| 44 | if emails: |
| 45 | lastDate = Gmail.getMostRecentDate(emails) |
| 46 | |
| 47 | def styleEmail(e): |
| 48 | return "New email from %s." % Gmail.getSender(e) |
| 49 | |
| 50 | for e in emails: |
| 51 | self.q.put(styleEmail(e)) |
| 52 | |
| 53 | return lastDate |
| 54 | |
| 55 | def getNotification(self): |
| 56 | """Returns a notification. Note that this function is consuming.""" |
| 57 | try: |
| 58 | notif = self.q.get(block=False) |
| 59 | return notif |
| 60 | except Queue.Empty: |
| 61 | return None |
| 62 | |
| 63 | def getAllNotifications(self): |
| 64 | """ |
| 65 | Return a list of notifications in chronological order. |
| 66 | Note that this function is consuming, so consecutive calls |