Add ytdlp binary

This commit is contained in:
0d0 2025-02-14 18:47:17 +01:00
parent ce59825161
commit 7789c0921c
4 changed files with 149 additions and 117 deletions

View file

@ -1,51 +1,8 @@
import { DOWNLOAD_PATH } from '$env/static/private';
import { redirect } from '@sveltejs/kit';
import ytdl from 'youtube-dl-exec';
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { spawn } from 'child_process';
import { getYouTubeMetadata, streamYouTube } from '$lib/server/ytdlp';
/**
* Fetch YouTube metadata (title, uploader/artist)
*/
async function getYouTubeMetadata(link: string) {
return await ytdl(link, {
dumpSingleJson: true,
noCheckCertificates: true,
noWarnings: true,
preferFreeFormats: true
});
}
/**
* Streams the YouTube video/audio using youtube-dl-exec
*/
function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
const args = [
'-o',
'-',
format === 'mp3' ? '--embed-metadata' : '',
'--format',
format === 'mp3' ? 'bestaudio' : 'best',
'--audio-format',
format === 'mp3' ? 'mp3' : '',
'--no-playlist'
].filter(Boolean);
const process = spawn('yt-dlp', [...args, link], { stdio: ['ignore', 'pipe', 'ignore'] });
process.stdout.on('data', (chunk) => controller.enqueue(chunk));
process.stdout.on('end', () => controller.close());
process.stdout.on('error', (err) => {
console.error('Stream error:', err);
controller.error(err);
});
}
});
}
/**
* Sanitize filename by removing unsafe characters
*/