[FIX] crm, mail_gateway: review, cleanup and improvements in mail_gateway and crm
[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
33 _logger = logging.getLogger('mailgate')
34
35 class mailgate_thread(osv.osv):
36     '''
37     Mailgateway Thread
38     '''
39     _name = 'mailgate.thread'
40     _description = 'Mailgateway Thread'
41
42     _columns = {
43         'message_ids': fields.one2many('mailgate.message', 'res_id', 'Messages', domain=[('history', '=', True)]),
44         'log_ids': fields.one2many('mailgate.message', 'res_id', 'Logs', domain=[('history', '=', False)]),
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 emails_get(self, cr, uid, ids, context=None):
54         raise Exception, _('Method is not implemented')
55
56     def msg_send(self, cr, uid, id, *args, **argv):
57         raise Exception, _('Method is not implemented')
58
59     def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \
60                     email_from=False, message_id=False, references=None, attach=None, context=None):
61         """
62         @param self: The object pointer
63         @param cr: the current row, from the database cursor,
64         @param uid: the current user’s ID for security checks,
65         @param cases: a browse record list
66         @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used
67         @param history: Value True/False, If True it makes entry in case History otherwise in Case Log
68         @param email: Email address if any
69         @param details: Details of case history if any 
70         @param atach: Attachment sent in email
71         @param context: A standard dictionary for contextual values"""
72         if context is None:
73             context = {}
74         if attach is None:
75             attach = []
76
77         # The mailgate sends the ids of the cases and not the object list
78
79         if all(isinstance(case_id, (int, long)) for case_id in cases):
80             cases = self.browse(cr, uid, cases, context=context)
81
82         att_obj = self.pool.get('ir.attachment')
83         obj = self.pool.get('mailgate.message')
84
85         for case in cases:
86             data = {
87                 'name': keyword, 
88                 'user_id': uid, 
89                 'model' : case._name, 
90                 'res_id': case.id, 
91                 'date': time.strftime('%Y-%m-%d %H:%M:%S'), 
92                 'message_id': message_id, 
93             }
94             attachments = []
95             if history:
96                 for att in attach:
97                     attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
98
99                 data = {
100                     'name': subject or 'History', 
101                     'history': True, 
102                     'user_id': uid, 
103                     'model' : case._name, 
104                     'res_id': case.id,
105                     'date': time.strftime('%Y-%m-%d %H:%M:%S'), 
106                     'description': details or (hasattr(case, 'description') and case.description or False), 
107                     'email_to': email or \
108                         (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
109                          case.user_id.address_id.email) or tools.config.get('email_from', False), 
110                     'email_from': email_from or \
111                         (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
112                          case.user_id.address_id.email) or tools.config.get('email_from', False), 
113                     'partner_id': hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False, 
114                     'references': references, 
115                     'message_id': message_id, 
116                     'attachment_ids': [(6, 0, attachments)]
117                 }
118             res = obj.create(cr, uid, data, context)
119         return True
120 mailgate_thread()
121
122 class mailgate_message(osv.osv):
123     '''
124     Mailgateway Message
125     '''
126     _name = 'mailgate.message'
127     _description = 'Mailgateway Message'
128     _order = 'id desc'
129     _columns = {
130         'name':fields.char('Subject', size=128), 
131         'model': fields.char('Object Name', size=128), 
132         'res_id': fields.integer('Resource ID'),
133         'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
134         'date': fields.datetime('Date'), 
135         'history': fields.boolean('Is History?'),
136         'user_id': fields.many2one('res.users', 'User Responsible', readonly=True), 
137         'message': fields.text('Description'), 
138         'email_from': fields.char('Email From', size=84), 
139         'email_to': fields.char('Email To', size=84), 
140         'email_cc': fields.char('Email CC', size=84), 
141         'email_bcc': fields.char('Email BCC', size=84), 
142         'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
143         'references': fields.text('References', readonly=True, help="Referencess emails."),
144         'description': fields.text('Description'), 
145         'partner_id': fields.many2one('res.partner', 'Partner', required=False), 
146         'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments'), 
147     }
148
149 mailgate_message()
150
151 class mailgate_tool(osv.osv_memory):
152
153     _name = 'email.server.tools'
154     _description = "Email Server Tools"
155
156     def _to_decode(self, s, charsets):
157         if not s:
158             return s
159         for charset in charsets:
160             if charset:
161                 try:
162                     return s.decode(charset)
163                 except UnicodeError:
164                     pass
165         return s.decode('latin1')
166
167     def _decode_header(self, text):
168         if text:
169             text = decode_header(text.replace('\r', '')) 
170         return ''.join(map(lambda x:self._to_decode(x[0], [x[1]]), text or []))
171
172     def to_email(self, text):
173         _email = re.compile(r'.*<.*@.*\..*>', re.UNICODE)
174         def record(path):
175             eml = path.group()
176             index = eml.index('<')
177             eml = eml[index:-1].replace('<', '').replace('>', '')
178             return eml
179
180         bits = _email.sub(record, text)
181         return bits
182
183     def history(self, cr, uid, model, res_ids, msg, attach, context=None):
184         """This function creates history for mails fetched
185         @param self: The object pointer
186         @param cr: the current row, from the database cursor,
187         @param uid: the current user’s ID for security checks,
188         @param model: OpenObject Model
189         @param res_ids: Ids of the record of OpenObject model created 
190         @param msg: Email details
191         @param attach: Email attachments
192         """
193         if isinstance(res_ids, (int, long)):
194             res_ids = [res_ids]
195
196         msg_pool = self.pool.get('mailgate.message')
197         for res_id in res_ids:
198             msg_data = {
199                         'name': msg.get('subject', 'No subject'), 
200                         'date': msg.get('date') , 
201                         'description': msg.get('body', msg.get('from')), 
202                         'history': True,
203                         'res_model': model, 
204                         'email_cc': msg.get('cc'), 
205                         'email_from': msg.get('from'), 
206                         'email_to': msg.get('to'), 
207                         'message_id': msg.get('message-id'), 
208                         'references': msg.get('references'), 
209                         'res_id': res_id,
210                         'user_id': uid, 
211                         'attachment_ids': [(6, 0, attach)]
212             }
213             msg_id = msg_pool.create(cr, uid, msg_data, context=context)
214         return True
215
216     def email_send(self, cr, uid, model, res_id, msg, from_email=False, email_default=False):
217         """This function Sends return email on submission of  Fetched email in OpenERP database
218         @param self: The object pointer
219         @param cr: the current row, from the database cursor,
220         @param uid: the current user’s ID for security checks,
221         @param model: OpenObject Model
222         @param res_id: Id of the record of OpenObject model created from the Email details 
223         @param msg: Email details
224         @param email_default: Default Email address in case of any Problem
225         """
226         history_pool = self.pool.get('mailgate.message')
227         model_pool = self.pool.get(model)
228         from_email = from_email or tools.config.get('email_from', None)
229         message = email.message_from_string(tools.ustr(msg).encode('utf-8'))
230         subject = message['Subject']
231
232         values = {}
233         if hasattr(model_pool, 'emails_get'):
234             values = model_pool.emails_get(cr, uid, [res_id])
235         emails = values.get(res_id, {})
236
237         priority = emails.get('priority', [3])[0]
238         em = emails['user_email'] + emails['email_from'] + emails['email_cc']
239         msg_mails = map(self.to_email, filter(None, em))
240
241         encoding = message.get_content_charset()
242         message['body'] = message.get_payload(decode=True)
243         if encoding:
244             message['body'] = self._to_decode(message['body'], [encoding])
245
246         from_mail = self._decode_header(message['From'])
247         body = _("""
248 Hello %s,""" % (from_mail))
249         body += _("""
250
251     Your Request ID: %s""") % (res_id)
252         body += _("""
253 Thanks
254
255 -------- Original Message --------
256 %s
257 """) % (self._to_decode(message['body'], [encoding]))
258         res = None
259         try:
260             res = tools.email_send(from_email, msg_mails, subject, body, openobject_id=res_id)
261         except Exception, e:
262             if email_default:
263                 temp_msg = '[%s] %s'%(res_id, message['Subject'])
264                 del message['Subject']
265                 message['Subject'] = '[OpenERP-FetchError] %s' %(temp_msg)
266                 tools.email_send(from_email, email_default, message.get('Subject'), message.get('body'), openobject_id=res_id)
267         return res
268
269     def process_email(self, cr, uid, model, message, attach=True, context=None):
270         """This function Processes email and create record for given OpenERP model 
271         @param self: The object pointer
272         @param cr: the current row, from the database cursor,
273         @param uid: the current user’s ID for security checks,
274         @param model: OpenObject Model
275         @param message: Email details
276         @param attach: Email attachments
277         @param context: A standard dictionary for contextual values"""
278         model_pool = self.pool.get(model)
279         if not context:
280             context = {}
281         res_id = False
282         # Create New Record into particular model
283         def create_record(msg):
284             if hasattr(model_pool, 'message_new'):
285                 res_id = model_pool.message_new(cr, uid, msg, context)
286             else:
287                 data = {
288                     'name': msg.get('subject'),
289                     'email_from': msg.get('from'),
290                     'email_cc': msg.get('cc'),
291                     'user_id': False,
292                     'description': msg.get('body'),
293                     'state' : 'draft',
294                 }
295                 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
296                 res_id = model_pool.create(cr, uid, data, context=context)
297
298                 att_ids = []
299                 if attach:
300                     for attachment in msg.get('attachments', []):
301                         data_attach = {
302                             'name': attachment,
303                             'datas': binascii.b2a_base64(str(attachments.get(attachment))),
304                             'datas_fname': attachment,
305                             'description': 'Mail attachment',
306                             'res_model': model,
307                             'res_id': res_id,
308                         }
309                         att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
310
311             return res_id
312
313         history_pool = self.pool.get('mailgate.message')
314
315         # Warning: message_from_string doesn't always work correctly on unicode,
316         # we must use utf-8 strings here :-(
317         msg_txt = email.message_from_string(tools.ustr(message).encode('utf-8'))
318         message_id = msg_txt.get('Message-ID', False)
319         msg = {}
320
321         if not message_id:
322             # Very unusual situation, be we should be fault-tolerant here
323             message_id = time.time()
324             msg_txt['Message-ID'] = message_id
325             _logger.info('Message without message-id, generating a random one: %s', message_id)
326
327         fields = msg_txt.keys()
328         msg['id'] = message_id
329         msg['message-id'] = message_id
330
331         if 'Subject' in fields:
332             msg['subject'] = self._decode_header(msg_txt.get('Subject'))
333
334         if 'Content-Type' in fields:
335             msg['content-type'] = msg_txt.get('Content-Type')
336
337         if 'From' in fields:
338             msg['from'] = self._decode_header(msg_txt.get('From'))
339
340         if 'Delivered-To' in fields:
341             msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
342
343         if 'Cc' in fields:
344             msg['cc'] = self._decode_header(msg_txt.get('Cc'))
345
346         if 'Reply-To' in fields:
347             msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
348
349         if 'Date' in fields:
350             msg['date'] = msg_txt.get('Date')
351
352         if 'Content-Transfer-Encoding' in fields:
353             msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
354
355         if 'References' in fields:
356             msg['references'] = msg_txt.get('References')
357
358         if 'X-Priority' in fields:
359             msg['priority'] = msg_txt.get('X-priority', '3 (Normal)').split(' ')[0]
360
361         if not msg_txt.is_multipart() or 'text/plain' in msg.get('content-type', ''):
362             encoding = msg_txt.get_content_charset()
363             msg['body'] = msg_txt.get_payload(decode=True)
364             if encoding:
365                 msg['body'] = tools.ustr(msg['body'])
366
367         attachments = {}
368         if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
369             body = ""
370             counter = 1
371             for part in msg_txt.walk():
372                 if part.get_content_maintype() == 'multipart':
373                     continue
374
375                 encoding = part.get_content_charset()
376
377                 if part.get_content_maintype()=='text':
378                     content = part.get_payload(decode=True)
379                     filename = part.get_filename()
380                     if filename :
381                         attachments[filename] = content
382                     else:
383                         if encoding:
384                             content = unicode(content, encoding)
385                         if part.get_content_subtype() == 'html':
386                             body = tools.html2plaintext(content)
387                         elif part.get_content_subtype() == 'plain':
388                             body = content
389                 elif part.get_content_maintype()=='application' or part.get_content_maintype()=='image' or part.get_content_maintype()=='text':
390                     filename = part.get_filename();
391                     if filename :
392                         attachments[filename] = part.get_payload(decode=True)
393                     else:
394                         res = part.get_payload(decode=True)
395                         if encoding:
396                             res = tools.ustr(res)
397
398                         body += res
399
400             msg['body'] = body
401             msg['attachments'] = attachments
402         res_ids = []
403         new_res_id = False
404         if msg.get('references'):
405             references = msg.get('references')
406             if '\r\n' in references:
407                 references = msg.get('references').split('\r\n')
408             else:
409                 references = msg.get('references').split(' ')
410             for ref in references:
411                 ref = ref.strip()
412                 res_id = tools.misc.reference_re.search(ref)
413                 if res_id:
414                     res_id = res_id.group(1)
415                 else:
416                     res_id = tools.misc.res_re.search(msg['subject'])
417                     if res_id:
418                         res_id = res_id.group(1)
419                 if res_id:
420                     res_id = int(res_id)
421                     res_ids.append(res_id)
422                     model_pool = self.pool.get(model)
423
424                     vals = {}
425                     if hasattr(model_pool, 'message_update'):
426                         model_pool.message_update(cr, uid, [res_id], vals, msg, context=context)
427
428         if not len(res_ids):
429             new_res_id = create_record(msg)
430             res_ids = [new_res_id]
431         # Store messages
432         context.update({'model' : model})
433         if hasattr(model_pool, '_history'):
434             model_pool._history(cr, uid, res_ids, _('Receive'), history=True,
435                             subject = msg.get('subject'),
436                             email = msg.get('to'),
437                             details = msg.get('body'),
438                             email_from = msg.get('from'),
439                             message_id = msg.get('message-id'),
440                             references = msg.get('references', False),
441                             attach = msg.get('attachments', {}).items(),
442                             context = context)
443         else:
444             self.history(cr, uid, model, res_ids, msg, att_ids, context=context)
445         return new_res_id
446
447     def get_partner(self, cr, uid, from_email, context=None):
448         """This function returns partner Id based on email passed
449         @param self: The object pointer
450         @param cr: the current row, from the database cursor,
451         @param uid: the current user’s ID for security checks
452         @param from_email: email address based on that function will search for the correct
453         """
454         address_pool = self.pool.get('res.partner.address')
455         res = {
456             'partner_address_id': False,
457             'partner_id': False
458         }
459         from_email = self.to_email(from_email)
460         address_ids = address_pool.search(cr, uid, [('email', '=', from_email)])
461         if address_ids:
462             address = address_pool.browse(cr, uid, address_ids[0])
463             res['partner_address_id'] = address_ids[0]
464             res['partner_id'] = address.partner_id.id
465
466         return res
467
468 mailgate_tool()