1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>)
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
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
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/>
20 ##############################################################################
22 from osv import osv, fields
27 from email.header import decode_header
28 from email.utils import parsedate
31 from tools.translate import _
35 _logger = logging.getLogger('mailgate')
37 class mailgate_thread(osv.osv):
41 _name = 'mailgate.thread'
42 _description = 'Mailgateway Thread'
45 'message_ids': fields.one2many('mailgate.message', 'res_id', 'Messages', readonly=True),
48 def copy(self, cr, uid, id, default=None, context=None):
50 Overrides orm copy method.
51 @param self: the object pointer
52 @param cr: the current row, from the database cursor,
53 @param uid: the current user’s ID for security checks,
54 @param id: Id of mailgate thread
55 @param default: Dictionary of default values for copy.
56 @param context: A standard dictionary for contextual values
66 return super(mailgate_thread, self).copy(cr, uid, id, default, context=context)
68 def message_new(self, cr, uid, msg, context):
69 raise Exception, _('Method is not implemented')
71 def message_update(self, cr, uid, ids, vals={}, msg="", default_act='pending', context=None):
72 raise Exception, _('Method is not implemented')
74 def message_followers(self, cr, uid, ids, context=None):
75 """ Get a list of emails of the people following this thread
78 if isinstance(ids, (str, int, long)):
80 for thread in self.browse(cr, uid, ids, context=context):
82 for message in thread.message_ids:
83 l.append((message.user_id and message.user_id.email) or '')
84 l.append(message.email_from or '')
85 l.append(message.email_cc or '')
89 def msg_send(self, cr, uid, id, *args, **argv):
90 raise Exception, _('Method is not implemented')
92 def history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \
93 email_from=False, message_id=False, references=None, attach=None, email_cc=None, \
94 email_bcc=None, email_date=None, context=None):
96 @param self: The object pointer
97 @param cr: the current row, from the database cursor,
98 @param uid: the current user’s ID for security checks,
99 @param cases: a browse record list
100 @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used
101 @param history: Value True/False, If True it makes entry in case History otherwise in Case Log
102 @param email: Email-To / Recipient address
103 @param email_from: Email From / Sender address if any
104 @param email_cc: Comma-Separated list of Carbon Copy Emails To addresse if any
105 @param email_bcc: Comma-Separated list of Blind Carbon Copy Emails To addresses if any
106 @param email_date: Email Date string if different from now, in server Timezone
107 @param details: Description, Details of case history if any
108 @param atach: Attachment sent in email
109 @param context: A standard dictionary for contextual values"""
116 edate = parsedate(email_date)
117 if edate is not None:
118 email_date = time.strftime('%Y-%m-%d %H:%M:%S', edate)
120 # The mailgate sends the ids of the cases and not the object list
122 if all(isinstance(case_id, (int, long)) for case_id in cases):
123 cases = self.browse(cr, uid, cases, context=context)
125 att_obj = self.pool.get('ir.attachment')
126 obj = self.pool.get('mailgate.message')
131 attachments.append(att_obj.create(cr, uid, {'res_model':case._name,'res_id':case.id,'name': att[0], 'datas': base64.encodestring(att[1])}))
133 partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
134 if not partner_id and case._name == 'res.partner':
139 'model' : case._name,
140 'partner_id': partner_id,
142 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
143 'message_id': message_id,
144 'description': details or (hasattr(case, 'description') and case.description or False),
145 'attachment_ids': [(6, 0, attachments)]
149 for param in (email, email_cc, email_bcc):
150 if isinstance(param, list):
151 param = ", ".join(param)
154 'name': subject or _('History'),
156 'date': email_date or time.strftime('%Y-%m-%d %H:%M:%S'),
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 'references': references,
165 obj.create(cr, uid, data, context=context)
169 def format_date_tz(date, tz=None):
172 format = tools.DEFAULT_SERVER_DATETIME_FORMAT
173 return tools.server_to_local_timestamp(date, format, format, tz)
175 class mailgate_message(osv.osv):
179 def open_document(self, cr, uid, ids, context=None):
181 @param self: The object pointer.
182 @param cr: A database cursor
183 @param uid: ID of the user currently logged in
184 @param ids: the ID of messages
185 @param context: A standard dictionary
190 mailgate_data = self.browse(cr, uid, message_id, context=context)
191 model = mailgate_data.model
192 res_id = mailgate_data.res_id
194 action_pool = self.pool.get('ir.actions.act_window')
195 action_ids = action_pool.search(cr, uid, [('res_model', '=', model)])
197 action_data = action_pool.read(cr, uid, action_ids[0], context=context)
199 'domain' : "[('id','=',%d)]"%(res_id),
205 def open_attachment(self, cr, uid, ids, context=None):
206 """ To Open attachments
207 @param self: The object pointer.
208 @param cr: A database cursor
209 @param uid: ID of the user currently logged in
210 @param ids: the ID of messages
211 @param context: A standard dictionary
214 action_pool = self.pool.get('ir.actions.act_window')
215 message_pool = self.browse(cr ,uid, ids, context=context)[0]
216 att_ids = [x.id for x in message_pool.attachment_ids]
217 action_ids = action_pool.search(cr, uid, [('res_model', '=', 'ir.attachment')])
219 action_data = action_pool.read(cr, uid, action_ids[0], context=context)
221 'domain': [('id','in',att_ids)],
226 def truncate_data(self, cr, uid, data, context=None):
227 data_list = data and data.split('\n') or []
228 if len(data_list) > 3:
229 res = '\n\t'.join(data_list[:3]) + '...'
231 res = '\n\t'.join(data_list)
234 def _get_display_text(self, cr, uid, ids, name, arg, context=None):
237 tz = context.get('tz')
239 for message in self.browse(cr, uid, ids, context=context):
241 msg_name = message.name
243 msg_txt += (message.email_from or '/') + _(' wrote on ') + format_date_tz(message.date, tz) + ':\n\t'
244 if message.description:
245 msg_txt += self.truncate_data(cr, uid, message.description, context=context)
247 msg_txt = (message.user_id.name or '/') + _(' on ') + format_date_tz(message.date, tz) + ':\n\t'
248 if msg_name == _('Opportunity'):
249 msg_txt += _("Converted to Opportunity")
250 elif msg_name == _('Note'):
251 msg_txt = (message.user_id.name or '/') + _(' added note on ') + format_date_tz(message.date, tz) + ':\n\t'
252 msg_txt += self.truncate_data(cr, uid, message.description, context=context)
253 elif msg_name == _('Stage'):
254 msg_txt += _("Changed Stage to: ") + message.description
256 msg_txt += _("Changed Status to: ") + msg_name
257 result[message.id] = msg_txt
260 _name = 'mailgate.message'
261 _description = 'Mailgateway Message'
264 'name':fields.text('Subject', readonly=True),
265 'model': fields.char('Object Name', size=128, select=1, readonly=True),
266 'res_id': fields.integer('Resource ID', select=1, readonly=True),
267 'ref_id': fields.char('Reference Id', size=256, readonly=True, help="Message Id in Email Server.", select=True),
268 'date': fields.datetime('Date', readonly=True),
269 'history': fields.boolean('Is History?', readonly=True),
270 'user_id': fields.many2one('res.users', 'User Responsible', readonly=True),
271 'message': fields.text('Description', readonly=True),
272 'email_from': fields.char('From', size=128, help="Email From", readonly=True),
273 'email_to': fields.char('To', help="Email Recipients", size=256, readonly=True),
274 'email_cc': fields.char('Cc', help="Carbon Copy Email Recipients", size=256, readonly=True),
275 'email_bcc': fields.char('Bcc', help='Blind Carbon Copy Email Recipients', size=256, readonly=True),
276 'message_id': fields.char('Message Id', size=1024, readonly=True, help="Message Id on Email.", select=True),
277 'references': fields.text('References', readonly=True, help="References emails."),
278 'description': fields.text('Description', readonly=True),
279 'partner_id': fields.many2one('res.partner', 'Partner', required=False),
280 'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments', readonly=True),
281 'display_text': fields.function(_get_display_text, method=True, type='text', size="512", string='Display Text'),
285 cr.execute("""SELECT indexname
287 WHERE indexname = 'mailgate_message_res_id_model_idx'""")
288 if not cr.fetchone():
289 cr.execute("""CREATE INDEX mailgate_message_res_id_model_idx
290 ON mailgate_message (model, res_id)""")
294 class mailgate_tool(osv.osv_memory):
296 _name = 'email.server.tools'
297 _description = "Email Server Tools"
299 def _decode_header(self, text):
300 """Returns unicode() string conversion of the the given encoded smtp header"""
302 text = decode_header(text.replace('\r', ''))
303 return ''.join([tools.ustr(x[0], x[1]) for x in text])
305 def to_email(self,text):
306 return re.findall(r'([^ ,<@]+@[^> ,]+)',text)
308 def history(self, cr, uid, model, res_ids, msg, attach, context=None):
309 """This function creates history for mails fetched
310 @param self: The object pointer
311 @param cr: the current row, from the database cursor,
312 @param uid: the current user’s ID for security checks,
313 @param model: OpenObject Model
314 @param res_ids: Ids of the record of OpenObject model created
315 @param msg: Email details
316 @param attach: Email attachments
318 if isinstance(res_ids, (int, long)):
321 msg_pool = self.pool.get('mailgate.message')
322 for res_id in res_ids:
323 case = self.pool.get(model).browse(cr, uid, res_id, context=context)
324 partner_id = hasattr(case, 'partner_id') and (case.partner_id and case.partner_id.id or False) or False
325 if not partner_id and model == 'res.partner':
328 'name': msg.get('subject', 'No subject'),
329 'date': msg.get('date'),
330 'description': msg.get('body', msg.get('from')),
332 'partner_id': partner_id,
334 'email_cc': msg.get('cc'),
335 'email_from': msg.get('from'),
336 'email_to': msg.get('to'),
337 'message_id': msg.get('message-id'),
338 'references': msg.get('references') or msg.get('in-reply-to'),
341 'attachment_ids': [(6, 0, attach)]
343 msg_pool.create(cr, uid, msg_data, context=context)
346 def email_forward(self, cr, uid, model, res_ids, msg, email_error=False, context=None):
347 """Sends an email to all people following the thread
348 @param res_id: Id of the record of OpenObject model created from the email message
349 @param msg: email.message.Message to forward
350 @param email_error: Default Email address in case of any Problem
352 model_pool = self.pool.get(model)
354 for res in model_pool.browse(cr, uid, res_ids, context=context):
355 message_followers = model_pool.message_followers(cr, uid, [res.id])[res.id]
356 message_followers_emails = self.to_email(','.join(filter(None, message_followers)))
357 message_recipients = self.to_email(','.join(filter(None,
358 [self._decode_header(msg['from']),
359 self._decode_header(msg['to']),
360 self._decode_header(msg['cc'])])))
361 message_forward = [i for i in message_followers_emails if (i and (i not in message_recipients))]
364 # TODO: we need an interface for this for all types of objects, not just leads
365 if hasattr(res, 'section_id'):
367 msg['reply-to'] = res.section_id.reply_to
369 smtp_from = self.to_email(msg['from'])
370 if not tools.misc._email_send(smtp_from, message_forward, msg, openobject_id=res.id) and email_error:
371 subj = msg['subject']
372 del msg['subject'], msg['to'], msg['cc'], msg['bcc']
373 msg['subject'] = '[OpenERP-Forward-Failed] %s' % subj
374 msg['to'] = email_error
375 tools.misc._email_send(smtp_from, self.to_email(email_error), msg, openobject_id=res.id)
377 def process_email(self, cr, uid, model, message, custom_values=None, attach=True, context=None):
378 """This function Processes email and create record for given OpenERP model
379 @param self: The object pointer
380 @param cr: the current row, from the database cursor,
381 @param uid: the current user’s ID for security checks,
382 @param model: OpenObject Model
383 @param message: Email details, passed as a string or an xmlrpclib.Binary
384 @param attach: Email attachments
385 @param context: A standard dictionary for contextual values"""
387 # extract message bytes, we are forced to pass the message as binary because
388 # we don't know its encoding until we parse its headers and hence can't
389 # convert it to utf-8 for transport between the mailgate script and here.
390 if isinstance(message, xmlrpclib.Binary):
391 message = str(message.data)
396 if custom_values is None or not isinstance(custom_values, dict):
399 model_pool = self.pool.get(model)
402 # Create New Record into particular model
403 def create_record(msg):
405 if hasattr(model_pool, 'message_new'):
406 res_id = model_pool.message_new(cr, uid, msg, context=context)
408 model_pool.write(cr, uid, [res_id], custom_values, context=context)
411 'name': msg.get('subject'),
412 'email_from': msg.get('from'),
413 'email_cc': msg.get('cc'),
415 'description': msg.get('body'),
418 data.update(self.get_partner(cr, uid, msg.get('from'), context=context))
419 res_id = model_pool.create(cr, uid, data, context=context)
422 for attachment in msg.get('attachments', []):
425 'datas': binascii.b2a_base64(str(attachments.get(attachment))),
426 'datas_fname': attachment,
427 'description': 'Mail attachment',
431 att_ids.append(self.pool.get('ir.attachment').create(cr, uid, data_attach))
433 return res_id, att_ids
435 # Warning: message_from_string doesn't always work correctly on unicode,
436 # we must use utf-8 strings here :-(
437 if isinstance(message, unicode):
438 message = message.encode('utf-8')
439 msg_txt = email.message_from_string(message)
440 message_id = msg_txt.get('message-id', False)
444 # Very unusual situation, be we should be fault-tolerant here
445 message_id = time.time()
446 msg_txt['message-id'] = message_id
447 _logger.info('Message without message-id, generating a random one: %s', message_id)
449 fields = msg_txt.keys()
450 msg['id'] = message_id
451 msg['message-id'] = message_id
453 if 'Subject' in fields:
454 msg['subject'] = self._decode_header(msg_txt.get('Subject'))
456 if 'Content-Type' in fields:
457 msg['content-type'] = msg_txt.get('Content-Type')
460 msg['from'] = self._decode_header(msg_txt.get('From'))
462 if 'Delivered-To' in fields:
463 msg['to'] = self._decode_header(msg_txt.get('Delivered-To'))
466 msg['cc'] = self._decode_header(msg_txt.get('CC'))
468 if 'Reply-to' in fields:
469 msg['reply'] = self._decode_header(msg_txt.get('Reply-To'))
472 msg['date'] = self._decode_header(msg_txt.get('Date'))
474 if 'Content-Transfer-Encoding' in fields:
475 msg['encoding'] = msg_txt.get('Content-Transfer-Encoding')
477 if 'References' in fields:
478 msg['references'] = msg_txt.get('References')
480 if 'In-Reply-To' in fields:
481 msg['in-reply-to'] = msg_txt.get('In-Reply-To')
483 if 'X-Priority' in fields:
484 msg['priority'] = msg_txt.get('X-Priority', '3 (Normal)').split(' ')[0]
486 if not msg_txt.is_multipart() or 'text/plain' in msg.get('Content-Type', ''):
487 encoding = msg_txt.get_content_charset()
488 body = msg_txt.get_payload(decode=True)
489 if 'text/html' in msg_txt.get('Content-Type', ''):
490 body = tools.html2plaintext(body)
491 msg['body'] = tools.ustr(body, encoding)
494 has_plain_text = False
495 if msg_txt.is_multipart() or 'multipart/alternative' in msg.get('content-type', ''):
497 for part in msg_txt.walk():
498 if part.get_content_maintype() == 'multipart':
501 encoding = part.get_content_charset()
502 filename = part.get_filename()
503 if part.get_content_maintype()=='text':
504 content = part.get_payload(decode=True)
506 attachments[filename] = content
507 elif not has_plain_text:
508 # main content parts should have 'text' maintype
509 # and no filename. we ignore the html part if
510 # there is already a plaintext part without filename,
511 # because presumably these are alternatives.
512 content = tools.ustr(content, encoding)
513 if part.get_content_subtype() == 'html':
514 body = tools.ustr(tools.html2plaintext(content))
515 elif part.get_content_subtype() == 'plain':
517 has_plain_text = True
518 elif part.get_content_maintype() in ('application', 'image'):
520 attachments[filename] = part.get_payload(decode=True)
522 res = part.get_payload(decode=True)
523 body += tools.ustr(res, encoding)
526 msg['attachments'] = attachments
530 if msg.get('references') or msg.get('in-reply-to'):
531 references = msg.get('references') or msg.get('in-reply-to')
532 if '\r\n' in references:
533 references = references.split('\r\n')
535 references = references.split(' ')
536 for ref in references:
538 res_id = tools.misc.reference_re.search(ref)
540 res_id = res_id.group(1)
542 res_id = tools.misc.res_re.search(msg['subject'])
544 res_id = res_id.group(1)
547 model_pool = self.pool.get(model)
548 if model_pool.exists(cr, uid, res_id):
549 res_ids.append(res_id)
550 if hasattr(model_pool, 'message_update'):
551 model_pool.message_update(cr, uid, [res_id], {}, msg, context=context)
553 raise NotImplementedError('model %s does not support updating records, mailgate API method message_update() is missing'%model)
556 new_res_id, attachment_ids = create_record(msg)
557 res_ids = [new_res_id]
560 context.update({'model' : model})
561 if hasattr(model_pool, 'history'):
562 model_pool.history(cr, uid, res_ids, _('receive'), history=True,
563 subject = msg.get('subject'),
564 email = msg.get('to'),
565 details = msg.get('body'),
566 email_from = msg.get('from'),
567 email_cc = msg.get('cc'),
568 message_id = msg.get('message-id'),
569 references = msg.get('references', False) or msg.get('in-reply-to', False),
570 attach = attachments.items(),
571 email_date = msg.get('date'),
574 self.history(cr, uid, model, res_ids, msg, attachment_ids, context=context)
575 self.email_forward(cr, uid, model, res_ids, msg_txt)
578 def get_partner(self, cr, uid, from_email, context=None):
579 """This function returns partner Id based on email passed
580 @param self: The object pointer
581 @param cr: the current row, from the database cursor,
582 @param uid: the current user’s ID for security checks
583 @param from_email: email address based on that function will search for the correct
585 address_pool = self.pool.get('res.partner.address')
587 'partner_address_id': False,
590 from_email = self.to_email(from_email)[0]
591 address_ids = address_pool.search(cr, uid, [('email', 'like', from_email)])
593 address = address_pool.browse(cr, uid, address_ids[0])
594 res['partner_address_id'] = address_ids[0]
595 res['partner_id'] = address.partner_id.id
601 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: