ziplayer 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/{AI-Guide.md → AGENTS.md} +717 -624
  2. package/README.md +658 -526
  3. package/dist/extensions/BaseExtension.d.ts +10 -1
  4. package/dist/extensions/BaseExtension.d.ts.map +1 -1
  5. package/dist/extensions/BaseExtension.js +27 -1
  6. package/dist/extensions/BaseExtension.js.map +1 -1
  7. package/dist/extensions/index.d.ts.map +1 -1
  8. package/dist/extensions/index.js +24 -6
  9. package/dist/extensions/index.js.map +1 -1
  10. package/dist/plugins/index.d.ts.map +1 -1
  11. package/dist/plugins/index.js +105 -51
  12. package/dist/plugins/index.js.map +1 -1
  13. package/dist/structures/Player.d.ts +90 -15
  14. package/dist/structures/Player.d.ts.map +1 -1
  15. package/dist/structures/Player.js +487 -81
  16. package/dist/structures/Player.js.map +1 -1
  17. package/dist/structures/PlayerManager.d.ts +70 -6
  18. package/dist/structures/PlayerManager.d.ts.map +1 -1
  19. package/dist/structures/PlayerManager.js +184 -19
  20. package/dist/structures/PlayerManager.js.map +1 -1
  21. package/dist/structures/Queue.d.ts +19 -0
  22. package/dist/structures/Queue.d.ts.map +1 -1
  23. package/dist/structures/Queue.js +21 -0
  24. package/dist/structures/Queue.js.map +1 -1
  25. package/dist/types/extension.d.ts +3 -0
  26. package/dist/types/extension.d.ts.map +1 -1
  27. package/dist/types/index.d.ts +69 -2
  28. package/dist/types/index.d.ts.map +1 -1
  29. package/dist/types/index.js +13 -0
  30. package/dist/types/index.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/extensions/BaseExtension.ts +31 -1
  33. package/src/extensions/index.ts +30 -7
  34. package/src/plugins/index.ts +137 -54
  35. package/src/structures/Player.ts +2937 -2457
  36. package/src/structures/PlayerManager.ts +916 -725
  37. package/src/structures/Queue.ts +621 -599
  38. package/src/types/extension.ts +3 -0
  39. package/src/types/index.ts +80 -2
