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