gmail_checker.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. """
  43. Verifying the Encoding and return unicode
  44. :param header: the header to decode
  45. :param encoding: the targeted encoding
  46. :return: either 'ASCII' or 'ISO-8859-1' or 'UTF-8'
  47. .. raises:: UnicodeDecodeError
  48. """
  49. if encoding is None:
  50. encoding = 'ASCII'
  51. try:
  52. return unicode(header, encoding)
  53. except UnicodeDecodeError:
  54. try:
  55. return unicode(header, 'ISO-8859-1')
  56. except UnicodeDecodeError:
  57. return unicode(header, 'UTF-8')
  58. def _is_parameters_ok(self):
  59. """
  60. Check if received parameters are ok to perform operations in the neuron
  61. :return: true if parameters are ok, raise an exception otherwise
  62. .. raises:: MissingParameterException
  63. """
  64. if self.username is None:
  65. raise MissingParameterException("Username parameter required")
  66. if self.password is None:
  67. raise MissingParameterException("Password parameter required")
  68. return True