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
//! General library interface.
use std::{cell::RefCell, rc::Rc, thread};
use futures::{FutureExt as _, future::LocalBoxFuture};
use tracerr::Traced;
use crate::{
media::{MediaManager, MediaManagerHandleImpl},
platform,
room::{Room, RoomHandleImpl},
rpc::{
ClientDisconnect, ReconnectError, RpcSession, WebSocketRpcClient,
WebSocketRpcSession,
},
};
/// General library interface.
///
/// Responsible for managing shared transports, local media and room
/// initialization.
#[derive(Clone, Debug)]
pub struct JasonImpl(Rc<RefCell<Inner>>);
/// Inner representation if a [`JasonImpl`].
#[derive(Debug)]
struct Inner {
/// [`JasonImpl`]s [`MediaManager`].
///
/// It's shared across [`Room`]s since [`MediaManager`] contains media
/// tracks that can be used by multiple [`Room`]s.
media_manager: Rc<MediaManager>,
/// [`Room`]s maintained by this [`JasonImpl`] instance.
rooms: Vec<Room>,
/// Connection with a media server.
///
/// [`JasonImpl`] will reuse this [`WebSocketRpcClient`] for each [`Room`]
/// if it's [`Some`].
///
/// New [`WebSocketRpcClient`] will be created for each [`Room`] if it's
/// [`None`].
rpc: Option<Rc<WebSocketRpcClient>>,
}
impl JasonImpl {
/// Instantiates a new [`JasonImpl`] interface to interact with this
/// library.
///
/// If a [`WebSocketRpcClient`] is provided, then [`JasonImpl`] will reuse
/// it for all the [`Room`]s created in this [`JasonImpl`].
///
/// If [`WebSocketRpcClient`] is not provided, then a new separate
/// [`WebSocketRpcClient`] will be created for each [`Room`].
#[must_use]
pub fn new(rpc: Option<Rc<WebSocketRpcClient>>) -> Self {
if !thread::panicking() {
platform::set_panic_hook();
}
if !log::logger().enabled(&log::Metadata::builder().build()) {
platform::init_logger();
}
Self(Rc::new(RefCell::new(Inner {
rooms: Vec::new(),
media_manager: Rc::new(MediaManager::default()),
rpc,
})))
}
/// Creates a new [`Room`] and returns its [`RoomHandleImpl`].
#[must_use]
pub fn init_room(&self) -> RoomHandleImpl {
let rpc = self.0.borrow().rpc.clone().unwrap_or_else(|| {
Rc::new(WebSocketRpcClient::new(Box::new(|| {
Rc::new(platform::WebSocketRpcTransport::new())
})))
});
self.inner_init_room(WebSocketRpcSession::new(rpc))
}
/// Returns a [`MediaManagerHandleImpl`].
#[must_use]
pub fn media_manager(&self) -> MediaManagerHandleImpl {
self.0.borrow().media_manager.new_handle()
}
/// Closes the provided [`RoomHandleImpl`].
pub fn close_room(&self, room_to_delete: &RoomHandleImpl) {
let index = self
.0
.borrow()
.rooms
.iter()
.enumerate()
.find(|(_, room)| room.inner_ptr_eq(room_to_delete))
.map(|(i, _)| i);
if let Some(i) = index {
let this = &mut self.0.borrow_mut();
let room = this.rooms.swap_remove(i);
room.set_close_reason(ClientDisconnect::RoomClosed.into());
drop(room);
}
}
/// Notifies this [`JasonImpl`] about a network change event (interface
/// switch or similar).
///
/// Drops and recreates active connections and schedules [ICE] restart after
/// reconnection.
///
/// # Errors
///
/// With a [`ReconnectError`] if new signalling could not be connected.
///
/// [ICE]: https://webrtcglossary.com/ice
#[must_use]
pub fn network_changed(
&self,
) -> LocalBoxFuture<'static, Result<(), Traced<ReconnectError>>> {
let inner = self.0.borrow();
let weak_rooms: Vec<_> =
inner.rooms.iter().map(Room::downgrade).collect();
async move {
for room in weak_rooms.into_iter().filter_map(|r| r.upgrade()) {
room.network_changed()
.await
.map_err(tracerr::map_from_and_wrap!())?;
}
Ok(())
}
.boxed_local()
}
/// Drops this [`JasonImpl`] API object, so all the related objects (rooms,
/// connections, streams, etc.) respectively. All objects related to this
/// [`JasonImpl`] API object will be detached (you will still hold them, but
/// unable to use).
pub fn dispose(self) {
self.0.borrow_mut().rooms.drain(..).for_each(|room| {
room.close(ClientDisconnect::RoomClosed.into());
});
}
/// Returns a [`RoomHandleImpl`] for an initialized [`Room`].
fn inner_init_room(&self, rpc: Rc<dyn RpcSession>) -> RoomHandleImpl {
let on_normal_close = rpc.on_normal_close();
let room = Room::new(rpc, Rc::clone(&self.0.borrow().media_manager));
let weak_room = room.downgrade();
let weak_inner = Rc::downgrade(&self.0);
platform::spawn(on_normal_close.map(move |reason| {
_ = (|| {
let this_room = weak_room.upgrade()?;
let inner = weak_inner.upgrade()?;
let mut inner = inner.borrow_mut();
let index =
inner.rooms.iter().position(|r| r.ptr_eq(&this_room));
if let Some(i) = index {
inner.rooms.remove(i).close(reason);
}
Some(())
})();
}));
let handle = room.new_handle();
self.0.borrow_mut().rooms.push(room);
handle
}
}
impl Default for JasonImpl {
fn default() -> Self {
Self::new(None)
}
}