Debian Codegraph @

addons/mail/models/discuss/discuss_channel_rtc_session.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import logging
4 import requests
5
6 from collections import defaultdict
7 from dateutil.relativedelta import relativedelta
8 from markupsafe import Markup
9
10 from odoo import api, fields, models
11 from odoo.addons.mail.tools import discuss, jwt
12 from odoo.addons.mail.tools.discuss import Store
13
14 _logger = logging.getLogger(__name__)
15
16
17 class DiscussChannelRtcSession(models.Model):
18 _name = 'discuss.channel.rtc.session'
19 _inherit = ["bus.listener.mixin"]
20 _description = 'Mail RTC session'
21 _rec_name = 'channel_member_id'
22
23 channel_member_id = fields.Many2one('discuss.channel.member', required=True, ondelete='cascade')
24 channel_id = fields.Many2one('discuss.channel', related='channel_member_id.channel_id', store=True, readonly=True, index='btree_not_null')
25 partner_id = fields.Many2one('res.partner', related='channel_member_id.partner_id', string="Partner", store=True, index=True)
26 guest_id = fields.Many2one('mail.guest', related='channel_member_id.guest_id')
27
28 write_date = fields.Datetime("Last Updated On", index=True)
29
30 is_screen_sharing_on = fields.Boolean(string="Is sharing the screen")
31 is_camera_on = fields.Boolean(string="Is sending user video")
32 is_muted = fields.Boolean(string="Is microphone muted")
33 is_deaf = fields.Boolean(string="Has disabled incoming sound")
34
35 _channel_member_unique = models.Constraint(
36 'UNIQUE(channel_member_id)',
37 'There can only be one rtc session per channel member',
38 )
39
40 @api.model_create_multi
41 def create(self, vals_list):
42 rtc_sessions = super().create(vals_list)
43 rtc_sessions_by_channel = defaultdict(lambda: self.env["discuss.channel.rtc.session"])
44 for rtc_session in rtc_sessions:
45 rtc_sessions_by_channel[rtc_session.channel_id] += rtc_session
46 for channel, rtc_sessions in rtc_sessions_by_channel.items():
47 Store(bus_channel=channel).add(
48 channel,
49 {"rtc_session_ids": Store.Many(rtc_sessions, mode="ADD")},
50 ).bus_send()
51 for channel in rtc_sessions.channel_id.filtered(lambda c: len(c.rtc_session_ids) == 1):
52 body = Markup('<div data-oe-type="call" class="o_mail_notification"></div>')
53 message = channel.message_post(body=body, message_type="notification")
54 # sudo - discuss.call.history: can create call history when call is created.
55 self.env["discuss.call.history"].sudo().create(
56 {
57 "channel_id": channel.id,
58 "start_dt": fields.Datetime.now(),
59 "start_call_message_id": message.id,
60 },
61 )
62 Store(bus_channel=channel).add(message, [Store.Many("call_history_ids", [])]).bus_send()
63 return rtc_sessions
64
65 def unlink(self):
66 call_ended_channels = self.channel_id.filtered(lambda c: not (c.rtc_session_ids - self))
67 for channel in call_ended_channels:
68 # If there is no member left in the RTC call, all invitations are cancelled.
69 # Note: invitation depends on field `rtc_inviting_session_id` so the cancel must be
70 # done before the delete to be able to know who was invited.
71 channel._rtc_cancel_invitations()
72 # If there is no member left in the RTC call, we remove the SFU channel uuid as the SFU
73 # server will timeout the channel. It is better to obtain a new channel from the SFU server
74 # than to attempt recycling a possibly stale channel uuid.
75 channel.sfu_channel_uuid = False
76 channel.sfu_server_url = False
77 rtc_sessions_by_channel = defaultdict(lambda: self.env["discuss.channel.rtc.session"])
78 for rtc_session in self:
79 rtc_sessions_by_channel[rtc_session.channel_id] += rtc_session
80 for channel, rtc_sessions in rtc_sessions_by_channel.items():
81 Store(bus_channel=channel).add(
82 channel,
83 {"rtc_session_ids": Store.Many(rtc_sessions, [], mode="DELETE")},
84 ).bus_send()
85 for rtc_session in self:
86 rtc_session._bus_send(
87 "discuss.channel.rtc.session/ended", {"sessionId": rtc_session.id}
88 )
89 # sudo - dicuss.rtc.call.history: setting the end date of the call
90 # after it ends is allowed.
91 for history in (
92 self.env["discuss.call.history"]
93 .sudo()
94 .search([("channel_id", "in", call_ended_channels.ids), ("end_dt", "=", False)])
95 ):
96 history.end_dt = fields.Datetime.now()
97 Store(bus_channel=history.channel_id).add(
98 history,
99 ["duration_hour", "end_dt"],
100 ).bus_send()
101 return super().unlink()
102
103 def _bus_channel(self):
104 return self.channel_member_id._bus_channel()
105
106 def _update_and_broadcast(self, values):
107 """ Updates the session and notifies all members of the channel
108 of the change.
109 """
110 valid_values = {'is_screen_sharing_on', 'is_camera_on', 'is_muted', 'is_deaf'}
111 self.write({key: values[key] for key in valid_values if key in values})
112 store = Store().add(self, extra_fields=self._get_store_extra_fields())
113 self.channel_id._bus_send(
114 "discuss.channel.rtc.session/update_and_broadcast",
115 {"data": store.get_result(), "channelId": self.channel_id.id},
116 )
117
118 @api.autovacuum
119 def _gc_inactive_sessions(self):
120 """ Garbage collect sessions that aren't active anymore,
121 this can happen when the server or the user's browser crash
122 or when the user's odoo session ends.
123 """
124 self.search(self._inactive_rtc_session_domain()).unlink()
125
126 def action_disconnect(self):
127 session_ids_by_channel_by_url = defaultdict(lambda: defaultdict(list))
128 for rtc_session in self:
129 sfu_channel_uuid = rtc_session.channel_id.sfu_channel_uuid
130 url = rtc_session.channel_id.sfu_server_url
131 if sfu_channel_uuid and url:
132 session_ids_by_channel_by_url[url][sfu_channel_uuid].append(rtc_session.id)
133 key = discuss.get_sfu_key(self.env)
134 if key:
135 with requests.Session() as requests_session:
136 for url, session_ids_by_channel in session_ids_by_channel_by_url.items():
137 try:
138 requests_session.post(
139 url + '/v1/disconnect',
140 data=jwt.sign({'sessionIdsByChannel': session_ids_by_channel}, key=key, ttl=20, algorithm=jwt.Algorithm.HS256),
141 timeout=3
142 ).raise_for_status()
143 except requests.exceptions.RequestException as error:
144 _logger.warning("Could not disconnect sessions at sfu server %s: %s", url, error)
145 self.unlink()
146
147 def _delete_inactive_rtc_sessions(self):
148 """Deletes the inactive sessions from self."""
149 self.filtered_domain(self._inactive_rtc_session_domain()).unlink()
150
151 def _notify_peers(self, notifications):
152 """ Used for peer-to-peer communication,
153 guarantees that the sender is the current guest or partner.
154
155 :param notifications: list of tuple with the following elements:
156 - target_session_ids: a list of discuss.channel.rtc.session ids
157 - content: a string with the content to be sent to the targets
158 """
159 self.ensure_one()
160 payload_by_target = defaultdict(lambda: {'sender': self.id, 'notifications': []})
161 for target_session_ids, content in notifications:
162 for target_session in self.env['discuss.channel.rtc.session'].browse(target_session_ids).exists():
163 payload_by_target[target_session]['notifications'].append(content)
164 for target, payload in payload_by_target.items():
165 target._bus_send("discuss.channel.rtc.session/peer_notification", payload)
166
167 def _to_store_defaults(self, target):
168 return Store.One(
169 "channel_member_id",
170 [
171 Store.One("channel_id", [], as_thread=True),
172 *self.env["discuss.channel.member"]._to_store_persona("avatar_card"),
173 ],
174 )
175
176 def _get_store_extra_fields(self):
177 return ["is_camera_on", "is_deaf", "is_muted", "is_screen_sharing_on"]
178
179 @api.model
180 def _inactive_rtc_session_domain(self):
181 return [('write_date', '<', fields.Datetime.now() - relativedelta(minutes=1, seconds=15))]