opentalk-roomserver-module-livekit 0.0.32

OpenTalk RoomServer LiveKit signaling module
Documentation
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
// SPDX-License-Identifier: EUPL-1.2
// SPDX-FileCopyrightText: OpenTalk Team <mail@opentalk.eu>

use std::{
    collections::{BTreeMap, BTreeSet, HashMap},
    sync::Arc,
    time::Duration,
};

use anyhow::anyhow;
use futures::{StreamExt as _, stream};
use livekit_api::services::room::RoomClient;
use livekit_protocol::TrackSource;
use opentalk_roomserver_signaling::{
    module_context::{ChannelDroppedError, ModuleContext},
    signaling_module::{
        ModuleJoinData, ModuleSwitchData, SignalingModule, SignalingModuleDescription,
        SignalingModuleFeatureDescription, SignalingModuleInitData,
    },
};
use opentalk_roomserver_types::{
    breakout::BreakoutRoom, connection_id::ConnectionId, room_kind::RoomKind,
    signaling::module_error::SignalingModuleError,
};
use opentalk_roomserver_types_livekit::{
    LiveKitCommand, LiveKitError, LiveKitEvent, LiveKitInternal, LiveKitSettings, LiveKitState,
    MicrophoneRestrictionError, MicrophoneRestrictionState, ParticipantsMuted,
};
use opentalk_types_common::modules::{ModuleId, module_id};
use opentalk_types_signaling::ParticipantId;
use tokio::sync::oneshot;

use crate::{
    loopback::LiveKitLoopback,
    room::{LiveKitConnection, LiveKitSubroom},
};

pub mod loopback;
mod room;

const LIVEKIT_MODULE_ID: ModuleId = module_id!("livekit");

const PARALLEL_UPDATES: usize = 25;
const ACCESS_TOKEN_TTL: Duration = Duration::from_secs(32);
const LIVEKIT_MEDIA_SOURCES: [TrackSource; 4] = [
    TrackSource::Camera,
    TrackSource::Microphone,
    TrackSource::ScreenShare,
    TrackSource::ScreenShareAudio,
];

pub struct LiveKitModule {
    settings: Arc<LiveKitSettings>,

    /// The default screenshare permission. If the moderator didn't explicitly set a policy,
    /// this will be used to grant or deny screensharing privileges.
    ///
    /// `True` - all participants are allowed to screenshare
    /// `False` - only moderators are allowed to screenshare
    default_screenshare_permission: bool,

    /// LiveKit API client used to communicate with the LiveKit server
    livekit_client: Arc<RoomClient>,

    rooms: HashMap<RoomKind, LiveKitSubroom>,
}

impl SignalingModuleDescription for LiveKitModule {
    const MODULE_ID: ModuleId = LIVEKIT_MODULE_ID;
    const DESCRIPTION: &'static str = "Handles Livekit media streams coordination and integration";
    const FEATURES: &[SignalingModuleFeatureDescription] = &[];
}

impl SignalingModule for LiveKitModule {
    const NAMESPACE: ModuleId = LIVEKIT_MODULE_ID;

    type Incoming = LiveKitCommand;

    type Outgoing = LiveKitEvent;

    type Internal = LiveKitInternal;

    type Loopback = Result<LiveKitLoopback, LiveKitError>;

    type JoinInfo = LiveKitState;

    type PeerJoinInfo = ();

    type Error = LiveKitError;

    fn init(init_data: SignalingModuleInitData) -> Option<Self> {
        let livekit_settings = (init_data
            .room_parameters
            .module_settings
            .get::<LiveKitSettings>()
            .ok()?)?;

        let default_screenshare_permission = init_data
            .settings
            .defaults
            .as_ref()
            .is_some_and(|d| !d.screen_share_requires_permission);

        let livekit_client = RoomClient::with_api_key(
            &livekit_settings.service_url,
            &livekit_settings.api_key,
            &livekit_settings.api_secret,
        );

        Some(Self {
            settings: Arc::new(livekit_settings.clone()),
            default_screenshare_permission,

            livekit_client: Arc::new(livekit_client),

            rooms: HashMap::new(),
        })
    }

    fn on_participant_joined(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        participant_id: ParticipantId,
        connection_id: ConnectionId,
        _is_first_connection: bool,
    ) -> Result<ModuleJoinData<Self>, SignalingModuleError<Self::Error>> {
        let room = self.rooms.entry(ctx.room).or_insert_with(|| {
            LiveKitSubroom::new(
                ctx,
                self.default_screenshare_permission,
                Arc::clone(&self.settings),
                Arc::clone(&self.livekit_client),
                ctx.room_id,
                ctx.room,
            )
        });

        room.join_info(ctx, participant_id, connection_id)
    }

    fn on_participant_disconnected(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        participant_id: ParticipantId,
        connection_id: ConnectionId,
    ) -> Result<(), SignalingModuleError<Self::Error>> {
        let Some(room) = self.rooms.get_mut(&ctx.room) else {
            return Err(anyhow::anyhow!("Unknown room").into());
        };
        room.start_revoke_participant_access(ctx, participant_id, connection_id);
        Ok(())
    }

