it's cool that we have format
All checks were successful
Bump deps (only minor versions) / ci (push) Successful in 18s

This commit is contained in:
0d0 2025-02-25 17:06:41 +01:00
parent 760812c692
commit 652208aa57
6 changed files with 69 additions and 60 deletions

View file

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

View file

@ -1,6 +1,6 @@
{ {
"mp3": "audio/mpeg", "mp3": "audio/mpeg",
"opus": "audio/ogg", "opus": "audio/ogg",
"wav": "audio/wav", "wav": "audio/wav",
"mp4": "video/mp4" "mp4": "video/mp4"
} }

View file

@ -2,18 +2,18 @@ import formats from '$lib/common/supportedFormats.json';
import winston from 'winston'; import winston from 'winston';
export const logger = winston.createLogger({ export const logger = winston.createLogger({
level: 'debug', level: 'debug',
format: winston.format.json(), format: winston.format.json(),
transports: [new winston.transports.Console()], transports: [new winston.transports.Console()]
}); });
const formatMime = new Map(Object.entries(formats)) const formatMime = new Map(Object.entries(formats));
export const isURLValid = (url: string) => { export const isURLValid = (url: string) => {
try { try {
new URL(url) new URL(url);
} catch { } catch {
return false return false;
} }
return true; return true;
} };
export const mimeTypeMap = formatMime; export const mimeTypeMap = formatMime;

View file

