-
Notifications
You must be signed in to change notification settings - Fork 114
/
mail_thread.py
4573 lines (4031 loc) · 221 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 ast
import base64
import datetime
import dateutil
import email
import email.policy
import hashlib
import hmac
import json
import lxml
import logging
import pytz
import re
import time
import threading
from collections import namedtuple
from email.message import EmailMessage
from email import message_from_string
from lxml import etree
from werkzeug import urls
from xmlrpc import client as xmlrpclib
from markupsafe import Markup, escape
from odoo import _, api, exceptions, fields, models, tools, registry, SUPERUSER_ID, Command
from odoo.addons.mail.tools.web_push import push_to_end_point, DeviceUnreachableError
from odoo.exceptions import MissingError, AccessError
from odoo.osv import expression
from odoo.tools import (
is_html_empty, html_escape, html2plaintext, parse_contact_from_email,
clean_context, split_every, Query, SQL, email_normalize_all,
)
from requests import Session
MAX_DIRECT_PUSH = 5
_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
resource. 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 discussion history
_mail_post_access = 'write' # access required on the document to post on it
_primary_email = 'email' # Must be set for the models that can be created by alias
_Attachment = namedtuple('Attachment', ('fname', 'content', 'info'))
message_is_follower = fields.Boolean(
'Is Follower', compute='_compute_message_is_follower', search='_search_message_is_follower')
message_follower_ids = fields.One2many(
'mail.followers', 'res_id', string='Followers', groups='base.group_user')
message_partner_ids = fields.Many2many(
comodel_name='res.partner', string='Followers (Partners)',
compute='_compute_message_partner_ids',
inverse='_inverse_message_partner_ids',
search='_search_message_partner_ids',
groups='base.group_user',
)
message_ids = fields.One2many(
'mail.message', 'res_id', string='Messages',
domain=lambda self: [('message_type', '!=', 'user_notification')], auto_join=True)
has_message = fields.Boolean(compute="_compute_has_message", search="_search_has_message", store=False)
message_needaction = fields.Boolean(
'Action Needed',
compute='_compute_message_needaction', search='_search_message_needaction',
help="If checked, new messages require your attention.")
message_needaction_counter = fields.Integer(
'Number of Actions', compute='_compute_message_needaction',
help="Number of messages requiring 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")
@api.depends('message_follower_ids')
def _compute_message_partner_ids(self):
for thread in self:
thread.message_partner_ids = thread.message_follower_ids.mapped('partner_id')
def _inverse_message_partner_ids(self):
for thread in self:
new_partners_ids = thread.message_partner_ids
previous_partners_ids = thread.message_follower_ids.partner_id
removed_partners_ids = previous_partners_ids - new_partners_ids
added_patners_ids = new_partners_ids - previous_partners_ids
if added_patners_ids:
thread.message_subscribe(added_patners_ids.ids)
if removed_partners_ids:
thread.message_unsubscribe(removed_partners_ids.ids)
@api.model
def _search_message_partner_ids(self, operator, operand):
"""Search function for message_follower_ids"""
neg = ''
if operator in expression.NEGATIVE_TERM_OPERATORS:
neg = 'not '
operator = expression.TERM_OPERATORS_NEGATION[operator]
followers = self.env['mail.followers'].sudo()._search([
('res_model', '=', self._name),
('partner_id', operator, operand),
])
# use inselect to avoid reading thousands of potentially followed objects
return [('id', neg + 'inselect', followers.subselect('res_id'))]
@api.depends('message_follower_ids')
def _compute_message_is_follower(self):
followers = self.env['mail.followers'].sudo().search_fetch(
[('res_model', '=', self._name), ('res_id', 'in', self.ids), ('partner_id', '=', self.env.user.partner_id.id)],
['res_id'],
)
following_ids = set(followers.mapped('res_id'))
for record in self:
record.message_is_follower = record.id in following_ids
@api.model
def _search_message_is_follower(self, operator, operand):
followers = self.env['mail.followers'].sudo().search_fetch(
[('res_model', '=', self._name), ('partner_id', '=', self.env.user.partner_id.id)],
['res_id'],
)
# Cases ('message_is_follower', '=', True) or ('message_is_follower', '!=', False)
if (operator == '=' and operand) or (operator == '!=' and not operand):
return [('id', 'in', followers.mapped('res_id'))]
else:
return [('id', 'not in', followers.mapped('res_id'))]
def _compute_has_message(self):
self.env['mail.message'].flush_model()
self.env.cr.execute("""
SELECT distinct res_id
FROM mail_message mm
WHERE res_id = any(%s)
AND mm.model=%s
""", [self.ids, self._name])
channel_ids = {r[0] for r in self.env.cr.fetchall()}
for record in self:
record.has_message = record.id in channel_ids
def _search_has_message(self, operator, value):
if (operator == '=' and value is True) or (operator == '!=' and value is False):
operator_new = 'inselect'
else:
operator_new = 'not inselect'
return [('id', operator_new, ("SELECT res_id FROM mail_message WHERE model=%s", [self._name]))]
def _compute_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_notification 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.env.cr.execute("""
SELECT msg.res_id, COUNT(msg.res_id)
FROM mail_message msg
INNER JOIN mail_notification notif
ON notif.mail_message_id = msg.id
WHERE notif.notification_status in ('exception', 'bounce')
AND notif.author_id = %(author_id)s
AND msg.model = %(model_name)s
AND msg.res_id in %(res_ids)s
AND msg.message_type != 'user_notification'
GROUP BY msg.res_id
""", {'author_id': self.env.user.partner_id.id, 'model_name': self._name, 'res_ids': 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):
message_ids = self.env['mail.message']._search([('has_error', operator, operand), ('author_id', '=', self.env.user.partner_id.id)])
return [('message_ids', 'in', message_ids)]
def _compute_message_attachment_count(self):
read_group_var = self.env['ir.attachment']._read_group([('res_id', 'in', self.ids), ('res_model', '=', self._name)],
groupby=['res_id'],
aggregates=['__count'])
attachment_count_dict = dict(read_group_var)
for record in self:
record.message_attachment_count = attachment_count_dict.get(record.id, 0)
# ------------------------------------------------------------
# CRUD
# ------------------------------------------------------------
@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'):
threads = super(MailThread, self).create(vals_list)
threads._track_discard()
return threads
threads = super(MailThread, self).create(vals_list)
# subscribe uid unless asked not to
if not self._context.get('mail_create_nosubscribe') and threads and self.env.user.active:
self.env['mail.followers']._insert_followers(
threads._name, threads.ids,
self.env.user.partner_id.ids, subtypes=None,
customer_ids=[],
check_existing=False
)
# 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:
subtype = thread._creation_subtype()
if not subtype:
threads_no_subtype += thread
continue
# if we have a subtype, post message to notify users from _message_auto_subscribe
thread.sudo().message_post(
subtype_id=subtype.id, author_id=self.env.user.partner_id.id,
# summary="o_mail_notification" is used to hide the message body in the front-end
body=Markup('<div summary="o_mail_notification"><p>%s</p></div>') % thread._creation_message()
)
if threads_no_subtype:
bodies = dict(
(thread.id, thread._creation_message())
for thread in threads_no_subtype)
threads_no_subtype._message_log_batch(bodies=bodies)
# post track template if a tracked field changed
threads._track_discard()
if not self._context.get('mail_notrack'):
fnames = self._track_get_fields()
for thread in threads:
create_values = create_values_list[thread.id]
changes = [fname for fname in fnames if create_values.get(fname)]
# 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.
if changes:
self.env.cr.precommit.add(thread._track_post_template_finalize) # call to _track_post_template_finalize bound to this record
self.env.cr.precommit.data.setdefault(f'mail.tracking.create.{self._name}.{thread.id}', changes)
return threads
def write(self, values):
if self._context.get('tracking_disable'):
return super(MailThread, self).write(values)
if not self._context.get('mail_notrack'):
self._track_prepare(self._fields)
# Perform write
result = super(MailThread, self).write(values)
# update followers
self._message_auto_subscribe(values)
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
# discard pending tracking
self._track_discard()
self.env['mail.message'].sudo().search([('model', '=', self._name), ('res_id', 'in', self.ids)]).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_message):
""" 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')
document_name = self._context.get('empty_list_help_document_name', _('document'))
nothing_here = is_html_empty(help_message)
alias = None
# specific res_id -> find its alias (i.e. section_id specified)
if model and res_id:
record = self.env[model].sudo().browse(res_id)
# check that the alias effectively creates new records
if ('alias_id' in record and record.alias_id and
record.alias_id.alias_name and record.alias_id.alias_domain and
record.alias_id.alias_model_id.model == self._name and
record.alias_id.alias_force_thread_id == 0):
alias = record.alias_id
# no res_id or res_id not linked to an alias -> generic help message, take a generic alias of the model
if not alias and model and self.env.company.alias_domain_id:
aliases = self.env['mail.alias'].search([
("alias_domain_id", "=", self.env.company.alias_domain_id.id),
("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 = Markup("<a href='mailto:%s'>%s</a>") % (alias.display_name, alias.display_name)
if nothing_here:
dyn_help = _("Add a new %(document)s or send an email to %(email_link)s",
document=html_escape(document_name),
email_link=email_link,
)
return super().get_empty_list_help(f"<p class='o_view_nocontent_smiling_face'>{dyn_help}</p>")
# do not add alias two times if it was added previously
if "oe_view_nocontent_alias" not in help_message:
dyn_help = _("Create new %(document)s by sending an email to %(email_link)s",
document=html_escape(document_name),
email_link=email_link,
)
return super().get_empty_list_help(f"{help_message}<p class='oe_view_nocontent_alias'>{dyn_help}</p>")
if nothing_here:
dyn_help = _("Create new %(document)s", document=html_escape(document_name))
return super().get_empty_list_help(f"<p class='o_view_nocontent_smiling_face'>{dyn_help}</p>")
return super().get_empty_list_help(help_message)
def _condition_to_sql(self, alias: str, fname: str, operator: str, value, query: Query) -> SQL:
if self.env.su or self.env.user._is_internal():
return super()._condition_to_sql(alias, fname, operator, value, query)
if fname != 'message_partner_ids':
return super()._condition_to_sql(alias, fname, operator, value, query)
user_partner = self.env.user.partner_id
allow_partner_ids = set((user_partner | user_partner.commercial_partner_id).ids)
operand = value if isinstance(value, (list, tuple)) else [value]
if not allow_partner_ids.issuperset(operand):
raise AccessError("Portal users can only filter threads by themselves as followers.")
return super(MailThread, self.sudo())._condition_to_sql(alias, fname, operator, value, query)
# ------------------------------------------------------
# MODELS / CRUD HELPERS
# ------------------------------------------------------
def _compute_field_value(self, field):
if not self._context.get('tracking_disable') and not self._context.get('mail_notrack'):
self._track_prepare(f.name for f in self.pool.field_computed[field] if f.store)
return super()._compute_field_value(field)
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 _creation_message(self):
""" Get the creation message to log into the chatter at the record's creation.
:returns: The message's body to log (either plain text or markup safe html).
"""
self.ensure_one()
doc_name = self.env['ir.model']._get(self._name).name
return _('%s created', doc_name)
@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 _valid_field_parameter(self, field, name):
# allow tracking on models inheriting from 'mail.thread'
return name == 'tracking' or super()._valid_field_parameter(field, name)
def _fallback_lang(self):
if not self._context.get("lang"):
return self.with_context(lang=self.env.user.lang)
return self
def _check_can_update_message_content(self, messages):
"""" Checks that the current user can update the content of the message.
Current heuristic is
* if no tracking;
* only for user generated content;
"""
if messages.tracking_value_ids:
raise exceptions.UserError(_("Messages with tracking values cannot be modified"))
if any(message.message_type != 'comment' for message in messages):
raise exceptions.UserError(_("Only messages type comment can have their content updated"))
# ------------------------------------------------------
# TRACKING / LOG
# ------------------------------------------------------
def _track_prepare(self, fields_iter):
""" Prepare the tracking of ``fields_iter`` for ``self``.
:param iter fields_iter: iterable of fields names to potentially track
"""
fnames = self._track_get_fields().intersection(fields_iter)
if not fnames:
return
self.env.cr.precommit.add(self._track_finalize)
initial_values = self.env.cr.precommit.data.setdefault(f'mail.tracking.{self._name}', {})
for record in self:
if not record.id:
continue
values = initial_values.setdefault(record.id, {})
if values is not None:
for fname in fnames:
values.setdefault(fname, record[fname])
def _track_discard(self):
""" Prevent any tracking of fields on ``self``. """
if not self._track_get_fields():
return
self.env.cr.precommit.add(self._track_finalize)
initial_values = self.env.cr.precommit.data.setdefault(f'mail.tracking.{self._name}', {})
# disable tracking by setting initial values to None
for id_ in self.ids:
initial_values[id_] = None
def _track_filter_for_display(self, tracking_values):
"""Filter out tracking values from being displayed."""
self.ensure_one()
return tracking_values
def _track_finalize(self):
""" Generate the tracking messages for the records that have been
prepared with ``_tracking_prepare``.
"""
initial_values = self.env.cr.precommit.data.pop(f'mail.tracking.{self._name}', {})
ids = [id_ for id_, vals in initial_values.items() if vals]
if not ids:
return
records = self.browse(ids).sudo()
fnames = self._track_get_fields()
context = clean_context(self._context)
tracking = records.with_context(context)._message_track(fnames, initial_values)
for record in records:
changes, _tracking_value_ids = tracking.get(record.id, (None, None))
record._message_track_post_template(changes)
# this method is called after the main flush() and just before commit();
# we have to flush() again in case we triggered some recomputations
self.env.flush_all()
def _track_set_author(self, author):
""" Set the author of the tracking message. """
if not self._track_get_fields():
return
authors = self.env.cr.precommit.data.setdefault(f'mail.tracking.author.{self._name}', {})
for id_ in self.ids:
authors[id_] = author
def _track_post_template_finalize(self):
"""Call the tracking template method with right values from precommit."""
self._message_track_post_template(self.env.cr.precommit.data.pop(f'mail.tracking.create.{self._name}.{self.id}', []))
self.env.flush_all()
def _track_set_log_message(self, message):
""" Link tracking to a message logged as body, in addition to subtype
description (if set) and tracking values that make the core content of
tracking message. """
if not self._track_get_fields():
return
body_values = self.env.cr.precommit.data.setdefault(f'mail.tracking.message.{self._name}', {})
for id_ in self.ids:
body_values[id_] = message
def _track_get_default_log_message(self, tracked_fields):
"""Get a default log message based on the changed fields.
:param List[str] tracked_fields: Name of the tracked fields being evaluated;
:return str: A message to log when these changes happen for this record;
"""
return ''
@tools.ormcache('self.env.uid', 'self.env.su')
def _track_get_fields(self):
""" Return the set of tracked fields names for the current model. """
model_fields = {
name
for name, field in self._fields.items()
if getattr(field, 'tracking', None) or getattr(field, 'track_visibility', None)
}
return model_fields and set(self.fields_get(model_fields, attributes=()))
def _track_subtype(self, initial_values):
""" Give the subtypes triggered by the changes on the record according
to values that have been updated.
:param dict initial_values: original values of the record; only modified
fields are present in the dict
:returns: a subtype browse record or False if no subtype is triggered
"""
self.ensure_one()
return False
def _message_track(self, fields_iter, initial_values_dict):
""" 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.
:param iter fields_iter: iterable of field names to track
:param dict initial_values_dict: mapping {record_id: initial_values}
where initial_values is a dict {field_name: value, ... }
:return: mapping {record_id: (changed_field_names, tracking_value_ids)}
containing existing records only
"""
if not fields_iter:
return {}
tracked_fields = self.fields_get(fields_iter, attributes=('string', 'type', 'selection', 'currency_field'))
tracking = dict()
for record in self:
try:
tracking[record.id] = record._mail_track(tracked_fields, initial_values_dict[record.id])
except MissingError:
continue
# find content to log as body
bodies = self.env.cr.precommit.data.pop(f'mail.tracking.message.{self._name}', {})
authors = self.env.cr.precommit.data.pop(f'mail.tracking.author.{self._name}', {})
for record in self:
changes, tracking_value_ids = tracking.get(record.id, (None, None))
if not changes:
continue
# find subtypes and post messages or log if no subtype found
subtype = record._track_subtype(
dict((col_name, initial_values_dict[record.id][col_name])
for col_name in changes)
)
author_id = authors[record.id].id if record.id in authors else None
# _set_log_message takes priority over _track_get_default_log_message even if it's an empty string
body = bodies[record.id] if record.id in bodies else record._track_get_default_log_message(changes)
if subtype:
if not subtype.exists():
_logger.debug('subtype "%s" not found' % subtype.name)
continue
record.message_post(
body=body,
author_id=author_id,
subtype_id=subtype.id,
tracking_value_ids=tracking_value_ids
)
elif tracking_value_ids:
record._message_log(
body=body,
author_id=author_id,
tracking_value_ids=tracking_value_ids
)
return tracking
def _message_track_post_template(self, changes):
""" Based on a tracking, post a message defined by ``_track_template``
parameters. It allows to implement automatic post of messages based
on templates (e.g. stage change triggering automatic email).
:param dict changes: mapping {record_id: (changed_field_names, tracking_value_ids)}
containing existing records only
"""
if not self or 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
cleaned_self = self.with_context(clean_context(self._context))._fallback_lang()
try:
templates = self._track_template(changes)
except MissingError:
if not self.exists():
return
raise
default_composition_mode = 'mass_mail' if len(self) != 1 else 'comment'
for _field_name, (template, post_kwargs) in templates.items():
if not template:
continue
composition_mode = post_kwargs.pop('composition_mode', default_composition_mode)
post_kwargs.setdefault('message_type', 'auto_comment')
if composition_mode == 'mass_mail':
cleaned_self.message_mail_with_source(template, **post_kwargs)
else:
cleaned_self.message_post_with_source(template, **post_kwargs)
return True
def _track_template(self, changes):
return dict()
# ------------------------------------------------------
# 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 = {
'author_id': False,
'body_html': body_html,
'subject': 'Re: %s' % message.get('subject'),
'email_to': bounce_to,
'auto_delete': True,
}
# find an email_from for the bounce email
email_from = False
if bounce_from := self.env.company.bounce_email:
email_from = tools.formataddr(('MAILER-DAEMON', bounce_from))
if not email_from:
catchall_aliases = self.env['mail.alias.domain'].search([]).mapped('catchall_email')
if not any(catchall_email in message['To'] for catchall_email in catchall_aliases):
email_from = tools.decode_message_header(message, 'To')
if not email_from:
email_from = tools.formataddr(('MAILER-DAEMON', self.env.user.email_normalized))
bounce_mail_values['email_from'] = email_from
bounce_mail_values.update(mail_values)
self.env['mail.mail'].sudo().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_ids, bounced_message = message_dict['bounced_msg_ids'], 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 = bounced_record_done or (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 isinstance(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({
'failure_reason': html2plaintext(message_dict.get('body') or ''),
'failure_type': 'mail_bounce',
'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_ids, 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_ids)
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
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
# Wrong model
if not model:
self._routing_warn(_('target model unspecified'), message_id, route, raise_exception)
return ()
if 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 (%(model)s,%(thread)s), fall back on document creation', model=model, thread=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. 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]
error = obj._alias_get_error(message, message_dict, alias)
if error:
self._routing_warn(
_('alias %(name)s: %(error)s', name=alias.alias_name, error=error.message or _('unknown error')),
message_id,
route,
False
)
alias._alias_bounce_incoming_email(message, message_dict, set_invalid=error.is_config_error)
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 _detect_is_bounce(self, message, message_dict):
"""Return True if the given email is a bounce email.
Bounce alias: if any To contains bounce_alias@domain
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"
"""
# detection based on email_to
bounce_aliases = self.env['mail.alias.domain'].search([]).mapped('bounce_email')
email_to_list = [
tools.email_normalize(e) or e
for e in (tools.email_split(message_dict['to']) or [''])
]
if bounce_aliases and any(email in bounce_aliases for email in email_to_list):
return True
email_from = message_dict['email_from']
email_from_localpart = (tools.email_split(email_from) or [''])[0].split('@', 1)[0].lower()
# detection based on email_from
if email_from_localpart == 'mailer-daemon':
return True
# detection based on content type
content_type = message.get_content_type()
if content_type == 'multipart/report' or 'report-type=delivery-status' in content_type:
return True
return False
@api.model
def _detect_loop_sender_domain(self, email_from_normalized):
"""Return the domain to be used to detect duplicated records created by alias.
:param email_from_normalized: FROM of the incoming email, normalized
"""
primary_email = self._mail_get_primary_email_field()
if primary_email:
return [(primary_email, 'ilike', email_from_normalized)]
_logger.info('Primary email missing on %s', self._name)
@api.model
def _detect_loop_sender(self, message, message_dict, routes):
"""This method returns True if the incoming email should be ignored.
The goal of this method is to prevent loops which can occur if an auto-replier
send emails to Odoo.
"""
email_from = message_dict.get('email_from')
if not email_from:
return False
email_from_normalized = tools.email_normalize(email_from)
if self.env['mail.gateway.allowed'].sudo().search_count(
[('email_normalized', '=', email_from_normalized)]
):
return False
# Detect the email address sent to many emails
get_param = self.env['ir.config_parameter'].sudo().get_param
# Period in minutes in which we will look for <mail.mail>
LOOP_MINUTES = int(get_param('mail.gateway.loop.minutes', 120))
LOOP_THRESHOLD = int(get_param('mail.gateway.loop.threshold', 20))
create_date_limit = self.env.cr.now() - datetime.timedelta(minutes=LOOP_MINUTES)
# Search only once per model
models = {
self.env[model]
for model, thread_id, *__ in routes or []
if not thread_id # Reply to an existing thread
}
for model in models:
if not hasattr(model, '_detect_loop_sender_domain'):
continue
domain = model._detect_loop_sender_domain(email_from_normalized)
if not domain:
continue
mail_incoming_messages_count = model.sudo().search_count(
expression.AND([
[('create_date', '>', create_date_limit)],
domain,
]),
)
if mail_incoming_messages_count >= LOOP_THRESHOLD:
_logger.info('Email address %s created too many <%s>.', email_from, model)
body = self.env['ir.qweb']._render(
'mail.message_notification_limit_email',
{'email': message_dict.get('to')},
minimal_qcontext=True,
raise_if_not_found=False,
)
# Add a reference with a tag, to be able to ignore response to this email