Skip to content

Commit

Permalink
refactor: fix all types conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
Fab1o0107 committed Jul 19, 2024
1 parent accb109 commit c98dc10
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 81 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@
"@types/node": "^20.14.11",
"@types/ws": "^8.5.11",
"cross-env": "^7.0.3",
"discord-api-types": "^0.37.92",
"eslint": "^9.7.0",
"eslint-config-prettier": "^9.1.0",
"eslint-formatter-pretty": "^6.0.1",
"eslint-plugin-prettier": "^5.2.1",
"lavalink-api-types": "^2.0.2",
"prettier": "^3.3.3",
"tsup": "^8.1.2",
"typedoc": "^0.26.4",
Expand Down
17 changes: 17 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 0 additions & 7 deletions src/Constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,6 @@ export enum VoiceState {
SessionFailedUpdate = 3
}

export enum OpCodes {
PlayerUpdate = "playerUpdate",
Stats = "stats",
Event = "event",
Ready = "ready"
}

export const RedisKey = {
NodeSession: (name: string) => `esbatu:node:${name}:session`,
NodePlayers: (name: string) => `esbatu:node:${name}:players`
Expand Down
33 changes: 20 additions & 13 deletions src/Esbatu.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable typescript/no-unsafe-member-access, typescript/no-unsafe-argument, typescript/no-unsafe-assignment, tsdoc/syntax */
/* eslint-disable tsdoc/syntax */
import { EventEmitter } from "node:events";
import type { GatewayVoiceServerUpdateDispatch, GatewayVoiceStateUpdateDispatch } from "discord-api-types/v10";
import { GatewayDispatchEvents } from "discord-api-types/v10";
import type { Redis } from "ioredis";
import { name as packageName, version as packageVersion } from "../package.json";
import { State, VoiceState } from "./Constants";
Expand Down Expand Up @@ -231,17 +233,18 @@ export abstract class Esbatu extends EventEmitter {
*
* @param packet Packet instance from Discord Gateway.
*/
// eslint-disable-next-line consistent-return, typescript/explicit-module-boundary-types
public updateInstance(packet: any): void {
const guildId = packet.d.guild_id;
public updateInstance(packet: GatewayVoiceServerUpdateDispatch | GatewayVoiceStateUpdateDispatch): void {
const guildId = packet.d.guild_id ?? "";
const connection = this.connections.get(guildId);
const AllowedPackets = ["VOICE_STATE_UPDATE", "VOICE_SERVER_UPDATE"];
const AllowedPackets: GatewayDispatchEvents[] = [
GatewayDispatchEvents.VoiceStateUpdate,
GatewayDispatchEvents.VoiceServerUpdate
];

if (!connection || !AllowedPackets.includes(packet.t)) return undefined;

if (packet.t === "VOICE_SERVER_UPDATE") {
// eslint-disable-next-line typescript/strict-boolean-expressions
if (!packet.d.endpoint) {
if (packet.t === GatewayDispatchEvents.VoiceServerUpdate) {
if (packet.d.endpoint === null) {
connection.emit("connectionUpdate", VoiceState.SessionEndpointMissing);

return undefined;
Expand All @@ -253,9 +256,12 @@ export abstract class Esbatu extends EventEmitter {
}

connection.lastRegion = connection.region?.repeat(1) ?? null;
// eslint-disable-next-line typescript/no-unsafe-call
connection.region = packet.d.endpoint.split(".").shift()?.replace(/\d/gu, "") ?? null;
connection.serverUpdate = packet.d;

connection.serverUpdate = {
token: packet.d.token,
endpoint: packet.d.endpoint
};

if (connection.region !== null && connection.lastRegion !== connection.region) {
this.emit(
Expand All @@ -278,7 +284,7 @@ export abstract class Esbatu extends EventEmitter {
connection.channelId = packet.d.channel_id;
connection.deafened = packet.d.self_deaf;
connection.muted = packet.d.self_mute;
connection.sessionId = packet.d.session_id ?? null;
connection.sessionId = packet.d.session_id;

if (connection.channelId !== null && connection.lastChannelId !== connection.channelId) {
this.emit(
Expand All @@ -299,15 +305,16 @@ export abstract class Esbatu extends EventEmitter {
"debug",
`[VOICE => DISCORD] State update received, session: ${connection.sessionId}, guild: ${guildId}.`
);

return undefined;
}

/**
* sendPacket is where your library send packets to Discord Gateway.
*
* @abstract
*/
// eslint-disable-next-line typescript/explicit-module-boundary-types
public abstract sendPacket(shardId: number, payload: any, important: boolean): void;
public abstract sendPacket(shardId: number, payload: unknown, important: boolean): void;
}

// @ts-expect-error ignore this ts(2300)
Expand Down
111 changes: 64 additions & 47 deletions src/guild/Player.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
/* eslint-disable jsdoc/check-param-names, tsdoc/syntax */
/* eslint-disable tsdoc/syntax */
import { EventEmitter } from "node:events";
import type { OpCodes } from "../Constants";
import type { PlayerUpdatePayload as IPlayerUpdatePayload, WebSocketOp } from "lavalink-api-types/v4";
import { WebSocketType } from "lavalink-api-types/v4";
import { RedisKey, State } from "../Constants";
import type { VoiceChannelOptions } from "../Esbatu";
import type { Exception, Track } from "../node/Rest";
import type { Node } from "../node/index";
import type { VoiceConnection } from "./VoiceConnection";

export type TrackEndReason = "cleanup" | "finished" | "loadFailed" | "replaced" | "stopped";
export type PlayerEventType =
| "TrackEndEvent"
| "TrackExceptionEvent"
| "TrackStartEvent"
| "TrackStuckEvent"
| "WebSocketClosedEvent";

export type PlayOptions = {
track: string;
options?: {
Expand Down Expand Up @@ -74,50 +67,67 @@ export type LowPassSettings = {
smoothing?: number;
};

export type PlayerEvent = {
op: OpCodes.Event;
type: PlayerEventType;
export type EventPayload = {
op: WebSocketOp.Event;
guildId: string;
type: WebSocketType;
};

export type TrackStartEvent = PlayerEvent & {
type: "TrackStartEvent";
export type TrackStartEventPayload = EventPayload & {
type: WebSocketType.TrackStartEvent;
track: Track;
};

export type TrackEndEvent = PlayerEvent & {
type: "TrackEndEvent";
export type TrackEndEventPayload = EventPayload & {
type: WebSocketType.TrackEndEvent;
track: Track | null;
reason: TrackEndReason;
};

export type TrackStuckEvent = PlayerEvent & {
type: "TrackStuckEvent";
export enum TrackEndReason {
Finished = "finished",
LoadFailed = "loadFailed",
Stopped = "stopped",
Replaced = "replaced",
Cleanup = "cleanup"
}

export type TrackStuckEventPayload = EventPayload & {
type: WebSocketType.TrackStuckEvent;
track: Track;
thresholdMs: number;
};

export type TrackExceptionEvent = PlayerEvent & {
type: "TrackExceptionEvent";
export type TrackExceptionEventPayload = EventPayload & {
type: WebSocketType.TrackExceptionEvent;
track: Track;
exception: Exception;
};

export type WebSocketClosedEvent = PlayerEvent & {
type: "WebSocketClosedEvent";
code: number;
export type WebSocketClosedEventPayload = EventPayload & {
type: WebSocketType.WebSocketClosedEvent;
code: WebsocketCloseCode;
reason: string;
byRemote: boolean;
};

export type PlayerUpdate = {
op: OpCodes.PlayerUpdate;
state: {
time: number;
position: number;
connected: boolean;
ping: number;
};
};
export enum WebsocketCloseCode {
UnknownError = 4_000,
UnknownOpCode = 4_001,
DecodeError = 4_002,
NotAuthenticated = 4_003,
AuthenticatedError = 4_004,
AlreadyAuthenticated = 4_005,
SessionInvalid = 4_006,
SessionTimeout = 4_009,
ServerNotFound = 4_011,
UnknownProtocol = 4_012,
Disconnected = 4_014,
VoiceServerCrashed = 4_015,
UnknownEncryptionMode = 4_016
}

export type PlayerUpdatePayload = IPlayerUpdatePayload & { guildId: string };

export type FilterOptions = {
volume?: number;
Expand Down Expand Up @@ -588,7 +598,7 @@ export class Player extends EventEmitter {
*
* @internal
*/
public onPlayerUpdate(data: { state: { position: number; ping: number; connected: boolean } }): void {
public onPlayerUpdate(data: PlayerUpdatePayload): void {
if (this._prepareMove) return undefined;

const { position, ping, connected } = data.state;
Expand All @@ -608,37 +618,44 @@ export class Player extends EventEmitter {
* @param data JSON data from Lavalink.
* @internal
*/
public onPlayerEvent(data: { type: string; track: Track }): void {
public onPlayerEvent(
data:
| TrackEndEventPayload
| TrackExceptionEventPayload
| TrackStartEventPayload
| TrackStuckEventPayload
| WebSocketClosedEventPayload
): void {
if (this._prepareMove) return undefined;

switch (data.type) {
case "TrackStartEvent":
case WebSocketType.TrackStartEvent:
this.trackIdentifier = data.track.info.identifier;
this._encodedTrack = data.track.encoded;

this.emit("start", data);

break;
case "TrackEndEvent":
case WebSocketType.TrackEndEvent:
this.emit("end", data);

break;
case "TrackStuckEvent":
case WebSocketType.TrackStuckEvent:
this.emit("stuck", data);

break;
case "TrackExceptionEvent":
case WebSocketType.TrackExceptionEvent:
this.emit("exception", data);

break;
case "WebSocketClosedEvent":
case WebSocketType.WebSocketClosedEvent:
this.emit("closed", data);

break;
default:
this.node.manager.emit(
"debug",
`[PLAYER => ${this.node.name}] Unknown player message, type: ${data.type}, guild: ${this.guildId}.`
`[PLAYER => ${this.node.name}] Unknown player message, type: ${data as unknown as string}, guild: ${this.guildId}.`
);
}

Expand All @@ -649,11 +666,11 @@ export class Player extends EventEmitter {
// @ts-expect-error ignore this ts(2300)
// eslint-disable-next-line typescript/no-redeclare
export declare type Player = {
on: ((event: "closed", listener: (reason: WebSocketClosedEvent) => void) => Player) &
((event: "end", listener: (reason: TrackEndEvent) => void) => Player) &
((event: "exception", listener: (reason: TrackExceptionEvent) => void) => Player) &
on: ((event: "closed", listener: (reason: WebSocketClosedEventPayload) => void) => Player) &
((event: "end", listener: (reason: TrackEndEventPayload) => void) => Player) &
((event: "exception", listener: (reason: TrackExceptionEventPayload) => void) => Player) &
((event: "resumed", listener: (player: Player) => void) => Player) &
((event: "start", listener: (data: TrackStartEvent) => void) => Player) &
((event: "stuck", listener: (data: TrackStuckEvent) => void) => Player) &
((event: "update", listener: (data: PlayerUpdate) => void) => Player);
((event: "start", listener: (data: TrackStartEventPayload) => void) => Player) &
((event: "stuck", listener: (data: TrackStuckEventPayload) => void) => Player) &
((event: "update", listener: (data: PlayerUpdatePayload) => void) => Player);
};
Loading

0 comments on commit c98dc10

Please sign in to comment.