Skip to content

Commit

Permalink
♻️ refactor player channel events
Browse files Browse the repository at this point in the history
  • Loading branch information
melike2d committed Feb 27, 2022
1 parent f260eb9 commit 5768421
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 9 deletions.
31 changes: 24 additions & 7 deletions src/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,22 +76,23 @@ export class Player<N extends Node = Node> extends EventEmitter<PlayerEvents> {
* @returns the player, useful for chaining.
*/
connect(channel: Snowflake | { id: Snowflake } | null, options: ConnectOptions = {}): this {
this.#_voiceUpdate = {}

/* parse the snowflake. */
channel = (typeof channel === "object" ? channel?.id : channel) ?? null;
this.channelId = channel && snowflakeToBigint(channel);

/* send the voice status update payload. */
this.node.debug(
"voice",
`updating voice status in guild=${this.guildId}, channel=${this.channelId}`,
`updating voice status in guild=${this.guildId}, channel=${channel}`,
this
);

this.node.sendGatewayPayload(this.guildId, {
op: 4,
d: {
guild_id: `${this.guildId}`,
channel_id: this.channelId ? `${this.channelId}` : null,
channel_id: channel ? `${channel}` : null,
self_mute: options.muted ?? false,
self_deaf: options.deafen ?? false,
},
Expand All @@ -106,6 +107,7 @@ export class Player<N extends Node = Node> extends EventEmitter<PlayerEvents> {
*/
disconnect(): this {
this.connect(null);
this.channelId = null;
return this;
}

Expand Down Expand Up @@ -309,15 +311,28 @@ export class Player<N extends Node = Node> extends EventEmitter<PlayerEvents> {
async handleVoiceUpdate(update: DiscordVoiceState | DiscordVoiceServer): Promise<this> {
/* update our local voice state or server data. */
if ("token" in update) {
if (this.#_voiceUpdate.event === update) {
return this;
}

this.#_voiceUpdate.event = update;
} else {
/* check if this voice state is for us and not some random user. */
if (snowflakeToBigint(update.user_id) !== this.node.userId) {
return this;
}

if (update.channel_id && this.channelId !== snowflakeToBigint(update.channel_id)) {
this.emit("channelMove", this.channelId!, snowflakeToBigint(update.channel_id));
const channel = snowflakeToBigint(update.channel_id!);
if (!channel && this.channelId) {
this.emit("channelLeave", this.channelId);
this.channelId = null;
this.#_voiceUpdate = {};
} else if (channel && !this.channelId) {
this.channelId = channel;
this.emit("channelJoin", channel);
} else if (channel !== this.channelId) {
this.emit("channelMove", this.channelId!, channel);
this.channelId = channel;
}

this.#_voiceUpdate.sessionId = update.session_id;
Expand Down Expand Up @@ -367,7 +382,7 @@ export class Player<N extends Node = Node> extends EventEmitter<PlayerEvents> {
this.emit("trackException", event.track, new Error(event.error));
break;
case "WebSocketClosedEvent":
this.emit("channelLeave", event.code, event.reason, event.byRemote)
this.emit("disconnected", event.code, event.reason, event.byRemote)
break;
}
}
Expand All @@ -380,7 +395,9 @@ export type PlayerEvents = {
trackEnd: [track: string | null, reason: Lavalink.TrackEndReason];
trackException: [track: string | null, error: Error];
trackStuck: [track: string | null, thresholdMs: number];
channelLeave: [code: number, reason: string, byRemote: boolean];
disconnected: [code: number, reason: string, byRemote: boolean];
channelJoin: [joined: bigint];
channelLeave: [left: bigint];
channelMove: [from: bigint, to: bigint];
};

Expand Down
21 changes: 19 additions & 2 deletions testing/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ cluster.on("nodeError", (_, error) => {
});

cluster.on("nodeDebug", (node, message) => {
console.debug(`[music] (node ${node.id}) ${message}`);
// console.debug(`[music] (node ${node.id}) ${message}`);
});

cluster.on("nodeConnect", (node, reconnect) => {
Expand Down Expand Up @@ -100,7 +100,9 @@ startBot({

player ??= cluster.createPlayer(message.guildId);
player.connect(vc.channelId, { deafen: true });
createQueue(player, message.channelId);
if (!queues.get(message.guildId)) {
createQueue(player, message.channelId);
}

return message.reply(embed(`Connected to <#${vc.channelId}>`), false);
}
Expand Down Expand Up @@ -161,6 +163,21 @@ startBot({
false
);
}
case "leave": {
let player = cluster.players.get(message.guildId);
if (!player?.connected) {
return message.reply(
embed("A player for this guild doesn't exist."),
false
);
}

player.disconnect()
return message.reply(
embed("Left voice channel"),
false
)
}
case "play": {
const vc = message.guild?.voiceStates?.get(message.authorId);
if (!vc?.channelId) {
Expand Down
4 changes: 4 additions & 0 deletions testing/queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ export class Queue extends EventEmitter<QueueEvents> {
constructor(player: Player) {
super();

player.on("channelJoin", joined => console.log(`[music] (player ${player!.guildId}) joined ${joined}`))
player.on("channelLeave", left => console.log(`[music] (player ${player!.guildId}) left ${left}`))
player.on("channelMove", (from, to) => console.log(`[music] (player ${player!.guildId}) moved from ${from} to ${to}`));

this.player = player
.on("trackEnd", (_, reason) => {
if (!["REPLACED"].includes(reason)) {
Expand Down

0 comments on commit 5768421

Please sign in to comment.