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