4143
|
1 #!/usr/bin/env python3 |
|
2 |
|
3 |
|
4 # Libervia CLI |
|
5 # Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org) |
|
6 |
|
7 # This program is free software: you can redistribute it and/or modify |
|
8 # it under the terms of the GNU Affero General Public License as published by |
|
9 # the Free Software Foundation, either version 3 of the License, or |
|
10 # (at your option) any later version. |
|
11 |
|
12 # This program is distributed in the hope that it will be useful, |
|
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
15 # GNU Affero General Public License for more details. |
|
16 |
|
17 # You should have received a copy of the GNU Affero General Public License |
|
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
19 |
|
20 |
|
21 from argparse import ArgumentParser |
|
22 import asyncio |
4206
|
23 from dataclasses import dataclass |
4143
|
24 from functools import partial |
|
25 import logging |
|
26 import os |
4206
|
27 from pathlib import Path |
|
28 from typing import Callable |
4143
|
29 |
|
30 from prompt_toolkit.input import create_input |
|
31 from prompt_toolkit.keys import Keys |
|
32 |
|
33 from libervia.backend.core.i18n import _ |
|
34 from libervia.backend.tools.common import data_format |
|
35 from libervia.cli.constants import Const as C |
|
36 from libervia.frontends.tools import aio, jid |
|
37 from rich.columns import Columns |
|
38 from rich.console import group |
|
39 from rich.live import Live |
|
40 from rich.panel import Panel |
|
41 from rich.text import Text |
|
42 |
|
43 from . import base |
|
44 |
|
45 __commands__ = ["Call"] |
|
46 |
|
47 |
4206
|
48 @dataclass |
|
49 class CallData: |
|
50 callee: jid.JID |
|
51 sid: str|None = None |
|
52 action_id: str|None = None |
|
53 |
|
54 |
4143
|
55 class WebRTCCall: |
4206
|
56 def __init__(self, host, profile: str, callee: jid.JID, **kwargs): |
|
57 """Create and setup a webRTC instance |
|
58 |
|
59 @param profile: profile making or receiving the call |
|
60 @param callee: peer jid |
|
61 @param kwargs: extra kw args to use when instantiating WebRTC |
|
62 """ |
4143
|
63 from libervia.frontends.tools import webrtc |
|
64 |
|
65 aio.install_glib_asyncio_iteration() |
|
66 self.host = host |
|
67 self.profile = profile |
4206
|
68 self.webrtc = webrtc.WebRTC(host.bridge, profile, **kwargs) |
4143
|
69 self.webrtc.callee = callee |
|
70 host.bridge.register_signal( |
|
71 "ice_candidates_new", self.on_ice_candidates_new, "plugin" |
|
72 ) |
|
73 host.bridge.register_signal("call_setup", self.on_call_setup, "plugin") |
|
74 host.bridge.register_signal("call_ended", self.on_call_ended, "plugin") |
|
75 |
|
76 @property |
|
77 def sid(self) -> str | None: |
|
78 return self.webrtc.sid |
|
79 |
|
80 @sid.setter |
|
81 def sid(self, new_sid: str | None) -> None: |
|
82 self.webrtc.sid = new_sid |
|
83 |
|
84 async def on_ice_candidates_new( |
|
85 self, sid: str, candidates_s: str, profile: str |
|
86 ) -> None: |
|
87 if sid != self.webrtc.sid or profile != self.profile: |
|
88 return |
|
89 self.webrtc.on_ice_candidates_new( |
|
90 data_format.deserialise(candidates_s), |
|
91 ) |
|
92 |
|
93 async def on_call_setup(self, sid: str, setup_data_s: str, profile: str) -> None: |
|
94 if sid != self.webrtc.sid or profile != self.profile: |
|
95 return |
|
96 setup_data = data_format.deserialise(setup_data_s) |
|
97 try: |
|
98 role = setup_data["role"] |
|
99 sdp = setup_data["sdp"] |
|
100 except KeyError: |
|
101 self.host.disp(f"Invalid setup data received: {setup_data}", error=True) |
|
102 return |
|
103 if role == "initiator": |
|
104 self.webrtc.on_accepted_call(sdp, profile) |
|
105 elif role == "responder": |
|
106 await self.webrtc.answer_call(sdp, profile) |
|
107 else: |
|
108 self.host.disp( |
|
109 f"Invalid role received during setup: {setup_data}", error=True |
|
110 ) |
|
111 # we want to be sure that call is ended if user presses `Ctrl + c` or anything |
|
112 # else stops the session. |
|
113 self.host.add_on_quit_callback( |
|
114 lambda: self.host.bridge.call_end(sid, "", profile) |
|
115 ) |
|
116 |
|
117 async def on_call_ended(self, sid: str, data_s: str, profile: str) -> None: |
|
118 if sid != self.webrtc.sid or profile != self.profile: |
|
119 return |
|
120 await self.webrtc.end_call() |
|
121 await self.host.a_quit() |
|
122 |
|
123 async def start(self): |
|
124 """Start a call. |
|
125 |
|
126 To be used only if we are initiator |
|
127 """ |
|
128 await self.webrtc.setup_call("initiator") |
|
129 self.webrtc.start_pipeline() |
|
130 |
|
131 |
|
132 class UI: |
|
133 def __init__(self, host, webrtc): |
|
134 self.host = host |
|
135 self.webrtc = webrtc |
|
136 |
|
137 def styled_shortcut_key(self, word: str, key: str | None = None) -> Text: |
|
138 """Return a word with the specified key or the first letter underlined.""" |
|
139 if key is None: |
|
140 key = word[0] |
|
141 index = word.find(key) |
|
142 before, keyword, after = word[:index], word[index], word[index + 1 :] |
|
143 return Text(before) + Text(keyword, style="shortcut") + Text(after) |
|
144 |
|
145 def get_micro_display(self): |
|
146 if self.webrtc.audio_muted: |
|
147 return Panel(Text("🔇 ") + self.styled_shortcut_key("Muted"), expand=False) |
|
148 else: |
|
149 return Panel( |
|
150 Text("🎤 ") + self.styled_shortcut_key("Unmuted", "m"), expand=False |
|
151 ) |
|
152 |
|
153 def get_video_display(self): |
|
154 if self.webrtc.video_muted: |
|
155 return Panel(Text("❌ ") + self.styled_shortcut_key("Video Off"), expand=False) |
|
156 else: |
|
157 return Panel(Text("🎥 ") + self.styled_shortcut_key("Video On"), expand=False) |
|
158 |
|
159 def get_phone_display(self): |
|
160 return Panel(Text("📞 ") + self.styled_shortcut_key("Hang up"), expand=False) |
|
161 |
|
162 @group() |
|
163 def generate_control_bar(self): |
|
164 """Return the full interface display.""" |
|
165 yield Columns( |
|
166 [ |
|
167 self.get_micro_display(), |
|
168 self.get_video_display(), |
|
169 self.get_phone_display(), |
|
170 ], |
|
171 expand=False, |
|
172 title="Calling [bold center]{}[/]".format(self.webrtc.callee), |
|
173 ) |
|
174 |
|
175 async def start(self): |
|
176 done = asyncio.Event() |
|
177 input = create_input() |
|
178 |
|
179 def keys_ready(live): |
|
180 for key_press in input.read_keys(): |
|
181 char = key_press.key.lower() |
|
182 if char == "m": |
|
183 # audio mute |
|
184 self.webrtc.audio_muted = not self.webrtc.audio_muted |
|
185 live.update(self.generate_control_bar(), refresh=True) |
|
186 elif char == "v": |
|
187 # video mute |
|
188 self.webrtc.video_muted = not self.webrtc.video_muted |
|
189 live.update(self.generate_control_bar(), refresh=True) |
|
190 elif char == "h" or key_press.key == Keys.ControlC: |
|
191 # Hang up |
|
192 done.set() |
|
193 elif char == "d": |
|
194 # generate dot file for debugging. Only available if |
|
195 # ``GST_DEBUG_DUMP_DOT_DIR`` is set. Filename is "pipeline.dot" with a |
|
196 # timestamp. |
|
197 if os.getenv("GST_DEBUG_DUMP_DOT_DIR"): |
|
198 self.webrtc.generate_dot_file() |
|
199 self.host.disp("Dot file generated.") |
|
200 |
|
201 with Live( |
|
202 self.generate_control_bar(), |
|
203 console=self.host.console, |
|
204 auto_refresh=False |
|
205 ) as live: |
|
206 with input.raw_mode(): |
|
207 with input.attach(partial(keys_ready, live)): |
|
208 await done.wait() |
|
209 |
|
210 await self.webrtc.end_call() |
|
211 await self.host.a_quit() |
|
212 |
|
213 |
|
214 class Common(base.CommandBase): |
|
215 |
4206
|
216 |
|
217 def __init__(self, *args, **kwargs): |
|
218 super().__init__( |
|
219 *args, |
|
220 use_output=C.OUTPUT_CUSTOM, |
|
221 extra_outputs={ |
|
222 "default": self.auto_output, |
|
223 "simple": self.simple_output, |
|
224 "gui": self.gui_output, |
|
225 }, |
|
226 **kwargs |
|
227 ) |
|
228 |
4143
|
229 def add_parser_options(self): |
|
230 self.parser.add_argument( |
|
231 "--no-ui", action="store_true", help=_("disable user interface") |
|
232 ) |
|
233 |
|
234 async def start(self): |
|
235 root_logger = logging.getLogger() |
|
236 # we don't want any formatting for messages from webrtc |
|
237 for handler in root_logger.handlers: |
|
238 handler.setFormatter(None) |
|
239 if self.verbosity == 0: |
|
240 root_logger.setLevel(logging.ERROR) |
|
241 if self.verbosity >= 1: |
|
242 root_logger.setLevel(logging.WARNING) |
|
243 if self.verbosity >= 2: |
|
244 root_logger.setLevel(logging.DEBUG) |
|
245 |
4206
|
246 async def make_webrtc_call(self, call_data: CallData, **kwargs) -> WebRTCCall: |
|
247 """Create the webrtc_call instance |
|
248 |
|
249 @param call_data: Call data of the command |
|
250 @param kwargs: extra args used to instanciate WebRTCCall |
|
251 |
|
252 """ |
|
253 webrtc_call = WebRTCCall(self.host, self.profile, call_data.callee, **kwargs) |
|
254 if call_data.sid is None: |
|
255 # we are making the call |
|
256 await webrtc_call.start() |
|
257 else: |
|
258 # we are receiving the call |
|
259 webrtc_call.sid = call_data.sid |
|
260 if call_data.action_id is not None: |
|
261 await self.host.bridge.action_launch( |
|
262 call_data.action_id, |
|
263 data_format.serialise({"cancelled": False}), |
|
264 self.profile |
|
265 ) |
|
266 return webrtc_call |
|
267 |
|
268 async def auto_output(self, call_data: CallData): |
|
269 """Make a guess on the best output to use on current platform""" |
|
270 # For now we just use simple output |
|
271 await self.simple_output(call_data) |
|
272 |
|
273 async def simple_output(self, call_data: CallData): |
|
274 """Run simple output, with GStreamer ``autovideosink``""" |
|
275 webrtc_call = await self.make_webrtc_call(call_data) |
4143
|
276 if not self.args.no_ui: |
|
277 ui = UI(self.host, webrtc_call.webrtc) |
|
278 await ui.start() |
|
279 |
4206
|
280 async def gui_output(self, call_data: CallData): |
|
281 """Run GUI output""" |
|
282 media_dir = Path(await self.host.bridge.config_get("", "media_dir")) |
|
283 icons_path = media_dir / "fonts/fontello/svg" |
|
284 try: |
|
285 from .call_gui import AVCallGUI |
|
286 await AVCallGUI.run(self, call_data, icons_path) |
|
287 except Exception as e: |
|
288 self.disp(f"Error starting GUI: {e}", error=True) |
|
289 self.host.quit(C.EXIT_ERROR) |
|
290 |
4143
|
291 |
|
292 class Make(Common): |
|
293 def __init__(self, host): |
|
294 super().__init__( |
|
295 host, |
|
296 "make", |
|
297 use_verbose=True, |
|
298 help=_("start a call"), |
|
299 ) |
|
300 |
|
301 def add_parser_options(self): |
|
302 super().add_parser_options() |
|
303 self.parser.add_argument( |
|
304 "entity", |
|
305 metavar="JID", |
|
306 help=_("JIDs of entity to call"), |
|
307 ) |
|
308 |
|
309 async def start(self): |
|
310 await super().start() |
4206
|
311 await super().output(CallData( |
|
312 callee=jid.JID(self.args.entity), |
|
313 )) |
4143
|
314 |
|
315 |
|
316 class Receive(Common): |
|
317 def __init__(self, host): |
|
318 super().__init__( |
|
319 host, |
|
320 "receive", |
|
321 use_verbose=True, |
|
322 help=_("wait for a call"), |
|
323 ) |
|
324 |
|
325 def add_parser_options(self): |
|
326 super().add_parser_options() |
|
327 auto_accept_group = self.parser.add_mutually_exclusive_group() |
|
328 auto_accept_group.add_argument( |
|
329 "-a", |
|
330 "--auto-accept", |
|
331 action="append", |
|
332 metavar="JID", |
|
333 default=[], |
|
334 help=_("automatically accept call from this jid (can be used multiple times)") |
|
335 ) |
|
336 auto_accept_group.add_argument( |
|
337 "--auto-accept-all", |
|
338 action="store_true", |
|
339 help=_("automatically accept call from anybody") |
|
340 ) |
|
341 |
|
342 async def on_action_new( |
|
343 self, action_data_s: str, action_id: str, security_limit: int, profile: str |
|
344 ) -> None: |
|
345 if profile != self.profile: |
|
346 return |
|
347 action_data = data_format.deserialise(action_data_s) |
|
348 if action_data.get("type") != C.META_TYPE_CALL: |
|
349 return |
|
350 peer_jid = jid.JID(action_data["from_jid"]).bare |
|
351 caller = peer_jid.bare |
|
352 if ( |
|
353 not self.args.auto_accept_all |
|
354 and caller not in self.args.auto_accept |
|
355 and not await self.host.confirm( |
|
356 _("📞 Incoming call from {caller}, do you accept?").format( |
|
357 caller=caller |
|
358 ) |
|
359 ) |
|
360 ): |
|
361 await self.host.bridge.action_launch( |
|
362 action_id, data_format.serialise({"cancelled": True}), profile |
|
363 ) |
|
364 return |
|
365 |
|
366 self.disp(_("✅ Incoming call from {caller} accepted.").format(caller=caller)) |
|
367 |
4206
|
368 await super().output(CallData( |
|
369 callee=peer_jid, |
|
370 sid=action_data["session_id"], |
|
371 action_id=action_id |
|
372 )) |
4143
|
373 |
|
374 async def start(self): |
|
375 await super().start() |
|
376 self.host.bridge.register_signal("action_new", self.on_action_new, "core") |
|
377 |
|
378 |
|
379 class Call(base.CommandBase): |
|
380 subcommands = (Make, Receive) |
|
381 |
|
382 def __init__(self, host): |
|
383 super().__init__(host, "call", use_profile=False, help=_("A/V calls and related")) |