Use winston and error management of stream controller
All checks were successful
Bump deps (only minor versions) / ci (push) Successful in 20s

This commit is contained in:
0d0 2025-02-25 14:26:07 +01:00
parent 0b58d9251e
commit 24ff0a0738
3 changed files with 36 additions and 10 deletions

View file

@ -2,7 +2,7 @@ import { create } from 'youtube-dl-exec';
import { env } from '$env/dynamic/private';
import { spawn } from 'node:child_process';
import supportedFormats from '$lib/common/supportedFormats.json';
import { mimeTypeMap } from '$lib/server/helpers';
import { logger, mimeTypeMap } from '$lib/server/helpers';
const YTDLP_PATH: string = env.YTDLP_PATH as string;
@ -24,31 +24,48 @@ export async function getYouTubeMetadata(link: string) {
* Streams the YouTube video/audio using youtube-dl-exec
*/
export function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> {
logger.debug(`Starting to stream: ${link}`);
const mimeType: string | undefined = mimeTypeMap.get(format)
if (!mimeType) {
throw new Error("Unsupported format");
}
logger.debug(`Given format is compatible: ${mimeType}`);
return new ReadableStream({
start(controller) {
const args = [
'--no-write-thumbnail',
'-o',
'-',
].filter(Boolean);
if(mimeType?.includes('audio')) {
if (mimeType?.includes('audio')) {
args.push(...['--extract-audio', '--embed-metadata', '--embed-thumbnail', '--audio-format', format])
} else if (mimeType.includes('video')) {
args.push(...['--embed-metadata', '--embed-thumbnail', '--format', format])
}
console.info(`${YTDLP_PATH} ${args.join(' ')} ${link}`)
const cmd = `${YTDLP_PATH} ${args.join(' ')} ${link}`
logger.debug(`Running: ${cmd}`);
const process = spawn(YTDLP_PATH, [...args, link], { stdio: ['ignore', 'pipe', 'ignore'] });
const process = spawn(YTDLP_PATH, [...args, link], { cwd: "/tmp", stdio: ['ignore', 'pipe', 'pipe'] });
process.stdout.on('data', (chunk) => controller.enqueue(chunk));
process.stdout.on('end', () => controller.close());
process.stdout.on('data', (chunk) => {
try {
controller.enqueue(chunk)
} catch (ex) {
process.kill()
}
});
process.stderr.on('data', (chunk) => logger.debug(chunk.toString()));
process.stdout.on('end', () => {
try {
controller.close()
} catch (ex) {
process.kill()
}
});
process.stdout.on('error', (err) => {
console.error('Stream error:', err);
controller.error(err);