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.

266 lines
10 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.translate import _
  28. from openerp.tools.safe_eval import safe_eval
  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.handle_folder(connection, folder)
  64. connection.close()
  65. return super(fetchmail_server, self).fetch_mail(
  66. cr, uid, check_original, context)
  67. @api.multi
  68. def handle_folder(self, connection, folder):
  69. '''Return ids of objects matched'''
  70. matched_object_ids = []
  71. for this in self:
  72. _logger.info(
  73. 'start checking for emails in %s server %s',
  74. folder.path, this.name)
  75. match_algorithm = folder.get_algorithm()
  76. if connection.select(folder.path)[0] != 'OK':
  77. _logger.error(
  78. 'Could not open mailbox %s on %s',
  79. folder.path, this.server)
  80. connection.select()
  81. continue
  82. result, msgids = this.get_msgids(connection)
  83. if result != 'OK':
  84. _logger.error(
  85. 'Could not search mailbox %s on %s',
  86. folder.path, this.server)
  87. continue
  88. for msgid in msgids[0].split():
  89. matched_object_ids += this.apply_matching(
  90. connection, folder, msgid, match_algorithm)
  91. _logger.info(
  92. 'finished checking for emails in %s server %s',
  93. folder.path, this.name)
  94. return matched_object_ids
  95. @api.multi
  96. def get_msgids(self, connection):
  97. '''Return imap ids of messages to process'''
  98. return connection.search(None, 'UNDELETED')
  99. @api.multi
  100. def apply_matching(self, connection, folder, msgid, match_algorithm):
  101. '''Return ids of objects matched'''
  102. matched_object_ids = []
  103. for this in self:
  104. result, msgdata = connection.fetch(msgid, '(RFC822)')
  105. if result != 'OK':
  106. _logger.error(
  107. 'Could not fetch %s in %s on %s',
  108. msgid, folder.path, this.server)
  109. continue
  110. mail_message = self.env['mail.thread'].message_parse(
  111. msgdata[0][1], save_original=this.original)
  112. if self.env['mail.message'].search(
  113. [('message_id', '=', mail_message['message_id'])]):
  114. continue
  115. found_ids = match_algorithm.search_matches(
  116. self.env.cr, self.env.uid, folder, mail_message, msgdata[0][1])
  117. if found_ids and (len(found_ids) == 1 or
  118. folder.match_first):
  119. try:
  120. self.env.cr.execute('savepoint apply_matching')
  121. match_algorithm.handle_match(
  122. self.env.cr, self.env.uid, connection,
  123. found_ids[0], folder, mail_message,
  124. msgdata[0][1], msgid, self.env.context)
  125. self.env.cr.execute('release savepoint apply_matching')
  126. matched_object_ids += found_ids[:1]
  127. except Exception:
  128. self.env.cr.execute('rollback to savepoint apply_matching')
  129. _logger.exception(
  130. "Failed to fetch mail %s from %s", msgid, this.name)
  131. elif folder.flag_nonmatching:
  132. connection.store(msgid, '+FLAGS', '\\FLAGGED')
  133. return matched_object_ids
  134. @api.multi
  135. def attach_mail(self, connection, object_id, folder, mail_message, msgid):
  136. '''Return ids of messages created'''
  137. mail_message_ids = []
  138. for this in self:
  139. partner_id = None
  140. if folder.model_id.model == 'res.partner':
  141. partner_id = object_id
  142. if 'partner_id' in self.env[folder.model_id.model]._columns:
  143. partner_id = self.env[folder.model_id.model].browse(object_id)\
  144. .partner_id.id
  145. attachments = []
  146. if this.attach and mail_message.get('attachments'):
  147. for attachment in mail_message['attachments']:
  148. fname, fcontent = attachment
  149. if isinstance(fcontent, unicode):
  150. fcontent = fcontent.encode('utf-8')
  151. data_attach = {
  152. 'name': fname,
  153. 'datas': base64.b64encode(str(fcontent)),
  154. 'datas_fname': fname,
  155. 'description': _('Mail attachment'),
  156. 'res_model': folder.model_id.model,
  157. 'res_id': object_id,
  158. }
  159. attachments.append(
  160. self.env['ir.attachment'].create(data_attach))
  161. mail_message_ids.append(
  162. self.env['mail.message'].create({
  163. 'author_id': partner_id,
  164. 'model': folder.model_id.model,
  165. 'res_id': object_id,
  166. 'type': 'email',
  167. 'body': mail_message.get('body'),
  168. 'subject': mail_message.get('subject'),
  169. 'email_from': mail_message.get('from'),
  170. 'date': mail_message.get('date'),
  171. 'message_id': mail_message.get('message_id'),
  172. 'attachment_ids': [(6, 0, [a.id for a in attachments])],
  173. }))
  174. if folder.delete_matching:
  175. connection.store(msgid, '+FLAGS', '\\DELETED')
  176. return mail_message_ids
  177. def button_confirm_login(self, cr, uid, ids, context=None):
  178. retval = super(fetchmail_server, self).button_confirm_login(
  179. cr, uid, ids, context)
  180. for this in self.browse(cr, uid, ids, context):
  181. this.write({'state': 'draft'})
  182. connection = this.connect()
  183. connection.select()
  184. for folder in this.folder_ids.filtered('active'):
  185. if connection.select(folder.path)[0] != 'OK':
  186. raise exceptions.ValidationError(
  187. _('Mailbox %s not found!') % folder.path)
  188. connection.close()
  189. this.write({'state': 'done'})
  190. return retval
  191. def fields_view_get(self, cr, user, view_id=None, view_type='form',
  192. context=None, toolbar=False, submenu=False):
  193. result = super(fetchmail_server, self).fields_view_get(
  194. cr, user, view_id, view_type, context, toolbar, submenu)
  195. if view_type == 'form':
  196. view = etree.fromstring(
  197. result['fields']['folder_ids']['views']['form']['arch'])
  198. modifiers = {}
  199. docstr = ''
  200. for algorithm in self.pool['fetchmail.server.folder']\
  201. ._get_match_algorithms().itervalues():
  202. for modifier in ['required', 'readonly']:
  203. for field in getattr(algorithm, modifier + '_fields'):
  204. modifiers.setdefault(field, {})
  205. modifiers[field].setdefault(modifier, [])
  206. if modifiers[field][modifier]:
  207. modifiers[field][modifier].insert(0, '|')
  208. modifiers[field][modifier].append(
  209. ("match_algorithm", "==", algorithm.__name__))
  210. docstr += _(algorithm.name) + '\n' + _(algorithm.__doc__) + \
  211. '\n\n'
  212. for field in view.xpath('//field'):
  213. if field.tag == 'field' and field.get('name') in modifiers:
  214. field.set('modifiers', simplejson.dumps(
  215. dict(
  216. safe_eval(field.attrib['modifiers'],
  217. UnquoteEvalContext({})),
  218. **modifiers[field.attrib['name']])))
  219. if (field.tag == 'field' and
  220. field.get('name') == 'match_algorithm'):
  221. field.set('help', docstr)
  222. result['fields']['folder_ids']['views']['form']['arch'] = \
  223. etree.tostring(view)
  224. return result