[MERGE] merge with latest stable
[odoo/odoo.git] / addons / mail_gateway / mail_gateway.py
index b756d9f..c4baca5 100644 (file)
@@ -25,6 +25,7 @@ import tools
 import binascii
 import email
 from email.header import decode_header
+from email.utils import parsedate
 import base64
 import re
 from tools.translate import _
@@ -54,8 +55,6 @@ class mailgate_thread(osv.osv):
         @param default: Dictionary of default values for copy.
         @param context: A standard dictionary for contextual values
         """
-        if context is None:
-            context = {}
         if default is None:
             default = {}
 
@@ -69,7 +68,7 @@ class mailgate_thread(osv.osv):
     def message_new(self, cr, uid, msg, context):
         raise Exception, _('Method is not implemented')
 
-    def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context={}):
+    def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context=None):
         raise Exception, _('Method is not implemented')
 
     def message_followers(self, cr, uid, ids, context=None):
@@ -113,6 +112,11 @@ class mailgate_thread(osv.osv):
         if attach is None:
             attach = []
 
+        if email_date:
+            edate = parsedate(email_date)
+            if edate is not None:
+                email_date = time.strftime('%Y-%m-%d %H:%M:%S', edate)
+
         # The mailgate sends the ids of the cases and not the object list
 
         if all(isinstance(case_id, (int, long)) for case_id in cases):
@@ -124,7 +128,27 @@ class mailgate_thread(osv.osv):
         for case in cases:
             attachments = []
             for att in attach:
-                    attachments.append(att_obj.create(cr, uid, {'name': att[0], 'datas': base64.encodestring(att[1])}))
+                if isinstance(att,(int,long)):
+                    attachments.append(att)
+                elif isinstance(att,dict):
+                    domain = [
+                        ('name', '=', att[0]),
+                        ('res_id', '=', case.id),
+                        ('res_model', '=', case._name)
+                    ]
+                    att_ids = att_obj.search(cr, uid, domain, context=context)
+
+                    if att_ids:
+                        attachments.extend(att_ids)
+                    else:
+                        values = {
+                            'res_model' : case._name,
+                            'res_id' : case.id,
+                            'name' : att[0],
+                            'datas' : base64.encodestring(att[1])
+                        }
+                        attachment_id = att_obj.create(cr, uid, values, context=context)
+                        attachments.append(attachment_id)
 
             partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
             if not partner_id and case._name == 'res.partner':
@@ -146,25 +170,18 @@ class mailgate_thread(osv.osv):
                     if isinstance(param, list):
                         param = ", ".join(param)
 
-                data = {
+                data.update({
                     'name': subject or _('History'),
                     'history': True,
-                    'user_id': uid,
-                    'model' : case._name,
-                    'res_id': case.id,
                     'date': email_date or time.strftime('%Y-%m-%d %H:%M:%S'),
-                    'description': details or (hasattr(case, 'description') and case.description or False),
                     'email_to': email,
                     'email_from': email_from or \
                         (hasattr(case, 'user_id') and case.user_id and case.user_id.address_id and \
                          case.user_id.address_id.email),
                     'email_cc': email_cc,
                     'email_bcc': email_bcc,
-                    'partner_id': partner_id,
                     'references': references,
-                    'message_id': message_id,
-                    'attachment_ids': [(6, 0, attachments)]
-                }
+                })
             obj.create(cr, uid, data, context=context)
         return True
 mailgate_thread()
@@ -179,7 +196,7 @@ class mailgate_message(osv.osv):
     '''
     Mailgateway Message
     '''
-    def open_document(self, cr, uid, ids, context):
+    def open_document(self, cr, uid, ids, context=None):
         """ To Open Document
         @param self: The object pointer.
         @param cr: A database cursor
@@ -190,7 +207,7 @@ class mailgate_message(osv.osv):
         action_data = False
         if ids:
             message_id = ids[0]
-            mailgate_data = self.browse(cr, uid, message_id)
+            mailgate_data = self.browse(cr, uid, message_id, context=context)
             model = mailgate_data.model
             res_id = mailgate_data.res_id
 
@@ -200,11 +217,12 @@ class mailgate_message(osv.osv):
                 action_data = action_pool.read(cr, uid, action_ids[0], context=context)
                 action_data.update({
                     'domain' : "[('id','=',%d)]"%(res_id),
-                    'nodestroy': True
+                    'nodestroy': True,
+                    'context': {}
                     })
         return action_data
 
-    def open_attachment(self, cr, uid, ids, context):
+    def open_attachment(self, cr, uid, ids, context=None):
         """ To Open attachments
         @param self: The object pointer.
         @param cr: A database cursor
@@ -214,11 +232,13 @@ class mailgate_message(osv.osv):
         """
         action_data = False
         action_pool = self.pool.get('ir.actions.act_window')
