forked from Vauxoo/odoo
/
mail_thread.py
2979 lines (2629 loc) · 153 KB
/
mail_thread.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import datetime
import dateutil
import email
import hashlib
import hmac
import lxml
import logging
import pytz
import re
import socket
import time
import threading
try:
from xmlrpc import client as xmlrpclib
except ImportError:
import xmlrpclib
from collections import namedtuple
from email import message_from_string, policy
from email.message import Message
from lxml import etree
from werkzeug import url_encode
from werkzeug import urls
from odoo import _, api, exceptions, fields, models, tools, registry, SUPERUSER_ID
from odoo.osv import expression
from odoo.tools import pycompat, ustr
from odoo.tools.misc import clean_context, split_every
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
class MailThread(models.AbstractModel):
''' mail_thread model is meant to be inherited by any model that needs to
act as a discussion topic on which messages can be attached. Public
methods are prefixed with ``message_`` in order to avoid name
collisions with methods of the models that will inherit from this class.
``mail.thread`` defines fields used to handle and display the
communication history. ``mail.thread`` also manages followers of
inheriting classes. All features and expected behavior are managed
by mail.thread. Widgets has been designed for the 7.0 and following
versions of Odoo.
Inheriting classes are not required to implement any method, as the
default implementation will work for any model. However it is common
to override at least the ``message_new`` and ``message_update``
methods (calling ``super``) to add model-specific behavior at
creation and update of a thread when processing incoming emails.
Options:
- _mail_flat_thread: if set to True, all messages without parent_id
are automatically attached to the first message posted on the
ressource. If set to False, the display of Chatter is done using
threads, and no parent_id is automatically set.
MailThread features can be somewhat controlled through context keys :
- ``mail_create_nosubscribe``: at create or message_post, do not subscribe
uid to the record thread
- ``mail_create_nolog``: at create, do not log the automatic '<Document>
created' message
- ``mail_notrack``: at create and write, do not perform the value tracking
creating messages
- ``tracking_disable``: at create and write, perform no MailThread features
(auto subscription, tracking, post, ...)
- ``mail_notify_force_send``: if less than 50 email notifications to send,
send them directly instead of using the queue; True by default
'''
_name = 'mail.thread'
_description = 'Email Thread'
_mail_flat_thread = True # flatten the discussino history
_mail_post_access = 'write' # access required on the document to post on it
_Attachment = namedtuple('Attachment', ('fname', 'content', 'info'))
message_is_follower = fields.Boolean(
'Is Follower', compute='_compute_is_follower', search='_search_is_follower')
message_follower_ids = fields.One2many(
'mail.followers', 'res_id', string='Followers')
message_partner_ids = fields.Many2many(
comodel_name='res.partner', string='Followers (Partners)',
compute='_get_followers', search='_search_follower_partners')
message_channel_ids = fields.Many2many(
comodel_name='mail.channel', string='Followers (Channels)',
compute='_get_followers', search='_search_follower_channels')
message_ids = fields.One2many(
'mail.message', 'res_id', string='Messages',
domain=lambda self: [('message_type', '!=', 'user_notification')], auto_join=True)
message_unread = fields.Boolean(
'Unread Messages', compute='_get_message_unread',
help="If checked, new messages require your attention.")
message_unread_counter = fields.Integer(
'Unread Messages Counter', compute='_get_message_unread',
help="Number of unread messages")
message_needaction = fields.Boolean(
'Action Needed', compute='_get_message_needaction', search='_search_message_needaction',
help="If checked, new messages require your attention.")
message_needaction_counter = fields.Integer(
'Number of Actions', compute='_get_message_needaction',
help="Number of messages which requires an action")
message_has_error = fields.Boolean(
'Message Delivery error', compute='_compute_message_has_error', search='_search_message_has_error',
help="If checked, some messages have a delivery error.")
message_has_error_counter = fields.Integer(
'Number of errors', compute='_compute_message_has_error',
help="Number of messages with delivery error")
message_attachment_count = fields.Integer('Attachment Count', compute='_compute_message_attachment_count', groups="base.group_user")
message_main_attachment_id = fields.Many2one(string="Main Attachment", comodel_name='ir.attachment', index=True, copy=False)
@api.depends('message_follower_ids')
def _get_followers(self):
for thread in self:
thread.message_partner_ids = thread.message_follower_ids.mapped('partner_id')
thread.message_channel_ids = thread.message_follower_ids.mapped('channel_id')
@api.model
def _search_follower_partners(self, operator, operand):
"""Search function for message_follower_ids
Do not use with operator 'not in'. Use instead message_is_followers
"""
# TOFIX make it work with not in
assert operator != "not in", "Do not search message_follower_ids with 'not in'"
followers = self.env['mail.followers'].sudo().search([
('res_model', '=', self._name),
('partner_id', operator, operand)])
# using read() below is much faster than followers.mapped('res_id')
return [('id', 'in', [res['res_id'] for res in followers.read(['res_id'])])]
@api.model
def _search_follower_channels(self, operator, operand):
"""Search function for message_follower_ids
Do not use with operator 'not in'. Use instead message_is_followers
"""
# TOFIX make it work with not in
assert operator != "not in", "Do not search message_follower_ids with 'not in'"
followers = self.env['mail.followers'].sudo().search([
('res_model', '=', self._name),
('channel_id', operator, operand)])
# using read() below is much faster than followers.mapped('res_id')
return [('id', 'in', [res['res_id'] for res in followers.read(['res_id'])])]
@api.depends('message_follower_ids')
def _compute_is_follower(self):
followers = self.env['mail.followers'].sudo().search([
('res_model', '=', self._name),
('res_id', 'in', self.ids),
('partner_id', '=', self.env.user.partner_id.id),
])
# using read() below is much faster than followers.mapped('res_id')
following_ids = [res['res_id'] for res in followers.read(['res_id'])]
for record in self:
record.message_is_follower = record.id in following_ids
@api.model
def _search_is_follower(self, operator, operand):
followers = self.env['mail.followers'].sudo().search([
('res_model', '=', self._name),
('partner_id', '=', self.env.user.partner_id.id),
])
# Cases ('message_is_follower', '=', True) or ('message_is_follower', '!=', False)
if (operator == '=' and operand) or (operator == '!=' and not operand):
# using read() below is much faster than followers.mapped('res_id')
return [('id', 'in', [res['res_id'] for res in followers.read(['res_id'])])]
else:
# using read() below is much faster than followers.mapped('res_id')
return [('id', 'not in', [res['res_id'] for res in followers.read(['res_id'])])]
def _get_message_unread(self):
partner_id = self.env.user.partner_id.id
res = dict.fromkeys(self.ids, 0)
if self.ids:
# search for unread messages, directly in SQL to improve performances
self._cr.execute(""" SELECT msg.res_id FROM mail_message msg
RIGHT JOIN mail_message_mail_channel_rel rel
ON rel.mail_message_id = msg.id
RIGHT JOIN mail_channel_partner cp
ON (cp.channel_id = rel.mail_channel_id AND cp.partner_id = %s AND
(cp.seen_message_id IS NULL OR cp.seen_message_id < msg.id))
WHERE msg.model = %s AND msg.res_id = ANY(%s) AND
msg.message_type != 'user_notification' AND
(msg.author_id IS NULL OR msg.author_id != %s) AND
(msg.message_type not in ('notification', 'user_notification') OR msg.model != 'mail.channel')""",
(partner_id, self._name, list(self.ids), partner_id,))
for result in self._cr.fetchall():
res[result[0]] += 1
for record in self:
record.message_unread_counter = res.get(record._origin.id, 0)
record.message_unread = bool(record.message_unread_counter)
def _get_message_needaction(self):
res = dict.fromkeys(self.ids, 0)
if self.ids:
# search for unread messages, directly in SQL to improve performances
self._cr.execute(""" SELECT msg.res_id FROM mail_message msg
RIGHT JOIN mail_message_res_partner_needaction_rel rel
ON rel.mail_message_id = msg.id AND rel.res_partner_id = %s AND (rel.is_read = false OR rel.is_read IS NULL)
WHERE msg.model = %s AND msg.res_id in %s AND msg.message_type != 'user_notification'""",
(self.env.user.partner_id.id, self._name, tuple(self.ids),))
for result in self._cr.fetchall():
res[result[0]] += 1
for record in self:
record.message_needaction_counter = res.get(record._origin.id, 0)
record.message_needaction = bool(record.message_needaction_counter)
@api.model
def _search_message_needaction(self, operator, operand):
return [('message_ids.needaction', operator, operand)]
def _compute_message_has_error(self):
res = {}
if self.ids:
self._cr.execute(""" SELECT msg.res_id, COUNT(msg.res_id) FROM mail_message msg
RIGHT JOIN mail_message_res_partner_needaction_rel rel
ON rel.mail_message_id = msg.id AND rel.notification_status in ('exception','bounce')
WHERE msg.author_id = %s AND msg.model = %s AND msg.res_id in %s AND msg.message_type != 'user_notification'
GROUP BY msg.res_id""",
(self.env.user.partner_id.id, self._name, tuple(self.ids),))
res.update(self._cr.fetchall())
for record in self:
record.message_has_error_counter = res.get(record._origin.id, 0)
record.message_has_error = bool(record.message_has_error_counter)
@api.model
def _search_message_has_error(self, operator, operand):
return ['&', ('message_ids.has_error', operator, operand), ('message_ids.author_id', '=', self.env.user.partner_id.id)]
def _compute_message_attachment_count(self):
read_group_var = self.env['ir.attachment'].read_group([('res_id', 'in', self.ids), ('res_model', '=', self._name)],
fields=['res_id'],
groupby=['res_id'])
attachment_count_dict = dict((d['res_id'], d['res_id_count']) for d in read_group_var)
for record in self:
record.message_attachment_count = attachment_count_dict.get(record.id, 0)
# ------------------------------------------------------
# CRUD overrides for automatic subscription and logging
# ------------------------------------------------------
@api.model_create_multi
def create(self, vals_list):
""" Chatter override :
- subscribe uid
- subscribe followers of parent
- log a creation message
"""
if self._context.get('tracking_disable'):
return super(MailThread, self).create(vals_list)
# subscribe uid unless asked not to
if not self._context.get('mail_create_nosubscribe'):
default_followers = self.env['mail.followers']._add_default_followers(self._name, [], self.env.user.partner_id.ids, customer_ids=[])[0][0]
for values in vals_list:
message_follower_ids = values.get('message_follower_ids') or []
message_follower_ids += [(0, 0, fol_vals) for fol_vals in default_followers]
values['message_follower_ids'] = message_follower_ids
threads = super(MailThread, self).create(vals_list)
# auto_subscribe: take values and defaults into account
create_values_list = {}
for thread, values in zip(threads, vals_list):
create_values = dict(values)
for key, val in self._context.items():
if key.startswith('default_') and key[8:] not in create_values:
create_values[key[8:]] = val
thread._message_auto_subscribe(create_values, followers_existing_policy='update')
create_values_list[thread.id] = create_values
# automatic logging unless asked not to (mainly for various testing purpose)
if not self._context.get('mail_create_nolog'):
threads_no_subtype = self.env[self._name]
for thread in threads:
body = thread._get_creation_message()
subtype = thread._creation_subtype()
if subtype: # if we have a subtype, post message to notify users from _message_auto_subscribe
thread.sudo().message_post(body=body, subtype_id=subtype.id, author_id=self.env.user.partner_id.id)
else:
threads_no_subtype += thread
if threads_no_subtype:
threads_no_subtype._message_log_batch(bodies={t.id: body for t in threads_no_subtype})
# post track template if a tracked field changed
if not self._context.get('mail_notrack'):
track_threads = threads.with_lang()
tracked_fields = self._get_tracked_fields()
for thread in track_threads:
create_values = create_values_list[thread.id]
changes = [field for field in tracked_fields if create_values.get(field)]
# based on tracked field to stay consistent with write
# we don't consider that a falsy field is a change, to stay consistent with previous implementation,
# but we may want to change that behaviour later.
thread._message_track_post_template(changes)
return threads
def write(self, values):
if self._context.get('tracking_disable'):
return super(MailThread, self).write(values)
# Track initial values of tracked fields
track_self = self.with_lang()
tracked_fields = None
if not self._context.get('mail_notrack'):
tracked_fields = track_self._get_tracked_fields()
if tracked_fields:
initial_values = dict((record.id, dict((key, getattr(record, key)) for key in tracked_fields))
for record in track_self)
# Perform write
result = super(MailThread, self).write(values)
# update followers
self._message_auto_subscribe(values)
# Perform the tracking
if tracked_fields:
tracking = track_self.with_context(clean_context(self._context)).message_track(tracked_fields, initial_values)
if any(change for rec_id, (change, tracking_value_ids) in tracking.items()):
(changes, tracking_value_ids) = tracking[track_self[0].id]
track_self._message_track_post_template(changes)
return result
def unlink(self):
""" Override unlink to delete messages and followers. This cannot be
cascaded, because link is done through (res_model, res_id). """
if not self:
return True
self.env['mail.message'].search([('model', '=', self._name), ('res_id', 'in', self.ids)]).sudo().unlink()
res = super(MailThread, self).unlink()
self.env['mail.followers'].sudo().search(
[('res_model', '=', self._name), ('res_id', 'in', self.ids)]
).unlink()
return res
def copy_data(self, default=None):
# avoid tracking multiple temporary changes during copy
return super(MailThread, self.with_context(mail_notrack=True)).copy_data(default=default)
@api.model
def get_empty_list_help(self, help):
""" Override of BaseModel.get_empty_list_help() to generate an help message
that adds alias information. """
model = self._context.get('empty_list_help_model')
res_id = self._context.get('empty_list_help_id')
catchall_domain = self.env['ir.config_parameter'].sudo().get_param("mail.catchall.domain")
document_name = self._context.get('empty_list_help_document_name', _('document'))
nothing_here = not help
alias = None
if catchall_domain and model and res_id: # specific res_id -> find its alias (i.e. section_id specified)
record = self.env[model].sudo().browse(res_id)
# check that the alias effectively creates new records
if record.alias_id and record.alias_id.alias_name and \
record.alias_id.alias_model_id and \
record.alias_id.alias_model_id.model == self._name and \
record.alias_id.alias_force_thread_id == 0:
alias = record.alias_id
if not alias and catchall_domain and model: # no res_id or res_id not linked to an alias -> generic help message, take a generic alias of the model
Alias = self.env['mail.alias']
aliases = Alias.search([
("alias_parent_model_id.model", "=", model),
("alias_name", "!=", False),
('alias_force_thread_id', '=', False),
('alias_parent_thread_id', '=', False)], order='id ASC')
if aliases and len(aliases) == 1:
alias = aliases[0]
if alias:
email_link = "<a href='mailto:%(email)s'>%(email)s</a>" % {'email': alias.display_name}
if nothing_here:
return "<p class='o_view_nocontent_smiling_face'>%(dyn_help)s</p>" % {
'dyn_help': _("Add a new %(document)s or send an email to %(email_link)s") % {
'document': document_name,
'email_link': email_link
}
}
# do not add alias two times if it was added previously
if "oe_view_nocontent_alias" not in help:
return "%(static_help)s<p class='oe_view_nocontent_alias'>%(dyn_help)s</p>" % {
'static_help': help,
'dyn_help': _("Create a new %(document)s by sending an email to %(email_link)s") % {
'document': document_name,
'email_link': email_link,
}
}
if nothing_here:
return "<p class='o_view_nocontent_smiling_face'>%(dyn_help)s</p>" % {
'dyn_help': _("Create a new %(document)s") % {
'document': document_name,
}
}
return help
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(MailThread, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
if view_type == 'form':
doc = etree.XML(res['arch'])
for node in doc.xpath("//field[@name='message_ids']"):
# the 'Log a note' button is employee only
options = safe_eval(node.get('options', '{}'))
is_employee = self.env.user.has_group('base.group_user')
options['display_log_button'] = is_employee
# save options on the node
node.set('options', repr(options))
res['arch'] = etree.tostring(doc, encoding='unicode')
return res
# ------------------------------------------------------
# Technical methods / wrappers / tools
# ------------------------------------------------------
def with_lang(self):
if not self._context.get("lang"):
return self.with_context(lang=self.env.user.lang)
return self
def _replace_local_links(self, html, base_url=None):
""" Replace local links by absolute links. It is required in various
cases, for example when sending emails on chatter or sending mass
mailings. It replaces
* href of links (mailto will not match the regex)
* src of images (base64 hardcoded data will not match the regex)
* styling using url like background-image: url
It is done using regex because it is shorten than using an html parser
to create a potentially complex soupe and hope to have a result that
has not been harmed.
"""
if not html:
return html
html = ustr(html)
def _sub_relative2absolute(match):
# compute here to do it only if really necessary + cache will ensure it is done only once
# if not base_url
if not _sub_relative2absolute.base_url:
_sub_relative2absolute.base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
return match.group(1) + urls.url_join(_sub_relative2absolute.base_url, match.group(2))
_sub_relative2absolute.base_url = base_url
html = re.sub(r"""(<img(?=\s)[^>]*\ssrc=")(/[^/][^"]+)""", _sub_relative2absolute, html)
html = re.sub(r"""(<a(?=\s)[^>]*\shref=")(/[^/][^"]+)""", _sub_relative2absolute, html)
html = re.sub(r"""(<[^>]+\bstyle="[^"]+\burl\('?)(/[^/'][^'")]+)""", _sub_relative2absolute, html)
return html
@api.model
def _garbage_collect_attachments(self):
""" Garbage collect lost mail attachments. Those are attachments
- linked to res_model 'mail.compose.message', the composer wizard
- with res_id 0, because they were created outside of an existing
wizard (typically user input through Chatter or reports
created on-the-fly by the templates)
- unused since at least one day (create_date and write_date)
"""
limit_date = datetime.datetime.utcnow() - datetime.timedelta(days=1)
limit_date_str = datetime.datetime.strftime(limit_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
self.env['ir.attachment'].search([
('res_model', '=', 'mail.compose.message'),
('res_id', '=', 0),
('create_date', '<', limit_date_str),
('write_date', '<', limit_date_str)]
).unlink()
return True
@api.model
def get_mail_message_access(self, res_ids, operation, model_name=None):
""" mail.message check permission rules for related document. This method is
meant to be inherited in order to implement addons-specific behavior.
A common behavior would be to allow creating messages when having read
access rule on the document, for portal document such as issues. """
DocModel = self.env[model_name] if model_name else self
create_allow = getattr(DocModel, '_mail_post_access', 'write')
if operation in ['write', 'unlink']:
check_operation = 'write'
elif operation == 'create' and create_allow in ['create', 'read', 'write', 'unlink']:
check_operation = create_allow
elif operation == 'create':
check_operation = 'write'
else:
check_operation = operation
return check_operation
def message_change_thread(self, new_thread):
"""
Transfer the list of the mail thread messages from an model to another
:param id : the old res_id of the mail.message
:param new_res_id : the new res_id of the mail.message
:param new_model : the name of the new model of the mail.message
Example : my_lead.message_change_thread(my_project_task)
will transfer the context of the thread of my_lead to my_project_task
"""
self.ensure_one()
# get the subtype of the comment Message
subtype_comment = self.env['ir.model.data'].xmlid_to_res_id('mail.mt_comment')
# get the ids of the comment and not-comment of the thread
# TDE check: sudo on mail.message, to be sure all messages are moved ?
MailMessage = self.env['mail.message']
msg_comment = MailMessage.search([
('model', '=', self._name),
('res_id', '=', self.id),
('message_type', '!=', 'user_notification'),
('subtype_id', '=', subtype_comment)])
msg_not_comment = MailMessage.search([
('model', '=', self._name),
('res_id', '=', self.id),
('message_type', '!=', 'user_notification'),
('subtype_id', '!=', subtype_comment)])
# update the messages
msg_comment.write({"res_id": new_thread.id, "model": new_thread._name})
msg_not_comment.write({"res_id": new_thread.id, "model": new_thread._name, "subtype_id": None})
return True
# ------------------------------------------------------
# Automatic log / Tracking
# ------------------------------------------------------
@api.model
def _get_tracked_fields(self):
""" Return a structure of tracked fields for the current model.
:return dict: a dict mapping field name to description, containing on_change fields
"""
tracked_fields = []
for name, field in self._fields.items():
tracking = getattr(field, 'tracking', None) or getattr(field, 'track_visibility', None)
if tracking:
tracked_fields.append(name)
if tracked_fields:
return self.fields_get(tracked_fields)
return {}
def _creation_subtype(self):
""" Give the subtypes triggered by the creation of a record
:returns: a subtype browse record (empty if no subtype is triggered)
"""
return self.env['mail.message.subtype']
def _get_creation_message(self):
""" Get the creation message to log into the chatter at the record's creation.
:returns: The message's body to log.
"""
self.ensure_one()
doc_name = self.env['ir.model']._get(self._name).name
return _('%s created') % doc_name
def _track_subtype(self, init_values):
""" Give the subtypes triggered by the changes on the record according
to values that have been updated.
:param init_values: the original values of the record; only modified fields
are present in the dict
:type init_values: dict
:returns: a subtype browse record or False if no subtype is trigerred
"""
return False
def _track_template(self, changes):
return dict()
def _message_track_post_template(self, changes):
if not changes:
return True
# Clean the context to get rid of residual default_* keys
# that could cause issues afterward during the mail.message
# generation. Example: 'default_parent_id' would refer to
# the parent_id of the current record that was used during
# its creation, but could refer to wrong parent message id,
# leading to a traceback in case the related message_id
# doesn't exist
self = self.with_context(clean_context(self._context))
templates = self._track_template(changes)
for field_name, (template, post_kwargs) in templates.items():
if not template:
continue
if isinstance(template, str):
self.message_post_with_view(template, **post_kwargs)
else:
self.message_post_with_template(template.id, **post_kwargs)
return True
def _message_track(self, tracked_fields, initial):
""" For a given record, fields to check (tuple column name, column info)
and initial values, return a structure that is a tuple containing :
- a set of updated column names
- a list of ORM (0, 0, values) commands to create 'mail.tracking.value' """
self.ensure_one()
changes = set() # contains onchange tracked fields that changed
tracking_value_ids = []
# generate tracked_values data structure: {'col_name': {col_info, new_value, old_value}}
for col_name, col_info in tracked_fields.items():
initial_value = initial[col_name]
new_value = self[col_name]
if new_value != initial_value and (new_value or initial_value): # because browse null != False
tracking_sequence = getattr(self._fields[col_name], 'tracking',
getattr(self._fields[col_name], 'track_sequence', 100)) # backward compatibility with old parameter name
if tracking_sequence is True:
tracking_sequence = 100
tracking = self.env['mail.tracking.value'].create_tracking_values(initial_value, new_value, col_name, col_info, tracking_sequence)
if tracking:
tracking_value_ids.append([0, 0, tracking])
changes.add(col_name)
return changes, tracking_value_ids
def message_track(self, tracked_fields, initial_values):
""" Track updated values. Comparing the initial and current values of
the fields given in tracked_fields, it generates a message containing
the updated values. This message can be linked to a mail.message.subtype
given by the ``_track_subtype`` method. """
if not tracked_fields:
return True
tracking = dict()
for record in self:
tracking[record.id] = record._message_track(tracked_fields, initial_values[record.id])
for record in self:
changes, tracking_value_ids = tracking[record.id]
if not changes:
continue
# find subtypes and post messages or log if no subtype found
subtype = False
# By passing this key, that allows to let the subtype empty and so don't sent email because partners_to_notify from mail_message._notify will be empty
if not self._context.get('mail_track_log_only'):
subtype = record._track_subtype(dict((col_name, initial_values[record.id][col_name]) for col_name in changes))
if subtype:
if not subtype.exists():
_logger.debug('subtype "%s" not found' % subtype.name)
continue
record.message_post(subtype_id=subtype.id, tracking_value_ids=tracking_value_ids)
elif tracking_value_ids:
record._message_log(tracking_value_ids=tracking_value_ids)
return tracking
# ------------------------------------------------------
# Mail gateway
# ------------------------------------------------------
def _routing_warn(self, error_message, message_id, route, raise_exception=True):
""" Tools method used in _routing_check_route: whether to log a warning or raise an error """
short_message = _("Mailbox unavailable - %s") % error_message
full_message = ('Routing mail with Message-Id %s: route %s: %s' %
(message_id, route, error_message))
_logger.info(full_message)
if raise_exception:
# sender should not see private diagnostics info, just the error
raise ValueError(short_message)
def _routing_create_bounce_email(self, email_from, body_html, message, **mail_values):
bounce_to = tools.decode_message_header(message, 'Return-Path') or email_from
bounce_mail_values = {
'body_html': body_html,
'subject': 'Re: %s' % message.get('subject'),
'email_to': bounce_to,
'auto_delete': True,
}
bounce_from = self.env['ir.mail_server']._get_default_bounce_address()
if bounce_from:
bounce_mail_values['email_from'] = 'MAILER-DAEMON <%s>' % bounce_from
bounce_mail_values.update(mail_values)
self.env['mail.mail'].create(bounce_mail_values).send()
@api.model
def _routing_handle_bounce(self, email_message, message_dict):
""" Handle bounce of incoming email. Based on values of the bounce (email
and related partner, send message and its messageID)
* find blacklist-enabled records with email_normalized = bounced email
and call ``_message_receive_bounce`` on each of them to propagate
bounce information through various records linked to same email;
* if not already done (i.e. if original record is not blacklist enabled
like a bounce on an applicant), find record linked to bounced message
and call ``_message_receive_bounce``;
:param email_message: incoming email;
:type email_message: email.message;
:param message_dict: dictionary holding already-parsed values and in
which bounce-related values will be added;
:type message_dict: dictionary;
"""
bounced_record, bounced_record_done = False, False
bounced_email, bounced_partner = message_dict['bounced_email'], message_dict['bounced_partner']
bounced_msg_id, bounced_message = message_dict['bounced_msg_id'], message_dict['bounced_message']
if bounced_email:
bounced_model, bounced_res_id = bounced_message.model, bounced_message.res_id
if bounced_model and bounced_model in self.env and bounced_res_id:
bounced_record = self.env[bounced_model].sudo().browse(bounced_res_id).exists()
bl_models = self.env['ir.model'].sudo().search(['&', ('is_mail_blacklist', '=', True), ('model', '!=', 'mail.thread.blacklist')])
for model in [bl_model for bl_model in bl_models if bl_model.model in self.env]: # transient test mode
rec_bounce_w_email = self.env[model.model].sudo().search([('email_normalized', '=', bounced_email)])
rec_bounce_w_email._message_receive_bounce(bounced_email, bounced_partner)
bounced_record_done = bool(bounced_record and model.model == bounced_model and bounced_record in rec_bounce_w_email)
# set record as bounced unless already done due to blacklist mixin
if bounced_record and not bounced_record_done and issubclass(type(bounced_record), self.pool['mail.thread']):
bounced_record._message_receive_bounce(bounced_email, bounced_partner)
if bounced_partner and bounced_message:
self.env['mail.notification'].sudo().search([
('mail_message_id', '=', bounced_message.id),
('res_partner_id', 'in', bounced_partner.ids)]
).write({'notification_status': 'bounce'})
if bounced_record:
_logger.info('Routing mail from %s to %s with Message-Id %s: not routing bounce email from %s replying to %s (model %s ID %s)',
message_dict['email_from'], message_dict['to'], message_dict['message_id'], bounced_email, bounced_msg_id, bounced_model, bounced_res_id)
elif bounced_email:
_logger.info('Routing mail from %s to %s with Message-Id %s: not routing bounce email from %s replying to %s (no document found)',
message_dict['email_from'], message_dict['to'], message_dict['message_id'], bounced_email, bounced_msg_id)
else:
_logger.info('Routing mail from %s to %s with Message-Id %s: not routing bounce email.',
message_dict['email_from'], message_dict['to'], message_dict['message_id'])
@api.model
def _routing_check_route(self, message, message_dict, route, raise_exception=True):
""" Verify route validity. Check and rules:
1 - if thread_id -> check that document effectively exists; otherwise
fallback on a message_new by resetting thread_id
2 - check that message_update exists if thread_id is set; or at least
that message_new exist
[ - find author_id if udpate_author is set]
3 - if there is an alias, check alias_contact:
'followers' and thread_id:
check on target document that the author is in the followers
'followers' and alias_parent_thread_id:
check on alias parent document that the author is in the
followers
'partners': check that author_id id set
:param message: an email.message instance
:param message_dict: dictionary of values that will be given to
mail_message.create()
:param route: route to check which is a tuple (model, thread_id,
custom_values, uid, alias)
:param raise_exception: if an error occurs, tell whether to raise an error
or just log a warning and try other processing or
invalidate route
"""
assert isinstance(route, (list, tuple)), 'A route should be a list or a tuple'
assert len(route) == 5, 'A route should contain 5 elements: model, thread_id, custom_values, uid, alias record'
message_id = message_dict['message_id']
email_from = message_dict['email_from']
author_id = message_dict.get('author_id')
model, thread_id, alias = route[0], route[1], route[4]
record_set = None
_generic_bounce_body_html = """<div>
<p>Hello,</p>
<p>The following email sent to {to} cannot be accepted because this is a private email address.
Only allowed people can contact us at this address.</p>
</div><blockquote>{body}</blockquote>"""
# Wrong model
if not model:
self._routing_warn(_('target model unspecified'), message_id, route, raise_exception)
return ()
elif model not in self.env:
self._routing_warn(_('unknown target model %s') % model, message_id, route, raise_exception)
return ()
record_set = self.env[model].browse(thread_id) if thread_id else self.env[model]
# Existing Document: check if exists and model accepts the mailgateway; if not, fallback on create if allowed
if thread_id:
if not record_set.exists():
self._routing_warn(_('reply to missing document (%s,%s), fall back on document creation') % (model, thread_id), message_id, route, False)
thread_id = None
elif not hasattr(record_set, 'message_update'):
self._routing_warn(_('reply to model %s that does not accept document update, fall back on document creation') % model, message_id, route, False)
thread_id = None
# New Document: check model accepts the mailgateway
if not thread_id and model and not hasattr(record_set, 'message_new'):
self._routing_warn(_('model %s does not accept document creation') % model, message_id, route, raise_exception)
return ()
# Update message author if asked. We do it now because we need it for aliases (contact settings)
if not author_id:
if record_set:
authors = self._mail_find_partner_from_emails([email_from], records=record_set)
elif alias and alias.alias_parent_model_id and alias.alias_parent_thread_id:
records = self.env[alias.alias_parent_model_id.model].browse(alias.alias_parent_thread_id)
authors = self._mail_find_partner_from_emails([email_from], records=records)
else:
authors = self._mail_find_partner_from_emails([email_from], records=None)
if authors:
message_dict['author_id'] = authors[0].id
# Alias: check alias_contact settings
if alias:
if thread_id:
obj = record_set[0]
elif alias.alias_parent_model_id and alias.alias_parent_thread_id:
obj = self.env[alias.alias_parent_model_id.model].browse(alias.alias_parent_thread_id)
else:
obj = self.env[model]
if hasattr(obj, '_alias_check_contact'):
check_result = obj._alias_check_contact(message, message_dict, alias)
else:
check_result = self.env['mail.alias.mixin']._alias_check_contact_on_record(obj, message, message_dict, alias)
if check_result is not True:
self._routing_warn(_('alias %s: %s') % (alias.alias_name, check_result.get('error_message', _('unknown error'))), message_id, route, False)
self._routing_create_bounce_email(
email_from,
check_result.get('error_template', _generic_bounce_body_html.format(
to=alias.display_name.lower(),
body=message_dict.get('body')
)),
message
)
return False
return (model, thread_id, route[2], route[3], route[4])
@api.model
def _routing_reset_bounce(self, email_message, message_dict):
"""Called by ``message_process`` when a new mail is received from an email address.
If the email is related to a partner, we consider that the number of message_bounce
is not relevant anymore as the email is valid - as we received an email from this
address. The model is here hardcoded because we cannot know with which model the
incomming mail match. We consider that if a mail arrives, we have to clear bounce for
each model having bounce count.
:param email_from: email address that sent the incoming email."""
valid_email = message_dict['email_from']
if valid_email:
bl_models = self.env['ir.model'].sudo().search(['&', ('is_mail_blacklist', '=', True), ('model', '!=', 'mail.thread.blacklist')])
for model in [bl_model for bl_model in bl_models if bl_model.model in self.env]: # transient test mode
self.env[model.model].sudo().search([('message_bounce', '>', 0), ('email_normalized', '=', valid_email)])._message_reset_bounce(valid_email)
@api.model
def message_route(self, message, message_dict, model=None, thread_id=None, custom_values=None):
""" Attempt to figure out the correct target model, thread_id,
custom_values and user_id to use for an incoming message.
Multiple values may be returned, if a message had multiple
recipients matching existing mail.aliases, for example.
The following heuristics are used, in this order:
* if the message replies to an existing thread by having a Message-Id
that matches an existing mail_message.message_id, we take the original
message model/thread_id pair and ignore custom_value as no creation will
take place;
* look for a mail.alias entry matching the message recipients and use the
corresponding model, thread_id, custom_values and user_id. This could
lead to a thread update or creation depending on the alias;
* fallback on provided ``model``, ``thread_id`` and ``custom_values``;
* raise an exception as no route has been found
:param string message: an email.message instance
:param dict message_dict: dictionary holding parsed message variables
:param string model: the fallback model to use if the message does not match
any of the currently configured mail aliases (may be None if a matching
alias is supposed to be present)
:type dict custom_values: optional dictionary of default field values
to pass to ``message_new`` if a new record needs to be created.
Ignored if the thread record already exists, and also if a matching
mail.alias was found (aliases define their own defaults)
:param int thread_id: optional ID of the record/thread from ``model`` to
which this mail should be attached. Only used if the message does not
reply to an existing thread and does not match any mail alias.
:return: list of routes [(model, thread_id, custom_values, user_id, alias)]
:raises: ValueError, TypeError
"""
if not isinstance(message, Message):
raise TypeError('message must be an email.message.Message at this point')
catchall_alias = self.env['ir.config_parameter'].sudo().get_param("mail.catchall.alias")
bounce_alias = self.env['ir.config_parameter'].sudo().get_param("mail.bounce.alias")
bounce_alias_static = tools.str2bool(self.env['ir.config_parameter'].sudo().get_param("mail.bounce.alias.static", "False"))
fallback_model = model
# get email.message.Message variables for future processing
local_hostname = socket.gethostname()
message_id = message_dict['message_id']
# compute references to find if message is a reply to an existing thread
thread_references = message_dict['references'] or message_dict['in_reply_to']
msg_references = [
re.sub(r'[\r\n\t ]+', r'', ref) # "Unfold" buggy references
for ref in tools.mail_header_msgid_re.findall(thread_references)
if 'reply_to' not in ref
]
mail_messages = self.env['mail.message'].sudo().search([('message_id', 'in', msg_references)], limit=1, order='id desc, message_id')
is_a_reply = bool(mail_messages)
reply_model, reply_thread_id = mail_messages.model, mail_messages.res_id
# author and recipients
email_from = message_dict['email_from']
email_from_localpart = (tools.email_split(email_from) or [''])[0].split('@', 1)[0].lower()
email_to = message_dict['to']
email_to_localparts = [
e.split('@', 1)[0].lower()
for e in (tools.email_split(email_to) or [''])
]
# Delivered-To is a safe bet in most modern MTAs, but we have to fallback on To + Cc values
# for all the odd MTAs out there, as there is no standard header for the envelope's `rcpt_to` value.
rcpt_tos_localparts = [
e.split('@')[0].lower()
for e in tools.email_split(message_dict['recipients'])
]
rcpt_tos_valid_localparts = [to for to in rcpt_tos_localparts]
# 0. Handle bounce: verify whether this is a bounced email and use it to collect bounce data and update notifications for customers
# Bounce regex: typical form of bounce is bounce_alias+128-crm.lead-34@domain
# group(1) = the mail ID; group(2) = the model (if any); group(3) = the record ID
# Bounce message (not alias)
# See http://datatracker.ietf.org/doc/rfc3462/?include_text=1
# As all MTA does not respect this RFC (googlemail is one of them),
# we also need to verify if the message come from "mailer-daemon"
# If not a bounce: reset bounce information
if bounce_alias and any(email.startswith(bounce_alias) for email in email_to_localparts):
bounce_re = re.compile("%s\+(\d+)-?([\w.]+)?-?(\d+)?" % re.escape(bounce_alias), re.UNICODE)
bounce_match = bounce_re.search(email_to)
if bounce_match:
self._routing_handle_bounce(message, message_dict)
return []
if bounce_alias and bounce_alias_static and any(email == bounce_alias for email in email_to_localparts):
self._routing_handle_bounce(message, message_dict)
return []
if message.get_content_type() == 'multipart/report' or email_from_localpart == 'mailer-daemon':
self._routing_handle_bounce(message, message_dict)
return []
self._routing_reset_bounce(message, message_dict)
# 1. Handle reply
# if destination = alias with different model -> consider it is a forward and not a reply
# if destination = alias with same model -> check contact settings as they still apply
if reply_model and reply_thread_id:
other_model_aliases = self.env['mail.alias'].search([
'&', '&',
('alias_name', '!=', False),
('alias_name', 'in', email_to_localparts),
('alias_model_id.model', '!=', reply_model),
])
if other_model_aliases:
is_a_reply = False
rcpt_tos_valid_localparts = [to for to in rcpt_tos_valid_localparts if to in other_model_aliases.mapped('alias_name')]
if is_a_reply:
dest_aliases = self.env['mail.alias'].search([
('alias_name', 'in', rcpt_tos_localparts),
('alias_model_id.model', '=', reply_model)
], limit=1)
user_id = self._mail_find_user_for_gateway(email_from, alias=dest_aliases).id or self._uid
route = self._routing_check_route(
message, message_dict,
(reply_model, reply_thread_id, custom_values, user_id, dest_aliases),
raise_exception=False)
if route:
_logger.info(
'Routing mail from %s to %s with Message-Id %s: direct reply to msg: model: %s, thread_id: %s, custom_values: %s, uid: %s',
email_from, email_to, message_id, reply_model, reply_thread_id, custom_values, self._uid)
return [route]
elif route is False:
return []
# 2. Handle new incoming email by checking aliases and applying their settings
if rcpt_tos_localparts:
# no route found for a matching reference (or reply), so parent is invalid
message_dict.pop('parent_id', None)
# check it does not directly contact catchall
if catchall_alias and email_to_localparts and all(email_localpart == catchall_alias for email_localpart in email_to_localparts):