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.

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