mail_channel.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import base64
  4. import logging
  5. from collections import defaultdict
  6. from hashlib import sha512
  7. from secrets import choice
  8. from odoo import _, api, fields, models, tools, Command
  9. from odoo.addons.base.models.avatar_mixin import get_hsl_from_seed
  10. from odoo.exceptions import UserError, ValidationError
  11. from odoo.osv import expression
  12. from odoo.tools import html_escape
  13. from odoo.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
  14. _logger = logging.getLogger(__name__)
  15. channel_avatar = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 530.06 530.06">
  16. <circle cx="265.03" cy="265.03" r="265.03" fill="#875a7b"/>
  17. <path d="M416.74,217.29l5-28a8.4,8.4,0,0,0-8.27-9.88H361.09l10.24-57.34a8.4,8.4,0,0,0-8.27-9.88H334.61a8.4,8.4,0,0,0-8.27,6.93L315.57,179.4H246.5l10.24-57.34a8.4,8.4,0,0,0-8.27-9.88H220a8.4,8.4,0,0,0-8.27,6.93L201,179.4H145.6a8.42,8.42,0,0,0-8.28,6.93l-5,28a8.4,8.4,0,0,0,8.27,9.88H193l-16,89.62H121.59a8.4,8.4,0,0,0-8.27,6.93l-5,28a8.4,8.4,0,0,0,8.27,9.88H169L158.73,416a8.4,8.4,0,0,0,8.27,9.88h28.45a8.42,8.42,0,0,0,8.28-6.93l10.76-60.29h69.07L273.32,416a8.4,8.4,0,0,0,8.27,9.88H310a8.4,8.4,0,0,0,8.27-6.93l10.77-60.29h55.38a8.41,8.41,0,0,0,8.28-6.93l5-28a8.4,8.4,0,0,0-8.27-9.88H337.08l16-89.62h55.38A8.4,8.4,0,0,0,416.74,217.29ZM291.56,313.84H222.5l16-89.62h69.07Z" fill="#ffffff"/>
  18. </svg>'''
  19. group_avatar = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 530.06 530.06">
  20. <circle cx="265.03" cy="265.03" r="265.03" fill="#875a7b"/>
  21. <path d="m184.356059,265.030004c-23.740561,0.73266 -43.157922,10.11172 -58.252302,28.136961l-29.455881,0c-12.0169,0 -22.128621,-2.96757 -30.335161,-8.90271s-12.309921,-14.618031 -12.309921,-26.048671c0,-51.730902 9.08582,-77.596463 27.257681,-77.596463c0.87928,0 4.06667,1.53874 9.56217,4.61622s12.639651,6.19167 21.432451,9.34235s17.512401,4.72613 26.158581,4.72613c9.8187,0 19.563981,-1.68536 29.236061,-5.05586c-0.73266,5.4223 -1.0991,10.25834 -1.0991,14.508121c0,20.370061 5.93514,39.127962 17.805421,56.273922zm235.42723,140.025346c0,17.585601 -5.34888,31.470971 -16.046861,41.655892s-24.912861,15.277491 -42.645082,15.277491l-192.122688,0c-17.732221,0 -31.947101,-5.09257 -42.645082,-15.277491s-16.046861,-24.070291 -16.046861,-41.655892c0,-7.7669 0.25653,-15.350691 0.76937,-22.751371s1.53874,-15.387401 3.07748,-23.960381s3.48041,-16.523211 5.82523,-23.850471s5.4955,-14.471411 9.45226,-21.432451s8.49978,-12.89618 13.628841,-17.805421c5.12906,-4.90924 11.393931,-8.82951 18.794611,-11.76037s15.570511,-4.3964 24.509931,-4.3964c1.46554,0 4.61622,1.57545 9.45226,4.72613s10.18492,6.6678 16.046861,10.55136c5.86194,3.88356 13.702041,7.40068 23.520741,10.55136s19.710601,4.72613 29.675701,4.72613s19.857001,-1.57545 29.675701,-4.72613s17.658801,-6.6678 23.520741,-10.55136c5.86194,-3.88356 11.21082,-7.40068 16.046861,-10.55136s7.98672,-4.72613 9.45226,-4.72613c8.93942,0 17.109251,1.46554 24.509931,4.3964s13.665551,6.85113 18.794611,11.76037c5.12906,4.90924 9.67208,10.844381 13.628841,17.805421s7.10744,14.105191 9.45226,21.432451s4.28649,15.277491 5.82523,23.850471s2.56464,16.559701 3.07748,23.960381s0.76937,14.984471 0.76937,22.751371zm-225.095689,-280.710152c0,15.534021 -5.4955,28.796421 -16.486501,39.787422s-24.253401,16.486501 -39.787422,16.486501s-28.796421,-5.4955 -39.787422,-16.486501s-16.486501,-24.253401 -16.486501,-39.787422s5.4955,-28.796421 16.486501,-39.787422s24.253401,-16.486501 39.787422,-16.486501s28.796421,5.4955 39.787422,16.486501s16.486501,24.253401 16.486501,39.787422zm154.753287,84.410884c0,23.300921 -8.24325,43.194632 -24.729751,59.681133s-36.380212,24.729751 -59.681133,24.729751s-43.194632,-8.24325 -59.681133,-24.729751s-24.729751,-36.380212 -24.729751,-59.681133s8.24325,-43.194632 24.729751,-59.681133s36.380212,-24.729751 59.681133,-24.729751s43.194632,8.24325 59.681133,24.729751s24.729751,36.380212 24.729751,59.681133zm126.616325,49.459502c0,11.43064 -4.10338,20.113531 -12.309921,26.048671s-18.318261,8.90271 -30.335161,8.90271l-29.455881,0c-15.094381,-18.025241 -34.511741,-27.404301 -58.252302,-28.136961c11.87028,-17.145961 17.805421,-35.903862 17.805421,-56.273922c0,-4.24978 -0.36644,-9.08582 -1.0991,-14.508121c9.67208,3.3705 19.417361,5.05586 29.236061,5.05586c8.64618,0 17.365781,-1.57545 26.158581,-4.72613s15.936951,-6.26487 21.432451,-9.34235s8.68289,-4.61622 9.56217,-4.61622c18.171861,0 27.257681,25.865561 27.257681,77.596463zm-28.136961,-133.870386c0,15.534021 -5.4955,28.796421 -16.486501,39.787422s-24.253401,16.486501 -39.787422,16.486501s-28.796421,-5.4955 -39.787422,-16.486501s-16.486501,-24.253401 -16.486501,-39.787422s5.4955,-28.796421 16.486501,-39.787422s24.253401,-16.486501 39.787422,-16.486501s28.796421,5.4955 39.787422,16.486501s16.486501,24.253401 16.486501,39.787422z" fill="#ffffff"/>
  22. </svg>'''
  23. class Channel(models.Model):
  24. """ A mail.channel is a discussion group that may behave like a listener
  25. on documents. """
  26. _description = 'Discussion Channel'
  27. _name = 'mail.channel'
  28. _mail_flat_thread = False
  29. _mail_post_access = 'read'
  30. _inherit = ['mail.thread']
  31. MAX_BOUNCE_LIMIT = 10
  32. @api.model
  33. def _generate_random_token(self):
  34. # Built to be shared on invitation link. It uses non-ambiguous characters and it is of a
  35. # reasonable length: enough to avoid brute force, but short enough to be shareable easily.
  36. # This token should not contain "mail.guest"._cookie_separator value.
  37. return ''.join(choice('abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789') for _i in range(10))
  38. # description
  39. name = fields.Char('Name', required=True)
  40. active = fields.Boolean(default=True, help="Set active to false to hide the channel without removing it.")
  41. channel_type = fields.Selection([
  42. ('chat', 'Chat'),
  43. ('channel', 'Channel'),
  44. ('group', 'Group')],
  45. string='Channel Type', required=True, default='channel', readonly=True, help="Chat is private and unique between 2 persons. Group is private among invited persons. Channel can be freely joined (depending on its configuration).")
  46. is_chat = fields.Boolean(string='Is a chat', compute='_compute_is_chat')
  47. default_display_mode = fields.Selection(string="Default Display Mode", selection=[('video_full_screen', "Full screen video")], help="Determines how the channel will be displayed by default when opening it from its invitation link. No value means display text (no voice/video).")
  48. description = fields.Text('Description')
  49. image_128 = fields.Image("Image", max_width=128, max_height=128)
  50. avatar_128 = fields.Image("Avatar", max_width=128, max_height=128, compute='_compute_avatar_128')
  51. channel_partner_ids = fields.Many2many(
  52. 'res.partner', string='Partners',
  53. compute='_compute_channel_partner_ids', inverse='_inverse_channel_partner_ids',
  54. compute_sudo=True, search='_search_channel_partner_ids',
  55. groups='base.group_user')
  56. channel_member_ids = fields.One2many(
  57. 'mail.channel.member', 'channel_id', string='Members',
  58. groups='base.group_user')
  59. rtc_session_ids = fields.One2many('mail.channel.rtc.session', 'channel_id', groups="base.group_system")
  60. is_member = fields.Boolean('Is Member', compute='_compute_is_member', search='_search_is_member')
  61. member_count = fields.Integer(string="Member Count", compute='_compute_member_count', compute_sudo=True)
  62. group_ids = fields.Many2many(
  63. 'res.groups', string='Auto Subscription',
  64. help="Members of those groups will automatically added as followers. "
  65. "Note that they will be able to manage their subscription manually "
  66. "if necessary.")
  67. # access
  68. uuid = fields.Char('UUID', size=50, default=_generate_random_token, copy=False)
  69. group_public_id = fields.Many2one('res.groups', string='Authorized Group', compute='_compute_group_public_id', readonly=False, store=True)
  70. invitation_url = fields.Char('Invitation URL', compute='_compute_invitation_url')
  71. _sql_constraints = [
  72. ('channel_type_not_null', 'CHECK(channel_type IS NOT NULL)', 'The channel type cannot be empty'),
  73. ('uuid_unique', 'UNIQUE(uuid)', 'The channel UUID must be unique'),
  74. ('group_public_id_check',
  75. "CHECK (channel_type = 'channel' OR group_public_id IS NULL)",
  76. 'Group authorization and group auto-subscription are only supported on channels.')
  77. ]
  78. # CONSTRAINTS
  79. @api.constrains('channel_member_ids', 'channel_partner_ids')
  80. def _constraint_partners_chat(self):
  81. for ch in self.sudo().filtered(lambda ch: ch.channel_type == 'chat'):
  82. if len(ch.channel_member_ids) > 2 or len(ch.channel_partner_ids) > 2:
  83. raise ValidationError(_("A channel of type 'chat' cannot have more than two users."))
  84. @api.constrains('group_public_id', 'group_ids')
  85. def _constraint_group_id_channel(self):
  86. failing_channels = self.sudo().filtered(lambda channel: channel.channel_type != 'channel' and (channel.group_public_id or channel.group_ids))
  87. if failing_channels:
  88. raise ValidationError(_("For %(channels)s, channel_type should be 'channel' to have the group-based authorization or group auto-subscription.", channels=', '.join([ch.name for ch in failing_channels])))
  89. # COMPUTE / INVERSE
  90. @api.depends('channel_type')
  91. def _compute_is_chat(self):
  92. for record in self:
  93. record.is_chat = record.channel_type == 'chat'
  94. @api.depends('channel_type', 'image_128', 'uuid')
  95. def _compute_avatar_128(self):
  96. for record in self:
  97. record.avatar_128 = record.image_128 or record._generate_avatar()
  98. def _generate_avatar(self):
  99. if self.channel_type not in ('channel', 'group'):
  100. return False
  101. avatar = group_avatar if self.channel_type == 'group' else channel_avatar
  102. bgcolor = get_hsl_from_seed(self.uuid)
  103. avatar = avatar.replace('fill="#875a7b"', f'fill="{bgcolor}"')
  104. return base64.b64encode(avatar.encode())
  105. @api.depends('channel_member_ids.partner_id')
  106. def _compute_channel_partner_ids(self):
  107. for channel in self:
  108. channel.channel_partner_ids = channel.channel_member_ids.partner_id
  109. def _inverse_channel_partner_ids(self):
  110. new_members = []
  111. outdated = self.env['mail.channel.member']
  112. for channel in self:
  113. current_members = channel.channel_member_ids
  114. partners = channel.channel_partner_ids
  115. partners_new = partners - current_members.partner_id
  116. new_members += [{
  117. 'channel_id': channel.id,
  118. 'partner_id': partner.id,
  119. } for partner in partners_new]
  120. outdated += current_members.filtered(lambda m: m.partner_id not in partners)
  121. if new_members:
  122. self.env['mail.channel.member'].create(new_members)
  123. if outdated:
  124. outdated.sudo().unlink()
  125. def _search_channel_partner_ids(self, operator, operand):
  126. return [(
  127. 'channel_member_ids',
  128. 'in',
  129. self.env['mail.channel.member'].sudo()._search([
  130. ('partner_id', operator, operand)
  131. ])
  132. )]
  133. @api.depends_context('uid', 'guest')
  134. @api.depends('channel_member_ids')
  135. def _compute_is_member(self):
  136. if not self:
  137. return
  138. if self.env.user._is_public():
  139. guest = self.env['mail.guest']._get_guest_from_context()
  140. if not guest:
  141. self.is_member = False
  142. return
  143. user_domain = [('guest_id', '=', guest.id)]
  144. else:
  145. user_domain = [('partner_id', '=', self.env.user.partner_id.id)]
  146. members = self.env['mail.channel.member'].sudo().search(expression.AND([[('channel_id', 'in', self.ids)], user_domain]))
  147. is_member_channels = {member.channel_id for member in members}
  148. for channel in self:
  149. channel.is_member = channel in is_member_channels
  150. def _search_is_member(self, operator, operand):
  151. is_in = (operator == '=' and operand) or (operator == '!=' and not operand)
  152. if self.env.user._is_public():
  153. guest = self.env['mail.guest']._get_guest_from_context()
  154. if not guest:
  155. return expression.FALSE_DOMAIN if is_in else expression.TRUE_DOMAIN
  156. user_domain = [('guest_id', '=', guest.id)]
  157. else:
  158. user_domain = [('partner_id', '=', self.env.user.partner_id.id)]
  159. return [(
  160. 'channel_member_ids',
  161. 'in' if is_in else 'not in',
  162. self.env['mail.channel.member'].sudo()._search(user_domain)
  163. )]
  164. @api.depends('channel_member_ids')
  165. def _compute_member_count(self):
  166. read_group_res = self.env['mail.channel.member']._read_group(domain=[('channel_id', 'in', self.ids)], fields=['channel_id'], groupby=['channel_id'])
  167. member_count_by_channel_id = {item['channel_id'][0]: item['channel_id_count'] for item in read_group_res}
  168. for channel in self:
  169. channel.member_count = member_count_by_channel_id.get(channel.id, 0)
  170. @api.depends('channel_type')
  171. def _compute_group_public_id(self):
  172. channels = self.filtered(lambda channel: channel.channel_type == 'channel')
  173. channels.filtered(lambda channel: not channel.group_public_id).group_public_id = self.env.ref('base.group_user')
  174. (self - channels).group_public_id = None
  175. @api.depends('uuid')
  176. def _compute_invitation_url(self):
  177. for channel in self:
  178. channel.invitation_url = f"/chat/{channel.id}/{channel.uuid}"
  179. # ------------------------------------------------------------
  180. # CRUD
  181. # ------------------------------------------------------------
  182. @api.model_create_multi
  183. def create(self, vals_list):
  184. for vals in vals_list:
  185. # find partners to add from partner_ids
  186. partner_ids_cmd = vals.get('channel_partner_ids') or []
  187. if any(cmd[0] not in (4, 6) for cmd in partner_ids_cmd):
  188. raise ValidationError(_('Invalid value when creating a channel with members, only 4 or 6 are allowed.'))
  189. partner_ids = [cmd[1] for cmd in partner_ids_cmd if cmd[0] == 4]
  190. partner_ids += [cmd[2] for cmd in partner_ids_cmd if cmd[0] == 6]
  191. # find partners to add from channel_member_ids
  192. membership_ids_cmd = vals.get('channel_member_ids', [])
  193. if any(cmd[0] != 0 for cmd in membership_ids_cmd):
  194. raise ValidationError(_('Invalid value when creating a channel with memberships, only 0 is allowed.'))
  195. membership_pids = [cmd[2]['partner_id'] for cmd in membership_ids_cmd if cmd[0] == 0]
  196. # always add current user to new channel to have right values for
  197. # is_pinned + ensure they have rights to see channel
  198. partner_ids_to_add = list(set(partner_ids + [self.env.user.partner_id.id]))
  199. vals['channel_member_ids'] = membership_ids_cmd + [
  200. (0, 0, {'partner_id': pid})
  201. for pid in partner_ids_to_add if pid not in membership_pids
  202. ]
  203. # clean vals
  204. vals.pop('channel_partner_ids', False)
  205. # Create channel and alias
  206. channels = super(Channel, self.with_context(mail_create_bypass_create_check=self.env['mail.channel.member']._bypass_create_check, mail_create_nolog=True, mail_create_nosubscribe=True)).create(vals_list)
  207. channels._subscribe_users_automatically()
  208. return channels
  209. @api.ondelete(at_uninstall=False)
  210. def _unlink_except_all_employee_channel(self):
  211. # Delete mail.channel
  212. try:
  213. all_emp_group = self.env.ref('mail.channel_all_employees')
  214. except ValueError:
  215. all_emp_group = None
  216. if all_emp_group and all_emp_group in self:
  217. raise UserError(_('You cannot delete those groups, as the Whole Company group is required by other modules.'))
  218. self.env['bus.bus']._sendmany([(channel, 'mail.channel/delete', {'id': channel.id}) for channel in self])
  219. def write(self, vals):
  220. if 'channel_type' in vals:
  221. failing_channels = self.sudo().filtered(lambda channel: channel.channel_type != vals.get('channel_type'))
  222. if failing_channels:
  223. raise UserError(_('Cannot change the channel type of: %(channel_names)s'), channel_names=', '.join(failing_channels.mapped('name')))
  224. result = super(Channel, self).write(vals)
  225. if vals.get('group_ids'):
  226. self._subscribe_users_automatically()
  227. if 'image_128' in vals:
  228. notifications = []
  229. for channel in self:
  230. notifications.append([channel, 'mail.channel/insert', {
  231. 'avatarCacheKey': channel._get_avatar_cache_key(),
  232. 'id': channel.id,
  233. }])
  234. self.env['bus.bus']._sendmany(notifications)
  235. return result
  236. def init(self):
  237. self._cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('mail_channel_member_seen_message_id_idx',))
  238. if not self._cr.fetchone():
  239. self._cr.execute('CREATE INDEX mail_channel_member_seen_message_id_idx ON mail_channel_member (channel_id,partner_id,seen_message_id)')
  240. # ------------------------------------------------------------
  241. # MEMBERS MANAGEMENT
  242. # ------------------------------------------------------------
  243. def _subscribe_users_automatically(self):
  244. new_members = self._subscribe_users_automatically_get_members()
  245. if new_members:
  246. to_create = [
  247. {'channel_id': channel_id, 'partner_id': partner_id}
  248. for channel_id in new_members
  249. for partner_id in new_members[channel_id]
  250. ]
  251. self.env['mail.channel.member'].sudo().create(to_create)
  252. def _subscribe_users_automatically_get_members(self):
  253. """ Return new members per channel ID """
  254. return dict(
  255. (channel.id, (channel.group_ids.users.partner_id - channel.channel_partner_ids).ids)
  256. for channel in self
  257. )
  258. def action_unfollow(self):
  259. self._action_unfollow(self.env.user.partner_id)
  260. def _action_unfollow(self, partner):
  261. self.message_unsubscribe(partner.ids)
  262. if partner not in self.with_context(active_test=False).channel_partner_ids:
  263. return True
  264. channel_info = self.channel_info()[0] # must be computed before leaving the channel (access rights)
  265. member = self.env['mail.channel.member'].search([('channel_id', '=', self.id), ('partner_id', '=', partner.id)])
  266. member_id = member.id
  267. member.unlink()
  268. # side effect of unsubscribe that wasn't taken into account because
  269. # channel_info is called before actually unpinning the channel
  270. channel_info['is_pinned'] = False
  271. self.env['bus.bus']._sendone(partner, 'mail.channel/leave', channel_info)
  272. notification = _('<div class="o_mail_notification">left the channel</div>')
  273. # post 'channel left' message as root since the partner just unsubscribed from the channel
  274. self.sudo().message_post(body=notification, subtype_xmlid="mail.mt_comment", author_id=partner.id)
  275. self.env['bus.bus']._sendone(self, 'mail.channel/insert', {
  276. 'channelMembers': [('insert-and-unlink', {'id': member_id})],
  277. 'id': self.id,
  278. 'memberCount': self.member_count,
  279. })
  280. def add_members(self, partner_ids=None, guest_ids=None, invite_to_rtc_call=False, open_chat_window=False, post_joined_message=True):
  281. """ Adds the given partner_ids and guest_ids as member of self channels. """
  282. self.check_access_rights('write')
  283. self.check_access_rule('write')
  284. current_partner = self.env['res.partner']
  285. current_guest = self.env['mail.guest']
  286. guest = self.env['mail.guest']._get_guest_from_context()
  287. if self.env.user._is_public() and guest:
  288. current_guest = guest
  289. else:
  290. current_partner = self.env.user.partner_id
  291. partners = self.env['res.partner'].browse(partner_ids or []).exists()
  292. guests = self.env['mail.guest'].browse(guest_ids or []).exists()
  293. notifications = []
  294. for channel in self:
  295. members_to_create = []
  296. if channel.group_public_id:
  297. invalid_partners = partners.filtered(lambda partner: channel.group_public_id not in partner.user_ids.groups_id)
  298. if invalid_partners:
  299. raise UserError(_(
  300. 'Channel "%(channel_name)s" only accepts members of group "%(group_name)s". Forbidden for: %(partner_names)s',
  301. channel_name=channel.name,
  302. group_name=channel.group_public_id.name,
  303. partner_names=', '.join(partner.name for partner in invalid_partners)
  304. ))
  305. if guests:
  306. raise UserError(_(
  307. 'Channel "%(channel_name)s" only accepts members of group "%(group_name)s". Forbidden for: %(guest_names)s',
  308. channel_name=channel.name,
  309. group_name=channel.group_public_id.name,
  310. guest_names=', '.join(guest.name for guest in guests)
  311. ))
  312. existing_members = self.env['mail.channel.member'].search(expression.AND([
  313. [('channel_id', '=', channel.id)],
  314. expression.OR([
  315. [('partner_id', 'in', partners.ids)],
  316. [('guest_id', 'in', guests.ids)]
  317. ])
  318. ]))
  319. members_to_create += [{
  320. 'partner_id': partner.id,
  321. 'channel_id': channel.id,
  322. } for partner in partners - existing_members.partner_id]
  323. members_to_create += [{
  324. 'guest_id': guest.id,
  325. 'channel_id': channel.id,
  326. } for guest in guests - existing_members.guest_id]
  327. new_members = self.env['mail.channel.member'].sudo().create(members_to_create)
  328. for member in new_members.filtered(lambda member: member.partner_id):
  329. # notify invited members through the bus
  330. user = member.partner_id.user_ids[0] if member.partner_id.user_ids else self.env['res.users']
  331. if user:
  332. notifications.append((member.partner_id, 'mail.channel/joined', {
  333. 'channel': member.channel_id.with_user(user).with_context(allowed_company_ids=user.company_ids.ids).sudo().channel_info()[0],
  334. 'invited_by_user_id': self.env.user.id,
  335. 'open_chat_window': open_chat_window,
  336. }))
  337. if post_joined_message:
  338. # notify existing members with a new message in the channel
  339. if member.partner_id == self.env.user.partner_id:
  340. notification = _('<div class="o_mail_notification">joined the channel</div>')
  341. else:
  342. notification = _(
  343. '<div class="o_mail_notification">invited %s to the channel</div>',
  344. member.partner_id._get_html_link(),
  345. )
  346. member.channel_id.message_post(body=notification, message_type="notification", subtype_xmlid="mail.mt_comment")
  347. for member in new_members.filtered(lambda member: member.guest_id):
  348. member.channel_id.message_post(body=_('<div class="o_mail_notification">joined the channel</div>'), message_type="notification", subtype_xmlid="mail.mt_comment")
  349. guest = member.guest_id
  350. if guest:
  351. notifications.append((guest, 'mail.channel/joined', {
  352. 'channel': member.channel_id.sudo().channel_info()[0],
  353. }))
  354. notifications.append((channel, 'mail.channel/insert', {
  355. 'channelMembers': [('insert', list(new_members._mail_channel_member_format().values()))],
  356. 'id': channel.id,
  357. 'memberCount': channel.member_count,
  358. }))
  359. if existing_members:
  360. # If the current user invited these members but they are already present, notify the current user about their existence as well.
  361. # In particular this fixes issues where the current user is not aware of its own member in the following case:
  362. # create channel from form view, and then join from discuss without refreshing the page.
  363. notifications.append((current_partner or current_guest, 'mail.channel/insert', {
  364. 'channelMembers': [('insert', list(existing_members._mail_channel_member_format().values()))],
  365. 'id': channel.id,
  366. 'memberCount': channel.member_count,
  367. }))
  368. if invite_to_rtc_call:
  369. for channel in self:
  370. current_channel_member = self.env['mail.channel.member'].sudo().search([('channel_id', '=', channel.id), ('partner_id', '=', current_partner.id), ('guest_id', '=', current_guest.id)])
  371. if current_channel_member and current_channel_member.rtc_session_ids:
  372. current_channel_member._rtc_invite_members(member_ids=new_members.ids)
  373. self.env['bus.bus']._sendmany(notifications)
  374. def _can_invite(self, partner_id):
  375. """Return True if the current user can invite the partner to the channel.
  376. * channel -- public channel: ok;
  377. * -- group restricted channel: both current user and target must in the group;
  378. * chat/group: current user must be member;
  379. :return boolean: whether inviting is ok"""
  380. partner = self.env['res.partner'].browse(partner_id)
  381. for channel in self.sudo():
  382. if channel.channel_type != 'channel' and not channel.is_member:
  383. return False
  384. if channel.group_public_id:
  385. if not partner.user_ids or channel.group_public_id not in partner.user_ids.groups_id:
  386. return False
  387. if channel.group_public_id not in self.env.user.groups_id:
  388. return False
  389. return True
  390. # ------------------------------------------------------------
  391. # RTC
  392. # ------------------------------------------------------------
  393. def _rtc_cancel_invitations(self, member_ids=None):
  394. """ Cancels the invitations of the RTC call from all invited members,
  395. if member_ids is provided, only the invitations of the specified members are canceled.
  396. :param list member_ids: list of the members ids from which the invitation has to be removed
  397. """
  398. self.ensure_one()
  399. channel_member_domain = [
  400. ('channel_id', '=', self.id),
  401. ('rtc_inviting_session_id', '!=', False),
  402. ]
  403. if member_ids:
  404. channel_member_domain = expression.AND([channel_member_domain, [('id', 'in', member_ids)]])
  405. invitation_notifications = []
  406. members = self.env['mail.channel.member'].search(channel_member_domain)
  407. for member in members:
  408. member.rtc_inviting_session_id = False
  409. if member.partner_id:
  410. target = member.partner_id
  411. else:
  412. target = member.guest_id
  413. invitation_notifications.append((target, 'mail.thread/insert', {
  414. 'id': self.id,
  415. 'model': 'mail.channel',
  416. 'rtcInvitingSession': [('unlink',)],
  417. }))
  418. self.env['bus.bus']._sendmany(invitation_notifications)
  419. channel_data = {'id': self.id, 'model': 'mail.channel'}
  420. if members:
  421. channel_data['invitedMembers'] = [('insert-and-unlink', list(members._mail_channel_member_format(fields={'id': True, 'channel': {}, 'persona': {'partner': {'id', 'name', 'im_status'}, 'guest': {'id', 'name', 'im_status'}}}).values()))]
  422. self.env['bus.bus']._sendone(self, 'mail.thread/insert', channel_data)
  423. return channel_data
  424. # ------------------------------------------------------------
  425. # MAILING
  426. # ------------------------------------------------------------
  427. def _notify_get_recipients(self, message, msg_vals, **kwargs):
  428. """ Override recipients computation as channel is not a standard
  429. mail.thread document. Indeed there are no followers on a channel.
  430. Instead of followers it has members that should be notified.
  431. :param message: see ``MailThread._notify_get_recipients()``;
  432. :param msg_vals: see ``MailThread._notify_get_recipients()``;
  433. :param kwargs: see ``MailThread._notify_get_recipients()``;
  434. :return recipients: structured data holding recipients data. See
  435. ``MailThread._notify_thread()`` for more details about its content
  436. and use;
  437. """
  438. # get values from msg_vals or from message if msg_vals doen't exists
  439. msg_sudo = message.sudo()
  440. message_type = msg_vals.get('message_type', 'email') if msg_vals else msg_sudo.message_type
  441. pids = msg_vals.get('partner_ids', []) if msg_vals else msg_sudo.partner_ids.ids
  442. # notify only user input (comment or incoming emails)
  443. if message_type not in ('comment', 'email'):
  444. return []
  445. # notify only mailing lists or if mentioning recipients
  446. if not pids:
  447. return []
  448. email_from = tools.email_normalize(msg_vals.get('email_from') or msg_sudo.email_from)
  449. author_id = msg_vals.get('author_id') or msg_sudo.author_id.id
  450. recipients_data = []
  451. if pids:
  452. self.env['res.partner'].flush_model(['active', 'email', 'partner_share'])
  453. self.env['res.users'].flush_model(['notification_type', 'partner_id'])
  454. sql_query = """
  455. SELECT DISTINCT ON (partner.id) partner.id,
  456. partner.partner_share,
  457. users.notification_type
  458. FROM res_partner partner
  459. LEFT JOIN res_users users on partner.id = users.partner_id
  460. WHERE partner.active IS TRUE
  461. AND partner.email != %s
  462. AND partner.id = ANY(%s) AND partner.id != ANY(%s)"""
  463. self.env.cr.execute(
  464. sql_query,
  465. (email_from or '', list(pids), [author_id] if author_id else [], )
  466. )
  467. for partner_id, partner_share, notif in self._cr.fetchall():
  468. # ocn_client: will add partners to recipient recipient_data. more ocn notifications. We neeed to filter them maybe
  469. recipients_data.append({
  470. 'id': partner_id,
  471. 'share': partner_share,
  472. 'active': True,
  473. 'notif': notif or 'email',
  474. 'type': 'user' if not partner_share and notif else 'customer',
  475. 'groups': [],
  476. })
  477. return recipients_data
  478. def _notify_get_recipients_groups(self, msg_vals=None):
  479. """ All recipients of a message on a channel are considered as partners.
  480. This means they will receive a minimal email, without a link to access
  481. in the backend. Mailing lists should indeed send minimal emails to avoid
  482. the noise. """
  483. groups = super(Channel, self)._notify_get_recipients_groups(msg_vals=msg_vals)
  484. for (index, (group_name, _group_func, group_data)) in enumerate(groups):
  485. if group_name != 'customer':
  486. groups[index] = (group_name, lambda partner: False, group_data)
  487. return groups
  488. def _notify_thread(self, message, msg_vals=False, **kwargs):
  489. # link message to channel
  490. rdata = super(Channel, self)._notify_thread(message, msg_vals=msg_vals, **kwargs)
  491. message_format_values = message.message_format()[0]
  492. bus_notifications = self._channel_message_notifications(message, message_format_values)
  493. # Last interest and is_pinned are updated for a chat when posting a message.
  494. # So a notification is needed to update UI, and it should come before the
  495. # notification of the message itself to ensure the channel automatically opens.
  496. if self.is_chat or self.channel_type == 'group':
  497. for member in self.channel_member_ids.filtered('partner_id'):
  498. bus_notifications.insert(0, [member.partner_id, 'mail.channel/last_interest_dt_changed', {
  499. 'id': self.id,
  500. 'isServerPinned': member.is_pinned,
  501. 'last_interest_dt': member.last_interest_dt,
  502. }])
  503. self.env['bus.bus'].sudo()._sendmany(bus_notifications)
  504. return rdata
  505. def _message_receive_bounce(self, email, partner):
  506. """ Override bounce management to unsubscribe bouncing addresses """
  507. for p in partner:
  508. if p.message_bounce >= self.MAX_BOUNCE_LIMIT:
  509. self._action_unfollow(p)
  510. return super(Channel, self)._message_receive_bounce(email, partner)
  511. def _message_compute_author(self, author_id=None, email_from=None, raise_on_email=True):
  512. return super()._message_compute_author(author_id=author_id, email_from=email_from, raise_on_email=False)
  513. def _message_compute_parent_id(self, parent_id):
  514. # super() unravels the chain of parents to set parent_id as the first
  515. # ancestor. We don't want that in channel.
  516. if not parent_id:
  517. return parent_id
  518. return self.env['mail.message'].search(
  519. [('id', '=', parent_id),
  520. ('model', '=', self._name),
  521. ('res_id', '=', self.id)
  522. ]).id
  523. @api.returns('mail.message', lambda value: value.id)
  524. def message_post(self, *, message_type='notification', **kwargs):
  525. self.filtered(lambda channel: channel.is_chat or channel.channel_type == 'group').mapped('channel_member_ids').sudo().write({
  526. 'is_pinned': True,
  527. 'last_interest_dt': fields.Datetime.now(),
  528. })
  529. # mail_post_autofollow=False is necessary to prevent adding followers
  530. # when using mentions in channels. Followers should not be added to
  531. # channels, and especially not automatically (because channel membership
  532. # should be managed with mail.channel.member instead).
  533. # The current client code might be setting the key to True on sending
  534. # message but it is only useful when targeting customers in chatter.
  535. # This value should simply be set to False in channels no matter what.
  536. return super(Channel, self.with_context(mail_create_nosubscribe=True, mail_post_autofollow=False)).message_post(message_type=message_type, **kwargs)
  537. def _message_post_after_hook(self, message, msg_vals):
  538. """
  539. Automatically set the message posted by the current user as seen for themselves.
  540. """
  541. self._set_last_seen_message(message)
  542. return super()._message_post_after_hook(message=message, msg_vals=msg_vals)
  543. def _check_can_update_message_content(self, message):
  544. """ We don't call super in this override as we want to ignore the
  545. mail.thread behavior completely """
  546. if not message.message_type == 'comment':
  547. raise UserError(_("Only messages type comment can have their content updated on model 'mail.channel'"))
  548. def _message_update_content_after_hook(self, message):
  549. self.ensure_one()
  550. self.env['bus.bus']._sendone(self, 'mail.message/insert', {
  551. 'id': message.id,
  552. 'body': message.body,
  553. 'attachments': message.attachment_ids._attachment_format(),
  554. })
  555. return super()._message_update_content_after_hook(message=message)
  556. def _message_add_reaction_after_hook(self, message, content):
  557. self.ensure_one()
  558. guest = self.env['mail.guest']._get_guest_from_context()
  559. if self.env.user._is_public() and guest:
  560. guests = [('insert', {'id': guest.id})]
  561. partners = []
  562. else:
  563. guests = []
  564. partners = [('insert', {'id': self.env.user.partner_id.id})]
  565. reactions = self.env['mail.message.reaction'].sudo().search([('message_id', '=', message.id), ('content', '=', content)])
  566. self.env['bus.bus']._sendone(self, 'mail.message/insert', {
  567. 'id': message.id,
  568. 'messageReactionGroups': [('insert' if len(reactions) > 0 else 'insert-and-unlink', {
  569. 'content': content,
  570. 'count': len(reactions),
  571. 'guests': guests,
  572. 'message': {'id': message.id},
  573. 'partners': partners,
  574. })],
  575. })
  576. return super()._message_add_reaction_after_hook(message=message, content=content)
  577. def _message_remove_reaction_after_hook(self, message, content):
  578. self.ensure_one()
  579. guest = self.env['mail.guest']._get_guest_from_context()
  580. if self.env.user._is_public() and guest:
  581. guests = [('insert-and-unlink', {'id': guest.id})]
  582. partners = []
  583. else:
  584. guests = []
  585. partners = [('insert-and-unlink', {'id': self.env.user.partner_id.id})]
  586. reactions = self.env['mail.message.reaction'].sudo().search([('message_id', '=', message.id), ('content', '=', content)])
  587. self.env['bus.bus']._sendone(self, 'mail.message/insert', {
  588. 'id': message.id,
  589. 'messageReactionGroups': [('insert' if len(reactions) > 0 else 'insert-and-unlink', {
  590. 'content': content,
  591. 'count': len(reactions),
  592. 'guests': guests,
  593. 'message': {'id': message.id},
  594. 'partners': partners,
  595. })],
  596. })
  597. return super()._message_remove_reaction_after_hook(message=message, content=content)
  598. def _message_subscribe(self, partner_ids=None, subtype_ids=None, customer_ids=None):
  599. """ Do not allow follower subscription on channels. Only members are
  600. considered. """
  601. raise UserError(_('Adding followers on channels is not possible. Consider adding members instead.'))
  602. # ------------------------------------------------------------
  603. # BROADCAST
  604. # ------------------------------------------------------------
  605. # Anonymous method
  606. def _broadcast(self, partner_ids):
  607. """ Broadcast the current channel header to the given partner ids
  608. :param partner_ids : the partner to notify
  609. """
  610. notifications = self._channel_channel_notifications(partner_ids)
  611. self.env['bus.bus']._sendmany(notifications)
  612. def _channel_channel_notifications(self, partner_ids):
  613. """ Generate the bus notifications of current channel for the given partner ids
  614. :param partner_ids : the partner to send the current channel header
  615. :returns list of bus notifications (tuple (bus_channe, message_content))
  616. """
  617. notifications = []
  618. for partner in self.env['res.partner'].browse(partner_ids):
  619. user_id = partner.user_ids and partner.user_ids[0] or False
  620. if user_id:
  621. user_channels = self.with_user(user_id).with_context(
  622. allowed_company_ids=user_id.company_ids.ids
  623. )
  624. for channel_info in user_channels.channel_info():
  625. notifications.append((partner, 'mail.channel/legacy_insert', channel_info))
  626. return notifications
  627. def _channel_message_notifications(self, message, message_format=False):
  628. """ Generate the bus notifications for the given message
  629. :param message : the mail.message to sent
  630. :returns list of bus notifications (tuple (bus_channe, message_content))
  631. """
  632. message_format = message_format or message.message_format()[0]
  633. notifications = []
  634. for channel in self:
  635. payload = {
  636. 'id': channel.id,
  637. 'message': dict(message_format),
  638. }
  639. notifications.append((channel, 'mail.channel/new_message', payload))
  640. return notifications
  641. # ------------------------------------------------------------
  642. # INSTANT MESSAGING API
  643. # ------------------------------------------------------------
  644. # A channel header should be broadcasted:
  645. # - when adding user to channel (only to the new added partners)
  646. # - when folding/minimizing a channel (only to the user making the action)
  647. # A message should be broadcasted:
  648. # - when a message is posted on a channel (to the channel, using _notify() method)
  649. # ------------------------------------------------------------
  650. def channel_info(self):
  651. """ Get the informations header for the current channels
  652. :returns a list of channels values
  653. :rtype : list(dict)
  654. """
  655. if not self:
  656. return []
  657. channel_infos = []
  658. rtc_sessions_by_channel = self.sudo().rtc_session_ids._mail_rtc_session_format_by_channel()
  659. channel_last_message_ids = dict((r['id'], r['message_id']) for r in self._channel_last_message_ids())
  660. current_partner = self.env['res.partner']
  661. current_guest = self.env['mail.guest']
  662. guest = self.env['mail.guest']._get_guest_from_context()
  663. if self.env.user._is_public and guest:
  664. current_guest = guest
  665. else:
  666. current_partner = self.env.user.partner_id
  667. all_needed_members_domain = expression.OR([
  668. [('channel_id.channel_type', '!=', 'channel')],
  669. [('rtc_inviting_session_id', '!=', False)],
  670. [('partner_id', '=', current_partner.id) if current_partner else expression.FALSE_LEAF],
  671. [('guest_id', '=', current_guest.id) if current_guest else expression.FALSE_LEAF],
  672. ])
  673. all_needed_members = self.env['mail.channel.member'].search(expression.AND([[('channel_id', 'in', self.ids)], all_needed_members_domain]), order='id')
  674. all_needed_members.partner_id.sudo().mail_partner_format() # prefetch in batch
  675. members_by_channel = defaultdict(lambda: self.env['mail.channel.member'])
  676. invited_members_by_channel = defaultdict(lambda: self.env['mail.channel.member'])
  677. member_of_current_user_by_channel = defaultdict(lambda: self.env['mail.channel.member'])
  678. for member in all_needed_members:
  679. members_by_channel[member.channel_id] |= member
  680. if member.rtc_inviting_session_id:
  681. invited_members_by_channel[member.channel_id] |= member
  682. if (current_partner and member.partner_id == current_partner) or (current_guest and member.guest_id == current_guest):
  683. member_of_current_user_by_channel[member.channel_id] = member
  684. for channel in self:
  685. channel_data = {
  686. 'avatarCacheKey': channel._get_avatar_cache_key(),
  687. 'channel_type': channel.channel_type,
  688. 'id': channel.id,
  689. 'memberCount': channel.member_count,
  690. }
  691. info = {
  692. 'id': channel.id,
  693. 'name': channel.name,
  694. 'defaultDisplayMode': channel.default_display_mode,
  695. 'description': channel.description,
  696. 'uuid': channel.uuid,
  697. 'state': 'open',
  698. 'is_minimized': False,
  699. 'group_based_subscription': bool(channel.group_ids),
  700. 'create_uid': channel.create_uid.id,
  701. 'authorizedGroupFullName': channel.group_public_id.full_name,
  702. }
  703. # add last message preview (only used in mobile)
  704. info['last_message_id'] = channel_last_message_ids.get(channel.id, False)
  705. # find the channel member state
  706. if current_partner or current_guest:
  707. info['message_needaction_counter'] = channel.message_needaction_counter
  708. member = member_of_current_user_by_channel.get(channel, self.env['mail.channel.member']).with_prefetch([m.id for m in member_of_current_user_by_channel.values()])
  709. if member:
  710. channel_data['channelMembers'] = [('insert', list(member._mail_channel_member_format().values()))]
  711. info['state'] = member.fold_state or 'open'
  712. channel_data['serverMessageUnreadCounter'] = member.message_unread_counter
  713. info['is_minimized'] = member.is_minimized
  714. info['seen_message_id'] = member.seen_message_id.id
  715. channel_data['custom_channel_name'] = member.custom_channel_name
  716. info['is_pinned'] = member.is_pinned
  717. info['last_interest_dt'] = member.last_interest_dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
  718. if member.rtc_inviting_session_id:
  719. info['rtc_inviting_session'] = {'id': member.rtc_inviting_session_id.id}
  720. # add members info
  721. if channel.channel_type != 'channel':
  722. # avoid sending potentially a lot of members for big channels
  723. # exclude chat and other small channels from this optimization because they are
  724. # assumed to be smaller and it's important to know the member list for them
  725. channel_data['channelMembers'] = [('insert', list(members_by_channel[channel]._mail_channel_member_format().values()))]
  726. info['seen_partners_info'] = sorted([{
  727. 'id': cp.id,
  728. 'partner_id': cp.partner_id.id,
  729. 'fetched_message_id': cp.fetched_message_id.id,
  730. 'seen_message_id': cp.seen_message_id.id,
  731. } for cp in members_by_channel[channel] if cp.partner_id], key=lambda p: p['partner_id'])
  732. # add RTC sessions info
  733. info.update({
  734. 'invitedMembers': [('insert', list(invited_members_by_channel[channel]._mail_channel_member_format(fields={'id': True, 'channel': {}, 'persona': {'partner': {'id', 'name', 'im_status'}, 'guest': {'id', 'name', 'im_status'}}}).values()))],
  735. 'rtcSessions': [('insert', rtc_sessions_by_channel.get(channel, []))],
  736. })
  737. info['channel'] = channel_data
  738. channel_infos.append(info)
  739. return channel_infos
  740. def _channel_fetch_message(self, last_id=False, limit=20):
  741. """ Return message values of the current channel.
  742. :param last_id : last message id to start the research
  743. :param limit : maximum number of messages to fetch
  744. :returns list of messages values
  745. :rtype : list(dict)
  746. """
  747. self.ensure_one()
  748. domain = ["&", ("model", "=", "mail.channel"), ("res_id", "in", self.ids)]
  749. if last_id:
  750. domain.append(("id", "<", last_id))
  751. return self.env['mail.message']._message_fetch(domain=domain, limit=limit).message_format()
  752. def _channel_format(self, fields=None):
  753. if not fields:
  754. fields = {'id': True}
  755. channels_formatted_data = {}
  756. for channel in self:
  757. data = {}
  758. if 'id' in fields:
  759. data['id'] = channel.id
  760. channels_formatted_data[channel] = data
  761. return channels_formatted_data
  762. # User methods
  763. @api.model
  764. def channel_get(self, partners_to, pin=True):
  765. """ Get the canonical private channel between some partners, create it if needed.
  766. To reuse an old channel (conversation), this one must be private, and contains
  767. only the given partners.
  768. :param partners_to : list of res.partner ids to add to the conversation
  769. :param pin : True if getting the channel should pin it for the current user
  770. :returns: channel_info of the created or existing channel
  771. :rtype: dict
  772. """
  773. if self.env.user.partner_id.id not in partners_to:
  774. partners_to.append(self.env.user.partner_id.id)
  775. if len(partners_to) > 2:
  776. raise UserError(_("A chat should not be created with more than 2 persons. Create a group instead."))
  777. # determine type according to the number of partner in the channel
  778. self.flush_model()
  779. self.env['mail.channel.member'].flush_model()
  780. self.env.cr.execute("""
  781. SELECT M.channel_id
  782. FROM mail_channel C, mail_channel_member M
  783. WHERE M.channel_id = C.id
  784. AND M.partner_id IN %s
  785. AND C.channel_type LIKE 'chat'
  786. AND NOT EXISTS (
  787. SELECT 1
  788. FROM mail_channel_member M2
  789. WHERE M2.channel_id = C.id
  790. AND M2.partner_id NOT IN %s
  791. )
  792. GROUP BY M.channel_id
  793. HAVING ARRAY_AGG(DISTINCT M.partner_id ORDER BY M.partner_id) = %s
  794. LIMIT 1
  795. """, (tuple(partners_to), tuple(partners_to), sorted(list(partners_to)),))
  796. result = self.env.cr.dictfetchall()
  797. if result:
  798. # get the existing channel between the given partners
  799. channel = self.browse(result[0].get('channel_id'))
  800. # pin up the channel for the current partner
  801. if pin:
  802. self.env['mail.channel.member'].search([('partner_id', '=', self.env.user.partner_id.id), ('channel_id', '=', channel.id)]).write({
  803. 'is_pinned': True,
  804. 'last_interest_dt': fields.Datetime.now(),
  805. })
  806. channel._broadcast(self.env.user.partner_id.ids)
  807. else:
  808. # create a new one
  809. channel = self.create({
  810. 'channel_partner_ids': [Command.link(partner_id) for partner_id in partners_to],
  811. 'channel_member_ids': [
  812. Command.create({
  813. 'partner_id': partner_id,
  814. # only pin for the current user, so the chat does not show up for the correspondent until a message has been sent
  815. 'is_pinned': partner_id == self.env.user.partner_id.id
  816. }) for partner_id in partners_to
  817. ],
  818. 'channel_type': 'chat',
  819. 'name': ', '.join(self.env['res.partner'].sudo().browse(partners_to).mapped('name')),
  820. })
  821. channel._broadcast(partners_to)
  822. return channel.channel_info()[0]
  823. def channel_fold(self, state=None):
  824. """ Update the fold_state of the given session. In order to syncronize web browser
  825. tabs, the change will be broadcast to themselves (the current user channel).
  826. Note: the user need to be logged
  827. :param state : the new status of the session for the current user.
  828. """
  829. domain = [('partner_id', '=', self.env.user.partner_id.id), ('channel_id', 'in', self.ids)]
  830. for session_state in self.env['mail.channel.member'].search(domain):
  831. if not state:
  832. state = session_state.fold_state
  833. if session_state.fold_state == 'open':
  834. state = 'folded'
  835. else:
  836. state = 'open'
  837. is_minimized = bool(state != 'closed')
  838. vals = {}
  839. if session_state.fold_state != state:
  840. vals['fold_state'] = state
  841. if session_state.is_minimized != is_minimized:
  842. vals['is_minimized'] = is_minimized
  843. if vals:
  844. session_state.write(vals)
  845. self.env['bus.bus']._sendone(self.env.user.partner_id, 'mail.thread/insert', {
  846. 'id': session_state.channel_id.id,
  847. 'model': 'mail.channel',
  848. 'serverFoldState': state,
  849. })
  850. def channel_pin(self, pinned=False):
  851. self.ensure_one()
  852. member = self.env['mail.channel.member'].search(
  853. [('partner_id', '=', self.env.user.partner_id.id), ('channel_id', '=', self.id), ('is_pinned', '!=', pinned)])
  854. if member:
  855. member.write({'is_pinned': pinned})
  856. if not pinned:
  857. self.env['bus.bus']._sendone(self.env.user.partner_id, 'mail.channel/unpin', {'id': self.id})
  858. else:
  859. self.env['bus.bus']._sendone(self.env.user.partner_id, 'mail.channel/legacy_insert', self.channel_info()[0])
  860. def _channel_seen(self, last_message_id=None):
  861. """
  862. Mark channel as seen by updating seen message id of the current logged partner
  863. :param last_message_id: the id of the message to be marked as seen, last message of the
  864. thread by default. This param SHOULD be required, the default behaviour is DEPRECATED and
  865. kept only for compatibility reasons.
  866. """
  867. self.ensure_one()
  868. domain = ["&", ("model", "=", "mail.channel"), ("res_id", "in", self.ids)]
  869. if last_message_id:
  870. domain = expression.AND([domain, [('id', '<=', last_message_id)]])
  871. last_message = self.env['mail.message'].search(domain, order="id DESC", limit=1)
  872. if not last_message:
  873. return
  874. self._set_last_seen_message(last_message)
  875. data = {
  876. 'channel_id': self.id,
  877. 'last_message_id': last_message.id,
  878. 'partner_id': self.env.user.partner_id.id,
  879. }
  880. target = self if self.channel_type == 'chat' else self.env.user.partner_id
  881. self.env['bus.bus']._sendone(target, 'mail.channel.member/seen', data)
  882. return last_message.id
  883. def _set_last_seen_message(self, last_message):
  884. """
  885. Set last seen message of `self` channels for the current user.
  886. :param last_message: the message to set as last seen message
  887. """
  888. channel_member_domain = expression.AND([
  889. [('channel_id', 'in', self.ids)],
  890. [('partner_id', '=', self.env.user.partner_id.id)],
  891. expression.OR([
  892. [('seen_message_id', '=', False)],
  893. [('seen_message_id', '<', last_message.id)]
  894. ])
  895. ])
  896. member = self.env['mail.channel.member'].search(channel_member_domain)
  897. member.write({
  898. 'fetched_message_id': last_message.id,
  899. 'seen_message_id': last_message.id,
  900. 'last_seen_dt': fields.Datetime.now(),
  901. })
  902. def channel_fetched(self):
  903. """ Broadcast the channel_fetched notification to channel members
  904. """
  905. for channel in self:
  906. if not channel.message_ids.ids:
  907. return
  908. if channel.channel_type != 'chat':
  909. return
  910. last_message_id = channel.message_ids.ids[0] # zero is the index of the last message
  911. member = self.env['mail.channel.member'].search([('channel_id', '=', channel.id), ('partner_id', '=', self.env.user.partner_id.id)], limit=1)
  912. if member.fetched_message_id.id == last_message_id:
  913. # last message fetched by user is already up-to-date
  914. return
  915. # Avoid serialization error when multiple tabs are opened.
  916. query = """
  917. UPDATE mail_channel_member
  918. SET fetched_message_id = %s
  919. WHERE id IN (
  920. SELECT id FROM mail_channel_member WHERE id = %s
  921. FOR NO KEY UPDATE SKIP LOCKED
  922. )
  923. """
  924. self.env.cr.execute(query, (last_message_id, member.id))
  925. self.env['bus.bus']._sendone(channel, 'mail.channel.member/fetched', {
  926. 'channel_id': channel.id,
  927. 'id': member.id,
  928. 'last_message_id': last_message_id,
  929. 'partner_id': self.env.user.partner_id.id,
  930. })
  931. def channel_set_custom_name(self, name):
  932. self.ensure_one()
  933. member = self.env['mail.channel.member'].search([('partner_id', '=', self.env.user.partner_id.id), ('channel_id', '=', self.id)])
  934. member.write({'custom_channel_name': name})
  935. self.env['bus.bus']._sendone(member.partner_id, 'mail.channel/insert', {
  936. 'custom_channel_name': name,
  937. 'id': self.id,
  938. })
  939. def channel_rename(self, name):
  940. self.ensure_one()
  941. self.write({'name': name})
  942. self.env['bus.bus']._sendone(self, 'mail.thread/insert', {
  943. 'id': self.id,
  944. 'model': 'mail.channel',
  945. 'name': name,
  946. })
  947. def channel_change_description(self, description):
  948. self.ensure_one()
  949. self.write({'description': description})
  950. self.env['bus.bus']._sendone(self, 'mail.thread/insert', {
  951. 'id': self.id,
  952. 'description': description,
  953. 'model': 'mail.channel',
  954. })
  955. def channel_join(self):
  956. """ Shortcut to add the current user as member of self channels.
  957. Prefer calling add_members() directly when possible.
  958. """
  959. self.add_members(self.env.user.partner_id.ids)
  960. @api.model
  961. def channel_create(self, name, group_id):
  962. """ Create a channel and add the current partner, broadcast it (to make the user directly
  963. listen to it when polling)
  964. :param name : the name of the channel to create
  965. :param group_id : the group allowed to join the channel.
  966. :return dict : channel header
  967. """
  968. # create the channel
  969. vals = {
  970. 'channel_type': 'channel',
  971. 'name': name,
  972. }
  973. new_channel = self.create(vals)
  974. group = self.env['res.groups'].search([('id', '=', group_id)]) if group_id else None
  975. new_channel.group_public_id = group.id if group else None
  976. notification = _('<div class="o_mail_notification">created <a href="#" class="o_channel_redirect" data-oe-id="%s">#%s</a></div>', new_channel.id, new_channel.name)
  977. new_channel.message_post(body=notification, message_type="notification", subtype_xmlid="mail.mt_comment")
  978. channel_info = new_channel.channel_info()[0]
  979. self.env['bus.bus']._sendone(self.env.user.partner_id, 'mail.channel/legacy_insert', channel_info)
  980. return channel_info
  981. @api.model
  982. def create_group(self, partners_to, default_display_mode=False, name=''):
  983. """ Creates a group channel.
  984. :param partners_to : list of res.partner ids to add to the conversation
  985. :param str default_display_mode: how the channel will be displayed by default
  986. :param str name: group name. default name is computed client side from the list of members if no name is set
  987. :returns: channel_info of the created channel
  988. :rtype: dict
  989. """
  990. channel = self.create({
  991. 'channel_member_ids': [Command.create({'partner_id': partner_id}) for partner_id in partners_to],
  992. 'channel_type': 'group',
  993. 'default_display_mode': default_display_mode,
  994. 'name': name,
  995. })
  996. channel._broadcast(partners_to)
  997. return channel.channel_info()[0]
  998. @api.model
  999. def get_mention_suggestions(self, search, limit=8):
  1000. """ Return 'limit'-first channels' id, name, channel_type and authorizedGroupFullName fields such that the
  1001. name matches a 'search' string. Exclude channels of type chat (DM) and group.
  1002. """
  1003. domain = expression.AND([
  1004. [('name', 'ilike', search)],
  1005. [('channel_type', '=', 'channel')],
  1006. [('channel_partner_ids', 'in', [self.env.user.partner_id.id])]
  1007. ])
  1008. channels = self.search(domain, limit=limit)
  1009. return [{
  1010. 'authorizedGroupFullName': channel.group_public_id.full_name,
  1011. 'channel': {
  1012. 'channel_type': channel.channel_type,
  1013. 'id': channel.id,
  1014. },
  1015. 'id': channel.id,
  1016. 'name': channel.name,
  1017. } for channel in channels]
  1018. def channel_fetch_preview(self):
  1019. """ Return the last message of the given channels """
  1020. if not self:
  1021. return []
  1022. channels_last_message_ids = self._channel_last_message_ids()
  1023. channels_preview = dict((r['message_id'], r) for r in channels_last_message_ids)
  1024. last_messages = self.env['mail.message'].browse(channels_preview).message_format()
  1025. for message in last_messages:
  1026. channel = channels_preview[message['id']]
  1027. del(channel['message_id'])
  1028. channel['last_message'] = message
  1029. return list(channels_preview.values())
  1030. def _channel_last_message_ids(self):
  1031. """ Return the last message of the given channels."""
  1032. if not self:
  1033. return []
  1034. self.env['mail.message'].flush_model()
  1035. self.env.cr.execute("""
  1036. SELECT res_id AS id, MAX(id) AS message_id
  1037. FROM mail_message
  1038. WHERE model = 'mail.channel' AND res_id IN %s
  1039. GROUP BY res_id
  1040. """, (tuple(self.ids),))
  1041. return self.env.cr.dictfetchall()
  1042. def load_more_members(self, known_member_ids):
  1043. self.ensure_one()
  1044. unknown_members = self.env['mail.channel.member'].search(
  1045. domain=[('id', 'not in', known_member_ids), ('channel_id', '=', self.id)],
  1046. limit=100
  1047. )
  1048. count = self.env['mail.channel.member'].search_count(
  1049. domain=[('channel_id', '=', self.id)],
  1050. )
  1051. return {
  1052. 'channelMembers': [('insert', list(unknown_members._mail_channel_member_format().values()))],
  1053. 'memberCount': count,
  1054. }
  1055. def _get_avatar_cache_key(self):
  1056. if not self.avatar_128:
  1057. return 'no-avatar'
  1058. return sha512(self.avatar_128).hexdigest()
  1059. # ------------------------------------------------------------
  1060. # COMMANDS
  1061. # ------------------------------------------------------------
  1062. def _send_transient_message(self, partner_to, content):
  1063. """ Notifies partner_to that a message (not stored in DB) has been
  1064. written in this channel.
  1065. `content` is HTML, dynamic parts should be escaped by the caller.
  1066. """
  1067. self.env['bus.bus']._sendone(partner_to, 'mail.channel/transient_message', {
  1068. 'body': "<span class='o_mail_notification'>" + content + "</span>",
  1069. 'model': self._name,
  1070. 'res_id': self.id,
  1071. })
  1072. def execute_command_help(self, **kwargs):
  1073. partner = self.env.user.partner_id
  1074. if self.channel_type == 'channel':
  1075. msg = _("You are in channel <b>#%s</b>.", html_escape(self.name))
  1076. else:
  1077. all_channel_members = self.env['mail.channel.member'].with_context(active_test=False)
  1078. channel_members = all_channel_members.search([('partner_id', '!=', partner.id), ('channel_id', '=', self.id)])
  1079. msg = _("You are in a private conversation with <b>@%s</b>.", _(" @").join(html_escape(member.partner_id.name or member.guest_id.name) for member in channel_members) if channel_members else _("Anonymous"))
  1080. msg += self._execute_command_help_message_extra()
  1081. self._send_transient_message(partner, msg)
  1082. def _execute_command_help_message_extra(self):
  1083. msg = _("""<br><br>
  1084. Type <b>@username</b> to mention someone, and grab their attention.<br>
  1085. Type <b>#channel</b> to mention a channel.<br>
  1086. Type <b>/command</b> to execute a command.<br>""")
  1087. return msg
  1088. def execute_command_leave(self, **kwargs):
  1089. if self.channel_type in ('channel', 'group'):
  1090. self.action_unfollow()
  1091. else:
  1092. self.channel_pin(False)
  1093. def execute_command_who(self, **kwargs):
  1094. channel_members = self.env['mail.channel.member'].with_context(active_test=False).search([('partner_id', '!=', self.env.user.partner_id.id), ('channel_id', '=', self.id)])
  1095. members = [
  1096. m.partner_id._get_html_link(title=f"@{m.partner_id.name}") if m.partner_id else f'<strong>@{html_escape(m.guest_id.name)}</strong>'
  1097. for m in channel_members[:30]
  1098. ]
  1099. if len(members) == 0:
  1100. msg = _("You are alone in this channel.")
  1101. else:
  1102. dots = "..." if len(members) != len(channel_members) else ""
  1103. msg = _("Users in this channel: %(members)s %(dots)s and you.", members=", ".join(members), dots=dots)
  1104. self._send_transient_message(self.env.user.partner_id, msg)