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.

248 lines
9.9 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 simplejson
  23. from lxml import etree
  24. from openerp.osv.orm import Model, except_orm, browse_null
  25. from openerp.tools.translate import _
  26. from openerp.osv import fields
  27. from openerp.addons.fetchmail.fetchmail import logger
  28. from openerp.tools.misc import UnquoteEvalContext
  29. from openerp.tools.safe_eval import safe_eval
  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. return 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. for this in self.browse(cr, uid, ids, context=context):
  71. logger.info('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. this.apply_matching(connection, folder, msgid, match_algorithm)
  88. logger.info('finished checking for emails in %s server %s',
  89. folder.path, this.name)
  90. def get_msgids(self, cr, uid, ids, connection, context=None):
  91. return connection.search(None, 'UNDELETED')
  92. def apply_matching(self, cr, uid, ids, connection, folder, msgid,
  93. match_algorithm, context=None):
  94. for this in self.browse(cr, uid, ids, context=context):
  95. result, msgdata = connection.fetch(msgid, '(RFC822)')
  96. if result != 'OK':
  97. logger.error(
  98. 'Could not fetch %s in %s on %s' % (
  99. msgid, folder.path, this.server))
  100. continue
  101. mail_message = self.pool.get('mail.message').parse_message(
  102. msgdata[0][1], this.original)
  103. if self.pool.get('mail.message').search(cr, uid, [
  104. ('message_id', '=', mail_message['message-id'])]):
  105. continue
  106. found_ids = match_algorithm.search_matches(
  107. cr, uid, folder,
  108. mail_message, msgdata[0][1])
  109. if found_ids and (len(found_ids) == 1 or
  110. folder.match_first):
  111. try:
  112. match_algorithm.handle_match(
  113. cr, uid, connection,
  114. found_ids[0], folder, mail_message,
  115. msgdata[0][1], msgid, context)
  116. cr.commit()
  117. except Exception, e:
  118. cr.rollback()
  119. logger.exception(
  120. "Failed to fetch mail %s from %s",
  121. msgid, this.name)
  122. elif folder.flag_nonmatching:
  123. connection.store(msgid, '+FLAGS', '\\FLAGGED')
  124. def attach_mail(
  125. self, cr, uid, ids, connection, object_id, folder,
  126. mail_message, msgid, context=None):
  127. for this in self.browse(cr, uid, ids, context):
  128. partner_id = None
  129. if folder.model_id.model == 'res.partner':
  130. partner_id = object_id
  131. if 'partner_id' in self.pool.get(folder.model_id.model)._columns:
  132. partner_id = self.pool.get(
  133. folder.model_id.model).browse(
  134. cr, uid, object_id, context
  135. ).partner_id.id
  136. self.pool.get('mail.message').create(
  137. cr, uid,
  138. {
  139. 'partner_id': partner_id,
  140. 'model': folder.model_id.model,
  141. 'res_id': object_id,
  142. 'body_text': mail_message.get('body'),
  143. 'body_html': mail_message.get('body_html'),
  144. 'subject': mail_message.get('subject'),
  145. 'email_to': mail_message.get('to'),
  146. 'email_from': mail_message.get('from'),
  147. 'email_cc': mail_message.get('cc'),
  148. 'reply_to': mail_message.get('reply'),
  149. 'date': mail_message.get('date'),
  150. 'message_id': mail_message.get('message-id'),
  151. 'subtype': mail_message.get('subtype'),
  152. 'headers': mail_message.get('headers'),
  153. 'state': folder.msg_state,
  154. },
  155. context)
  156. if this.attach:
  157. # TODO: create attachments
  158. pass
  159. if folder.delete_matching:
  160. connection.store(msgid, '+FLAGS', '\\DELETED')
  161. def button_confirm_login(self, cr, uid, ids, context=None):
  162. retval = super(fetchmail_server, self).button_confirm_login(cr, uid,
  163. ids,
  164. context)
  165. for this in self.browse(cr, uid, ids, context):
  166. this.write({'state': 'draft'})
  167. connection = this.connect()
  168. connection.select()
  169. for folder in this.folder_ids:
  170. if connection.select(folder.path)[0] != 'OK':
  171. raise except_orm(
  172. _('Error'), _('Mailbox %s not found!') %
  173. folder.path)
  174. folder.get_algorithm().search_matches(
  175. cr, uid, folder, browse_null(), '')
  176. connection.close()
  177. this.write({'state': 'done'})
  178. return retval
  179. def fields_view_get(self, cr, user, view_id=None, view_type='form',
  180. context=None, toolbar=False, submenu=False):
  181. result = super(fetchmail_server, self).fields_view_get(
  182. cr, user, view_id, view_type, context, toolbar, submenu)
  183. if view_type == 'form':
  184. view = etree.fromstring(
  185. result['fields']['folder_ids']['views']['form']['arch'])
  186. modifiers = {}
  187. docstr = ''
  188. for algorithm in self.pool.get('fetchmail.server.folder')\
  189. ._get_match_algorithms().itervalues():
  190. for modifier in ['required', 'readonly']:
  191. for field in getattr(algorithm, modifier + '_fields'):
  192. modifiers.setdefault(field, {})
  193. modifiers[field].setdefault(modifier, [])
  194. if modifiers[field][modifier]:
  195. modifiers[field][modifier].insert(0, '|')
  196. modifiers[field][modifier].append(
  197. ("match_algorithm", "==", algorithm.__name__))
  198. docstr += _(algorithm.name) + '\n' + _(algorithm.__doc__) + \
  199. '\n\n'
  200. for field in view:
  201. if field.tag == 'field' and field.get('name') in modifiers:
  202. field.set('modifiers', simplejson.dumps(
  203. dict(
  204. eval(field.attrib['modifiers'],
  205. UnquoteEvalContext({})),
  206. **modifiers[field.attrib['name']])))
  207. if (field.tag == 'field' and
  208. field.get('name') == 'match_algorithm'):
  209. field.set('help', docstr)
  210. result['fields']['folder_ids']['views']['form']['arch'] = \
  211. etree.tostring(view)
  212. return result