Skip to content

Commit

Permalink
Minor optimizations and warnings for no user ID
Browse files Browse the repository at this point in the history
  • Loading branch information
PapiOphidian committed Feb 17, 2024
1 parent f9950fd commit 199d50f
Show file tree
Hide file tree
Showing 10 changed files with 274 additions and 233 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright 2019-2023 Jacz
Copyright 2019-2024 Jacz

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
16 changes: 8 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lavacord",
"version": "2.1.2-v4",
"version": "2.1.3-v4",
"description": "A simple by design lavalink wrapper made for any discord library.",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand Down Expand Up @@ -39,22 +39,22 @@
"ws": "^8.15.0"
},
"devDependencies": {
"@types/node": "^20.10.4",
"@types/node": "^20.11.19",
"@types/ws": "^8.5.10",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
"eslint": "^8.55.0",
"@typescript-eslint/eslint-plugin": "^7.0.1",
"@typescript-eslint/parser": "^7.0.1",
"eslint": "^8.56.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.1.1",
"typedoc": "^0.25.4",
"typedoc": "^0.25.8",
"typescript": "^5.3.3"
},
"optionalDependencies": {
"discord.js": "14.x",
"eris": "0.17.x",
"detritus-client": "0.16.x",
"cloudstorm": "0.9.x",
"oceanic.js": "1.8.1"
"cloudstorm": "0.10.x",
"oceanic.js": "1.9.0"
},
"files": [
"dist",
Expand Down
22 changes: 14 additions & 8 deletions src/cloudstorm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,20 @@ export class Manager extends BaseManager {
}

client.on("event", packet => {
if (packet.t === "VOICE_SERVER_UPDATE") {
this.voiceServerUpdate(packet.d as VoiceServerUpdate);
} else if (packet.t === "VOICE_STATE_UPDATE") {
this.voiceStateUpdate(packet.d as VoiceStateUpdate);
} else if (packet.t === "GUILD_CREATE") {
for (const state of packet.d.voice_states ?? []) {
this.voiceStateUpdate({ ...state, guild_id: (packet.d as unknown as { id: string; }).id } as VoiceStateUpdate);
}
switch (packet.t) {
case "VOICE_SERVER_UPDATE":
this.voiceServerUpdate(packet.d as VoiceServerUpdate);
break;

case "VOICE_STATE_UPDATE":
this.voiceStateUpdate(packet.d as VoiceStateUpdate);
break;

case "GUILD_CREATE":
for (const state of packet.d.voice_states ?? []) this.voiceStateUpdate({ ...state, guild_id: packet.d.id } as VoiceStateUpdate);
break;

default: break;
}
});
}
Expand Down
18 changes: 15 additions & 3 deletions src/detritus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,21 @@ export class Manager extends BaseManager {
}

client.on("raw", packet => {
if (packet.t === "VOICE_SERVER_UPDATE") this.voiceServerUpdate(packet.d);
else if (packet.t === "VOICE_STATE_UPDATE") this.voiceStateUpdate(packet.d);
else if (packet.t === "GUILD_CREATE") for (const state of packet.d.voice_states ?? []) this.voiceStateUpdate({ ...state, guild_id: packet.d.id });
switch (packet.t) {
case "VOICE_SERVER_UPDATE":
this.voiceServerUpdate(packet.d);
break;

case "VOICE_STATE_UPDATE":
this.voiceStateUpdate(packet.d);
break;

case "GUILD_CREATE":
for (const state of packet.d.voice_states ?? []) this.voiceStateUpdate({ ...state, guild_id: packet.d.id });
break;

default: break;
}
});
}
}
18 changes: 15 additions & 3 deletions src/eris.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,21 @@ export class Manager extends BaseManager {
}

