-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathyt.js
More file actions
640 lines (546 loc) · 20.5 KB
/
Copy pathyt.js
File metadata and controls
640 lines (546 loc) · 20.5 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
AudioPlayerStatus,
VoiceConnectionStatus,
StreamType,
entersState,
} = require('@discordjs/voice');
const { EmbedBuilder } = require('discord.js');
const { execFile } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { promisify } = require('util');
const prism = require('prism-media');
const execFileAsync = promisify(execFile);
const pythonCommand = process.env.PYTHON_BIN || (process.platform === 'win32' ? 'py' : 'python3');
const ytDlpTimeoutMs = Number(process.env.YTDLP_TIMEOUT_MS) || 60_000;
function getYouTubeCookieFilePath() {
const cookieFile = process.env.YOUTUBE_COOKIE_FILE?.trim();
if (!cookieFile) return null;
return path.resolve(cookieFile);
}
function getYouTubeCookieString() {
const cookieFile = getYouTubeCookieFilePath();
if (cookieFile && fs.existsSync(cookieFile)) {
const fileContents = fs.readFileSync(cookieFile, 'utf8');
const pairs = [];
for (const line of fileContents.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const parts = trimmed.split('\t');
if (parts.length >= 7) {
const name = parts[5];
const value = parts.slice(6).join('\t');
if (name) {
pairs.push(`${name}=${value}`);
}
}
}
if (pairs.length > 0) {
return pairs.join('; ');
}
}
return process.env.YOUTUBE_COOKIE?.trim() || null;
}
function buildYtDlpCookieFile() {
const existingCookieFile = getYouTubeCookieFilePath();
if (existingCookieFile && fs.existsSync(existingCookieFile)) {
return { filePath: existingCookieFile, temporary: false };
}
const cookieString = getYouTubeCookieString();
if (!cookieString) return null;
const lines = [
'# Netscape HTTP Cookie File',
];
for (const part of cookieString.split(';')) {
const trimmed = part.trim();
if (!trimmed) continue;
const separatorIndex = trimmed.indexOf('=');
if (separatorIndex === -1) continue;
const name = trimmed.slice(0, separatorIndex).trim();
const value = trimmed.slice(separatorIndex + 1).trim();
if (!name) continue;
lines.push(`.youtube.com\tTRUE\t/\tTRUE\t2147483647\t${name}\t${value}`);
}
if (lines.length === 1) return null;
const filePath = path.join(os.tmpdir(), `raadio-exile-ytdlp-cookies-${process.pid}.txt`);
fs.writeFileSync(filePath, `${lines.join('\n')}\n`, { encoding: 'utf8', mode: 0o600 });
return { filePath, temporary: true };
}
async function runYtDlp(args) {
const cookieFile = buildYtDlpCookieFile();
const fullArgs = [
'-m',
'yt_dlp',
'--js-runtimes',
process.env.YTDLP_JS_RUNTIME || 'node',
];
if (cookieFile) {
fullArgs.push('--cookies', cookieFile.filePath);
}
fullArgs.push(...args);
try {
return await execFileAsync(pythonCommand, fullArgs, {
windowsHide: true,
maxBuffer: 16 * 1024 * 1024,
timeout: ytDlpTimeoutMs,
});
} finally {
if (cookieFile?.temporary) {
fs.rmSync(cookieFile.filePath, { force: true });
}
}
}
function getOrCreateState(message, guildStates) {
const guildId = message.guild.id;
let state = guildStates.get(guildId);
if (!state) {
state = {
connection: null,
player: null,
queue: [],
currentSourceType: null,
textChannel: null,
timeoutId: null,
emptyChannelTimeoutId: null,
connectionListenersAttached: false,
playerListenersAttached: false,
lastPlayedRadioKey: null,
lastPlayedRadioInfo: null,
nowPlayingRadioMsgId: null,
announcementIntervalId: null,
isAnnouncementPlaying: false,
resumeRadioAfterAnnouncement: false,
currentYtDlpProcess: null,
};
guildStates.set(guildId, state);
}
state.textChannel = message.channel;
clearTimeout(state.timeoutId);
return state;
}
function extractVideoId(input) {
if (!input) return null;
const trimmed = input.trim();
if (/^[A-Za-z0-9_-]{11}$/.test(trimmed)) return trimmed;
try {
const url = new URL(trimmed);
const hostname = url.hostname.toLowerCase();
const isYouTubeHost = hostname === 'youtube.com' || hostname.endsWith('.youtube.com');
if (!isYouTubeHost && hostname !== 'youtu.be') return null;
if (hostname === 'youtu.be') {
return url.pathname.split('/').filter(Boolean)[0] || null;
}
if (url.pathname === '/watch') {
return url.searchParams.get('v');
}
const parts = url.pathname.split('/').filter(Boolean);
if (parts[0] === 'shorts' || parts[0] === 'live' || parts[0] === 'embed') {
return parts[1] || null;
}
} catch {
return null;
}
return null;
}
function normalizeThumbnail(thumbnails) {
if (!Array.isArray(thumbnails) || thumbnails.length === 0) return [];
return thumbnails
.map((thumbnail) => {
if (!thumbnail) return null;
if (typeof thumbnail === 'string') return { url: thumbnail };
return { url: thumbnail.url || thumbnail[0]?.url || null };
})
.filter((thumbnail) => thumbnail?.url);
}
function formatDuration(seconds) {
if (!Number.isFinite(seconds) || seconds < 0) return 'N/A';
const rounded = Math.round(seconds);
const hours = Math.floor(rounded / 3600);
const minutes = Math.floor((rounded % 3600) / 60);
const remainingSeconds = rounded % 60;
return hours > 0
? `${hours}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
: `${minutes}:${String(remainingSeconds).padStart(2, '0')}`;
}
function normalizeVideoFromYtDlp(info, fallbackUrl) {
const videoId = info?.id || extractVideoId(fallbackUrl);
if (!videoId) return null;
const thumbnails = normalizeThumbnail(info.thumbnails);
if (info.thumbnail && !thumbnails.some((thumbnail) => thumbnail.url === info.thumbnail)) {
thumbnails.unshift({ url: info.thumbnail });
}
return {
id: videoId,
title: info.title || 'Unknown title',
url: info.webpage_url || fallbackUrl || `https://www.youtube.com/watch?v=${videoId}`,
thumbnails,
durationRaw: info.duration_string || formatDuration(info.duration),
};
}
async function ensureVoiceConnection(message, guildStates) {
const voiceChannel = message.member?.voice?.channel;
if (!voiceChannel) {
await message.reply('Liitu esmalt haale kanaliga!');
return null;
}
const guildId = message.guild.id;
const state = getOrCreateState(message, guildStates);
try {
if (
!state.connection ||
state.connection.state?.status === VoiceConnectionStatus.Destroyed ||
state.connection.state?.status === VoiceConnectionStatus.Disconnected
) {
if (state.connection && state.connection.state?.status !== VoiceConnectionStatus.Destroyed) {
try {
state.connection.destroy();
} catch (_) {}
}
state.connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId,
adapterCreator: message.guild.voiceAdapterCreator,
});
state.connection.rejoinAttempts = 0;
state.connectionListenersAttached = false;
console.log(`[YT] joinVoiceChannel called for guild ${guildId} (${voiceChannel.name})`);
} else if (state.connection.joinConfig?.channelId !== voiceChannel.id) {
await message.reply(
`Olen juba teises kanalis (${message.guild.channels.cache.get(state.connection.joinConfig.channelId)?.name}). Liiguta mind voi kasuta \`!stop\`.`
);
return null;
}
await entersState(state.connection, VoiceConnectionStatus.Ready, 20_000);
return { guildId, state };
} catch (error) {
console.error(`[YT] Error joining/connecting to voice channel for guild ${guildId}:`, error);
try {
if (state.connection && state.connection.state?.status !== VoiceConnectionStatus.Destroyed) {
state.connection.destroy();
}
} catch (_) {}
guildStates.delete(guildId);
await message.reply('Ei saanud haale kanaliga ühendust luua.');
return null;
}
}
async function searchFirstVideo(query) {
const videoId = extractVideoId(query);
const target = videoId
? `https://www.youtube.com/watch?v=${videoId}`
: `ytsearch1:${query}`;
const selectionArgs = videoId
? ['--no-playlist']
: ['--flat-playlist', '--playlist-end', '1'];
const { stdout } = await runYtDlp([
...selectionArgs,
'--skip-download',
'--dump-json',
'--',
target,
]);
const jsonLine = stdout.split(/\r?\n/).find((line) => line.trim());
if (!jsonLine) return null;
return normalizeVideoFromYtDlp(JSON.parse(jsonLine), videoId ? target : null);
}
async function resolveYtDlpStream(videoUrl) {
const { stdout } = await runYtDlp([
'-f',
'bestaudio/best',
'--dump-single-json',
'--no-playlist',
'--',
videoUrl,
]);
const info = JSON.parse(stdout.trim());
if (!info.url) {
throw new Error('yt-dlp did not return a stream URL');
}
return { url: info.url, httpHeaders: info.http_headers || {} };
}
function buildFfmpegHeaderArgs(httpHeaders) {
const serializedHeaders = Object.entries(httpHeaders || {})
.filter(([name, value]) => name && value != null)
.map(([name, value]) => `${String(name).replace(/[\r\n:]/g, '')}: ${String(value).replace(/[\r\n]/g, '')}\r\n`)
.join('');
return serializedHeaders ? ['-headers', serializedHeaders] : [];
}
function addToQueue(message, video, guildId, guildStates, options = {}) {
const { announce = true } = options;
const state = guildStates.get(guildId);
if (!state || !video) return false;
state.queue.push(video);
if (announce) {
const queueEmbed = new EmbedBuilder()
.setColor('#FF0000')
.setTitle('Lisatud jarkorda')
.setDescription(`[${video.title}](${video.url})\nKestus: ${video.durationRaw || 'N/A'}`)
.setThumbnail(video.thumbnails?.[0]?.url || null)
.setFooter({ text: `Lisas: ${message.author.tag}` });
message.channel.send({ embeds: [queueEmbed] }).catch(console.error);
}
if (!state.player || state.player.state.status === AudioPlayerStatus.Idle || state.currentSourceType !== 'youtube') {
playFromQueue(guildId, guildStates);
}
return true;
}
async function queueFromSearch(message, query, guildStates, options = {}) {
const connectionInfo = await ensureVoiceConnection(message, guildStates);
if (!connectionInfo) return { ok: false, reason: 'voice' };
try {
const video = await searchFirstVideo(query);
if (!video) {
return { ok: false, reason: 'not_found', query };
}
addToQueue(message, video, connectionInfo.guildId, guildStates, options);
return { ok: true, video, query };
} catch (error) {
console.error(`[YT] Error resolving YouTube video for guild ${connectionInfo.guildId}:`, error);
return { ok: false, reason: 'search_error', query, error };
}
}
async function queueMultipleSearches(message, queries, guildStates) {
const results = [];
for (const query of queries) {
const result = await queueFromSearch(message, query, guildStates, { announce: false });
results.push(result);
}
return results;
}
async function playYouTube(message, args, guildStates) {
if (!args.length) {
return message.reply("Palun sisesta YouTube'i otsingusona voi link.");
}
try {
await message.react('🔍').catch(() => {});
const result = await queueFromSearch(message, args.join(' '), guildStates);
await message.reactions.removeAll().catch(() => {});
if (!result.ok) {
if (result.reason === 'voice') return;
if (result.reason === 'not_found') {
return message.reply('Ei leidnud selle paringuga YouTube videot.');
}
return message.reply('YouTube otsingul tekkis viga.');
}
} catch (error) {
console.error('[YT] Unexpected playYouTube error:', error);
await message.reactions.removeAll().catch(() => {});
return message.reply('YouTube otsingul tekkis viga.');
}
}
async function playFromQueue(guildId, guildStates) {
const state = guildStates.get(guildId);
if (!state) {
console.log(`[YT Playback] No state for guild ${guildId}`);
return;
}
if (!state.connection || state.connection.state?.status === VoiceConnectionStatus.Destroyed) {
console.log(`[YT Playback] No usable connection for guild ${guildId}`);
guildStates.delete(guildId);
return;
}
try {
if (state.connection.state.status !== VoiceConnectionStatus.Ready) {
console.log(`[YT Playback] Waiting for connection to be Ready for guild ${guildId}`);
await entersState(state.connection, VoiceConnectionStatus.Ready, 15_000);
}
} catch (error) {
console.error(`[YT Playback] Connection did not become Ready for guild ${guildId}:`, error);
try {
if (state.connection && state.connection.state?.status !== VoiceConnectionStatus.Destroyed) {
state.connection.destroy();
}
} catch (_) {}
guildStates.delete(guildId);
return;
}
if (!state.queue || state.queue.length === 0) {
console.log(`[YT Playback] Queue empty for guild ${guildId}`);
state.currentSourceType = null;
state.timeoutId = setTimeout(() => {
const latestState = guildStates.get(guildId);
if (latestState && latestState.connection && latestState.connection.state.status !== VoiceConnectionStatus.Destroyed) {
const playerIdle = !latestState.player || latestState.player.state.status === AudioPlayerStatus.Idle;
const queueEmpty = !latestState.queue || latestState.queue.length === 0;
if (playerIdle && queueEmpty) {
latestState.textChannel?.send('YouTube jarkord on tuhi, lahkun kanalist passiivsuse tottu.').catch(console.error);
try {
latestState.connection.destroy();
} catch (_) {}
}
guildStates.delete(guildId);
}
}, 300_000);
state.textChannel?.send('YouTube jarkord on tuhi.').catch(console.error);
return;
}
if (state.player && state.currentSourceType && state.currentSourceType !== 'youtube') {
console.log(`[YT Playback] Stopping previous source (${state.currentSourceType}) for guild ${guildId}`);
try {
state.player.stop(true);
} catch (_) {}
}
state.currentSourceType = 'youtube';
const video = state.queue[0];
if (!state.player) {
state.player = createAudioPlayer();
state.playerListenersAttached = false;
attachLocalPlayerListeners(guildId, guildStates);
state.connection.subscribe(state.player);
console.log(`[YT Playback] Created and subscribed new player for guild ${guildId}`);
} else if (!state.connection.state.subscription || state.connection.state.subscription.player !== state.player) {
state.connection.subscribe(state.player);
console.log(`[YT Playback] Resubscribed player for guild ${guildId}`);
}
try {
console.log(`[YT Playback] Streaming: ${video.title} (${video.url}) for guild ${guildId}`);
const stream = await resolveYtDlpStream(video.url);
const ffmpegStream = new prism.FFmpeg({
args: [
'-reconnect', '1',
'-reconnect_streamed', '1',
'-reconnect_delay_max', '5',
'-analyzeduration', '0',
'-loglevel', '0',
...buildFfmpegHeaderArgs(stream.httpHeaders),
'-i', stream.url,
'-map_metadata', '-1',
'-c:a', 'libopus',
'-ar', '48000',
'-ac', '2',
'-f', 'ogg',
],
});
state.currentYtDlpProcess = ffmpegStream;
const resource = createAudioResource(ffmpegStream, { inputType: StreamType.OggOpus });
state.player.play(resource);
try {
await entersState(state.player, AudioPlayerStatus.Playing, 5_000);
console.log(`[YT Playback] Player now Playing for guild ${guildId}`);
} catch (error) {
console.warn(`[YT Playback] Player did not enter Playing state in time for guild ${guildId}:`, error?.message || error);
}
const playingEmbed = new EmbedBuilder()
.setColor('#FF0000')
.setTitle('Mangib nuud (YouTube)')
.setDescription(`[${video.title}](${video.url})\nKestus: ${video.durationRaw || 'N/A'}`)
.setThumbnail(video.thumbnails?.[0]?.url || null)
.setTimestamp();
state.textChannel?.send({ embeds: [playingEmbed] }).catch(console.error);
} catch (error) {
console.error(`[YT Playback] Error playing ${video?.title || 'unknown'} for guild ${guildId}:`, error);
state.textChannel?.send(`Viga video mangimisel: ${error.message || error}`).catch(console.error);
state.queue.shift();
playFromQueue(guildId, guildStates);
}
}
function attachLocalPlayerListeners(guildId, guildStates) {
const state = guildStates.get(guildId);
if (!state || !state.player || state._localPlayerListenersAttached) return;
state._localPlayerListenersAttached = true;
state.player.on(AudioPlayerStatus.Idle, (oldState) => {
const currentState = guildStates.get(guildId);
if (!currentState) return;
currentState.currentYtDlpProcess = null;
if (oldState?.status === AudioPlayerStatus.Playing) {
currentState.queue.shift();
if (currentState.queue && currentState.queue.length > 0) {
setImmediate(() => playFromQueue(guildId, guildStates));
} else {
currentState.currentSourceType = null;
currentState.textChannel?.send('Jarkord loppes.').catch(console.error);
clearTimeout(currentState.timeoutId);
currentState.timeoutId = setTimeout(() => {
const latest = guildStates.get(guildId);
if (latest && latest.connection && latest.connection.state.status !== VoiceConnectionStatus.Destroyed) {
try {
latest.connection.destroy();
} catch (_) {}
guildStates.delete(guildId);
}
}, 300_000);
}
} else {
console.log(`[YT Local Listener] Idle but previous status not Playing for guild ${guildId} (was ${oldState?.status})`);
}
});
state.player.on('error', (error) => {
const currentState = guildStates.get(guildId);
if (!currentState) return;
currentState.currentYtDlpProcess = null;
console.error(`[YT Local Listener] Player error for guild ${guildId}:`, error);
currentState.textChannel?.send(`Pleieril viga: ${error.message || error}`).catch(console.error);
if (currentState.queue && currentState.queue.length > 0) {
currentState.queue.shift();
setImmediate(() => playFromQueue(guildId, guildStates));
} else {
try {
currentState.connection?.destroy();
} catch (_) {}
guildStates.delete(guildId);
}
});
state.player.on(AudioPlayerStatus.Playing, () => {
const currentState = guildStates.get(guildId);
if (!currentState) return;
clearTimeout(currentState.timeoutId);
console.log(`[YT Local Listener] Player started playing (guild ${guildId}).`);
});
}
async function skipSong(message, guildStates) {
const guildId = message.guild.id;
const state = guildStates.get(guildId);
if (!state || !state.player) {
return message.reply('Praegu ei mangi midagi.');
}
if (state.currentSourceType !== 'youtube') {
return message.reply('Praegu ei mangi YouTube jarkorda, ei saa vahele jatta.');
}
if (!state.queue || state.queue.length <= 1) {
if (!state.queue || state.queue.length === 0) {
return message.reply('Jarkord on tuhi, midagi pole vahele jatta.');
}
return message.reply('Jarkorras pole rohkem laule peale praeguse.');
}
const skippedVideo = state.queue[0];
message.reply(`Jatan vahele: ${skippedVideo.title}`).catch(console.error);
try {
state.player.stop(true);
} catch (error) {
console.error('[skipSong] player.stop error', error);
}
}
async function showQueue(message, guildStates) {
const guildId = message.guild.id;
const state = guildStates.get(guildId);
if (!state || !state.queue || state.queue.length === 0) {
return message.reply('Jarkord on tuhi.');
}
const nowPlaying = state.queue[0];
const upcoming = state.queue.slice(1, 11);
const embed = new EmbedBuilder()
.setColor('#FF0000')
.setTitle('Muusika jarkord')
.setDescription(
`**Praegu mangib:**\n[${nowPlaying.title}](${nowPlaying.url}) - ${nowPlaying.durationRaw || 'N/A'}\n\n` +
(upcoming.length > 0
? `**Jargmisena (${upcoming.length}/${state.queue.length - 1}):**\n` +
upcoming.map((video, index) => `${index + 1}. [${video.title}](${video.url}) - ${video.durationRaw || 'N/A'}`).join('\n')
: 'Rohkem laule jarkorras pole.') +
(state.queue.length > 11 ? `\n...ja veel ${state.queue.length - 11} laulu.` : '')
)
.setTimestamp();
message.channel.send({ embeds: [embed] }).catch(console.error);
}
module.exports = {
playYouTube,
playFromQueue,
queueFromSearch,
queueMultipleSearches,
skipSong,
showQueue,
};