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">
|
<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>
|
</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';
|
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;
|
||||||
const HTTPS_PROXY: string = env.v as string;
|
const HTTPS_PROXY: string = env.HTTPS_PROXY as string;
|
||||||
|
|
||||||
export const ytdl = create(YTDLP_PATH);
|
export const ytdl = create(YTDLP_PATH);
|
||||||
|
|
||||||
|
@ -13,17 +13,22 @@ export const ytdl = create(YTDLP_PATH);
|
||||||
* Fetch YouTube metadata (title, uploader/artist)
|
* Fetch YouTube metadata (title, uploader/artist)
|
||||||
*/
|
*/
|
||||||
export async function getYouTubeMetadata(link: string) {
|
export async function getYouTubeMetadata(link: string) {
|
||||||
return await ytdl(link, {
|
const options = {
|
||||||
dumpSingleJson: true,
|
dumpSingleJson: true,
|
||||||
noCheckCertificates: true,
|
noCheckCertificates: true,
|
||||||
noWarnings: true,
|
noWarnings: true,
|
||||||
preferFreeFormats: 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> {
|
export function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> {
|
||||||
logger.debug(`Starting to stream: ${link}`);
|
logger.debug(`Starting to stream: ${link}`);
|
||||||
|
|
|
@ -2,7 +2,9 @@
|
||||||
import { PUBLIC_VERSION } from '$env/static/public';
|
import { PUBLIC_VERSION } from '$env/static/public';
|
||||||
import supportedFormats from '$lib/common/supportedFormats.json';
|
import supportedFormats from '$lib/common/supportedFormats.json';
|
||||||
import Loader from '$lib/components/Loader.svelte';
|
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 source = $state('youtube');
|
||||||
let link = $state('');
|
let link = $state('');
|
||||||
|
@ -12,6 +14,7 @@
|
||||||
let disabled = $state(true);
|
let disabled = $state(true);
|
||||||
let metadata = $state(false);
|
let metadata = $state(false);
|
||||||
let logs = $state('');
|
let logs = $state('');
|
||||||
|
let downloadManager: DownloadManager|null = null;
|
||||||
|
|
||||||
const formats = Object.keys(supportedFormats).map((f) => {
|
const formats = Object.keys(supportedFormats).map((f) => {
|
||||||
return { value: f, label: f.toUpperCase() };
|
return { value: f, label: f.toUpperCase() };
|
||||||
|
@ -25,7 +28,16 @@
|
||||||
showModal = !showModal;
|
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 = '';
|
link = '';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -166,7 +178,6 @@
|
||||||
id="btn-download"
|
id="btn-download"
|
||||||
{href}
|
{href}
|
||||||
onclick={onClick}
|
onclick={onClick}
|
||||||
rel="external"
|
|
||||||
class="{disabled
|
class="{disabled
|
||||||
? 'pointer-events-none opacity-50'
|
? '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"
|
: ''} 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,14 +38,15 @@ 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);
|
||||||
let filename = `noname.${format}`;
|
let filename = '';
|
||||||
|
let contentLength = 0;
|
||||||
|
|
||||||
if (!!metadata) {
|
|
||||||
try {
|
try {
|
||||||
logger.debug(`Fetching video data to set filename`);
|
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, filesize_approx } = ytMetadata;
|
||||||
|
contentLength = filesize_approx;
|
||||||
const safeTitle = `${uploader} - ${title}`;
|
const safeTitle = `${uploader} - ${title}`;
|
||||||
filename = `${safeTitle}.${format}`;
|
filename = `${safeTitle}.${format}`;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
@ -53,13 +54,14 @@ export const GET: RequestHandler = async ({ url }) => {
|
||||||
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');
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Stream video/audio
|
// Stream video/audio
|
||||||
return new Response(streamYouTube(link, format), {
|
return new Response(streamYouTube(link, format), {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': `${mimeTypeMap.get(format)}`,
|
'Content-Type': `${mimeTypeMap.get(format)}`,
|
||||||
|
'Content-Length': contentLength,
|
||||||
'Content-Disposition': `attachment; filename="${filename}"`
|
'Content-Disposition': `attachment; filename="${filename}"`
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue