@ziplayer/plugin 0.0.5 → 0.1.1

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.
@@ -0,0 +1,564 @@
1
+ import { BasePlugin, Track, SearchResult } from "ziplayer";
2
+ import YouTube, { Video, Playlist, Channel } from "youtube-sr";
3
+
4
+ /**
5
+ * Plugin YTSR để tìm kiếm nâng cao trên YouTube mà không cần tạo stream.
6
+ *
7
+ * Plugin này cung cấp các tính năng tìm kiếm nâng cao cho YouTube bao gồm:
8
+ * - Tìm kiếm video với nhiều tùy chọn lọc
9
+ * - Tìm kiếm playlist và channel
10
+ * - Hỗ trợ các loại tìm kiếm khác nhau (video, playlist, channel)
11
+ * - Không tạo stream, chỉ trả về metadata
12
+ *
13
+ * @example
14
+ * const ytsrPlugin = new YTSRPlugin();
15
+ *
16
+ * // Tìm kiếm video
17
+ * const videoResult = await ytsrPlugin.search("Never Gonna Give You Up", "user123");
18
+ *
19
+ * // Tìm kiếm playlist
20
+ * const playlistResult = await ytsrPlugin.searchPlaylist("chill music playlist", "user123");
21
+ *
22
+ * // Tìm kiếm channel
23
+ * const channelResult = await ytsrPlugin.searchChannel("PewDiePie", "user123");
24
+ *
25
+ * @since 1.0.0
26
+ */
27
+ export class YTSRPlugin extends BasePlugin {
28
+ name = "ytsr";
29
+ version = "1.0.0";
30
+
31
+ /**
32
+ * Tạo một instance mới của YTSRPlugin.
33
+ *
34
+ * Plugin này không cần khởi tạo bất kỳ client nào vì sử dụng youtube-sr
35
+ * để tìm kiếm thông tin từ YouTube.
36
+ *
37
+ * @example
38
+ * const plugin = new YTSRPlugin();
39
+ * // Plugin sẵn sàng sử dụng ngay lập tức
40
+ */
41
+ constructor() {
42
+ super();
43
+ }
44
+
45
+ /**
46
+ * Xác định xem plugin có thể xử lý query này không.
47
+ *
48
+ * @param query - Query tìm kiếm hoặc URL để kiểm tra
49
+ * @returns `true` nếu plugin có thể xử lý query, `false` nếu không
50
+ *
51
+ * @example
52
+ * plugin.canHandle("Never Gonna Give You Up"); // true
53
+ * plugin.canHandle("https://www.youtube.com/watch?v=dQw4w9WgXcQ"); // true
54
+ * plugin.canHandle("spotify:track:123"); // false
55
+ */
56
+ canHandle(query: string): boolean {
57
+ const q = (query || "").trim().toLowerCase();
58
+
59
+ // Tránh xử lý các pattern rõ ràng cho các extractor khác
60
+ if (q.startsWith("tts:") || q.startsWith("say ")) return false;
61
+ if (q.startsWith("spotify:") || q.includes("open.spotify.com")) return false;
62
+ if (q.includes("soundcloud")) return false;
63
+
64
+ // Xử lý URL YouTube
65
+ if (q.startsWith("http://") || q.startsWith("https://")) {
66
+ try {
67
+ const parsed = new URL(query);
68
+ const allowedHosts = ["youtube.com", "www.youtube.com", "music.youtube.com", "youtu.be", "www.youtu.be"];
69
+ return allowedHosts.includes(parsed.hostname.toLowerCase());
70
+ } catch (e) {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ // Xử lý tất cả text khác như tìm kiếm YouTube
76
+ return true;
77
+ }
78
+
79
+ /**
80
+ * Xác thực xem URL có phải là URL YouTube hợp lệ không.
81
+ *
82
+ * @param url - URL để xác thực
83
+ * @returns `true` nếu URL hợp lệ, `false` nếu không
84
+ *
85
+ * @example
86
+ * plugin.validate("https://www.youtube.com/watch?v=dQw4w9WgXcQ"); // true
87
+ * plugin.validate("https://youtu.be/dQw4w9WgXcQ"); // true
88
+ * plugin.validate("https://spotify.com/track/123"); // false
89
+ */
90
+ validate(url: string): boolean {
91
+ try {
92
+ const parsed = new URL(url);
93
+ const allowedHosts = ["youtube.com", "www.youtube.com", "music.youtube.com", "youtu.be", "www.youtu.be", "m.youtube.com"];
94
+ return allowedHosts.includes(parsed.hostname.toLowerCase());
95
+ } catch (e) {
96
+ return false;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Tìm kiếm video trên YouTube với các tùy chọn nâng cao.
102
+ *
103
+ * @param query - Query tìm kiếm
104
+ * @param requestedBy - ID của user yêu cầu tìm kiếm
105
+ * @param options - Tùy chọn tìm kiếm nâng cao
106
+ * @param options.limit - Số lượng kết quả tối đa (mặc định: 10)
107
+ * @param options.type - Loại tìm kiếm: "video", "playlist", "channel", "all" (mặc định: "video")
108
+ * @param options.duration - Lọc theo thời lượng: "short", "medium", "long", "all" (mặc định: "all")
109
+ * @param options.sortBy - Sắp xếp theo: "relevance", "uploadDate", "viewCount", "rating" (mặc định: "relevance")
110
+ * @param options.uploadDate - Lọc theo ngày upload: "hour", "today", "week", "month", "year", "all" (mặc định: "all")
111
+ * @returns SearchResult chứa các track được tìm thấy
112
+ *
113
+ * @example
114
+ * // Tìm kiếm video cơ bản
115
+ * const result = await plugin.search("Never Gonna Give You Up", "user123");
116
+ *
117
+ * // Tìm kiếm với tùy chọn nâng cao
118
+ * const advancedResult = await plugin.search("chill music", "user123", {
119
+ * limit: 5,
120
+ * duration: "medium",
121
+ * sortBy: "viewCount",
122
+ * uploadDate: "month"
123
+ * });
124
+ */
125
+ async search(
126
+ query: string,
127
+ requestedBy: string,
128
+ options: {
129
+ limit?: number;
130
+ type?: "video" | "playlist" | "channel" | "all";
131
+ duration?: "short" | "medium" | "long" | "all";
132
+ sortBy?: "relevance" | "uploadDate" | "viewCount" | "rating";
133
+ uploadDate?: "hour" | "today" | "week" | "month" | "year" | "all";
134
+ } = {},
135
+ ): Promise<SearchResult> {
136
+ const { limit = 10, type = "video", duration = "all", sortBy = "relevance", uploadDate = "all" } = options;
137
+
138
+ try {
139
+ // Nếu là URL YouTube, xử lý như video đơn lẻ hoặc playlist Mix
140
+ if (this.validate(query)) {
141
+ const listId = this.extractListId(query);
142
+ if (listId && this.isMixListId(listId)) {
143
+ // Xử lý playlist Mix (RD)
144
+ return await this.handleMixPlaylistInternal(query, requestedBy, limit);
145
+ }
146
+
147
+ const videoId = this.extractVideoId(query);
148
+ if (videoId) {
149
+ const video = await this.getVideoByIdInternal(videoId);
150
+ if (video) {
151
+ return {
152
+ tracks: [this.buildTrackFromVideo(video, requestedBy)],
153
+ };
154
+ }
155
+ }
156
+ }
157
+
158
+ // Tìm kiếm với youtube-sr
159
+ const searchOptions: any = {
160
+ limit,
161
+ type: type === "all" ? "all" : type,
162
+ safeSearch: false,
163
+ };
164
+
165
+ // Thêm các filter nâng cao
166
+ if (duration !== "all") {
167
+ searchOptions.duration = duration;
168
+ }
169
+ if (sortBy !== "relevance") {
170
+ searchOptions.sortBy = sortBy;
171
+ }
172
+ if (uploadDate !== "all") {
173
+ searchOptions.uploadDate = uploadDate;
174
+ }
175
+
176
+ const results = await YouTube.search(query, searchOptions);
177
+
178
+ const tracks: Track[] = [];
179
+
180
+ // Xử lý kết quả dựa trên loại tìm kiếm
181
+ if (type === "video" || type === "all") {
182
+ const videos = results.filter((item: any): item is Video => item instanceof Video);
183
+ tracks.push(...videos.slice(0, limit).map((video: Video) => this.buildTrackFromVideo(video, requestedBy)));
184
+ }
185
+
186
+ if (type === "playlist" || type === "all") {
187
+ const playlists = results.filter((item: any): item is Playlist => item instanceof Playlist);
188
+ // Chuyển đổi playlist thành tracks
189
+ playlists.slice(0, Math.floor(limit / 2)).forEach((playlist: any) => {
190
+ tracks.push(this.buildTrackFromPlaylist(playlist, requestedBy));
191
+ });
192
+ }
193
+
194
+ if (type === "channel" || type === "all") {
195
+ const channels = results.filter((item: any): item is Channel => item instanceof Channel);
196
+ // Chuyển đổi channel thành tracks (lấy video mới nhất)
197
+ channels.slice(0, Math.floor(limit / 3)).forEach((channel: any) => {
198
+ tracks.push(this.buildTrackFromChannel(channel, requestedBy));
199
+ });
200
+ }
201
+
202
+ return { tracks: tracks.slice(0, limit) };
203
+ } catch (error: any) {
204
+ throw new Error(`YTSR search failed: ${error?.message || error}`);
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Tìm kiếm playlist trên YouTube.
210
+ *
211
+ * @param query - Query tìm kiếm playlist
212
+ * @param requestedBy - ID của user yêu cầu tìm kiếm
213
+ * @param limit - Số lượng playlist tối đa (mặc định: 5)
214
+ * @returns SearchResult chứa các playlist được tìm thấy
215
+ *
216
+ * @example
217
+ * const playlists = await plugin.searchPlaylist("chill music playlist", "user123", 3);
218
+ * console.log(`Tìm thấy ${playlists.tracks.length} playlist`);
219
+ */
220
+ async searchPlaylist(query: string, requestedBy: string, limit: number = 5): Promise<SearchResult> {
221
+ return this.search(query, requestedBy, { type: "playlist", limit });
222
+ }
223
+
224
+ /**
225
+ * Tìm kiếm channel trên YouTube.
226
+ *
227
+ * @param query - Query tìm kiếm channel
228
+ * @param requestedBy - ID của user yêu cầu tìm kiếm
229
+ * @param limit - Số lượng channel tối đa (mặc định: 5)
230
+ * @returns SearchResult chứa các channel được tìm thấy
231
+ *
232
+ * @example
233
+ * const channels = await plugin.searchChannel("PewDiePie", "user123", 3);
234
+ * console.log(`Tìm thấy ${channels.tracks.length} channel`);
235
+ */
236
+ async searchChannel(query: string, requestedBy: string, limit: number = 5): Promise<SearchResult> {
237
+ return this.search(query, requestedBy, { type: "channel", limit });
238
+ }
239
+
240
+ /**
241
+ * Tìm kiếm video theo ID cụ thể.
242
+ *
243
+ * @param videoId - ID của video YouTube
244
+ * @param requestedBy - ID của user yêu cầu
245
+ * @returns Track object của video
246
+ *
247
+ * @example
248
+ * const video = await plugin.getVideoById("dQw4w9WgXcQ", "user123");
249
+ * console.log(video.title);
250
+ */
251
+ async getVideoById(videoId: string, requestedBy: string): Promise<Track | null> {
252
+ try {
253
+ const video = await this.getVideoByIdInternal(videoId);
254
+ return video ? this.buildTrackFromVideo(video, requestedBy) : null;
255
+ } catch (error: any) {
256
+ throw new Error(`Failed to get video by ID: ${error?.message || error}`);
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Lấy thông tin chi tiết của video từ ID.
262
+ *
263
+ * @param videoId - ID của video YouTube
264
+ * @returns Video object hoặc null nếu không tìm thấy
265
+ */
266
+ private async getVideoByIdInternal(videoId: string): Promise<Video | null> {
267
+ try {
268
+ const results = await YouTube.search(`https://www.youtube.com/watch?v=${videoId}`, { limit: 1, type: "video" });
269
+ const video = results.find((item: any): item is Video => item instanceof Video);
270
+ return video || null;
271
+ } catch {
272
+ return null;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Xây dựng Track object từ Video object của youtube-sr.
278
+ *
279
+ * @param video - Video object từ youtube-sr
280
+ * @param requestedBy - ID của user yêu cầu
281
+ * @returns Track object
282
+ */
283
+ private buildTrackFromVideo(video: Video, requestedBy: string): Track {
284
+ return {
285
+ id: video.id,
286
+ title: video.title,
287
+ url: video.url,
288
+ duration: typeof video.duration === "number" ? video.duration : (video.duration as any)?.seconds || 0,
289
+ thumbnail: video.thumbnail?.url || (video as any).thumbnails?.[0]?.url,
290
+ requestedBy,
291
+ source: this.name,
292
+ metadata: {
293
+ author: video.channel?.name,
294
+ views: video.views,
295
+ description: video.description,
296
+ publishedAt: video.uploadedAt,
297
+ channelUrl: video.channel?.url,
298
+ channelId: video.channel?.id,
299
+ },
300
+ } as Track;
301
+ }
302
+
303
+ /**
304
+ * Xây dựng Track object từ Playlist object của youtube-sr.
305
+ *
306
+ * @param playlist - Playlist object từ youtube-sr
307
+ * @param requestedBy - ID của user yêu cầu
308
+ * @returns Track object
309
+ */
310
+ private buildTrackFromPlaylist(playlist: Playlist, requestedBy: string): Track {
311
+ return {
312
+ id: playlist.id,
313
+ title: playlist.title,
314
+ url: playlist.url,
315
+ duration: 0, // Playlist không có duration cố định
316
+ thumbnail: playlist.thumbnail?.url || (playlist as any).thumbnails?.[0]?.url,
317
+ requestedBy,
318
+ source: this.name,
319
+ metadata: {
320
+ author: playlist.channel?.name,
321
+ views: playlist.views,
322
+ description: (playlist as any).description,
323
+ publishedAt: (playlist as any).uploadedAt,
324
+ channelUrl: playlist.channel?.url,
325
+ channelId: playlist.channel?.id,
326
+ videoCount: playlist.videoCount,
327
+ type: "playlist",
328
+ },
329
+ } as Track;
330
+ }
331
+
332
+ /**
333
+ * Xây dựng Track object từ Channel object của youtube-sr.
334
+ *
335
+ * @param channel - Channel object từ youtube-sr
336
+ * @param requestedBy - ID của user yêu cầu
337
+ * @returns Track object
338
+ */
339
+ private buildTrackFromChannel(channel: Channel, requestedBy: string): Track {
340
+ return {
341
+ id: channel.id,
342
+ title: channel.name,
343
+ url: channel.url,
344
+ duration: 0, // Channel không có duration
345
+ thumbnail: (channel as any).thumbnail?.url || (channel as any).thumbnails?.[0]?.url,
346
+ requestedBy,
347
+ source: this.name,
348
+ metadata: {
349
+ author: channel.name,
350
+ views: channel.subscribers,
351
+ description: (channel as any).description,
352
+ publishedAt: (channel as any).joinedAt,
353
+ channelUrl: channel.url,
354
+ channelId: channel.id,
355
+ subscriberCount: channel.subscribers,
356
+ type: "channel",
357
+ },
358
+ } as Track;
359
+ }
360
+
361
+ /**
362
+ * Xử lý playlist Mix (RD) của YouTube (internal).
363
+ *
364
+ * @param url - URL của playlist Mix
365
+ * @param requestedBy - ID của user yêu cầu
366
+ * @param limit - Số lượng track tối đa
367
+ * @returns SearchResult chứa các track từ Mix
368
+ */
369
+ private async handleMixPlaylistInternal(url: string, requestedBy: string, limit: number): Promise<SearchResult> {
370
+ try {
371
+ const videoId = this.extractVideoId(url);
372
+ if (!videoId) {
373
+ throw new Error("Không thể trích xuất video ID từ URL Mix");
374
+ }
375
+
376
+ // Lấy thông tin video gốc
377
+ const anchorVideo = await this.getVideoByIdInternal(videoId);
378
+ if (!anchorVideo) {
379
+ throw new Error("Không thể lấy thông tin video gốc");
380
+ }
381
+
382
+ // Tìm kiếm các video liên quan để tạo Mix
383
+ const searchQuery = `${anchorVideo.title} ${anchorVideo.channel?.name || ""}`;
384
+ const searchResult = await this.search(searchQuery, requestedBy, {
385
+ limit: limit + 5, // Lấy thêm để có thể lọc
386
+ type: "video",
387
+ });
388
+
389
+ // Lọc và sắp xếp kết quả để tạo Mix
390
+ const mixTracks = searchResult.tracks
391
+ .filter((track) => track.id !== videoId) // Loại bỏ video gốc
392
+ .slice(0, limit);
393
+
394
+ // Thêm video gốc vào đầu Mix
395
+ const anchorTrack = this.buildTrackFromVideo(anchorVideo, requestedBy);
396
+ mixTracks.unshift(anchorTrack);
397
+
398
+ return {
399
+ tracks: mixTracks.slice(0, limit),
400
+ playlist: {
401
+ name: `YouTube Mix - ${anchorVideo.title}`,
402
+ url: url,
403
+ thumbnail: anchorVideo.thumbnail?.url || (anchorVideo as any).thumbnails?.[0]?.url,
404
+ },
405
+ };
406
+ } catch (error: any) {
407
+ throw new Error(`Failed to handle Mix playlist: ${error?.message || error}`);
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Kiểm tra xem listId có phải là Mix playlist không.
413
+ *
414
+ * @param listId - ID của playlist
415
+ * @returns true nếu là Mix playlist
416
+ */
417
+ private isMixListId(listId: string): boolean {
418
+ // YouTube Mix playlists thường bắt đầu với 'RD'
419
+ return typeof listId === "string" && listId.toUpperCase().startsWith("RD");
420
+ }
421
+
422
+ /**
423
+ * Trích xuất playlist ID từ URL YouTube.
424
+ *
425
+ * @param input - URL chứa playlist ID
426
+ * @returns Playlist ID hoặc null nếu không tìm thấy
427
+ */
428
+ private extractListId(input: string): string | null {
429
+ try {
430
+ const u = new URL(input);
431
+ return u.searchParams.get("list");
432
+ } catch {
433
+ return null;
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Trích xuất video ID từ URL YouTube.
439
+ *
440
+ * @param input - URL hoặc string chứa video ID
441
+ * @returns Video ID hoặc null nếu không tìm thấy
442
+ */
443
+ private extractVideoId(input: string): string | null {
444
+ try {
445
+ const u = new URL(input);
446
+ const allowedShortHosts = ["youtu.be"];
447
+ const allowedLongHosts = ["youtube.com", "www.youtube.com", "music.youtube.com", "m.youtube.com"];
448
+
449
+ if (allowedShortHosts.includes(u.hostname)) {
450
+ return u.pathname.split("/").filter(Boolean)[0] || null;
451
+ }
452
+
453
+ if (allowedLongHosts.includes(u.hostname)) {
454
+ // watch?v=, shorts/, embed/
455
+ if (u.searchParams.get("v")) return u.searchParams.get("v");
456
+ const path = u.pathname;
457
+ if (path.startsWith("/shorts/")) return path.replace("/shorts/", "");
458
+ if (path.startsWith("/embed/")) return path.replace("/embed/", "");
459
+ }
460
+
461
+ return null;
462
+ } catch {
463
+ return null;
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Plugin này không hỗ trợ tạo stream, chỉ dành cho tìm kiếm metadata.
469
+ *
470
+ * @param track - Track object
471
+ * @throws Error vì plugin này không hỗ trợ streaming
472
+ */
473
+ async getStream(track: Track): Promise<any> {
474
+ throw new Error("YTSRPlugin không hỗ trợ streaming. Plugin này chỉ dành cho tìm kiếm metadata.");
475
+ }
476
+
477
+ /**
478
+ * Xử lý playlist Mix (RD) của YouTube.
479
+ *
480
+ * @param mixUrl - URL của playlist Mix YouTube
481
+ * @param requestedBy - ID của user yêu cầu
482
+ * @param limit - Số lượng track tối đa (mặc định: 10)
483
+ * @returns SearchResult chứa các track từ Mix playlist
484
+ *
485
+ * @example
486
+ * const mixResult = await plugin.handleMixPlaylist(
487
+ * "https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=RDMWGnHCaqxdU&start_radio=1",
488
+ * "user123",
489
+ * 15
490
+ * );
491
+ * console.log(`Mix playlist: ${mixResult.playlist?.name}`);
492
+ * console.log(`Tìm thấy ${mixResult.tracks.length} track trong Mix`);
493
+ */
494
+ async handleMixPlaylist(mixUrl: string, requestedBy: string, limit: number = 10): Promise<SearchResult> {
495
+ return this.handleMixPlaylistInternal(mixUrl, requestedBy, limit);
496
+ }
497
+
498
+ /**
499
+ * Lấy các video liên quan cho một video YouTube cụ thể.
500
+ *
501
+ * @param trackURL - URL của video YouTube để lấy video liên quan
502
+ * @param opts - Tùy chọn cho việc lọc và giới hạn kết quả
503
+ * @param opts.limit - Số lượng video liên quan tối đa (mặc định: 5)
504
+ * @param opts.offset - Số lượng video bỏ qua từ đầu (mặc định: 0)
505
+ * @param opts.history - Mảng các track để loại trừ khỏi kết quả
506
+ * @returns Mảng các Track object liên quan
507
+ *
508
+ * @example
509
+ * const related = await plugin.getRelatedTracks(
510
+ * "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
511
+ * { limit: 3, history: [currentTrack] }
512
+ * );
513
+ * console.log(`Tìm thấy ${related.length} video liên quan`);
514
+ */
515
+ async getRelatedTracks(trackURL: string, opts: { limit?: number; offset?: number; history?: Track[] } = {}): Promise<Track[]> {
516
+ const { limit = 5, offset = 0, history = [] } = opts;
517
+
518
+ try {
519
+ const videoId = this.extractVideoId(trackURL);
520
+ if (!videoId) {
521
+ throw new Error("Không thể trích xuất video ID từ URL");
522
+ }
523
+
524
+ // Tìm kiếm video liên quan bằng cách tìm kiếm với title của video hiện tại
525
+ const currentVideo = await this.getVideoByIdInternal(videoId);
526
+ if (!currentVideo) {
527
+ throw new Error("Không thể lấy thông tin video hiện tại");
528
+ }
529
+
530
+ // Tìm kiếm các video liên quan dựa trên title và channel
531
+ const searchQuery = `${currentVideo.title} ${currentVideo.channel?.name || ""}`;
532
+ const searchResult = await this.search(searchQuery, "auto", {
533
+ limit: limit + offset + history.length,
534
+ type: "video",
535
+ });
536
+
537
+ // Lọc ra video hiện tại và các video trong history
538
+ const filteredTracks = searchResult.tracks.filter((track) => {
539
+ // Loại bỏ video hiện tại
540
+ if (track.id === videoId) return false;
541
+
542
+ // Loại bỏ các video trong history
543
+ if (history.some((h) => h.id === track.id || h.url === track.url)) return false;
544
+
545
+ return true;
546
+ });
547
+
548
+ // Áp dụng offset và limit
549
+ return filteredTracks.slice(offset, offset + limit);
550
+ } catch (error: any) {
551
+ throw new Error(`Failed to get related tracks: ${error?.message || error}`);
552
+ }
553
+ }
554
+
555
+ /**
556
+ * Plugin này không hỗ trợ fallback stream.
557
+ *
558
+ * @param track - Track object
559
+ * @throws Error vì plugin này không hỗ trợ streaming
560
+ */
561
+ async getFallback(track: Track): Promise<any> {
562
+ throw new Error("YTSRPlugin không hỗ trợ fallback streaming. Plugin này chỉ dành cho tìm kiếm metadata.");
563
+ }
564
+ }