From 75446db21b0e201d13de09d1a3ad8178cb44fe49 Mon Sep 17 00:00:00 2001 From: 1Lucas1apk Date: Fri, 23 Feb 2024 10:16:12 -0400 Subject: [PATCH 01/16] reoganize dirty functions in the code --- .../database-960185850346471505.json | 5 + dist/src/@Entities/MoonlinkNode.js | 5 +- src/@Entities/MoonlinkNode.ts | 217 +++++------------- testBot/index.js | 6 +- 4 files changed, 66 insertions(+), 167 deletions(-) create mode 100644 dist/src/@Datastore/database-960185850346471505.json diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json new file mode 100644 index 00000000..2c74db69 --- /dev/null +++ b/dist/src/@Datastore/database-960185850346471505.json @@ -0,0 +1,5 @@ +{ + "sessionId": { + "LAVALINK": "JbRiEOHpl2LbbIQB" + } +} \ No newline at end of file diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index 0767cd49..13a154cb 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -105,9 +105,8 @@ class MoonlinkNode { }; if (this.resume) headers["Session-Id"] = - this.db.get(`sessionId.${this.identifier ?? this.host}`) ?? + this.db.get(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`) ?? null; - console.log(headers, this.db.get(`sessionId.${this.identifier ?? this.host.replace(/\./g, '-')}`)); this.socket = new MoonlinkWebSocket_1.MoonlinkWebSocket(`ws${this.secure ? "s" : ""}://${this.address}/v4/websocket`, { headers }); this.socket.on("open", this.open.bind(this)); this.socket.on("close", this.close.bind(this)); @@ -200,7 +199,7 @@ class MoonlinkNode { case "ready": this.sessionId = payload.sessionId; this.resume - ? this.db.set(`sessionId.${this.identifier ?? this.host.replace(/\./g, '-')}`, this.sessionId) + ? this.db.set(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`, this.sessionId) : null; this.resumed = payload.resumed; this._manager.nodes.map.set("sessionId", payload.sessionId); diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index 76d42a53..f4530345 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -54,13 +54,7 @@ export class MoonlinkNode { this.host = node.host; this.identifier = node.identifier || null; this.password = node.password ? node.password : "youshallnotpass"; - this.port = node.port - ? node.port - : node.secure - ? node.secure == true - ? 443 - : 80 - : null; + this.port = node.port ?? node.secure == true ? 443 : 80; this.secure = node.secure || false; this.regions = node.regions; this.http = `http${node.secure ? "s" : ""}://${this.address}/v4/`; @@ -108,14 +102,14 @@ export class MoonlinkNode { public check(node: INode): void | never { if (typeof node.host !== "string" && typeof node.host !== "undefined") throw new Error( - '[ @Moonlink/Node ]: "host" option is not configured correctly' + '@Moonlink(Nodes) - "host" option is not configured correctly' ); if ( typeof node.password !== "string" && typeof node.password !== "undefined" ) throw new Error( - '[ @Moonlink/Node ]: the option "password" is not set correctly' + '@Moonlink(Nodes) - the option "password" is not set correctly' ); if ( (node.port && typeof node.port !== "number") || @@ -123,14 +117,14 @@ export class MoonlinkNode { node.port < 0 ) throw new Error( - '[ @Moonlink/Node ]: the "port" option is not set correctly' + '@Moonlink(Nodes) - the "port" option is not set correctly' ); if ( typeof node.retryAmount !== "undefined" && typeof node.retryAmount !== "number" ) throw new Error( - '[ @Moonlink/Node ]: the "retryAmount" option is not set correctly' + '@Moonlink(Nodes) - the "retryAmount" option is not set correctly' ); if ( @@ -138,7 +132,7 @@ export class MoonlinkNode { typeof node.retryDelay !== "number" ) throw new Error( - '[ @Moonlink/Node ]: the "retryDelay" option is not set correctly' + '@Moonlink(Nodes) - the "retryDelay" option is not set correctly' ); } @@ -170,10 +164,12 @@ export class MoonlinkNode { }; if (this.resume) headers["Session-Id"] = - this.db.get(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`) ?? - null; - - + this.db.get( + `sessionId.${ + this.identifier ?? this.host.replace(/\./g, "-") + }` + ) ?? null; + this.socket = new MoonlinkWebSocket( `ws${this.secure ? "s" : ""}://${this.address}/v4/websocket`, { headers } @@ -188,60 +184,25 @@ export class MoonlinkNode { this._manager.emit( "debug", `@Moonlink(Node) - The Node ${ - this.identifier ? this.identifier : this.host + this.identifier ?? this.host } has been connected successfully` ); this._manager.emit("nodeCreate", this); this.state = State.CONNECTED; } - private async movePlayersToNextNode(): Promise { - if (!this._manager.options.movePlayersToNextNode) return; - const state = this.state; - this.state = State.MOVING; - try { - let obj = this._manager.players.all || []; - const players = Object.keys(obj); - for (const player of players) { - if (obj[player].node == this) { - let nextNode = - this._manager.nodes.sortByUsage("players")[0]; - let playerClass = this._manager.players.get( - obj[player].guildId - ); - this._manager.emit( - "debug", - `@Moonlink(Node) - Moving player ${ - obj[player].guildId - } to ${ - nextNode.identifier - ? nextNode.identifier - : nextNode.host - }` - ); - playerClass.node = nextNode; - await playerClass.restart(); - } - } - this.state = state; - } catch (err) { - throw new Error( - "@Moonlink(Node) - not to other connected lavalinks " + err - ); - } - } + private reconnect(): void { if (this.reconnectAttempts >= this.retryAmount) { this._manager.emit( "debug", `@Moonlink(Node) - Node ${ - this.identifier ? this.identifier : this.host + this.identifier ?? this.host } was destroyed due to inactivity, attempts to reconnect were failed` ); this._manager.emit("nodeDestroy", this); this.socket.close(1000, "destroy"); this.socket.removeAllListeners(); - this.movePlayersToNextNode(); } else { this.reconnectTimeout = setTimeout(() => { this.socket.removeAllListeners(); @@ -251,7 +212,7 @@ export class MoonlinkNode { this.connect(); this._manager.emit( "debug", - `@Moonlink(Node) - we are trying to reconnect node ${ + `@Moonlink(Node) - We are trying to reconnect node ${ this.identifier ?? this.host }, attempted number ${this.reconnectAttempts} ` @@ -265,25 +226,10 @@ export class MoonlinkNode { this._manager.emit( "debug", `@Moonlink(Node) - The node connection ${ - this.identifier ? this.identifier : this.host + this.identifier ?? this.host } has been closed` ); this._manager.emit("nodeClose", this, code, reason); - if ( - this.state !== State.DISCONNECTED || - this.state !== State.RECONNECTING - ) { - let obj = this._manager.players.all || []; - if (obj.length !== 0) { - const players = Object.keys(obj); - for (const player of players) { - if (obj[player].node == this) { - this._manager.players.get(obj[player].guildId).playing = - false; - } - } - } - } this.state = State.DISCONNECTED; } protected async message(data: Buffer | string): Promise { @@ -306,7 +252,6 @@ export class MoonlinkNode { ) : null; this.resumed = payload.resumed; - this._manager.nodes.map.set("sessionId", payload.sessionId); this.rest.setSessionId(this.sessionId); if (!this._manager.initiated && !this.resumed) { this.db.delete("queue"); @@ -327,55 +272,12 @@ export class MoonlinkNode { }); this._manager.emit( "debug", - `[ @Moonlink/Node ]: Resuming configured on Lavalink` + `@Moonlink(Nodes) - Resuming configured` ); } this.version = await this.rest.getVersion(); this.info = await this.rest.getInfo(); - if (this._manager.options.autoResume) { - this.state = State.AUTORESUMING; - let obj = this._manager.players.all || []; - const players = Object.keys(obj); - for (const player of players) { - if (obj[player].node == this) { - await this._manager.players.attemptConnection( - obj[player].guildId - ); - this._manager.players - .get(obj[player].guildId) - .restart(); - } - } - } - if (this.resumed) { - this.state = State.RESUMING; - let players: any = await this.rest.get( - `sessions/${this.sessionId}/players` - ); - for (const player of players) { - let previousInfosPlayer: PreviousInfosPlayer = - this.db.get( - `players.${player.guildId}` - ) || {}; - let playerClass = this._manager.players.create({ - guildId: player.guildId, - voiceChannel: previousInfosPlayer.voiceChannel, - textChannel: previousInfosPlayer.textChannel, - node: this.host - }); - playerClass.connect({ - setDeaf: true, - setMute: false - }); - playerClass.playing = true; - playerClass.connected = true; - let track = new (Structure.get("MoonlinkTrack"))( - player.track - ); - playerClass.current = track; - } - } this.state = State.READY; break; case "stats": @@ -385,14 +287,9 @@ export class MoonlinkNode { case "playerUpdate": let player = this._manager.players.get(payload.guildId); player.ping = payload.state.ping; - if (player.current instanceof MoonlinkTrack) { - player.current - .setPosition(payload.state.position) - .setTime(payload.state.time); - } else if (player.current) { - player.current.position = payload.state.position; - player.current.time = payload.state.time; - } + player.current.position = payload.state.position; + player.current.time = payload.state.time; + break; case "event": this.handleEvent(payload); @@ -402,7 +299,7 @@ export class MoonlinkNode { "nodeError", this, new Error( - `[ @Moonlink/Nodes ]: Unexpected op "${payload.op}" with data: ${payload}` + `@Moonlink(Nodes) - Unexpected op "${payload.op}" with data: ${payload}` ) ); } @@ -412,77 +309,74 @@ export class MoonlinkNode { this._manager.emit("nodeError", this, error); this._manager.emit( "debug", - "[ @Moonlink/Nodes ]: An error occurred in one of the lavalink(s) server connection(s): " + + "@Moonlink(Nodes) - An error occurred in one of the lavalink(s) server connection(s): " + error ); } protected async handleEvent(payload: any): Promise { if (!payload) return; if (!payload.guildId) return; - if (!this._manager.players.has(payload.guildId)) return; let player: MoonlinkPlayer = this._manager.players.get(payload.guildId); + if (!player) return; + switch (payload.type) { case "TrackStartEvent": { - let current = player.current; - if (!current) return; + if (player.current) { + player.current = new MoonlinkTrack( + await this.rest.decodeTrack(payload.track) + ); + } player.playing = true; player.paused = false; - this._manager.emit("trackStart", player, current); + this._manager.emit("trackStart", player, player.current); break; } case "TrackEndEvent": { - let track = player.current; - let queue: string[] = player.queue.all; - player.playing = false; - if (this._manager.options.previousTracksInArray) (player.previous as MoonlinkTrack[]).push( track as MoonlinkTrack ); - else player.previous = track; + else player.previous = player.current; + player.playing = false; - if (["loadFailed", "cleanup"].includes(payload.reason)) { - if (!queue) { - player.queue.clear(); - return this._manager.emit("queueEnd", player, track); - } - player.play(); - return; - } if (payload.reason === "replaced") { - this._manager.emit("trackEnd", player, track, payload); + this._manager.emit( + "trackEnd", + player, + player.current, + payload + ); return; } - if (track && player.loop) { + if (player.current && [1, 2].includes(player.loop)) { if (player.loop == 1) { await this.rest.update({ guildId: payload.guildId, - data: { track: { encoded: track.encoded } } + data: { track: { encoded: player.current.encoded } } }); return; } if (player.loop == 2) { player.queue.add(player.current as MoonlinkTrack); - if (!queue || queue.length === 0) + if (!player.queue.all || !player.queue.size) return this._manager.emit( "trackEnd", player, - track, + player.current, payload ); player.play(); return; - } else { - this._manager.emit("trackEnd", player, track); - this._manager.emit( - "debug", - "@Manager(Nodes) - invalid loop value will be ignored!" - ); } } if (player.queue.size) { - this._manager.emit("trackEnd", player, track); + this._manager.emit( + "trackEnd", + player, + player.current, + payload + ); player.play(); return; } @@ -491,8 +385,9 @@ export class MoonlinkNode { player.autoPlay === true ) { if (payload.reason == "stopped") return; - let uri = `https://www.youtube.com/watch?v=${track.identifier}&list=RD${track.identifier}`; - let req: SearchResult = await this._manager.search(uri); + let req: SearchResult = await this._manager.search( + `https://www.youtube.com/watch?v=${player.curren.identifier}&list=RD${player.current.identifier}` + ); if ( !req || !req.tracks || @@ -512,16 +407,15 @@ export class MoonlinkNode { /* Logic created by PiscesXD */ if (player.autoLeave) { player.destroy(); - this._manager.emit("autoLeaved", player, track); + this._manager.emit("autoLeaved", player, player.current); } if (!player.queue.size) { this._manager.emit( "debug", - "[ @Moonlink/Nodes ]: The queue is empty" + "@Moonlink(Nodes) - The queue is empty" ); this._manager.emit("queueEnd", player); player.current = null; - player.queue.clear(); } break; } @@ -538,11 +432,12 @@ export class MoonlinkNode { } case "WebSocketClosedEvent": { this._manager.emit("socketClosed", player, payload); + //migrar pro outro node se tiver players break; } default: { const error = new Error( - `[ @Moonlink/Nodes ] unknown event '${payload.type}'.` + `@Moonlink(Nodes) - unknown event '${payload.type}'.` ); this._manager.emit("nodeError", this, error); } diff --git a/testBot/index.js b/testBot/index.js index eec0d060..16942d17 100644 --- a/testBot/index.js +++ b/testBot/index.js @@ -46,17 +46,17 @@ for (const folder of commandFolders) { } client.moon = new MoonlinkManager( - [{ + [/*{ host: "lavalink.jirayu.pw", port: 2333, password: "youshallnotpass", secure: false - }/*, { + }*/ { host: "localhost", port: 2333, secure: false, identifier: "LAVALINK" - }, /*{ + } /*{ host: "65.108.101.89", port: 17958, secure: false, From 70a3b999b4de26d42efce9400bd12508d0993c04 Mon Sep 17 00:00:00 2001 From: 1Lucas1apk Date: Sat, 24 Feb 2024 12:35:59 -0400 Subject: [PATCH 02/16] AutoResume, resume, movePlayers system redone --- .../database-960185850346471505.json | 2 +- dist/src/@Entities/MoonlinkNode.d.ts | 21 +- dist/src/@Entities/MoonlinkNode.js | 263 ++++++------------ src/@Entities/MoonlinkNode.ts | 166 ++++++----- 4 files changed, 204 insertions(+), 248 deletions(-) diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json index 2c74db69..7a69e616 100644 --- a/dist/src/@Datastore/database-960185850346471505.json +++ b/dist/src/@Datastore/database-960185850346471505.json @@ -1,5 +1,5 @@ { "sessionId": { - "LAVALINK": "JbRiEOHpl2LbbIQB" + "LAVALINK": "a0BhFPXAGFqbCv4k" } } \ No newline at end of file diff --git a/dist/src/@Entities/MoonlinkNode.d.ts b/dist/src/@Entities/MoonlinkNode.d.ts index 2e301361..8b42f43f 100644 --- a/dist/src/@Entities/MoonlinkNode.d.ts +++ b/dist/src/@Entities/MoonlinkNode.d.ts @@ -1,7 +1,7 @@ /// import { INode, INodeStats } from "../@Typings"; import { MoonlinkWebSocket } from "../@Services/MoonlinkWebSocket"; -import { MoonlinkRestFul, MoonlinkDatabase } from "../../index"; +import { MoonlinkRestFul } from "../../index"; export declare class MoonlinkNode { private _manager; private reconnectTimeout?; @@ -12,32 +12,33 @@ export declare class MoonlinkNode { host: string; identifier?: string; password: string; - port: number | null; + port?: number; secure: boolean; - regions: string[] | null; + regions?: string[]; http: string; rest: MoonlinkRestFul; + info?: Record; + version?: string; resume?: boolean; resumed?: boolean; + autoResume?: boolean; resumeTimeout?: number; sessionId: string; socket: MoonlinkWebSocket | null; - version: any; state: string; - stats: INodeStats; - info: any; + stats: INodeStats | Record; calls: number; - db: MoonlinkDatabase; constructor(node: INode); get address(): string; - check(node: INode): void | never; + check(node: INode): void; request(endpoint: string, params: any): Promise; connect(): Promise; open(): void; - private movePlayersToNextNode; private reconnect; protected close(code: number, reason: any): void; - protected message(data: Buffer | string): Promise; protected error(error: Error): void; + protected message(data: Buffer | string): Promise; protected handleEvent(payload: any): Promise; + private movePlayers; + private get getAllPlayers(); } diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index 13a154cb..d4690410 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -4,7 +4,7 @@ exports.MoonlinkNode = void 0; const MoonlinkWebSocket_1 = require("../@Services/MoonlinkWebSocket"); const index_1 = require("../../index"); class MoonlinkNode { - _manager; + _manager = index_1.Structure.manager; reconnectTimeout; reconnectAttempts = 1; retryAmount = 6; @@ -18,55 +18,27 @@ class MoonlinkNode { regions; http; rest; + info = {}; + version; resume; resumed; + autoResume = index_1.Structure.manager.options?.autoResume; resumeTimeout = 30000; sessionId; socket; - version = ""; - state = index_1.State.DISCONNECTED; - stats; - info = {}; + state = "DISCONNECTED"; + stats = {}; calls = 0; - db = index_1.Structure.db; constructor(node) { - this._manager = index_1.Structure.manager; this.check(node); this.host = node.host; this.identifier = node.identifier || null; this.password = node.password ? node.password : "youshallnotpass"; - this.port = node.port - ? node.port - : node.secure - ? node.secure == true - ? 443 - : 80 - : null; + this.port = node.port ? node.port : node.secure == true ? 443 : 80; this.secure = node.secure || false; this.regions = node.regions; this.http = `http${node.secure ? "s" : ""}://${this.address}/v4/`; this.resume = this._manager.options?.resume; - this.stats = { - players: 0, - playingPlayers: 0, - uptime: 0, - memory: { - free: 0, - used: 0, - allocated: 0, - reservable: 0 - }, - cpu: { - cores: 0, - systemLoad: 0, - lavalinkLoad: 0 - }, - frameStats: { - sent: 0, - nulled: 0, - deficit: 0 - } - }; this.rest = new (index_1.Structure.get("MoonlinkRestFul"))(this); this.connect(); } @@ -75,29 +47,29 @@ class MoonlinkNode { } check(node) { if (typeof node.host !== "string" && typeof node.host !== "undefined") - throw new Error('[ @Moonlink/Node ]: "host" option is not configured correctly'); + throw new Error('@Moonlink(Nodes) - "host" option is not configured correctly'); if (typeof node.password !== "string" && typeof node.password !== "undefined") - throw new Error('[ @Moonlink/Node ]: the option "password" is not set correctly'); + throw new Error('@Moonlink(Nodes) - the option "password" is not set correctly'); if ((node.port && typeof node.port !== "number") || node.port > 65535 || node.port < 0) - throw new Error('[ @Moonlink/Node ]: the "port" option is not set correctly'); + throw new Error('@Moonlink(Nodes) - the "port" option is not set correctly'); if (typeof node.retryAmount !== "undefined" && typeof node.retryAmount !== "number") - throw new Error('[ @Moonlink/Node ]: the "retryAmount" option is not set correctly'); + throw new Error('@Moonlink(Nodes) - the "retryAmount" option is not set correctly'); if (typeof node.retryDelay !== "undefined" && typeof node.retryDelay !== "number") - throw new Error('[ @Moonlink/Node ]: the "retryDelay" option is not set correctly'); + throw new Error('@Moonlink(Nodes) - the "retryDelay" option is not set correctly'); } request(endpoint, params) { this.calls++; return this.rest.get(`${endpoint}?${params}`); } async connect() { - if (this.state == index_1.State.CONNECTED || this.state == index_1.State.READY) + if (this.state == "CONNECTED" || this.state == "READY") return; - this.state = index_1.State.CONNECTING; + this.state = "CONNECTING"; let headers = { Authorization: this.password, "User-Id": this._manager.options.clientId, @@ -105,8 +77,7 @@ class MoonlinkNode { }; if (this.resume) headers["Session-Id"] = - this.db.get(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`) ?? - null; + index_1.Structure.db.get(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`) ?? null; this.socket = new MoonlinkWebSocket_1.MoonlinkWebSocket(`ws${this.secure ? "s" : ""}://${this.address}/v4/websocket`, { headers }); this.socket.on("open", this.open.bind(this)); this.socket.on("close", this.close.bind(this)); @@ -116,52 +87,28 @@ class MoonlinkNode { open() { if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout); - this._manager.emit("debug", `@Moonlink(Node) - The Node ${this.identifier ? this.identifier : this.host} has been connected successfully`); + this._manager.emit("debug", `@Moonlink(Node) - The Node ${this.identifier ?? this.host} has been connected successfully`); this._manager.emit("nodeCreate", this); - this.state = index_1.State.CONNECTED; - } - async movePlayersToNextNode() { - if (!this._manager.options.movePlayersToNextNode) - return; - const state = this.state; - this.state = index_1.State.MOVING; - try { - let obj = this._manager.players.all || []; - const players = Object.keys(obj); - for (const player of players) { - if (obj[player].node == this) { - let nextNode = this._manager.nodes.sortByUsage("players")[0]; - let playerClass = this._manager.players.get(obj[player].guildId); - this._manager.emit("debug", `@Moonlink(Node) - Moving player ${obj[player].guildId} to ${nextNode.identifier - ? nextNode.identifier - : nextNode.host}`); - playerClass.node = nextNode; - await playerClass.restart(); - } - } - this.state = state; - } - catch (err) { - throw new Error("@Moonlink(Node) - not to other connected lavalinks " + err); - } + this.state = "CONNECTED"; } reconnect() { if (this.reconnectAttempts >= this.retryAmount) { - this._manager.emit("debug", `@Moonlink(Node) - Node ${this.identifier ? this.identifier : this.host} was destroyed due to inactivity, attempts to reconnect were failed`); + this._manager.emit("debug", `@Moonlink(Node) - Node ${this.identifier ?? this.host} was destroyed due to inactivity, attempts to reconnect were failed`); this._manager.emit("nodeDestroy", this); this.socket.close(1000, "destroy"); this.socket.removeAllListeners(); - this.movePlayersToNextNode(); } else { this.reconnectTimeout = setTimeout(() => { this.socket.removeAllListeners(); this.socket = null; - this.state = index_1.State.RECONNECTING; + this.state = "RECONNECTING"; this._manager.emit("nodeReconnect", this); this.connect(); - this._manager.emit("debug", `@Moonlink(Node) - we are trying to reconnect node ${this.identifier ?? this.host}, attempted number ${this.reconnectAttempts} + this._manager.emit("debug", `@Moonlink(Node) - We are trying to reconnect node ${this.identifier ?? this.host}, attempted number ${this.reconnectAttempts} `); + if (this.getAllPlayers.length) + this.movePlayers(); this.reconnectAttempts++; }, this.retryDelay); } @@ -169,22 +116,19 @@ class MoonlinkNode { close(code, reason) { if (code !== 1000 || reason !== "destroy") this.reconnect(); - this._manager.emit("debug", `@Moonlink(Node) - The node connection ${this.identifier ? this.identifier : this.host} has been closed`); + this._manager.emit("debug", `@Moonlink(Node) - The node connection ${this.identifier ?? this.host} has been closed`); this._manager.emit("nodeClose", this, code, reason); - if (this.state !== index_1.State.DISCONNECTED || - this.state !== index_1.State.RECONNECTING) { - let obj = this._manager.players.all || []; - if (obj.length !== 0) { - const players = Object.keys(obj); - for (const player of players) { - if (obj[player].node == this) { - this._manager.players.get(obj[player].guildId).playing = - false; - } - } - } - } - this.state = index_1.State.DISCONNECTED; + this.getAllPlayers.forEach(player => { + player.playing = false; + }); + this.state = "DISCONNECTED"; + } + error(error) { + if (!error) + return; + this._manager.emit("nodeError", this, error); + this._manager.emit("debug", `@Moonlink(Nodes) - The ${this.identifier ?? this.host} an error has occurred: + ${error}`); } async message(data) { if (Array.isArray(data)) @@ -199,16 +143,15 @@ class MoonlinkNode { case "ready": this.sessionId = payload.sessionId; this.resume - ? this.db.set(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`, this.sessionId) + ? index_1.Structure.db.set(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`, this.sessionId) : null; this.resumed = payload.resumed; - this._manager.nodes.map.set("sessionId", payload.sessionId); this.rest.setSessionId(this.sessionId); if (!this._manager.initiated && !this.resumed) { - this.db.delete("queue"); - this.db.delete("players"); + index_1.Structure.db.delete("queue"); + index_1.Structure.db.delete("players"); } - this._manager.emit("debug", `@Moonlink(Node) - ${this.resumed ? ` session was resumed, ` : ``} session is currently ${this.sessionId}`); + this._manager.emit("debug", `@Moonlink(Node) - ${this.resumed ? ` session was resumed,` : ``} session is currently ${this.sessionId}`); if (this.resume) { this.rest.patch(`sessions/${this.sessionId}`, { data: { @@ -216,45 +159,33 @@ class MoonlinkNode { timeout: this.resumeTimeout } }); - this._manager.emit("debug", `[ @Moonlink/Node ]: Resuming configured on Lavalink`); + this._manager.emit("debug", `@Moonlink(Nodes) - Resuming configured`); } this.version = await this.rest.getVersion(); this.info = await this.rest.getInfo(); - if (this._manager.options.autoResume) { - this.state = index_1.State.AUTORESUMING; - let obj = this._manager.players.all || []; - const players = Object.keys(obj); - for (const player of players) { - if (obj[player].node == this) { - await this._manager.players.attemptConnection(obj[player].guildId); - this._manager.players - .get(obj[player].guildId) - .restart(); - } + if (this.autoResume) { + let resumePlayers = this.getAllPlayers; + for (const resumePlayer of resumePlayers) { + resumePlayer.restart(); } } if (this.resumed) { - this.state = index_1.State.RESUMING; - let players = await this.rest.get(`sessions/${this.sessionId}/players`); - for (const player of players) { - let previousInfosPlayer = this.db.get(`players.${player.guildId}`) || {}; - let playerClass = this._manager.players.create({ - guildId: player.guildId, + const resumedPlayers = await this.rest.get(`sessions/${this.sessionId}/players`); + for (const resumedPlayer of resumedPlayers) { + const previousInfosPlayer = index_1.Structure.db.get(`players.${resumedPlayer.guildId}`) || {}; + const player = this._manager.players.create({ + guildId: resumedPlayer.guildId, voiceChannel: previousInfosPlayer.voiceChannel, textChannel: previousInfosPlayer.textChannel, - node: this.host - }); - playerClass.connect({ - setDeaf: true, - setMute: false + node: this.identifier ?? this.host }); - playerClass.playing = true; - playerClass.connected = true; - let track = new (index_1.Structure.get("MoonlinkTrack"))(player.track); - playerClass.current = track; + player.playing = true; + player.connected = true; + const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); + player.current = track; } } - this.state = index_1.State.READY; + this.state = "READY"; break; case "stats": delete payload.op; @@ -263,90 +194,62 @@ class MoonlinkNode { case "playerUpdate": let player = this._manager.players.get(payload.guildId); player.ping = payload.state.ping; - if (player.current instanceof index_1.MoonlinkTrack) { - player.current - .setPosition(payload.state.position) - .setTime(payload.state.time); - } - else if (player.current) { - player.current.position = payload.state.position; - player.current.time = payload.state.time; - } + player.current.position = payload.state.position; + player.current.time = payload.state.time; break; case "event": this.handleEvent(payload); break; default: - this._manager.emit("nodeError", this, new Error(`[ @Moonlink/Nodes ]: Unexpected op "${payload.op}" with data: ${payload}`)); + this._manager.emit("nodeError", this, new Error(`@Moonlink(Nodes) - Unexpected op "${payload.op}" with data: ${payload}`)); } } - error(error) { - if (!error) - return; - this._manager.emit("nodeError", this, error); - this._manager.emit("debug", "[ @Moonlink/Nodes ]: An error occurred in one of the lavalink(s) server connection(s): " + - error); - } async handleEvent(payload) { if (!payload) return; if (!payload.guildId) return; - if (!this._manager.players.has(payload.guildId)) - return; let player = this._manager.players.get(payload.guildId); + if (!player) + return; switch (payload.type) { case "TrackStartEvent": { - let current = player.current; - if (!current) - return; + if (!player.current) { + player.current = new index_1.MoonlinkTrack((await this.rest.decodeTrack(payload.track))); + } player.playing = true; player.paused = false; - this._manager.emit("trackStart", player, current); + this._manager.emit("trackStart", player, player.current); break; } case "TrackEndEvent": { - let track = player.current; - let queue = player.queue.all; - player.playing = false; if (this._manager.options.previousTracksInArray) - player.previous.push(track); + player.previous.push(player.current); else - player.previous = track; - if (["loadFailed", "cleanup"].includes(payload.reason)) { - if (!queue) { - player.queue.clear(); - return this._manager.emit("queueEnd", player, track); - } - player.play(); - return; - } + player.previous = player.current; + player.playing = false; if (payload.reason === "replaced") { - this._manager.emit("trackEnd", player, track, payload); + this._manager.emit("trackEnd", player, player.current, payload); return; } - if (track && player.loop) { + if (player.current && [1, 2].includes(player.loop)) { if (player.loop == 1) { await this.rest.update({ guildId: payload.guildId, - data: { track: { encoded: track.encoded } } + data: { track: { encoded: player.current.encoded } } }); return; } if (player.loop == 2) { player.queue.add(player.current); - if (!queue || queue.length === 0) - return this._manager.emit("trackEnd", player, track, payload); + if (!player.queue.all || !player.queue.size) + return this._manager.emit("trackEnd", player, player.current, payload); player.play(); return; } - else { - this._manager.emit("trackEnd", player, track); - this._manager.emit("debug", "@Manager(Nodes) - invalid loop value will be ignored!"); - } } if (player.queue.size) { - this._manager.emit("trackEnd", player, track); + this._manager.emit("trackEnd", player, player.current, payload); player.play(); return; } @@ -354,8 +257,7 @@ class MoonlinkNode { player.autoPlay === true) { if (payload.reason == "stopped") return; - let uri = `https://www.youtube.com/watch?v=${track.identifier}&list=RD${track.identifier}`; - let req = await this._manager.search(uri); + let req = await this._manager.search(`https://www.youtube.com/watch?v=${player.current.identifier}&list=RD${player.current.identifier}`); if (!req || !req.tracks || ["loadFailed", "cleanup"].includes(req.loadType)) @@ -367,13 +269,12 @@ class MoonlinkNode { } if (player.autoLeave) { player.destroy(); - this._manager.emit("autoLeaved", player, track); + this._manager.emit("autoLeaved", player, player.current); } if (!player.queue.size) { - this._manager.emit("debug", "[ @Moonlink/Nodes ]: The queue is empty"); + this._manager.emit("debug", "@Moonlink(Nodes) - The queue is empty"); this._manager.emit("queueEnd", player); player.current = null; - player.queue.clear(); } break; } @@ -392,10 +293,22 @@ class MoonlinkNode { break; } default: { - const error = new Error(`[ @Moonlink/Nodes ] unknown event '${payload.type}'.`); + const error = new Error(`@Moonlink(Nodes) - unknown event '${payload.type}'.`); this._manager.emit("nodeError", this, error); } } } + movePlayers() { + this.getAllPlayers.forEach(player => { + let anotherNode = this._manager.nodes.sortByUsage(this._manager.options?.sortNode ?? "players")[0]; + this._manager.emit("debug", `@Moonlink(Node) - Moving player ${player.guildId} to ${anotherNode.identifier ?? anotherNode.host}`); + player.node = anotherNode; + player.restart(); + }); + return true; + } + get getAllPlayers() { + return Object.values(this._manager.players.all).filter(player => player.node === this); + } } exports.MoonlinkNode = MoonlinkNode; diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index f4530345..545e2432 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -4,19 +4,20 @@ import { SearchResult, PreviousInfosPlayer } from "../@Typings"; + import { MoonlinkWebSocket } from "../@Services/MoonlinkWebSocket"; + import { MoonlinkManager, MoonlinkTrack, MoonlinkPlayer, MoonlinkRestFul, MoonlinkDatabase, - Structure, - State + Structure } from "../../index"; export class MoonlinkNode { - private _manager: MoonlinkManager; + private _manager: MoonlinkManager = Structure.manager; private reconnectTimeout?: NodeJS.Timeout; private reconnectAttempts: number = 1; private retryAmount: number = 6; @@ -26,22 +27,22 @@ export class MoonlinkNode { public host: string; public identifier?: string; public password: string; - public port: number | null; + public port?: number; public secure: boolean; - public regions: string[] | null; + public regions?: string[]; public http: string; public rest: MoonlinkRestFul; - public resume?: boolean; + public info?: Record = {}; + public version?: string; + public resume?: boolean = Structure.manager.options?.resume; public resumed?: boolean; + public autoResume?: boolean = Structure.manager.options?.autoResume; public resumeTimeout?: number = 30000; public sessionId: string; public socket: MoonlinkWebSocket | null; - public version: any = ""; - public state: string = State.DISCONNECTED; - public stats: INodeStats; - public info: any = {}; + public state: string = "DISCONNECTED"; + public stats: INodeStats | Record = {}; public calls: number = 0; - public db: MoonlinkDatabase = Structure.db; /** * Initializes a new MoonlinkNode instance with the provided configuration. @@ -49,37 +50,14 @@ export class MoonlinkNode { */ constructor(node: INode) { - this._manager = Structure.manager; this.check(node); this.host = node.host; this.identifier = node.identifier || null; this.password = node.password ? node.password : "youshallnotpass"; - this.port = node.port ?? node.secure == true ? 443 : 80; + this.port = node.port ? node.port : node.secure == true ? 443 : 80; this.secure = node.secure || false; this.regions = node.regions; this.http = `http${node.secure ? "s" : ""}://${this.address}/v4/`; - this.resume = this._manager.options?.resume; - this.stats = { - players: 0, - playingPlayers: 0, - uptime: 0, - memory: { - free: 0, - used: 0, - allocated: 0, - reservable: 0 - }, - cpu: { - cores: 0, - systemLoad: 0, - lavalinkLoad: 0 - }, - frameStats: { - sent: 0, - nulled: 0, - deficit: 0 - } - }; this.rest = new (Structure.get("MoonlinkRestFul"))(this); this.connect(); @@ -99,7 +77,7 @@ export class MoonlinkNode { * @param node - The configuration object for the Lavalink node. */ - public check(node: INode): void | never { + public check(node: INode): void { if (typeof node.host !== "string" && typeof node.host !== "undefined") throw new Error( '@Moonlink(Nodes) - "host" option is not configured correctly' @@ -154,8 +132,8 @@ export class MoonlinkNode { */ public async connect(): Promise { - if (this.state == State.CONNECTED || this.state == State.READY) return; - this.state = State.CONNECTING; + if (this.state == "CONNECTED" || this.state == "READY") return; + this.state = "CONNECTING"; let headers = { Authorization: this.password, @@ -164,7 +142,7 @@ export class MoonlinkNode { }; if (this.resume) headers["Session-Id"] = - this.db.get( + Structure.db.get( `sessionId.${ this.identifier ?? this.host.replace(/\./g, "-") }` @@ -188,8 +166,7 @@ export class MoonlinkNode { } has been connected successfully` ); this._manager.emit("nodeCreate", this); - - this.state = State.CONNECTED; + this.state = "CONNECTED"; } private reconnect(): void { @@ -207,7 +184,7 @@ export class MoonlinkNode { this.reconnectTimeout = setTimeout(() => { this.socket.removeAllListeners(); this.socket = null; - this.state = State.RECONNECTING; + this.state = "RECONNECTING"; this._manager.emit("nodeReconnect", this); this.connect(); this._manager.emit( @@ -217,10 +194,12 @@ export class MoonlinkNode { }, attempted number ${this.reconnectAttempts} ` ); + if (this.getAllPlayers.length) this.movePlayers(); this.reconnectAttempts++; }, this.retryDelay); } } + protected close(code: number, reason: any): void { if (code !== 1000 || reason !== "destroy") this.reconnect(); this._manager.emit( @@ -230,8 +209,26 @@ export class MoonlinkNode { } has been closed` ); this._manager.emit("nodeClose", this, code, reason); - this.state = State.DISCONNECTED; + + this.getAllPlayers.forEach(player => { + player.playing = false; + }); + + this.state = "DISCONNECTED"; } + + protected error(error: Error): void { + if (!error) return; + this._manager.emit("nodeError", this, error); + this._manager.emit( + "debug", + `@Moonlink(Nodes) - The ${ + this.identifier ?? this.host + } an error has occurred: + ${error}` + ); + } + protected async message(data: Buffer | string): Promise { if (Array.isArray(data)) data = Buffer.concat(data); else if (data instanceof ArrayBuffer) data = Buffer.from(data); @@ -244,7 +241,7 @@ export class MoonlinkNode { case "ready": this.sessionId = payload.sessionId; this.resume - ? this.db.set( + ? Structure.db.set( `sessionId.${ this.identifier ?? this.host.replace(/\./g, "-") }`, @@ -254,13 +251,13 @@ export class MoonlinkNode { this.resumed = payload.resumed; this.rest.setSessionId(this.sessionId); if (!this._manager.initiated && !this.resumed) { - this.db.delete("queue"); - this.db.delete("players"); + Structure.db.delete("queue"); + Structure.db.delete("players"); } this._manager.emit( "debug", `@Moonlink(Node) - ${ - this.resumed ? ` session was resumed, ` : `` + this.resumed ? ` session was resumed,` : `` } session is currently ${this.sessionId}` ); if (this.resume) { @@ -278,7 +275,37 @@ export class MoonlinkNode { this.version = await this.rest.getVersion(); this.info = await this.rest.getInfo(); - this.state = State.READY; + if (this.autoResume) { + let resumePlayers = this.getAllPlayers; + for (const resumePlayer of resumePlayers) { + resumePlayer.restart(); + } + } + if (this.resumed) { + const resumedPlayers: any[] = await this.rest.get( + `sessions/${this.sessionId}/players` + ); + + for (const resumedPlayer of resumedPlayers) { + const previousInfosPlayer: PreviousInfosPlayer = + Structure.db.get( + `players.${resumedPlayer.guildId}` + ) || {}; + const player = this._manager.players.create({ + guildId: resumedPlayer.guildId, + voiceChannel: previousInfosPlayer.voiceChannel, + textChannel: previousInfosPlayer.textChannel, + node: this.identifier ?? this.host + }); + player.playing = true; + player.connected = true; + const track = new (Structure.get("MoonlinkTrack"))( + resumedPlayer.track + ); + player.current = track; + } + } + this.state = "READY"; break; case "stats": delete payload.op; @@ -304,15 +331,7 @@ export class MoonlinkNode { ); } } - protected error(error: Error): void { - if (!error) return; - this._manager.emit("nodeError", this, error); - this._manager.emit( - "debug", - "@Moonlink(Nodes) - An error occurred in one of the lavalink(s) server connection(s): " + - error - ); - } + protected async handleEvent(payload: any): Promise { if (!payload) return; if (!payload.guildId) return; @@ -321,10 +340,10 @@ export class MoonlinkNode { switch (payload.type) { case "TrackStartEvent": { - if (player.current) { + if (!player.current) { player.current = new MoonlinkTrack( - await this.rest.decodeTrack(payload.track) - ); + (await this.rest.decodeTrack(payload.track)) as any + ) as MoonlinkTrack; } player.playing = true; player.paused = false; @@ -334,7 +353,7 @@ export class MoonlinkNode { case "TrackEndEvent": { if (this._manager.options.previousTracksInArray) (player.previous as MoonlinkTrack[]).push( - track as MoonlinkTrack + player.current as MoonlinkTrack ); else player.previous = player.current; player.playing = false; @@ -386,7 +405,7 @@ export class MoonlinkNode { ) { if (payload.reason == "stopped") return; let req: SearchResult = await this._manager.search( - `https://www.youtube.com/watch?v=${player.curren.identifier}&list=RD${player.current.identifier}` + `https://www.youtube.com/watch?v=${player.current.identifier}&list=RD${player.current.identifier}` ); if ( !req || @@ -443,4 +462,27 @@ export class MoonlinkNode { } } } + + private movePlayers(): boolean { + this.getAllPlayers.forEach(player => { + let anotherNode = this._manager.nodes.sortByUsage( + this._manager.options?.sortNode ?? "players" + )[0]; + this._manager.emit( + "debug", + `@Moonlink(Node) - Moving player ${player.guildId} to ${ + anotherNode.identifier ?? anotherNode.host + }` + ); + player.node = anotherNode; + player.restart(); + }); + return true; + } + + private get getAllPlayers(): MoonlinkPlayer[] { + return Object.values(this._manager.players.all).filter( + player => player.node === this + ); + } } From 404f29fdd4773fe1712fa1640bbb298cb866365f Mon Sep 17 00:00:00 2001 From: 1Lucas1apk Date: Sat, 24 Feb 2024 20:44:31 -0400 Subject: [PATCH 03/16] test --- dist/index.mjs | 1 - .../database-960185850346471505.json | 5 ---- dist/src/@Entities/MoonlinkNode.js | 12 ++++++---- dist/src/@Managers/MoonlinkManager.d.ts | 2 ++ dist/src/@Managers/NodeManager.d.ts | 11 --------- dist/src/@Managers/NodeManager.js | 15 ++---------- dist/src/@Managers/PlayerManager.js | 8 +++---- dist/src/@Utils/MoonlinkDatabase.d.ts | 8 ++++--- dist/src/@Utils/MoonlinkDatabase.js | 4 +++- src/@Entities/MoonlinkNode.ts | 24 ++++++++++++------- src/@Managers/MoonlinkManager.ts | 2 ++ src/@Managers/NodeManager.ts | 15 ++---------- src/@Managers/PlayerManager.ts | 11 ++++----- src/@Utils/MoonlinkDatabase.ts | 18 +++++++++----- testBot/index.js | 12 ++++++---- 15 files changed, 67 insertions(+), 81 deletions(-) delete mode 100644 dist/src/@Datastore/database-960185850346471505.json diff --git a/dist/index.mjs b/dist/index.mjs index a09dddd9..ce350811 100644 --- a/dist/index.mjs +++ b/dist/index.mjs @@ -12,7 +12,6 @@ export const MoonlinkTrack = mod.MoonlinkTrack; export const NodeManager = mod.NodeManager; export const PlayerManager = mod.PlayerManager; export const Plugin = mod.Plugin; -export const State = mod.State; export const Structure = mod.Structure; export const makeRequest = mod.makeRequest; export const version = mod.version; diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json deleted file mode 100644 index 7a69e616..00000000 --- a/dist/src/@Datastore/database-960185850346471505.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "sessionId": { - "LAVALINK": "a0BhFPXAGFqbCv4k" - } -} \ No newline at end of file diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index d4690410..cbd95f27 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -20,7 +20,7 @@ class MoonlinkNode { rest; info = {}; version; - resume; + resume = index_1.Structure.manager.options?.resume; resumed; autoResume = index_1.Structure.manager.options?.autoResume; resumeTimeout = 30000; @@ -38,7 +38,6 @@ class MoonlinkNode { this.secure = node.secure || false; this.regions = node.regions; this.http = `http${node.secure ? "s" : ""}://${this.address}/v4/`; - this.resume = this._manager.options?.resume; this.rest = new (index_1.Structure.get("MoonlinkRestFul"))(this); this.connect(); } @@ -70,14 +69,15 @@ class MoonlinkNode { if (this.state == "CONNECTED" || this.state == "READY") return; this.state = "CONNECTING"; + if (Object.keys(index_1.Structure.db.data).length == 0) + await index_1.Structure.db.fetch(); let headers = { Authorization: this.password, "User-Id": this._manager.options.clientId, "Client-Name": this._manager.options.clientName }; if (this.resume) - headers["Session-Id"] = - index_1.Structure.db.get(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`) ?? null; + headers["Session-Id"] = index_1.Structure.db.get(`sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}`); this.socket = new MoonlinkWebSocket_1.MoonlinkWebSocket(`ws${this.secure ? "s" : ""}://${this.address}/v4/websocket`, { headers }); this.socket.on("open", this.open.bind(this)); this.socket.on("close", this.close.bind(this)); @@ -152,6 +152,7 @@ class MoonlinkNode { index_1.Structure.db.delete("players"); } this._manager.emit("debug", `@Moonlink(Node) - ${this.resumed ? ` session was resumed,` : ``} session is currently ${this.sessionId}`); + this._manager.emit("nodeReady", this, this.sessionId, this.resumed); if (this.resume) { this.rest.patch(`sessions/${this.sessionId}`, { data: { @@ -171,6 +172,7 @@ class MoonlinkNode { } if (this.resumed) { const resumedPlayers = await this.rest.get(`sessions/${this.sessionId}/players`); + console.log(resumedPlayers); for (const resumedPlayer of resumedPlayers) { const previousInfosPlayer = index_1.Structure.db.get(`players.${resumedPlayer.guildId}`) || {}; const player = this._manager.players.create({ @@ -183,7 +185,9 @@ class MoonlinkNode { player.connected = true; const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); player.current = track; + player.restart(); } + this._manager.emit("nodeResumed", this, resumedPlayers); } this.state = "READY"; break; diff --git a/dist/src/@Managers/MoonlinkManager.d.ts b/dist/src/@Managers/MoonlinkManager.d.ts index ff52ef58..d948c261 100644 --- a/dist/src/@Managers/MoonlinkManager.d.ts +++ b/dist/src/@Managers/MoonlinkManager.d.ts @@ -6,7 +6,9 @@ export interface MoonlinkEvents { autoLeaved: (player: MoonlinkPlayer, track?: any) => void; debug: (...args: any) => void; nodeCreate: (node: MoonlinkNode) => void; + nodeReady: (node: MoonlinkNode, sessionId: string, resumed: boolean) => void; nodeDestroy: (node: MoonlinkNode) => void; + nodeResumed: (node: MoonlinkNode, players: MoonlinkEvents[]) => void; nodeReconnect: (node: MoonlinkNode) => void; nodeClose: (node: MoonlinkNode, code: number, reason: any) => void; nodeRaw: (node: MoonlinkNode, payload: object) => void; diff --git a/dist/src/@Managers/NodeManager.d.ts b/dist/src/@Managers/NodeManager.d.ts index 1d69615d..d25e3ed3 100644 --- a/dist/src/@Managers/NodeManager.d.ts +++ b/dist/src/@Managers/NodeManager.d.ts @@ -17,14 +17,3 @@ export declare class NodeManager { private sortNodesByPlayingPlayers; private sortNodesByPlayers; } -export declare const State: { - READY: string; - CONNECTED: string; - CONNECTING: string; - DISCONNECTING: string; - DISCONNECTED: string; - RECONNECTING: string; - AUTORESUMING: string; - RESUMING: string; - MOVING: string; -}; diff --git a/dist/src/@Managers/NodeManager.js b/dist/src/@Managers/NodeManager.js index 84de442f..ab8b5955 100644 --- a/dist/src/@Managers/NodeManager.js +++ b/dist/src/@Managers/NodeManager.js @@ -1,6 +1,6 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.State = exports.NodeManager = void 0; +exports.NodeManager = void 0; const index_1 = require("../../index"); class NodeManager { initiated = false; @@ -46,7 +46,7 @@ class NodeManager { } sortByUsage(sortType) { this._manager.emit("debug", `@Moonlink(Nodes) - A new lavalink server is being drawn, sorting the type ${sortType}`); - const connectedNodes = [...this.map.values()].filter(node => node.state == exports.State.READY); + const connectedNodes = [...this.map.values()].filter(node => node.state == "READY"); if (connectedNodes.length == 0) throw new TypeError("[ @Moonlink/Manager ]: No lavalink server connected"); switch (sortType) { @@ -87,14 +87,3 @@ class NodeManager { } } exports.NodeManager = NodeManager; -exports.State = { - READY: "READY", - CONNECTED: "CONNECTED", - CONNECTING: "CONNECTING", - DISCONNECTING: "DISCONNECTING", - DISCONNECTED: "DISCONNECTED", - RECONNECTING: "RECONNECTING", - AUTORESUMING: "AUTORESUMING", - RESUMING: "RESUMING", - MOVING: "MOVING" -}; diff --git a/dist/src/@Managers/PlayerManager.js b/dist/src/@Managers/PlayerManager.js index 7fb39064..22c70782 100644 --- a/dist/src/@Managers/PlayerManager.js +++ b/dist/src/@Managers/PlayerManager.js @@ -45,9 +45,9 @@ class PlayerManager { async attemptConnection(guildId) { if (!this.cache[guildId] || (!this.voices && - !(this.voices[guildId]?.token && - this.voices[guildId]?.endpoint && - this.voices[guildId]?.sessionId))) { + !this.voices[guildId]?.token && + !this.voices[guildId]?.endpoint && + !this.voices[guildId]?.sessionId)) { return false; } if (this._manager.options?.balancingPlayersByRegion) { @@ -55,7 +55,7 @@ class PlayerManager { if (!this.cache[guildId].voiceRegion) { const connectedNodes = [ ...this._manager.nodes.map.values() - ].filter(node => node.state == index_1.State.READY); + ].filter(node => node.state == "READY"); const matchingNode = connectedNodes.find(node => node.regions.includes(voiceRegion)); this.cache[guildId].voiceRegion = voiceRegion; if (matchingNode) { diff --git a/dist/src/@Utils/MoonlinkDatabase.d.ts b/dist/src/@Utils/MoonlinkDatabase.d.ts index b2ed43f6..6cfaac37 100644 --- a/dist/src/@Utils/MoonlinkDatabase.d.ts +++ b/dist/src/@Utils/MoonlinkDatabase.d.ts @@ -1,6 +1,7 @@ +type Data = Record; export declare class MoonlinkDatabase { - private data; - private id; + data: Data; + id: string; constructor(clientId: string); set(key: string, value: T): void; get(key: string): T | undefined; @@ -8,6 +9,7 @@ export declare class MoonlinkDatabase { delete(key: string): boolean; private updateData; private getFilePath; - private fetch; + fetch(): void; private save; } +export {}; diff --git a/dist/src/@Utils/MoonlinkDatabase.js b/dist/src/@Utils/MoonlinkDatabase.js index 1d82902d..f8635d4b 100644 --- a/dist/src/@Utils/MoonlinkDatabase.js +++ b/dist/src/@Utils/MoonlinkDatabase.js @@ -25,7 +25,9 @@ class MoonlinkDatabase { get(key) { if (!key) throw new Error('[ @Moonlink(Database) - "key" is empty'); - return key.split(".").reduce((acc, curr) => acc?.[curr], this.data); + if (Object.keys(this.data).length === 0) + this.fetch(); + return (key.split(".").reduce((acc, curr) => acc?.[curr], this.data) ?? null); } push(key, value) { if (!key) diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index 545e2432..d24c8a33 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -134,20 +134,17 @@ export class MoonlinkNode { public async connect(): Promise { if (this.state == "CONNECTED" || this.state == "READY") return; this.state = "CONNECTING"; - + if (Object.keys(Structure.db.data).length == 0) + await Structure.db.fetch(); let headers = { Authorization: this.password, "User-Id": this._manager.options.clientId, "Client-Name": this._manager.options.clientName }; if (this.resume) - headers["Session-Id"] = - Structure.db.get( - `sessionId.${ - this.identifier ?? this.host.replace(/\./g, "-") - }` - ) ?? null; - + headers["Session-Id"] = Structure.db.get( + `sessionId.${this.identifier ?? this.host.replace(/\./g, "-")}` + ); this.socket = new MoonlinkWebSocket( `ws${this.secure ? "s" : ""}://${this.address}/v4/websocket`, { headers } @@ -260,6 +257,12 @@ export class MoonlinkNode { this.resumed ? ` session was resumed,` : `` } session is currently ${this.sessionId}` ); + this._manager.emit( + "nodeReady", + this, + this.sessionId, + this.resumed + ); if (this.resume) { this.rest.patch(`sessions/${this.sessionId}`, { data: { @@ -277,6 +280,7 @@ export class MoonlinkNode { this.info = await this.rest.getInfo(); if (this.autoResume) { let resumePlayers = this.getAllPlayers; + for (const resumePlayer of resumePlayers) { resumePlayer.restart(); } @@ -285,7 +289,7 @@ export class MoonlinkNode { const resumedPlayers: any[] = await this.rest.get( `sessions/${this.sessionId}/players` ); - + console.log(resumedPlayers); for (const resumedPlayer of resumedPlayers) { const previousInfosPlayer: PreviousInfosPlayer = Structure.db.get( @@ -303,7 +307,9 @@ export class MoonlinkNode { resumedPlayer.track ); player.current = track; + player.restart(); } + this._manager.emit("nodeResumed", this, resumedPlayers); } this.state = "READY"; break; diff --git a/src/@Managers/MoonlinkManager.ts b/src/@Managers/MoonlinkManager.ts index 0dd1abb2..9c2f6bc4 100644 --- a/src/@Managers/MoonlinkManager.ts +++ b/src/@Managers/MoonlinkManager.ts @@ -22,7 +22,9 @@ export interface MoonlinkEvents { autoLeaved: (player: MoonlinkPlayer, track?: any) => void; debug: (...args: any) => void; nodeCreate: (node: MoonlinkNode) => void; + nodeReady: (node: MoonlinkNode, sessionId: string, resumed: boolean) => void; nodeDestroy: (node: MoonlinkNode) => void; + nodeResumed: (node: MoonlinkNode, players: MoonlinkEvents[]) => void; nodeReconnect: (node: MoonlinkNode) => void; nodeClose: (node: MoonlinkNode, code: number, reason: any) => void; nodeRaw: (node: MoonlinkNode, payload: object) => void; diff --git a/src/@Managers/NodeManager.ts b/src/@Managers/NodeManager.ts index 3f49a771..fa6b54fd 100644 --- a/src/@Managers/NodeManager.ts +++ b/src/@Managers/NodeManager.ts @@ -65,13 +65,14 @@ export class NodeManager { public get(name) { return this.map.get(name) ? this.map.get(name) : null; } + public sortByUsage(sortType: SortType): MoonlinkNode[] { this._manager.emit( "debug", `@Moonlink(Nodes) - A new lavalink server is being drawn, sorting the type ${sortType}` ); const connectedNodes = [...this.map.values()].filter( - node => node.state == State.READY + node => node.state == "READY" ); if (connectedNodes.length == 0) throw new TypeError( @@ -128,15 +129,3 @@ export class NodeManager { ); } } - -export const State = { - READY: "READY", - CONNECTED: "CONNECTED", - CONNECTING: "CONNECTING", - DISCONNECTING: "DISCONNECTING", - DISCONNECTED: "DISCONNECTED", - RECONNECTING: "RECONNECTING", - AUTORESUMING: "AUTORESUMING", - RESUMING: "RESUMING", - MOVING: "MOVING" -}; diff --git a/src/@Managers/PlayerManager.ts b/src/@Managers/PlayerManager.ts index 7c2a921d..8e3210a7 100644 --- a/src/@Managers/PlayerManager.ts +++ b/src/@Managers/PlayerManager.ts @@ -4,7 +4,6 @@ import { MoonlinkManager, createOptions, Structure, - State, PreviousInfosPlayer } from "../../index"; export class PlayerManager { @@ -74,11 +73,11 @@ export class PlayerManager { if ( !this.cache[guildId] || (!this.voices && - !( + ! this.voices[guildId]?.token && - this.voices[guildId]?.endpoint && - this.voices[guildId]?.sessionId - )) + !this.voices[guildId]?.endpoint && + ! this.voices[guildId]?.sessionId + ) ) { return false; } @@ -90,7 +89,7 @@ export class PlayerManager { if (!this.cache[guildId].voiceRegion) { const connectedNodes = [ ...this._manager.nodes.map.values() - ].filter(node => node.state == State.READY); + ].filter(node => node.state == "READY"); const matchingNode = connectedNodes.find(node => node.regions.includes(voiceRegion) ); diff --git a/src/@Utils/MoonlinkDatabase.ts b/src/@Utils/MoonlinkDatabase.ts index 1570418d..2665777c 100644 --- a/src/@Utils/MoonlinkDatabase.ts +++ b/src/@Utils/MoonlinkDatabase.ts @@ -4,8 +4,8 @@ import path from "path"; type Data = Record; export class MoonlinkDatabase { - private data: Data = {}; - private id: string; + public data: Data = {}; + public id: string; constructor(clientId: string) { this.fetch(); @@ -24,8 +24,11 @@ export class MoonlinkDatabase { get(key: string): T | undefined { if (!key) throw new Error('[ @Moonlink(Database) - "key" is empty'); + if (Object.keys(this.data).length === 0) this.fetch(); - return key.split(".").reduce((acc, curr) => acc?.[curr], this.data); + return ( + key.split(".").reduce((acc, curr) => acc?.[curr], this.data) ?? null + ); } push(key: string, value: T): void { @@ -41,7 +44,7 @@ export class MoonlinkDatabase { ); } } - + delete(key: string): boolean { if (!key) throw new Error('@Moonlink(Database) - "key" is empty'); @@ -92,7 +95,7 @@ export class MoonlinkDatabase { ); } - private fetch() { + fetch() { try { const directory = path.join(__dirname, "../@Datastore"); if (!fs.existsSync(directory)) { @@ -107,7 +110,10 @@ export class MoonlinkDatabase { if (err.code === "ENOENT") { this.data = {}; } else { - throw new Error("@Moonlink(Database) - Failed to fetch data (Error):", err); + throw new Error( + "@Moonlink(Database) - Failed to fetch data (Error):", + err + ); } } } diff --git a/testBot/index.js b/testBot/index.js index 16942d17..54cfc2b2 100644 --- a/testBot/index.js +++ b/testBot/index.js @@ -46,16 +46,19 @@ for (const folder of commandFolders) { } client.moon = new MoonlinkManager( - [/*{ + [{ + host: "541b2cbb-4e46-4064-b8de-53bbe5ac63dc-00-20h37tgfzow4w.kirk.replit.dev", + password: "maybeiwasboring", secure: true, port: 443 + }/*{ host: "lavalink.jirayu.pw", port: 2333, password: "youshallnotpass", secure: false - }*/ { + }*//* { host: "localhost", port: 2333, secure: false, - identifier: "LAVALINK" + identifier: "NODELINK" } /*{ host: "65.108.101.89", port: 17958, @@ -68,7 +71,7 @@ client.moon = new MoonlinkManager( port: 7784, password: "PasswordIsZoldy", secure: false, - }, { + },{ host: "lavalink-v4.teramont.net", port: 443, password: "eHKuFcz67k4lBS64", @@ -85,7 +88,6 @@ client.moon = new MoonlinkManager( }*/], { //http2: true, - movePlayersToNextNode: true, autoResume: true, resume: true, clientName: "Moonlink/Blio", From 2effc789ad2ba98a6302b99d0da71addf1b4e2a0 Mon Sep 17 00:00:00 2001 From: 1Lucas1apk Date: Sat, 24 Feb 2024 22:17:25 -0400 Subject: [PATCH 04/16] Fix: system (resume, autoResume, player status, movePlayer and others) --- dist/src/@Entities/MoonlinkNode.js | 60 +++++++++++++-------- dist/src/@Entities/MoonlinkPlayer.js | 24 ++++----- src/@Entities/MoonlinkNode.ts | 78 ++++++++++++++-------------- src/@Entities/MoonlinkPlayer.ts | 5 +- testBot/index.js | 4 +- 5 files changed, 95 insertions(+), 76 deletions(-) diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index cbd95f27..e7b68eac 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -147,6 +147,7 @@ class MoonlinkNode { : null; this.resumed = payload.resumed; this.rest.setSessionId(this.sessionId); + this.state = "READY"; if (!this._manager.initiated && !this.resumed) { index_1.Structure.db.delete("queue"); index_1.Structure.db.delete("players"); @@ -185,15 +186,16 @@ class MoonlinkNode { player.connected = true; const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); player.current = track; - player.restart(); + player.current.position = resumedPlayer.state.position; + await player.restart(); } this._manager.emit("nodeResumed", this, resumedPlayers); } - this.state = "READY"; break; case "stats": delete payload.op; this.stats = { ...payload }; + console.log(payload); break; case "playerUpdate": let player = this._manager.players.get(payload.guildId); @@ -213,47 +215,61 @@ class MoonlinkNode { return; if (!payload.guildId) return; - let player = this._manager.players.get(payload.guildId); - if (!player) + if (!this._manager.players.has(payload.guildId)) return; + let player = this._manager.players.get(payload.guildId); switch (payload.type) { case "TrackStartEvent": { - if (!player.current) { - player.current = new index_1.MoonlinkTrack((await this.rest.decodeTrack(payload.track))); - } + let current = player.current; + if (!current) + return; player.playing = true; player.paused = false; - this._manager.emit("trackStart", player, player.current); + this._manager.emit("trackStart", player, current); break; } case "TrackEndEvent": { + let track = player.current; + let queue = player.queue.all; + player.playing = false; if (this._manager.options.previousTracksInArray) - player.previous.push(player.current); + player.previous.push(track); else - player.previous = player.current; - player.playing = false; + player.previous = track; + if (["loadFailed", "cleanup"].includes(payload.reason)) { + if (!queue) { + player.queue.clear(); + return this._manager.emit("queueEnd", player, track); + } + player.play(); + return; + } if (payload.reason === "replaced") { - this._manager.emit("trackEnd", player, player.current, payload); + this._manager.emit("trackEnd", player, track, payload); return; } - if (player.current && [1, 2].includes(player.loop)) { + if (track && player.loop) { if (player.loop == 1) { await this.rest.update({ guildId: payload.guildId, - data: { track: { encoded: player.current.encoded } } + data: { track: { encoded: track.encoded } } }); return; } if (player.loop == 2) { player.queue.add(player.current); - if (!player.queue.all || !player.queue.size) - return this._manager.emit("trackEnd", player, player.current, payload); + if (!queue || queue.length === 0) + return this._manager.emit("trackEnd", player, track, payload); player.play(); return; } + else { + this._manager.emit("trackEnd", player, track); + this._manager.emit("debug", "@Manager(Nodes) - invalid loop value will be ignored!"); + } } if (player.queue.size) { - this._manager.emit("trackEnd", player, player.current, payload); + this._manager.emit("trackEnd", player, track); player.play(); return; } @@ -261,7 +277,8 @@ class MoonlinkNode { player.autoPlay === true) { if (payload.reason == "stopped") return; - let req = await this._manager.search(`https://www.youtube.com/watch?v=${player.current.identifier}&list=RD${player.current.identifier}`); + let uri = `https://www.youtube.com/watch?v=${track.identifier}&list=RD${track.identifier}`; + let req = await this._manager.search(uri); if (!req || !req.tracks || ["loadFailed", "cleanup"].includes(req.loadType)) @@ -273,12 +290,13 @@ class MoonlinkNode { } if (player.autoLeave) { player.destroy(); - this._manager.emit("autoLeaved", player, player.current); + this._manager.emit("autoLeaved", player, track); } if (!player.queue.size) { - this._manager.emit("debug", "@Moonlink(Nodes) - The queue is empty"); + this._manager.emit("debug", "[ @Moonlink/Nodes ]: The queue is empty"); this._manager.emit("queueEnd", player); player.current = null; + player.queue.clear(); } break; } @@ -297,7 +315,7 @@ class MoonlinkNode { break; } default: { - const error = new Error(`@Moonlink(Nodes) - unknown event '${payload.type}'.`); + const error = new Error(`[ @Moonlink/Nodes ] unknown event '${payload.type}'.`); this._manager.emit("nodeError", this, error); } } diff --git a/dist/src/@Entities/MoonlinkPlayer.js b/dist/src/@Entities/MoonlinkPlayer.js index bb1139fc..cddb7746 100644 --- a/dist/src/@Entities/MoonlinkPlayer.js +++ b/dist/src/@Entities/MoonlinkPlayer.js @@ -122,8 +122,6 @@ class MoonlinkPlayer { return true; } async restart() { - if (!this.current || !this.queue.size) - return; this.connect({ setDeaf: true, setMute: false @@ -133,16 +131,18 @@ class MoonlinkPlayer { this.play(); return; } - await this.node.rest.update({ - guildId: this.guildId, - data: { - track: { - encoded: this.current.encoded - }, - position: this.current.position, - volume: this.volume - } - }); + else { + await this.node.rest.update({ + guildId: this.guildId, + data: { + track: { + encoded: this.current.encoded + }, + position: this.current.position, + volume: this.volume + } + }); + } this.manager.emit("playerRestarted", this); } async play(track) { diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index d24c8a33..e647b035 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -247,6 +247,7 @@ export class MoonlinkNode { : null; this.resumed = payload.resumed; this.rest.setSessionId(this.sessionId); + this.state = "READY"; if (!this._manager.initiated && !this.resumed) { Structure.db.delete("queue"); Structure.db.delete("players"); @@ -307,15 +308,16 @@ export class MoonlinkNode { resumedPlayer.track ); player.current = track; - player.restart(); + player.current.position = resumedPlayer.state.position; + await player.restart(); } this._manager.emit("nodeResumed", this, resumedPlayers); } - this.state = "READY"; break; case "stats": delete payload.op; this.stats = { ...payload }; + console.log(payload) break; case "playerUpdate": let player = this._manager.players.get(payload.guildId); @@ -337,71 +339,73 @@ export class MoonlinkNode { ); } } - protected async handleEvent(payload: any): Promise { if (!payload) return; if (!payload.guildId) return; + if (!this._manager.players.has(payload.guildId)) return; let player: MoonlinkPlayer = this._manager.players.get(payload.guildId); - if (!player) return; - switch (payload.type) { case "TrackStartEvent": { - if (!player.current) { - player.current = new MoonlinkTrack( - (await this.rest.decodeTrack(payload.track)) as any - ) as MoonlinkTrack; - } + let current = player.current; + if (!current) return; player.playing = true; player.paused = false; - this._manager.emit("trackStart", player, player.current); + this._manager.emit("trackStart", player, current); break; } case "TrackEndEvent": { + let track = player.current; + let queue: string[] = player.queue.all; + player.playing = false; + if (this._manager.options.previousTracksInArray) (player.previous as MoonlinkTrack[]).push( - player.current as MoonlinkTrack + track as MoonlinkTrack ); - else player.previous = player.current; - player.playing = false; + else player.previous = track; + if (["loadFailed", "cleanup"].includes(payload.reason)) { + if (!queue) { + player.queue.clear(); + return this._manager.emit("queueEnd", player, track); + } + player.play(); + return; + } if (payload.reason === "replaced") { - this._manager.emit( - "trackEnd", - player, - player.current, - payload - ); + this._manager.emit("trackEnd", player, track, payload); return; } - if (player.current && [1, 2].includes(player.loop)) { + if (track && player.loop) { if (player.loop == 1) { await this.rest.update({ guildId: payload.guildId, - data: { track: { encoded: player.current.encoded } } + data: { track: { encoded: track.encoded } } }); return; } if (player.loop == 2) { player.queue.add(player.current as MoonlinkTrack); - if (!player.queue.all || !player.queue.size) + if (!queue || queue.length === 0) return this._manager.emit( "trackEnd", player, - player.current, + track, payload ); player.play(); return; + } else { + this._manager.emit("trackEnd", player, track); + this._manager.emit( + "debug", + "@Manager(Nodes) - invalid loop value will be ignored!" + ); } } if (player.queue.size) { - this._manager.emit( - "trackEnd", - player, - player.current, - payload - ); + this._manager.emit("trackEnd", player, track); player.play(); return; } @@ -410,9 +414,8 @@ export class MoonlinkNode { player.autoPlay === true ) { if (payload.reason == "stopped") return; - let req: SearchResult = await this._manager.search( - `https://www.youtube.com/watch?v=${player.current.identifier}&list=RD${player.current.identifier}` - ); + let uri = `https://www.youtube.com/watch?v=${track.identifier}&list=RD${track.identifier}`; + let req: SearchResult = await this._manager.search(uri); if ( !req || !req.tracks || @@ -432,15 +435,16 @@ export class MoonlinkNode { /* Logic created by PiscesXD */ if (player.autoLeave) { player.destroy(); - this._manager.emit("autoLeaved", player, player.current); + this._manager.emit("autoLeaved", player, track); } if (!player.queue.size) { this._manager.emit( "debug", - "@Moonlink(Nodes) - The queue is empty" + "[ @Moonlink/Nodes ]: The queue is empty" ); this._manager.emit("queueEnd", player); player.current = null; + player.queue.clear(); } break; } @@ -457,18 +461,16 @@ export class MoonlinkNode { } case "WebSocketClosedEvent": { this._manager.emit("socketClosed", player, payload); - //migrar pro outro node se tiver players break; } default: { const error = new Error( - `@Moonlink(Nodes) - unknown event '${payload.type}'.` + `[ @Moonlink/Nodes ] unknown event '${payload.type}'.` ); this._manager.emit("nodeError", this, error); } } } - private movePlayers(): boolean { this.getAllPlayers.forEach(player => { let anotherNode = this._manager.nodes.sortByUsage( diff --git a/src/@Entities/MoonlinkPlayer.ts b/src/@Entities/MoonlinkPlayer.ts index a7fed31d..79610875 100644 --- a/src/@Entities/MoonlinkPlayer.ts +++ b/src/@Entities/MoonlinkPlayer.ts @@ -209,7 +209,6 @@ export class MoonlinkPlayer { * Restart the player by reconnecting and updating its state. */ public async restart(): Promise { - if (!this.current || !this.queue.size) return; this.connect({ setDeaf: true, @@ -221,8 +220,7 @@ export class MoonlinkPlayer { if (!this.current && this.queue.size) { this.play(); return; - } - + } else { await this.node.rest.update({ guildId: this.guildId, data: { @@ -233,6 +231,7 @@ export class MoonlinkPlayer { volume: this.volume } }); + } this.manager.emit("playerRestarted", this); } /** diff --git a/testBot/index.js b/testBot/index.js index 54cfc2b2..fb8fd951 100644 --- a/testBot/index.js +++ b/testBot/index.js @@ -46,7 +46,7 @@ for (const folder of commandFolders) { } client.moon = new MoonlinkManager( - [{ + [/*{ host: "541b2cbb-4e46-4064-b8de-53bbe5ac63dc-00-20h37tgfzow4w.kirk.replit.dev", password: "maybeiwasboring", secure: true, port: 443 }/*{ @@ -54,7 +54,7 @@ client.moon = new MoonlinkManager( port: 2333, password: "youshallnotpass", secure: false - }*//* { + }*/{ host: "localhost", port: 2333, secure: false, From 952900c0c14de44586e1769da25e863c588fa989 Mon Sep 17 00:00:00 2001 From: 1Lucas1apk Date: Sat, 24 Feb 2024 22:36:11 -0400 Subject: [PATCH 05/16] remove console.log() --- dist/src/@Entities/MoonlinkNode.js | 2 -- src/@Entities/MoonlinkNode.ts | 3 --- 2 files changed, 5 deletions(-) diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index e7b68eac..b63c8ffa 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -173,7 +173,6 @@ class MoonlinkNode { } if (this.resumed) { const resumedPlayers = await this.rest.get(`sessions/${this.sessionId}/players`); - console.log(resumedPlayers); for (const resumedPlayer of resumedPlayers) { const previousInfosPlayer = index_1.Structure.db.get(`players.${resumedPlayer.guildId}`) || {}; const player = this._manager.players.create({ @@ -195,7 +194,6 @@ class MoonlinkNode { case "stats": delete payload.op; this.stats = { ...payload }; - console.log(payload); break; case "playerUpdate": let player = this._manager.players.get(payload.guildId); diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index e647b035..9c9eb4f7 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -12,7 +12,6 @@ import { MoonlinkTrack, MoonlinkPlayer, MoonlinkRestFul, - MoonlinkDatabase, Structure } from "../../index"; @@ -290,7 +289,6 @@ export class MoonlinkNode { const resumedPlayers: any[] = await this.rest.get( `sessions/${this.sessionId}/players` ); - console.log(resumedPlayers); for (const resumedPlayer of resumedPlayers) { const previousInfosPlayer: PreviousInfosPlayer = Structure.db.get( @@ -317,7 +315,6 @@ export class MoonlinkNode { case "stats": delete payload.op; this.stats = { ...payload }; - console.log(payload) break; case "playerUpdate": let player = this._manager.players.get(payload.guildId); From 5aeb4cdb79a667da19b34440f8e746f2975f152b Mon Sep 17 00:00:00 2001 From: * Date: Mon, 26 Feb 2024 18:48:12 -0400 Subject: [PATCH 06/16] fixed position current, filters in player --- .../database-960185850346471505.json | 5 ++++ dist/src/@Entities/MoonlinkNode.js | 4 ++-- dist/src/@Entities/MoonlinkPlayer.d.ts | 3 ++- dist/src/@Entities/MoonlinkPlayer.js | 2 ++ dist/src/@Managers/MoonlinkManager.d.ts | 2 +- dist/src/@Managers/MoonlinkManager.js | 3 ++- package-lock.json | 11 +++++++-- package.json | 1 + src/@Entities/MoonlinkNode.ts | 4 +--- src/@Entities/MoonlinkPlayer.ts | 24 ++++++++++--------- src/@Managers/MoonlinkManager.ts | 9 +++++-- testBot/index.js | 10 ++------ yarn.lock | 5 ++++ 13 files changed, 52 insertions(+), 31 deletions(-) create mode 100644 dist/src/@Datastore/database-960185850346471505.json diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json new file mode 100644 index 00000000..fa2d8267 --- /dev/null +++ b/dist/src/@Datastore/database-960185850346471505.json @@ -0,0 +1,5 @@ +{ + "sessionId": { + "NODELINK": "01YxB03Gn88y7u4z" + } +} \ No newline at end of file diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index b63c8ffa..aa084c64 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -69,8 +69,6 @@ class MoonlinkNode { if (this.state == "CONNECTED" || this.state == "READY") return; this.state = "CONNECTING"; - if (Object.keys(index_1.Structure.db.data).length == 0) - await index_1.Structure.db.fetch(); let headers = { Authorization: this.password, "User-Id": this._manager.options.clientId, @@ -198,6 +196,8 @@ class MoonlinkNode { case "playerUpdate": let player = this._manager.players.get(payload.guildId); player.ping = payload.state.ping; + if (!player.current) + return; player.current.position = payload.state.position; player.current.time = payload.state.time; break; diff --git a/dist/src/@Entities/MoonlinkPlayer.d.ts b/dist/src/@Entities/MoonlinkPlayer.d.ts index 1a09539b..bf2f66b5 100644 --- a/dist/src/@Entities/MoonlinkPlayer.d.ts +++ b/dist/src/@Entities/MoonlinkPlayer.d.ts @@ -1,4 +1,4 @@ -import { MoonlinkManager, MoonlinkQueue, MoonlinkNode, MoonlinkTrack } from "../../index"; +import { MoonlinkManager, MoonlinkQueue, MoonlinkNode, MoonlinkTrack, MoonlinkFilters } from "../../index"; import { IPlayerData, connectOptions } from "../@Typings"; export declare class MoonlinkPlayer { manager: MoonlinkManager; @@ -15,6 +15,7 @@ export declare class MoonlinkPlayer { volume: number; ping: number; queue: MoonlinkQueue; + filters: MoonlinkFilters; current: Record; previous: MoonlinkTrack[] | MoonlinkTrack | Record; data: Record; diff --git a/dist/src/@Entities/MoonlinkPlayer.js b/dist/src/@Entities/MoonlinkPlayer.js index cddb7746..3bcec5d1 100644 --- a/dist/src/@Entities/MoonlinkPlayer.js +++ b/dist/src/@Entities/MoonlinkPlayer.js @@ -17,6 +17,7 @@ class MoonlinkPlayer { volume; ping; queue; + filters; current; previous; data; @@ -39,6 +40,7 @@ class MoonlinkPlayer { this.previous = []; this.data = {}; this.node = this.manager.nodes.get(data.node); + this.filters = new (index_1.Structure.get("MoonlinkFilters"))(this); if (this.manager.options.resume) this.manager.players.backup(this); } diff --git a/dist/src/@Managers/MoonlinkManager.d.ts b/dist/src/@Managers/MoonlinkManager.d.ts index d948c261..dd40d207 100644 --- a/dist/src/@Managers/MoonlinkManager.d.ts +++ b/dist/src/@Managers/MoonlinkManager.d.ts @@ -54,7 +54,7 @@ export declare class MoonlinkManager extends EventEmitter { options: IOptions; initiated: boolean; constructor(nodes: INode[], options: IOptions, SPayload: Function); - init(clientId?: string): this; + init(clientId?: string): Promise; search(options: string | SearchQuery): Promise; packetUpdate(packet: VoicePacket): void; } diff --git a/dist/src/@Managers/MoonlinkManager.js b/dist/src/@Managers/MoonlinkManager.js index 19d05c65..bcc00d6f 100644 --- a/dist/src/@Managers/MoonlinkManager.js +++ b/dist/src/@Managers/MoonlinkManager.js @@ -27,7 +27,7 @@ class MoonlinkManager extends node_events_1.EventEmitter { if (!this.options.clientName) this.options.clientName = `Moonlink/${this.version} (https://github.com/Ecliptia/moonlink.js)`; } - init(clientId) { + async init(clientId) { if (this.initiated) return this; this.emit("debug", "@Moonlink - moonlink.js has started the initialization process, do not attempt to use functions until everything is initialized correctly "); @@ -36,6 +36,7 @@ class MoonlinkManager extends node_events_1.EventEmitter { this.options.clientId = clientId; this.clientId = clientId; index_1.Structure.init(this); + await index_1.Structure.db.fetch(); this.nodes.init(); this.players.init(); this.initiated = true; diff --git a/package-lock.json b/package-lock.json index 960a7c29..ddd7cde4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,18 +1,19 @@ { "name": "moonlink.js", - "version": "3.2.22", + "version": "3.4.52", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "moonlink.js", - "version": "3.2.22", + "version": "3.4.52", "license": "Apache-2.0", "devDependencies": { "@types/node": "^18.15.11", "discord.js": "^14.14.1", "get-image-colors": "^4.0.1", "mongoose": "^8.1.1", + "typecript": "^0.0.1-security", "typedoc": "^0.25.4", "typedoc-plugin-markdown": "^3.17.1" }, @@ -1441,6 +1442,12 @@ "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==", "dev": true }, + "node_modules/typecript": { + "version": "0.0.1-security", + "resolved": "https://registry.npmjs.org/typecript/-/typecript-0.0.1-security.tgz", + "integrity": "sha512-88WUWdO0zl/cC+X44m7TJkNssn0sTwZOSAyZu7ZmY6BfGJ4idVWJGjFmd6wEjS3yhWUYrAszzNMHZMIJ7h3ycg==", + "dev": true + }, "node_modules/typedoc": { "version": "0.25.7", "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.25.7.tgz", diff --git a/package.json b/package.json index c1a47163..85d94e5b 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "discord.js": "^14.14.1", "get-image-colors": "^4.0.1", "mongoose": "^8.1.1", + "typecript": "^0.0.1-security", "typedoc": "^0.25.4", "typedoc-plugin-markdown": "^3.17.1" } diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index 9c9eb4f7..8ca77f9c 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -133,8 +133,6 @@ export class MoonlinkNode { public async connect(): Promise { if (this.state == "CONNECTED" || this.state == "READY") return; this.state = "CONNECTING"; - if (Object.keys(Structure.db.data).length == 0) - await Structure.db.fetch(); let headers = { Authorization: this.password, "User-Id": this._manager.options.clientId, @@ -319,9 +317,9 @@ export class MoonlinkNode { case "playerUpdate": let player = this._manager.players.get(payload.guildId); player.ping = payload.state.ping; + if (!player.current) return; player.current.position = payload.state.position; player.current.time = payload.state.time; - break; case "event": this.handleEvent(payload); diff --git a/src/@Entities/MoonlinkPlayer.ts b/src/@Entities/MoonlinkPlayer.ts index 79610875..c54f1c7a 100644 --- a/src/@Entities/MoonlinkPlayer.ts +++ b/src/@Entities/MoonlinkPlayer.ts @@ -3,6 +3,7 @@ import { MoonlinkQueue, MoonlinkNode, MoonlinkTrack, + MoonlinkFilters, Structure } from "../../index"; import { IPlayerData, connectOptions } from "../@Typings"; @@ -21,6 +22,7 @@ export class MoonlinkPlayer { public volume: number; public ping: number; public queue: MoonlinkQueue; + public filters: MoonlinkFilters; public current: Record; public previous: MoonlinkTrack[] | MoonlinkTrack | Record; public data: Record; @@ -52,6 +54,7 @@ export class MoonlinkPlayer { this.previous = []; this.data = {}; this.node = this.manager.nodes.get(data.node); + this.filters = new (Structure.get("MoonlinkFilters"))(this); if (this.manager.options.resume) this.manager.players.backup(this); } @@ -209,7 +212,6 @@ export class MoonlinkPlayer { * Restart the player by reconnecting and updating its state. */ public async restart(): Promise { - this.connect({ setDeaf: true, setMute: false @@ -221,16 +223,16 @@ export class MoonlinkPlayer { this.play(); return; } else { - await this.node.rest.update({ - guildId: this.guildId, - data: { - track: { - encoded: this.current.encoded - }, - position: this.current.position, - volume: this.volume - } - }); + await this.node.rest.update({ + guildId: this.guildId, + data: { + track: { + encoded: this.current.encoded + }, + position: this.current.position, + volume: this.volume + } + }); } this.manager.emit("playerRestarted", this); } diff --git a/src/@Managers/MoonlinkManager.ts b/src/@Managers/MoonlinkManager.ts index 9c2f6bc4..46294110 100644 --- a/src/@Managers/MoonlinkManager.ts +++ b/src/@Managers/MoonlinkManager.ts @@ -22,7 +22,11 @@ export interface MoonlinkEvents { autoLeaved: (player: MoonlinkPlayer, track?: any) => void; debug: (...args: any) => void; nodeCreate: (node: MoonlinkNode) => void; - nodeReady: (node: MoonlinkNode, sessionId: string, resumed: boolean) => void; + nodeReady: ( + node: MoonlinkNode, + sessionId: string, + resumed: boolean + ) => void; nodeDestroy: (node: MoonlinkNode) => void; nodeResumed: (node: MoonlinkNode, players: MoonlinkEvents[]) => void; nodeReconnect: (node: MoonlinkNode) => void; @@ -132,7 +136,7 @@ export class MoonlinkManager extends EventEmitter { if (!this.options.clientName) this.options.clientName = `Moonlink/${this.version} (https://github.com/Ecliptia/moonlink.js)`; } - public init(clientId?: string): this { + public async init(clientId?: string): Promise { if (this.initiated) return this; this.emit( "debug", @@ -145,6 +149,7 @@ export class MoonlinkManager extends EventEmitter { this.options.clientId = clientId; this.clientId = clientId; Structure.init(this); + await Structure.db.fetch(); this.nodes.init(); this.players.init(); this.initiated = true; diff --git a/testBot/index.js b/testBot/index.js index fb8fd951..9f00f2ff 100644 --- a/testBot/index.js +++ b/testBot/index.js @@ -9,10 +9,6 @@ const { makeRequest } = require("../dist/index.js") -const { - Lyrics -} = require("../../moonlink.js-lyrics/index.js") - const fs = require("fs"); const path = require("path"); const http = require("http"); @@ -90,9 +86,7 @@ client.moon = new MoonlinkManager( //http2: true, autoResume: true, resume: true, - clientName: "Moonlink/Blio", - WebSocketDebug: true, - plugins: [new Lyrics()], + clientName: "Moonlink/Blio" }, (id, data) => { let guild = client.guilds.cache.get(id); @@ -134,4 +128,4 @@ client.on("error", (error) => { log(`[ Client ]: Client error: ${error}`); }); -client.login(require ("../config.json").token); \ No newline at end of file +client.login(require ("../config.json").token); diff --git a/yarn.lock b/yarn.lock index 0956eaaf..1a7a6bba 100644 --- a/yarn.lock +++ b/yarn.lock @@ -912,6 +912,11 @@ tweetnacl@^0.14.3, tweetnacl@~0.14.0: resolved "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz" integrity sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA== +typecript@^0.0.1-security: + version "0.0.1-security" + resolved "https://registry.npmjs.org/typecript/-/typecript-0.0.1-security.tgz" + integrity sha512-88WUWdO0zl/cC+X44m7TJkNssn0sTwZOSAyZu7ZmY6BfGJ4idVWJGjFmd6wEjS3yhWUYrAszzNMHZMIJ7h3ycg== + typedoc-plugin-markdown@^3.17.1: version "3.17.1" resolved "https://registry.npmjs.org/typedoc-plugin-markdown/-/typedoc-plugin-markdown-3.17.1.tgz" From 73f5959c2ab2382a0662a5457c05623461f84ca0 Mon Sep 17 00:00:00 2001 From: Lucas Morais Rodrigues <76886832+1Lucas1apk@users.noreply.github.com> Date: Tue, 27 Feb 2024 06:45:19 -0400 Subject: [PATCH 07/16] Atualizar o database-960185850346471505.json --- dist/src/@Datastore/database-960185850346471505.json | 5 ----- 1 file changed, 5 deletions(-) diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json index fa2d8267..e69de29b 100644 --- a/dist/src/@Datastore/database-960185850346471505.json +++ b/dist/src/@Datastore/database-960185850346471505.json @@ -1,5 +0,0 @@ -{ - "sessionId": { - "NODELINK": "01YxB03Gn88y7u4z" - } -} \ No newline at end of file From 5436fde51fd57ee1b5bc7cc69b34b183c2fb9fe3 Mon Sep 17 00:00:00 2001 From: * Date: Tue, 27 Feb 2024 10:11:27 -0400 Subject: [PATCH 08/16] fixed non-existent player --- dist/src/@Datastore/database-960185850346471505.json | 0 dist/src/@Entities/MoonlinkNode.js | 2 ++ src/@Entities/MoonlinkNode.ts | 1 + 3 files changed, 3 insertions(+) delete mode 100644 dist/src/@Datastore/database-960185850346471505.json diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json deleted file mode 100644 index e69de29b..00000000 diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index aa084c64..1473c10c 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -195,6 +195,8 @@ class MoonlinkNode { break; case "playerUpdate": let player = this._manager.players.get(payload.guildId); + if (!player) + return; player.ping = payload.state.ping; if (!player.current) return; diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index 8ca77f9c..1dca5239 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -316,6 +316,7 @@ export class MoonlinkNode { break; case "playerUpdate": let player = this._manager.players.get(payload.guildId); + if (!player) return; player.ping = payload.state.ping; if (!player.current) return; player.current.position = payload.state.position; From 36f4bdcd1a7d5cec38120bd1796bf954dd9ffbdf Mon Sep 17 00:00:00 2001 From: * Date: Tue, 27 Feb 2024 11:11:29 -0400 Subject: [PATCH 09/16] improve: retrieval of players' information in the resume --- dist/src/@Entities/MoonlinkNode.js | 5 +++ dist/src/@Entities/MoonlinkPlayer.js | 24 +++++++++++++ dist/src/@Managers/PlayerManager.js | 28 ++++++--------- dist/src/@Typings/index.d.ts | 11 ++++-- src/@Entities/MoonlinkNode.ts | 5 +++ src/@Entities/MoonlinkPlayer.ts | 17 +++++++-- src/@Managers/PlayerManager.ts | 54 +++++++++++++--------------- src/@Typings/index.ts | 11 ++++-- 8 files changed, 102 insertions(+), 53 deletions(-) diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index 1473c10c..6c02d053 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -177,10 +177,15 @@ class MoonlinkNode { guildId: resumedPlayer.guildId, voiceChannel: previousInfosPlayer.voiceChannel, textChannel: previousInfosPlayer.textChannel, + volume: previousInfosPlayer.volume, + loop: previousInfosPlayer.loop, + autoPlay: previousInfosPlayer.autoPlay, + autoLeave: previousInfosPlayer.autoLeave, node: this.identifier ?? this.host }); player.playing = true; player.connected = true; + player.previous = previousInfosPlayer.previous; const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); player.current = track; player.current.position = resumedPlayer.state.position; diff --git a/dist/src/@Entities/MoonlinkPlayer.js b/dist/src/@Entities/MoonlinkPlayer.js index 3bcec5d1..d8c38670 100644 --- a/dist/src/@Entities/MoonlinkPlayer.js +++ b/dist/src/@Entities/MoonlinkPlayer.js @@ -83,6 +83,8 @@ class MoonlinkPlayer { mode ? mode : (mode = !this.autoLeave); this.autoLeave = mode; this.manager.emit("playerAutoLeaveTriggered", this, mode); + if (this.manager.options.resume) + this.manager.players.backup(this); return mode; } setAutoPlay(mode) { @@ -91,6 +93,8 @@ class MoonlinkPlayer { } this.autoPlay = mode; this.manager.emit("playerAutoPlayTriggered", this, mode); + if (this.manager.options.resume) + this.manager.players.backup(this); return mode; } connect(options) { @@ -146,6 +150,8 @@ class MoonlinkPlayer { }); } this.manager.emit("playerRestarted", this); + if (this.manager.options.resume) + this.manager.players.backup(this); } async play(track) { if (!track && !this.queue.size) @@ -190,6 +196,8 @@ class MoonlinkPlayer { return true; await this.updatePlaybackStatus(true); this.manager.emit("playerPaused", this); + if (this.manager.options.resume) + this.manager.players.backup(this); return true; } async resume() { @@ -197,6 +205,8 @@ class MoonlinkPlayer { return true; await this.updatePlaybackStatus(false); this.manager.emit("playerResume", this); + if (this.manager.options.resume) + this.manager.players.backup(this); return true; } async updatePlaybackStatus(paused) { @@ -215,11 +225,15 @@ class MoonlinkPlayer { track: { encoded: null } } }); + if (this.manager.options.resume) + this.manager.players.backup(this); } this.manager.emit("playerStopped", this, this.current); this.manager.options?.destroyPlayersStopped && destroy ? this.destroy() : this.queue.clear(); + if (this.manager.options.resume) + this.manager.players.backup(this); return true; } async skip(position) { @@ -245,6 +259,8 @@ class MoonlinkPlayer { this.stop(); return true; } + if (this.manager.options.resume) + this.manager.players.backup(this); } async setVolume(percent) { if (typeof percent == "undefined" || isNaN(percent)) { @@ -259,6 +275,8 @@ class MoonlinkPlayer { }); this.manager.emit("playerVolumeChanged", this, this.volume, percent); this.volume = percent; + if (this.manager.options.resume) + this.manager.players.backup(this); return percent; } setLoop(mode) { @@ -276,6 +294,8 @@ class MoonlinkPlayer { } this.manager.emit("playerLoopSet", this, this.loop, mode); this.loop = mode; + if (this.manager.options.resume) + this.manager.players.backup(this); return mode; } async destroy() { @@ -306,6 +326,8 @@ class MoonlinkPlayer { guildId: this.guildId, data: { position } }); + if (this.manager.options.resume) + this.manager.players.backup(this); return position; } shuffle() { @@ -315,6 +337,8 @@ class MoonlinkPlayer { let oldQueue = Array.from(this.queue.all); let shuffleStatus = this.queue.shuffle(); this.manager.emit("playerShuffled", this, oldQueue, this.queue.all, shuffleStatus); + if (this.manager.options.resume) + this.manager.players.backup(this); return shuffleStatus; } } diff --git a/dist/src/@Managers/PlayerManager.js b/dist/src/@Managers/PlayerManager.js index 22c70782..f619de00 100644 --- a/dist/src/@Managers/PlayerManager.js +++ b/dist/src/@Managers/PlayerManager.js @@ -123,23 +123,17 @@ class PlayerManager { return this.cache ?? null; } backup(player) { - const db = index_1.Structure.db; - let { guildId } = player; - const existingData = db.get(`players.${guildId}`) || {}; - if (player.voiceChannel && - player.voiceChannel !== - (existingData.voiceChannel && existingData.voiceChannel)) { - existingData.voiceChannel = player.voiceChannel; - } - if (player.textChannel && - player.textChannel !== - (existingData.textChannel && existingData.textChannel)) { - existingData.textChannel = player.textChannel; - } - if (existingData !== - (db.get(`players.${guildId}`) || {})) { - db.set(`players.${guildId}`, existingData); - } + let { guildId, textChannel, voiceChannel, loop, voiceRegion, autoPlay, autoLeave, previous, volume } = player; + index_1.Structure.db.set(`players.${guildId}`, { + guildId, + textChannel, + voiceChannel, + loop, + autoPlay, + autoLeave, + previous, + volume + }); return true; } delete(guildId) { diff --git a/dist/src/@Typings/index.d.ts b/dist/src/@Typings/index.d.ts index 316aa137..87e6d330 100644 --- a/dist/src/@Typings/index.d.ts +++ b/dist/src/@Typings/index.d.ts @@ -4,7 +4,9 @@ export interface createOptions { guildId: string; textChannel: string; voiceChannel: string; - autoPlay?: boolean | null; + autoPlay?: boolean; + autoLeave?: boolean; + loop?: number; volume?: number; node?: string; } @@ -101,7 +103,6 @@ export interface IOptions { resume?: boolean; plugins?: Plugin[]; http2?: boolean; - movePlayersToNextNode?: boolean; destroyPlayersStopped?: boolean; balancingPlayersByRegion?: boolean; previousTracksInArray?: boolean; @@ -154,6 +155,12 @@ export interface objectTrack { export interface PreviousInfosPlayer { voiceChannel?: string; textChannel?: string; + guildId?: string; + volume?: number; + autoPlay?: boolean; + autoLeave?: boolean; + previous?: object | MoonlinkTrack; + loop?: number; } export interface RestOptions { guildId: string; diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index 1dca5239..dd489733 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -296,10 +296,15 @@ export class MoonlinkNode { guildId: resumedPlayer.guildId, voiceChannel: previousInfosPlayer.voiceChannel, textChannel: previousInfosPlayer.textChannel, + volume: previousInfosPlayer.volume, + loop: previousInfosPlayer.loop, + autoPlay: previousInfosPlayer.autoPlay, + autoLeave: previousInfosPlayer.autoLeave, node: this.identifier ?? this.host }); player.playing = true; player.connected = true; + player.previous = previousInfosPlayer.previous; const track = new (Structure.get("MoonlinkTrack"))( resumedPlayer.track ); diff --git a/src/@Entities/MoonlinkPlayer.ts b/src/@Entities/MoonlinkPlayer.ts index c54f1c7a..40e682fa 100644 --- a/src/@Entities/MoonlinkPlayer.ts +++ b/src/@Entities/MoonlinkPlayer.ts @@ -139,6 +139,7 @@ export class MoonlinkPlayer { this.autoLeave = mode; this.manager.emit("playerAutoLeaveTriggered", this, mode); + if (this.manager.options.resume) this.manager.players.backup(this); return mode; } /** @@ -156,6 +157,7 @@ export class MoonlinkPlayer { this.autoPlay = mode; this.manager.emit("playerAutoPlayTriggered", this, mode); + if (this.manager.options.resume) this.manager.players.backup(this); return mode; } @@ -182,6 +184,7 @@ export class MoonlinkPlayer { this.connected = true; this.manager.emit("playerConnected", this); + return true; } @@ -235,6 +238,7 @@ export class MoonlinkPlayer { }); } this.manager.emit("playerRestarted", this); + if (this.manager.options.resume) this.manager.players.backup(this); } /** * Play the next track in the queue. @@ -292,6 +296,7 @@ export class MoonlinkPlayer { if (this.paused) return true; await this.updatePlaybackStatus(true); this.manager.emit("playerPaused", this); + if (this.manager.options.resume) this.manager.players.backup(this); return true; } @@ -303,6 +308,7 @@ export class MoonlinkPlayer { if (this.playing) return true; await this.updatePlaybackStatus(false); this.manager.emit("playerResume", this); + if (this.manager.options.resume) this.manager.players.backup(this); return true; } @@ -331,12 +337,14 @@ export class MoonlinkPlayer { track: { encoded: null } } }); + if (this.manager.options.resume) this.manager.players.backup(this); } this.manager.emit("playerStopped", this, this.current as MoonlinkTrack); this.manager.options?.destroyPlayersStopped && destroy ? this.destroy() : this.queue.clear(); + if (this.manager.options.resume) this.manager.players.backup(this); return true; } @@ -383,6 +391,7 @@ export class MoonlinkPlayer { this.stop(); return true; } + if (this.manager.options.resume) this.manager.players.backup(this); } /** @@ -411,6 +420,8 @@ export class MoonlinkPlayer { this.manager.emit("playerVolumeChanged", this, this.volume, percent); this.volume = percent; + + if (this.manager.options.resume) this.manager.players.backup(this); return percent; } @@ -443,6 +454,8 @@ export class MoonlinkPlayer { this.manager.emit("playerLoopSet", this, this.loop, mode); this.loop = mode; + if (this.manager.options.resume) this.manager.players.backup(this); + return mode; } @@ -509,7 +522,7 @@ export class MoonlinkPlayer { guildId: this.guildId, data: { position } }); - + if (this.manager.options.resume) this.manager.players.backup(this); return position; } @@ -533,7 +546,7 @@ export class MoonlinkPlayer { this.queue.all, shuffleStatus ); - + if (this.manager.options.resume) this.manager.players.backup(this); return shuffleStatus; } } diff --git a/src/@Managers/PlayerManager.ts b/src/@Managers/PlayerManager.ts index 8e3210a7..93cd2329 100644 --- a/src/@Managers/PlayerManager.ts +++ b/src/@Managers/PlayerManager.ts @@ -73,11 +73,9 @@ export class PlayerManager { if ( !this.cache[guildId] || (!this.voices && - ! - this.voices[guildId]?.token && - !this.voices[guildId]?.endpoint && - ! this.voices[guildId]?.sessionId - ) + !this.voices[guildId]?.token && + !this.voices[guildId]?.endpoint && + !this.voices[guildId]?.sessionId) ) { return false; } @@ -187,31 +185,27 @@ export class PlayerManager { return this.cache ?? null; } public backup(player): boolean { - const db = Structure.db; - let { guildId } = player; - const existingData = - db.get(`players.${guildId}`) || {}; - if ( - player.voiceChannel && - player.voiceChannel !== - (existingData.voiceChannel && existingData.voiceChannel) - ) { - existingData.voiceChannel = player.voiceChannel; - } - - if ( - player.textChannel && - player.textChannel !== - (existingData.textChannel && existingData.textChannel) - ) { - existingData.textChannel = player.textChannel; - } - if ( - existingData !== - (db.get(`players.${guildId}`) || {}) - ) { - db.set(`players.${guildId}`, existingData); - } + let { + guildId, + textChannel, + voiceChannel, + loop, + voiceRegion, + autoPlay, + autoLeave, + previous, + volume + } = player; + Structure.db.set(`players.${guildId}`, { + guildId, + textChannel, + voiceChannel, + loop, + autoPlay, + autoLeave, + previous, + volume + }); return true; } diff --git a/src/@Typings/index.ts b/src/@Typings/index.ts index c2bcab43..1c11f9ad 100644 --- a/src/@Typings/index.ts +++ b/src/@Typings/index.ts @@ -18,7 +18,9 @@ export interface createOptions { guildId: string; textChannel: string; voiceChannel: string; - autoPlay?: boolean | null; + autoPlay?: boolean; + autoLeave?: boolean; + loop?: number; volume?: number; node?: string; } @@ -135,7 +137,6 @@ export interface IOptions { resume?: boolean; plugins?: Plugin[]; http2?: boolean; - movePlayersToNextNode?: boolean; destroyPlayersStopped?: boolean; balancingPlayersByRegion?: boolean; previousTracksInArray?: boolean; @@ -196,6 +197,12 @@ export interface objectTrack { export interface PreviousInfosPlayer { voiceChannel?: string; textChannel?: string; + guildId?: string; + volume?: number; + autoPlay?: boolean; + autoLeave?: boolean; + previous?: object | MoonlinkTrack; + loop?: number; } export interface RestOptions { From aa4e2220becac6133eecb209b054c4f8662e2d25 Mon Sep 17 00:00:00 2001 From: * Date: Tue, 27 Feb 2024 11:21:35 -0400 Subject: [PATCH 10/16] fix deepscan --- dist/src/@Entities/MoonlinkPlayer.js | 4 ++-- dist/src/@Managers/PlayerManager.js | 9 ++++----- src/@Entities/MoonlinkPlayer.ts | 2 +- src/@Managers/PlayerManager.ts | 9 +++------ 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/dist/src/@Entities/MoonlinkPlayer.js b/dist/src/@Entities/MoonlinkPlayer.js index d8c38670..f5c79b44 100644 --- a/dist/src/@Entities/MoonlinkPlayer.js +++ b/dist/src/@Entities/MoonlinkPlayer.js @@ -257,10 +257,10 @@ class MoonlinkPlayer { } else { this.stop(); + if (this.manager.options.resume) + this.manager.players.backup(this); return true; } - if (this.manager.options.resume) - this.manager.players.backup(this); } async setVolume(percent) { if (typeof percent == "undefined" || isNaN(percent)) { diff --git a/dist/src/@Managers/PlayerManager.js b/dist/src/@Managers/PlayerManager.js index f619de00..4c7f57b2 100644 --- a/dist/src/@Managers/PlayerManager.js +++ b/dist/src/@Managers/PlayerManager.js @@ -44,12 +44,11 @@ class PlayerManager { } async attemptConnection(guildId) { if (!this.cache[guildId] || - (!this.voices && + (!this.voices || !this.voices[guildId]?.token && - !this.voices[guildId]?.endpoint && - !this.voices[guildId]?.sessionId)) { + !this.voices[guildId]?.endpoint && + !this.voices[guildId]?.sessionId)) return false; - } if (this._manager.options?.balancingPlayersByRegion) { const voiceRegion = this.voices[guildId]?.endpoint?.match(/([a-zA-Z-]+)\d+/)?.[1]; if (!this.cache[guildId].voiceRegion) { @@ -123,7 +122,7 @@ class PlayerManager { return this.cache ?? null; } backup(player) { - let { guildId, textChannel, voiceChannel, loop, voiceRegion, autoPlay, autoLeave, previous, volume } = player; + let { guildId, textChannel, voiceChannel, loop, autoPlay, autoLeave, previous, volume } = player; index_1.Structure.db.set(`players.${guildId}`, { guildId, textChannel, diff --git a/src/@Entities/MoonlinkPlayer.ts b/src/@Entities/MoonlinkPlayer.ts index 40e682fa..acf46cdf 100644 --- a/src/@Entities/MoonlinkPlayer.ts +++ b/src/@Entities/MoonlinkPlayer.ts @@ -389,9 +389,9 @@ export class MoonlinkPlayer { return false; } else { this.stop(); + if (this.manager.options.resume) this.manager.players.backup(this); return true; } - if (this.manager.options.resume) this.manager.players.backup(this); } /** diff --git a/src/@Managers/PlayerManager.ts b/src/@Managers/PlayerManager.ts index 93cd2329..937a8738 100644 --- a/src/@Managers/PlayerManager.ts +++ b/src/@Managers/PlayerManager.ts @@ -3,8 +3,7 @@ import { MoonlinkTrack, MoonlinkManager, createOptions, - Structure, - PreviousInfosPlayer + Structure } from "../../index"; export class PlayerManager { public _manager: MoonlinkManager; @@ -72,13 +71,12 @@ export class PlayerManager { public async attemptConnection(guildId: string): Promise { if ( !this.cache[guildId] || - (!this.voices && + (!this.voices || !this.voices[guildId]?.token && !this.voices[guildId]?.endpoint && !this.voices[guildId]?.sessionId) - ) { + ) return false; - } if (this._manager.options?.balancingPlayersByRegion) { const voiceRegion = @@ -190,7 +188,6 @@ export class PlayerManager { textChannel, voiceChannel, loop, - voiceRegion, autoPlay, autoLeave, previous, From b9ca1d2200082caadf4865cc63457631b2f55b54 Mon Sep 17 00:00:00 2001 From: * Date: Tue, 27 Feb 2024 20:33:25 -0400 Subject: [PATCH 11/16] fix --- dist/index.mjs | 17 -------------- dist/src/@Entities/MoonlinkNode.js | 2 +- dist/src/@Entities/MoonlinkPlayer.js | 4 ++++ dist/src/@Managers/PlayerManager.js | 29 ++++++++++++------------ dist/src/@Typings/index.d.ts | 1 + dist/src/@Utils/MoonlinkTrack.d.ts | 5 ++-- dist/src/@Utils/MoonlinkTrack.js | 21 +++++++++++------ src/@Entities/MoonlinkNode.ts | 7 +++--- src/@Entities/MoonlinkPlayer.ts | 5 +++- src/@Managers/PlayerManager.ts | 34 +++++++++++----------------- src/@Typings/index.ts | 1 + src/@Utils/MoonlinkTrack.ts | 24 ++++++++++++-------- 12 files changed, 74 insertions(+), 76 deletions(-) delete mode 100644 dist/index.mjs diff --git a/dist/index.mjs b/dist/index.mjs deleted file mode 100644 index ce350811..00000000 --- a/dist/index.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import mod from "./index.js"; - -export default mod; -export const MoonlinkDatabase = mod.MoonlinkDatabase; -export const MoonlinkFilters = mod.MoonlinkFilters; -export const MoonlinkManager = mod.MoonlinkManager; -export const MoonlinkNode = mod.MoonlinkNode; -export const MoonlinkPlayer = mod.MoonlinkPlayer; -export const MoonlinkQueue = mod.MoonlinkQueue; -export const MoonlinkRestFul = mod.MoonlinkRestFul; -export const MoonlinkTrack = mod.MoonlinkTrack; -export const NodeManager = mod.NodeManager; -export const PlayerManager = mod.PlayerManager; -export const Plugin = mod.Plugin; -export const Structure = mod.Structure; -export const makeRequest = mod.makeRequest; -export const version = mod.version; diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index 6c02d053..41054886 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -186,7 +186,7 @@ class MoonlinkNode { player.playing = true; player.connected = true; player.previous = previousInfosPlayer.previous; - const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); + const track = new (index_1.Structure.get("MoonlinkTrack"))().resolveQueueData(previousInfosPlayer.current); player.current = track; player.current.position = resumedPlayer.state.position; await player.restart(); diff --git a/dist/src/@Entities/MoonlinkPlayer.js b/dist/src/@Entities/MoonlinkPlayer.js index f5c79b44..1a463bde 100644 --- a/dist/src/@Entities/MoonlinkPlayer.js +++ b/dist/src/@Entities/MoonlinkPlayer.js @@ -189,6 +189,8 @@ class MoonlinkPlayer { volume: this.volume } }); + if (this.manager.options.resume) + this.manager.players.backup(this); return true; } async pause() { @@ -306,6 +308,8 @@ class MoonlinkPlayer { this.manager.players.delete(this.guildId); this.manager.emit("debug", "@Moonlink(Player) - Destroyed player " + this.guildId); this.manager.emit("playerDestroyed", this.guildId); + if (this.manager.options.resume) + this.manager.players.backup(this); return true; } validateNumberParam(param, paramName) { diff --git a/dist/src/@Managers/PlayerManager.js b/dist/src/@Managers/PlayerManager.js index 4c7f57b2..a7a3f088 100644 --- a/dist/src/@Managers/PlayerManager.js +++ b/dist/src/@Managers/PlayerManager.js @@ -44,10 +44,10 @@ class PlayerManager { } async attemptConnection(guildId) { if (!this.cache[guildId] || - (!this.voices || - !this.voices[guildId]?.token && - !this.voices[guildId]?.endpoint && - !this.voices[guildId]?.sessionId)) + !this.voices || + (!this.voices[guildId]?.token && + !this.voices[guildId]?.endpoint && + !this.voices[guildId]?.sessionId)) return false; if (this._manager.options?.balancingPlayersByRegion) { const voiceRegion = this.voices[guildId]?.endpoint?.match(/([a-zA-Z-]+)\d+/)?.[1]; @@ -122,21 +122,22 @@ class PlayerManager { return this.cache ?? null; } backup(player) { - let { guildId, textChannel, voiceChannel, loop, autoPlay, autoLeave, previous, volume } = player; - index_1.Structure.db.set(`players.${guildId}`, { - guildId, - textChannel, - voiceChannel, - loop, - autoPlay, - autoLeave, - previous, - volume + index_1.Structure.db.set(`players.${player.guildId}`, { + guildId: player.guildId, + textChannel: player.textChannel, + voiceChannel: player.voiceChannel, + loop: player.loop, + autoPlay: player.autoPlay, + autoLeave: player.autoLeave, + previous: player.previous, + volume: player.volume, + current: player.current }); return true; } delete(guildId) { delete this.cache[guildId]; + index_1.Structure.db.delete(`players.${guildId}`); } } exports.PlayerManager = PlayerManager; diff --git a/dist/src/@Typings/index.d.ts b/dist/src/@Typings/index.d.ts index 87e6d330..b3faba35 100644 --- a/dist/src/@Typings/index.d.ts +++ b/dist/src/@Typings/index.d.ts @@ -161,6 +161,7 @@ export interface PreviousInfosPlayer { autoLeave?: boolean; previous?: object | MoonlinkTrack; loop?: number; + current?: Record; } export interface RestOptions { guildId: string; diff --git a/dist/src/@Utils/MoonlinkTrack.d.ts b/dist/src/@Utils/MoonlinkTrack.d.ts index ee64aef0..0b50b8fd 100644 --- a/dist/src/@Utils/MoonlinkTrack.d.ts +++ b/dist/src/@Utils/MoonlinkTrack.d.ts @@ -14,8 +14,7 @@ export declare class MoonlinkTrack { artworkUrl: string; isrc: string; time?: number; - constructor(data: MoonlinkTrackOptions, requester?: string | any); + constructor(data?: MoonlinkTrackOptions, requester?: string | any); get calculateRealTimePosition(): number; - setPosition(data: number): this; - setTime(data: number): this; + resolveQueueData(data: any): void; } diff --git a/dist/src/@Utils/MoonlinkTrack.js b/dist/src/@Utils/MoonlinkTrack.js index 00e2486e..9c36a1ad 100644 --- a/dist/src/@Utils/MoonlinkTrack.js +++ b/dist/src/@Utils/MoonlinkTrack.js @@ -45,13 +45,20 @@ class MoonlinkTrack { } return this.position; } - setPosition(data) { - this.position = data; - return this; - } - setTime(data) { - this.time = data; - return this; + resolveQueueData(data) { + this.encoded = data.encoded; + this.title = data.title; + this.author = data.author; + this.url = data.url; + this.duration = data.duration; + this.position = data.position; + this.identifier = data.identifier; + this.isSeekable = Boolean(data.isSeekable); + this.isStream = Boolean(data.isStream); + this.sourceName = data.sourceName; + this.requester = data.requester; + this.artworkUrl = data.artworkUrl; + this.isrc = data.isrc; } } exports.MoonlinkTrack = MoonlinkTrack; diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index dd489733..ca3d0eb4 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -305,9 +305,10 @@ export class MoonlinkNode { player.playing = true; player.connected = true; player.previous = previousInfosPlayer.previous; - const track = new (Structure.get("MoonlinkTrack"))( - resumedPlayer.track - ); + const track = new (Structure.get( + "MoonlinkTrack" + ))().resolveQueueData(previousInfosPlayer.current); + //@ts-ignore player.current = track; player.current.position = resumedPlayer.state.position; await player.restart(); diff --git a/src/@Entities/MoonlinkPlayer.ts b/src/@Entities/MoonlinkPlayer.ts index acf46cdf..74450c1b 100644 --- a/src/@Entities/MoonlinkPlayer.ts +++ b/src/@Entities/MoonlinkPlayer.ts @@ -285,6 +285,7 @@ export class MoonlinkPlayer { volume: this.volume } }); + if (this.manager.options.resume) this.manager.players.backup(this); return true; } @@ -389,7 +390,7 @@ export class MoonlinkPlayer { return false; } else { this.stop(); - if (this.manager.options.resume) this.manager.players.backup(this); + if (this.manager.options.resume) this.manager.players.backup(this); return true; } } @@ -473,6 +474,8 @@ export class MoonlinkPlayer { "@Moonlink(Player) - Destroyed player " + this.guildId ); this.manager.emit("playerDestroyed", this.guildId); + + if (this.manager.options.resume) this.manager.players.backup(this); return true; } diff --git a/src/@Managers/PlayerManager.ts b/src/@Managers/PlayerManager.ts index 937a8738..3119a8d0 100644 --- a/src/@Managers/PlayerManager.ts +++ b/src/@Managers/PlayerManager.ts @@ -71,8 +71,8 @@ export class PlayerManager { public async attemptConnection(guildId: string): Promise { if ( !this.cache[guildId] || - (!this.voices || - !this.voices[guildId]?.token && + !this.voices || + (!this.voices[guildId]?.token && !this.voices[guildId]?.endpoint && !this.voices[guildId]?.sessionId) ) @@ -183,30 +183,22 @@ export class PlayerManager { return this.cache ?? null; } public backup(player): boolean { - let { - guildId, - textChannel, - voiceChannel, - loop, - autoPlay, - autoLeave, - previous, - volume - } = player; - Structure.db.set(`players.${guildId}`, { - guildId, - textChannel, - voiceChannel, - loop, - autoPlay, - autoLeave, - previous, - volume + Structure.db.set(`players.${player.guildId}`, { + guildId: player.guildId, + textChannel: player.textChannel, + voiceChannel: player.voiceChannel, + loop: player.loop, + autoPlay: player.autoPlay, + autoLeave: player.autoLeave, + previous: player.previous, + volume: player.volume, + current: player.current }); return true; } public delete(guildId): void { delete this.cache[guildId]; + Structure.db.delete(`players.${guildId}`); } } diff --git a/src/@Typings/index.ts b/src/@Typings/index.ts index 1c11f9ad..ee3e3134 100644 --- a/src/@Typings/index.ts +++ b/src/@Typings/index.ts @@ -203,6 +203,7 @@ export interface PreviousInfosPlayer { autoLeave?: boolean; previous?: object | MoonlinkTrack; loop?: number; + current?: Record; } export interface RestOptions { diff --git a/src/@Utils/MoonlinkTrack.ts b/src/@Utils/MoonlinkTrack.ts index 3b1e22a2..153f89b0 100644 --- a/src/@Utils/MoonlinkTrack.ts +++ b/src/@Utils/MoonlinkTrack.ts @@ -14,7 +14,7 @@ export class MoonlinkTrack { public artworkUrl: string; public isrc: string; public time?: number = 0; - constructor(data: MoonlinkTrackOptions, requester?: string | any) { + constructor(data?: MoonlinkTrackOptions, requester?: string | any) { this.encoded = data.encoded; this.title = data.info.title; this.author = data.info.author; @@ -48,13 +48,19 @@ export class MoonlinkTrack { return this.position; } - - public setPosition(data: number): this { - this.position = data; - return this; - } - public setTime(data: number): this { - this.time = data; - return this + public resolveQueueData(data) { + this.encoded = data.encoded; + this.title = data.title; + this.author = data.author; + this.url = data.url; + this.duration = data.duration; + this.position = data.position; + this.identifier = data.identifier; + this.isSeekable = Boolean(data.isSeekable); + this.isStream = Boolean(data.isStream); + this.sourceName = data.sourceName; + this.requester = data.requester; + this.artworkUrl = data.artworkUrl; + this.isrc = data.isrc; } } From 82e824a0f068410c539cc8ffa562d39d86cd9968 Mon Sep 17 00:00:00 2001 From: * Date: Wed, 28 Feb 2024 07:44:52 -0400 Subject: [PATCH 12/16] replace track --- dist/src/@Entities/MoonlinkNode.js | 3 ++- dist/src/@Entities/MoonlinkPlayer.js | 2 +- dist/src/@Typings/index.d.ts | 2 ++ src/@Entities/MoonlinkNode.ts | 3 ++- src/@Entities/MoonlinkPlayer.ts | 3 ++- src/@Typings/index.ts | 2 ++ 6 files changed, 11 insertions(+), 4 deletions(-) diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index 41054886..95ee1fbc 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -181,7 +181,8 @@ class MoonlinkNode { loop: previousInfosPlayer.loop, autoPlay: previousInfosPlayer.autoPlay, autoLeave: previousInfosPlayer.autoLeave, - node: this.identifier ?? this.host + node: this.identifier ?? this.host, + notBackup: true }); player.playing = true; player.connected = true; diff --git a/dist/src/@Entities/MoonlinkPlayer.js b/dist/src/@Entities/MoonlinkPlayer.js index 1a463bde..50877d6f 100644 --- a/dist/src/@Entities/MoonlinkPlayer.js +++ b/dist/src/@Entities/MoonlinkPlayer.js @@ -41,7 +41,7 @@ class MoonlinkPlayer { this.data = {}; this.node = this.manager.nodes.get(data.node); this.filters = new (index_1.Structure.get("MoonlinkFilters"))(this); - if (this.manager.options.resume) + if (!data.notBackup && this.manager.options.resume) this.manager.players.backup(this); } set(key, value) { diff --git a/dist/src/@Typings/index.d.ts b/dist/src/@Typings/index.d.ts index b3faba35..ae04806e 100644 --- a/dist/src/@Typings/index.d.ts +++ b/dist/src/@Typings/index.d.ts @@ -6,6 +6,7 @@ export interface createOptions { voiceChannel: string; autoPlay?: boolean; autoLeave?: boolean; + notBackup?: boolean; loop?: number; volume?: number; node?: string; @@ -194,6 +195,7 @@ export interface IPlayerData { shuffled?: boolean | null; loop?: number | null; volume?: number | null; + notBackup?: boolean; ping?: number; node?: string; } diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index ca3d0eb4..3d18864a 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -300,7 +300,8 @@ export class MoonlinkNode { loop: previousInfosPlayer.loop, autoPlay: previousInfosPlayer.autoPlay, autoLeave: previousInfosPlayer.autoLeave, - node: this.identifier ?? this.host + node: this.identifier ?? this.host, + notBackup: true }); player.playing = true; player.connected = true; diff --git a/src/@Entities/MoonlinkPlayer.ts b/src/@Entities/MoonlinkPlayer.ts index 74450c1b..806775d9 100644 --- a/src/@Entities/MoonlinkPlayer.ts +++ b/src/@Entities/MoonlinkPlayer.ts @@ -56,7 +56,8 @@ export class MoonlinkPlayer { this.node = this.manager.nodes.get(data.node); this.filters = new (Structure.get("MoonlinkFilters"))(this); - if (this.manager.options.resume) this.manager.players.backup(this); + if (!data.notBackup && this.manager.options.resume) + this.manager.players.backup(this); } /** diff --git a/src/@Typings/index.ts b/src/@Typings/index.ts index ee3e3134..adc8c374 100644 --- a/src/@Typings/index.ts +++ b/src/@Typings/index.ts @@ -20,6 +20,7 @@ export interface createOptions { voiceChannel: string; autoPlay?: boolean; autoLeave?: boolean; + notBackup?: boolean; loop?: number; volume?: number; node?: string; @@ -239,6 +240,7 @@ export interface IPlayerData { shuffled?: boolean | null; loop?: number | null; volume?: number | null; + notBackup?: boolean; ping?: number; node?: string; } From 31b4a4166171dc8a6634d8c00caf8db8179147bc Mon Sep 17 00:00:00 2001 From: * Date: Wed, 28 Feb 2024 11:00:20 -0400 Subject: [PATCH 13/16] fix --- dist/src/@Entities/MoonlinkNode.js | 2 +- src/@Entities/MoonlinkNode.ts | 2 +- testBot/index.js | 9 +++++---- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index 95ee1fbc..aebc9a35 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -187,7 +187,7 @@ class MoonlinkNode { player.playing = true; player.connected = true; player.previous = previousInfosPlayer.previous; - const track = new (index_1.Structure.get("MoonlinkTrack"))().resolveQueueData(previousInfosPlayer.current); + const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); player.current = track; player.current.position = resumedPlayer.state.position; await player.restart(); diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index 3d18864a..cd265ec9 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -308,7 +308,7 @@ export class MoonlinkNode { player.previous = previousInfosPlayer.previous; const track = new (Structure.get( "MoonlinkTrack" - ))().resolveQueueData(previousInfosPlayer.current); + ))(resumedPlayer.track) //@ts-ignore player.current = track; player.current.position = resumedPlayer.state.position; diff --git a/testBot/index.js b/testBot/index.js index 9f00f2ff..acbfb87b 100644 --- a/testBot/index.js +++ b/testBot/index.js @@ -42,15 +42,15 @@ for (const folder of commandFolders) { } client.moon = new MoonlinkManager( - [/*{ + [{ host: "541b2cbb-4e46-4064-b8de-53bbe5ac63dc-00-20h37tgfzow4w.kirk.replit.dev", password: "maybeiwasboring", secure: true, port: 443 - }/*{ + }, /* { host: "lavalink.jirayu.pw", port: 2333, password: "youshallnotpass", secure: false - }*/{ + }*/ { host: "localhost", port: 2333, secure: false, @@ -84,6 +84,7 @@ client.moon = new MoonlinkManager( }*/], { //http2: true, + resume: true, autoResume: true, resume: true, clientName: "Moonlink/Blio" @@ -128,4 +129,4 @@ client.on("error", (error) => { log(`[ Client ]: Client error: ${error}`); }); -client.login(require ("../config.json").token); +client.login(require ("../config.json").token); \ No newline at end of file From 2b8b6fb9cb2b2a50d9af40899ce7e8b2cac4b4fe Mon Sep 17 00:00:00 2001 From: * Date: Wed, 28 Feb 2024 12:38:58 -0400 Subject: [PATCH 14/16] fix encoded in another position --- .../database-960185850346471505.json | 34 +++++++++++++++++++ dist/src/@Entities/MoonlinkNode.js | 6 ++-- src/@Entities/MoonlinkNode.ts | 17 +++++++--- 3 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 dist/src/@Datastore/database-960185850346471505.json diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json new file mode 100644 index 00000000..0448468c --- /dev/null +++ b/dist/src/@Datastore/database-960185850346471505.json @@ -0,0 +1,34 @@ +{ + "sessionId": { + "NODELINK": "5yOVigdxaT5fCpVj" + }, + "players": { + "990369410344701964": { + "guildId": "990369410344701964", + "textChannel": "1209680553557885008", + "voiceChannel": "1089198118022680626", + "loop": 1, + "autoLeave": false, + "previous": [], + "volume": 80, + "current": { + "encoded": "QAAAvwMAKVF1YW5kbyB2b2PDqiBlbmNvbnRyYSB1bWEgTE9MSSBubyBEaXNjb3JkAARCcnVnAAAAAAAAzwgACy1KYTJobEZyYjY4AAEAK2h0dHBzOi8vd3d3LnlvdXR1YmUuY29tL3dhdGNoP3Y9LUphMmhsRnJiNjgBADRodHRwczovL2kueXRpbWcuY29tL3ZpLy1KYTJobEZyYjY4L21heHJlc2RlZmF1bHQuanBnAAAHeW91dHViZQAAAAAAAAAA", + "identifier": "-Ja2hlFrb68", + "title": "Quando você encontra uma LOLI no Discord", + "author": "Brug", + "url": "https://www.youtube.com/watch?v=-Ja2hlFrb68", + "duration": 53000, + "position": 0, + "isSeekable": true, + "isStream": false, + "sourceName": "youtube", + "artworkUrl": "https://i.ytimg.com/vi/-Ja2hlFrb68/maxresdefault.jpg", + "isrc": null, + "time": 0 + } + } + }, + "queue": { + "990369410344701964": [] + } +} \ No newline at end of file diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index aebc9a35..30e5f081 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -258,12 +258,14 @@ class MoonlinkNode { if (player.loop == 1) { await this.rest.update({ guildId: payload.guildId, - data: { track: { encoded: track.encoded } } + data: { track: { encoded: payload.track.encoded } } }); + if (this.resumed) + player.current = new (index_1.Structure.get("MoonlinkTrack"))(payload.track); return; } if (player.loop == 2) { - player.queue.add(player.current); + player.queue.add(new (index_1.Structure.get("MoonlinkTrack"))(payload.track)); if (!queue || queue.length === 0) return this._manager.emit("trackEnd", player, track, payload); player.play(); diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index cd265ec9..47a79250 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -306,9 +306,9 @@ export class MoonlinkNode { player.playing = true; player.connected = true; player.previous = previousInfosPlayer.previous; - const track = new (Structure.get( - "MoonlinkTrack" - ))(resumedPlayer.track) + const track = new (Structure.get("MoonlinkTrack"))( + resumedPlayer.track + ); //@ts-ignore player.current = track; player.current.position = resumedPlayer.state.position; @@ -383,12 +383,19 @@ export class MoonlinkNode { if (player.loop == 1) { await this.rest.update({ guildId: payload.guildId, - data: { track: { encoded: track.encoded } } + data: { track: { encoded: payload.track.encoded } } }); + if(this.resumed) player.current = new (Structure.get("MoonlinkTrack"))( + payload.track + ); return; } if (player.loop == 2) { - player.queue.add(player.current as MoonlinkTrack); + player.queue.add( + new (Structure.get("MoonlinkTrack"))( + payload.track + ) as MoonlinkTrack + ); if (!queue || queue.length === 0) return this._manager.emit( "trackEnd", From 9eb47dc76571f1a6a49526e08f8e12e1e4a4eb3b Mon Sep 17 00:00:00 2001 From: * Date: Wed, 28 Feb 2024 21:06:04 -0400 Subject: [PATCH 15/16] improve: doing a little cleaning --- dist/index.mjs | 17 ++++++++++ .../database-960185850346471505.json | 34 ------------------- dist/src/@Entities/MoonlinkNode.js | 15 ++++---- dist/src/@Managers/PlayerManager.js | 2 +- dist/src/@Typings/index.d.ts | 1 + package.json | 2 +- src/@Entities/MoonlinkNode.ts | 29 ++++++++++------ src/@Managers/PlayerManager.ts | 2 +- src/@Typings/index.ts | 1 + testBot/index.js | 1 - 10 files changed, 50 insertions(+), 54 deletions(-) create mode 100644 dist/index.mjs delete mode 100644 dist/src/@Datastore/database-960185850346471505.json diff --git a/dist/index.mjs b/dist/index.mjs new file mode 100644 index 00000000..ce350811 --- /dev/null +++ b/dist/index.mjs @@ -0,0 +1,17 @@ +import mod from "./index.js"; + +export default mod; +export const MoonlinkDatabase = mod.MoonlinkDatabase; +export const MoonlinkFilters = mod.MoonlinkFilters; +export const MoonlinkManager = mod.MoonlinkManager; +export const MoonlinkNode = mod.MoonlinkNode; +export const MoonlinkPlayer = mod.MoonlinkPlayer; +export const MoonlinkQueue = mod.MoonlinkQueue; +export const MoonlinkRestFul = mod.MoonlinkRestFul; +export const MoonlinkTrack = mod.MoonlinkTrack; +export const NodeManager = mod.NodeManager; +export const PlayerManager = mod.PlayerManager; +export const Plugin = mod.Plugin; +export const Structure = mod.Structure; +export const makeRequest = mod.makeRequest; +export const version = mod.version; diff --git a/dist/src/@Datastore/database-960185850346471505.json b/dist/src/@Datastore/database-960185850346471505.json deleted file mode 100644 index 0448468c..00000000 --- a/dist/src/@Datastore/database-960185850346471505.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "sessionId": { - "NODELINK": "5yOVigdxaT5fCpVj" - }, - "players": { - "990369410344701964": { - "guildId": "990369410344701964", - "textChannel": "1209680553557885008", - "voiceChannel": "1089198118022680626", - "loop": 1, - "autoLeave": false, - "previous": [], - "volume": 80, - "current": { - "encoded": "QAAAvwMAKVF1YW5kbyB2b2PDqiBlbmNvbnRyYSB1bWEgTE9MSSBubyBEaXNjb3JkAARCcnVnAAAAAAAAzwgACy1KYTJobEZyYjY4AAEAK2h0dHBzOi8vd3d3LnlvdXR1YmUuY29tL3dhdGNoP3Y9LUphMmhsRnJiNjgBADRodHRwczovL2kueXRpbWcuY29tL3ZpLy1KYTJobEZyYjY4L21heHJlc2RlZmF1bHQuanBnAAAHeW91dHViZQAAAAAAAAAA", - "identifier": "-Ja2hlFrb68", - "title": "Quando você encontra uma LOLI no Discord", - "author": "Brug", - "url": "https://www.youtube.com/watch?v=-Ja2hlFrb68", - "duration": 53000, - "position": 0, - "isSeekable": true, - "isStream": false, - "sourceName": "youtube", - "artworkUrl": "https://i.ytimg.com/vi/-Ja2hlFrb68/maxresdefault.jpg", - "isrc": null, - "time": 0 - } - } - }, - "queue": { - "990369410344701964": [] - } -} \ No newline at end of file diff --git a/dist/src/@Entities/MoonlinkNode.js b/dist/src/@Entities/MoonlinkNode.js index 30e5f081..3b3a4615 100644 --- a/dist/src/@Entities/MoonlinkNode.js +++ b/dist/src/@Entities/MoonlinkNode.js @@ -105,7 +105,8 @@ class MoonlinkNode { this.connect(); this._manager.emit("debug", `@Moonlink(Node) - We are trying to reconnect node ${this.identifier ?? this.host}, attempted number ${this.reconnectAttempts} `); - if (this.getAllPlayers.length) + if (this.getAllPlayers.length && + this._manager.options?.switchPlayersAnotherNode) this.movePlayers(); this.reconnectAttempts++; }, this.retryDelay); @@ -187,10 +188,12 @@ class MoonlinkNode { player.playing = true; player.connected = true; player.previous = previousInfosPlayer.previous; - const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); - player.current = track; - player.current.position = resumedPlayer.state.position; - await player.restart(); + if (resumedPlayer.track) { + const track = new (index_1.Structure.get("MoonlinkTrack"))(resumedPlayer.track); + player.current = track; + player.current.position = resumedPlayer.state.position; + await player.restart(); + } } this._manager.emit("nodeResumed", this, resumedPlayers); } @@ -228,7 +231,7 @@ class MoonlinkNode { case "TrackStartEvent": { let current = player.current; if (!current) - return; + current = new (index_1.Structure.get("MoonlinkTrack"))(payload.track); player.playing = true; player.paused = false; this._manager.emit("trackStart", player, current); diff --git a/dist/src/@Managers/PlayerManager.js b/dist/src/@Managers/PlayerManager.js index a7a3f088..2b50ea22 100644 --- a/dist/src/@Managers/PlayerManager.js +++ b/dist/src/@Managers/PlayerManager.js @@ -44,7 +44,7 @@ class PlayerManager { } async attemptConnection(guildId) { if (!this.cache[guildId] || - !this.voices || + !this.voices[guildId] || (!this.voices[guildId]?.token && !this.voices[guildId]?.endpoint && !this.voices[guildId]?.sessionId)) diff --git a/dist/src/@Typings/index.d.ts b/dist/src/@Typings/index.d.ts index ae04806e..052962d1 100644 --- a/dist/src/@Typings/index.d.ts +++ b/dist/src/@Typings/index.d.ts @@ -104,6 +104,7 @@ export interface IOptions { resume?: boolean; plugins?: Plugin[]; http2?: boolean; + switchPlayersAnotherNode?: boolean; destroyPlayersStopped?: boolean; balancingPlayersByRegion?: boolean; previousTracksInArray?: boolean; diff --git a/package.json b/package.json index 85d94e5b..416c69b6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "moonlink.js", - "version": "3.4.52", + "version": "3.5.4", "description": "Imagine a Music... 🌙✨ Welcome to Moonlink.js! We invite you to create your own music bot on Discord using Lavalink, in a simple and easy way! 🎶🤖", "keywords": [ "bot", diff --git a/src/@Entities/MoonlinkNode.ts b/src/@Entities/MoonlinkNode.ts index 47a79250..8c0cb3d5 100644 --- a/src/@Entities/MoonlinkNode.ts +++ b/src/@Entities/MoonlinkNode.ts @@ -188,7 +188,11 @@ export class MoonlinkNode { }, attempted number ${this.reconnectAttempts} ` ); - if (this.getAllPlayers.length) this.movePlayers(); + if ( + this.getAllPlayers.length && + this._manager.options?.switchPlayersAnotherNode + ) + this.movePlayers(); this.reconnectAttempts++; }, this.retryDelay); } @@ -306,13 +310,14 @@ export class MoonlinkNode { player.playing = true; player.connected = true; player.previous = previousInfosPlayer.previous; - const track = new (Structure.get("MoonlinkTrack"))( - resumedPlayer.track - ); - //@ts-ignore - player.current = track; + if (resumedPlayer.track) { + const track = new (Structure.get("MoonlinkTrack"))( + resumedPlayer.track + ); + player.current = track; player.current.position = resumedPlayer.state.position; await player.restart(); + } } this._manager.emit("nodeResumed", this, resumedPlayers); } @@ -350,7 +355,10 @@ export class MoonlinkNode { switch (payload.type) { case "TrackStartEvent": { let current = player.current; - if (!current) return; + if (!current) + current = new (Structure.get("MoonlinkTrack"))( + payload.track + ); player.playing = true; player.paused = false; this._manager.emit("trackStart", player, current); @@ -385,9 +393,10 @@ export class MoonlinkNode { guildId: payload.guildId, data: { track: { encoded: payload.track.encoded } } }); - if(this.resumed) player.current = new (Structure.get("MoonlinkTrack"))( - payload.track - ); + if (this.resumed) + player.current = new (Structure.get( + "MoonlinkTrack" + ))(payload.track); return; } if (player.loop == 2) { diff --git a/src/@Managers/PlayerManager.ts b/src/@Managers/PlayerManager.ts index 3119a8d0..74ee85fa 100644 --- a/src/@Managers/PlayerManager.ts +++ b/src/@Managers/PlayerManager.ts @@ -71,7 +71,7 @@ export class PlayerManager { public async attemptConnection(guildId: string): Promise { if ( !this.cache[guildId] || - !this.voices || + !this.voices[guildId] || (!this.voices[guildId]?.token && !this.voices[guildId]?.endpoint && !this.voices[guildId]?.sessionId) diff --git a/src/@Typings/index.ts b/src/@Typings/index.ts index adc8c374..fcf96d91 100644 --- a/src/@Typings/index.ts +++ b/src/@Typings/index.ts @@ -138,6 +138,7 @@ export interface IOptions { resume?: boolean; plugins?: Plugin[]; http2?: boolean; + switchPlayersAnotherNode?: boolean; destroyPlayersStopped?: boolean; balancingPlayersByRegion?: boolean; previousTracksInArray?: boolean; diff --git a/testBot/index.js b/testBot/index.js index acbfb87b..5449c875 100644 --- a/testBot/index.js +++ b/testBot/index.js @@ -86,7 +86,6 @@ client.moon = new MoonlinkManager( //http2: true, resume: true, autoResume: true, - resume: true, clientName: "Moonlink/Blio" }, (id, data) => { From 06f18dde421ae19a769a05cbb2770d4011d9ecf8 Mon Sep 17 00:00:00 2001 From: * Date: Wed, 28 Feb 2024 21:14:45 -0400 Subject: [PATCH 16/16] remove: attemptConnection --- dist/src/@Entities/MoonlinkPlayer.js | 1 - src/@Entities/MoonlinkPlayer.ts | 2 -- 2 files changed, 3 deletions(-) diff --git a/dist/src/@Entities/MoonlinkPlayer.js b/dist/src/@Entities/MoonlinkPlayer.js index 50877d6f..a5e46527 100644 --- a/dist/src/@Entities/MoonlinkPlayer.js +++ b/dist/src/@Entities/MoonlinkPlayer.js @@ -132,7 +132,6 @@ class MoonlinkPlayer { setDeaf: true, setMute: false }); - await this.manager.players.attemptConnection(this.guildId); if (!this.current && this.queue.size) { this.play(); return; diff --git a/src/@Entities/MoonlinkPlayer.ts b/src/@Entities/MoonlinkPlayer.ts index 806775d9..d5bb1b95 100644 --- a/src/@Entities/MoonlinkPlayer.ts +++ b/src/@Entities/MoonlinkPlayer.ts @@ -221,8 +221,6 @@ export class MoonlinkPlayer { setMute: false }); - await this.manager.players.attemptConnection(this.guildId); - if (!this.current && this.queue.size) { this.play(); return;