[FIX] mail_gateway: set partner_id in mail history if not
[odoo/odoo.git] / addons / mail_gateway / mail_gateway.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 from osv import osv, fields
23 import time
24 import tools
25 import binascii
26 import email
27 from email.header import decode_header
28 import base64
29 import re
30 from tools.translate import _
31 import logging
32 import xmlrpclib
33
34 _logger = logging.getLogger('mailgate')
35
36 class mailgate_thread(osv.osv):
37     '''
38     Mailgateway Thread
39     '''
40     _name = 'mailgate.thread'
41     _description = 'Mailgateway Thread'
42
43     _columns = {
44         'message_ids': fields.one2many('mailgate.message', 'res_id', 'Messages', readonly=True),
45     }
46
47     def copy(self, cr, uid, id, default=None, context=None):
48         """
49         Overrides orm copy method.
50         @param self: the object pointer
51         @param cr: the current row, from the database cursor,
52         @param uid: the current user’s ID for security checks,
53         @param id: Id of mailgate thread
54         @param default: Dictionary of default values for copy.
55         @param context: A standard dictionary for contextual values
56         """
57         if context is None:
58             context = {}
59         if default is None:
60             default = {}
61
62         default.update({
63             'message_ids': [],
64             'date_closed': False,
65             'date_open': False
66         })
67         return super(mailgate_thread, self).copy(cr, uid, id, default, context=context)
68
69     def message_new(self, cr, uid, msg, context):
70         raise Exception, _('Method is not implemented')
71
72     def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context={}):
73         raise Exception, _('Method is not implemented')
74
75     def message_followers(self, cr, uid, ids, context=None):
76         """ Get a list of emails of the people following this thread
77         """
78         res = {}
79         if isinstance(ids, (str, int, long)):
80             ids = [long(ids)]
81         for thread in self.browse(cr, uid, ids, context=context):
82             l=[]
83             for message in thread.message_ids:
84                 l.append((message.user_id and message.user_id.email) or '')
85                 l.append(message.email_from or '')
86                 l.append(message.email_cc or '')
87             res[thread.id] = l
88         return res
89
90     def msg_send(self, cr, uid, id, *args, **argv):
91         raise Exception, _('Method is not implemented')
92
93     def history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \
94                     email_from=False, message_id=False, references=None, attach=None, email_cc=None, \
95                     email_bcc=None, email_date=None, context=None):
96         """
97         @param self: The object pointer
98         @param cr: the current row, from the database cursor,
99         @param uid: the current user’s ID for security checks,
100         @param cases: a browse record list
101         @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used
102         @param history: Value True/False, If True it makes entry in case History otherwise in Case Log
103         @param email: Email-To / Recipient address
104         @param email_from: Email From / Sender address if any
105         @param email_cc: Comma-Separated list of Carbon Copy Emails To addresse if any
106         @param email_bcc: Comma-Separated list of Blind Carbon Copy Emails To addresses if any
107         @param email_date: Email Date string if different from now, in server Timezone
108         @param details: Description, Details of case history if any
109         @param atach: Attachment sent in email
110         @param context: A standard dictionary for contextual values"""
111         if context is None:
112             context = {}
113         if attach is None:
114             attach = []
115
116         # The mailgate sends the ids of the cases and not the object list
117
118         if all(isinstance(case_id, (int, long)) for case_id in cases):
119             cases = self.browse(cr, uid, cases, context=context)
120
121         att_obj = self.pool.get('ir.attachment')
122         obj = self.pool.get('mailgate.message')
123
124         for case in cases:
125             partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
126             if not partner_id and case._name == 'res.partner':
127                 partner_id = case.id
128             data = {
129                 'name': keyword,
130                 'user_id': uid,
131                 'model' : case._name,
132                 'partner_id': partner_id,
133                 'res_id': case.id,
134                 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
135                 'message_id': message_id,
136             }
137             attachments = []
138             if history:
139                 for att in attach:
140                     attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
141
142                 for param in (email, email_cc, email_bcc):
143                     if isinstance(param, list):
144                         param = ", ".join(param)
145
146                 data = {
147                     'name': subject or _('History'),
148                     'history': True,
149                     'user_id': uid,
150                     'model' : case._name,
151                     'res_id': case.id,
152                     'date': email_date or time.strftime('%Y-%m-%d %H:%M:%S'),
153                     'description': details or (hasattr(case, 'description') and case.description or False),
154                     'email_to': email,
155                     'email_from': email_from or \
156                         (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
157                          case.user_id.address_id.email),
158                     'email_cc': email_cc,
159                     'email_bcc': email_bcc,
160                     'partner_id': partner_id,
161                     'references': references,
162                     'message_id': message_id,
163                     'attachment_ids': [(6, 0, attachments)]
164                 }
165             obj.create(cr, uid, data, context=context)
166         return True
167 mailgate_thread()
168
169 def format_date_tz(date, tz=None):
170     if not date:
171         return 'n/a'
172     format = tools.DEFAULT_SERVER_DATETIME_FORMAT
173     return tools.server_to_local_timestamp(date, format, format, tz)
174
175 class mailgate_message(osv.osv):
176     '''
177     Mailgateway Message
178     '''
179     def _get_display_text(self, cr, uid, ids, name, arg, context=None):
180         if context is None:
181             context = {}
182         tz = context.get('tz')
183         result = {}
184         for message in self.browse(cr, uid, ids, context=context):
185             msg_txt = ''
186             if message.history:
187                 msg_txt += (message.email_from or '/') + _(' wrote on ') + format_date_tz(message.date, tz) + ':\n\t'
188                 if message.description:
189                     msg_txt += '\n\t'.join(message.description.split('\n')[:3]) + '...'
190             else:
191                 msg_txt = (message.user_id.name or '/') + _('  on ') + format_date_tz(message.date, tz) + ':\n\t'
192                 if message.name == _('Opportunity'):
193                     msg_txt += _("Converted to Opportunity")
194                 else:
195                     msg_txt += _("Changed Status to: ") + message.name
196             result[message.id] = msg_txt
197         return result
198
199     _name = 'mailgate.message'
200     _description = 'Mailgateway Message'
201     _order = 'date desc'
202     _columns = {
203         'name':fields.text('Subject', readonly=True),
204         'model': fields.char('Object Name', size=128, select=1, readonly=True),
205         'res_id': fields.integer('Resource ID', select=1, readonly=True),
206         'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
207         'date': fields.datetime('Date', readonly=True),
208         'history': fields.boolean('Is History?', readonly=True),
209         'user_id': fields.many2one('res.users', 'User Responsible', readonly=True),
210         'message': fields.text('Description', readonly=True),
211         'email_from': fields.char('From', size=128, help="Email From", readonly=True),
212         'email_to': fields.char('To', help="Email Recipients", size=256, readonly=True),
213         'email_cc': fields.char('Cc', help="Carbon Copy Email Recipients", size=256, readonly=True),
214         'email_bcc': fields.char('Bcc', help='Blind Carbon Copy Email Recipients', size=256, readonly=True),
215         'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
216         'references': fields.text('References', readonly=True, help="References emails."),
217         'description': fields.text('Description', readonly=True),
218         'partner_id': fields.many2one('res.partner', 'Partner', required=False),
219         'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments', readonly=True),
220         'display_text': fields.function(_get_display_text, method=True, type='text', size="512", string='Display Text'),
221     }
222
223     def init(self, cr):
224         cr.execute("""SELECT indexname
225                       FROM pg_indexes
226                       WHERE indexname = 'mailgate_message_res_id_model_idx'""")
227         if not cr.fetchone():
228             cr.execute("""CREATE INDEX mailgate_message_res_id_model_idx
229                           ON mailgate_message (model, res_id)""")
230
231 mailgate_message()
232
233 class mailgate_tool(osv.osv_memory):
234
235     _name = 'email.server.tools'
236     _description = "Email Server Tools"
237
238     def _decode_header(self, text):
239         """Returns unicode() string conversion of the the given encoded smtp header"""
240         if text:
241             text = decode_header(text.replace('\r', ''))
242             return ''.join([tools.ustr(x[0], x[1]) for x in text])
243
244     def to_email(self,text):
245         return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
246
247     def history(self, cr, uid, model, res_ids, msg, attach, context=None):
248         """This function creates history for mails fetched
249         @param self: The object pointer
250         @param cr: the current row, from the database cursor,
251         @param uid: the current user’s ID for security checks,
252         @param model: OpenObject Model
253         @param res_ids: Ids of the record of OpenObject model created
254         @param msg: Email details
255         @param attach: Email attachments
256         """
257         if isinstance(res_ids, (int, long)):
258             res_ids = [res_ids]
259
260         msg_pool = self.pool.get('mailgate.message')
261         for res_id in res_ids:
262             case = self.pool.get(model).browse(cr, uid, res_id, context=context)
263             partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
264             if not partner_id and model == 'res.partner':
265                 partner_id = res_id
266             msg_data = {
267                 'name': msg.get('subject', 'No subject'),
268                 'date': msg.get('date'),
269                 'description': msg.get('body', msg.get('from')),
270                 'history': True,
271                 'partner_id': partner_id,
272                 'res_model': model,
273                 'email_cc': msg.get('cc'),
274                 'email_from': msg.get('from'),
275                 'email_to': msg.get('to'),
276                 'message_id': msg.get('message-id'),
277                 'references': msg.get('references') or msg.get('in-reply-to'),
278                 'res_id': res_id,
279                 'user_id': uid,
280                 'attachment_ids': [(6, 0, attach)]
281             }
282             msg_pool.create(cr, uid, msg_data, context=context)
283         return True
284
285     def email_forward(self, cr, uid, model, res_ids, msg, email_error=False, context=None):
286         """Sends an email to all people following the thread
287         @param res_id: Id of the record of OpenObject model created from the email message
288         @param msg: email.message.Message to forward
289         @param email_error: Default Email address in case of any Problem
290         """
291         model_pool = self.pool.get(model)
292
293         for res in model_pool.browse(cr, uid, res_ids, context=context):
294             message_followers = model_pool.message_followers(cr, uid, [res.id])[res.id]
295             message_followers_emails = self.to_email(','.join(filter(None, message_followers)))
296             message_recipients = self.to_email(','.join(filter(None,
297                                                          [self._decode_header(msg['from']),
298                                                          self._decode_header(msg['to']),
299                                                          self._decode_header(msg['cc'])])))
300             message_forward = [i for i in message_followers_emails if (i and (i not in message_recipients))]
301
302             if message_forward:
303                 # TODO: we need an interface for this for all types of objects, not just leads
304                 if hasattr(res, 'section_id'):
305                     del msg['reply-to']
306                     msg['reply-to'] = res.section_id.reply_to
307
308                 smtp_from = self.to_email(msg['from'])
309                 if not tools.misc._email_send(smtp_from, message_forward, msg, openobject_id=res.id) and email_error:
310                     subj = msg['subject']
311                     del msg['subject'], msg['to'], msg['cc'], msg['bcc']
312                     msg['subject'] = '[OpenERP-Forward-Failed] %s' % subj
313                     msg['to'] = email_error
314                     tools.misc._email_send(smtp_from, self.to_email(email_error), msg, openobject_id=res.id)
315
316     def process_email(self, cr, uid, model, message, attach=True, context=None):
317         """This function Processes email and create record for given OpenERP model
318         @param self: The object pointer
319         @param cr: the current row, from the database cursor,
320         @param uid: the current user’s ID for security checks,
321         @param model: OpenObject Model
322         @param message: Email details, passed as a string or an xmlrpclib.Binary
323         @param attach: Email attachments
324         @param context: A standard dictionary for contextual values"""
325
326         # extract message bytes, we are forced to pass the message as binary because
327         # we don't know its encoding until we parse its headers and hence can't
328         # convert it to utf-8 for transport between the mailgate script and here.
329         if isinstance(message, xmlrpclib.Binary):
330             message = str(message.data)
331
332         if not context:
333             context = {}
334
335         model_pool = self.pool.get(model)
336         res_id = False
337
338         # Create New Record into particular model
339         def create_record(msg):
340             att_ids = []
341             if hasattr(model_pool, 'message_new'):
342                 res_id = model_pool.message_new(cr, uid, msg, context)
343             else:
344                 data = {
345                     'name': msg.get('subject'),
346                     'email_from': msg.get('from'),
347                     'email_cc': msg.get('cc'),
348                     'user_id': False,
349                     'description': msg.get('body'),
350                     'state' : 'draft',
351                 }
352                 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
353                 res_id = model_pool.create(cr, uid, data, context=context)
354
355                 if attach:
356                     for attachment in msg.get('attachments', []):
357                         data_attach = {
358                             'name': attachment,
359                             'datas': binascii.b2a_base64(str(attachments.get(attachment))),
360                             'datas_fname': attachment,
361                             'description': 'Mail attachment',
362                             'res_model': model,
363                             'res_id': res_id,
364                         }
365                         att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
366
367             return res_id, att_ids
368
369         # Warning: message_from_string doesn't always work correctly on unicode,
370         # we must use utf-8 strings here :-(
371         if isinstance(message, unicode):
372             message = message.encode('utf-8')
373         msg_txt = email.message_from_string(message)
374         message_id = msg_txt.get('message-id', False)
375         msg = {}
376
377         if not message_id:
378             # Very unusual situation, be we should be fault-tolerant here
379             message_id = time.time()
380             msg_txt['message-id'] = message_id
381             _logger.info('Message without message-id, generating a random one: %s', message_id)
382
383         fields = msg_txt.keys()
384         msg['id'] = message_id
385         msg['message-id'] = message_id
386
387         if 'Subject' in fields:
388             msg['subject'] = self._decode_header(msg_txt.get('Subject'))
389
390         if 'Content-Type' in fields:
391             msg['content-type'] = msg_txt.get('Content-Type')
392
393         if 'From' in fields:
394             msg['from'] = self._decode_header(msg_txt.get('From'))
395
396         if 'Delivered-To' in fields:
397             msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
398
399         if 'CC' in fields:
400             msg['cc'] = self._decode_header(msg_txt.get('CC'))
401
402         if 'Reply-to' in fields:
403             msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
404
405         if 'Date' in fields:
406             msg['date'] = self._decode_header(msg_txt.get('Date'))
407
408         if 'Content-Transfer-Encoding' in fields:
409             msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
410
411         if 'References' in fields:
412             msg['references'] = msg_txt.get('References')
413
414         if 'In-Reply-To' in fields:
415             msg['in-reply-to'] = msg_txt.get('In-Reply-To')
416
417         if 'X-Priority' in fields:
418             msg['priority'] = msg_txt.get('X-Priority', '3 (Normal)').split(' ')[0]
419
420         if not msg_txt.is_multipart() or 'text/plain' in msg.get('Content-Type', ''):
421             encoding = msg_txt.get_content_charset()
422             body = msg_txt.get_payload(decode=True)
423             msg['body'] = tools.ustr(body, encoding)
424
425         attachments = {}
426         has_plain_text = False
427         if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
428             body = ""
429             for part in msg_txt.walk():
430                 if part.get_content_maintype() == 'multipart':
431                     continue
432
433                 encoding = part.get_content_charset()
434                 filename = part.get_filename()
435                 if part.get_content_maintype()=='text':
436                     content = part.get_payload(decode=True)
437                     if filename:
438                         attachments[filename] = content
439                     elif not has_plain_text:
440                         # main content parts should have 'text' maintype
441                         # and no filename. we ignore the html part if
442                         # there is already a plaintext part without filename,
443                         # because presumably these are alternatives.
444                         content = tools.ustr(content, encoding)
445                         if part.get_content_subtype() == 'html':
446                             body = tools.ustr(tools.html2plaintext(content))
447                         elif part.get_content_subtype() == 'plain':
448                             body = content
449                             has_plain_text = True
450                 elif part.get_content_maintype() in ('application', 'image'):
451                     if filename :
452                         attachments[filename] = part.get_payload(decode=True)
453                     else:
454                         res = part.get_payload(decode=True)
455                         body += tools.ustr(res, encoding)
456
457             msg['body'] = body
458             msg['attachments'] = attachments
459         res_ids = []
460         attachment_ids = []
461         new_res_id = False
462         if msg.get('references') or msg.get('in-reply-to'):
463             references = msg.get('references') or msg.get('in-reply-to')
464             if '\r\n' in references:
465                 references = references.split('\r\n')
466             else:
467                 references = references.split(' ')
468             for ref in references:
469                 ref = ref.strip()
470                 res_id = tools.misc.reference_re.search(ref)
471                 if res_id:
472                     res_id = res_id.group(1)
473                 else:
474                     res_id = tools.misc.res_re.search(msg['subject'])
475                     if res_id:
476                         res_id = res_id.group(1)
477                 if res_id:
478                     res_id = int(res_id)
479                     model_pool = self.pool.get(model)
480                     if model_pool.exists(cr, uid, res_id):
481                         res_ids.append(res_id)
482                         if hasattr(model_pool, 'message_update'):
483                             model_pool.message_update(cr, uid, [res_id], {}, msg, context=context)
484                         else:
485                             raise NotImplementedError('model %s does not support updating records, mailgate API method message_update() is missing'%model)
486
487         if not len(res_ids):
488             new_res_id, attachment_ids = create_record(msg)
489             res_ids = [new_res_id]
490
491         # Store messages
492         context.update({'model' : model})
493         if hasattr(model_pool, 'history'):
494             model_pool.history(cr, uid, res_ids, _('receive'), history=True,
495                             subject = msg.get('subject'),
496                             email = msg.get('to'),
497                             details = msg.get('body'),
498                             email_from = msg.get('from'),
499                             email_cc = msg.get('cc'),
500                             message_id = msg.get('message-id'),
501                             references = msg.get('references', False) or msg.get('in-reply-to', False),
502                             attach = attachments.items(),
503                             context = context)
504         else:
505             self.history(cr, uid, model, res_ids, msg, attachment_ids, context=context)
506         self.email_forward(cr, uid, model, res_ids, msg_txt)
507         return new_res_id
508
509     def get_partner(self, cr, uid, from_email, context=None):
510         """This function returns partner Id based on email passed
511         @param self: The object pointer
512         @param cr: the current row, from the database cursor,
513         @param uid: the current user’s ID for security checks
514         @param from_email: email address based on that function will search for the correct
515         """
516         address_pool = self.pool.get('res.partner.address')
517         res = {
518             'partner_address_id': False,
519             'partner_id': False
520         }
521         from_email = self.to_email(from_email)[0]
522         address_ids = address_pool.search(cr, uid, [('email', 'like', from_email)])
523         if address_ids:
524             address = address_pool.browse(cr, uid, address_ids[0])
525             res['partner_address_id'] = address_ids[0]
526             res['partner_id'] = address.partner_id.id
527
528         return res
529
530 mailgate_tool()