@ -25,45 +25,46 @@ export async function getYouTubeMetadata(link: string) {
*/ */
export function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> { export function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> {
logger.debug(`Starting to stream: ${link}`); 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}`); 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', '-'].filter(Boolean);
'--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]) 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]);
} }
const cmd = `${YTDLP_PATH} ${args.join(' ')} ${link}` const cmd = `${YTDLP_PATH} ${args.join(' ')} ${link}`;
logger.debug(`Running: ${cmd}`); logger.debug(`Running: ${cmd}`);
const process = spawn(YTDLP_PATH, [...args, link], { cwd: "/tmp", stdio: ['ignore', 'pipe', 'pipe'] }); const process = spawn(YTDLP_PATH, [...args, link], {
cwd: '/tmp',
stdio: ['ignore', 'pipe', 'pipe']
});
process.stdout.on('data', (chunk) => { process.stdout.on('data', (chunk) => {
try { try {
controller.enqueue(chunk) controller.enqueue(chunk);
} catch (ex) { } catch (ex) {
process.kill() process.kill();
} }
}); });
process.stderr.on('data', (chunk) => logger.debug(chunk.toString())); process.stderr.on('data', (chunk) => logger.debug(chunk.toString()));
process.stdout.on('end', () => { process.stdout.on('end', () => {
try { try {
controller.close() controller.close();
} catch (ex) { } catch (ex) {
logger.error(ex) logger.error(ex);
} }
}); });
process.stdout.on('error', (err) => { process.stdout.on('error', (err) => {

View file

@ -24,21 +24,21 @@
}; };
onMount(() => { onMount(() => {
document.cookie = 'downloading=0' document.cookie = 'downloading=0';
}); });
const readLogs = () => { const readLogs = () => {
logId = setInterval(() => { logId = setInterval(() => {
logs += "We're downloading <br>" logs += "We're downloading <br>";
}, 2000) }, 2000);
} };
const onClick = () => { const onClick = () => {
let checkIterations = 0; let checkIterations = 0;
link = ''; link = '';
downloading = true; downloading = true;
document.cookie = 'downloading=1' document.cookie = 'downloading=1';
readLogs() readLogs();
const id = setInterval(() => { const id = setInterval(() => {
if (document.cookie.includes('downloading=0') || checkIterations > 3) { if (document.cookie.includes('downloading=0') || checkIterations > 3) {
@ -72,8 +72,7 @@
searchParams.append('link', link); searchParams.append('link', link);
searchParams.append('format', format); searchParams.append('format', format);
if (metadata) if (metadata) searchParams.append('metadata', '1');
searchParams.append('metadata', "1");
href = `/download?${searchParams.toString()}`; href = `/download?${searchParams.toString()}`;
}; };
@ -88,12 +87,18 @@
} }
}); });
</script> </script>
<div <div
id="wrapper" id="wrapper"
class="relative mx-auto rounded-lg bg-black p-6 text-[#00ff7f] shadow-lg sm:max-w-sm sm:border-4 sm:border-[#00ff7f] md:mt-10 md:max-w-md lg:max-w-lg 2xl:max-w-2xl" class="relative mx-auto rounded-lg bg-black p-6 text-[#00ff7f] shadow-lg sm:max-w-sm sm:border-4 sm:border-[#00ff7f] md:mt-10 md:max-w-md lg:max-w-lg 2xl:max-w-2xl"
> >
<div
<div id="loader" class={["backdrop-blur-xs bg-black/20 absolute inset-0 z-10 flex items-center justify-center", { downloading }]}> id="loader"
class={[
'absolute inset-0 z-10 flex items-center justify-center bg-black/20 backdrop-blur-xs',
{ downloading }
]}
>
<Loader /> <Loader />
{@html logs} {@html logs}
</div> </div>
@ -182,7 +187,9 @@
<!-- Metadata --> <!-- Metadata -->
<div> <div>
<label for="metadata" class="mb-2 block text-[#00e5ff]">Set filename (<span class='text-red-700'>SLOW</span>)</label> <label for="metadata" class="mb-2 block text-[#00e5ff]"
>Set filename (<span class="text-red-700">SLOW</span>)</label
>
<input <input
type="checkbox" type="checkbox"
id="metadata" id="metadata"
@ -218,7 +225,7 @@
source, paste the link, and select a format to start downloading! source, paste the link, and select a format to start downloading!
</p> </p>
<span class="mt-10 block"> <span class="mt-10 block">
<a class="underline text-[#00e5ff]" href="https://git.pweapon.org/odo/dl.emersa.it" <a class="text-[#00e5ff] underline" href="https://git.pweapon.org/odo/dl.emersa.it"
>Click here for the source code</a >Click here for the source code</a
> >
</span> </span>
@ -237,10 +244,10 @@
font-family: 'Press Start 2P', cursive; font-family: 'Press Start 2P', cursive;
} }
@media (max-height: 1000px) { @media (max-height: 1000px) {
* { * {
font-size: 10px; font-size: 10px;
} }
} }
@media (min-width: 1024px) { @media (min-width: 1024px) {
* { * {
@ -248,14 +255,13 @@
} }
} }
#loader { #loader {
display: none; display: none;
} }
#loader.downloading { #loader.downloading {
display: grid; display: grid;
justify-items: center; justify-items: center;
align-items: center; align-items: center;
} }
.not-available { .not-available {
text-decoration-line: line-through; text-decoration-line: line-through;

View file

@ -30,9 +30,12 @@ const validateRequest = (url: URL) => {
logger.debug(`Request is valid`); logger.debug(`Request is valid`);
return { return {
link, format, source, metadata link,
} format,
} source,
metadata
};
};
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);
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}`;
@ -46,7 +49,7 @@ export const GET: RequestHandler = async ({ url }) => {
const safeTitle = `${uploader} - ${title}`; const safeTitle = `${uploader} - ${title}`;
filename = `${safeTitle}.${format}`; filename = `${safeTitle}.${format}`;
} catch (err) { } catch (err) {
logger.error(err) logger.error(err);
logger.error('Error fetching metadata:'); logger.error('Error fetching metadata:');
throw error(500, 'Failed to fetch video metadata'); throw error(500, 'Failed to fetch video metadata');
} }
@ -56,14 +59,13 @@ export const GET: RequestHandler = async ({ url }) => {
// Stream video/audio // Stream video/audio
return new Response(streamYouTube(link, format), { return new Response(streamYouTube(link, format), {
headers: { headers: {
'Content-Type': "text/event-stream", 'Content-Type': 'text/event-stream',
'Content-Disposition': `attachment; filename="${filename}"`, 'Content-Disposition': `attachment; filename="${filename}"`,
'Set-Cookie': 'downloading=0' 'Set-Cookie': 'downloading=0'
} }
}); });
} catch (err) { } catch (err) {
logger.error(err) logger.error(err);
logger.error('Filed to stream file'); logger.error('Filed to stream file');
throw error(500, 'Failed to stream file'); throw error(500, 'Failed to stream file');
} }