    fn on_websocket_message(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        sender: ParticipantId,
        connection_id: ConnectionId,
        payload: Self::Incoming,
    ) -> Result<(), SignalingModuleError<Self::Error>> {
        match payload {
            LiveKitCommand::CreateNewAccessToken => {
                self.issue_access_token(ctx, sender, connection_id)
            }
            LiveKitCommand::GrantScreenSharePermission { participants } => {
                self.set_screenshare_permissions(ctx, sender, participants, true)
            }
            LiveKitCommand::RevokeScreenSharePermission { participants } => {
                self.set_screenshare_permissions(ctx, sender, participants, false)
            }
            LiveKitCommand::RequestPopoutStreamAccessToken => {
                self.issue_popout_stream_access_token(ctx, sender, connection_id)
            }
        }
    }

    fn on_loopback_event(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        event: Self::Loopback,
    ) -> Result<(), SignalingModuleError<Self::Error>> {
        match event? {
            LiveKitLoopback::RoomCreated | LiveKitLoopback::RoomRemoved => Ok(()),
            LiveKitLoopback::NoteRevokedTokens {
                token_identities,
                participant_id,
                connection_id,
            } => self.note_revoked_tokens(ctx, token_identities, participant_id, connection_id),
            LiveKitLoopback::ScreenSharePermissionsUpdated {
                sender,
                participants,
                grant,
            } => Self::notify_screen_share_permission_update(ctx, sender, participants, grant),
        }
    }

    fn on_internal_command(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        command: Self::Internal,
    ) -> Result<(), SignalingModuleError<Self::Error>> {
        match command {
            LiveKitInternal::Mute {
                sender,
                participants,
                return_channel,
            } => self.mute(ctx, sender, participants, return_channel),
            LiveKitInternal::UpdateMicrophoneRestrictions {
                sender,
                new_state,
                return_channel,
            } => self.update_microphone_restrictions(ctx, sender, new_state, return_channel)?,
        }

        Ok(())
    }

    fn on_closing(&mut self, ctx: &mut ModuleContext<'_, Self>) -> Result<(), anyhow::Error> {
        let rooms = self.rooms.drain().collect();
        Self::cleanup_rooms(ctx, rooms);

        Ok(())
    }

    fn on_breakout_start(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        rooms: &[BreakoutRoom],
        _duration: Option<Duration>,
    ) -> Result<(), SignalingModuleError<Self::Error>> {
        for room in rooms {
            self.rooms
                .entry(RoomKind::Breakout(room.id))
                .or_insert_with(|| {
                    let room_kind = RoomKind::Breakout(room.id);
                    tracing::debug!("create room: {:?}", room_kind);
                    LiveKitSubroom::new(
                        ctx,
                        self.default_screenshare_permission,
                        self.settings.clone(),
                        Arc::clone(&self.livekit_client),
                        ctx.room_id,
                        room_kind,
                    )
                });
        }
        Ok(())
    }

    fn on_breakout_switch(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        participant_id: ParticipantId,
        old_room: RoomKind,
        new_room: RoomKind,
    ) -> Result<ModuleSwitchData<Self>, SignalingModuleError<Self::Error>> {
        let connections = ctx.participants.connections();
        let connections = connections.get(&participant_id).ok_or_else(|| {
            anyhow::anyhow!("Unknown participant can't switch breakout rooms {participant_id}")
        })?;

        let Some(room) = self.rooms.get_mut(&old_room) else {
            return Err(anyhow::anyhow!(
                "Source room not found while switching breakout rooms ({old_room:?})"
            )
            .into());
        };
        for connection_id in connections {
            room.start_revoke_participant_access(ctx, participant_id, *connection_id);
        }

        let Some(room) = self.rooms.get_mut(&new_room) else {
            return Err(anyhow::anyhow!(
                "Destination room not found while switching breakout rooms ({new_room:?})"
            )
            .into());
        };
        let mut switch_success = BTreeMap::new();
        for &connection_id in connections {
            let join_info = room
                .join_info(ctx, participant_id, connection_id)?
                .join_success;
            switch_success.insert(connection_id, join_info);
        }
        Ok(ModuleSwitchData {
            switch_success,
            ..Default::default()
        })
    }

    fn on_breakout_closed(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
    ) -> Result<(), SignalingModuleError<Self::Error>> {
        let breakout_rooms = self
            .rooms
            .extract_if(|kind, _| *kind != RoomKind::Main)
            .collect();
        Self::cleanup_rooms(ctx, breakout_rooms);

        Ok(())
    }
}

