Skip to content

Commit

Permalink
Fix: system (resume, autoResume, player status, movePlayer and others) (
Browse files Browse the repository at this point in the history
Ecliptia#88)

1. **Resume System Fix**: Addressed issues with the resume system,
ensuring its proper functionality.
   
2. **Refactoring for Better Performance**: Certain components were
refactored to enhance the overall efficiency of the package.

3. **Enhanced Functionality**:
- **AutoResume**: Implemented the autoResume feature to optimize the
user experience during music playback.
- **MovePlayer**: Added functionality to move music players within the
system.
- **Player Status Updates**: Ensured that music player statuses are
appropriately updated when a Node is destroyed.
- **New Parameters**: Introduced parameters allowing the retrieval of
all music players associated with a specific node, enhancing flexibility
and usability.

4. **Event Enhancements**:
- **NodeReady and NodeResumed Events**: Added NodeReady and NodeResumed
events to improve event.

5.
  • Loading branch information
1Lucas1apk authored Feb 29, 2024
2 parents 55f2cd9 + 06f18dd commit 7ce5b90
Show file tree
Hide file tree
Showing 27 changed files with 476 additions and 515 deletions.
1 change: 0 additions & 1 deletion dist/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
21 changes: 11 additions & 10 deletions dist/src/@Entities/MoonlinkNode.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// <reference types="node" />
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?;
Expand All @@ -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<string, any>;
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<string, any>;
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<object>;
connect(): Promise<any>;
open(): void;
private movePlayersToNextNode;
private reconnect;
protected close(code: number, reason: any): void;
protected message(data: Buffer | string): Promise<void>;
protected error(error: Error): void;
protected message(data: Buffer | string): Promise<void>;
protected handleEvent(payload: any): Promise<any>;
private movePlayers;
private get getAllPlayers();
}
239 changes: 92 additions & 147 deletions dist/src/@Entities/MoonlinkNode.js

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion dist/src/@Entities/MoonlinkPlayer.d.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -15,6 +15,7 @@ export declare class MoonlinkPlayer {
volume: number;
ping: number;
queue: MoonlinkQueue;
filters: MoonlinkFilters;
current: Record<string, any>;
previous: MoonlinkTrack[] | MoonlinkTrack | Record<string, any>;
data: Record<string, any>;
Expand Down
57 changes: 43 additions & 14 deletions dist/src/@Entities/MoonlinkPlayer.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class MoonlinkPlayer {
volume;
ping;
queue;
filters;
current;
previous;
data;
Expand All @@ -39,7 +40,8 @@ class MoonlinkPlayer {
this.previous = [];
this.data = {};
this.node = this.manager.nodes.get(data.node);
if (this.manager.options.resume)
this.filters = new (index_1.Structure.get("MoonlinkFilters"))(this);
if (!data.notBackup && this.manager.options.resume)
this.manager.players.backup(this);
}
set(key, value) {
Expand Down Expand Up @@ -81,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) {
Expand All @@ -89,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) {
Expand Down Expand Up @@ -122,28 +128,29 @@ class MoonlinkPlayer {
return true;
}
async restart() {
if (!this.current || !this.queue.size)
return;
this.connect({
setDeaf: true,
setMute: false
});
await this.manager.players.attemptConnection(this.guildId);
if (!this.current && this.queue.size) {
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);
if (this.manager.options.resume)
this.manager.players.backup(this);
}
async play(track) {
if (!track && !this.queue.size)
Expand Down Expand Up @@ -181,20 +188,26 @@ class MoonlinkPlayer {
volume: this.volume
}
});
if (this.manager.options.resume)
this.manager.players.backup(this);
return true;
}
async pause() {
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;
}
async resume() {
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;
}
async updatePlaybackStatus(paused) {
Expand All @@ -213,11 +226,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) {
Expand All @@ -241,6 +258,8 @@ class MoonlinkPlayer {
}
else {
this.stop();
if (this.manager.options.resume)
this.manager.players.backup(this);
return true;
}
}
Expand All @@ -257,6 +276,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) {
Expand All @@ -274,6 +295,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() {
Expand All @@ -284,6 +307,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) {
Expand All @@ -304,6 +329,8 @@ class MoonlinkPlayer {
guildId: this.guildId,
data: { position }
});
if (this.manager.options.resume)
this.manager.players.backup(this);
return position;
}
shuffle() {
Expand All @@ -313,6 +340,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;
}
}
Expand Down
4 changes: 3 additions & 1 deletion dist/src/@Managers/MoonlinkManager.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -52,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<this>;
search(options: string | SearchQuery): Promise<SearchResult>;
packetUpdate(packet: VoicePacket): void;
}
3 changes: 2 additions & 1 deletion dist/src/@Managers/MoonlinkManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ");
Expand All @@ -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;
Expand Down
11 changes: 0 additions & 11 deletions dist/src/@Managers/NodeManager.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
15 changes: 2 additions & 13 deletions dist/src/@Managers/NodeManager.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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"
};
40 changes: 17 additions & 23 deletions dist/src/@Managers/PlayerManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,17 @@ 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] ||
(!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];
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) {
Expand Down Expand Up @@ -123,27 +122,22 @@ 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);
}
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;
Loading

0 comments on commit 7ce5b90

Please sign in to comment.