client.on("rawWS", (packet: DiscordPacket) => {
if (packet.t === "VOICE_SERVER_UPDATE") this.voiceServerUpdate(packet.d);
else if (packet.t === "VOICE_STATE_UPDATE") this.voiceStateUpdate(packet.d);
else if (packet.t === "GUILD_CREATE") for (const state of packet.d.voice_states ?? []) this.voiceStateUpdate({ ...state, guild_id: packet.d.id });
switch (packet.t) {
case "VOICE_SERVER_UPDATE":
this.voiceServerUpdate(packet.d);
break;

case "VOICE_STATE_UPDATE":
this.voiceStateUpdate(packet.d);
break;

case "GUILD_CREATE":
for (const state of packet.d.voice_states ?? []) this.voiceStateUpdate({ ...state, guild_id: packet.d.id });
break;

default: break;
}
});
}
}
51 changes: 29 additions & 22 deletions src/lib/LavalinkNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export class LavalinkNode {
* Connects the node to Lavalink
*/
public async connect(): Promise<WebSocket> {
this.ws = await new Promise<WebSocket>((resolve, reject) => {
return new Promise<WebSocket>((resolve, reject) => {
if (this.connected) this.ws!.close();

return Rest.version(this)
Expand All @@ -140,25 +140,22 @@ export class LavalinkNode {
};

const onOpen = (): void => {
this.ws = ws;
this.onOpen();
ws.removeListener("open", onOpen);
ws.removeListener("error", onEvent);
ws.removeListener("close", onEvent);
ws.removeListener("open", onOpen)
.removeListener("error", onEvent)
.removeListener("close", onEvent)
.on("error", error => this.onError(error))
.on("close", (code, reason) => this.onClose(code, reason));
resolve(ws);
};

ws
.on("message", data => this.onMessage(data))
.once("open", onOpen)
.once("error", onEvent)
.once("close", onEvent);
}).catch(reject);
});

this.ws!
.on("message", data => this.onMessage(data))
.on("error", error => this.onError(error))
.on("close", (code, reason) => this.onClose(code, reason));
return this.ws!;
}

/**
Expand Down Expand Up @@ -202,17 +199,27 @@ export class LavalinkNode {

const msg: WebsocketMessage = JSON.parse(str);

if (msg.op === "ready") {
if (msg.sessionId) this.sessionId = msg.sessionId;
if (!this._sessionUpdated) {
this._sessionUpdated = true;
Rest.updateSession(this).catch(e => this.manager.emit("error", e, this));
}
} else if (msg.op && msg.op === "stats") {
this.stats = { ...msg };
delete (this.stats as any).op;
} else if ((msg.op === "event" || msg.op === "playerUpdate") && this.manager.players.has(msg.guildId)) {
this.manager.players.get(msg.guildId)!.emit(msg.op, msg as any);
switch (msg.op) {
case "ready":
if (msg.sessionId) this.sessionId = msg.sessionId;
if (!this._sessionUpdated) {
this._sessionUpdated = true;
Rest.updateSession(this).catch(e => this.manager.emit("error", e, this));
}
break;

case "stats":
this.stats = { ...msg };
delete (this.stats as any).op;
break;

case "event":
case "playerUpdate":
if (!this.manager.players.has(msg.guildId)) break;
this.manager.players.get(msg.guildId)!.emit(msg.op, msg as any);
break;

default: break;
}

this.manager.emit("raw", msg, this);
Expand Down
16 changes: 11 additions & 5 deletions src/lib/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,14 @@ export class Manager extends EventEmitter {
/**
* Connects all the {@link LavalinkNode} to the respective Lavalink instance
*/
public connect(): Promise<Array<WebSocket | boolean>> {
return Promise.all([...this.nodes.values()].map(node => node.connect()));
public connect(): Promise<Array<WebSocket>> {
if (!this.user) {
console.warn("Lavacord Manager.connect was called without the client user ID being set.\
You should construct your Manager when your client becomes ready as that's where you/your Discord lib receives the current user info.\
Alternatively, you can get your client's user ID (which is all that lavacord needs) by doing\
Buffer.from(token.split(\".\")[0], \"base64\").toString(\"utf8\") unless your token was generated a REALLY long time ago.");
}
return Promise.all(Array.from(this.nodes.values()).map(node => node.connect()));
}

/**
Expand All @@ -73,8 +79,8 @@ export class Manager extends EventEmitter {
*/
public disconnect(): Promise<Array<boolean>> {
const promises = [];
for (const id of [...this.players.keys()]) promises.push(this.leave(id));
for (const node of [...this.nodes.values()]) node.destroy();
for (const id of Array.from(this.players.keys())) promises.push(this.leave(id));
for (const node of Array.from(this.nodes.values())) node.destroy();
return Promise.all(promises);
}

Expand Down Expand Up @@ -230,7 +236,7 @@ export class Manager extends EventEmitter {
* Gets all connected nodes, sorts them by cou load of the node
*/
public get idealNodes(): Array<LavalinkNode> {
return [...this.nodes.values()]
return Array.from(this.nodes.values())
.filter(node => node.connected)
.sort((a, b) => {
const aload = a.stats.cpu ? a.stats.cpu.systemLoad / a.stats.cpu.cores * 100 : 0;
Expand Down
7 changes: 2 additions & 5 deletions src/lib/Rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ import type { LavalinkNode } from "./LavalinkNode";
import type { TrackLoadingResult, DecodeTrackResult, DecodeTracksResult, GetLavalinkVersionResult, UpdateSessionResult, UpdateSessionData, ErrorResponse, UpdatePlayerData, UpdatePlayerResult, DestroyPlayerResult } from "lavalink-types/v4";

export class RestError extends Error {
public json: ErrorResponse;

constructor(data: ErrorResponse) {
super(data.message);
this.json = data;
constructor(public json: ErrorResponse) {
super(json.message);
}
}

Expand Down
25 changes: 16 additions & 9 deletions src/oceanic.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Manager as BaseManager } from "./lib/Manager";
import type { ManagerOptions, LavalinkNodeOptions, VoiceServerUpdate, VoiceStateUpdate } from "./lib/Types";
import type { Client, RawVoiceState } from "oceanic.js";
import type { Client } from "oceanic.js";

export * from "./index";

Expand All @@ -23,14 +23,21 @@ export class Manager extends BaseManager {
}

client.on("packet", packet => {
if (packet.t === "VOICE_SERVER_UPDATE") {
this.voiceServerUpdate(packet.d as VoiceServerUpdate);
} else if (packet.t === "VOICE_STATE_UPDATE") {
this.voiceStateUpdate(packet.d as VoiceStateUpdate);
} else if (packet.t === "GUILD_CREATE") {
for (const state of (packet.d as { voice_states?: Array<RawVoiceState>; }).voice_states ?? []) {
this.voiceStateUpdate({ ...state, guild_id: packet.d.id } as VoiceStateUpdate);
}
switch (packet.t) {
case "VOICE_SERVER_UPDATE":
this.voiceServerUpdate(packet.d as VoiceServerUpdate);
break;

case "VOICE_STATE_UPDATE":
this.voiceStateUpdate(packet.d as VoiceStateUpdate);
break;

case "GUILD_CREATE":
if (packet.d.unavailable) break;
for (const state of packet.d.voice_states ?? []) this.voiceStateUpdate({ ...state, guild_id: packet.d.id } as VoiceStateUpdate);
break;

default: break;
}
});
}
Expand Down
Loading

0 comments on commit 199d50f

Please sign in to comment.