+        message_pool = self.browse(cr ,uid, ids, context=context)[0]
+        att_ids = [x.id for x in message_pool.attachment_ids] 
         action_ids = action_pool.search(cr, uid, [('res_model', '=', 'ir.attachment')])
         if action_ids:
             action_data = action_pool.read(cr, uid, action_ids[0], context=context)
             action_data.update({
-                'domain': [('res_id','in',ids),('res_model','=',self._name)],
+                'domain': [('id','in',att_ids)],
                 'nodestroy': True
                 })
         return action_data
@@ -238,19 +258,22 @@ class mailgate_message(osv.osv):
         result = {}
         for message in self.browse(cr, uid, ids, context=context):
             msg_txt = ''
+            msg_name = message.name
             if message.history:
                 msg_txt += (message.email_from or '/') + _(' wrote on ') + format_date_tz(message.date, tz) + ':\n\t'
                 if message.description:
                     msg_txt += self.truncate_data(cr, uid, message.description, context=context)
             else:
                 msg_txt = (message.user_id.name or '/') + _(' on ') + format_date_tz(message.date, tz) + ':\n\t'
-                if message.name == _('Opportunity'):
+                if msg_name == _('Opportunity'):
                     msg_txt += _("Converted to Opportunity")
-                elif message.name == _('Note'):
+                elif msg_name == _('Note'):
                     msg_txt = (message.user_id.name or '/') + _(' added note on ') + format_date_tz(message.date, tz) + ':\n\t'
                     msg_txt += self.truncate_data(cr, uid, message.description, context=context)
-                else:
-                    msg_txt += _("Changed Status to: ") + message.name
+                elif msg_name == _('Stage'):
+                    msg_txt += _("Changed Stage to: ") + message.description
+                elif msg_name:
+                    msg_txt += _("Changed Status to: ") + msg_name
             result[message.id] = msg_txt
         return result
 
@@ -346,8 +369,8 @@ class mailgate_tool(osv.osv_memory):
         @param msg: email.message.Message to forward
         @param email_error: Default Email address in case of any Problem
         """
-        model_pool = self.pool.get(model)
 
+        model_pool = self.pool.get(model)
         for res in model_pool.browse(cr, uid, res_ids, context=context):
             message_followers = model_pool.message_followers(cr, uid, [res.id])[res.id]
             message_followers_emails = self.to_email(','.join(filter(None, message_followers)))
@@ -387,7 +410,7 @@ class mailgate_tool(osv.osv_memory):
         if isinstance(message, xmlrpclib.Binary):
             message = str(message.data)
 
-        if not context:
+        if context is None:
             context = {}
 
         if custom_values is None or not isinstance(custom_values, dict):
@@ -400,7 +423,7 @@ class mailgate_tool(osv.osv_memory):
         def create_record(msg):
             att_ids = []
             if hasattr(model_pool, 'message_new'):
-                res_id = model_pool.message_new(cr, uid, msg, context)
+                res_id,att_ids = model_pool.message_new(cr, uid, msg, context=context)
                 if custom_values:
                     model_pool.write(cr, uid, [res_id], custom_values, context=context)
             else:
@@ -483,6 +506,8 @@ class mailgate_tool(osv.osv_memory):
         if not msg_txt.is_multipart() or 'text/plain' in msg.get('Content-Type', ''):
             encoding = msg_txt.get_content_charset()
             body = msg_txt.get_payload(decode=True)
+            if 'text/html' in msg_txt.get('Content-Type', ''):
+                body = tools.html2plaintext(body)
             msg['body'] = tools.ustr(body, encoding)
 
         attachments = {}
@@ -510,7 +535,8 @@ class mailgate_tool(osv.osv_memory):
                         elif part.get_content_subtype() == 'plain':
                             body = content
                             has_plain_text = True
-                elif part.get_content_maintype() in ('application', 'image'):
+                elif part.get_content_maintype() in ('application', 'image') \
+                        or part.get_content_subtype() in ('octet-stream'):
                     if filename :
                         attachments[filename] = part.get_payload(decode=True)
                     else:
@@ -562,7 +588,8 @@ class mailgate_tool(osv.osv_memory):
                             email_cc = msg.get('cc'),
                             message_id = msg.get('message-id'),
                             references = msg.get('references', False) or msg.get('in-reply-to', False),
-                            attach = attachments.items(),
+                            attach = attachment_ids or attachments.items(),
+                            email_date = msg.get('date'),
                             context = context)
         else:
             self.history(cr, uid, model, res_ids, msg, attachment_ids, context=context)