-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Structure.ts
364 lines (343 loc) · 12.3 KB
/
Structure.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { EventEmitter } from "node:events";
import { INode, Extendable, SortType, createOptions } from "../@Typings";
import {
MoonlinkManager,
MoonlinkRestFul,
MoonlinkPlayer,
MoonlinkFilters,
MoonlinkDatabase,
MoonlinkQueue,
MoonlinkNode,
MoonlinkTrack
} from "../../index";
export const State = {
READY: "READY",
CONNECTED: "CONNECTED",
CONNECTING: "CONNECTING",
DISCONNECTING: "DISCONNECTING",
DISCONNECTED: "DISCONNECTED",
RECONNECTING: "RECONNECTING",
AUTORESUMING: "AUTORESUMING",
RESUMING: "RESUMING",
MOVING: "MOVING"
};
export class Players {
public _manager: MoonlinkManager;
public map: Map<any, any>;
constructor() {
this.map = new Map();
}
public init(): void {
this._manager = Structure.manager;
this._manager.emit(
"debug",
"@Moonlink(Players) - Structure(Players) has been initialized, and assigned the value of the main class "
);
}
public handleVoiceServerUpdate(update: any, guildId: string): void {
const existingVoiceServer = this.map.get("voiceServer") || {};
existingVoiceServer[guildId] = { event: update };
this.map.set("voiceServer", existingVoiceServer);
this.attemptConnection(guildId);
}
public handlePlayerDisconnect(player: MoonlinkPlayer, guildId: string): void {
const players = this.map.get("players") || {};
this._manager.emit("playerDisconnect", player);
players[guildId] = {
...players[guildId],
connected: false,
voiceChannel: null,
playing: false,
};
Object.assign(player, { connected: false, voiceChannel: null, playing: false });
player.stop();
}
public handlePlayerMove(
player: MoonlinkPlayer,
newChannelId: string,
oldChannelId: string,
guildId: string
): void {
const players: any = this.map.get("players") || {};
this._manager.emit("playerMove", player, newChannelId, oldChannelId);
players[guildId] = {
...players[guildId],
voiceChannel: newChannelId
};
this.map.set("players", players);
player.voiceChannel = newChannelId;
}
public updateVoiceStates(guildId: string, update: any): void {
const voiceStates = this.map.get("voiceStates") || {};
voiceStates[guildId] = update;
this.map.set("voiceStates", voiceStates);
}
public async attemptConnection(guildId: string): Promise<boolean> {
const voiceServer = this.map.get("voiceServer") || {};
const voiceStates = this.map.get("voiceStates") || {};
const players = this.map.get("players") || {};
if (!players[guildId] || !voiceServer[guildId]) return false;
await this._manager.nodes.get(players[guildId].node).rest.update({
guildId,
data: {
voice: {
sessionId: voiceStates[guildId]?.session_id,
endpoint: voiceServer[guildId].event.endpoint,
token: voiceServer[guildId].event.token
}
}
});
return true;
}
public has(guildId: string): boolean {
return !!this.map.get("players")?.[guildId];
}
public get(guildId: string): MoonlinkPlayer | null {
if (!guildId && typeof guildId !== "string")
throw new Error(
'[ @Moonlink/Manager ]: "guildId" option in parameter to get player is empty or type is different from string'
);
if (!this.has(guildId)) return null;
return new (Structure.get("MoonlinkPlayer"))(
this.map.get("players")[guildId],
this._manager,
this.map
);
}
public create(data: createOptions): MoonlinkPlayer {
if (
typeof data !== "object" ||
!data.guildId ||
typeof data.guildId !== "string" ||
!data.textChannel ||
typeof data.textChannel !== "string" ||
!data.voiceChannel ||
typeof data.voiceChannel !== "string" ||
(data.autoPlay !== undefined &&
typeof data.autoPlay !== "boolean") ||
(data.node && typeof data.node !== "string")
) {
const missingParams = [];
if (!data.guildId || typeof data.guildId !== "string")
missingParams.push("guildId");
if (!data.textChannel || typeof data.textChannel !== "string")
missingParams.push("textChannel");
if (!data.voiceChannel || typeof data.voiceChannel !== "string")
missingParams.push("voiceChannel");
if (
data.autoPlay !== undefined &&
typeof data.autoPlay !== "boolean"
)
missingParams.push("autoPlay");
if (data.node && typeof data.node !== "string")
missingParams.push("node");
throw new Error(
`[ @Moonlink/Manager ]: Invalid or missing parameters for player creation: ${missingParams.join(
", "
)}`
);
}
if (this.has(data.guildId)) return this.get(data.guildId);
let players_map: Map<string, object> | object =
this.map.get("players") || {};
let nodeSorted = this._manager.nodes.sortByUsage(
`${
this._manager.options.sortNode
? this._manager.options.sortNode
: "players"
}`
)[0];
players_map[data.guildId] = {
guildId: data.guildId,
textChannel: data.textChannel,
voiceChannel: data.voiceChannel,
volume: data.volume || 80,
playing: false,
connected: false,
paused: false,
shuffled: false,
loop: null,
autoPlay: data.autoPlay !== undefined ? data.autoPlay : undefined,
node: data.node || nodeSorted?.identifier || nodeSorted?.host
};
this.map.set("players", players_map);
this._manager.emit(
"debug",
`@Moonlink(Players) - A server player was created (${data.guildId})`
);
this._manager.emit("playerCreated", data.guildId);
return new (Structure.get("MoonlinkPlayer"))(
players_map[data.guildId],
this._manager,
this.map
);
}
public get all(): Record<string, any> | null {
return this.map.get("players") ?? null;
}
}
export class Nodes {
public initiated: boolean = false;
public _manager: MoonlinkManager;
public map: Map<any, any>;
constructor() {
this.map = new Map();
}
public init(): void {
this._manager = Structure.manager;
this.check();
this._manager.emit(
"debug",
"@Moonlink(Nodes) - Structure(Nodes) was successfully initialized and assigned the value of the main class and checked the nodes"
);
this.initiated = true;
}
public check(): void {
if (!this._manager?._nodes)
throw new Error('@Moonlink(Nodes) - "nodes" option is empty');
if (this._manager?._nodes && !Array.isArray(this._manager?._nodes))
throw new Error(
'@Moonlink(Nodes) - the "nodes" option has to be in an array'
);
if (this._manager?._nodes && this._manager?._nodes.length == 0)
throw new Error(
'@Moonlink(Nodes) - there are no parameters with "node(s)" information in the object'
);
this._manager?._nodes.forEach(node => this.add(node));
}
public add(node: INode): void {
this._manager.emit(
"debug",
`@Moonlink(Nodes) - The node ${
node.host || node.identifier
} has been added, and is starting its initialization process`
);
const NodeInstance: MoonlinkNode = new (Structure.get("MoonlinkNode"))(
node
);
if (node.identifier) this.map.set(node.identifier, NodeInstance);
else this.map.set(node.host, NodeInstance);
return;
}
public remove(name: string): boolean {
if (!name) {
throw new Error('[ @Moonlink/Manager ]: option "name" is empty');
}
const removed = this.map.delete(name);
this._manager.emit(
"debug",
`@Moonlink(Nodes) - The node ${name} has been successfully deleted`
);
return removed;
}
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
);
if (connectedNodes.length == 0)
throw new TypeError(
"[ @Moonlink/Manager ]: No lavalink server connected"
);
switch (sortType) {
case "memory":
return this.sortNodesByMemoryUsage(connectedNodes);
case "cpuLavalink":
return this.sortNodesByLavalinkCpuLoad(connectedNodes);
case "cpuSystem":
return this.sortNodesBySystemCpuLoad(connectedNodes);
case "calls":
return this.sortNodesByCalls(connectedNodes);
case "playingPlayers":
return this.sortNodesByPlayingPlayers(connectedNodes);
case "players":
default:
return this.sortNodesByPlayers(connectedNodes);
}
}
private sortNodesByMemoryUsage(nodes: MoonlinkNode[]): MoonlinkNode[] {
return nodes.sort(
(a, b) =>
(a.stats?.memory?.used || 0) - (b.stats?.memory?.used || 0)
);
}
private sortNodesByLavalinkCpuLoad(nodes: MoonlinkNode[]): MoonlinkNode[] {
return nodes.sort(
(a, b) =>
(a.stats?.cpu?.lavalinkLoad || 0) -
(b.stats?.cpu?.lavalinkLoad || 0)
);
}
private sortNodesBySystemCpuLoad(nodes: MoonlinkNode[]): MoonlinkNode[] {
return nodes.sort(
(a, b) =>
(a.stats?.cpu?.systemLoad || 0) -
(b.stats?.cpu?.systemLoad || 0)
);
}
private sortNodesByCalls(nodes: MoonlinkNode[]): MoonlinkNode[] {
return nodes.sort((a, b) => a.calls - b.calls);
}
private sortNodesByPlayingPlayers(nodes: MoonlinkNode[]): MoonlinkNode[] {
return nodes.sort(
(a, b) =>
(a.stats?.playingPlayers || 0) - (b.stats?.playingPlayers || 0)
);
}
private sortNodesByPlayers(nodes: MoonlinkNode[]): MoonlinkNode[] {
return nodes.sort(
(a, b) => (a.stats?.players || 0) - (b.stats?.players || 0)
);
}
}
const structures: Extendable = {
MoonlinkManager,
MoonlinkRestFul,
MoonlinkPlayer,
MoonlinkFilters,
MoonlinkDatabase,
MoonlinkQueue,
MoonlinkNode,
MoonlinkTrack,
Players,
Nodes
};
export abstract class Structure {
public static manager: MoonlinkManager;
public static db: MoonlinkDatabase;
public static extend<K extends keyof Extendable, T extends Extendable[K]>(
name: K,
extender: (target: Extendable[K]) => T
): T {
if (!(name in structures)) {
throw new TypeError(`"${name}" is not a valid structure`);
}
const extended = extender(structures[name]);
structures[name] = extended;
return extended;
}
public static init(manager: MoonlinkManager): void {
this.manager = manager;
this.db = new (Structure.get("MoonlinkDatabase"))(manager.clientId);
this.manager.emit(
"debug",
`@Moonlink(Structure) - The main class and database are assigned to structure :)`
);
}
public static get<K extends keyof Extendable>(name: K): Extendable[K] {
const structure = structures[name];
if (!structure) {
throw new TypeError(`"${name}" structure must be provided.`);
}
return structure;
}
}
export class Plugin {
public load(manager: MoonlinkManager): void {}
}