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.

291 lines
12 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 base64
  23. import simplejson
  24. from lxml import etree
  25. from openerp.osv.orm import Model, except_orm
  26. from openerp.tools.translate import _
  27. from openerp.osv import fields
  28. from openerp.addons.fetchmail.fetchmail import logger
  29. from openerp.tools.misc import UnquoteEvalContext
  30. class fetchmail_server(Model):
  31. _inherit = 'fetchmail.server'
  32. _columns = {
  33. 'folder_ids': fields.one2many(
  34. 'fetchmail.server.folder', 'server_id', 'Folders'),
  35. }
  36. _defaults = {
  37. 'type': 'imap',
  38. }
  39. def __init__(self, pool, cr):
  40. self._columns['object_id'].required = False
  41. super(fetchmail_server, self).__init__(pool, cr)
  42. def onchange_server_type(
  43. self, cr, uid, ids, server_type=False, ssl=False,
  44. object_id=False):
  45. retval = super(
  46. fetchmail_server, self).onchange_server_type(cr, uid,
  47. ids, server_type, ssl,
  48. object_id)
  49. retval['value']['state'] = 'draft'
  50. return retval
  51. def fetch_mail(self, cr, uid, ids, context=None):
  52. if context is None:
  53. context = {}
  54. check_original = []
  55. for this in self.browse(cr, uid, ids, context):
  56. if this.object_id:
  57. check_original.append(this.id)
  58. context.update(
  59. {
  60. 'fetchmail_server_id': this.id,
  61. 'server_type': this.type
  62. })
  63. connection = this.connect()
  64. for folder in this.folder_ids:
  65. this.handle_folder(connection, folder)
  66. connection.close()
  67. return super(fetchmail_server, self).fetch_mail(
  68. cr, uid, check_original, context)
  69. def handle_folder(self, cr, uid, ids, connection, folder, context=None):
  70. '''Return ids of objects matched'''
  71. matched_object_ids = []
  72. for this in self.browse(cr, uid, ids, context=context):
  73. logger.info('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. def get_msgids(self, cr, uid, ids, connection, context=None):
  96. '''Return imap ids of messages to process'''
  97. return connection.search(None, 'UNDELETED')
  98. def apply_matching(self, cr, uid, ids, connection, folder, msgid,
  99. match_algorithm, context=None):
  100. '''Return ids of objects matched'''
  101. matched_object_ids = []
  102. for this in self.browse(cr, uid, ids, context=context):
  103. result, msgdata = connection.fetch(msgid, '(RFC822)')
  104. if result != 'OK':
  105. logger.error(
  106. 'Could not fetch %s in %s on %s',
  107. msgid, folder.path, this.server)
  108. continue
  109. mail_message = self.pool.get('mail.message').parse_message(
  110. msgdata[0][1], this.original)
  111. if self.pool.get('mail.message').search(
  112. cr, uid,
  113. [('message_id', '=', mail_message['message-id'])]):
  114. continue
  115. found_ids = match_algorithm.search_matches(
  116. cr, uid, folder,
  117. mail_message, msgdata[0][1])
  118. if found_ids and (len(found_ids) == 1 or
  119. folder.match_first):
  120. try:
  121. cr.execute('savepoint apply_matching')
  122. # OpenERP 6.1 does a rollback on validation errors
  123. rollback_org = cr.rollback
  124. cr.rollback = lambda: None
  125. match_algorithm.handle_match(
  126. cr, uid, connection,
  127. found_ids[0], folder, mail_message,
  128. msgdata[0][1], msgid, context)
  129. cr.rollback = rollback_org
  130. cr.execute('release savepoint apply_matching')
  131. matched_object_ids += found_ids[:1]
  132. except Exception:
  133. logger.exception(
  134. "Failed to fetch mail %s from %s",
  135. msgid, this.name)
  136. cr.rollback = rollback_org
  137. cr.execute('rollback to savepoint apply_matching')
  138. elif folder.flag_nonmatching:
  139. connection.store(msgid, '+FLAGS', '\\FLAGGED')
  140. return matched_object_ids
  141. def attach_mail(
  142. self, cr, uid, ids, connection, object_id, folder,
  143. mail_message, msgid, context=None):
  144. '''Return ids of messages created'''
  145. mail_message_ids = []
  146. for this in self.browse(cr, uid, ids, context):
  147. partner_id = None
  148. if folder.model_id.model == 'res.partner':
  149. partner_id = object_id
  150. if 'partner_id' in self.pool.get(folder.model_id.model)._columns:
  151. partner_id = self.pool.get(
  152. folder.model_id.model).browse(
  153. cr, uid, object_id, context
  154. ).partner_id.id
  155. attachments = []
  156. if this.attach and mail_message.get('attachments'):
  157. for attachment in mail_message['attachments']:
  158. fname, fcontent = attachment
  159. if isinstance(fcontent, unicode):
  160. fcontent = fcontent.encode('utf-8')
  161. data_attach = {
  162. 'name': fname,
  163. 'datas': base64.b64encode(str(fcontent)),
  164. 'datas_fname': fname,
  165. 'description': _('Mail attachment'),
  166. 'res_model': folder.model_id.model,
  167. 'res_id': object_id,
  168. }
  169. attachments.append(
  170. self.pool.get('ir.attachment').create(
  171. cr, uid, data_attach, context=context))
  172. mail_message_ids.append(
  173. self.pool.get('mail.message').create(
  174. cr, uid,
  175. {
  176. 'partner_id': partner_id,
  177. 'model': folder.model_id.model,
  178. 'res_id': object_id,
  179. 'body_text': mail_message.get('body'),
  180. 'body_html': mail_message.get('body_html'),
  181. 'subject': mail_message.get('subject') or '',
  182. 'email_to': mail_message.get('to'),
  183. 'email_from': mail_message.get('from'),
  184. 'email_cc': mail_message.get('cc'),
  185. 'reply_to': mail_message.get('reply'),
  186. 'date': mail_message.get('date'),
  187. 'message_id': mail_message.get('message-id'),
  188. 'subtype': mail_message.get('subtype'),
  189. 'headers': mail_message.get('headers'),
  190. 'state': folder.msg_state,
  191. 'attachment_ids': [(6, 0, attachments)],
  192. },
  193. context))
  194. if folder.delete_matching:
  195. connection.store(msgid, '+FLAGS', '\\DELETED')
  196. return mail_message_ids
  197. def button_confirm_login(self, cr, uid, ids, context=None):
  198. retval = super(fetchmail_server, self).button_confirm_login(cr, uid,
  199. ids,
  200. context)
  201. for this in self.browse(cr, uid, ids, context):
  202. this.write({'state': 'draft'})
  203. connection = this.connect()
  204. connection.select()
  205. for folder in this.folder_ids:
  206. if connection.select(folder.path)[0] != 'OK':
  207. raise except_orm(
  208. _('Error'), _('Mailbox %s not found!') %
  209. folder.path)
  210. connection.close()
  211. this.write({'state': 'done'})
  212. return retval
  213. def fields_view_get(self, cr, user, view_id=None, view_type='form',
  214. context=None, toolbar=False, submenu=False):
  215. result = super(fetchmail_server, self).fields_view_get(
  216. cr, user, view_id, view_type, context, toolbar, submenu)
  217. if view_type == 'form':
  218. view = etree.fromstring(
  219. result['fields']['folder_ids']['views']['form']['arch'])
  220. modifiers = {}
  221. docstr = ''
  222. for algorithm in self.pool.get('fetchmail.server.folder')\
  223. ._get_match_algorithms().itervalues():
  224. for modifier in ['required', 'readonly']:
  225. for field in getattr(algorithm, modifier + '_fields'):
  226. modifiers.setdefault(field, {})
  227. modifiers[field].setdefault(modifier, [])
  228. if modifiers[field][modifier]:
  229. modifiers[field][modifier].insert(0, '|')
  230. modifiers[field][modifier].append(
  231. ("match_algorithm", "==", algorithm.__name__))
  232. docstr += _(algorithm.name) + '\n' + _(algorithm.__doc__) + \
  233. '\n\n'
  234. for field in view:
  235. if field.tag == 'field' and field.get('name') in modifiers:
  236. field.set('modifiers', simplejson.dumps(
  237. dict(
  238. eval(field.attrib['modifiers'],
  239. UnquoteEvalContext({})),
  240. **modifiers[field.attrib['name']])))
  241. if (field.tag == 'field' and
  242. field.get('name') == 'match_algorithm'):
  243. field.set('help', docstr)
  244. result['fields']['folder_ids']['views']['form']['arch'] = \
  245. etree.tostring(view)
  246. return result