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

7
src/hooks.server.ts Normal file
View file

@ -0,0 +1,7 @@
import { logger } from "$lib/server/helpers";
export async function handle({ event, resolve }) {
logger.info(`Received request: ${event.url}`);
return await resolve(event);;
}

View file

@ -2,7 +2,7 @@ import { create } from 'youtube-dl-exec';
import { env } from '$env/dynamic/private'; import { env } from '$env/dynamic/private';
import { spawn } from 'node:child_process'; import { spawn } from 'node:child_process';
import supportedFormats from '$lib/common/supportedFormats.json'; 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; 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 * Streams the YouTube video/audio using youtube-dl-exec
*/ */
export function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> { export function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> {
logger.debug(`Starting to stream: ${link}`);
const mimeType: string | undefined = mimeTypeMap.get(format) const mimeType: string | undefined = mimeTypeMap.get(format)
if (!mimeType) { if (!mimeType) {
throw new Error("Unsupported format"); throw new Error("Unsupported format");
} }
logger.debug(`Given format is compatible: ${mimeType}`);
return new ReadableStream({ return new ReadableStream({
start(controller) { start(controller) {
const args = [ const args = [
'--no-write-thumbnail',
'-o', '-o',
'-', '-',
].filter(Boolean); ].filter(Boolean);
if(mimeType?.includes('audio')) { if (mimeType?.includes('audio')) {
args.push(...['--extract-audio', '--embed-metadata', '--embed-thumbnail', '--audio-format', format]) args.push(...['--extract-audio', '--embed-metadata', '--embed-thumbnail', '--audio-format', format])
} else if (mimeType.includes('video')) { } else if (mimeType.includes('video')) {
args.push(...['--embed-metadata', '--embed-thumbnail', '--format', format]) 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('data', (chunk) => {
process.stdout.on('end', () => controller.close()); 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) => { process.stdout.on('error', (err) => {
console.error('Stream error:', err); console.error('Stream error:', err);
controller.error(err); controller.error(err);

View file

@ -1,14 +1,14 @@
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { getYouTubeMetadata, streamYouTube, ytdl } from '$lib/server/ytdlp'; import { getYouTubeMetadata, streamYouTube, ytdl } from '$lib/server/ytdlp';
import { isURLValid, mimeTypeMap } from '$lib/server/helpers'; import { isURLValid, logger, mimeTypeMap } from '$lib/server/helpers';
const validateRequest = (url: URL) => { const validateRequest = (url: URL) => {
// Get query params // Get query params
const link = url.searchParams.get('link'); const link = url.searchParams.get('link');
const format = url.searchParams.get('format'); // mp3, mp4 const format = url.searchParams.get('format'); // mp3, mp4
const source = url.searchParams.get('source'); // youtube or spotify const source = url.searchParams.get('source'); // youtube or spotify
const metadata = url.searchParams.get('metadata'); const metadata = url.searchParams.has('metadata');
// Validate input // Validate input
if (!link || !format || !source) { if (!link || !format || !source) {
@ -32,11 +32,13 @@ const validateRequest = (url: URL) => {
} }
} }
export const GET: RequestHandler = async ({ url }) => { export const GET: RequestHandler = async ({ url }) => {
const { format, source, metadata, link } = validateRequest(url) const { format, source, metadata, link } = validateRequest(url);
logger.debug(`Request is valid`);
let filename = `you-clicked-no-metadata-so-i-cant-put-a-correct-name.${format}`; let filename = `you-clicked-no-metadata-so-i-cant-put-a-correct-name.${format}`;
if (!!metadata) { if (!!metadata) {
try { try {
logger.debug(`Fetching video data to set filename`);
// Fetch metadata for filename // Fetch metadata for filename
const ytMetadata = await getYouTubeMetadata(link); const ytMetadata = await getYouTubeMetadata(link);
const { title, uploader } = ytMetadata; const { title, uploader } = ytMetadata;