gmail_checker.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # -*- coding: utf-8 -*-
  2. import logging
  3. from gmail import Gmail
  4. from email.header import decode_header
  5. from core.NeuronModule import NeuronModule, MissingParameterException
  6. logging.basicConfig()
  7. logger = logging.getLogger("kalliope")
  8. class Gmail_checker(NeuronModule):
  9. def __init__(self, **kwargs):
  10. super(Gmail_checker, self).__init__(**kwargs)
  11. self.username = kwargs.get('username', None)
  12. self.password = kwargs.get('password', None)
  13. # check if parameters have been provided
  14. if self._is_parameters_ok():
  15. # prepare a returned dict
  16. returned_dict = dict()
  17. g = Gmail()
  18. g.login(self.username, self.password)
  19. # check if login succeed
  20. logging.debug("Gmail loggin ok: %s" % g.logged_in) # Should be True, AuthenticationError if login fails
  21. # get unread mail
  22. unread = g.inbox().mail(unread=True)
  23. returned_dict["unread"] = len(unread)
  24. if len(unread) > 0:
  25. # add a list of subject
  26. subject_list = list()
  27. for email in unread:
  28. email.fetch()
  29. encoded_subject = email.subject
  30. subject = self._parse_subject(encoded_subject)
  31. subject_list.append(subject)
  32. returned_dict["subjects"] = subject_list
  33. logger.debug("gmail neuron returned dict: %s" % str(returned_dict))
  34. # logout of gmail
  35. g.logout()
  36. self.say(returned_dict)
  37. def _parse_subject(self, encoded_subject):
  38. dh = decode_header(encoded_subject)
  39. return ''.join([self.try_parse(t[0], t[1]) for t in dh])
  40. @staticmethod
  41. def try_parse(header, encoding):
  42. if encoding is None:
  43. encoding = 'ASCII'
  44. try:
  45. return unicode(header, encoding)
  46. except UnicodeDecodeError:
  47. try:
  48. return unicode(header, 'ISO-8859-1')
  49. except UnicodeDecodeError:
  50. return unicode(header, 'UTF-8')
  51. def _is_parameters_ok(self):
  52. """
  53. Check if received parameters are ok to perform operations in the neuron
  54. :return: true if parameters are ok, raise an exception otherwise
  55. """
  56. if self.username is None:
  57. raise MissingParameterException("Username parameter required")
  58. if self.password is None:
  59. raise MissingParameterException("Password parameter required")
  60. return True