-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathparticipant.ts
547 lines (475 loc) · 16.5 KB
/
participant.ts
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0
import { FfiClient, FfiHandle } from './ffi_client.js';
import {
DisconnectReason,
type OwnedParticipant,
type ParticipantInfo,
type ParticipantKind,
} from './proto/participant_pb.js';
import type {
PublishDataCallback,
PublishDataResponse,
PublishSipDtmfCallback,
PublishSipDtmfResponse,
PublishTrackCallback,
PublishTrackResponse,
PublishTranscriptionCallback,
PublishTranscriptionResponse,
SendChatMessageCallback,
SendChatMessageResponse,
SetLocalAttributesCallback,
SetLocalAttributesResponse,
SetLocalMetadataCallback,
SetLocalMetadataResponse,
SetLocalNameCallback,
SetLocalNameResponse,
TrackPublishOptions,
UnpublishTrackCallback,
UnpublishTrackResponse,
} from './proto/room_pb.js';
import { ChatMessage as ChatMessageModel } from './proto/room_pb.js';
import {
EditChatMessageRequest,
TranscriptionSegment as ProtoTranscriptionSegment,
PublishDataRequest,
PublishSipDtmfRequest,
PublishTrackRequest,
PublishTranscriptionRequest,
SendChatMessageRequest,
SetLocalAttributesRequest,
SetLocalMetadataRequest,
SetLocalNameRequest,
UnpublishTrackRequest,
} from './proto/room_pb.js';
import type {
PerformRpcCallback,
PerformRpcResponse,
RegisterRpcMethodResponse,
RpcMethodInvocationResponseResponse,
UnregisterRpcMethodResponse,
} from './proto/rpc_pb.js';
import {
PerformRpcRequest,
RegisterRpcMethodRequest,
RpcMethodInvocationResponseRequest,
UnregisterRpcMethodRequest,
} from './proto/rpc_pb.js';
import { type PerformRpcParams, RpcError, type RpcInvocationData } from './rpc.js';
import type { LocalTrack } from './track.js';
import type { RemoteTrackPublication, TrackPublication } from './track_publication.js';
import { LocalTrackPublication } from './track_publication.js';
import type { Transcription } from './transcription.js';
import type { ChatMessage } from './types.js';
export abstract class Participant {
/** @internal */
info: ParticipantInfo;
/** @internal */
ffi_handle: FfiHandle;
trackPublications = new Map<string, TrackPublication>();
constructor(owned_info: OwnedParticipant) {
this.info = owned_info!.info!;
this.ffi_handle = new FfiHandle(owned_info.handle!.id!);
}
get sid(): string | undefined {
return this.info.sid;
}
get name(): string | undefined {
return this.info.name;
}
get identity(): string | undefined {
return this.info.identity;
}
get metadata(): string | undefined {
return this.info.metadata;
}
get attributes(): Record<string, string> | undefined {
return this.info.attributes;
}
get kind(): ParticipantKind | undefined {
return this.info.kind;
}
get disconnectReason(): DisconnectReason | undefined {
if (this.info.disconnectReason === DisconnectReason.UNKNOWN_REASON) {
return undefined;
}
return this.info.disconnectReason;
}
}
export type DataPublishOptions = {
/**
* whether to send this as reliable or lossy.
* For data that you need delivery guarantee (such as chat messages), use Reliable.
* For data that should arrive as quickly as possible, but you are ok with dropped
* packets, use Lossy.
*/
reliable?: boolean;
/**
* the identities of participants who will receive the message, will be sent to every one if empty
*/
destination_identities?: string[];
/** the topic under which the message gets published */
topic?: string;
};
export class LocalParticipant extends Participant {
private rpcHandlers: Map<string, (data: RpcInvocationData) => Promise<string>> = new Map();
trackPublications: Map<string, LocalTrackPublication> = new Map();
async publishData(data: Uint8Array, options: DataPublishOptions) {
const req = new PublishDataRequest({
localParticipantHandle: this.ffi_handle.handle,
dataPtr: FfiClient.instance.retrievePtr(data),
dataLen: BigInt(data.byteLength),
reliable: options.reliable,
topic: options.topic,
destinationIdentities: options.destination_identities,
});
const res = FfiClient.instance.request<PublishDataResponse>({
message: { case: 'publishData', value: req },
});
const cb = await FfiClient.instance.waitFor<PublishDataCallback>((ev) => {
return ev.message.case == 'publishData' && ev.message.value.asyncId == res.asyncId;
});
if (cb.error) {
throw new Error(cb.error);
}
}
async publishDtmf(code: number, digit: string) {
const req = new PublishSipDtmfRequest({
localParticipantHandle: this.ffi_handle.handle,
code,
digit,
});
const res = FfiClient.instance.request<PublishSipDtmfResponse>({
message: { case: 'publishSipDtmf', value: req },
});
const cb = await FfiClient.instance.waitFor<PublishSipDtmfCallback>((ev) => {
return ev.message.case == 'publishSipDtmf' && ev.message.value.asyncId == res.asyncId;
});
if (cb.error) {
throw new Error(cb.error);
}
}
async publishTranscription(transcription: Transcription) {
const req = new PublishTranscriptionRequest({
localParticipantHandle: this.ffi_handle.handle,
participantIdentity: transcription.participantIdentity,
segments: transcription.segments.map(
(s) =>
new ProtoTranscriptionSegment({
id: s.id,
text: s.text,
startTime: s.startTime,
endTime: s.endTime,
final: s.final,
language: s.language,
}),
),
trackId: transcription.trackSid,
});
const res = FfiClient.instance.request<PublishTranscriptionResponse>({
message: { case: 'publishTranscription', value: req },
});
const cb = await FfiClient.instance.waitFor<PublishTranscriptionCallback>((ev) => {
return ev.message.case == 'publishTranscription' && ev.message.value.asyncId == res.asyncId;
});
if (cb.error) {
throw new Error(cb.error);
}
}
async updateMetadata(metadata: string) {
const req = new SetLocalMetadataRequest({
localParticipantHandle: this.ffi_handle.handle,
metadata: metadata,
});
const res = FfiClient.instance.request<SetLocalMetadataResponse>({
message: { case: 'setLocalMetadata', value: req },
});
await FfiClient.instance.waitFor<SetLocalMetadataCallback>((ev) => {
return ev.message.case == 'setLocalMetadata' && ev.message.value.asyncId == res.asyncId;
});
}
/**
* Sends a chat message to participants in the room
*
* @param text - The text content of the chat message.
* @param destinationIdentities - An optional array of recipient identities to whom the message will be sent. If omitted, the message is broadcast to all participants.
* @param senderIdentity - An optional identity of the sender. If omitted, the default sender identity is used.
*
*/
async sendChatMessage(
text: string,
destinationIdentities?: Array<string>,
senderIdentity?: string,
): Promise<ChatMessage> {
const req = new SendChatMessageRequest({
localParticipantHandle: this.ffi_handle.handle,
message: text,
destinationIdentities,
senderIdentity,
});
const res = FfiClient.instance.request<SendChatMessageResponse>({
message: { case: 'sendChatMessage', value: req },
});
const cb = await FfiClient.instance.waitFor<SendChatMessageCallback>((ev) => {
return ev.message.case == 'chatMessage' && ev.message.value.asyncId == res.asyncId;
});
switch (cb.message.case) {
case 'chatMessage':
const { id, timestamp, editTimestamp, message } = cb.message.value!;
return {
id: id!,
timestamp: Number(timestamp),
editTimestamp: Number(editTimestamp),
message: message!,
};
case 'error':
default:
throw new Error(cb.message.value);
}
}
/**
* @experimental
*/
async editChatMessage(
editText: string,
originalMessage: ChatMessage,
destinationIdentities?: Array<string>,
senderIdentity?: string,
): Promise<ChatMessage> {
const req = new EditChatMessageRequest({
localParticipantHandle: this.ffi_handle.handle,
editText,
originalMessage: new ChatMessageModel({
...originalMessage,
timestamp: BigInt(originalMessage.timestamp),
editTimestamp: originalMessage.editTimestamp
? BigInt(originalMessage.editTimestamp)
: undefined,
}),
destinationIdentities,
senderIdentity,
});
const res = FfiClient.instance.request<SendChatMessageResponse>({
message: { case: 'editChatMessage', value: req },
});
const cb = await FfiClient.instance.waitFor<SendChatMessageCallback>((ev) => {
return ev.message.case == 'chatMessage' && ev.message.value.asyncId == res.asyncId;
});
switch (cb.message.case) {
case 'chatMessage':
const { id, timestamp, editTimestamp, message } = cb.message.value!;
return {
id: id!,
timestamp: Number(timestamp),
editTimestamp: Number(editTimestamp),
message: message!,
};
case 'error':
default:
throw new Error(cb.message.value);
}
}
async updateName(name: string) {
const req = new SetLocalNameRequest({
localParticipantHandle: this.ffi_handle.handle,
name: name,
});
const res = FfiClient.instance.request<SetLocalNameResponse>({
message: { case: 'setLocalName', value: req },
});
await FfiClient.instance.waitFor<SetLocalNameCallback>((ev) => {
return ev.message.case == 'setLocalName' && ev.message.value.asyncId == res.asyncId;
});
}
async setAttributes(attributes: Record<string, string>) {
const req = new SetLocalAttributesRequest({
localParticipantHandle: this.ffi_handle.handle,
attributes: Object.entries(attributes).map(([key, value]) => ({ key, value })),
});
const res = FfiClient.instance.request<SetLocalAttributesResponse>({
message: { case: 'setLocalAttributes', value: req },
});
await FfiClient.instance.waitFor<SetLocalAttributesCallback>((ev) => {
return ev.message.case == 'setLocalAttributes' && ev.message.value.asyncId == res.asyncId;
});
}
async publishTrack(
track: LocalTrack,
options: TrackPublishOptions,
): Promise<LocalTrackPublication> {
const req = new PublishTrackRequest({
localParticipantHandle: this.ffi_handle.handle,
trackHandle: track.ffi_handle.handle,
options: options,
});
const res = FfiClient.instance.request<PublishTrackResponse>({
message: { case: 'publishTrack', value: req },
});
const cb = await FfiClient.instance.waitFor<PublishTrackCallback>((ev) => {
return ev.message.case == 'publishTrack' && ev.message.value.asyncId == res.asyncId;
});
switch (cb.message.case) {
case 'publication':
const track_publication = new LocalTrackPublication(cb.message.value!);
track_publication.track = track;
this.trackPublications.set(track_publication.sid!, track_publication);
return track_publication;
case 'error':
default:
throw new Error(cb.message.value);
}
}
async unpublishTrack(trackSid: string, stopOnUnpublish?: boolean) {
const req = new UnpublishTrackRequest({
localParticipantHandle: this.ffi_handle.handle,
trackSid: trackSid,
stopOnUnpublish: stopOnUnpublish ?? true,
});
const res = FfiClient.instance.request<UnpublishTrackResponse>({
message: { case: 'unpublishTrack', value: req },
});
const cb = await FfiClient.instance.waitFor<UnpublishTrackCallback>((ev) => {
return ev.message.case == 'unpublishTrack' && ev.message.value.asyncId == res.asyncId;
});
if (cb.error) {
throw new Error(cb.error);
}
const pub = this.trackPublications.get(trackSid);
if (pub) {
pub.track = undefined;
}
this.trackPublications.delete(trackSid);
}
/**
* Initiate an RPC call to a remote participant.
* @param params - Parameters for initiating the RPC call, see {@link PerformRpcParams}
* @returns A promise that resolves with the response payload or rejects with an error.
* @throws Error on failure. Details in `message`.
*/
async performRpc({
destinationIdentity,
method,
payload,
responseTimeout,
}: PerformRpcParams): Promise<string> {
const req = new PerformRpcRequest({
localParticipantHandle: this.ffi_handle.handle,
destinationIdentity,
method,
payload,
responseTimeoutMs: responseTimeout,
});
const res = FfiClient.instance.request<PerformRpcResponse>({
message: { case: 'performRpc', value: req },
});
const cb = await FfiClient.instance.waitFor<PerformRpcCallback>((ev) => {
return ev.message.case === 'performRpc' && ev.message.value.asyncId === res.asyncId;
});
if (cb.error) {
throw RpcError.fromProto(cb.error);
}
return cb.payload!;
}
/**
* Establishes the participant as a receiver for calls of the specified RPC method.
* Will overwrite any existing callback for the same method.
*
* @param method - The name of the indicated RPC method
* @param handler - Will be invoked when an RPC request for this method is received
* @returns A promise that resolves when the method is successfully registered
*
* @example
* ```typescript
* room.localParticipant?.registerRpcMethod(
* 'greet',
* async (data: RpcInvocationData) => {
* console.log(`Received greeting from ${data.callerIdentity}: ${data.payload}`);
* return `Hello, ${data.callerIdentity}!`;
* }
* );
* ```
*
* See {@link RpcInvocationData} for more details on invocation params.
*
* The handler should return a Promise that resolves to a string.
* If unable to respond within `responseTimeout`, the request will result in an error on the caller's side.
*
* You may throw errors of type `RpcError` with a string `message` in the handler,
* and they will be received on the caller's side with the message intact.
* Other errors thrown in your handler will not be transmitted as-is, and will instead arrive to the caller as `1500` ("Application Error").
*/
registerRpcMethod(method: string, handler: (data: RpcInvocationData) => Promise<string>) {
this.rpcHandlers.set(method, handler);
const req = new RegisterRpcMethodRequest({
localParticipantHandle: this.ffi_handle.handle,
method,
});
FfiClient.instance.request<RegisterRpcMethodResponse>({
message: { case: 'registerRpcMethod', value: req },
});
}
/**
* Unregisters a previously registered RPC method.
*
* @param method - The name of the RPC method to unregister
*/
unregisterRpcMethod(method: string) {
this.rpcHandlers.delete(method);
const req = new UnregisterRpcMethodRequest({
localParticipantHandle: this.ffi_handle.handle,
method,
});
FfiClient.instance.request<UnregisterRpcMethodResponse>({
message: { case: 'unregisterRpcMethod', value: req },
});
}
/** @internal */
async handleRpcMethodInvocation(
invocationId: bigint,
method: string,
requestId: string,
callerIdentity: string,
payload: string,
responseTimeout: number,
) {
let responseError: RpcError | null = null;
let responsePayload: string | null = null;
const handler = this.rpcHandlers.get(method);
if (!handler) {
responseError = RpcError.builtIn('UNSUPPORTED_METHOD');
} else {
try {
responsePayload = await handler({ requestId, callerIdentity, payload, responseTimeout });
} catch (error) {
if (error instanceof RpcError) {
responseError = error;
} else {
console.warn(
`Uncaught error returned by RPC handler for ${method}. Returning APPLICATION_ERROR instead.`,
error,
);
responseError = RpcError.builtIn('APPLICATION_ERROR');
}
}
}
const req = new RpcMethodInvocationResponseRequest({
localParticipantHandle: this.ffi_handle.handle,
invocationId,
error: responseError ? responseError.toProto() : undefined,
payload: responsePayload ?? undefined,
});
const res = FfiClient.instance.request<RpcMethodInvocationResponseResponse>({
message: { case: 'rpcMethodInvocationResponse', value: req },
});
if (res.error) {
console.warn(`error sending rpc method invocation response: ${res.error}`);
}
}
}
export class RemoteParticipant extends Participant {
trackPublications: Map<string, RemoteTrackPublication> = new Map();
constructor(owned_info: OwnedParticipant) {
super(owned_info);
}
}