-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathRoomServiceClient.ts
More file actions
440 lines (409 loc) · 12.8 KB
/
RoomServiceClient.ts
File metadata and controls
440 lines (409 loc) · 12.8 KB
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
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0
import type { DataPacket_Kind, RoomAgentDispatch, RoomEgress, TrackInfo } from '@livekit/protocol';
import {
CreateRoomRequest,
DeleteRoomRequest,
ForwardParticipantRequest,
ListParticipantsRequest,
ListParticipantsResponse,
ListRoomsRequest,
ListRoomsResponse,
MoveParticipantRequest,
MuteRoomTrackRequest,
MuteRoomTrackResponse,
ParticipantInfo,
ParticipantPermission,
Room,
RoomParticipantIdentity,
SendDataRequest,
UpdateParticipantRequest,
UpdateRoomMetadataRequest,
UpdateSubscriptionsRequest,
} from '@livekit/protocol';
import { ServiceBase } from './ServiceBase.js';
import type { Rpc } from './TwirpRPC.js';
import { TwirpRpc, livekitPackage } from './TwirpRPC.js';
import { getRandomBytes } from './crypto/uuid.js';
/**
* Options for when creating a room
*/
export interface CreateOptions {
/**
* name of the room. required
*/
name: string;
/**
* number of seconds to keep the room open before any participant joins
*/
emptyTimeout?: number;
/**
* number of seconds to keep the room open after the last participant leaves
* this option is helpful to give a grace period for participants to re-join
*/
departureTimeout?: number;
/**
* limit to the number of participants in a room at a time
*/
maxParticipants?: number;
/**
* initial room metadata
*/
metadata?: string;
/**
* add egress options
*/
egress?: RoomEgress;
/**
* minimum playout delay in milliseconds
*/
minPlayoutDelay?: number;
/**
* maximum playout delay in milliseconds
*/
maxPlayoutDelay?: number;
/**
* improves A/V sync when min_playout_delay set to a value larger than 200ms.
* It will disables transceiver re-use -- this option is not recommended
* for rooms with frequent subscription changes
*/
syncStreams?: boolean;
/**
* override the node room is allocated to, for debugging
* does not work with Cloud
*/
nodeId?: string;
/**
* Define agents that should be dispatched to this room
*/
agents?: RoomAgentDispatch[];
}
export type SendDataOptions = {
/** If set, only deliver to listed participant identities */
destinationIdentities?: string[];
destinationSids?: string[];
topic?: string;
};
export type UpdateParticipantOptions = {
/** only attributes you'd want to update should be set, set value to empty string to remove it */
attributes?: { [key: string]: string };
metadata?: string;
/** permissions are updated atomically - all desired permissions would need to be set */
permission?: Partial<ParticipantPermission>;
name?: string;
};
const svc = 'RoomService';
/**
* Client to access Room APIs
*/
export class RoomServiceClient extends ServiceBase {
private readonly rpc: Rpc;
/**
*
* @param host - hostname including protocol. i.e. 'https://<project>.livekit.cloud'
* @param apiKey - API Key, can be set in env var LIVEKIT_API_KEY
* @param secret - API Secret, can be set in env var LIVEKIT_API_SECRET
*/
constructor(host: string, apiKey?: string, secret?: string) {
super(apiKey, secret);
this.rpc = new TwirpRpc(host, livekitPackage);
}
/**
* Creates a new room. Explicit room creation is not required, since rooms will
* be automatically created when the first participant joins. This method can be
* used to customize room settings.
* @param options -
*/
async createRoom(options: CreateOptions): Promise<Room> {
const data = await this.rpc.request(
svc,
'CreateRoom',
new CreateRoomRequest(options).toJson(),
await this.authHeader({ roomCreate: true }),
);
return Room.fromJson(data, { ignoreUnknownFields: true });
}
/**
* List active rooms
* @param names - when undefined or empty, list all rooms.
* otherwise returns rooms with matching names
* @returns
*/
async listRooms(names?: string[]): Promise<Room[]> {
const data = await this.rpc.request(
svc,
'ListRooms',
new ListRoomsRequest({ names: names ?? [] }).toJson(),
await this.authHeader({ roomList: true }),
);
const res = ListRoomsResponse.fromJson(data, { ignoreUnknownFields: true });
return res.rooms ?? [];
}
async deleteRoom(room: string): Promise<void> {
await this.rpc.request(
svc,
'DeleteRoom',
new DeleteRoomRequest({ room }).toJson(),
await this.authHeader({ roomCreate: true }),
);
}
/**
* Update metadata of a room
* @param room - name of the room
* @param metadata - the new metadata for the room
*/
async updateRoomMetadata(room: string, metadata: string) {
const data = await this.rpc.request(
svc,
'UpdateRoomMetadata',
new UpdateRoomMetadataRequest({ room, metadata }).toJson(),
await this.authHeader({ roomAdmin: true, room }),
);
return Room.fromJson(data, { ignoreUnknownFields: true });
}
/**
* List participants in a room
* @param room - name of the room
*/
async listParticipants(room: string): Promise<ParticipantInfo[]> {
const data = await this.rpc.request(
svc,
'ListParticipants',
new ListParticipantsRequest({ room }).toJson(),
await this.authHeader({ roomAdmin: true, room }),
);
const res = ListParticipantsResponse.fromJson(data, { ignoreUnknownFields: true });
return res.participants ?? [];
}
/**
* Get information on a specific participant, including the tracks that participant
* has published
* @param room - name of the room
* @param identity - identity of the participant to return
*/
async getParticipant(room: string, identity: string): Promise<ParticipantInfo> {
const data = await this.rpc.request(
svc,
'GetParticipant',
new RoomParticipantIdentity({ room, identity }).toJson(),
await this.authHeader({ roomAdmin: true, room }),
);
return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });
}
/**
* Removes a participant in the room. This will disconnect the participant
* and will emit a Disconnected event for that participant.
* Even after being removed, the participant can still re-join the room.
* @param room -
* @param identity -
*/
async removeParticipant(room: string, identity: string): Promise<void> {
await this.rpc.request(
svc,
'RemoveParticipant',
new RoomParticipantIdentity({ room, identity }).toJson(),
await this.authHeader({ roomAdmin: true, room }),
);
}
/**
* Forwards a participant's track to another room. This will create a
* participant to join the destination room that has same information
* with the source participant except the kind to be `Forwarded`. All
* changes to the source participant will be reflected to the forwarded
* participant. When the source participant disconnects or the
* `RemoveParticipant` method is called in the destination room, the
* forwarding will be stopped.
* @param room -
* @param identity -
* @param destinationRoom - the room to forward the participant to
*/
async forwardParticipant(room: string, identity: string, destinationRoom: string): Promise<void> {
await this.rpc.request(
svc,
'ForwardParticipant',
new ForwardParticipantRequest({ room, identity, destinationRoom }).toJson(),
await this.authHeader({ roomAdmin: true, room, destinationRoom }),
);
}
/**
* Move a connected participant to a different room. Requires `roomAdmin` and `destinationRoom`.
* The participant will be removed from the current room and added to the destination room.
* From the other observers' perspective, the participant would've disconnected from the previous room and joined the new one.
* @param room -
* @param identity -
* @param destinationRoom - the room to move the participant to
*/
async moveParticipant(room: string, identity: string, destinationRoom: string): Promise<void> {
await this.rpc.request(
svc,
'MoveParticipant',
new MoveParticipantRequest({ room, identity, destinationRoom }).toJson(),
await this.authHeader({ roomAdmin: true, room, destinationRoom }),
);
}
/**
* Mutes a track that the participant has published.
* @param room -
* @param identity -
* @param trackSid - sid of the track to be muted
* @param muted - true to mute, false to unmute
*/
async mutePublishedTrack(
room: string,
identity: string,
trackSid: string,
muted: boolean,
): Promise<TrackInfo> {
const req = new MuteRoomTrackRequest({
room,
identity,
trackSid,
muted,
}).toJson();
const data = await this.rpc.request(
svc,
'MutePublishedTrack',
req,
await this.authHeader({ roomAdmin: true, room }),
);
const res = MuteRoomTrackResponse.fromJson(data, { ignoreUnknownFields: true });
return res.track!;
}
/**
* Updates a participant's state or permissions
* @param room - target room
* @param identity - participant identity
* @param options - participant fields to update
*/
async updateParticipant(
room: string,
identity: string,
options: UpdateParticipantOptions,
): Promise<ParticipantInfo>;
/**
* Updates a participant's state or permissions
* @param room - target room
* @param identity - participant identity
* @param options - participant fields to update
*/
async updateParticipant(
room: string,
identity: string,
metadata?: string,
permission?: Partial<ParticipantPermission>,
name?: string,
): Promise<ParticipantInfo>;
async updateParticipant(
room: string,
identity: string,
metadataOrOptions?: string | UpdateParticipantOptions,
maybePermission?: Partial<ParticipantPermission>,
maybeName?: string,
): Promise<ParticipantInfo> {
const hasOptions = typeof metadataOrOptions === 'object';
const metadata = hasOptions ? metadataOrOptions?.metadata : metadataOrOptions;
const permission = hasOptions ? metadataOrOptions.permission : maybePermission;
const name = hasOptions ? metadataOrOptions.name : maybeName;
const attributes: Record<string, string> | undefined = hasOptions
? metadataOrOptions.attributes
: {};
const req = new UpdateParticipantRequest({
room,
identity,
attributes,
metadata,
name,
});
if (permission) {
req.permission = new ParticipantPermission(permission);
}
const data = await this.rpc.request(
svc,
'UpdateParticipant',
req.toJson(),
await this.authHeader({ roomAdmin: true, room }),
);
return ParticipantInfo.fromJson(data, { ignoreUnknownFields: true });
}
/**
* Updates a participant's subscription to tracks
* @param room -
* @param identity -
* @param trackSids -
* @param subscribe - true to subscribe, false to unsubscribe
*/
async updateSubscriptions(
room: string,
identity: string,
trackSids: string[],
subscribe: boolean,
): Promise<void> {
const req = new UpdateSubscriptionsRequest({
room,
identity,
trackSids,
subscribe,
participantTracks: [],
}).toJson();
await this.rpc.request(
svc,
'UpdateSubscriptions',
req,
await this.authHeader({ roomAdmin: true, room }),
);
}
/**
* Sends data message to participants in the room
* @param room -
* @param data - opaque payload to send
* @param kind - delivery reliability
* @param options - optionally specify a topic and destinationSids (when destinationSids is empty, message is sent to everyone)
*/
async sendData(
room: string,
data: Uint8Array,
kind: DataPacket_Kind,
options: SendDataOptions,
): Promise<void>;
/**
* Sends data message to participants in the room
* @deprecated use sendData(room, data, kind, options) instead
* @param room -
* @param data - opaque payload to send
* @param kind - delivery reliability
* @param destinationSids - optional. when empty, message is sent to everyone
*/
async sendData(
room: string,
data: Uint8Array,
kind: DataPacket_Kind,
destinationSids?: string[],
): Promise<void>;
async sendData(
room: string,
data: Uint8Array,
kind: DataPacket_Kind,
options: SendDataOptions | string[] = {},
): Promise<void> {
const destinationSids = Array.isArray(options) ? options : options.destinationSids;
const topic = Array.isArray(options) ? undefined : options.topic;
const req = new SendDataRequest({
room,
data,
kind,
destinationSids: destinationSids ?? [],
topic,
});
if (!Array.isArray(options) && options.destinationIdentities) {
req.destinationIdentities = options.destinationIdentities;
}
req.nonce = await getRandomBytes(16);
await this.rpc.request(
svc,
'SendData',
req.toJson(),
await this.authHeader({ roomAdmin: true, room }),
);
}
}