@@ -1,725 +1,916 @@
1
- import { EventEmitter } from "events";
2
- import { Player } from "./Player";
3
- import { PlayerManagerOptions, PlayerOptions, Track, SourcePlugin, SearchResult, ManagerEvents, PlayerStats } from "../types";
4
- import type { BaseExtension } from "../extensions";
5
- import { withTimeout } from "../utils/timeout";
6
-
7
- const GLOBAL_MANAGER_KEY: symbol = Symbol.for("ziplayer.PlayerManager.instance");
8
-
9
- export const getGlobalManager = (): PlayerManager | null => {
10
- try {
11
- const instance = (globalThis as any)[GLOBAL_MANAGER_KEY];
12
- if (!instance) {
13
- return null;
14
- }
15
- return instance as PlayerManager;
16
- } catch (error) {
17
- console.error("[PlayerManager] Error getting global instance:", error);
18
- return null;
19
- }
20
- };
21
-
22
- const setGlobalManager = (instance: PlayerManager): void => {
23
- try {
24
- (globalThis as any)[GLOBAL_MANAGER_KEY] = instance;
25
- } catch (error) {
26
- console.error("[PlayerManager] Error setting global instance:", error);
27
- }
28
- };
29
-
30
- export declare interface PlayerManager {
31
- on<K extends keyof ManagerEvents>(event: K, listener: (...args: ManagerEvents[K]) => void): this;
32
- emit<K extends keyof ManagerEvents>(event: K, ...args: ManagerEvents[K]): boolean;
33
- }
34
-
35
- interface ManagerCacheEntry<T> {
36
- data: T;
37
- timestamp: number;
38
- expiresAt: number;
39
- }
40
-
41
- /**
42
- * The main class for managing players across multiple Discord guilds.
43
- *
44
- * @example
45
- * // Basic setup with plugins and extensions
46
- * const manager = new PlayerManager({
47
- * plugins: [
48
- * new YouTubePlugin(),
49
- * new SoundCloudPlugin(),
50
- * new SpotifyPlugin(),
51
- * new TTSPlugin({ defaultLang: "en" })
52
- * ],
53
- * extensions: [
54
- * new voiceExt(null, { lang: "en-US" }),
55
- * new lavalinkExt(null, {
56
- * nodes: [{ host: "localhost", port: 2333, password: "youshallnotpass" }]
57
- * })
58
- * ],
59
- * extractorTimeout: 10000,
60
- * autoCleanup: true,
61
- * cleanupInterval: 60000
62
- * });
63
- *
64
- * // Create a player for a guild
65
- * const player = await manager.create(guildId, {
66
- * tts: { interrupt: true, volume: 1 },
67
- * leaveOnEnd: true,
68
- * leaveTimeout: 30000
69
- * });
70
- *
71
- * // Get existing player
72
- * const existingPlayer = manager.get(guildId);
73
- * if (existingPlayer) {
74
- * await existingPlayer.play("Never Gonna Give You Up", userId);
75
- * }
76
- */
77
- export class PlayerManager extends EventEmitter {
78
- private static instance: PlayerManager | null = null;
79
- private players: Map<string, Player> = new Map();
80
- private searchCache: Map<string, ManagerCacheEntry<SearchResult>>;
81
- private readonly SEARCH_CACHE_TTL = 60 * 1000; // 1 minute
82
- private readonly MAX_CACHE_SIZE = 100;
83
- private cleanupInterval: NodeJS.Timeout | null = null;
84
- private statsInterval: NodeJS.Timeout | null = null;
85
-
86
- static async default(opt?: PlayerOptions): Promise<Player> {
87
- let globaldef = getGlobalManager();
88
- if (!globaldef) {
89
- globaldef = new PlayerManager({});
90
- }
91
- return await globaldef.create("default", opt);
92
- }
93
-
94
- private plugins: SourcePlugin[];
95
- private extensions: any[];
96
- private B_debug: boolean = false;
97
- private extractorTimeout: number = 10000;
98
- private autoCleanup: boolean = true;
99
- private cleanupTimeout: number = 60000; // 1 minute
100
- private enableSearchCache: boolean = true;
101
-
102
- private debug(message?: any, ...optionalParams: any[]): void {
103
- if (this.listenerCount("debug") > 0) {
104
- this.emit("debug", `[PlayerManager] ${message}`, ...optionalParams);
105
- if (!this.B_debug) {
106
- this.B_debug = true;
107
- }
108
- }
109
- }
110
-
111
- constructor(options: PlayerManagerOptions = {}) {
112
- super();
113
- this.plugins = [];
114
- this.searchCache = new Map();
115
-
116
- // Initialize plugins
117
- const provided = options.plugins || [];
118
- for (const p of provided as any[]) {
119
- try {
120
- if (p && typeof p === "object") {
121
- this.plugins.push(p as SourcePlugin);
122
- } else if (typeof p === "function") {
123
- const instance = new (p as any)();
124
- this.plugins.push(instance as SourcePlugin);
125
- }
126
- this.debug(`Registered plugin: ${p.name || "unnamed"}`);
127
- } catch (e) {
128
- this.debug(`Failed to init plugin:`, e);
129
- }
130
- }
131
-
132
- this.extensions = options.extensions || [];
133
- this.extractorTimeout = options.extractorTimeout ?? 10000;
134
- this.autoCleanup = options.autoCleanup ?? true;
135
- this.cleanupTimeout = options.cleanupInterval ?? 60000;
136
- this.enableSearchCache = options.enableSearchCache ?? true;
137
-
138
- // Setup auto cleanup
139
- if (this.autoCleanup) {
140
- this.startAutoCleanup();
141
- }
142
-
143
- // Setup stats collection (optional)
144
- if (options.enableStatsCollection) {
145
- this.startStatsCollection();
146
- }
147
-
148
- setGlobalManager(this);
149
- this.debug(`Initialized with ${this.plugins.length} plugins, ${this.extensions.length} extensions`);
150
- }
151
-
152
- private withTimeout<T>(promise: Promise<T>, message: string): Promise<T> {
153
- const timeout = this.extractorTimeout;
154
- return Promise.race([promise, new Promise<never>((_, reject) => setTimeout(() => reject(new Error(message)), timeout))]);
155
- }
156
-
157
- private resolveGuildId(guildOrId: string | { id: string }): string {
158
- if (typeof guildOrId === "string") return guildOrId;
159
- if (guildOrId && typeof guildOrId === "object" && "id" in guildOrId) return guildOrId.id;
160
- throw new Error("Invalid guild or guildId provided.");
161
- }
162
-
163
- private getSearchCacheKey(query: string): string {
164
- return query.toLowerCase().trim();
165
- }
166
-
167
- private getCachedSearch(query: string): SearchResult | null {
168
- if (!this.enableSearchCache) return null;
169
-
170
- const key = this.getSearchCacheKey(query);
171
- const cached = this.searchCache.get(key);
172
-
173
- if (cached && Date.now() < cached.expiresAt) {
174
- this.debug(`[Cache] Search hit for: ${query}`);
175
- return cached.data;
176
- }
177
-
178
- if (cached) {
179
- this.searchCache.delete(key);
180
- }
181
-
182
- return null;
183
- }
184
-
185
- private setCachedSearch(query: string, result: SearchResult): void {
186
- if (!this.enableSearchCache) return;
187
-
188
- // Clean up old entries if cache is too large
189
- if (this.searchCache.size >= this.MAX_CACHE_SIZE) {
190
- const oldest = Array.from(this.searchCache.entries()).sort((a, b) => a[1].timestamp - b[1].timestamp)[0];
191
- if (oldest) this.searchCache.delete(oldest[0]);
192
- }
193
-
194
- const key = this.getSearchCacheKey(query);
195
- this.searchCache.set(key, {
196
- data: result,
197
- timestamp: Date.now(),
198
- expiresAt: Date.now() + this.SEARCH_CACHE_TTL,
199
- });
200
- this.debug(`[Cache] Search stored for: ${query}`);
201
- }
202
-
203
- private clearExpiredCache(): void {
204
- const now = Date.now();
205
- let expiredCount = 0;
206
-
207
- for (const [key, entry] of this.searchCache) {
208
- if (now >= entry.expiresAt) {
209
- this.searchCache.delete(key);
210
- expiredCount++;
211
- }
212
- }
213
-
214
- if (expiredCount > 0) {
215
- this.debug(`[Cache] Cleared ${expiredCount} expired search entries`);
216
- }
217
- }
218
-
219
- private startAutoCleanup(): void {
220
- if (this.cleanupInterval) {
221
- clearInterval(this.cleanupInterval);
222
- }
223
-
224
- this.cleanupInterval = setInterval(() => {
225
- this.cleanupInactivePlayers();
226
- this.clearExpiredCache();
227
- }, this.cleanupTimeout);
228
-
229
- this.debug(`Auto-cleanup started with interval: ${this.cleanupTimeout}ms`);
230
- }
231
-
232
- private startStatsCollection(): void {
233
- if (this.statsInterval) {
234
- clearInterval(this.statsInterval);
235
- }
236
-
237
- this.statsInterval = setInterval(() => {
238
- const stats = this.getStats();
239
- this.emit("stats", stats);
240
- }, 30000); // Every 30 seconds
241
- }
242
-
243
- private cleanupInactivePlayers(): void {
244
- let cleanedCount = 0;
245
-
246
- for (const [guildId, player] of this.players) {
247
- // Clean up players that are not playing and not connected
248
- if (!player.isPlaying && !player.connection && player.queue.isEmpty) {
249
- const idleTime = Date.now() - (player as any)._lastActivity || Date.now();
250
- if (idleTime > this.cleanupTimeout) {
251
- this.debug(`Cleaning up inactive player for guild: ${guildId}`);
252
- player.destroy();
253
- this.players.delete(guildId);
254
- cleanedCount++;
255
- }
256
- }
257
- }
258
-
259
- if (cleanedCount > 0) {
260
- this.debug(`Cleaned up ${cleanedCount} inactive players`);
261
- }
262
- }
263
-
264
- /**
265
- * Create a new player for a guild
266
- *
267
- * @param {string | {id: string}} guildOrId - Guild ID or guild object
268
- * @param {PlayerOptions} options - Player configuration options
269
- * @returns {Promise<Player>} The created player instance
270
- */
271
- async create(guildOrId: string | { id: string }, options?: PlayerOptions): Promise<Player> {
272
- const guildId = this.resolveGuildId(guildOrId);
273
-
274
- if (this.players.has(guildId)) {
275
- this.debug(`Player already exists for guildId: ${guildId}, returning existing`);
276
- return this.players.get(guildId)!;
277
- }
278
-
279
- this.debug(`Creating player for guildId: ${guildId}`);
280
- const player = new Player(guildId, options, this);
281
-
282
- // Add all registered plugins
283
- this.plugins.forEach((plugin) => player.addPlugin(plugin));
284
-
285
- // Activate extensions
286
- let extsToActivate: any[] = [];
287
- const optExts = (options as any)?.extensions as any[] | string[] | undefined;
288
-
289
- if (Array.isArray(optExts)) {
290
- if (optExts.length === 0) {
291
- extsToActivate = [];
292
- } else if (typeof optExts[0] === "string") {
293
- const wanted = new Set(optExts as string[]);
294
- extsToActivate = this.extensions.filter((ext) => {
295
- const name = typeof ext === "function" ? ext.name : ext?.name;
296
- return !!name && wanted.has(name);
297
- });
298
- } else {
299
- extsToActivate = optExts;
300
- }
301
- } else {
302
- // Use all extensions by default
303
- extsToActivate = this.extensions;
304
- }
305
-
306
- for (const ext of extsToActivate) {
307
- let instance = ext;
308
- if (typeof ext === "function") {
309
- try {
310
- instance = new ext(player);
311
- } catch (e) {
312
- this.debug(`Extension constructor error for ${ext.name}:`, e);
313
- continue;
314
- }
315
- }
316
-
317
- if (instance && typeof instance === "object") {
318
- const extInstance = instance as BaseExtension;
319
- if ("player" in extInstance && !extInstance.player) extInstance.player = player;
320
- player.attachExtension(extInstance);
321
-
322
- if (typeof extInstance.active === "function") {
323
- let activated: boolean | void = true;
324
- try {
325
- activated = await withTimeout(
326
- Promise.resolve(extInstance.active({ manager: this, player })),
327
- player.options.extractorTimeout ?? 15000,
328
- `Extension ${extInstance?.name} activation timed out`,
329
- );
330
- this.debug(`Extension ${extInstance?.name} active check returned: ${activated}`);
331
- } catch (e) {
332
- activated = false;
333
- this.debug(`Extension activation error for ${extInstance?.name}:`, e);
334
- }
335
-
336
- if (activated === false) {
337
- player.detachExtension(extInstance);
338
- continue;
339
- }
340
- }
341
- }
342
- }
343
-
344
- // Forward all player events to manager
345
- this.setupEventForwarding(player, guildId);
346
-
347
- // Mark last activity
348
- (player as any)._lastActivity = Date.now();
349
-
350
- this.players.set(guildId, player);
351
- this.debug(`Player created for guildId: ${guildId}`);
352
- return player;
353
- }
354
-
355
- private setupEventForwarding(player: Player, guildId: string): void {
356
- const forwardEvents = {
357
- willPlay: "willPlay",
358
- trackStart: "trackStart",
359
- trackEnd: "trackEnd",
360
- queueEnd: "queueEnd",
361
- playerError: "playerError",
362
- connectionError: "connectionError",
363
- volumeChange: "volumeChange",
364
- queueAdd: "queueAdd",
365
- queueAddList: "queueAddList",
366
- queueRemove: "queueRemove",
367
- playerPause: "playerPause",
368
- playerResume: "playerResume",
369
- playerStop: "playerStop",
370
- ttsStart: "ttsStart",
371
- ttsEnd: "ttsEnd",
372
- streamError: "streamError",
373
- } as const satisfies Record<string, keyof ManagerEvents>;
374
-
375
- for (const [sourceEvent, targetEvent] of Object.entries(forwardEvents) as [
376
- keyof typeof forwardEvents,
377
- keyof ManagerEvents,
378
- ][]) {
379
- player.on(sourceEvent, (...args: any[]) => {
380
- if (sourceEvent === "trackStart") {
381
- player._lastActivity = Date.now();
382
- }
383
-
384
- (this.emit as any)(targetEvent, player, ...args);
385
- });
386
- }
387
-
388
- player.on("playerDestroy", () => {
389
- this.emit("playerDestroy", player);
390
-
391
- this.players.delete(guildId);
392
-
393
- this.debug(`Player destroyed for guildId: ${guildId}`);
394
- });
395
-
396
- player.on("debug", (...args) => {
397
- if (this.listenerCount("debug") > 0) {
398
- this.emit("debug", ...args);
399
- }
400
- });
401
- }
402
- /**
403
- * Get an existing player for a guild
404
- *
405
- * @param {string | {id: string}} guildOrId - Guild ID or guild object
406
- * @returns {Player | undefined} The player instance or undefined if not found
407
- */
408
- get(guildOrId: string | { id: string }): Player | undefined {
409
- const guildId = this.resolveGuildId(guildOrId);
410
- const player = this.players.get(guildId);
411
- if (player) {
412
- (player as any)._lastActivity = Date.now();
413
- }
414
- return player;
415
- }
416
-
417
- /**
418
- * Get an existing player for a guild (alias for get)
419
- */
420
- getPlayer(guildOrId: string | { id: string }): Player | undefined {
421
- return this.get(guildOrId);
422
- }
423
-
424
- /**
425
- * Get all players
426
- *
427
- * @returns {Player[]} All player instances
428
- */
429
- getAll(): Player[] {
430
- return Array.from(this.players.values());
431
- }
432
-
433
- /**
434
- * Alias for getAll
435
- */
436
- getall(): Player[] {
437
- return this.getAll();
438
- }
439
-
440
- /**
441
- * Get players by filter
442
- *
443
- * @param {(player: Player) => boolean} filter - Filter function
444
- * @returns {Player[]} Filtered player instances
445
- */
446
- getPlayersByFilter(filter: (player: Player) => boolean): Player[] {
447
- return this.getAll().filter(filter);
448
- }
449
-
450
- /**
451
- * Get players in a voice channel
452
- *
453
- * @param {string} channelId - Voice channel ID
454
- * @returns {Player[]} Players in the channel
455
- */
456
- getPlayersInChannel(channelId: string): Player[] {
457
- return this.getAll().filter((p) => p.connection?.joinConfig.channelId === channelId);
458
- }
459
-
460
- /**
461
- * Destroy a player and clean up resources
462
- *
463
- * @param {string | {id: string}} guildOrId - Guild ID or guild object
464
- * @returns {boolean} True if player was destroyed, false if not found
465
- */
466
- delete(guildOrId: string | { id: string }): boolean {
467
- const guildId = this.resolveGuildId(guildOrId);
468
- const player = this.players.get(guildId);
469
-
470
- if (player) {
471
- this.debug(`Deleting player for guildId: ${guildId}`);
472
- player.destroy();
473
- return true;
474
- }
475
- return false;
476
- }
477
-
478
- /**
479
- * Destroy multiple players by filter
480
- *
481
- * @param {(player: Player) => boolean} filter - Filter function
482
- * @returns {number} Number of players destroyed
483
- */
484
- deleteWhere(filter: (player: Player) => boolean): number {
485
- const toDelete = this.getPlayersByFilter(filter);
486
- let count = 0;
487
-
488
- for (const player of toDelete) {
489
- const guildId = player.guildId;
490
- player.destroy();
491
- this.players.delete(guildId);
492
- count++;
493
- }
494
-
495
- if (count > 0) {
496
- this.debug(`Deleted ${count} players by filter`);
497
- }
498
- return count;
499
- }
500
-
501
- /**
502
- * Check if a player exists for a guild
503
- *
504
- * @param {string | {id: string}} guildOrId - Guild ID or guild object
505
- * @returns {boolean} True if player exists
506
- */
507
- has(guildOrId: string | { id: string }): boolean {
508
- const guildId = this.resolveGuildId(guildOrId);
509
- return this.players.has(guildId);
510
- }
511
-
512
- /**
513
- * Get number of players
514
- */
515
- get size(): number {
516
- return this.players.size;
517
- }
518
-
519
- /**
520
- * Check if debug is enabled
521
- */
522
- get debugEnabled(): boolean {
523
- return this.B_debug;
524
- }
525
-
526
- /**
527
- * Get manager statistics
528
- *
529
- * @returns {PlayerStats} Statistics about players
530
- */
531
- getStats(): PlayerStats {
532
- let activePlayers = 0;
533
- let pausedPlayers = 0;
534
- let connectedPlayers = 0;
535
- let totalTracksInQueue = 0;
536
-
537
- for (const player of this.players.values()) {
538
- if (player.isPlaying) activePlayers++;
539
- if (player.isPaused) pausedPlayers++;
540
- if (player.connection) connectedPlayers++;
541
- totalTracksInQueue += player.queueSize;
542
- }
543
-
544
- return {
545
- totalPlayers: this.players.size,
546
- activePlayers,
547
- pausedPlayers,
548
- connectedPlayers,
549
- totalTracksInQueue,
550
- };
551
- }
552
-
553
- /**
554
- * Broadcast an action to all players
555
- *
556
- * @param {string} action - Action to perform
557
- * @param {...any[]} args - Arguments for the action
558
- * @example
559
- * manager.broadcast("setVolume", 50);
560
- * manager.broadcast("pause");
561
- */
562
- broadcast(action: string, ...args: any[]): void {
563
- for (const player of this.players.values()) {
564
- if (typeof (player as any)[action] === "function") {
565
- try {
566
- (player as any)[action](...args);
567
- } catch (error) {
568
- this.debug(`Error broadcasting ${action} to ${player.guildId}:`, error);
569
- }
570
- }
571
- }
572
- }
573
-
574
- /**
575
- * Destroy all players and clean up
576
- */
577
- destroy(): void {
578
- this.debug(`Destroying all players`);
579
-
580
- // Stop cleanup intervals
581
- if (this.cleanupInterval) {
582
- clearInterval(this.cleanupInterval);
583
- this.cleanupInterval = null;
584
- }
585
-
586
- if (this.statsInterval) {
587
- clearInterval(this.statsInterval);
588
- this.statsInterval = null;
589
- }
590
-
591
- // Destroy all players
592
- for (const player of this.players.values()) {
593
- player.destroy();
594
- }
595
-
596
- this.players.clear();
597
- this.searchCache.clear();
598
- this.removeAllListeners();
599
- this.debug(`PlayerManager destroyed`);
600
- }
601
-
602
- /**
603
- * Search using registered plugins without creating a Player.
604
- *
605
- * @param {string} query - The query to search for
606
- * @param {string} requestedBy - The user ID who requested the search
607
- * @returns {Promise<SearchResult>} The search result
608
- */
609
- async search(query: string, requestedBy: string): Promise<SearchResult> {
610
- this.debug(`Search called with query: ${query}, requestedBy: ${requestedBy}`);
611
-
612
- // Check cache first
613
- const cached = this.getCachedSearch(query);
614
- if (cached) {
615
- return cached;
616
- }
617
-
618
- const plugin = this.plugins.find((p) => p.canHandle(query));
619
- if (!plugin) {
620
- this.debug(`No plugin found to handle: ${query}`);
621
- throw new Error(`No plugin found to handle: ${query}`);
622
- }
623
-
624
- try {
625
- const result = await this.withTimeout(plugin.search(query, requestedBy), "Search operation timed out");
626
- this.setCachedSearch(query, result);
627
- return result;
628
- } catch (error) {
629
- this.debug(`Search error:`, error);
630
- throw error as Error;
631
- }
632
- }
633
-
634
- /**
635
- * Clear search cache
636
- */
637
- clearSearchCache(): void {
638
- const size = this.searchCache.size;
639
- this.searchCache.clear();
640
- this.debug(`Cleared ${size} search cache entries`);
641
- }
642
-
643
- /**
644
- * Register a plugin after initialization
645
- *
646
- * @param {SourcePlugin} plugin - Plugin to register
647
- */
648
- registerPlugin(plugin: SourcePlugin): void {
649
- this.plugins.push(plugin);
650
- this.debug(`Registered plugin: ${plugin.name}`);
651
-
652
- // Register plugin with all existing players
653
- for (const player of this.players.values()) {
654
- player.addPlugin(plugin);
655
- }
656
- }
657
-
658
- /**
659
- * Unregister a plugin
660
- *
661
- * @param {string} name - Plugin name to unregister
662
- * @returns {boolean} True if plugin was unregistered
663
- */
664
- unregisterPlugin(name: string): boolean {
665
- const index = this.plugins.findIndex((p) => p.name === name);
666
- if (index === -1) return false;
667
-
668
- this.plugins.splice(index, 1);
669
- this.debug(`Unregistered plugin: ${name}`);
670
-
671
- // Note: Cannot easily remove plugins from existing players
672
- return true;
673
- }
674
-
675
- /**
676
- * Get all registered plugins
677
- */
678
- getPlugins(): SourcePlugin[] {
679
- return [...this.plugins];
680
- }
681
-
682
- /**
683
- * Register an extension after initialization
684
- *
685
- * @param {BaseExtension} extension - Extension to register
686
- */
687
- registerExtension(extension: BaseExtension): void {
688
- this.extensions.push(extension);
689
- this.debug(`Registered extension: ${extension.name}`);
690
-
691
- // Register extension with all existing players
692
- for (const player of this.players.values()) {
693
- player.attachExtension(extension);
694
- }
695
- }
696
-
697
- /**
698
- * Get manager configuration
699
- */
700
- getConfig(): object {
701
- return {
702
- extractorTimeout: this.extractorTimeout,
703
- autoCleanup: this.autoCleanup,
704
- cleanupTimeout: this.cleanupTimeout,
705
- enableSearchCache: this.enableSearchCache,
706
- pluginsCount: this.plugins.length,
707
- extensionsCount: this.extensions.length,
708
- playersCount: this.players.size,
709
- };
710
- }
711
- }
712
-
713
- /**
714
- * Get the global PlayerManager instance
715
- *
716
- * @returns {PlayerManager | null} Global instance or null
717
- */
718
- export function getInstance(): PlayerManager | null {
719
- const globalInst = getGlobalManager();
720
- if (!globalInst) {
721
- console.error("[PlayerManager] Global instance not found, make sure to initialize with new PlayerManager(options)");
722
- return null;
723
- }
724
- return globalInst;
725
- }
1
+ import { EventEmitter } from "events";
2
+ import { Player } from "./Player";
3
+ import {
4
+ PlaybackMode,
5
+ PlayerManagerOptions,
6
+ PlayerOptions,
7
+ type Track,
8
+ SourcePlugin,
9
+ SearchResult,
10
+ ManagerEvents,
11
+ PlayerStats,
12
+ type PlaybackMirrorOptions,
13
+ type TrackMiddleware,
14
+ normalizeTrackMiddleware,
15
+ } from "../types";
16
+ import type { BaseExtension } from "../extensions";
17
+ import { withTimeout } from "../utils/timeout";
18
+ import { PluginManager } from "../plugins";
19
+
20
+ const GLOBAL_MANAGER_KEY: symbol = Symbol.for("ziplayer.PlayerManager.instance");
21
+
22
+ export const getGlobalManager = (): PlayerManager | null => {
23
+ try {
24
+ const instance = (globalThis as any)[GLOBAL_MANAGER_KEY];
25
+ if (!instance) {
26
+ return null;
27
+ }
28
+ return instance as PlayerManager;
29
+ } catch (error) {
30
+ console.error("[PlayerManager] Error getting global instance:", error);
31
+ return null;
32
+ }
33
+ };
34
+
35
+ const setGlobalManager = (instance: PlayerManager): void => {
36
+ try {
37
+ (globalThis as any)[GLOBAL_MANAGER_KEY] = instance;
38
+ } catch (error) {
39
+ console.error("[PlayerManager] Error setting global instance:", error);
40
+ }
41
+ };
42
+
43
+ export declare interface PlayerManager {
44
+ on<K extends keyof ManagerEvents>(event: K, listener: (...args: ManagerEvents[K]) => void): this;
45
+ emit<K extends keyof ManagerEvents>(event: K, ...args: ManagerEvents[K]): boolean;
46
+ }
47
+
48
+ interface ManagerCacheEntry<T> {
49
+ data: T;
50
+ timestamp: number;
51
+ expiresAt: number;
52
+ }
53
+
54
+ /**
55
+ * The main class for managing players across multiple Discord guilds.
56
+ *
57
+ * @example
58
+ * // Basic setup with plugins and extensions
59
+ * const manager = new PlayerManager({
60
+ * plugins: [
61
+ * new YouTubePlugin(),
62
+ * new SoundCloudPlugin(),
63
+ * new SpotifyPlugin(),
64
+ * new TTSPlugin({ defaultLang: "en" })
65
+ * ],
66
+ * extensions: [
67
+ * new voiceExt(null, { lang: "en-US" }),
68
+ * new lavalinkExt(null, {
69
+ * nodes: [{ host: "localhost", port: 2333, password: "youshallnotpass" }]
70
+ * })
71
+ * ],
72
+ * extractorTimeout: 10000,
73
+ * autoCleanup: true,
74
+ * cleanupInterval: 60000
75
+ * });
76
+ *
77
+ * // Create a player for a guild
78
+ * const player = await manager.create(guildId, {
79
+ * tts: { interrupt: true, volume: 1 },
80
+ * leaveOnEnd: true,
81
+ * leaveTimeout: 30000
82
+ * });
83
+ *
84
+ * // Get existing player
85
+ * const existingPlayer = manager.get(guildId);
86
+ * if (existingPlayer) {
87
+ * await existingPlayer.play("Never Gonna Give You Up", userId);
88
+ * }
89
+ */
90
+ export class PlayerManager extends EventEmitter {
91
+ private static instance: PlayerManager | null = null;
92
+ private players: Map<string, Player> = new Map();
93
+ private searchCache: Map<string, ManagerCacheEntry<SearchResult>>;
94
+ private readonly SEARCH_CACHE_TTL = 60 * 1000; // 1 minute
95
+ private readonly MAX_CACHE_SIZE = 100;
96
+ private cleanupInterval: NodeJS.Timeout | null = null;
97
+ private statsInterval: NodeJS.Timeout | null = null;
98
+
99
+ static async default(opt?: PlayerOptions): Promise<Player> {
100
+ let globaldef = getGlobalManager();
101
+ if (!globaldef) {
102
+ globaldef = new PlayerManager({});
103
+ }
104
+ return await globaldef.create("default", opt);
105
+ }
106
+
107
+ private plugins: SourcePlugin[];
108
+ private pluginManager: PluginManager;
109
+ private extensions: any[];
110
+ private B_debug: boolean = false;
111
+ private extractorTimeout: number = 10000;
112
+ private autoCleanup: boolean = true;
113
+ private cleanupTimeout: number = 60000; // 1 minute
114
+ private enableSearchCache: boolean = true;
115
+ private trackMiddlewareFromOptions: TrackMiddleware[] = [];
116
+
117
+ private debug(message?: any, ...optionalParams: any[]): void {
118
+ if (this.listenerCount("debug") > 0) {
119
+ this.emit("debug", `[PlayerManager] ${message}`, ...optionalParams);
120
+ if (!this.B_debug) {
121
+ this.B_debug = true;
122
+ }
123
+ }
124
+ }
125
+
126
+ constructor(options: PlayerManagerOptions = {}) {
127
+ super();
128
+ this.plugins = [];
129
+ this.pluginManager = new PluginManager(null as any, this, {
130
+ extractorTimeout: this.extractorTimeout,
131
+ });
132
+ this.searchCache = new Map();
133
+
134
+ // Initialize plugins
135
+ const provided = options.plugins || [];
136
+ for (const p of provided as any[]) {
137
+ try {
138
+ let instance: SourcePlugin | null = null;
139
+
140
+ if (p && typeof p === "object") {
141
+ instance = p as SourcePlugin;
142
+ } else if (typeof p === "function") {
143
+ instance = new (p as any)();
144
+ }
145
+
146
+ if (instance) {
147
+ this.plugins.push(instance);
148
+ this.pluginManager.register(instance);
149
+ }
150
+ this.debug(`Registered plugin: ${p.name || "unnamed"}`);
151
+ } catch (e) {
152
+ this.debug(`Failed to init plugin:`, e);
153
+ }
154
+ }
155
+
156
+ this.extensions = options.extensions || [];
157
+ this.extractorTimeout = options.extractorTimeout ?? 10000;
158
+ this.autoCleanup = options.autoCleanup ?? true;
159
+ this.cleanupTimeout = options.cleanupInterval ?? 60000;
160
+ this.enableSearchCache = options.enableSearchCache ?? true;
161
+ this.trackMiddlewareFromOptions = normalizeTrackMiddleware(options.trackMiddleware);
162
+
163
+ // Setup auto cleanup
164
+ if (this.autoCleanup) {
165
+ this.startAutoCleanup();
166
+ }
167
+
168
+ // Setup stats collection (optional)
169
+ if (options.enableStatsCollection) {
170
+ this.startStatsCollection();
171
+ }
172
+
173
+ setGlobalManager(this);
174
+ this.debug(`Initialized with ${this.plugins.length} plugins, ${this.extensions.length} extensions`);
175
+ }
176
+
177
+ private resolveGuildId(guildOrId: string | { id: string }): string {
178
+ if (typeof guildOrId === "string") return guildOrId;
179
+ if (guildOrId && typeof guildOrId === "object" && "id" in guildOrId) return guildOrId.id;
180
+ throw new Error("Invalid guild or guildId provided.");
181
+ }
182
+
183
+ private getSearchCacheKey(query: string): string {
184
+ return query.toLowerCase().trim();
185
+ }
186
+
187
+ private getCachedSearch(query: string): SearchResult | null {
188
+ if (!this.enableSearchCache) return null;
189
+
190
+ const key = this.getSearchCacheKey(query);
191
+ const cached = this.searchCache.get(key);
192
+
193
+ if (cached && Date.now() < cached.expiresAt) {
194
+ this.debug(`[Cache] Search hit for: ${query}`);
195
+ return cached.data;
196
+ }
197
+
198
+ if (cached) {
199
+ this.searchCache.delete(key);
200
+ }
201
+
202
+ return null;
203
+ }
204
+
205
+ private setCachedSearch(query: string, result: SearchResult): void {
206
+ if (!this.enableSearchCache) return;
207
+
208
+ // Clean up old entries if cache is too large
209
+ if (this.searchCache.size >= this.MAX_CACHE_SIZE) {
210
+ const oldest = Array.from(this.searchCache.entries()).sort((a, b) => a[1].timestamp - b[1].timestamp)[0];
211
+ if (oldest) this.searchCache.delete(oldest[0]);
212
+ }
213
+
214
+ const key = this.getSearchCacheKey(query);
215
+ this.searchCache.set(key, {
216
+ data: result,
217
+ timestamp: Date.now(),
218
+ expiresAt: Date.now() + this.SEARCH_CACHE_TTL,
219
+ });
220
+ this.debug(`[Cache] Search stored for: ${query}`);
221
+ }
222
+
223
+ private clearExpiredCache(): void {
224
+ const now = Date.now();
225
+ let expiredCount = 0;
226
+
227
+ for (const [key, entry] of this.searchCache) {
228
+ if (now >= entry.expiresAt) {
229
+ this.searchCache.delete(key);
230
+ expiredCount++;
231
+ }
232
+ }
233
+
234
+ if (expiredCount > 0) {
235
+ this.debug(`[Cache] Cleared ${expiredCount} expired search entries`);
236
+ }
237
+ }
238
+
239
+ private startAutoCleanup(): void {
240
+ if (this.cleanupInterval) {
241
+ clearInterval(this.cleanupInterval);
242
+ }
243
+
244
+ this.cleanupInterval = setInterval(() => {
245
+ this.cleanupInactivePlayers();
246
+ this.clearExpiredCache();
247
+ }, this.cleanupTimeout);
248
+
249
+ this.debug(`Auto-cleanup started with interval: ${this.cleanupTimeout}ms`);
250
+ }
251
+
252
+ private startStatsCollection(): void {
253
+ if (this.statsInterval) {
254
+ clearInterval(this.statsInterval);
255
+ }
256
+
257
+ this.statsInterval = setInterval(() => {
258
+ const stats = this.getStats();
259
+ this.emit("stats", stats);
260
+ }, 30000); // Every 30 seconds
261
+ }
262
+
263
+ private cleanupInactivePlayers(): void {
264
+ let cleanedCount = 0;
265
+
266
+ for (const [guildId, player] of this.players) {
267
+ // Clean up players that are not playing and not connected
268
+ if (!player.isPlaying && !player.connection && player.queue.isEmpty) {
269
+ const idleTime = Date.now() - (player as any)._lastActivity || Date.now();
270
+ if (idleTime > this.cleanupTimeout) {
271
+ this.debug(`Cleaning up inactive player for guild: ${guildId}`);
272
+ player.destroy();
273
+ this.players.delete(guildId);
274
+ cleanedCount++;
275
+ }
276
+ }
277
+ }
278
+
279
+ if (cleanedCount > 0) {
280
+ this.debug(`Cleaned up ${cleanedCount} inactive players`);
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Create a new player for a guild
286
+ *
287
+ * @param {string | {id: string}} guildOrId - Guild ID or guild object
288
+ * @param {PlayerOptions} options - Player configuration options
289
+ * @returns {Promise<Player>} The created player instance
290
+ */
291
+ async create(guildOrId: string | { id: string }, options?: PlayerOptions): Promise<Player> {
292
+ const guildId = this.resolveGuildId(guildOrId);
293
+
294
+ if (this.players.has(guildId)) {
295
+ this.debug(`Player already exists for guildId: ${guildId}, returning existing`);
296
+ return this.players.get(guildId)!;
297
+ }
298
+
299
+ this.debug(`Creating player for guildId: ${guildId}`);
300
+ const player = new Player(guildId, options, this);
301
+
302
+ // Add all registered plugins
303
+ this.plugins.forEach((plugin) => player.addPlugin(plugin));
304
+
305
+ // Activate extensions
306
+ let extsToActivate: any[] = [];
307
+ const optExts = (options as any)?.extensions as any[] | string[] | undefined;
308
+
309
+ if (Array.isArray(optExts)) {
310
+ if (optExts.length === 0) {
311
+ extsToActivate = [];
312
+ } else if (typeof optExts[0] === "string") {
313
+ const wanted = new Set(optExts as string[]);
314
+ extsToActivate = this.extensions.filter((ext) => {
315
+ const name = typeof ext === "function" ? ext.name : ext?.name;
316
+ return !!name && wanted.has(name);
317
+ });
318
+ } else {
319
+ extsToActivate = optExts;
320
+ }
321
+ } else {
322
+ // Use all extensions by default
323
+ extsToActivate = this.extensions;
324
+ }
325
+
326
+ for (const ext of extsToActivate) {
327
+ let instance = ext;
328
+ if (typeof ext === "function") {
329
+ try {
330
+ instance = new ext(player);
331
+ } catch (e) {
332
+ this.debug(`Extension constructor error for ${ext.name}:`, e);
333
+ continue;
334
+ }
335
+ }
336
+
337
+ if (instance && typeof instance === "object") {
338
+ const extInstance = instance as BaseExtension;
339
+ if ("player" in extInstance && !extInstance.player) extInstance.player = player;
340
+ player.attachExtension(extInstance);
341
+
342
+ if (typeof extInstance.active === "function") {
343
+ let activated: boolean | void = true;
344
+ try {
345
+ activated = await withTimeout(
346
+ Promise.resolve(extInstance.active({ manager: this, player })),
347
+ player.options.extractorTimeout ?? 15000,
348
+ `Extension ${extInstance?.name} activation timed out`,
349
+ );
350
+ this.debug(`Extension ${extInstance?.name} active check returned: ${activated}`);
351
+ } catch (e) {
352
+ activated = false;
353
+ this.debug(`Extension activation error for ${extInstance?.name}:`, e);
354
+ }
355
+
356
+ if (activated === false) {
357
+ player.detachExtension(extInstance);
358
+ continue;
359
+ }
360
+ }
361
+ }
362
+ }
363
+
364
+ // Forward all player events to manager
365
+ this.setupEventForwarding(player, guildId);
366
+
367
+ // Mark last activity
368
+ (player as any)._lastActivity = Date.now();
369
+
370
+ this.players.set(guildId, player);
371
+ this.debug(`Player created for guildId: ${guildId}`);
372
+ return player;
373
+ }
374
+
375
+ private setupEventForwarding(player: Player, guildId: string): void {
376
+ const forwardEvents = {
377
+ willPlay: "willPlay",
378
+ trackStart: "trackStart",
379
+ trackEnd: "trackEnd",
380
+ queueEnd: "queueEnd",
381
+ playerError: "playerError",
382
+ connectionError: "connectionError",
383
+ volumeChange: "volumeChange",
384
+ queueAdd: "queueAdd",
385
+ queueAddList: "queueAddList",
386
+ queueRemove: "queueRemove",
387
+ playerPause: "playerPause",
388
+ playerResume: "playerResume",
389
+ playerStop: "playerStop",
390
+ ttsStart: "ttsStart",
391
+ ttsEnd: "ttsEnd",
392
+ streamError: "streamError",
393
+ forwardModeStart: "forwardModeStart",
394
+ forwardModeEnd: "forwardModeEnd",
395
+ } as const satisfies Record<string, keyof ManagerEvents>;
396
+
397
+ for (const [sourceEvent, targetEvent] of Object.entries(forwardEvents) as [
398
+ keyof typeof forwardEvents,
399
+ keyof ManagerEvents,
400
+ ][]) {
401
+ player.on(sourceEvent, (...args: any[]) => {
402
+ if (sourceEvent === "trackStart") {
403
+ player._lastActivity = Date.now();
404
+ }
405
+
406
+ (this.emit as any)(targetEvent, player, ...args);
407
+ });
408
+ }
409
+
410
+ player.on("playerDestroy", () => {
411
+ this.emit("playerDestroy", player);
412
+
413
+ // Cleanup: unsubscribe all followers when leader is destroyed
414
+ if (player.forwardFollowers.size > 0) {
415
+ this.debug(`Leader ${guildId} destroyed, cleaning up ${player.forwardFollowers.size} followers`);
416
+ for (const follower of [...player.forwardFollowers]) {
417
+ try {
418
+ follower.unsubscribeForward("Leader destroyed");
419
+ } catch (err) {
420
+ this.debug(`Failed to unsubscribe follower ${follower.guildId}:`, err);
421
+ }
422
+ }
423
+ }
424
+
425
+ // Cleanup: if this player is a follower, unsubscribe from leader
426
+ if (player.playbackMode === PlaybackMode.FORWARD && player.forwardLeader) {
427
+ this.debug(`Follower ${guildId} destroyed, unsubscribing from leader ${player.forwardLeader.guildId}`);
428
+ player.unsubscribeForward("Follower destroyed");
429
+ }
430
+
431
+ this.players.delete(guildId);
432
+
433
+ this.debug(`Player destroyed for guildId: ${guildId}`);
434
+ });
435
+
436
+ player.on("debug", (...args) => {
437
+ if (this.listenerCount("debug") > 0) {
438
+ this.emit("debug", ...args);
439
+ }
440
+ });
441
+ }
442
+ /**
443
+ * Get an existing player for a guild
444
+ *
445
+ * @param {string | {id: string}} guildOrId - Guild ID or guild object
446
+ * @returns {Player | undefined} The player instance or undefined if not found
447
+ */
448
+ get(guildOrId: string | { id: string }): Player | undefined {
449
+ const guildId = this.resolveGuildId(guildOrId);
450
+ const player = this.players.get(guildId);
451
+ if (player) {
452
+ (player as any)._lastActivity = Date.now();
453
+ }
454
+ return player;
455
+ }
456
+
457
+ /**
458
+ * Get an existing player for a guild (alias for get)
459
+ */
460
+ getPlayer(guildOrId: string | { id: string }): Player | undefined {
461
+ return this.get(guildOrId);
462
+ }
463
+
464
+ /**
465
+ * Get all players
466
+ *
467
+ * @returns {Player[]} All player instances
468
+ */
469
+ getAll(): Player[] {
470
+ return Array.from(this.players.values());
471
+ }
472
+
473
+ /**
474
+ * Alias for getAll
475
+ */
476
+ getall(): Player[] {
477
+ return this.getAll();
478
+ }
479
+
480
+ /**
481
+ * Get players by filter
482
+ *
483
+ * @param {(player: Player) => boolean} filter - Filter function
484
+ * @returns {Player[]} Filtered player instances
485
+ */
486
+ getPlayersByFilter(filter: (player: Player) => boolean): Player[] {
487
+ return this.getAll().filter(filter);
488
+ }
489
+
490
+ /**
491
+ * Get players in a voice channel
492
+ *
493
+ * @param {string} channelId - Voice channel ID
494
+ * @returns {Player[]} Players in the channel
495
+ */
496
+ getPlayersInChannel(channelId: string): Player[] {
497
+ return this.getAll().filter((p) => p.connection?.joinConfig.channelId === channelId);
498
+ }
499
+
500
+ /**
501
+ * Destroy a player and clean up resources
502
+ *
503
+ * @param {string | {id: string}} guildOrId - Guild ID or guild object
504
+ * @returns {boolean} True if player was destroyed, false if not found
505
+ */
506
+ delete(guildOrId: string | { id: string }): boolean {
507
+ const guildId = this.resolveGuildId(guildOrId);
508
+ const player = this.players.get(guildId);
509
+
510
+ if (player) {
511
+ this.debug(`Deleting player for guildId: ${guildId}`);
512
+ player.destroy();
513
+ return true;
514
+ }
515
+ return false;
516
+ }
517
+
518
+ /**
519
+ * Destroy multiple players by filter
520
+ *
521
+ * @param {(player: Player) => boolean} filter - Filter function
522
+ * @returns {number} Number of players destroyed
523
+ */
524
+ deleteWhere(filter: (player: Player) => boolean): number {
525
+ const toDelete = this.getPlayersByFilter(filter);
526
+ let count = 0;
527
+
528
+ for (const player of toDelete) {
529
+ const guildId = player.guildId;
530
+ player.destroy();
531
+ this.players.delete(guildId);
532
+ count++;
533
+ }
534
+
535
+ if (count > 0) {
536
+ this.debug(`Deleted ${count} players by filter`);
537
+ }
538
+ return count;
539
+ }
540
+
541
+ /**
542
+ * Check if a player exists for a guild
543
+ *
544
+ * @param {string | {id: string}} guildOrId - Guild ID or guild object
545
+ * @returns {boolean} True if player exists
546
+ */
547
+ has(guildOrId: string | { id: string }): boolean {
548
+ const guildId = this.resolveGuildId(guildOrId);
549
+ return this.players.has(guildId);
550
+ }
551
+
552
+ /**
553
+ * Get number of players
554
+ */
555
+ get size(): number {
556
+ return this.players.size;
557
+ }
558
+
559
+ /**
560
+ * Check if debug is enabled
561
+ */
562
+ get debugEnabled(): boolean {
563
+ return this.B_debug;
564
+ }
565
+
566
+ /**
567
+ * Get manager statistics
568
+ *
569
+ * @returns {PlayerStats} Statistics about players
570
+ */
571
+ getStats(): PlayerStats {
572
+ let activePlayers = 0;
573
+ let pausedPlayers = 0;
574
+ let connectedPlayers = 0;
575
+ let totalTracksInQueue = 0;
576
+ let forwardHealthStatus = [];
577
+ let leader = 0;
578
+ let follower = 0;
579
+
580
+ for (const player of this.players.values()) {
581
+ if (player.isPlaying) activePlayers++;
582
+ if (player.isPaused) pausedPlayers++;
583
+ if (player.connection) connectedPlayers++;
584
+ totalTracksInQueue += player.queueSize;
585
+ const forwardStatus = player.getForwardHealthStatus();
586
+ if (forwardStatus.role === "leader") leader++;
587
+ if (forwardStatus.role === "follower") follower++;
588
+
589
+ forwardHealthStatus.push(forwardStatus);
590
+ }
591
+
592
+ return {
593
+ totalPlayers: this.players.size,
594
+ leader,
595
+ follower,
596
+ activePlayers,
597
+ pausedPlayers,
598
+ connectedPlayers,
599
+ totalTracksInQueue,
600
+ forwardHealthStatus,
601
+ };
602
+ }
603
+
604
+ /**
605
+ * Broadcast an action to all players
606
+ *
607
+ * @param {string} action - Action to perform
608
+ * @param {...any[]} args - Arguments for the action
609
+ * @example
610
+ * manager.broadcast("setVolume", 50);
611
+ * manager.broadcast("pause");
612
+ */
613
+ broadcast(action: string, ...args: any[]): void {
614
+ for (const player of this.players.values()) {
615
+ if (typeof (player as any)[action] === "function") {
616
+ try {
617
+ (player as any)[action](...args);
618
+ } catch (error) {
619
+ this.debug(`Error broadcasting ${action} to ${player.guildId}:`, error);
620
+ }
621
+ }
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Like {@link broadcast} but awaits every return value (for async methods such as `play`).
627
+ * Uses `Promise.allSettled` — failures are captured per guild, not thrown as a whole.
628
+ */
629
+ async broadcastAsync(action: string, ...args: any[]): Promise<PromiseSettledResult<unknown>[]> {
630
+ const pending: Promise<unknown>[] = [];
631
+ for (const player of this.players.values()) {
632
+ const fn = (player as any)[action];
633
+ if (typeof fn !== "function") continue;
634
+ try {
635
+ pending.push(Promise.resolve(fn.apply(player, args)));
636
+ } catch (error) {
637
+ pending.push(Promise.reject(error));
638
+ }
639
+ }
640
+ return Promise.allSettled(pending);
641
+ }
642
+
643
+ /**
644
+ * Broadcast a player method only to the given guild ids (players must already exist).
645
+ */
646
+ broadcastGuilds(guildIds: readonly string[], action: string, ...args: any[]): void {
647
+ const wanted = new Set(guildIds);
648
+ for (const player of this.players.values()) {
649
+ if (!wanted.has(player.guildId)) continue;
650
+ if (typeof (player as any)[action] === "function") {
651
+ try {
652
+ (player as any)[action](...args);
653
+ } catch (error) {
654
+ this.debug(`Error broadcasting ${action} to ${player.guildId}:`, error);
655
+ }
656
+ }
657
+ }
658
+ }
659
+
660
+ /**
661
+ * Global {@link TrackMiddleware} configured on this manager (applied before per-player middleware).
662
+ */
663
+ getTrackMiddlewareChain(): TrackMiddleware[] {
664
+ return [...this.trackMiddlewareFromOptions];
665
+ }
666
+
667
+ /**
668
+ * Mirror playback from one leader guild to multiple follower guilds.
669
+ *
670
+ * Followers directly subscribe to the leader player's audio pipeline,
671
+ * allowing multiple guilds to hear the same audio stream with extremely
672
+ * low CPU and bandwidth usage.
673
+ *
674
+ * Unlike traditional mirroring, followers do not create independent streams.
675
+ * Instead, their voice connections subscribe directly to the leader player's
676
+ * {@link audioPlayer}.
677
+ *
678
+ * ## Features
679
+ * - Shared playback pipeline
680
+ * - Followers may join at different times
681
+ * - Real-time track synchronization
682
+ * - Optional volume synchronization
683
+ * - Automatic cleanup on destroy
684
+ * - Low CPU / bandwidth usage
685
+ *
686
+ * ## Lifecycle
687
+ * - Destroying the leader automatically unsubscribes all followers.
688
+ * - Destroying a follower only removes that follower.
689
+ * - Followers may manually unsubscribe using {@link Player.unsubscribeForward}.
690
+ *
691
+ * ## Requirements
692
+ * - All guilds must already have active players.
693
+ * - All players must already be connected to voice channels.
694
+ *
695
+ * @param {PlaybackMirrorOptions} options Playback mirror configuration.
696
+ *
697
+ * @returns {() => void} Cleanup function that unsubscribes all followers.
698
+ *
699
+ * @example
700
+ * const stopMirror = manager.subscribeForwardMirror({
701
+ * leaderGuildId: "123",
702
+ * followerGuildIds: ["456", "789"],
703
+ * mirrorUserId: client.user.id,
704
+ * syncVolume: true,
705
+ * });
706
+ *
707
+ * // later
708
+ * stopMirror();
709
+ */
710
+
711
+ subscribeForwardMirror(options: PlaybackMirrorOptions): () => void {
712
+ const leader = this.get(options.leaderGuildId);
713
+
714
+ if (!leader) {
715
+ throw new Error(`subscribeForwardMirror: no player for leader guild ${options.leaderGuildId}`);
716
+ }
717
+ if (!leader.connection) {
718
+ throw new Error(`Leader player ${options.leaderGuildId} is not connected to a voice channel`);
719
+ }
720
+ const followers = [...new Set(options.followerGuildIds)].filter((id) => id !== options.leaderGuildId);
721
+
722
+ for (const gid of followers) {
723
+ const fp = this.get(gid);
724
+
725
+ if (!fp) {
726
+ this.debug(`Playback mirror: no player for follower guild ${gid}`);
727
+ continue;
728
+ }
729
+
730
+ if (!fp.connection) {
731
+ this.debug(`Playback mirror: follower ${gid} not connected to voice channel`);
732
+ continue;
733
+ }
734
+
735
+ fp.subscribeTo(leader, {
736
+ forwardMode: options.forwardMode,
737
+ });
738
+ }
739
+
740
+ return () => {
741
+ for (const gid of followers) {
742
+ const fp = this.get(gid);
743
+
744
+ try {
745
+ fp?.unsubscribeForward();
746
+ } catch {}
747
+ }
748
+ };
749
+ }
750
+
751
+ /**
752
+ * Destroy all players and clean up
753
+ */
754
+ destroy(): void {
755
+ this.debug(`Destroying all players`);
756
+
757
+ // Stop cleanup intervals
758
+ if (this.cleanupInterval) {
759
+ clearInterval(this.cleanupInterval);
760
+ this.cleanupInterval = null;
761
+ }
762
+
763
+ if (this.statsInterval) {
764
+ clearInterval(this.statsInterval);
765
+ this.statsInterval = null;
766
+ }
767
+
768
+ // Destroy all players
769
+ for (const player of this.players.values()) {
770
+ player.destroy();
771
+ }
772
+
773
+ this.players.clear();
774
+ this.searchCache.clear();
775
+ this.removeAllListeners();
776
+ this.debug(`PlayerManager destroyed`);
777
+ }
778
+
779
+ /**
780
+ * Search using PluginManager without creating a Player.
781
+ *
782
+ * Uses the same search pipeline as Player.search():
783
+ * - cache
784
+ * - plugin deduplication
785
+ * - plugin scoring/evaluation
786
+ * - fallback handling
787
+ *
788
+ * @param {string} query
789
+ * @param {string} requestedBy
790
+ * @returns {Promise<SearchResult>}
791
+ */
792
+ async search(query: string, requestedBy: string): Promise<SearchResult> {
793
+ this.debug(`Search called with query: ${query}, requestedBy: ${requestedBy}`);
794
+
795
+ // Cache
796
+ const cached = this.getCachedSearch(query);
797
+ if (cached) {
798
+ return cached;
799
+ }
800
+
801
+ try {
802
+ const result = await this.pluginManager.search(query, requestedBy);
803
+
804
+ if (!result || !Array.isArray(result.tracks) || result.tracks.length === 0) {
805
+ throw new Error(`No results found for: ${query}`);
806
+ }
807
+
808
+ this.debug(`Plugin search returned ${result.tracks.length} tracks (score: ${result.score?.score ?? "unknown"}%)`);
809
+
810
+ if (result.score) {
811
+ this.debug(`Search evaluation - ${result.score.reason}`);
812
+ }
813
+
814
+ this.setCachedSearch(query, result);
815
+
816
+ return result;
817
+ } catch (error) {
818
+ this.debug(`Search error:`, error);
819
+ throw error as Error;
820
+ }
821
+ }
822
+
823
+ /**
824
+ * Clear search cache
825
+ */
826
+ clearSearchCache(): void {
827
+ const size = this.searchCache.size;
828
+ this.searchCache.clear();
829
+ this.debug(`Cleared ${size} search cache entries`);
830
+ }
831
+
832
+ /**
833
+ * Register a plugin after initialization
834
+ *
835
+ * @param {SourcePlugin} plugin - Plugin to register
836
+ */
837
+ registerPlugin(plugin: SourcePlugin): void {
838
+ this.plugins.push(plugin);
839
+ this.pluginManager.register(plugin);
840
+
841
+ this.debug(`Registered plugin: ${plugin.name}`);
842
+
843
+ for (const player of this.players.values()) {
844
+ player.addPlugin(plugin);
845
+ }
846
+ }
847
+
848
+ /**
849
+ * Unregister a plugin
850
+ *
851
+ * @param {string} name - Plugin name to unregister
852
+ * @returns {boolean} True if plugin was unregistered
853
+ */
854
+ unregisterPlugin(name: string): boolean {
855
+ const index = this.plugins.findIndex((p) => p.name === name);
856
+ if (index === -1) return false;
857
+
858
+ this.plugins.splice(index, 1);
859
+ this.pluginManager.unregister(name);
860
+
861
+ this.debug(`Unregistered plugin: ${name}`);
862
+
863
+ return true;
864
+ }
865
+
866
+ /**
867
+ * Get all registered plugins
868
+ */
869
+ getPlugins(): SourcePlugin[] {
870
+ return [...this.plugins];
871
+ }
872
+
873
+ /**
874
+ * Register an extension after initialization
875
+ *
876
+ * @param {BaseExtension} extension - Extension to register
877
+ */
878
+ registerExtension(extension: BaseExtension): void {
879
+ this.extensions.push(extension);
880
+ this.debug(`Registered extension: ${extension.name}`);
881
+
882
+ // Register extension with all existing players
883
+ for (const player of this.players.values()) {
884
+ player.attachExtension(extension);
885
+ }
886
+ }
887
+
888
+ /**
889
+ * Get manager configuration
890
+ */
891
+ getConfig(): object {
892
+ return {
893
+ extractorTimeout: this.extractorTimeout,
894
+ autoCleanup: this.autoCleanup,
895
+ cleanupTimeout: this.cleanupTimeout,
896
+ enableSearchCache: this.enableSearchCache,
897
+ pluginsCount: this.plugins.length,
898
+ extensionsCount: this.extensions.length,
899
+ playersCount: this.players.size,
900
+ };
901
+ }
902
+ }
903
+
904
+ /**
905
+ * Get the global PlayerManager instance
906
+ *
907
+ * @returns {PlayerManager | null} Global instance or null
908
+ */
909
+ export function getInstance(): PlayerManager | null {
910
+ const globalInst = getGlobalManager();
911
+ if (!globalInst) {
912
+ console.error("[PlayerManager] Global instance not found, make sure to initialize with new PlayerManager(options)");
913
+ return null;
914
+ }
915
+ return globalInst;
916
+ }