pi-roundtable 0.47.3 → 0.48.0
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/CHANGELOG.md +7 -0
- package/README.md +5 -0
- package/docs/plugins.md +55 -4
- package/package.json +6 -1
- package/src/core/builtin/discord.ts +41 -0
- package/src/core/config/adapters.ts +10 -0
- package/src/core/discord/discord-surface.ts +4 -0
- package/src/core/discord/voice/voice-clock.ts +51 -0
- package/src/core/discord/voice/voice-discord.ts +170 -0
- package/src/core/discord/voice/voice-link.ts +322 -0
- package/src/core/discord/voice/voice-service.ts +308 -0
- package/src/core/discord/voice/voice-session.ts +230 -0
- package/src/core/discord/voice/voice.ts +144 -0
- package/src/core/host/define-roundtable.ts +1 -0
- package/src/core/testing/fake-discord.ts +7 -2
- package/src/core/testing/fake-voice.ts +227 -0
- package/src/core/testing/plugin-stand-ins.ts +27 -0
- package/src/core/testing/test-host.ts +5 -1
- package/src/discord/index.ts +14 -0
- package/src/testing.ts +7 -19
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DiscordGatewayAdapterCreator,
|
|
3
|
+
VoiceConnection,
|
|
4
|
+
VoiceConnectionState,
|
|
5
|
+
} from "@discordjs/voice";
|
|
6
|
+
import type { Logger } from "../../kernel/log.ts";
|
|
7
|
+
import { systemClock, type VoiceClock } from "./voice-clock.ts";
|
|
8
|
+
import type {
|
|
9
|
+
VoiceLink,
|
|
10
|
+
VoiceLinkHandlers,
|
|
11
|
+
VoiceLinkStatus,
|
|
12
|
+
} from "./voice-service.ts";
|
|
13
|
+
|
|
14
|
+
/** What the link uses of @discordjs/voice, so a test gives a stand-in `joinVoiceChannel`. */
|
|
15
|
+
export type VoiceLib = Pick<
|
|
16
|
+
typeof import("@discordjs/voice"),
|
|
17
|
+
| "joinVoiceChannel"
|
|
18
|
+
| "getVoiceConnection"
|
|
19
|
+
| "VoiceConnectionStatus"
|
|
20
|
+
| "VoiceConnectionDisconnectReason"
|
|
21
|
+
| "EndBehaviorType"
|
|
22
|
+
>;
|
|
23
|
+
|
|
24
|
+
/** One speaker's Opus decoder: packets in, `VOICE_PCM` frames out. Opus keeps state between packets, so each speaker has their own. */
|
|
25
|
+
export interface OpusDecoder {
|
|
26
|
+
/** Throws for a packet that is no Opus. */
|
|
27
|
+
decode(packet: Uint8Array): Uint8Array;
|
|
28
|
+
free(): void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Discord's voice close code for a bot that was disconnected, moved, or whose channel was deleted. */
|
|
32
|
+
const DISCONNECTED = 4014;
|
|
33
|
+
/** How often a connection the main gateway could not carry is asked for again. */
|
|
34
|
+
const REJOIN_MS = 3_000;
|
|
35
|
+
/** The voice connection group, so a connection another library opened in the guild is never taken for ours. */
|
|
36
|
+
const GROUP = "pi-roundtable";
|
|
37
|
+
/**
|
|
38
|
+
* How long a speaker is quiet before their decoder is freed. opusscript's decoders share one
|
|
39
|
+
* fixed heap, which holds 79 of them in the whole process: one more decodes nothing until others
|
|
40
|
+
* are freed. So a decoder is kept only for who is speaking, not for everyone who ever spoke.
|
|
41
|
+
*/
|
|
42
|
+
const DECODER_IDLE_MS = 60_000;
|
|
43
|
+
|
|
44
|
+
/** One speaker's decoder, and when it last had a packet. */
|
|
45
|
+
interface Hearing {
|
|
46
|
+
decoder: OpusDecoder;
|
|
47
|
+
lastAt: number;
|
|
48
|
+
/** Runs when the speaker may have been quiet for `DECODER_IDLE_MS`. */
|
|
49
|
+
timer: unknown;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Loads @discordjs/voice with the DAVE library Discord's end-to-end encryption needs, which
|
|
54
|
+
* nothing else in the host imports: a host without `discord.voice` never loads them.
|
|
55
|
+
*/
|
|
56
|
+
export async function loadVoiceLib(): Promise<VoiceLib> {
|
|
57
|
+
try {
|
|
58
|
+
const [lib] = await Promise.all([
|
|
59
|
+
import("@discordjs/voice"),
|
|
60
|
+
import("@snazzah/davey"),
|
|
61
|
+
]);
|
|
62
|
+
return lib;
|
|
63
|
+
} catch (cause) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
"discord.voice is on, but @discordjs/voice or @snazzah/davey could not be loaded. Install pi-roundtable's dependencies again (bun install), or set discord.voice to false.",
|
|
66
|
+
{ cause },
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Loads the Opus decoder (opusscript, WebAssembly: no native build) and answers a maker of 48 kHz mono decoders. */
|
|
72
|
+
export async function loadOpusDecoders(): Promise<() => OpusDecoder> {
|
|
73
|
+
try {
|
|
74
|
+
const { default: OpusScript } = await import("opusscript");
|
|
75
|
+
return () => {
|
|
76
|
+
// One channel: libopus mixes Discord's stereo down as it decodes.
|
|
77
|
+
const decoder = new OpusScript(48_000, 1);
|
|
78
|
+
return {
|
|
79
|
+
decode: (packet) =>
|
|
80
|
+
decoder.decode(
|
|
81
|
+
Buffer.isBuffer(packet) ? packet : Buffer.from(packet),
|
|
82
|
+
),
|
|
83
|
+
free: () => decoder.delete(),
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
} catch (cause) {
|
|
87
|
+
throw new Error(
|
|
88
|
+
"discord.voice is on, but opusscript could not be loaded. Install pi-roundtable's dependencies again (bun install), or set discord.voice to false.",
|
|
89
|
+
{ cause },
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface VoiceLinkOptions {
|
|
95
|
+
guildId: string;
|
|
96
|
+
channelId: string;
|
|
97
|
+
adapterCreator: DiscordGatewayAdapterCreator;
|
|
98
|
+
decoder: () => OpusDecoder;
|
|
99
|
+
logger: Logger;
|
|
100
|
+
/** What the rejoin attempts wait by. Default: the host's clock. */
|
|
101
|
+
clock?: VoiceClock;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Joins the channel muted and not deafened, and hears every speaker: each one's Opus packets,
|
|
106
|
+
* already decrypted by @discordjs/voice (transport encryption and DAVE), are decoded here and
|
|
107
|
+
* handed on as frames. The audio is never logged and never written anywhere.
|
|
108
|
+
*/
|
|
109
|
+
export function openVoiceLink(
|
|
110
|
+
lib: VoiceLib,
|
|
111
|
+
options: VoiceLinkOptions,
|
|
112
|
+
): VoiceLink {
|
|
113
|
+
const { guildId, channelId } = options;
|
|
114
|
+
let connection: VoiceConnection | undefined;
|
|
115
|
+
try {
|
|
116
|
+
connection = lib.joinVoiceChannel({
|
|
117
|
+
guildId,
|
|
118
|
+
channelId,
|
|
119
|
+
group: GROUP,
|
|
120
|
+
adapterCreator: options.adapterCreator,
|
|
121
|
+
selfDeaf: false,
|
|
122
|
+
selfMute: true,
|
|
123
|
+
});
|
|
124
|
+
return linkOver(lib, connection, options);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
// Not left behind: the library keeps a connection by guild, even one whose join threw, and hands it to the guild's next join.
|
|
127
|
+
const left = connection ?? lib.getVoiceConnection(guildId, GROUP);
|
|
128
|
+
try {
|
|
129
|
+
if (left && left.state.status !== lib.VoiceConnectionStatus.Destroyed)
|
|
130
|
+
left.destroy();
|
|
131
|
+
} catch {
|
|
132
|
+
// The library forgot the connection before this threw; the failure to report is the first.
|
|
133
|
+
}
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The link over a connection the library made: what `openVoiceLink` answers. */
|
|
139
|
+
function linkOver(
|
|
140
|
+
lib: VoiceLib,
|
|
141
|
+
connection: VoiceConnection,
|
|
142
|
+
options: VoiceLinkOptions,
|
|
143
|
+
): VoiceLink {
|
|
144
|
+
const { guildId, channelId, logger } = options;
|
|
145
|
+
const clock = options.clock ?? systemClock;
|
|
146
|
+
const { VoiceConnectionStatus: Status } = lib;
|
|
147
|
+
const decoders = new Map<string, Hearing>();
|
|
148
|
+
/** How many packets of each speaker were not decoded. */
|
|
149
|
+
const undecoded = new Map<string, number>();
|
|
150
|
+
const subscribed = new Set<string>();
|
|
151
|
+
let handlers: VoiceLinkHandlers | undefined;
|
|
152
|
+
let closed = false;
|
|
153
|
+
/** The timer of the next rejoin, while the last one was refused. */
|
|
154
|
+
let rejoin: unknown;
|
|
155
|
+
/** Whether a rejoin is being asked for right now. */
|
|
156
|
+
let rejoining = false;
|
|
157
|
+
|
|
158
|
+
const statusOf = (state: VoiceConnectionState): VoiceLinkStatus => {
|
|
159
|
+
if (state.status === Status.Ready) return "ready";
|
|
160
|
+
return state.status === Status.Destroyed ? "closed" : "reconnecting";
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A connection the main gateway dropped is asked for again, once now and once every `REJOIN_MS`
|
|
165
|
+
* until it is carried; Discord's own disconnect is not. Whoever owns the link ends the waiting
|
|
166
|
+
* by closing it.
|
|
167
|
+
*/
|
|
168
|
+
const recover = (state: VoiceConnectionState): void => {
|
|
169
|
+
// `rejoin()` reports its own outcome as a state change before it answers: that one is not a drop to recover from.
|
|
170
|
+
if (rejoining) return;
|
|
171
|
+
clock.clearTimeout(rejoin);
|
|
172
|
+
rejoin = undefined;
|
|
173
|
+
if (closed || state.status !== Status.Disconnected) return;
|
|
174
|
+
const refused =
|
|
175
|
+
state.reason === lib.VoiceConnectionDisconnectReason.WebSocketClose &&
|
|
176
|
+
state.closeCode === DISCONNECTED;
|
|
177
|
+
if (refused) return;
|
|
178
|
+
let carried: boolean;
|
|
179
|
+
rejoining = true;
|
|
180
|
+
try {
|
|
181
|
+
carried = connection.rejoin();
|
|
182
|
+
} finally {
|
|
183
|
+
rejoining = false;
|
|
184
|
+
}
|
|
185
|
+
if (carried) return;
|
|
186
|
+
rejoin = clock.setTimeout(() => retry(), REJOIN_MS);
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
/** A later rejoin that throws is a refused one: warned, no audio, asked for again. */
|
|
190
|
+
const retry = (): void => {
|
|
191
|
+
try {
|
|
192
|
+
recover(connection.state);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
logger.warn(
|
|
195
|
+
{
|
|
196
|
+
guildId,
|
|
197
|
+
channelId,
|
|
198
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
199
|
+
},
|
|
200
|
+
"voice rejoin failed",
|
|
201
|
+
);
|
|
202
|
+
rejoin = clock.setTimeout(() => retry(), REJOIN_MS);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/** Frees a speaker's decoder; their next packet makes a new one. */
|
|
207
|
+
const forget = (userId: string): void => {
|
|
208
|
+
const hearing = decoders.get(userId);
|
|
209
|
+
if (!hearing) return;
|
|
210
|
+
decoders.delete(userId);
|
|
211
|
+
clock.clearTimeout(hearing.timer);
|
|
212
|
+
hearing.decoder.free();
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
/** The idle timer ran: the decoder is freed if no packet came since, else the timer waits out the rest. */
|
|
216
|
+
const idle = (userId: string): void => {
|
|
217
|
+
const hearing = decoders.get(userId);
|
|
218
|
+
if (!hearing) return;
|
|
219
|
+
const left = hearing.lastAt + DECODER_IDLE_MS - clock.now();
|
|
220
|
+
if (left > 0) hearing.timer = clock.setTimeout(() => idle(userId), left);
|
|
221
|
+
else forget(userId);
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
/** One packet through its speaker's decoder, which is made when first needed; undefined for a packet that was not decoded. */
|
|
225
|
+
const decode = (
|
|
226
|
+
userId: string,
|
|
227
|
+
packet: Uint8Array,
|
|
228
|
+
): Uint8Array | undefined => {
|
|
229
|
+
try {
|
|
230
|
+
let hearing = decoders.get(userId);
|
|
231
|
+
if (!hearing) {
|
|
232
|
+
hearing = { decoder: options.decoder(), lastAt: 0, timer: undefined };
|
|
233
|
+
hearing.timer = clock.setTimeout(() => idle(userId), DECODER_IDLE_MS);
|
|
234
|
+
decoders.set(userId, hearing);
|
|
235
|
+
}
|
|
236
|
+
hearing.lastAt = clock.now();
|
|
237
|
+
return hearing.decoder.decode(packet);
|
|
238
|
+
} catch (error) {
|
|
239
|
+
// Counted and named by its speaker, once; never logged with its bytes.
|
|
240
|
+
const lost = (undecoded.get(userId) ?? 0) + 1;
|
|
241
|
+
undecoded.set(userId, lost);
|
|
242
|
+
if (lost === 1)
|
|
243
|
+
logger.warn(
|
|
244
|
+
{
|
|
245
|
+
guildId,
|
|
246
|
+
userId,
|
|
247
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
248
|
+
},
|
|
249
|
+
"voice packet not decoded",
|
|
250
|
+
);
|
|
251
|
+
// The decoder may be one the heap had no room for: the next packet gets a new one, which decodes once others were freed.
|
|
252
|
+
forget(userId);
|
|
253
|
+
return undefined;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const hear = (userId: string): void => {
|
|
258
|
+
if (closed || subscribed.has(userId)) return;
|
|
259
|
+
subscribed.add(userId);
|
|
260
|
+
const stream = connection.receiver.subscribe(userId, {
|
|
261
|
+
end: { behavior: lib.EndBehaviorType.Manual },
|
|
262
|
+
});
|
|
263
|
+
stream.on("data", (packet: Uint8Array) => {
|
|
264
|
+
// A packet the stream still held when the link closed is not decoded: its decoder is freed.
|
|
265
|
+
if (closed) return;
|
|
266
|
+
const pcm = decode(userId, packet);
|
|
267
|
+
if (pcm) handlers?.frame(userId, pcm);
|
|
268
|
+
});
|
|
269
|
+
// @discordjs/voice destroys the stream on a packet it cannot decrypt; the speaker is heard again from the next one.
|
|
270
|
+
stream.on("error", (error: Error) =>
|
|
271
|
+
logger.debug(
|
|
272
|
+
{ guildId, userId, reason: error.message },
|
|
273
|
+
"voice stream failed",
|
|
274
|
+
),
|
|
275
|
+
);
|
|
276
|
+
stream.once("close", () => {
|
|
277
|
+
subscribed.delete(userId);
|
|
278
|
+
if (!closed && connection.state.status !== Status.Destroyed) hear(userId);
|
|
279
|
+
});
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
connection.receiver.speaking.on("start", hear);
|
|
283
|
+
connection.on("stateChange", (_before, state) => {
|
|
284
|
+
recover(state);
|
|
285
|
+
if (state.status === Status.Destroyed) release();
|
|
286
|
+
handlers?.status(statusOf(state));
|
|
287
|
+
});
|
|
288
|
+
connection.on("error", (error) =>
|
|
289
|
+
logger.warn({ guildId, channelId, err: error }, "voice connection error"),
|
|
290
|
+
);
|
|
291
|
+
|
|
292
|
+
const release = (): void => {
|
|
293
|
+
if (closed) return;
|
|
294
|
+
closed = true;
|
|
295
|
+
clock.clearTimeout(rejoin);
|
|
296
|
+
connection.receiver.speaking.off("start", hear);
|
|
297
|
+
for (const stream of connection.receiver.subscriptions.values())
|
|
298
|
+
stream.destroy();
|
|
299
|
+
for (const userId of [...decoders.keys()]) forget(userId);
|
|
300
|
+
let lost = 0;
|
|
301
|
+
for (const count of undecoded.values()) lost += count;
|
|
302
|
+
if (lost > 0)
|
|
303
|
+
logger.warn(
|
|
304
|
+
{ guildId, undecoded: lost, speakers: undecoded.size },
|
|
305
|
+
"voice packets were not decoded",
|
|
306
|
+
);
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
recover(connection.state);
|
|
310
|
+
return {
|
|
311
|
+
status: () => (closed ? "closed" : statusOf(connection.state)),
|
|
312
|
+
listen: (given) => {
|
|
313
|
+
handlers = given;
|
|
314
|
+
},
|
|
315
|
+
forget,
|
|
316
|
+
close: () => {
|
|
317
|
+
release();
|
|
318
|
+
// Tells Discord the bot left the channel; reports `closed` through the state change.
|
|
319
|
+
if (connection.state.status !== Status.Destroyed) connection.destroy();
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import type { Logger } from "../../kernel/log.ts";
|
|
2
|
+
import type {
|
|
3
|
+
DiscordVoice,
|
|
4
|
+
VoiceDisconnectReason,
|
|
5
|
+
VoiceJoinFailure,
|
|
6
|
+
VoiceJoinOptions,
|
|
7
|
+
VoiceJoinResult,
|
|
8
|
+
VoiceMember,
|
|
9
|
+
} from "./voice.ts";
|
|
10
|
+
import { systemClock, type VoiceClock } from "./voice-clock.ts";
|
|
11
|
+
import { VoiceSessionState } from "./voice-session.ts";
|
|
12
|
+
|
|
13
|
+
/** A channel as the bot sees it, read when a join is asked. */
|
|
14
|
+
export interface VoiceChannelFacts {
|
|
15
|
+
guildId: string;
|
|
16
|
+
kind: "voice" | "stage" | "other";
|
|
17
|
+
/** Whether the bot may see the channel and connect to it. */
|
|
18
|
+
connectable: boolean;
|
|
19
|
+
/** Whether the channel is at its user limit and the bot may not move members. */
|
|
20
|
+
full: boolean;
|
|
21
|
+
/** Who is in it now, without the bot. */
|
|
22
|
+
members: VoiceMember[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Someone's voice channel changed: `channelId` is where they are now, undefined for nowhere. */
|
|
26
|
+
export interface VoiceStateChange {
|
|
27
|
+
guildId: string;
|
|
28
|
+
userId: string;
|
|
29
|
+
channelId: string | undefined;
|
|
30
|
+
member: VoiceMember;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `ready` hears audio; `reconnecting` is trying to; `closed` never will again. */
|
|
34
|
+
export type VoiceLinkStatus = "ready" | "reconnecting" | "closed";
|
|
35
|
+
|
|
36
|
+
/** What a voice connection reports to the session that owns it. */
|
|
37
|
+
export interface VoiceLinkHandlers {
|
|
38
|
+
status(status: VoiceLinkStatus): void;
|
|
39
|
+
/** One decoded frame of a speaker, in the `VOICE_PCM` format, which the link keeps no reference to. */
|
|
40
|
+
frame(userId: string, pcm: Uint8Array): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** One voice connection: the bot in a channel, muted and not deafened. */
|
|
44
|
+
export interface VoiceLink {
|
|
45
|
+
status(): VoiceLinkStatus;
|
|
46
|
+
/** Takes the one listener of the link; what happened before it is read from `status()`. */
|
|
47
|
+
listen(handlers: VoiceLinkHandlers): void;
|
|
48
|
+
/** Someone left the channel: what the link kept to hear them is freed, and made again if they are heard after all. */
|
|
49
|
+
forget(userId: string): void;
|
|
50
|
+
/** Leaves the channel and frees the decoders; does nothing the second time. */
|
|
51
|
+
close(): void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What the voice service needs of Discord: discord.js and @discordjs/voice in a host, a stand-in in a test. */
|
|
55
|
+
export interface VoiceGateway {
|
|
56
|
+
/** Whether the gateway connection is up. */
|
|
57
|
+
ready(): boolean;
|
|
58
|
+
/** The bot's own user id; undefined until the connection is ready. */
|
|
59
|
+
botId(): string | undefined;
|
|
60
|
+
/** The channel as it is now; `gone` for one Discord does not know, `forbidden` for one the bot may not see. Throws when Discord cannot be reached. */
|
|
61
|
+
channel(channelId: string): Promise<VoiceChannelFacts | "gone" | "forbidden">;
|
|
62
|
+
/** Reports every voice channel change in every guild. */
|
|
63
|
+
onVoiceState(listener: (change: VoiceStateChange) => void): void;
|
|
64
|
+
/** Loads what a connection needs, so a host that cannot hear fails as it starts. */
|
|
65
|
+
prepare(): Promise<void>;
|
|
66
|
+
/** Opens the voice connection; rejects when it cannot be opened at all. */
|
|
67
|
+
connect(target: { guildId: string; channelId: string }): Promise<VoiceLink>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface VoiceServiceOptions {
|
|
71
|
+
gateway: VoiceGateway;
|
|
72
|
+
logger: Logger;
|
|
73
|
+
clock?: VoiceClock;
|
|
74
|
+
/** How long a new connection may take to become ready. Default 20 s. */
|
|
75
|
+
connectMs?: number;
|
|
76
|
+
/** How long a dropped connection may take to come back before the session ends; at most 30 s. Default 20 s. */
|
|
77
|
+
resumeMs?: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The voice service as the Discord plugin holds it: what plugins get, and its place in the host's start and stop. */
|
|
81
|
+
export interface VoiceService extends DiscordVoice {
|
|
82
|
+
start(): Promise<void>;
|
|
83
|
+
/** Ends every session with `stopped` and refuses joins from then on. */
|
|
84
|
+
stop(): Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const DEFAULTS = { silenceMs: 800, maxUtteranceMs: 30_000 };
|
|
88
|
+
const MAX_RESUME_MS = 30_000;
|
|
89
|
+
|
|
90
|
+
function inRange(name: string, value: number, min: number, max: number) {
|
|
91
|
+
if (!Number.isInteger(value) || value < min || value > max)
|
|
92
|
+
throw new RangeError(
|
|
93
|
+
`voice join: ${name} must be a whole number from ${min} to ${max}, got ${value}.`,
|
|
94
|
+
);
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const MESSAGES: Record<VoiceJoinFailure, string> = {
|
|
99
|
+
forbidden:
|
|
100
|
+
"The bot may not connect to the channel. Give it View Channel and Connect there.",
|
|
101
|
+
channel_gone: "The guild has no such channel.",
|
|
102
|
+
not_voice: "The channel is neither a voice nor a stage channel.",
|
|
103
|
+
full: "The channel is full.",
|
|
104
|
+
unavailable: "Discord voice is not available right now. Try again.",
|
|
105
|
+
already_joined:
|
|
106
|
+
"The bot is already in a voice channel of this guild, or joining one. Leave it first.",
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
function failed(failure: VoiceJoinFailure, message?: string): VoiceJoinResult {
|
|
110
|
+
return { ok: false, failure, message: message ?? MESSAGES[failure] };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface Joined {
|
|
114
|
+
session: VoiceSessionState;
|
|
115
|
+
link: VoiceLink | undefined;
|
|
116
|
+
/** Whether `join` answered with the session: until then nothing ends it but the join itself. */
|
|
117
|
+
open: boolean;
|
|
118
|
+
/** Runs when the connection stayed down too long. */
|
|
119
|
+
resume: unknown;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Voice sessions over a gateway, one per guild. A join checks the channel before it connects, so
|
|
124
|
+
* each refusal has its own failure; a connection that drops has `resumeMs` to come back.
|
|
125
|
+
*/
|
|
126
|
+
export function voiceService(options: VoiceServiceOptions): VoiceService {
|
|
127
|
+
const { gateway, logger } = options;
|
|
128
|
+
const clock = options.clock ?? systemClock;
|
|
129
|
+
const connectMs = options.connectMs ?? 20_000;
|
|
130
|
+
const resumeMs = Math.min(options.resumeMs ?? 20_000, MAX_RESUME_MS);
|
|
131
|
+
/** By guild: Discord has one voice connection per guild. */
|
|
132
|
+
const joined = new Map<string, Joined>();
|
|
133
|
+
let stopping = false;
|
|
134
|
+
|
|
135
|
+
const end = (entry: Joined, reason: VoiceDisconnectReason): void => {
|
|
136
|
+
const { session } = entry;
|
|
137
|
+
if (joined.get(session.guildId) === entry) joined.delete(session.guildId);
|
|
138
|
+
clock.clearTimeout(entry.resume);
|
|
139
|
+
entry.resume = undefined;
|
|
140
|
+
session.end(reason);
|
|
141
|
+
entry.link?.close();
|
|
142
|
+
logger.info(
|
|
143
|
+
{ guildId: session.guildId, channelId: session.channelId, reason },
|
|
144
|
+
"voice session ended",
|
|
145
|
+
);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const onStatus = (entry: Joined, status: VoiceLinkStatus): void => {
|
|
149
|
+
if (!entry.open || entry.session.ended() !== undefined) return;
|
|
150
|
+
if (status === "closed") {
|
|
151
|
+
end(entry, "connection_lost");
|
|
152
|
+
} else if (status === "ready") {
|
|
153
|
+
if (entry.resume === undefined) return;
|
|
154
|
+
clock.clearTimeout(entry.resume);
|
|
155
|
+
entry.resume = undefined;
|
|
156
|
+
void reread(entry);
|
|
157
|
+
} else {
|
|
158
|
+
entry.resume ??= clock.setTimeout(
|
|
159
|
+
() => end(entry, "connection_lost"),
|
|
160
|
+
resumeMs,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
/** Someone is no longer in the session's channel: what they were saying is delivered, then the link lets go of them. */
|
|
166
|
+
const gone = (entry: Joined, userId: string): void => {
|
|
167
|
+
entry.session.memberLeft(userId);
|
|
168
|
+
entry.link?.forget(userId);
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* A dropped connection is back: who is in the channel is read again, and whoever left or
|
|
173
|
+
* entered meanwhile is reported now. A gateway that had to identify again is sent the guild's
|
|
174
|
+
* voice states anew, with no word of what changed.
|
|
175
|
+
*/
|
|
176
|
+
const reread = async (entry: Joined): Promise<void> => {
|
|
177
|
+
const { session } = entry;
|
|
178
|
+
try {
|
|
179
|
+
const facts = await gateway.channel(session.channelId);
|
|
180
|
+
if (session.ended() !== undefined || typeof facts === "string") return;
|
|
181
|
+
const there = new Set(facts.members.map((member) => member.userId));
|
|
182
|
+
for (const { userId } of session.members())
|
|
183
|
+
if (!there.has(userId)) gone(entry, userId);
|
|
184
|
+
for (const member of facts.members) session.memberJoined(member);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
logger.warn(
|
|
187
|
+
{ guildId: session.guildId, channelId: session.channelId, err: error },
|
|
188
|
+
"voice members not read again",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
gateway.onVoiceState((change) => {
|
|
194
|
+
const entry = joined.get(change.guildId);
|
|
195
|
+
if (!entry) return;
|
|
196
|
+
const { session } = entry;
|
|
197
|
+
if (change.userId === gateway.botId()) {
|
|
198
|
+
// Its own way into the channel is the join's to wait for.
|
|
199
|
+
if (!entry.open || change.channelId === session.channelId) return;
|
|
200
|
+
return end(entry, change.channelId === undefined ? "removed" : "moved");
|
|
201
|
+
}
|
|
202
|
+
if (change.channelId === session.channelId)
|
|
203
|
+
session.memberJoined(change.member);
|
|
204
|
+
else gone(entry, change.userId);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
/** Resolves true once the link is ready; false when it closed or took longer than `connectMs`. */
|
|
208
|
+
const comesUp = (entry: Joined, link: VoiceLink): Promise<boolean> =>
|
|
209
|
+
new Promise((resolve) => {
|
|
210
|
+
const timer = clock.setTimeout(() => resolve(false), connectMs);
|
|
211
|
+
const settle = (status: VoiceLinkStatus) => {
|
|
212
|
+
if (status === "reconnecting") return;
|
|
213
|
+
clock.clearTimeout(timer);
|
|
214
|
+
resolve(status === "ready");
|
|
215
|
+
};
|
|
216
|
+
link.listen({
|
|
217
|
+
status: (status) => {
|
|
218
|
+
settle(status);
|
|
219
|
+
onStatus(entry, status);
|
|
220
|
+
},
|
|
221
|
+
frame: (userId, pcm) => entry.session.frame(userId, pcm),
|
|
222
|
+
});
|
|
223
|
+
settle(link.status());
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
const join = async (
|
|
227
|
+
target: { guildId: string; channelId: string },
|
|
228
|
+
given: VoiceJoinOptions = {},
|
|
229
|
+
): Promise<VoiceJoinResult> => {
|
|
230
|
+
const silenceMs = inRange(
|
|
231
|
+
"silenceMs",
|
|
232
|
+
given.silenceMs ?? DEFAULTS.silenceMs,
|
|
233
|
+
200,
|
|
234
|
+
5_000,
|
|
235
|
+
);
|
|
236
|
+
const maxUtteranceMs = inRange(
|
|
237
|
+
"maxUtteranceMs",
|
|
238
|
+
given.maxUtteranceMs ?? DEFAULTS.maxUtteranceMs,
|
|
239
|
+
1_000,
|
|
240
|
+
300_000,
|
|
241
|
+
);
|
|
242
|
+
const { guildId, channelId } = target;
|
|
243
|
+
if (stopping || !gateway.ready()) return failed("unavailable");
|
|
244
|
+
if (joined.has(guildId)) return failed("already_joined");
|
|
245
|
+
// Held from here on, so a second join of the guild is refused while this one is under way.
|
|
246
|
+
const entry: Joined = {
|
|
247
|
+
session: new VoiceSessionState({
|
|
248
|
+
guildId,
|
|
249
|
+
channelId,
|
|
250
|
+
members: [],
|
|
251
|
+
silenceMs,
|
|
252
|
+
maxUtteranceMs,
|
|
253
|
+
clock,
|
|
254
|
+
logger,
|
|
255
|
+
leave: () => end(entry, "left"),
|
|
256
|
+
}),
|
|
257
|
+
link: undefined,
|
|
258
|
+
open: false,
|
|
259
|
+
resume: undefined,
|
|
260
|
+
};
|
|
261
|
+
joined.set(guildId, entry);
|
|
262
|
+
const refuse = (failure: VoiceJoinFailure, error?: unknown) => {
|
|
263
|
+
if (joined.get(guildId) === entry) joined.delete(guildId);
|
|
264
|
+
entry.link?.close();
|
|
265
|
+
if (error !== undefined)
|
|
266
|
+
logger.warn({ guildId, channelId, err: error }, "voice join failed");
|
|
267
|
+
return failed(failure);
|
|
268
|
+
};
|
|
269
|
+
try {
|
|
270
|
+
const facts = await gateway.channel(channelId);
|
|
271
|
+
if (facts === "gone") return refuse("channel_gone");
|
|
272
|
+
if (facts === "forbidden") return refuse("forbidden");
|
|
273
|
+
if (facts.kind === "other") return refuse("not_voice");
|
|
274
|
+
if (facts.guildId !== guildId) return refuse("channel_gone");
|
|
275
|
+
if (!facts.connectable) return refuse("forbidden");
|
|
276
|
+
if (facts.full) return refuse("full");
|
|
277
|
+
// Whoever enters or leaves while the connection comes up is heard through the gateway from here.
|
|
278
|
+
for (const member of facts.members) entry.session.memberJoined(member);
|
|
279
|
+
if (stopping) return refuse("unavailable");
|
|
280
|
+
const link = await gateway.connect(target);
|
|
281
|
+
entry.link = link;
|
|
282
|
+
const up = await comesUp(entry, link);
|
|
283
|
+
if (stopping || !up || link.status() === "closed")
|
|
284
|
+
return refuse("unavailable");
|
|
285
|
+
entry.open = true;
|
|
286
|
+
// A drop between coming up and here starts the resume time like any later one.
|
|
287
|
+
if (link.status() === "reconnecting") onStatus(entry, "reconnecting");
|
|
288
|
+
} catch (error) {
|
|
289
|
+
return refuse("unavailable", error);
|
|
290
|
+
}
|
|
291
|
+
logger.info({ guildId, channelId }, "voice session joined");
|
|
292
|
+
return { ok: true, session: entry.session };
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
return {
|
|
296
|
+
join,
|
|
297
|
+
session: (guildId) => {
|
|
298
|
+
const entry = joined.get(guildId);
|
|
299
|
+
return entry?.open ? entry.session : undefined;
|
|
300
|
+
},
|
|
301
|
+
start: () => gateway.prepare(),
|
|
302
|
+
stop: async () => {
|
|
303
|
+
stopping = true;
|
|
304
|
+
for (const entry of [...joined.values()])
|
|
305
|
+
if (entry.open) end(entry, "stopped");
|
|
306
|
+
},
|
|
307
|
+
};
|
|
308
|
+
}
|