You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
8.8 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright - 2013-2018 Therp BV <https://therp.nl>.
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. import base64
  5. import logging
  6. from odoo import _, api, models, fields
  7. from odoo.exceptions import UserError
  8. from .. import match_algorithm
  9. _logger = logging.getLogger(__name__)
  10. class FetchmailServerFolder(models.Model):
  11. _name = 'fetchmail.server.folder'
  12. _rec_name = 'path'
  13. _order = 'sequence'
  14. def _get_match_algorithms(self):
  15. def get_all_subclasses(cls):
  16. return (cls.__subclasses__() +
  17. [subsub
  18. for sub in cls.__subclasses__()
  19. for subsub in get_all_subclasses(sub)])
  20. return dict([(cls.__name__, cls)
  21. for cls in get_all_subclasses(
  22. match_algorithm.base.Base)])
  23. def _get_match_algorithms_sel(self):
  24. algorithms = []
  25. for cls in self._get_match_algorithms().itervalues():
  26. algorithms.append((cls.__name__, cls.name))
  27. algorithms.sort()
  28. return algorithms
  29. sequence = fields.Integer('Sequence')
  30. path = fields.Char(
  31. 'Path',
  32. help="The path to your mail folder. Typically would be something like "
  33. "'INBOX.myfolder'", required=True)
  34. model_id = fields.Many2one(
  35. 'ir.model', 'Model', required=True,
  36. help='The model to attach emails to')
  37. model_field = fields.Char(
  38. 'Field (model)',
  39. help='The field in your model that contains the field to match '
  40. 'against.\n'
  41. 'Examples:\n'
  42. "'email' if your model is res.partner, or "
  43. "'partner_id.email' if you're matching sale orders")
  44. model_order = fields.Char(
  45. 'Order (model)',
  46. help='Field(s) to order by, this mostly useful in conjunction '
  47. "with 'Use 1st match'")
  48. match_algorithm = fields.Selection(
  49. _get_match_algorithms_sel,
  50. 'Match algorithm', required=True,
  51. help='The algorithm used to determine which object an email matches.')
  52. mail_field = fields.Char(
  53. 'Field (email)',
  54. help='The field in the email used for matching. Typically '
  55. "this is 'to' or 'from'")
  56. server_id = fields.Many2one('fetchmail.server', 'Server')
  57. delete_matching = fields.Boolean(
  58. 'Delete matches',
  59. help='Delete matched emails from server')
  60. flag_nonmatching = fields.Boolean(
  61. 'Flag nonmatching',
  62. default=True,
  63. help="Flag emails in the server that don't match any object in Odoo")
  64. match_first = fields.Boolean(
  65. 'Use 1st match',
  66. help='If there are multiple matches, use the first one. If '
  67. 'not checked, multiple matches count as no match at all')
  68. domain = fields.Char(
  69. 'Domain',
  70. help='Fill in a search filter to narrow down objects to match')
  71. msg_state = fields.Selection(
  72. selection=[('sent', 'Sent'), ('received', 'Received')],
  73. string='Message state',
  74. default='received',
  75. help='The state messages fetched from this folder should be '
  76. 'assigned in Odoo')
  77. active = fields.Boolean('Active', default=True)
  78. @api.multi
  79. def get_algorithm(self):
  80. return self._get_match_algorithms()[self.match_algorithm]()
  81. @api.multi
  82. def button_attach_mail_manually(self):
  83. self.ensure_one()
  84. return {
  85. 'type': 'ir.actions.act_window',
  86. 'res_model': 'fetchmail.attach.mail.manually',
  87. 'target': 'new',
  88. 'context': dict(self.env.context, folder_id=self.id),
  89. 'view_type': 'form',
  90. 'view_mode': 'form'}
  91. @api.multi
  92. def get_msgids(self, connection, criteria):
  93. """Return imap ids of messages to process"""
  94. self.ensure_one()
  95. server = self.server_id
  96. _logger.info(
  97. 'start checking for emails in folder %s on server %s',
  98. self.path, server.name)
  99. if connection.select(self.path)[0] != 'OK':
  100. raise UserError(_(
  101. "Could not open mailbox %s on %s") %
  102. (self.path, server.name))
  103. result, msgids = connection.search(None, criteria)
  104. if result != 'OK':
  105. raise UserError(_(
  106. "Could not search mailbox %s on %s") %
  107. (self.path, server.name))
  108. _logger.info(
  109. 'finished checking for emails in %s on server %s',
  110. self.path, server.name)
  111. return msgids
  112. @api.multi
  113. def fetch_msg(self, connection, msgid):
  114. """Select a single message from a folder."""
  115. self.ensure_one()
  116. server = self.server_id
  117. result, msgdata = connection.fetch(msgid, '(RFC822)')
  118. if result != 'OK':
  119. raise UserError(_(
  120. "Could not fetch %s in %s on %s") %
  121. (msgid, self.path, server.server))
  122. message_org = msgdata[0][1] # rfc822 message source
  123. mail_message = self.env['mail.thread'].message_parse(
  124. message_org, save_original=server.original)
  125. return (mail_message, message_org)
  126. @api.multi
  127. def retrieve_imap_folder(self, connection):
  128. """Retrieve all mails for one IMAP folder."""
  129. self.ensure_one()
  130. msgids = self.get_msgids(connection, 'UNDELETED')
  131. match_algorithm = self.get_algorithm()
  132. for msgid in msgids[0].split():
  133. try:
  134. self.env.cr.execute('savepoint apply_matching')
  135. self.apply_matching(connection, msgid, match_algorithm)
  136. self.env.cr.execute('release savepoint apply_matching')
  137. except Exception:
  138. self.env.cr.execute('rollback to savepoint apply_matching')
  139. _logger.exception(
  140. "Failed to fetch mail %s from %s",
  141. msgid, self.server_id.name)
  142. @api.multi
  143. def update_msg(self, connection, msgid, matched=True, flagged=False):
  144. """Update msg in imap folder depending on match and settings."""
  145. if matched:
  146. if self.delete_matching:
  147. connection.store(msgid, '+FLAGS', '\\DELETED')
  148. elif flagged and self.flag_nonmatching:
  149. connection.store(msgid, '-FLAGS', '\\FLAGGED')
  150. else:
  151. if self.flag_nonmatching:
  152. connection.store(msgid, '+FLAGS', '\\FLAGGED')
  153. @api.multi
  154. def apply_matching(self, connection, msgid, match_algorithm):
  155. """Return ids of objects matched"""
  156. self.ensure_one()
  157. mail_message, message_org = self.fetch_msg(connection, msgid)
  158. if self.env['mail.message'].search(
  159. [('message_id', '=', mail_message['message_id'])]):
  160. # Ignore mails that have been handled already
  161. return
  162. matches = match_algorithm.search_matches(self, mail_message)
  163. matched = matches and (len(matches) == 1 or self.match_first)
  164. if matched:
  165. match_algorithm.handle_match(
  166. connection,
  167. matches[0], self, mail_message,
  168. message_org, msgid)
  169. self.update_msg(connection, msgid, matched=matched)
  170. @api.multi
  171. def attach_mail(self, match_object, mail_message):
  172. """Attach mail to match_object."""
  173. self.ensure_one()
  174. partner = False
  175. model_name = self.model_id.model
  176. if model_name == 'res.partner':
  177. partner = match_object
  178. elif 'partner_id' in self.env[model_name]._fields:
  179. partner = match_object.partner_id
  180. attachments = []
  181. if self.server_id.attach and mail_message.get('attachments'):
  182. for attachment in mail_message['attachments']:
  183. # Attachment should at least have filename and data, but
  184. # might have some extra element(s)
  185. if len(attachment) < 2:
  186. continue
  187. fname, fcontent = attachment[:2]
  188. if isinstance(fcontent, unicode):
  189. fcontent = fcontent.encode('utf-8')
  190. data_attach = {
  191. 'name': fname,
  192. 'datas': base64.b64encode(str(fcontent)),
  193. 'datas_fname': fname,
  194. 'description': _('Mail attachment'),
  195. 'res_model': model_name,
  196. 'res_id': match_object.id}
  197. attachments.append(
  198. self.env['ir.attachment'].create(data_attach))
  199. self.env['mail.message'].create({
  200. 'author_id': partner and partner.id or False,
  201. 'model': model_name,
  202. 'res_id': match_object.id,
  203. 'message_type': 'email',
  204. 'body': mail_message.get('body'),
  205. 'subject': mail_message.get('subject'),
  206. 'email_from': mail_message.get('from'),
  207. 'date': mail_message.get('date'),
  208. 'message_id': mail_message.get('message_id'),
  209. 'attachment_ids': [(6, 0, [a.id for a in attachments])]})