/
mail_thread.py
2464 lines (2169 loc) · 123 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
try:
from xmlrpc import client as xmlrpclib
except ImportError:
import xmlrpclib
from collections import namedtuple
from email.message import Message
from lxml import etree
from werkzeug import urls
from odoo import _, api, exceptions, fields, models, tools
from odoo.tools import pycompat, ustr, formataddr
from odoo.tools.misc import clean_context
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',
domain=lambda self: [('res_model', '=', self._name)])
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: [('model', '=', self._name)], 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 error', compute='_compute_message_has_error',
help="Number of messages with delivery error")
message_attachment_count = fields.Integer('Attachment Count', compute='_compute_message_attachment_count')
message_main_attachment_id = fields.Many2one(string="Main Attachment", comodel_name='ir.attachment', index=True, copy=False)
@api.one
@api.depends('message_follower_ids')
def _get_followers(self):
self.message_partner_ids = self.message_follower_ids.mapped('partner_id')
self.message_channel_ids = self.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.multi
@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'])])]
@api.multi
def _get_message_unread(self):
res = dict((res_id, 0) for res_id in self.ids)
partner_id = self.env.user.partner_id.id
# 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.author_id IS NULL OR msg.author_id != %s) AND
(msg.message_type != '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.id, 0)
record.message_unread = bool(record.message_unread_counter)
@api.multi
def _get_message_needaction(self):
res = dict((res_id, 0) for res_id in self.ids)
if not res:
return
# 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""",
(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.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)]
@api.multi
def _compute_message_has_error(self):
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.email_status in ('exception','bounce')
WHERE msg.author_id = %s AND msg.model = %s AND msg.res_id in %s
GROUP BY msg.res_id""",
(self.env.user.partner_id.id, self._name, tuple(self.ids),))
res = dict()
for result in self._cr.fetchall():
res[result[0]] = result[1]
for record in self:
record.message_has_error_counter = res.get(record.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)]
@api.multi
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'):
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 self.env['mail.followers']._add_default_followers(self._name, [], self.env.user.partner_id.ids, customer_ids=[])[0][0]]
values['message_follower_ids'] = message_follower_ids
threads = super(MailThread, self).create(vals_list)
# automatic logging unless asked not to (mainly for various testing purpose)
if not self._context.get('mail_create_nolog'):
doc_name = self.env['ir.model']._get(self._name).name
for thread in threads:
thread._message_log(body=_('%s created') % doc_name)
# auto_subscribe: take values and defaults into account
for thread, values in pycompat.izip(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')
# track values
if not self._context.get('mail_notrack'):
if not self._context.get('lang'):
track_threads = threads.with_context(lang=self.env.user.lang)
else:
track_threads = threads
for thread, values in pycompat.izip(track_threads, vals_list):
tracked_fields = thread._get_tracked_fields(list(values))
if tracked_fields:
initial_values = {thread.id: dict.fromkeys(tracked_fields, False)}
thread.message_track(tracked_fields, initial_values)
return threads
@api.multi
def write(self, values):
if self._context.get('tracking_disable'):
return super(MailThread, self).write(values)
# Track initial values of tracked fields
if 'lang' not in self._context:
track_self = self.with_context(lang=self.env.user.lang)
else:
track_self = self
tracked_fields = None
if not self._context.get('mail_notrack'):
tracked_fields = track_self._get_tracked_fields(list(values))
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:
track_self.with_context(clean_context(self._context)).message_track(tracked_fields, initial_values)
return result
@api.multi
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)]).unlink()
res = super(MailThread, self).unlink()
self.env['mail.followers'].sudo().search(
[('res_model', '=', self._name), ('res_id', 'in', self.ids)]
).unlink()
return res
@api.multi
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.name_get()[0][1]}
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 _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 check_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. """
if model_name:
DocModel = self.env[model_name]
else:
DocModel = self
if hasattr(DocModel, '_mail_post_access'):
create_allow = DocModel._mail_post_access
else:
create_allow = '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
DocModel.check_access_rights(check_operation)
DocModel.browse(res_ids).check_access_rule(check_operation)
@api.multi
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),
('subtype_id', '=', subtype_comment)])
msg_not_comment = MailMessage.search([
('model', '=', self._name),
('res_id', '=', self.id),
('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, updated_fields):
""" Return a structure of tracked fields for the current model.
:param list updated_fields: modified field names
:return dict: a dict mapping field name to description, containing on_change fields
"""
tracked_fields = []
for name, field in self._fields.items():
if getattr(field, 'track_visibility', False):
tracked_fields.append(name)
if tracked_fields:
return self.fields_get(tracked_fields)
return {}
@api.multi
def _track_subtype(self, init_values):
""" Give the subtypes triggered by the changes on the record according
to values that have been updated.
:param ids: list of a single ID, the ID of the record being modified
:type ids: singleton list
:param init_values: the original values of the record; only modified fields
are present in the dict
:type init_values: dict
:returns: a subtype xml_id or False if no subtype is trigerred
"""
return False
@api.multi
def _track_template(self, tracking):
return dict()
@api.multi
def _message_track_post_template(self, tracking):
if not any(change for rec_id, (change, tracking_value_ids) in tracking.items()):
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(tracking)
for field_name, (template, post_kwargs) in templates.items():
if not template:
continue
if isinstance(template, pycompat.string_types):
self.message_post_with_view(template, **post_kwargs)
else:
self.message_post_with_template(template.id, **post_kwargs)
return True
@api.multi
def _message_track_get_changes(self, tracked_fields, initial_values):
""" Batch method of _message_track. """
result = dict()
for record in self:
result[record.id] = record._message_track(tracked_fields, initial_values[record.id])
return result
@api.multi
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 changes (initial value, new value, column name, column info) """
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 = getattr(self, col_name)
if new_value != initial_value and (new_value or initial_value): # because browse null != False
track_sequence = getattr(self._fields[col_name], 'track_sequence', 100)
tracking = self.env['mail.tracking.value'].create_tracking_values(initial_value, new_value, col_name, col_info, track_sequence)
if tracking:
tracking_value_ids.append([0, 0, tracking])
if col_name in tracked_fields:
changes.add(col_name)
return changes, tracking_value_ids
@api.multi
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 = self._message_track_get_changes(tracked_fields, initial_values)
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_xmlid = 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_xmlid = record._track_subtype(dict((col_name, initial_values[record.id][col_name]) for col_name in changes))
if subtype_xmlid:
subtype_rec = self.env.ref(subtype_xmlid) # TDE FIXME check for raise if not found
if not (subtype_rec and subtype_rec.exists()):
_logger.debug('subtype %s not found' % subtype_xmlid)
continue
record.message_post(subtype=subtype_xmlid, tracking_value_ids=tracking_value_ids)
elif tracking_value_ids:
record._message_log(tracking_value_ids=tracking_value_ids)
self._message_track_post_template(tracking)
return True
# ------------------------------------------------------
# Email Notification
# ------------------------------------------------------
@api.model
def _notify_encode_link(self, base_link, params):
secret = self.env['ir.config_parameter'].sudo().get_param('database.secret')
token = '%s?%s' % (base_link, ' '.join('%s=%s' % (key, params[key]) for key in sorted(params)))
hm = hmac.new(secret.encode('utf-8'), token.encode('utf-8'), hashlib.sha1).hexdigest()
return hm
@api.multi
def _notify_get_action_link(self, link_type, **kwargs):
local_kwargs = dict(kwargs) # do not modify in-place, modify copy instead
base_params = {
'model': kwargs.get('model', self._name),
'res_id': kwargs.get('res_id', self.ids and self.ids[0] or False),
}
local_kwargs.pop('message_id', None)
local_kwargs.pop('model', None)
local_kwargs.pop('res_id', None)
if link_type in ['view', 'assign', 'follow', 'unfollow']:
params = dict(base_params, **local_kwargs)
base_link = '/mail/%s' % link_type
elif link_type == 'controller':
controller = local_kwargs.pop('controller')
params = dict(base_params, **local_kwargs)
params.pop('model')
base_link = '%s' % controller
else:
return ''
if link_type not in ['view']:
token = self._notify_encode_link(base_link, params)
params['token'] = token
link = '%s?%s' % (base_link, urls.url_encode(params))
if self and hasattr(self, 'get_base_url'):
link = self[0].get_base_url() + link
return link
@api.multi
def _notify_get_groups(self, message, groups):
""" Return groups used to classify recipients of a notification email.
Groups is a list of tuple containing of form (group_name, group_func,
group_data) where
* group_name is an identifier used only to be able to override and manipulate
groups. Default groups are user (recipients linked to an employee user),
portal (recipients linked to a portal user) and customer (recipients not
linked to any user). An example of override use would be to add a group
linked to a res.groups like Hr Officers to set specific action buttons to
them.
* group_func is a function pointer taking a partner record as parameter. This
method will be applied on recipients to know whether they belong to a given
group or not. Only first matching group is kept. Evaluation order is the
list order.
* group_data is a dict containing parameters for the notification email
* has_button_access: whether to display Access <Document> in email. True
by default for new groups, False for portal / customer.
* button_access: dict with url and title of the button
* actions: list of action buttons to display in the notification email.
Each action is a dict containing url and title of the button.
Groups has a default value that you can find in mail_thread
``_notify_classify_recipients`` method.
"""
return groups
@api.multi
def _notify_classify_recipients(self, message, recipient_data):
""" Classify recipients to be notified of a message in groups to have
specific rendering depending on their group. For example users could
have access to buttons customers should not have in their emails.
Module-specific grouping should be done by overriding ``_notify_get_groups``
method defined here-under.
:param message: mail.message record about to be notified
:param recipients: res.partner recordset to notify UPDATE ME
"""
result = {}
access_link = self._notify_get_action_link('view')
if message.model:
model = self.env['ir.model'].with_context(
lang=self.env.context.get('lang', self.env.user.lang))
model_name = model._get(message.model).display_name
view_title = _('View %s') % model_name
else:
view_title = _('View')
default_groups = [
('user', lambda pdata: pdata['type'] == 'user', {}),
('portal', lambda pdata: pdata['type'] == 'portal', {
'has_button_access': False,
}),
('customer', lambda pdata: True, {
'has_button_access': False,
})
]
groups = self._notify_get_groups(message, default_groups)
for group_name, group_func, group_data in groups:
group_data.setdefault('has_button_access', True)
group_data.setdefault('button_access', {
'url': access_link,
'title': view_title})
group_data.setdefault('actions', list())
group_data.setdefault('recipients', list())
for recipient in recipient_data:
for group_name, group_func, group_data in groups:
if group_func(recipient):
group_data['recipients'].append(recipient['id'])
break
for group_name, group_method, group_data in groups:
result[group_name] = group_data
return result
def _notify_classify_recipients_on_records(self, message, recipient_data, records=None):
""" Generic wrapper on ``_notify_classify_recipients`` checking mail.thread
inheritance and allowing to call model-specific implementation in a one liner.
This method should not be overridden. """
if records and hasattr(records, '_notify_classify_recipients'):
return records._notify_classify_recipients(message, recipient_data)
return self._notify_classify_recipients(message, recipient_data)
@api.multi
def _notify_get_reply_to(self, default=None, records=None, company=None, doc_names=None):
""" Returns the preferred reply-to email address when replying to a thread
on documents. Documents are either given by self it this method is called
as a true multi method on a record set or can be given using records to
have a generic implementation available for all models.
Reply-to is formatted like "MyCompany MyDocument <reply.to@domain>".
Heuristic it the following:
* search for specific aliases as they always have priority; it is limited
to aliases linked to documents (like project alias for task for example);
* use catchall address;
* use default;
This method works on documents
* as a true multi method for models inheriting from mail.thread; call
``records._notify_get_reply_to(...)``;
* as a generic implementation if records are given; call ``MailThread.
_notify_get_reply_to(records=records, ...)``;
* as a generic implementation is self is a void mail.thread record set
meaning catchall is computed; call ``MailThread._notify_get_reply_to
(records=None)``;
Tweak this method on a specific model by overriding if it inherits from
mail.thread. An example would be tasks taking their reply-to alias from
their project.
:param default: default email if no alias or catchall is found;
:param records: record_set if self if a generic mail.thread record allowing
generic implementation of finding reply-to;
:param company: used to compute company name part of the from name; provide
it if already known, otherwise fall back on user company;
:param doc_names: dict(res_id, doc_name) used to compute doc name part of
the from name; provide it if already known to avoid queries, otherwise
name_get on document will be performed;
:return result: dictionary. Keys are record IDs and value is formatted
like an email "Company_name Document_name <reply_to@email>"/
"""
_records = self if self and self._name != 'mail.thread' else records
model = _records._name if _records and _records._name != 'mail.thread' else False
res_ids = _records.ids if _records and model else []
_res_ids = res_ids or [False] # always have a default value located in False
alias_domain = self.env['ir.config_parameter'].sudo().get_param("mail.catchall.domain")
result = dict.fromkeys(_res_ids, False)
result_email = dict()
doc_names = doc_names if doc_names else dict()
if alias_domain:
if model and res_ids:
if not doc_names:
doc_names = dict((rec.id, rec.display_name) for rec in _records)
mail_aliases = self.env['mail.alias'].sudo().search([
('alias_parent_model_id.model', '=', model),
('alias_parent_thread_id', 'in', res_ids),
('alias_name', '!=', False)])
# take only first found alias for each thread_id, to match order (1 found -> limit=1 for each res_id)
for alias in mail_aliases:
result_email.setdefault(alias.alias_parent_thread_id, '%s@%s' % (alias.alias_name, alias_domain))
# left ids: use catchall
left_ids = set(_res_ids) - set(result_email)
if left_ids:
catchall = self.env['ir.config_parameter'].sudo().get_param("mail.catchall.alias")
if catchall:
result_email.update(dict((rid, '%s@%s' % (catchall, alias_domain)) for rid in left_ids))
# compute name of reply-to - TDE tocheck: quotes and stuff like that
company_name = company.name if company else self.env.user.company_id.name
for res_id in result_email.keys():
name = '%s%s%s' % (company_name, ' ' if doc_names.get(res_id) else '', doc_names.get(res_id, ''))
result[res_id] = formataddr((name, result_email[res_id]))
left_ids = set(_res_ids) - set(result_email)
if left_ids:
result.update(dict((res_id, default) for res_id in left_ids))
return result
@api.model
def _notify_get_reply_to_on_records(self, default=None, records=None, company=None, doc_names=None):
""" Generic wrapper on ``_notify_get_reply_to`` checking mail.thread inheritance
and allowing to call model-specific implementation in a one liner. This
method should not be overridden. """
if records and hasattr(records, '_notify_get_reply_to'):
return records._notify_get_reply_to(default=default, company=company, doc_names=doc_names)
return self._notify_get_reply_to(default=default, records=records, company=company, doc_names=doc_names)
@api.multi
def _notify_specific_email_values(self, message):
""" Get specific notification email values to store on the notification
mail.mail. Override to add values related to a specific model.
:param message: mail.message record being notified by email
"""
if not self:
return {}
self.ensure_one()
return {'headers': repr({
'X-Odoo-Objects': "%s-%s" % (self._name, self.id),
})}
@api.model
def _notify_specific_email_values_on_records(self, message, records=None):
""" Generic wrapper on ``_notify_specific_email_values`` checking mail.thread
inheritance and allowing to call model-specific implementation in a one liner.
This method should not be overridden. """
if records and hasattr(records, '_notify_specific_email_values'):
return records._notify_specific_email_values(message)
return self._notify_specific_email_values(message)
@api.multi
def _notify_email_recipients(self, message, recipient_ids):
""" Format email notification recipient values to store on the notification
mail.mail. Basic method just set the recipient partners as mail_mail
recipients. Override to generate other mail values like email_to or
email_cc.
:param message: mail.message record being notified by email
:param recipient_ids: res.partner recordset to notify
"""
return {
'recipient_ids': [(4, pid) for pid in recipient_ids]
}
@api.model
def _notify_email_recipients_on_records(self, message, recipient_ids, records=None):
""" Generic wrapper on ``_notify_email_recipients`` checking mail.thread
inheritance and allowing to call model-specific implementation in a one liner.
This method should not be overridden. """
if records and hasattr(records, '_notify_email_recipients'):
return records._notify_email_recipients(message, recipient_ids)
return self._notify_email_recipients(message, recipient_ids)
# ------------------------------------------------------
# Mail gateway
# ------------------------------------------------------
def _message_find_partners(self, message, header_fields=['From']):
""" Find partners related to some header fields of the message.
:param string message: an email.message instance """
s = ', '.join([tools.decode_smtp_header(message.get(h)) for h in header_fields if message.get(h)])
return [x for x in self._find_partner_from_emails(tools.email_split(s)) if x]
def _routing_warn(self, error_message, warn_suffix, message_id, route, raise_exception):
""" Tools method used in message_route_verify: 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 + (warn_suffix and '; %s' % warn_suffix or ''))
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 message_route_verify(self, message, message_dict, route,
update_author=True, assert_model=True,
create_fallback=True, allow_private=False,
drop_alias=False):
""" 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 update_author: update message_dict['author_id']. TDE TODO: move me
:param assert_model: if an error occurs, tell whether to raise an error
or just log a warning and try other processing or