impl LiveKitModule {
    /// creates a new access token and sends it to the participant
    fn issue_access_token(
        &mut self,
        ctx: &mut ModuleContext<'_, LiveKitModule>,
        participant: ParticipantId,
        connection: ConnectionId,
    ) -> Result<(), SignalingModuleError<LiveKitError>> {
        let Some(room) = self.rooms.get_mut(&ctx.room) else {
            return Err(anyhow::anyhow!("Unknown room").into());
        };
        tracing::debug!("Issue access token to {participant:?}");
        let credentials = room.create_new_access_token(ctx, participant, connection)?;
        ctx.send_ws_message([participant], LiveKitEvent::Credentials(credentials))?;
        Ok(())
    }

    #[tracing::instrument(level = "debug", skip(self, ctx, return_channel))]
    pub fn mute(
        &self,
        ctx: &mut ModuleContext<'_, LiveKitModule>,
        sender: Option<ParticipantId>,
        participants: BTreeSet<ParticipantId>,
        return_channel: oneshot::Sender<ParticipantsMuted>,
    ) {
        let connections = ctx
            .participants
            .all_unfiltered
            .iter()
            .filter(|(participant_id, _)| participants.contains(participant_id))
            .flat_map(|(participant_id, state)| {
                state.connections().map(|connection_id| {
                    LiveKitConnection::new(*participant_id, connection_id, ctx.room_id, state.room)
                })
            })
            .collect();

        tracing::debug!("spawn background task to mute participants");
        let livekit_client = Arc::clone(&self.livekit_client);
        ctx.spawn_optional(async move {
            let muted = loopback::mute_participants(livekit_client, sender, connections).await;
            if return_channel.send(muted).is_err() {
                tracing::error!("Channel dropped when muting participants");
            }
            None
        });
    }

    fn note_revoked_tokens(
        &mut self,
        ctx: &mut ModuleContext<'_, LiveKitModule>,
        revoked_token_identities: BTreeSet<String>,
        participant_id: ParticipantId,
        connection_id: ConnectionId,
    ) -> Result<(), SignalingModuleError<LiveKitError>> {
        let Some(room) = self.rooms.get_mut(&ctx.room) else {
            return Err(anyhow::anyhow!("Unknown room").into());
        };
        room.note_revoked_tokens(revoked_token_identities, participant_id, connection_id)
    }

    fn set_screenshare_permissions(
        &mut self,
        ctx: &mut ModuleContext<'_, LiveKitModule>,
        sender: ParticipantId,
        participants: BTreeSet<ParticipantId>,
        grant: bool,
    ) -> Result<(), SignalingModuleError<LiveKitError>> {
        let Some(room) = self.rooms.get_mut(&ctx.room) else {
            return Err(anyhow::anyhow!("Unknown room").into());
        };
        room.set_screenshare_permissions(ctx, sender, participants, grant)
    }

    fn notify_screen_share_permission_update(
        ctx: &mut ModuleContext<'_, LiveKitModule>,
        sender: ParticipantId,
        participants: BTreeSet<ParticipantId>,
        grant: bool,
    ) -> Result<(), SignalingModuleError<LiveKitError>> {
        ctx.send_ws_message(
            [sender],
            LiveKitEvent::ScreenSharePermissionsUpdated {
                grant,
                participants,
            },
        )?;
        Ok(())
    }

    fn issue_popout_stream_access_token(
        &mut self,
        ctx: &mut ModuleContext<'_, LiveKitModule>,
        participant_id: ParticipantId,
        connection_id: ConnectionId,
    ) -> Result<(), SignalingModuleError<LiveKitError>> {
        let Some(room) = self.rooms.get_mut(&ctx.room) else {
            return Err(anyhow::anyhow!("Unknown room").into());
        };
        room.issue_popout_stream_access_token(ctx, participant_id, connection_id)
    }

    fn update_microphone_restrictions(
        &mut self,
        ctx: &mut ModuleContext<'_, Self>,
        sender: ParticipantId,
        new_state: MicrophoneRestrictionState,
        return_channel: oneshot::Sender<
            Result<MicrophoneRestrictionState, MicrophoneRestrictionError>,
        >,
    ) -> Result<(), SignalingModuleError<LiveKitError>> {
        let Some(room) = self.rooms.get_mut(&ctx.room) else {
            return Err(anyhow::anyhow!("Unknown room").into());
        };
        room.update_microphone_restrictions(ctx, sender, new_state, return_channel)
            .map_err(|ChannelDroppedError| {
                SignalingModuleError::Internal(anyhow!(
                    "Channel dropped when restricting microphone permissions"
                ))
            })
    }

    fn cleanup_rooms(ctx: &mut ModuleContext<'_, Self>, rooms: HashMap<RoomKind, LiveKitSubroom>) {
        ctx.spawn(async {
            stream::iter(rooms.into_iter().map(|(id, r)| async move {
                r.cleanup_room().await;
                tracing::debug!("LiveKitRoom removed: {id:?}");
            }))
            .buffer_unordered(PARALLEL_UPDATES)
            .collect::<Vec<()>>()
            .await;

            Ok(LiveKitLoopback::RoomRemoved)
        });
    }
}

fn build_livekit_participant_id(participant: ParticipantId, connection: ConnectionId) -> String {
    format!("{participant}:{connection}")
}