lolka.js 0.4.3 → 0.4.4
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 +38 -0
- package/package.json +1 -1
- package/src/client/voice/VoiceConnection.js +274 -58
- package/src/structures/Guild.js +5 -2
- package/typings/index.d.mts +8 -0
- package/typings/index.d.ts +8 -0
package/README.md
CHANGED
|
@@ -78,6 +78,16 @@ client.login('token');
|
|
|
78
78
|
Leave the channel with `connection.destroy()`, and stop playback (without leaving) with
|
|
79
79
|
`connection.stop()`. Playing files requires `ffmpeg` to be available in the bot's environment.
|
|
80
80
|
|
|
81
|
+
Calling `joinVoiceChannel` again for a guild that already has a live connection reuses it and moves the
|
|
82
|
+
bot via `connection.rejoin({ channelId, selfMute, selfDeaf })` (all fields optional), like `@discordjs/voice`.
|
|
83
|
+
Moving the bot between channels, or the channel being moved to another voice server, is transparent to
|
|
84
|
+
`play()`: the outgoing track is kept and playback continues. After such a move the `track` event fires
|
|
85
|
+
again for every participant (the old tracks end), and `ready` is still emitted only once. If the voice
|
|
86
|
+
server kicks the bot, or the connection to the voice server is lost, and no move follows within a few
|
|
87
|
+
seconds, the connection is destroyed (`state` stays `'ready'` during that grace period). A failed initial
|
|
88
|
+
start also destroys the connection, so the next `joinVoiceChannel` creates a fresh one. Connections are
|
|
89
|
+
reused per client and guild, so several clients in one process do not interfere.
|
|
90
|
+
|
|
81
91
|
`joinVoiceChannel(options)` accepts:
|
|
82
92
|
|
|
83
93
|
| option | type | description |
|
|
@@ -87,3 +97,31 @@ Leave the channel with `connection.destroy()`, and stop playback (without leavin
|
|
|
87
97
|
| `adapterCreator` | `Function` | `guild.voiceAdapterCreator` |
|
|
88
98
|
| `selfMute` | `boolean` | default `false` |
|
|
89
99
|
| `selfDeaf` | `boolean` | default `false` |
|
|
100
|
+
|
|
101
|
+
## Configuration
|
|
102
|
+
|
|
103
|
+
`lolka.js` talks to the public lolka by default. These environment variables override the endpoints
|
|
104
|
+
(read when a client is created, no trailing slash needed):
|
|
105
|
+
|
|
106
|
+
| variable | default | description |
|
|
107
|
+
| --- | --- | --- |
|
|
108
|
+
| `LOLKA_API_BASE` | `https://lolka.app/api/bot` | Bot API base (the library appends `/v10`). The gateway URL is taken from `GET /gateway/bot` |
|
|
109
|
+
| `LOLKA_CDN` | `https://cdn.lolka.app` | CDN for avatars, banners, icons, emojis, soundboard |
|
|
110
|
+
| `LOLKA_WEB` | `https://lolka.app` | Web client, used for channel/message links and bot authorization |
|
|
111
|
+
| `LOLKA_INVITE` | `https://lolka.gg` | Base of invite links |
|
|
112
|
+
|
|
113
|
+
### CDN
|
|
114
|
+
|
|
115
|
+
The lolka CDN does no resizing and serves only webp, so the `size`, `extension` and `forceStatic`
|
|
116
|
+
options of `avatarURL()`, `iconURL()`, `bannerURL()` and friends are ignored. `client.rest.cdn` is a
|
|
117
|
+
`LolkaCDN` (exported, together with the `LolkaCDNBase`, `LolkaWebBase`, `LolkaInviteBase` and
|
|
118
|
+
`LolkaApiBase` constants, which are snapshots of the values at load time).
|
|
119
|
+
|
|
120
|
+
### Links
|
|
121
|
+
|
|
122
|
+
- `invite.url` is `https://lolka.gg/{code}`; invites are also recognised as `https://lolka.app/i/{code}`
|
|
123
|
+
- `client.generateInvite()` returns `https://lolka.app/bot-authorize?client_id=...`
|
|
124
|
+
- `webhook.url` is `https://lolka.app/api/webhooks/{id}/{token}`; `WebhookClient` accepts such URLs
|
|
125
|
+
- `channel.url` is `https://lolka.app/servers/{guild}/channels/{channel}` (DMs: `/me/channels/{channel}`),
|
|
126
|
+
`message.url` appends `/{message}`
|
|
127
|
+
- the exported `channelLink()` and `messageLink()` build the same URLs
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "lolka.js",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.4",
|
|
5
5
|
"description": "A powerful library for interacting with the lolka bot API (discord.js-compatible fork)",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"build": "node ./scripts/esmDts.mjs",
|
|
@@ -44,15 +44,27 @@ const SAMPLE_RATE = 48000;
|
|
|
44
44
|
const CHANNELS = 2;
|
|
45
45
|
const FRAME_SAMPLES = 480; // 10 мс
|
|
46
46
|
const FRAME_BYTES = FRAME_SAMPLES * CHANNELS * 2;
|
|
47
|
+
const DEFAULT_KICK_GRACE_MS = 5000;
|
|
48
|
+
|
|
49
|
+
// Живые соединения: owner (голосовой менеджер клиента) -> guildId -> соединение. Повторный
|
|
50
|
+
// joinVoiceChannel переиспользует соединение через rejoin(); разные клиенты не пересекаются.
|
|
51
|
+
const defaultOwner = {};
|
|
52
|
+
const connections = new WeakMap();
|
|
53
|
+
|
|
54
|
+
function ownerOf(adapterCreator) {
|
|
55
|
+
return adapterCreator?.voiceManager ?? defaultOwner;
|
|
56
|
+
}
|
|
47
57
|
|
|
48
58
|
// JSON-RPC поверх WebSocket к голосовому серверу.
|
|
49
59
|
// request: { id, method, data }
|
|
50
60
|
// response: { id, response: true, data } | { id, response: true, error }
|
|
51
61
|
// notification: { notification: true, method, data }
|
|
52
62
|
class VoiceSignaling {
|
|
53
|
-
constructor(url, onNotification) {
|
|
63
|
+
constructor(url, onNotification, onClose) {
|
|
54
64
|
this.url = url;
|
|
55
65
|
this.onNotification = onNotification;
|
|
66
|
+
this.onClose = onClose;
|
|
67
|
+
this.closing = false;
|
|
56
68
|
this.ws = null;
|
|
57
69
|
this.pending = new Map();
|
|
58
70
|
this.nextId = 1;
|
|
@@ -63,6 +75,13 @@ class VoiceSignaling {
|
|
|
63
75
|
this.ws = new WebSocketImpl(this.url);
|
|
64
76
|
this.ws.on('open', resolve);
|
|
65
77
|
this.ws.on('error', reject);
|
|
78
|
+
this.ws.on('close', () => {
|
|
79
|
+
for (const [id, p] of this.pending) {
|
|
80
|
+
this.pending.delete(id);
|
|
81
|
+
p.reject(new Error('voice signaling closed'));
|
|
82
|
+
}
|
|
83
|
+
if (!this.closing) this.onClose?.();
|
|
84
|
+
});
|
|
66
85
|
this.ws.on('message', buffer => {
|
|
67
86
|
let obj;
|
|
68
87
|
try {
|
|
@@ -87,18 +106,34 @@ class VoiceSignaling {
|
|
|
87
106
|
request(method, data = {}, timeout = 15000) {
|
|
88
107
|
return new Promise((resolve, reject) => {
|
|
89
108
|
const id = this.nextId++;
|
|
90
|
-
|
|
91
|
-
this.ws.send(JSON.stringify({ id, method, data }));
|
|
92
|
-
setTimeout(() => {
|
|
109
|
+
const timer = setTimeout(() => {
|
|
93
110
|
if (this.pending.has(id)) {
|
|
94
111
|
this.pending.delete(id);
|
|
95
112
|
reject(new Error(`voice signaling timeout: ${method}`));
|
|
96
113
|
}
|
|
97
114
|
}, timeout);
|
|
115
|
+
this.pending.set(id, {
|
|
116
|
+
resolve: value => {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
resolve(value);
|
|
119
|
+
},
|
|
120
|
+
reject: error => {
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
reject(error);
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
this.ws.send(JSON.stringify({ id, method, data }));
|
|
127
|
+
} catch (error) {
|
|
128
|
+
this.pending.delete(id);
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
reject(error);
|
|
131
|
+
}
|
|
98
132
|
});
|
|
99
133
|
}
|
|
100
134
|
|
|
101
135
|
close() {
|
|
136
|
+
this.closing = true;
|
|
102
137
|
try {
|
|
103
138
|
this.ws?.close();
|
|
104
139
|
} catch {
|
|
@@ -119,6 +154,7 @@ class VoiceConnection extends EventEmitter {
|
|
|
119
154
|
}
|
|
120
155
|
ensureVoiceDeps();
|
|
121
156
|
|
|
157
|
+
this._owner = ownerOf(adapterCreator);
|
|
122
158
|
this.channelId = channelId;
|
|
123
159
|
this.guildId = guildId;
|
|
124
160
|
this.state = 'connecting';
|
|
@@ -140,8 +176,13 @@ class VoiceConnection extends EventEmitter {
|
|
|
140
176
|
this._playTimer = null;
|
|
141
177
|
this._playFF = null;
|
|
142
178
|
|
|
179
|
+
this._kickTimer = null;
|
|
143
180
|
this._started = false;
|
|
144
181
|
this._destroyed = false;
|
|
182
|
+
this._migration = 0; // счётчик переездов: результат устаревшего старта/переезда игнорируется
|
|
183
|
+
this._readyAnnounced = false;
|
|
184
|
+
this._roomChanged = false;
|
|
185
|
+
this._stateReceived = false;
|
|
145
186
|
|
|
146
187
|
let readyResolve;
|
|
147
188
|
let readyReject;
|
|
@@ -153,132 +194,270 @@ class VoiceConnection extends EventEmitter {
|
|
|
153
194
|
this._readyResolve = readyResolve;
|
|
154
195
|
this._readyReject = readyReject;
|
|
155
196
|
|
|
197
|
+
this._selfMute = Boolean(selfMute);
|
|
198
|
+
this._selfDeaf = Boolean(selfDeaf);
|
|
199
|
+
|
|
156
200
|
this._adapter = adapterCreator({
|
|
157
201
|
onVoiceStateUpdate: data => {
|
|
158
202
|
this.sessionId = data.session_id;
|
|
159
203
|
if (data.channel_id === null || data.channel_id === undefined) {
|
|
160
|
-
this.destroy();
|
|
204
|
+
if (this._stateReceived) this.destroy();
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
this._stateReceived = true;
|
|
208
|
+
const channelId = String(data.channel_id);
|
|
209
|
+
if (channelId !== String(this.channelId)) {
|
|
210
|
+
this.channelId = channelId;
|
|
211
|
+
if (this._started) this._roomChanged = true;
|
|
161
212
|
}
|
|
162
213
|
},
|
|
163
214
|
onVoiceServerUpdate: data => {
|
|
215
|
+
// Повторный Voice Server Update у уже поднятого соединения приходит, когда голосовой сервер
|
|
216
|
+
// канала сменили вручную (SetChannelVoiceServer -> migrateBotParticipant) или назначенный
|
|
217
|
+
// сервер нездоров и бот повторил op 4; также после перемещения бота в другой канал (тот же
|
|
218
|
+
// endpoint, но новая комната). Failover мёртвого сервера сюда не приходит — он только кикает.
|
|
219
|
+
// Смена одного лишь токена сессию не трогает: бэкенд перевыпускает его на каждый
|
|
220
|
+
// Voice State Update (например, при self_mute).
|
|
221
|
+
const serverChanged =
|
|
222
|
+
this._started && Boolean(data.endpoint) && (data.endpoint !== this.endpoint || this._roomChanged);
|
|
164
223
|
this.token = data.token;
|
|
165
|
-
this.endpoint = data.endpoint;
|
|
166
|
-
|
|
224
|
+
if (data.endpoint || !this._started) this.endpoint = data.endpoint;
|
|
225
|
+
if (serverChanged) {
|
|
226
|
+
this._roomChanged = false;
|
|
227
|
+
this._migrate();
|
|
228
|
+
} else {
|
|
229
|
+
this._maybeStart();
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
// Шард отключился безвозвратно: полный локальный teardown без op 4 и без adapter.destroy().
|
|
233
|
+
destroy: () => {
|
|
234
|
+
if (this._destroyed) return;
|
|
235
|
+
this._destroyed = true;
|
|
236
|
+
this.state = 'destroyed';
|
|
237
|
+
this._finalize();
|
|
238
|
+
this.emit('destroyed');
|
|
167
239
|
},
|
|
168
|
-
destroy: () => this._cleanup(),
|
|
169
240
|
});
|
|
170
241
|
|
|
242
|
+
this._sendState(channelId);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
_sendState(channelId) {
|
|
171
246
|
// Op 4 — Voice State Update (просим сервер подключить нас к каналу).
|
|
172
|
-
this._adapter.sendPayload({
|
|
247
|
+
return this._adapter.sendPayload({
|
|
173
248
|
op: 4,
|
|
174
|
-
d: { guild_id: guildId, channel_id: channelId, self_mute:
|
|
249
|
+
d: { guild_id: this.guildId, channel_id: channelId, self_mute: this._selfMute, self_deaf: this._selfDeaf },
|
|
175
250
|
});
|
|
176
251
|
}
|
|
177
252
|
|
|
253
|
+
/**
|
|
254
|
+
* Переместить соединение в другой канал (или обновить mute/deaf) без пересоздания.
|
|
255
|
+
* @param {Object} options
|
|
256
|
+
* @param {string} [options.channelId] ID нового голосового канала
|
|
257
|
+
* @param {boolean} [options.selfMute]
|
|
258
|
+
* @param {boolean} [options.selfDeaf]
|
|
259
|
+
* @returns {boolean} Удалось ли отправить op 4
|
|
260
|
+
*/
|
|
261
|
+
rejoin({ channelId = this.channelId, selfMute = this._selfMute, selfDeaf = this._selfDeaf } = {}) {
|
|
262
|
+
if (this._destroyed) throw new Error('voice connection is destroyed');
|
|
263
|
+
this._selfMute = Boolean(selfMute);
|
|
264
|
+
this._selfDeaf = Boolean(selfDeaf);
|
|
265
|
+
return this._sendState(channelId);
|
|
266
|
+
}
|
|
267
|
+
|
|
178
268
|
/** Дождаться готовности соединения (WebRTC поднят). */
|
|
179
269
|
awaitReady(timeout = 30000) {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
270
|
+
let timer;
|
|
271
|
+
const timeoutPromise = new Promise((_, rej) => {
|
|
272
|
+
timer = setTimeout(() => rej(new Error('voice connection timeout')), timeout);
|
|
273
|
+
});
|
|
274
|
+
return Promise.race([this._ready, timeoutPromise]).finally(() => clearTimeout(timer));
|
|
184
275
|
}
|
|
185
276
|
|
|
186
277
|
async _maybeStart() {
|
|
187
278
|
if (this._started || this._destroyed || !this.token || !this.endpoint) return;
|
|
188
279
|
this._started = true;
|
|
280
|
+
const migration = this._migration;
|
|
189
281
|
try {
|
|
190
|
-
await this._start();
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
this.
|
|
282
|
+
await this._start(migration);
|
|
283
|
+
// Пока поднимались, голосовой сервер сменился — исход этого старта уже не важен,
|
|
284
|
+
// готовность объявит _migrate.
|
|
285
|
+
if (migration !== this._migration) return;
|
|
286
|
+
this._markReady();
|
|
194
287
|
} catch (error) {
|
|
195
|
-
this.
|
|
196
|
-
this.emit('error', error);
|
|
288
|
+
if (migration !== this._migration || this._destroyed) return;
|
|
197
289
|
this._readyReject(error);
|
|
290
|
+
if (this.listenerCount('error') > 0) this.emit('error', error);
|
|
291
|
+
this.destroy();
|
|
198
292
|
}
|
|
199
293
|
}
|
|
200
294
|
|
|
295
|
+
/** Соединение поднято: `ready` и awaitReady() срабатывают один раз, даже после переездов. */
|
|
296
|
+
_markReady() {
|
|
297
|
+
this.state = 'ready';
|
|
298
|
+
if (this._readyAnnounced) return;
|
|
299
|
+
this._readyAnnounced = true;
|
|
300
|
+
this.emit('ready');
|
|
301
|
+
this._readyResolve();
|
|
302
|
+
}
|
|
303
|
+
|
|
201
304
|
_signalingUrl() {
|
|
202
305
|
let ep = this.endpoint || '';
|
|
203
306
|
if (!ep.includes('://')) ep = `ws://${ep}`;
|
|
204
307
|
return `${ep}${ep.includes('?') ? '&' : '?'}token=${this.token}`;
|
|
205
308
|
}
|
|
206
309
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
this.
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
310
|
+
/**
|
|
311
|
+
* Голосовой сервер сменился — пересобираем сессию на новом endpoint. Исходящий трек
|
|
312
|
+
* сохраняется, поэтому текущее воспроизведение не прерывается.
|
|
313
|
+
*/
|
|
314
|
+
async _migrate() {
|
|
315
|
+
if (this._destroyed) return;
|
|
316
|
+
const migration = ++this._migration;
|
|
317
|
+
this.state = 'connecting';
|
|
318
|
+
this._closeSession();
|
|
319
|
+
try {
|
|
320
|
+
await this._start(migration);
|
|
321
|
+
if (migration !== this._migration || this._destroyed) return;
|
|
322
|
+
this._markReady();
|
|
323
|
+
} catch (error) {
|
|
324
|
+
if (migration !== this._migration || this._destroyed) return;
|
|
325
|
+
this._readyReject(error);
|
|
326
|
+
if (this.listenerCount('error') > 0) this.emit('error', error);
|
|
327
|
+
this.destroy();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
217
330
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
331
|
+
async _start(migration) {
|
|
332
|
+
const check = () => {
|
|
333
|
+
if (migration !== this._migration || this._destroyed) throw new Error('voice session superseded');
|
|
334
|
+
};
|
|
335
|
+
const signaling = new VoiceSignaling(
|
|
336
|
+
this._signalingUrl(),
|
|
337
|
+
(method, data) => {
|
|
338
|
+
// Уведомления от уже заменённого сигналинга (прежний голосовой сервер) игнорируем —
|
|
339
|
+
// иначе его запоздалый `kicked` уничтожил бы переехавшее соединение.
|
|
340
|
+
if (this._signaling !== signaling) return undefined;
|
|
341
|
+
return this._onNotification(method, data);
|
|
342
|
+
},
|
|
343
|
+
() => {
|
|
344
|
+
if (this._signaling === signaling) this._scheduleKickDestroy();
|
|
345
|
+
},
|
|
346
|
+
);
|
|
347
|
+
this._signaling = signaling;
|
|
348
|
+
await signaling.connect();
|
|
349
|
+
check();
|
|
350
|
+
|
|
351
|
+
const routerRtpCapabilities = await signaling.request('getRouterRtpCapabilities', {});
|
|
352
|
+
check();
|
|
353
|
+
const device = new rtcClient.Device({ handlerName: 'Chrome111' });
|
|
354
|
+
await device.load({ routerRtpCapabilities });
|
|
355
|
+
check();
|
|
356
|
+
this._device = device;
|
|
357
|
+
|
|
358
|
+
await this._createSendTransport(check);
|
|
359
|
+
await this._createRecvTransport(check);
|
|
360
|
+
check();
|
|
361
|
+
|
|
362
|
+
// Постоянный исходящий трек; play() подаёт в него PCM. Создаётся один раз и переживает
|
|
363
|
+
// смену голосового сервера (stopTracks: false — закрытие продюсера трек не останавливает).
|
|
364
|
+
if (!this._audioSource) {
|
|
365
|
+
this._audioSource = new wrtc.nonstandard.RTCAudioSource();
|
|
366
|
+
this._audioTrack = this._audioSource.createTrack();
|
|
367
|
+
}
|
|
368
|
+
this._producer = await this._sendTransport.produce({ track: this._audioTrack, stopTracks: false });
|
|
222
369
|
|
|
223
|
-
|
|
370
|
+
check();
|
|
371
|
+
const { producers } = await signaling.request('getProducers', {});
|
|
372
|
+
check();
|
|
224
373
|
for (const p of producers) await this._consume(p.producerId, p.userId, p.kind);
|
|
225
374
|
}
|
|
226
375
|
|
|
227
|
-
async _createSendTransport() {
|
|
376
|
+
async _createSendTransport(check) {
|
|
228
377
|
const params = await this._signaling.request('createWebRtcTransport', { direction: 'send' });
|
|
378
|
+
check();
|
|
229
379
|
this._sendTransport = this._device.createSendTransport(params);
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
380
|
+
const signaling = this._signaling;
|
|
381
|
+
const transport = this._sendTransport;
|
|
382
|
+
transport.on('connect', ({ dtlsParameters }, callback, errback) =>
|
|
383
|
+
signaling
|
|
384
|
+
.request('connectTransport', { transportId: transport.id, dtlsParameters })
|
|
233
385
|
.then(() => callback())
|
|
234
386
|
.catch(errback),
|
|
235
387
|
);
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
.request('produce', { transportId:
|
|
388
|
+
transport.on('produce', ({ kind, rtpParameters, appData }, callback, errback) =>
|
|
389
|
+
signaling
|
|
390
|
+
.request('produce', { transportId: transport.id, kind, rtpParameters, appData })
|
|
239
391
|
.then(({ id }) => callback({ id }))
|
|
240
392
|
.catch(errback),
|
|
241
393
|
);
|
|
242
394
|
}
|
|
243
395
|
|
|
244
|
-
async _createRecvTransport() {
|
|
396
|
+
async _createRecvTransport(check) {
|
|
245
397
|
const params = await this._signaling.request('createWebRtcTransport', { direction: 'recv' });
|
|
398
|
+
check();
|
|
246
399
|
this._recvTransport = this._device.createRecvTransport(params);
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
400
|
+
const signaling = this._signaling;
|
|
401
|
+
const transport = this._recvTransport;
|
|
402
|
+
transport.on('connect', ({ dtlsParameters }, callback, errback) =>
|
|
403
|
+
signaling
|
|
404
|
+
.request('connectTransport', { transportId: transport.id, dtlsParameters })
|
|
250
405
|
.then(() => callback())
|
|
251
406
|
.catch(errback),
|
|
252
407
|
);
|
|
253
408
|
}
|
|
254
409
|
|
|
255
410
|
async _consume(producerId, userId, kind) {
|
|
256
|
-
|
|
411
|
+
const recv = this._recvTransport;
|
|
412
|
+
const signaling = this._signaling;
|
|
413
|
+
if (kind !== 'audio' || !recv || !signaling || this._consumers.has(producerId)) return;
|
|
257
414
|
try {
|
|
258
|
-
const params = await
|
|
259
|
-
transportId:
|
|
415
|
+
const params = await signaling.request('consume', {
|
|
416
|
+
transportId: recv.id,
|
|
260
417
|
producerId,
|
|
261
418
|
rtpCapabilities: this._device.rtpCapabilities,
|
|
262
419
|
});
|
|
263
|
-
|
|
264
|
-
|
|
420
|
+
if (this._recvTransport !== recv) return;
|
|
421
|
+
const consumer = await recv.consume(params);
|
|
422
|
+
if (this._recvTransport !== recv) return;
|
|
423
|
+
await signaling.request('resumeConsumer', { consumerId: consumer.id });
|
|
424
|
+
if (this._recvTransport !== recv) return;
|
|
265
425
|
this._consumers.set(producerId, consumer);
|
|
266
426
|
this.emit('track', consumer.track, userId, producerId);
|
|
267
427
|
} catch (error) {
|
|
268
|
-
this.emit('error', error);
|
|
428
|
+
if (this._recvTransport === recv && this.listenerCount('error') > 0) this.emit('error', error);
|
|
269
429
|
}
|
|
270
430
|
}
|
|
271
431
|
|
|
272
432
|
async _onNotification(method, data) {
|
|
273
433
|
if (method === 'newProducer') {
|
|
274
434
|
await this._consume(data.producerId, data.userId, data.kind);
|
|
275
|
-
} else if (method === '
|
|
435
|
+
} else if (method === 'producerClosed') {
|
|
276
436
|
if (data.producerId) this._consumers.delete(data.producerId);
|
|
437
|
+
} else if (method === 'consumerClosed') {
|
|
438
|
+
for (const [producerId, consumer] of this._consumers) {
|
|
439
|
+
if (consumer.id === data.consumerId) this._consumers.delete(producerId);
|
|
440
|
+
}
|
|
277
441
|
} else if (method === 'kicked') {
|
|
278
|
-
this.
|
|
442
|
+
this._scheduleKickDestroy();
|
|
279
443
|
}
|
|
280
444
|
}
|
|
281
445
|
|
|
446
|
+
/**
|
|
447
|
+
* Сервер кикнул нас (или сигналинг оборвался). При перемещении бота в другой канал за киком сразу
|
|
448
|
+
* следует переезд, поэтому уничтожаем соединение только если за grace-период переезда не было.
|
|
449
|
+
*/
|
|
450
|
+
_scheduleKickDestroy() {
|
|
451
|
+
if (this._destroyed) return;
|
|
452
|
+
const migration = this._migration;
|
|
453
|
+
clearTimeout(this._kickTimer);
|
|
454
|
+
this._kickTimer = setTimeout(() => {
|
|
455
|
+
this._kickTimer = null;
|
|
456
|
+
if (!this._destroyed && migration === this._migration) this.destroy();
|
|
457
|
+
}, VoiceConnection.kickGraceMs);
|
|
458
|
+
this._kickTimer.unref?.();
|
|
459
|
+
}
|
|
460
|
+
|
|
282
461
|
/**
|
|
283
462
|
* Проиграть аудио в канал.
|
|
284
463
|
* @param {string|import('node:stream').Readable} input Путь к файлу или Readable-поток (любой формат — через ffmpeg).
|
|
@@ -369,7 +548,6 @@ class VoiceConnection extends EventEmitter {
|
|
|
369
548
|
if (this._destroyed) return;
|
|
370
549
|
this._destroyed = true;
|
|
371
550
|
this.state = 'destroyed';
|
|
372
|
-
this.stop();
|
|
373
551
|
try {
|
|
374
552
|
this._adapter?.sendPayload({
|
|
375
553
|
op: 4,
|
|
@@ -378,7 +556,7 @@ class VoiceConnection extends EventEmitter {
|
|
|
378
556
|
} catch {
|
|
379
557
|
// ignore
|
|
380
558
|
}
|
|
381
|
-
this.
|
|
559
|
+
this._finalize();
|
|
382
560
|
try {
|
|
383
561
|
this._adapter?.destroy();
|
|
384
562
|
} catch {
|
|
@@ -387,7 +565,25 @@ class VoiceConnection extends EventEmitter {
|
|
|
387
565
|
this.emit('destroyed');
|
|
388
566
|
}
|
|
389
567
|
|
|
390
|
-
|
|
568
|
+
_finalize() {
|
|
569
|
+
clearTimeout(this._kickTimer);
|
|
570
|
+
this._kickTimer = null;
|
|
571
|
+
this.stop();
|
|
572
|
+
this._closeSession();
|
|
573
|
+
try {
|
|
574
|
+
this._audioTrack?.stop();
|
|
575
|
+
} catch {
|
|
576
|
+
// ignore
|
|
577
|
+
}
|
|
578
|
+
this._audioTrack = null;
|
|
579
|
+
this._audioSource = null;
|
|
580
|
+
if (!this._readyAnnounced) this._readyReject(new Error('voice connection destroyed'));
|
|
581
|
+
const byGuild = connections.get(this._owner);
|
|
582
|
+
if (byGuild?.get(this.guildId) === this) byGuild.delete(this.guildId);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** Закрыть сессию с текущим голосовым сервером, не трогая исходящий трек. */
|
|
586
|
+
_closeSession() {
|
|
391
587
|
this._consumers.clear();
|
|
392
588
|
for (const transport of [this._sendTransport, this._recvTransport]) {
|
|
393
589
|
try {
|
|
@@ -398,6 +594,7 @@ class VoiceConnection extends EventEmitter {
|
|
|
398
594
|
}
|
|
399
595
|
this._sendTransport = null;
|
|
400
596
|
this._recvTransport = null;
|
|
597
|
+
this._producer = null;
|
|
401
598
|
this._signaling?.close();
|
|
402
599
|
this._signaling = null;
|
|
403
600
|
}
|
|
@@ -414,7 +611,26 @@ class VoiceConnection extends EventEmitter {
|
|
|
414
611
|
* @returns {VoiceConnection}
|
|
415
612
|
*/
|
|
416
613
|
function joinVoiceChannel(options) {
|
|
417
|
-
|
|
614
|
+
const owner = ownerOf(options.adapterCreator);
|
|
615
|
+
let byGuild = connections.get(owner);
|
|
616
|
+
const existing = byGuild?.get(options.guildId);
|
|
617
|
+
if (existing && !existing._destroyed) {
|
|
618
|
+
existing.rejoin({ channelId: options.channelId, selfMute: options.selfMute, selfDeaf: options.selfDeaf });
|
|
619
|
+
return existing;
|
|
620
|
+
}
|
|
621
|
+
const connection = new VoiceConnection(options);
|
|
622
|
+
if (!byGuild) {
|
|
623
|
+
byGuild = new Map();
|
|
624
|
+
connections.set(owner, byGuild);
|
|
625
|
+
}
|
|
626
|
+
byGuild.set(options.guildId, connection);
|
|
627
|
+
return connection;
|
|
418
628
|
}
|
|
419
629
|
|
|
630
|
+
/**
|
|
631
|
+
* How long (ms) the connection survives a kick or a lost signaling socket waiting for a move.
|
|
632
|
+
* @type {number}
|
|
633
|
+
*/
|
|
634
|
+
VoiceConnection.kickGraceMs = DEFAULT_KICK_GRACE_MS;
|
|
635
|
+
|
|
420
636
|
module.exports = { VoiceConnection, joinVoiceChannel };
|
package/src/structures/Guild.js
CHANGED
|
@@ -1457,7 +1457,7 @@ class Guild extends AnonymousGuild {
|
|
|
1457
1457
|
* @readonly
|
|
1458
1458
|
*/
|
|
1459
1459
|
get voiceAdapterCreator() {
|
|
1460
|
-
|
|
1460
|
+
const creator = methods => {
|
|
1461
1461
|
this.client.voice.adapters.set(this.id, methods);
|
|
1462
1462
|
return {
|
|
1463
1463
|
sendPayload: data => {
|
|
@@ -1466,10 +1466,13 @@ class Guild extends AnonymousGuild {
|
|
|
1466
1466
|
return true;
|
|
1467
1467
|
},
|
|
1468
1468
|
destroy: () => {
|
|
1469
|
-
this.client.voice.adapters.delete(this.id);
|
|
1469
|
+
if (this.client.voice.adapters.get(this.id) === methods) this.client.voice.adapters.delete(this.id);
|
|
1470
1470
|
},
|
|
1471
1471
|
};
|
|
1472
1472
|
};
|
|
1473
|
+
// Метка владельца: voice-соединения разных клиентов в одной гильдии не пересекаются.
|
|
1474
|
+
creator.voiceManager = this.client.voice;
|
|
1475
|
+
return creator;
|
|
1473
1476
|
}
|
|
1474
1477
|
|
|
1475
1478
|
/**
|
package/typings/index.d.mts
CHANGED
|
@@ -8136,9 +8136,16 @@ export interface VoiceConnectionOptions {
|
|
|
8136
8136
|
selfDeaf?: boolean;
|
|
8137
8137
|
}
|
|
8138
8138
|
|
|
8139
|
+
export interface VoiceConnectionRejoinOptions {
|
|
8140
|
+
channelId?: string;
|
|
8141
|
+
selfMute?: boolean;
|
|
8142
|
+
selfDeaf?: boolean;
|
|
8143
|
+
}
|
|
8144
|
+
|
|
8139
8145
|
export type VoiceConnectionState = 'connecting' | 'ready' | 'error' | 'destroyed';
|
|
8140
8146
|
|
|
8141
8147
|
export class VoiceConnection extends EventEmitter {
|
|
8148
|
+
public static kickGraceMs: number;
|
|
8142
8149
|
private constructor(options: VoiceConnectionOptions);
|
|
8143
8150
|
public channelId: string;
|
|
8144
8151
|
public guildId: string;
|
|
@@ -8147,6 +8154,7 @@ export class VoiceConnection extends EventEmitter {
|
|
|
8147
8154
|
public token: string | null;
|
|
8148
8155
|
public endpoint: string | null;
|
|
8149
8156
|
public awaitReady(timeout?: number): Promise<void>;
|
|
8157
|
+
public rejoin(options?: VoiceConnectionRejoinOptions): boolean;
|
|
8150
8158
|
public play(input: string | NodeJS.ReadableStream): void;
|
|
8151
8159
|
public stop(): void;
|
|
8152
8160
|
public destroy(): void;
|
package/typings/index.d.ts
CHANGED
|
@@ -8136,9 +8136,16 @@ export interface VoiceConnectionOptions {
|
|
|
8136
8136
|
selfDeaf?: boolean;
|
|
8137
8137
|
}
|
|
8138
8138
|
|
|
8139
|
+
export interface VoiceConnectionRejoinOptions {
|
|
8140
|
+
channelId?: string;
|
|
8141
|
+
selfMute?: boolean;
|
|
8142
|
+
selfDeaf?: boolean;
|
|
8143
|
+
}
|
|
8144
|
+
|
|
8139
8145
|
export type VoiceConnectionState = 'connecting' | 'ready' | 'error' | 'destroyed';
|
|
8140
8146
|
|
|
8141
8147
|
export class VoiceConnection extends EventEmitter {
|
|
8148
|
+
public static kickGraceMs: number;
|
|
8142
8149
|
private constructor(options: VoiceConnectionOptions);
|
|
8143
8150
|
public channelId: string;
|
|
8144
8151
|
public guildId: string;
|
|
@@ -8147,6 +8154,7 @@ export class VoiceConnection extends EventEmitter {
|
|
|
8147
8154
|
public token: string | null;
|
|
8148
8155
|
public endpoint: string | null;
|
|
8149
8156
|
public awaitReady(timeout?: number): Promise<void>;
|
|
8157
|
+
public rejoin(options?: VoiceConnectionRejoinOptions): boolean;
|
|
8150
8158
|
public play(input: string | NodeJS.ReadableStream): void;
|
|
8151
8159
|
public stop(): void;
|
|
8152
8160
|
public destroy(): void;
|