[FIX] crm: State changes of all crm object shouldn't be in Email section of partner...
[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             attachments = []
126             for att in attach:
127                     attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
128
129             partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
130             if not partner_id and case._name == 'res.partner':
131                 partner_id = case.id
132             data = {
133                 'name': keyword,
134                 'user_id': uid,
135                 'model' : case._name,
136                 'partner_id': partner_id,
137                 'res_id': case.id,
138                 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
139                 'message_id': message_id,
140                 'description': details or (hasattr(case, 'description') and case.description or False),
141                 'attachment_ids': [(6, 0, attachments)]
142             }
143
144             if history:
145                 for param in (email, email_cc, email_bcc):
146                     if isinstance(param, list):
147                         param = ", ".join(param)
148
149                 data = {
150                     'name': subject or _('History'),
151                     'history': True,
152                     'user_id': uid,
153                     'model' : case._name,
154                     'res_id': case.id,
155                     'date': email_date or time.strftime('%Y-%m-%d %H:%M:%S'),
156                     'description': details or (hasattr(case, 'description') and case.description or False),
157                     'email_to': email,
158                     'email_from': email_from or \
159                         (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
160                          case.user_id.address_id.email),
161                     'email_cc': email_cc,
162                     'email_bcc': email_bcc,
163                     'partner_id': partner_id,
164                     'references': references,
165                     'message_id': message_id,
166                     'attachment_ids': [(6, 0, attachments)]
167                 }
168             obj.create(cr, uid, data, context=context)
169         return True
170 mailgate_thread()
171
172 def format_date_tz(date, tz=None):
173     if not date:
174         return 'n/a'
175     format = tools.DEFAULT_SERVER_DATETIME_FORMAT
176     return tools.server_to_local_timestamp(date, format, format, tz)
177
178 class mailgate_message(osv.osv):
179     '''
180     Mailgateway Message
181     '''
182     def open_document(self, cr, uid, ids, context):
183         """ To Open Document
184         @param self: The object pointer.
185         @param cr: A database cursor
186         @param uid: ID of the user currently logged in
187         @param ids: the ID of messages
188         @param context: A standard dictionary
189         """
190         action_data = False
191         if ids:
192             message_id = ids[0]
193             mailgate_data = self.browse(cr, uid, message_id)
194             model = mailgate_data.model
195             res_id = mailgate_data.res_id
196
197             action_pool = self.pool.get('ir.actions.act_window')
198             action_ids = action_pool.search(cr, uid, [('res_model', '=', model)])
199             if action_ids:
200                 action_data = action_pool.read(cr, uid, action_ids[0], context=context)
201                 action_data.update({
202                     'domain' : "[('id','=',%d)]"%(res_id),
203                     'nodestroy': True,
204                     'context': {}
205                     })
206         return action_data
207
208     def open_attachment(self, cr, uid, ids, context):
209         """ To Open attachments
210         @param self: The object pointer.
211         @param cr: A database cursor
212         @param uid: ID of the user currently logged in
213         @param ids: the ID of messages
214         @param context: A standard dictionary
215         """
216         action_data = False
217         action_pool = self.pool.get('ir.actions.act_window')
218         message_pool = self.browse(cr ,uid, ids)[0]
219         action_ids = action_pool.search(cr, uid, [('res_model', '=', 'ir.attachment')])
220         if action_ids:
221             action_data = action_pool.read(cr, uid, action_ids[0], context=context)
222             action_data.update({
223                 'domain': [('res_id','=',message_pool.res_id),('res_model','=',message_pool.model)],
224                 'nodestroy': True
225                 })
226         return action_data
227
228     def truncate_data(self, cr, uid, data, context=None):
229         data_list = data and data.split('\n') or []
230         if len(data_list) > 3:
231             res = '\n\t'.join(data_list[:3]) + '...'
232         else:
233             res = '\n\t'.join(data_list)
234         return res
235
236     def _get_display_text(self, cr, uid, ids, name, arg, context=None):
237         if context is None:
238             context = {}
239         tz = context.get('tz')
240         result = {}
241         for message in self.browse(cr, uid, ids, context=context):
242             msg_txt = ''
243             if message.history:
244                 msg_txt += (message.email_from or '/') + _(' wrote on ') + format_date_tz(message.date, tz) + ':\n\t'
245                 if message.description:
246                     msg_txt += self.truncate_data(cr, uid, message.description, context=context)
247             else:
248                 msg_txt = (message.user_id.name or '/') + _(' on ') + format_date_tz(message.date, tz) + ':\n\t'
249                 if message.name == _('Opportunity'):
250                     msg_txt += _("Converted to Opportunity")
251                 elif message.name == _('Note'):
252                     msg_txt = (message.user_id.name or '/') + _(' added note on ') + format_date_tz(message.date, tz) + ':\n\t'
253                     msg_txt += self.truncate_data(cr, uid, message.description, context=context)
254                 elif message.name == _('Stage'):
255                     msg_txt += _("Changed Stage to: ") + message.description
256                 else:
257                     msg_txt += _("Changed Status to: ") + message.name
258             result[message.id] = msg_txt
259         return result
260
261     _name = 'mailgate.message'
262     _description = 'Mailgateway Message'
263     _order = 'date desc'
264     _columns = {
265         'name':fields.text('Subject', readonly=True),
266         'model': fields.char('Object Name', size=128, select=1, readonly=True),
267         'res_id': fields.integer('Resource ID', select=1, readonly=True),
268         'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
269         'date': fields.datetime('Date', readonly=True),
270         'history': fields.boolean('Is History?', readonly=True),
271         'user_id': fields.many2one('res.users', 'User Responsible', readonly=True),
272         'message': fields.text('Description', readonly=True),
273         'email_from': fields.char('From', size=128, help="Email From", readonly=True),
274         'email_to': fields.char('To', help="Email Recipients", size=256, readonly=True),
275         'email_cc': fields.char('Cc', help="Carbon Copy Email Recipients", size=256, readonly=True),
276         'email_bcc': fields.char('Bcc', help='Blind Carbon Copy Email Recipients', size=256, readonly=True),
277         'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
278         'references': fields.text('References', readonly=True, help="References emails."),
279         'description': fields.text('Description', readonly=True),
280         'partner_id': fields.many2one('res.partner', 'Partner', required=False),
281         'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments', readonly=True),
282         'display_text': fields.function(_get_display_text, method=True, type='text', size="512", string='Display Text'),
283     }
284
285     def init(self, cr):
286         cr.execute("""SELECT indexname
287                       FROM pg_indexes
288                       WHERE indexname = 'mailgate_message_res_id_model_idx'""")
289         if not cr.fetchone():
290             cr.execute("""CREATE INDEX mailgate_message_res_id_model_idx
291                           ON mailgate_message (model, res_id)""")
292
293 mailgate_message()
294
295 class mailgate_tool(osv.osv_memory):
296
297     _name = 'email.server.tools'
298     _description = "Email Server Tools"
299
300     def _decode_header(self, text):
301         """Returns unicode() string conversion of the the given encoded smtp header"""
302         if text:
303             text = decode_header(text.replace('\r', ''))
304             return ''.join([tools.ustr(x[0], x[1]) for x in text])
305
306     def to_email(self,text):
307         return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
308
309     def history(self, cr, uid, model, res_ids, msg, attach, context=None):
310         """This function creates history for mails fetched
311         @param self: The object pointer
312         @param cr: the current row, from the database cursor,
313         @param uid: the current user’s ID for security checks,
314         @param model: OpenObject Model
315         @param res_ids: Ids of the record of OpenObject model created
316         @param msg: Email details
317         @param attach: Email attachments
318         """
319         if isinstance(res_ids, (int, long)):
320             res_ids = [res_ids]
321
322         msg_pool = self.pool.get('mailgate.message')
323         for res_id in res_ids:
324             case = self.pool.get(model).browse(cr, uid, res_id, context=context)
325             partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
326             if not partner_id and model == 'res.partner':
327                 partner_id = res_id
328             msg_data = {
329                 'name': msg.get('subject', 'No subject'),
330                 'date': msg.get('date'),
331                 'description': msg.get('body', msg.get('from')),
332                 'history': True,
333                 'partner_id': partner_id,
334                 'model': model,
335                 'email_cc': msg.get('cc'),
336                 'email_from': msg.get('from'),
337                 'email_to': msg.get('to'),
338                 'message_id': msg.get('message-id'),
339                 'references': msg.get('references') or msg.get('in-reply-to'),
340                 'res_id': res_id,
341                 'user_id': uid,
342                 'attachment_ids': [(6, 0, attach)]
343             }
344             msg_pool.create(cr, uid, msg_data, context=context)
345         return True
346
347     def email_forward(self, cr, uid, model, res_ids, msg, email_error=False, context=None):
348         """Sends an email to all people following the thread
349         @param res_id: Id of the record of OpenObject model created from the email message
350         @param msg: email.message.Message to forward
351         @param email_error: Default Email address in case of any Problem
352         """
353         model_pool = self.pool.get(model)
354
355         for res in model_pool.browse(cr, uid, res_ids, context=context):
356             message_followers = model_pool.message_followers(cr, uid, [res.id])[res.id]
357             message_followers_emails = self.to_email(','.join(filter(None, message_followers)))
358             message_recipients = self.to_email(','.join(filter(None,
359                                                          [self._decode_header(msg['from']),
360                                                          self._decode_header(msg['to']),
361                                                          self._decode_header(msg['cc'])])))
362             message_forward = [i for i in message_followers_emails if (i and (i not in message_recipients))]
363
364             if message_forward:
365                 # TODO: we need an interface for this for all types of objects, not just leads
366                 if hasattr(res, 'section_id'):
367                     del msg['reply-to']
368                     msg['reply-to'] = res.section_id.reply_to
369
370                 smtp_from = self.to_email(msg['from'])
371                 if not tools.misc._email_send(smtp_from, message_forward, msg, openobject_id=res.id) and email_error:
372                     subj = msg['subject']
373                     del msg['subject'], msg['to'], msg['cc'], msg['bcc']
374                     msg['subject'] = '[OpenERP-Forward-Failed] %s' % subj
375                     msg['to'] = email_error
376                     tools.misc._email_send(smtp_from, self.to_email(email_error), msg, openobject_id=res.id)
377
378     def process_email(self, cr, uid, model, message, custom_values=None, attach=True, context=None):
379         """This function Processes email and create record for given OpenERP model
380         @param self: The object pointer
381         @param cr: the current row, from the database cursor,
382         @param uid: the current user’s ID for security checks,
383         @param model: OpenObject Model
384         @param message: Email details, passed as a string or an xmlrpclib.Binary
385         @param attach: Email attachments
386         @param context: A standard dictionary for contextual values"""
387
388         # extract message bytes, we are forced to pass the message as binary because
389         # we don't know its encoding until we parse its headers and hence can't
390         # convert it to utf-8 for transport between the mailgate script and here.
391         if isinstance(message, xmlrpclib.Binary):
392             message = str(message.data)
393
394         if not context:
395             context = {}
396
397         if custom_values is None or not isinstance(custom_values, dict):
398             custom_values = {}
399
400         model_pool = self.pool.get(model)
401         res_id = False
402
403         # Create New Record into particular model
404         def create_record(msg):
405             att_ids = []
406             if hasattr(model_pool, 'message_new'):
407                 res_id = model_pool.message_new(cr, uid, msg, context)
408                 if custom_values:
409                     model_pool.write(cr, uid, [res_id], custom_values, context=context)
410             else:
411                 data = {
412                     'name': msg.get('subject'),
413                     'email_from': msg.get('from'),
414                     'email_cc': msg.get('cc'),
415                     'user_id': False,
416                     'description': msg.get('body'),
417                     'state' : 'draft',
418                 }
419                 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
420                 res_id = model_pool.create(cr, uid, data, context=context)
421
422                 if attach:
423                     for attachment in msg.get('attachments', []):
424                         data_attach = {
425                             'name': attachment,
426                             'datas': binascii.b2a_base64(str(attachments.get(attachment))),
427                             'datas_fname': attachment,
428                             'description': 'Mail attachment',
429                             'res_model': model,
430                             'res_id': res_id,
431                         }
432                         att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
433
434             return res_id, att_ids
435
436         # Warning: message_from_string doesn't always work correctly on unicode,
437         # we must use utf-8 strings here :-(
438         if isinstance(message, unicode):
439             message = message.encode('utf-8')
440         msg_txt = email.message_from_string(message)
441         message_id = msg_txt.get('message-id', False)
442         msg = {}
443
444         if not message_id:
445             # Very unusual situation, be we should be fault-tolerant here
446             message_id = time.time()
447             msg_txt['message-id'] = message_id
448             _logger.info('Message without message-id, generating a random one: %s', message_id)
449
450         fields = msg_txt.keys()
451         msg['id'] = message_id
452         msg['message-id'] = message_id
453
454         if 'Subject' in fields:
455             msg['subject'] = self._decode_header(msg_txt.get('Subject'))
456
457         if 'Content-Type' in fields:
458             msg['content-type'] = msg_txt.get('Content-Type')
459
460         if 'From' in fields:
461             msg['from'] = self._decode_header(msg_txt.get('From'))
462
463         if 'Delivered-To' in fields:
464             msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
465
466         if 'CC' in fields:
467             msg['cc'] = self._decode_header(msg_txt.get('CC'))
468
469         if 'Reply-to' in fields:
470             msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
471
472         if 'Date' in fields:
473             msg['date'] = self._decode_header(msg_txt.get('Date'))
474
475         if 'Content-Transfer-Encoding' in fields:
476             msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
477
478         if 'References' in fields:
479             msg['references'] = msg_txt.get('References')
480
481         if 'In-Reply-To' in fields:
482             msg['in-reply-to'] = msg_txt.get('In-Reply-To')
483
484         if 'X-Priority' in fields:
485             msg['priority'] = msg_txt.get('X-Priority', '3 (Normal)').split(' ')[0]
486
487         if not msg_txt.is_multipart() or 'text/plain' in msg.get('Content-Type', ''):
488             encoding = msg_txt.get_content_charset()
489             body = msg_txt.get_payload(decode=True)
490             if 'text/html' in msg_txt.get('Content-Type', ''):
491                 body = tools.html2plaintext(body)
492             msg['body'] = tools.ustr(body, encoding)
493
494         attachments = {}
495         has_plain_text = False
496         if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
497             body = ""
498             for part in msg_txt.walk():
499                 if part.get_content_maintype() == 'multipart':
500                     continue
501
502                 encoding = part.get_content_charset()
503                 filename = part.get_filename()
504                 if part.get_content_maintype()=='text':
505                     content = part.get_payload(decode=True)
506                     if filename:
507                         attachments[filename] = content
508                     elif not has_plain_text:
509                         # main content parts should have 'text' maintype
510                         # and no filename. we ignore the html part if
511                         # there is already a plaintext part without filename,
512                         # because presumably these are alternatives.
513                         content = tools.ustr(content, encoding)
514                         if part.get_content_subtype() == 'html':
515                             body = tools.ustr(tools.html2plaintext(content))
516                         elif part.get_content_subtype() == 'plain':
517                             body = content
518                             has_plain_text = True
519                 elif part.get_content_maintype() in ('application', 'image'):
520                     if filename :
521                         attachments[filename] = part.get_payload(decode=True)
522                     else:
523                         res = part.get_payload(decode=True)
524                         body += tools.ustr(res, encoding)
525
526             msg['body'] = body
527             msg['attachments'] = attachments
528         res_ids = []
529         attachment_ids = []
530         new_res_id = False
531         if msg.get('references') or msg.get('in-reply-to'):
532             references = msg.get('references') or msg.get('in-reply-to')
533             if '\r\n' in references:
534                 references = references.split('\r\n')
535             else:
536                 references = references.split(' ')
537             for ref in references:
538                 ref = ref.strip()
539                 res_id = tools.misc.reference_re.search(ref)
540                 if res_id:
541                     res_id = res_id.group(1)
542                 else:
543                     res_id = tools.misc.res_re.search(msg['subject'])
544                     if res_id:
545                         res_id = res_id.group(1)
546                 if res_id:
547                     res_id = int(res_id)
548                     model_pool = self.pool.get(model)
549                     if model_pool.exists(cr, uid, res_id):
550                         res_ids.append(res_id)
551                         if hasattr(model_pool, 'message_update'):
552                             model_pool.message_update(cr, uid, [res_id], {}, msg, context=context)
553                         else:
554                             raise NotImplementedError('model %s does not support updating records, mailgate API method message_update() is missing'%model)
555
556         if not len(res_ids):
557             new_res_id, attachment_ids = create_record(msg)
558             res_ids = [new_res_id]
559
560         # Store messages
561         context.update({'model' : model})
562         if hasattr(model_pool, 'history'):
563             model_pool.history(cr, uid, res_ids, _('receive'), history=True,
564                             subject = msg.get('subject'),
565                             email = msg.get('to'),
566                             details = msg.get('body'),
567                             email_from = msg.get('from'),
568                             email_cc = msg.get('cc'),
569                             message_id = msg.get('message-id'),
570                             references = msg.get('references', False) or msg.get('in-reply-to', False),
571                             attach = attachments.items(),
572                             email_date = msg.get('date'),
573                             context = context)
574         else:
575             self.history(cr, uid, model, res_ids, msg, attachment_ids, context=context)
576         self.email_forward(cr, uid, model, res_ids, msg_txt)
577         return new_res_id
578
579     def get_partner(self, cr, uid, from_email, context=None):
580         """This function returns partner Id based on email passed
581         @param self: The object pointer
582         @param cr: the current row, from the database cursor,
583         @param uid: the current user’s ID for security checks
584         @param from_email: email address based on that function will search for the correct
585         """
586         address_pool = self.pool.get('res.partner.address')
587         res = {
588             'partner_address_id': False,
589             'partner_id': False
590         }
591         from_email = self.to_email(from_email)[0]
592         address_ids = address_pool.search(cr, uid, [('email', 'like', from_email)])
593         if address_ids:
594             address = address_pool.browse(cr, uid, address_ids[0])
595             res['partner_address_id'] = address_ids[0]
596             res['partner_id'] = address.partner_id.id
597
598         return res
599
600 mailgate_tool()
601
602 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: