lolka.js 0.4.4 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +242 -12
- package/package.json +3 -5
- package/src/client/voice/AudioPlayer.js +358 -0
- package/src/client/voice/AudioResource.js +137 -0
- package/src/client/voice/VoiceConnection.js +296 -383
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libdatachannel.txt +373 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libjuice.txt +373 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-libsrtp.txt +35 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-nlohmann-json.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-addon-api.txt +9 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-node-api-headers.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-openssl.txt +177 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-opus.txt +44 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-plog.txt +21 -0
- package/src/client/voice/_lolka_voice/LICENSES/LICENSE-usrsctp.txt +27 -0
- package/src/client/voice/_lolka_voice/LICENSES/THIRD-PARTY.txt +16 -0
- package/src/client/voice/_lolka_voice/MANIFEST.json +47 -0
- package/src/client/voice/_lolka_voice/_loader.js +103 -0
- package/src/client/voice/_lolka_voice/_native/linux-aarch64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-aarch64-musl/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/linux-x86_64-musl/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/macos-arm64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/macos-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_native/windows-x86_64/core.node +0 -0
- package/src/client/voice/_lolka_voice/_version.js +4 -0
- package/src/client/voice/_lolka_voice/caps.js +56 -0
- package/src/client/voice/_lolka_voice/core.d.ts +200 -0
- package/src/client/voice/_lolka_voice/errors.js +22 -0
- package/src/client/voice/_lolka_voice/events.js +119 -0
- package/src/client/voice/_lolka_voice/index.d.ts +226 -0
- package/src/client/voice/_lolka_voice/index.js +35 -0
- package/src/client/voice/_lolka_voice/player.js +606 -0
- package/src/client/voice/_lolka_voice/receive.js +387 -0
- package/src/client/voice/_lolka_voice/sdp.js +137 -0
- package/src/client/voice/_lolka_voice/session.js +335 -0
- package/src/client/voice/_lolka_voice/signaling.js +120 -0
- package/src/client/voice/_lolka_voice/transport.js +260 -0
- package/src/client/voice/media/OpusPlayback.js +199 -0
- package/src/client/voice/media/Receiver.js +245 -0
- package/src/client/voice/media/deps.js +27 -0
- package/src/index.js +11 -0
- package/typings/index.d.mts +248 -4
- package/typings/index.d.ts +248 -4
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Сессия голоса с одним голосовым сервером: сигналинг, send-транспорт, produce, приём.
|
|
4
|
+
// Это то, что в lolka.js 0.5.0 лежало в VoiceConnection (_startSession, _createSendTransport, _startReceive,
|
|
5
|
+
// _consume, _onNotification). Соединение (VoiceConnection) остаётся у владельца: адаптер, op 4, rejoin, kick grace.
|
|
6
|
+
//
|
|
7
|
+
// `onClosed(reason)` вызывается, когда сессия закончилась не по инициативе владельца: `'kicked'` (сервер выкинул
|
|
8
|
+
// пира, например при переезде в другой канал) или `'disconnected'` (оборвался сигналинг).
|
|
9
|
+
//
|
|
10
|
+
// Порядок старта – как `_startSession` в lolka.js: сигналинг, router caps, send-транспорт, produce, отправитель,
|
|
11
|
+
// приём (если запрошен). Отправитель (`SendPlayer`) принадлежит владельцу и переживает сессии: сессия только
|
|
12
|
+
// подключает к нему свой send-трек и отключает при закрытии.
|
|
13
|
+
|
|
14
|
+
const { debuglog } = require('node:util');
|
|
15
|
+
const { randomBytes } = require('node:crypto');
|
|
16
|
+
const { opusFromCaps, produceRtpParameters } = require('./caps');
|
|
17
|
+
const { getRuntime } = require('./events');
|
|
18
|
+
const { SendPlayer } = require('./player');
|
|
19
|
+
const { RecvSession, DEFAULT_MAX_CLOSED_SECTIONS } = require('./receive');
|
|
20
|
+
const { Signaling } = require('./signaling');
|
|
21
|
+
const { SendTransport } = require('./transport');
|
|
22
|
+
|
|
23
|
+
const debug = debuglog('lolkajs-voice');
|
|
24
|
+
|
|
25
|
+
const randomU32 = () => randomBytes(4).readUInt32BE(0);
|
|
26
|
+
|
|
27
|
+
class VoiceSession {
|
|
28
|
+
/**
|
|
29
|
+
* @param {Object} options
|
|
30
|
+
* @param {string} options.endpoint адрес голосового сервера
|
|
31
|
+
* @param {string} options.token
|
|
32
|
+
* @param {string} [options.name] префикс имён нативных Peer
|
|
33
|
+
* @param {SendPlayer} [options.player] отправитель владельца; без него сессия создаёт и закрывает свой
|
|
34
|
+
* @param {boolean} [options.receive] включить приём сразу при старте
|
|
35
|
+
* @param {number} [options.recvRebuildThreshold] сколько закрытых секций терпит recv-транспорт до пересоздания
|
|
36
|
+
* @param {number} [options.requestTimeoutMs]
|
|
37
|
+
* @param {(reason: 'kicked' | 'disconnected') => void} [options.onClosed]
|
|
38
|
+
* @param {(remote: import('./receive').RemoteAudio) => void} [options.onTrack]
|
|
39
|
+
* @param {(remote: import('./receive').RemoteAudio) => void} [options.onTrackEnded]
|
|
40
|
+
* @param {(userId: string, speaking: boolean) => void} [options.onSpeaking]
|
|
41
|
+
* @param {(error: Error) => void} [options.onError] ошибки фоновых операций и колбэков владельца
|
|
42
|
+
* @param {{ core: Object, router: Object }} [options.runtime] ядро и маршрутизатор (подмена в тестах)
|
|
43
|
+
*/
|
|
44
|
+
constructor({
|
|
45
|
+
endpoint,
|
|
46
|
+
token,
|
|
47
|
+
name = 'lolka',
|
|
48
|
+
player = null,
|
|
49
|
+
receive = false,
|
|
50
|
+
recvRebuildThreshold = DEFAULT_MAX_CLOSED_SECTIONS,
|
|
51
|
+
requestTimeoutMs = 15000,
|
|
52
|
+
onClosed,
|
|
53
|
+
onTrack,
|
|
54
|
+
onTrackEnded,
|
|
55
|
+
onSpeaking,
|
|
56
|
+
onError,
|
|
57
|
+
runtime = getRuntime(),
|
|
58
|
+
}) {
|
|
59
|
+
this._runtime = runtime;
|
|
60
|
+
this._endpoint = endpoint;
|
|
61
|
+
this._token = token;
|
|
62
|
+
this._name = name;
|
|
63
|
+
this._recvRebuildThreshold = recvRebuildThreshold;
|
|
64
|
+
this._requestTimeoutMs = requestTimeoutMs;
|
|
65
|
+
this._onClosed = onClosed;
|
|
66
|
+
this._onTrack = onTrack;
|
|
67
|
+
this._onTrackEnded = onTrackEnded;
|
|
68
|
+
this._onSpeaking = onSpeaking;
|
|
69
|
+
this._onError = onError;
|
|
70
|
+
this.player = player ?? new SendPlayer({ runtime });
|
|
71
|
+
this._ownPlayer = player === null;
|
|
72
|
+
|
|
73
|
+
this.signaling = null;
|
|
74
|
+
this.sendTransport = null;
|
|
75
|
+
this.opus = null;
|
|
76
|
+
this._recv = null;
|
|
77
|
+
this._receiveWanted = Boolean(receive);
|
|
78
|
+
this._receiving = false;
|
|
79
|
+
this._producersSynced = false;
|
|
80
|
+
this._receiveChain = Promise.resolve();
|
|
81
|
+
this._started = false;
|
|
82
|
+
this._closeNotified = false;
|
|
83
|
+
this._pendingClose = null;
|
|
84
|
+
this._closed = false;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
get endpoint() {
|
|
88
|
+
return this._endpoint;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
get token() {
|
|
92
|
+
return this._token;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Включён ли приём чужого звука (создан recv-транспорт). */
|
|
96
|
+
get receiving() {
|
|
97
|
+
return this._receiving;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Живые консьюмеры по producerId. */
|
|
101
|
+
get consumers() {
|
|
102
|
+
return this._recv ? this._recv.consumers : new Map();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Состояние send-транспорта или `null`, пока его нет. */
|
|
106
|
+
get transportState() {
|
|
107
|
+
return this.sendTransport ? this.sendTransport.state : null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Включить приём чужого звука (идемпотентно). Приём, однажды включённый, остаётся до конца сессии:
|
|
112
|
+
* на сервере нельзя закрыть consumer. Ошибка включения уходит в `onError`; следующий запрос попробует снова.
|
|
113
|
+
*/
|
|
114
|
+
requestReceive() {
|
|
115
|
+
this._receiveWanted = true;
|
|
116
|
+
// приём без синхронизации со списком продюсеров (getProducers упал) повторяется: consume уже дедуплицирует
|
|
117
|
+
if (!this._started || this._closed || (this._receiving && this._producersSynced)) return;
|
|
118
|
+
this.enableReceive().catch(error => {
|
|
119
|
+
if (!this._closed) this._fail(error);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
_signalingUrl() {
|
|
124
|
+
let endpoint = this._endpoint || '';
|
|
125
|
+
if (!endpoint.includes('://')) endpoint = `ws://${endpoint}`;
|
|
126
|
+
return `${endpoint}${endpoint.includes('?') ? '&' : '?'}token=${this._token}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
_request(method, data) {
|
|
130
|
+
const signaling = this.signaling;
|
|
131
|
+
if (!signaling) return Promise.reject(new Error('voice signaling closed'));
|
|
132
|
+
return signaling.request(method, data);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
_check() {
|
|
136
|
+
if (this._closed) throw new Error('voice connection was closed while starting');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Колбэк владельца не должен ломать сессию: ошибка уходит в onError (или в debug).
|
|
140
|
+
_safe(callback, ...args) {
|
|
141
|
+
if (!callback) return;
|
|
142
|
+
try {
|
|
143
|
+
callback(...args);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
this._fail(error);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
_fail(error) {
|
|
150
|
+
if (this._onError) {
|
|
151
|
+
try {
|
|
152
|
+
this._onError(error);
|
|
153
|
+
} catch (inner) {
|
|
154
|
+
debug('onError failed: %s', inner?.message);
|
|
155
|
+
}
|
|
156
|
+
} else {
|
|
157
|
+
debug('voice session error: %s', error?.message);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async start() {
|
|
162
|
+
try {
|
|
163
|
+
await this._start();
|
|
164
|
+
} catch (error) {
|
|
165
|
+
// любой сбой (в том числе закрытие во время старта): добиваем всё, что успело подняться –
|
|
166
|
+
// сигналинг, транспорты, «призрачный» пир в SFU
|
|
167
|
+
const closedMeanwhile = this._closed;
|
|
168
|
+
this._closed = true;
|
|
169
|
+
await this._cleanup();
|
|
170
|
+
if (closedMeanwhile) throw new Error('voice connection was closed while starting', { cause: error });
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
this._started = true;
|
|
174
|
+
// requestReceive() мог прийти между проверкой в _start() и этой строкой
|
|
175
|
+
if (this._receiveWanted && !(this._receiving && this._producersSynced)) this.requestReceive();
|
|
176
|
+
const pending = this._pendingClose;
|
|
177
|
+
this._pendingClose = null;
|
|
178
|
+
if (pending !== null) this._notifyClosed(pending);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async _start() {
|
|
182
|
+
const signaling = new Signaling(
|
|
183
|
+
this._signalingUrl(),
|
|
184
|
+
(method, data) => this._onNotification(method, data),
|
|
185
|
+
() => this._notifyClosed('disconnected'),
|
|
186
|
+
{ requestTimeoutMs: this._requestTimeoutMs },
|
|
187
|
+
);
|
|
188
|
+
this.signaling = signaling;
|
|
189
|
+
await signaling.connect();
|
|
190
|
+
this._check();
|
|
191
|
+
|
|
192
|
+
const caps = await this._request('getRouterRtpCapabilities', {});
|
|
193
|
+
this._check();
|
|
194
|
+
const opus = opusFromCaps(caps);
|
|
195
|
+
this.opus = opus;
|
|
196
|
+
|
|
197
|
+
const ssrc = randomU32();
|
|
198
|
+
const cname = `lolka-${randomU32().toString(36)}`;
|
|
199
|
+
const params = await this._request('createWebRtcTransport', { direction: 'send', bwe: false });
|
|
200
|
+
this._check();
|
|
201
|
+
const transport = new SendTransport(this._runtime, { name: `${this._name}-send`, params, opus, ssrc, cname });
|
|
202
|
+
this.sendTransport = transport;
|
|
203
|
+
await transport.connect((method, data) => this._request(method, data));
|
|
204
|
+
this._check();
|
|
205
|
+
|
|
206
|
+
await this._request('produce', {
|
|
207
|
+
transportId: params.id,
|
|
208
|
+
kind: 'audio',
|
|
209
|
+
rtpParameters: produceRtpParameters({ opus, ssrc, cname }),
|
|
210
|
+
appData: { source: 'mic' },
|
|
211
|
+
});
|
|
212
|
+
this._check();
|
|
213
|
+
debug('producer created ssrc=%s', ssrc);
|
|
214
|
+
this.player.attach(transport.track, { pt: opus.pt, ssrc, mid: '0', midExt: opus.midId, levelExt: opus.levelId });
|
|
215
|
+
|
|
216
|
+
if (this._receiveWanted) await this.enableReceive();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Включить приём: recv-транспорт, getProducers, consume всех аудио-продюсеров. Идемпотентно. */
|
|
220
|
+
enableReceive() {
|
|
221
|
+
const task = this._receiveChain.then(() => this._enableReceive());
|
|
222
|
+
this._receiveChain = task.catch(() => {});
|
|
223
|
+
return task;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async _enableReceive() {
|
|
227
|
+
if (this._closed) return;
|
|
228
|
+
if (!this._receiving) {
|
|
229
|
+
const session = new RecvSession({
|
|
230
|
+
runtime: this._runtime,
|
|
231
|
+
request: (method, data) => this._request(method, data),
|
|
232
|
+
opus: this.opus,
|
|
233
|
+
name: this._name,
|
|
234
|
+
onTrack: remote => this._safe(this._onTrack, remote),
|
|
235
|
+
onTrackEnded: remote => this._safe(this._onTrackEnded, remote),
|
|
236
|
+
onError: error => this._fail(error),
|
|
237
|
+
maxClosedSections: this._recvRebuildThreshold,
|
|
238
|
+
});
|
|
239
|
+
this._recv = session;
|
|
240
|
+
try {
|
|
241
|
+
await session.start();
|
|
242
|
+
this._check();
|
|
243
|
+
this._receiving = true;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
this._recv = null;
|
|
246
|
+
session.close();
|
|
247
|
+
throw error;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
if (this._producersSynced) return;
|
|
251
|
+
const { producers } = await this._request('getProducers', {});
|
|
252
|
+
this._check();
|
|
253
|
+
for (const p of producers ?? []) {
|
|
254
|
+
await this._consume(p.producerId, p.userId, p.kind, p.peerId);
|
|
255
|
+
this._check();
|
|
256
|
+
}
|
|
257
|
+
this._producersSynced = true;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async _consume(producerId, userId, kind, peerId = null) {
|
|
261
|
+
// бот слушает только голос: видео-продюсеры (камера и т.п.) не потребляем
|
|
262
|
+
const recv = this._recv;
|
|
263
|
+
if (kind !== 'audio' || !producerId || !recv || this._closed) return;
|
|
264
|
+
try {
|
|
265
|
+
await recv.consume(producerId, userId, peerId);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (!recv.closed) this._fail(error);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// уведомления сервера
|
|
272
|
+
|
|
273
|
+
_notifyClosed(reason) {
|
|
274
|
+
if (this._closed || this._closeNotified) return;
|
|
275
|
+
if (!this._started) {
|
|
276
|
+
// закрытие во время start(): сообщим владельцу, когда сессия поднимется
|
|
277
|
+
if (this._pendingClose === null) this._pendingClose = reason;
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
this._closeNotified = true;
|
|
281
|
+
this._safe(this._onClosed, reason);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async _onNotification(method, data) {
|
|
285
|
+
if (this._closed) return;
|
|
286
|
+
debug('notification %s', method);
|
|
287
|
+
const recv = this._recv;
|
|
288
|
+
if (method === 'newProducer') {
|
|
289
|
+
if (this._receiving) await this._consume(data.producerId, data.userId, data.kind, data.peerId);
|
|
290
|
+
} else if (method === 'producerClosed') {
|
|
291
|
+
if (recv && data.producerId) recv.producerClosed(data.producerId);
|
|
292
|
+
} else if (method === 'peerClosed') {
|
|
293
|
+
recv?.peerClosed(data.peerId);
|
|
294
|
+
} else if (method === 'consumerClosed') {
|
|
295
|
+
if (recv && data.consumerId) recv.consumerClosed(data.consumerId);
|
|
296
|
+
} else if (method === 'peerTalking') {
|
|
297
|
+
this._safe(this._onSpeaking, String(data.userId), true);
|
|
298
|
+
} else if (method === 'peerStoppedTalking') {
|
|
299
|
+
this._safe(this._onSpeaking, String(data.userId), false);
|
|
300
|
+
} else if (method === 'kicked') {
|
|
301
|
+
this._notifyClosed('kicked');
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// закрытие
|
|
306
|
+
|
|
307
|
+
/** Закрыть сессию: снимает только свой send-трек с отправителя. Идемпотентно; ждёт закрытия нативных Peer. */
|
|
308
|
+
async close() {
|
|
309
|
+
if (this._closed) return;
|
|
310
|
+
this._closed = true;
|
|
311
|
+
await this._cleanup();
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Освобождает всё, что успело подняться; безопасно вызывать повторно.
|
|
315
|
+
async _cleanup() {
|
|
316
|
+
const closing = [];
|
|
317
|
+
const recv = this._recv;
|
|
318
|
+
this._recv = null;
|
|
319
|
+
if (recv) closing.push(recv.close());
|
|
320
|
+
const transport = this.sendTransport;
|
|
321
|
+
this.sendTransport = null;
|
|
322
|
+
if (transport) {
|
|
323
|
+
// отправитель переживает сессию: отключаем только свой трек
|
|
324
|
+
this.player.detach(transport.track);
|
|
325
|
+
closing.push(transport.close());
|
|
326
|
+
}
|
|
327
|
+
if (this._ownPlayer) this.player.close();
|
|
328
|
+
const signaling = this.signaling;
|
|
329
|
+
this.signaling = null;
|
|
330
|
+
signaling?.close();
|
|
331
|
+
await Promise.all(closing);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
module.exports = { VoiceSession };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { debuglog } = require('node:util');
|
|
4
|
+
|
|
5
|
+
const debug = debuglog('lolkajs-voice');
|
|
6
|
+
|
|
7
|
+
// JSON-RPC поверх WebSocket к голосовому серверу (mediasoup).
|
|
8
|
+
// request: { id, method, data }
|
|
9
|
+
// response: { id, response: true, data } | { id, response: true, error }
|
|
10
|
+
// notification: { notification: true, method, data }
|
|
11
|
+
//
|
|
12
|
+
// `ws` берётся из node_modules пакета-хозяина и загружается лениво.
|
|
13
|
+
class Signaling {
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} url
|
|
16
|
+
* @param {(method: string, data: Object) => any} onNotification может вернуть Promise: его ошибка не роняет процесс
|
|
17
|
+
* @param {() => void} [onClose] сокет оборвался не по `close()`
|
|
18
|
+
* @param {{ requestTimeoutMs?: number }} [options]
|
|
19
|
+
*/
|
|
20
|
+
constructor(url, onNotification, onClose, { requestTimeoutMs = 15000 } = {}) {
|
|
21
|
+
this.url = url;
|
|
22
|
+
this.onNotification = onNotification;
|
|
23
|
+
this.onClose = onClose;
|
|
24
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
25
|
+
this.closing = false;
|
|
26
|
+
this.ws = null;
|
|
27
|
+
this.pending = new Map();
|
|
28
|
+
this.nextId = 1;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
connect() {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
const WebSocket = require('ws');
|
|
34
|
+
this.ws = new WebSocket(this.url);
|
|
35
|
+
this.ws.on('open', resolve);
|
|
36
|
+
this.ws.on('error', reject);
|
|
37
|
+
this.ws.on('close', () => {
|
|
38
|
+
for (const [id, p] of this.pending) {
|
|
39
|
+
this.pending.delete(id);
|
|
40
|
+
p.reject(new Error('voice signaling closed'));
|
|
41
|
+
}
|
|
42
|
+
if (!this.closing) this.onClose?.();
|
|
43
|
+
});
|
|
44
|
+
this.ws.on('message', buffer => {
|
|
45
|
+
let obj;
|
|
46
|
+
try {
|
|
47
|
+
obj = JSON.parse(buffer.toString());
|
|
48
|
+
} catch {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (obj.response) {
|
|
52
|
+
const p = this.pending.get(obj.id);
|
|
53
|
+
if (p) {
|
|
54
|
+
this.pending.delete(obj.id);
|
|
55
|
+
if (obj.error) p.reject(new Error(String(obj.error)));
|
|
56
|
+
else p.resolve(obj.data ?? {});
|
|
57
|
+
}
|
|
58
|
+
} else if (obj.notification) {
|
|
59
|
+
// обработчик вправе слать свои запросы: ответы читает тот же цикл сообщений
|
|
60
|
+
let result;
|
|
61
|
+
try {
|
|
62
|
+
result = this.onNotification(obj.method, obj.data ?? {});
|
|
63
|
+
} catch (error) {
|
|
64
|
+
debug('notification %s failed: %s', obj.method, error?.message);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
Promise.resolve(result).catch(error => debug('notification %s failed: %s', obj.method, error?.message));
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
request(method, data = {}, timeout = this.requestTimeoutMs) {
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
if (!this.ws || this.closing) {
|
|
76
|
+
reject(new Error('voice signaling closed'));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const id = this.nextId++;
|
|
80
|
+
const timer = setTimeout(() => {
|
|
81
|
+
if (this.pending.has(id)) {
|
|
82
|
+
this.pending.delete(id);
|
|
83
|
+
reject(new Error(`voice signaling timeout: ${method}`));
|
|
84
|
+
}
|
|
85
|
+
}, timeout);
|
|
86
|
+
this.pending.set(id, {
|
|
87
|
+
resolve: value => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
resolve(value);
|
|
90
|
+
},
|
|
91
|
+
reject: error => {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
reject(error);
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
try {
|
|
97
|
+
this.ws.send(JSON.stringify({ id, method, data }));
|
|
98
|
+
} catch (error) {
|
|
99
|
+
this.pending.delete(id);
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
reject(error);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
close() {
|
|
107
|
+
this.closing = true;
|
|
108
|
+
try {
|
|
109
|
+
this.ws?.close();
|
|
110
|
+
} catch {
|
|
111
|
+
// ignore
|
|
112
|
+
}
|
|
113
|
+
for (const [id, p] of this.pending) {
|
|
114
|
+
this.pending.delete(id);
|
|
115
|
+
p.reject(new Error('voice signaling closed'));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = { Signaling };
|