Update download method
This commit is contained in:
parent
e82c027ad9
commit
08578eef0b
5 changed files with 128 additions and 23 deletions
21
src/lib/client/downloader.ts
Normal file
21
src/lib/client/downloader.ts
Normal file
|
@ -0,0 +1,21 @@
|
|||
const createAnchorElement = (url: string, filename: string): HTMLAnchorElement => {
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = filename;
|
||||
return anchor
|
||||
}
|
||||
export const download = async (url: string, filename: string) => {
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const objectURL = window.URL.createObjectURL(blob);
|
||||
const anchor = createAnchorElement(url, filename)
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
window.URL.revokeObjectURL(objectURL);
|
||||
}
|
|
@ -1,3 +1,69 @@
|
|||
<script lang="ts">
|
||||
let props = $props();
|
||||
import { onMount } from 'svelte';
|
||||
let { url, dismiss } = $props();
|
||||
|
||||
let visible = $state(false);
|
||||
let progress = $state(0);
|
||||
let filename = $state('');
|
||||
onMount(async () => {
|
||||
if (!url) return;
|
||||
|
||||
try {
|
||||
visible = true;
|
||||
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error('Download failed');
|
||||
|
||||
const contentDisposition: string = response?.headers?.get('content-disposition');
|
||||
filename = contentDisposition.split('filename=')[1];
|
||||
const contentLength: number = Number(response?.headers?.get('content-length'));
|
||||
const reader = response?.body?.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let receivedLength = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value }: ReadableStreamReadResult<Uint8Array> = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
chunks.push(value);
|
||||
receivedLength += value.length;
|
||||
progress = Math.round((receivedLength / contentLength) * 100);
|
||||
}
|
||||
}
|
||||
|
||||
const blob = new Blob(chunks);
|
||||
const downloadUrl = URL.createObjectURL(blob);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = downloadUrl;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
|
||||
URL.revokeObjectURL(downloadUrl);
|
||||
|
||||
setTimeout(() => {
|
||||
visible = false;
|
||||
}, 1500); // auto-dismiss
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
visible = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if visible}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm font-mono">
|
||||
<div class="w-[90%] max-w-sm rounded-2xl border border-green-400 bg-[#000f00] p-6 text-green-300 shadow-2xl text-sm">
|
||||
<p class="mb-2 text-center text-cyan-300">
|
||||
Downloading <span class="text-green-400 font-semibold">{filename}</span>
|
||||
</p>
|
||||
<div class="w-full h-4 rounded-md bg-black border border-green-500 overflow-hidden">
|
||||
<div
|
||||
class="h-full bg-gradient-to-r from-green-400 to-green-600 transition-all duration-300"
|
||||
style="width: {progress}%"
|
||||
/>
|
||||
</div>
|
||||
<p class="mt-2 text-center text-pink-400">{progress}%</p>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
|
|
@ -5,7 +5,7 @@ import supportedFormats from '$lib/common/supportedFormats.json';
|
|||
import { logger, mimeTypeMap } from '$lib/server/helpers';
|
||||
|
||||
const YTDLP_PATH: string = env.YTDLP_PATH as string;
|
||||
const HTTPS_PROXY: string = env.v as string;
|
||||
const HTTPS_PROXY: string = env.HTTPS_PROXY as string;
|
||||
|
||||
export const ytdl = create(YTDLP_PATH);
|
||||
|
||||
|
@ -13,17 +13,22 @@ export const ytdl = create(YTDLP_PATH);
|
|||
* Fetch YouTube metadata (title, uploader/artist)
|
||||
*/
|
||||
export async function getYouTubeMetadata(link: string) {
|
||||
return await ytdl(link, {
|
||||
const options = {
|
||||
dumpSingleJson: true,
|
||||
noCheckCertificates: true,
|
||||
noWarnings: true,
|
||||
preferFreeFormats: true,
|
||||
proxy: HTTPS_PROXY ? HTTPS_PROXY : ''
|
||||
});
|
||||
}
|
||||
|
||||
if (HTTPS_PROXY) {
|
||||
options.proxy = HTTPS_PROXY;
|
||||
}
|
||||
|
||||
return await ytdl(link, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams the YouTube video/audio using yt-dlp
|
||||
* Streams the YouTube video/audio using youtube-dl-exec
|
||||
*/
|
||||
export function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> {
|
||||
logger.debug(`Starting to stream: ${link}`);
|
||||
|
|
|
@ -2,7 +2,9 @@
|
|||
import { PUBLIC_VERSION } from '$env/static/public';
|
||||
import supportedFormats from '$lib/common/supportedFormats.json';
|
||||
import Loader from '$lib/components/Loader.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import { download } from '$lib/client/downloader';
|
||||
import DownloadManager from '$lib/components/DownloadManager.svelte';
|
||||
import { mount, unmount } from 'svelte';
|
||||
|
||||
let source = $state('youtube');
|
||||
let link = $state('');
|
||||
|
@ -12,6 +14,7 @@
|
|||
let disabled = $state(true);
|
||||
let metadata = $state(false);
|
||||
let logs = $state('');
|
||||
let downloadManager: DownloadManager|null = null;
|
||||
|
||||
const formats = Object.keys(supportedFormats).map((f) => {
|
||||
return { value: f, label: f.toUpperCase() };
|
||||
|
@ -25,7 +28,16 @@
|
|||
showModal = !showModal;
|
||||
};
|
||||
|
||||
const onClick = () => {
|
||||
const dismiss = () => {
|
||||
unmount(downloadManager)
|
||||
}
|
||||
|
||||
const onClick = async (evt) => {
|
||||
evt.preventDefault();
|
||||
|
||||
const props = $state( { url: href });
|
||||
downloadManager = mount(DownloadManager, { target: document.body, props, events: { dismiss } });
|
||||
|
||||
link = '';
|
||||
};
|
||||
|
||||
|
@ -166,7 +178,6 @@
|
|||
id="btn-download"
|
||||
{href}
|
||||
onclick={onClick}
|
||||
rel="external"
|
||||
class="{disabled
|
||||
? 'pointer-events-none opacity-50'
|
||||
: ''} block w-full rounded-md border border-pink-400 bg-pink-600 px-4 py-3 text-center text-base font-bold text-black transition hover:bg-pink-500 active:border-yellow-400"
|
||||
|
|
|
@ -38,28 +38,30 @@ const validateRequest = (url: URL) => {
|
|||
};
|
||||
export const GET: RequestHandler = async ({ url }) => {
|
||||
const { format, source, metadata, link } = validateRequest(url);
|
||||
let filename = `noname.${format}`;
|
||||
let filename = '';
|
||||
let contentLength = 0;
|
||||
|
||||
if (!!metadata) {
|
||||
try {
|
||||
logger.debug(`Fetching video data to set filename`);
|
||||
// Fetch metadata for filename
|
||||
const ytMetadata = await getYouTubeMetadata(link);
|
||||
const { title, uploader } = ytMetadata;
|
||||
const safeTitle = `${uploader} - ${title}`;
|
||||
filename = `${safeTitle}.${format}`;
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
logger.error('Error fetching metadata:');
|
||||
throw error(500, 'Failed to fetch video metadata');
|
||||
}
|
||||
try {
|
||||
logger.debug(`Fetching video data to set filename`);
|
||||
// Fetch metadata for filename
|
||||
const ytMetadata = await getYouTubeMetadata(link);
|
||||
const { title, uploader, filesize_approx } = ytMetadata;
|
||||
contentLength = filesize_approx;
|
||||
const safeTitle = `${uploader} - ${title}`;
|
||||
filename = `${safeTitle}.${format}`;
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
logger.error('Error fetching metadata:');
|
||||
throw error(500, 'Failed to fetch video metadata');
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
// Stream video/audio
|
||||
return new Response(streamYouTube(link, format), {
|
||||
headers: {
|
||||
'Content-Type': `${mimeTypeMap.get(format)}`,
|
||||
'Content-Length': contentLength,
|
||||
'Content-Disposition': `attachment; filename="${filename}"`
|
||||
}
|
||||
});
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue