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.

276 lines
11 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # This module copyright (C) 2013 Therp BV (<http://therp.nl>)
  6. # All Rights Reserved
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import logging
  23. import base64
  24. import simplejson
  25. from lxml import etree
  26. from openerp import models, fields, api, exceptions
  27. from openerp.tools.safe_eval import safe_eval
  28. from openerp.tools.translate import _
  29. from openerp.tools.misc import UnquoteEvalContext
  30. _logger = logging.getLogger(__name__)
  31. class fetchmail_server(models.Model):
  32. _inherit = 'fetchmail.server'
  33. folder_ids = fields.One2many(
  34. 'fetchmail.server.folder', 'server_id', 'Folders',
  35. context={'active_test': False})
  36. object_id = fields.Many2one(required=False)
  37. _defaults = {
  38. 'type': 'imap',
  39. }
  40. def onchange_server_type(
  41. self, cr, uid, ids, server_type=False, ssl=False,
  42. object_id=False):
  43. retval = super(
  44. fetchmail_server, self).onchange_server_type(cr, uid,
  45. ids, server_type, ssl,
  46. object_id)
  47. retval['value']['state'] = 'draft'
  48. return retval
  49. def fetch_mail(self, cr, uid, ids, context=None):
  50. if context is None:
  51. context = {}
  52. check_original = []
  53. for this in self.browse(cr, uid, ids, context):
  54. if this.object_id:
  55. check_original.append(this.id)
  56. context.update(
  57. {
  58. 'fetchmail_server_id': this.id,
  59. 'server_type': this.type
  60. })
  61. connection = this.connect()
  62. for folder in this.folder_ids.filtered('active'):
  63. this.with_context(safe_eval(folder.context or '{}'))\
  64. .handle_folder(connection, folder)
  65. connection.close()
  66. return super(fetchmail_server, self).fetch_mail(
  67. cr, uid, check_original, context)
  68. @api.multi
  69. def handle_folder(self, connection, folder):
  70. '''Return ids of objects matched'''
  71. matched_object_ids = []
  72. for this in self:
  73. _logger.info(
  74. 'start checking for emails in %s server %s',
  75. folder.path, this.name)
  76. match_algorithm = folder.get_algorithm()
  77. if connection.select(folder.path)[0] != 'OK':
  78. _logger.error(
  79. 'Could not open mailbox %s on %s',
  80. folder.path, this.server)
  81. connection.select()
  82. continue
  83. result, msgids = this.get_msgids(connection)
  84. if result != 'OK':
  85. _logger.error(
  86. 'Could not search mailbox %s on %s',
  87. folder.path, this.server)
  88. continue
  89. for msgid in msgids[0].split():
  90. matched_object_ids += this.apply_matching(
  91. connection, folder, msgid, match_algorithm)
  92. _logger.info(
  93. 'finished checking for emails in %s server %s',
  94. folder.path, this.name)
  95. return matched_object_ids
  96. @api.multi
  97. def get_msgids(self, connection):
  98. '''Return imap ids of messages to process'''
  99. return connection.search(None, 'UNDELETED')
  100. @api.multi
  101. def apply_matching(self, connection, folder, msgid, match_algorithm):
  102. '''Return ids of objects matched'''
  103. matched_object_ids = []
  104. for this in self:
  105. result, msgdata = connection.fetch(msgid, '(RFC822)')
  106. if result != 'OK':
  107. _logger.error(
  108. 'Could not fetch %s in %s on %s',
  109. msgid, folder.path, this.server)
  110. continue
  111. mail_message = self.env['mail.thread'].message_parse(
  112. msgdata[0][1], save_original=this.original)
  113. if self.env['mail.message'].search(
  114. [('message_id', '=', mail_message['message_id'])]):
  115. continue
  116. found_ids = match_algorithm.search_matches(
  117. self.env.cr, self.env.uid, folder, mail_message, msgdata[0][1])
  118. if found_ids and (len(found_ids) == 1 or
  119. folder.match_first):
  120. try:
  121. self.env.cr.execute('savepoint apply_matching')
  122. match_algorithm.handle_match(
  123. self.env.cr, self.env.uid, connection,
  124. found_ids[0], folder, mail_message,
  125. msgdata[0][1], msgid, self.env.context)
  126. self.env.cr.execute('release savepoint apply_matching')
  127. matched_object_ids += found_ids[:1]
  128. except Exception:
  129. self.env.cr.execute('rollback to savepoint apply_matching')
  130. _logger.exception(
  131. "Failed to fetch mail %s from %s", msgid, this.name)
  132. elif folder.flag_nonmatching:
  133. connection.store(msgid, '+FLAGS', '\\FLAGGED')
  134. return matched_object_ids
  135. @api.multi
  136. def attach_mail(self, connection, object_id, folder, mail_message, msgid):
  137. '''Return ids of messages created'''
  138. mail_message_ids = []
  139. for this in self:
  140. partner_id = None
  141. if folder.model_id.model == 'res.partner':
  142. partner_id = object_id
  143. if 'partner_id' in self.env[folder.model_id.model]._columns:
  144. partner_id = self.env[folder.model_id.model].browse(object_id)\
  145. .partner_id.id
  146. attachments = []
  147. if this.attach and mail_message.get('attachments'):
  148. for attachment in mail_message['attachments']:
  149. fname, fcontent = attachment
  150. if isinstance(fcontent, unicode):
  151. fcontent = fcontent.encode('utf-8')
  152. data_attach = {
  153. 'name': fname,
  154. 'datas': base64.b64encode(str(fcontent)),
  155. 'datas_fname': fname,
  156. 'description': _('Mail attachment'),
  157. 'res_model': folder.model_id.model,
  158. 'res_id': object_id,
  159. }
  160. attachments.append(
  161. self.env['ir.attachment'].create(data_attach))
  162. mail_message_ids.append(
  163. self.env['mail.message'].create({
  164. 'author_id': partner_id,
  165. 'model': folder.model_id.model,
  166. 'res_id': object_id,
  167. 'type': 'email',
  168. 'body': mail_message.get('body'),
  169. 'subject': mail_message.get('subject'),
  170. 'email_from': mail_message.get('from'),
  171. 'date': mail_message.get('date'),
  172. 'message_id': mail_message.get('message_id'),
  173. 'attachment_ids': [(6, 0, [a.id for a in attachments])],
  174. }))
  175. if folder.delete_matching:
  176. connection.store(msgid, '+FLAGS', '\\DELETED')
  177. return mail_message_ids
  178. def button_confirm_login(self, cr, uid, ids, context=None):
  179. retval = super(fetchmail_server, self).button_confirm_login(
  180. cr, uid, ids, context)
  181. for this in self.browse(cr, uid, ids, context):
  182. this.write({'state': 'draft'})
  183. connection = this.connect()
  184. connection.select()
  185. for folder in this.folder_ids.filtered('active'):
  186. try:
  187. folder_context = safe_eval(folder.context or '{}')
  188. except Exception, e:
  189. raise exceptions.ValidationError(
  190. _('Invalid context "%s": %s') % (folder.context, e))
  191. if not isinstance(folder_context, dict):
  192. raise exceptions.ValidationError(
  193. _('Context "%s" is not a dictionary.') %
  194. folder.context)
  195. if connection.select(folder.path)[0] != 'OK':
  196. raise exceptions.ValidationError(
  197. _('Mailbox %s not found!') % folder.path)
  198. connection.close()
  199. this.write({'state': 'done'})
  200. return retval
  201. def fields_view_get(self, cr, user, view_id=None, view_type='form',
  202. context=None, toolbar=False, submenu=False):
  203. result = super(fetchmail_server, self).fields_view_get(
  204. cr, user, view_id, view_type, context, toolbar, submenu)
  205. if view_type == 'form':
  206. view = etree.fromstring(
  207. result['fields']['folder_ids']['views']['form']['arch'])
  208. modifiers = {}
  209. docstr = ''
  210. for algorithm in self.pool['fetchmail.server.folder']\
  211. ._get_match_algorithms().itervalues():
  212. for modifier in ['required', 'readonly']:
  213. for field in getattr(algorithm, modifier + '_fields'):
  214. modifiers.setdefault(field, {})
  215. modifiers[field].setdefault(modifier, [])
  216. if modifiers[field][modifier]:
  217. modifiers[field][modifier].insert(0, '|')
  218. modifiers[field][modifier].append(
  219. ("match_algorithm", "==", algorithm.__name__))
  220. docstr += _(algorithm.name) + '\n' + _(algorithm.__doc__) + \
  221. '\n\n'
  222. for field in view.xpath('//field'):
  223. if field.tag == 'field' and field.get('name') in modifiers:
  224. field.set('modifiers', simplejson.dumps(
  225. dict(
  226. eval(field.attrib['modifiers'],
  227. UnquoteEvalContext({})),
  228. **modifiers[field.attrib['name']])))
  229. if (field.tag == 'field' and
  230. field.get('name') == 'match_algorithm'):
  231. field.set('help', docstr)
  232. result['fields']['folder_ids']['views']['form']['arch'] = \
  233. etree.tostring(view)
  234. return result