-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathchat.ts
More file actions
197 lines (176 loc) · 6.48 KB
/
chat.ts
File metadata and controls
197 lines (176 loc) · 6.48 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
/* eslint-disable camelcase */
import type { Participant, Room, ChatMessage, SendTextOptions } from 'livekit-client';
import { compareVersions, RoomEvent } from 'livekit-client';
import { BehaviorSubject, Subject, scan, map, takeUntil, from, filter } from 'rxjs';
import {
DataTopic,
LegacyDataTopic,
sendMessage,
setupDataMessageHandler,
} from '../observables/dataChannel';
import { log } from '../logger';
/** @public */
export type { ChatMessage };
/** @public */
export interface ReceivedChatMessage extends ChatMessage {
from?: Participant;
}
export interface LegacyChatMessage extends ChatMessage {
ignoreLegacy?: boolean;
}
export interface LegacyReceivedChatMessage extends ReceivedChatMessage {
ignoreLegacy?: boolean;
}
/**
* @public
* @deprecated the new chat API doesn't rely on encoders and decoders anymore and uses a dedicated chat API instead
*/
export type MessageEncoder = (message: LegacyChatMessage) => Uint8Array;
/**
* @public
* @deprecated the new chat API doesn't rely on encoders and decoders anymore and uses a dedicated chat API instead
*/
export type MessageDecoder = (message: Uint8Array) => LegacyReceivedChatMessage;
/** @public */
export type ChatOptions = {
/** @deprecated the new chat API doesn't rely on encoders and decoders anymore and uses a dedicated chat API instead */
messageEncoder?: (message: LegacyChatMessage) => Uint8Array;
/** @deprecated the new chat API doesn't rely on encoders and decoders anymore and uses a dedicated chat API instead */
messageDecoder?: (message: Uint8Array) => LegacyReceivedChatMessage;
channelTopic?: string;
/** @deprecated the new chat API doesn't rely on update topics anymore and uses a dedicated chat API instead */
updateChannelTopic?: string;
};
const topicSubjectMap: WeakMap<Room, Map<string, Subject<ReceivedChatMessage>>> = new WeakMap();
function isIgnorableChatMessage(msg: ReceivedChatMessage | LegacyReceivedChatMessage) {
return (msg as LegacyChatMessage).ignoreLegacy == true;
}
const decodeLegacyMsg = (message: Uint8Array) =>
JSON.parse(new TextDecoder().decode(message)) as LegacyReceivedChatMessage | ReceivedChatMessage;
const encodeLegacyMsg = (message: LegacyReceivedChatMessage) =>
new TextEncoder().encode(JSON.stringify(message));
export function setupChat(room: Room, options?: ChatOptions) {
const serverSupportsDataStreams = () =>
room.serverInfo?.edition === 1 ||
(!!room.serverInfo?.version && compareVersions(room.serverInfo?.version, '1.8.2') > 0);
const onDestroyObservable = new Subject<void>();
const topic = options?.channelTopic ?? DataTopic.CHAT;
const legacyTopic = options?.channelTopic ?? LegacyDataTopic.CHAT;
let needsSetup = false;
if (!topicSubjectMap.has(room)) {
needsSetup = true;
}
const topicMap = topicSubjectMap.get(room) ?? new Map<string, Subject<ReceivedChatMessage>>();
const messageSubject = topicMap.get(topic) ?? new Subject<ReceivedChatMessage>();
topicMap.set(topic, messageSubject);
topicSubjectMap.set(room, topicMap);
const finalMessageDecoder = options?.messageDecoder ?? decodeLegacyMsg;
if (needsSetup) {
room.registerTextStreamHandler(topic, async (reader, participantInfo) => {
const { id, timestamp } = reader.info;
const streamObservable = from(reader).pipe(
scan((acc: string, chunk: string) => {
return acc + chunk;
}),
map((chunk: string) => {
return {
id,
timestamp,
message: chunk,
from: room.getParticipantByIdentity(participantInfo.identity),
// editTimestamp: type === 'update' ? timestamp : undefined,
} as ReceivedChatMessage;
}),
);
streamObservable.subscribe({
next: (value) => messageSubject.next(value),
});
});
/** legacy chat protocol handling */
const { messageObservable } = setupDataMessageHandler(room, [legacyTopic]);
messageObservable
.pipe(
map((msg) => {
const parsedMessage = finalMessageDecoder(msg.payload);
if (isIgnorableChatMessage(parsedMessage)) {
return undefined;
}
const newMessage: ReceivedChatMessage = { ...parsedMessage, from: msg.from };
return newMessage;
}),
filter((msg) => !!msg),
takeUntil(onDestroyObservable),
)
.subscribe(messageSubject);
}
/** Build up the message array over time. */
const messagesObservable = messageSubject.pipe(
scan<ReceivedChatMessage, ReceivedChatMessage[]>((acc, value) => {
if (
'id' in value &&
acc.find((msg) => msg.from?.identity === value.from?.identity && msg.id === value.id)
) {
const replaceIndex = acc.findIndex((msg) => msg.id === value.id);
if (replaceIndex > -1) {
const originalMsg = acc[replaceIndex];
acc[replaceIndex] = {
...value,
timestamp: originalMsg.timestamp,
editTimestamp: value.timestamp,
};
}
return [...acc];
}
return [...acc, value];
}, []),
takeUntil(onDestroyObservable),
);
const isSending$ = new BehaviorSubject<boolean>(false);
const finalMessageEncoder = options?.messageEncoder ?? encodeLegacyMsg;
const send = async (message: string, options?: SendTextOptions) => {
if (!options) {
options = {};
}
options.topic ??= topic;
isSending$.next(true);
try {
const info = await room.localParticipant.sendText(message, options);
const chatMsg: ReceivedChatMessage = {
id: info.id,
timestamp: Date.now(),
message,
from: room.localParticipant,
attachedFiles: options.attachments,
};
messageSubject.next(chatMsg);
const encodedLegacyMsg = finalMessageEncoder({
...chatMsg,
ignoreLegacy: serverSupportsDataStreams(),
});
try {
await sendMessage(room.localParticipant, encodedLegacyMsg, {
reliable: true,
topic: legacyTopic,
});
} catch (error) {
log.info('could not send message in legacy chat format', error);
}
return chatMsg;
} finally {
isSending$.next(false);
}
};
function destroy() {
onDestroyObservable.next();
onDestroyObservable.complete();
messageSubject.complete();
topicSubjectMap.delete(room);
room.unregisterTextStreamHandler(topic);
}
room.once(RoomEvent.Disconnected, destroy);
return {
messageObservable: messagesObservable,
isSendingObservable: isSending$,
send,
};
}