Initial commit

This commit is contained in:
0d0 2025-01-24 19:04:29 +01:00
commit 1f35f0411b
28 changed files with 5703 additions and 0 deletions

View file

@ -0,0 +1,40 @@
name: Update Minor Dependencies and Build Container
on:
schedule:
- cron: '0 0 * * *' # Runs every night at midnight (UTC)
workflow_dispatch: # Allows manual triggering
jobs:
update-dependencies:
runs-on: docker
steps:
- name: Checkout Repository
uses: actions/checkout@v3
with:
token: ${{ secrets.FORGEJO_TOKEN }} # Make sure to add this token in your repo secrets
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '20' # Adjust as needed
- name: Configure npm version
run: npm install
- name: Check and Update Minor Dependencies
run: npx npm-check-updates --target minor -u
- name: Install Updated Dependencies
run: npm install
- name: Commit and Push Changes
run: |
git config --global user.name "forgejo-bot"
git config --global user.email "bot@pweapon.org"
git add package.json || exit 0
git commit -m "chore: update minor dependencies"
git push origin HEAD:${GITHUB_REF#refs/heads/}
env:
GITHUB_TOKEN: ${{ secrets.FORGEJO_TOKEN }}

25
.gitignore vendored Normal file
View file

@ -0,0 +1,25 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
downloads

1
.npmrc Normal file
View file

@ -0,0 +1 @@
engine-strict=true

4
.prettierignore Normal file
View file

@ -0,0 +1,4 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock

15
.prettierrc Normal file
View file

@ -0,0 +1,15 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
"overrides": [
{
"files": "*.svelte",
"options": {
"parser": "svelte"
}
}
]
}

34
eslint.config.js Normal file
View file

@ -0,0 +1,34 @@
import prettier from 'eslint-config-prettier';
import js from '@eslint/js';
import { includeIgnoreFile } from '@eslint/compat';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';
import { fileURLToPath } from 'node:url';
import ts from 'typescript-eslint';
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
export default ts.config(
includeIgnoreFile(gitignorePath),
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node
}
}
},
{
files: ['**/*.svelte'],
languageOptions: {
parserOptions: {
parser: ts.parser
}
}
}
);

4956
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

43
package.json Normal file
View file

@ -0,0 +1,43 @@
{
"name": "dl.emersa.it",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint ."
},
"devDependencies": {
"@eslint/compat": "^1.2.6",
"@eslint/js": "^9.19.0",
"@sveltejs/adapter-auto": "^4.0.0",
"@sveltejs/adapter-node": "^5.2.12",
"@sveltejs/kit": "^2.17.1",
"@sveltejs/vite-plugin-svelte": "^5.0.3",
"@tailwindcss/forms": "^0.5.10",
"@tailwindcss/typography": "^0.5.16",
"autoprefixer": "^10.4.20",
"eslint": "^9.19.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-svelte": "^2.46.1",
"globals": "^15.14.0",
"prettier": "^3.4.2",
"prettier-plugin-svelte": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.11",
"svelte": "^5.19.9",
"svelte-check": "^4.1.4",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.3",
"typescript-eslint": "^8.23.0",
"vite": "^6.1.0"
},
"dependencies": {
"youtube-dl-exec": "^3.0.15"
}
}

6
postcss.config.js Normal file
View file

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
};

32
scripts/deploy.sh Executable file
View file

@ -0,0 +1,32 @@
#!/usr/bin/bash
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NO_DELETE=false
SSH_SERVER="example"
PROJECT_ROOT=example_directory
SSH_REMOTE_DIR="${SSH_SERVER}:${PROJECT_ROOT}"
for arg in "$@"
do
if [ "$arg" == "--no-delete" ]; then
NO_DELETE=true
fi
done
if [ "$NO_DELETE" = false ]; then
echo "Deleting node_modules..."
rm -rf node_modules/
else
echo "Skipping deletion of node_modules."
fi
npm ci
npm run build
rsync -r --delete --progress build/ "${SSH_REMOTE_DIR}"
rsync package.json "${SSH_REMOTE_DIR}"
rsync package-lock.json "${SSH_REMOTE_DIR}"
ssh "${SSH_SERVER}" "cd ${PROJECT_ROOT}; npm ci"
ssh "${SSH_SERVER}" "systemctl restart downloader"

3
src/app.css Normal file
View file

@ -0,0 +1,3 @@
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

13
src/app.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

39
src/app.html Normal file
View file

@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<link rel="manifest" href="manifest.json">
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
<style>
@font-face {
font-family: 'Press Start 2P';
src: url('/fonts/PressStart2P-Regular.ttf');
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
background: black; /* Fallback */
background-image: radial-gradient(circle, #37ff1456 8%, transparent 8%),
radial-gradient(circle, #37ff1456 8%, transparent 8%);
background-size:
60px 60px,
30px 30px; /* Larger grid sizes for more spacing */
background-position:
0 0,
15px 15px; /* Offset the smaller pattern slightly */
font-family: 'Press Start 2P', sans-serif;
color: #37ff1456; /* Retro green text */
margin: 0;
}
</style>
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View file

@ -0,0 +1,3 @@
<script lang='ts'>
let props = $props();
</script>

View file

@ -0,0 +1,6 @@
<div
class="absolute inset-0 z-10 flex items-center justify-center bg-white bg-opacity-50"
id="spinner"
>
<div class="h-20 w-20 animate-spin rounded-full border-b-2 border-t-2 border-gray-900"></div>
</div>

1
src/lib/index.ts Normal file
View file

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

20
src/routes/+layout.svelte Normal file
View file

@ -0,0 +1,20 @@
<script lang="ts">
import '../app.css';
let { children } = $props();
</script>
{@render children()}
<footer
class="absolute bottom-0 w-[100dvw] mt-10 bg-black text-green-500 text-center py-4 border-t-4 border-green-500"
>
Made with ❤️ by Emersa <span>©</span>
</footer>
<style>
span {
transform: rotate(180deg);
display: inline-block;
}
</style>

202
src/routes/+page.svelte Normal file
View file

@ -0,0 +1,202 @@
<script>
let source = $state('youtube');
let link = $state('');
let format = $state('mp3');
let loading = $state(true);
let showModal = $state(false);
let error = $state(false);
let href = $state('');
// let formats = ['ogg', 'mp3', 'mp4']
const formats = [{ value: 'mp3', label: 'MP3' }];
const toggleModal = () => {
showModal = !showModal;
};
const handleSubmit = async (e) => {
e.preventDefault();
console.log({
source,
link,
format
});
const searchParams = new URLSearchParams();
searchParams.append('source', source);
searchParams.append('link', link);
searchParams.append('format', format);
href = `/download?${searchParams.toString()}`;
};
$effect(() => {
// Auto selected the radio button based on url regex
if (link.includes('spotify')) {
source = 'spotify';
} else if (link.includes('youtube')) {
source = 'youtube';
}
});
</script>
<div
id="wrapper"
class="relative mx-auto rounded-lg bg-black p-6 text-green-500 shadow-lg sm:max-w-sm sm:border-4 sm:border-green-500 md:mt-10 md:max-w-md lg:max-w-lg 2xl:max-w-2xl"
>
<!-- Info Icon -->
<button
onclick={toggleModal}
class="absolute right-3 top-3 text-pink-500 transition hover:text-pink-300"
aria-label="Open Info Modal"
>
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="h-6 w-6" viewBox="0 0 24 24">
<path
d="M12 0C5.373 0 0 5.373 0 12c0 6.627 5.373 12 12 12s12-5.373 12-12C24 5.373 18.627 0 12 0zm.75 18h-1.5v-6h1.5v6zm0-8h-1.5V8h1.5v2z"
/>
</svg>
</button>
<h1 id='title' class="mb-6 text-center text-xl">🐙 Scaricatore 🐙</h1>
<form class="space-y-6" onsubmit={handleSubmit}>
<!-- Source Selection -->
<fieldset class="space-y-4">
<legend class="text-green-400">Choose Source:</legend>
<label class="flex items-center space-x-3">
<input type="radio" name="source" value="youtube" bind:group={source} class="retro-radio" />
<span>YouTube</span>
</label>
<label class="flex items-center space-x-3">
<input
disabled
type="radio"
name="source"
value="spotify"
bind:group={source}
class="retro-radio"
/>
<span class="not-available">Spotify</span>
</label>
<label class="flex items-center space-x-3">
<input type="radio" name="source" value="other" bind:group={source} class="retro-radio" />
<span>
Other (<a
href="https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md"
target="_blank"
rel="noopener noreferrer"
class="text-pink-500 hover:underline"
>supported sites
</a>)
</span>
</label>
</fieldset>
<!-- Link Input -->
<div>
<label for="link" class="mb-2 block text-green-400"> Enter Playlist or Video Link: </label>
<input
name="link"
type="url"
id="link"
bind:value={link}
required
placeholder="Paste your link here"
class="w-full rounded-lg border-4 border-green-500 bg-green-200 px-4 py-3 text-black focus:border-pink-500 focus:outline-none"
/>
</div>
<!-- Format Selection -->
<div>
<label for="format" class="mb-2 block text-green-400"> Choose Format: </label>
<select
id="format"
name="format"
bind:value={format}
class="w-full rounded-lg border-4 border-green-500 bg-green-200 px-4 py-3 text-black focus:border-pink-500 focus:outline-none"
>
{#each formats as format}
<option value={format.value}>{format.label}</option>
{/each}
</select>
</div>
<!-- Submit Button -->
<button
type="submit"
class="w-full rounded-lg border-4 border-pink-700 bg-pink-500 px-4 py-3 text-black transition hover:bg-pink-600 active:border-yellow-500"
>
Create download link
</button>
{#if href}
<a class="download-link" {href}> Download </a>
{/if}
</form>
</div>
<!-- Modal -->
{#if showModal}
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-80">
<div
class="w-4/5 max-w-lg rounded-lg border-4 border-green-500 bg-green-900 p-6 text-center text-green-100"
>
<h2 class="mb-4 text-lg"> Retro Media Downloader Info</h2>
<p>
This app allows you to download Spotify playlists and YouTube videos directly. Choose your
source, paste the link, and select a format to start downloading!
</p>
<button
onclick={toggleModal}
class="mt-6 rounded-lg border-4 border-pink-700 bg-pink-500 px-4 py-2 text-black hover:bg-pink-600"
>
Close
</button>
</div>
</div>
{/if}
<style>
* {
font-size: 12px;
}
.download-link {
margin: 0 auto;
padding: 5px;
display: block;
text-decoration: underline;
text-align: center;
}
.not-available {
text-decoration-line: line-through;
text-decoration-color: red;
}
.retro-radio {
appearance: none;
background-color: #000;
border: 2px solid #39ff14;
width: 20px;
height: 20px;
cursor: pointer;
}
.retro-radio:checked {
background-color: #39ff14;
box-shadow:
0 0 4px #39ff14,
0 0 10px #39ff14;
}
input[type='url'],
select {
font-family: inherit;
}
#title {
font-size: 22px;
}
</style>

View file

@ -0,0 +1,91 @@
import { DOWNLOAD_PATH } from '$env/static/private';
import { redirect } from '@sveltejs/kit';
import ytdl from 'youtube-dl-exec';
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { spawn } from 'child_process';
/**
* Fetch YouTube metadata (title, uploader/artist)
*/
async function getYouTubeMetadata(link: string) {
return await ytdl(link, {
dumpSingleJson: true,
noCheckCertificates: true,
noWarnings: true,
preferFreeFormats: true
});
}
/**
* Streams the YouTube video/audio using youtube-dl-exec
*/
function streamYouTube(link: string, format: string): ReadableStream<Uint8Array> {
return new ReadableStream({
start(controller) {
const args = [
'-o',
'-',
format === 'mp3' ? '--embed-metadata' : '',
'--format',
format === 'mp3' ? 'bestaudio' : 'best',
'--audio-format',
format === 'mp3' ? 'mp3' : '',
'--no-playlist'
].filter(Boolean);
const process = spawn('yt-dlp', [...args, link], { stdio: ['ignore', 'pipe', 'ignore'] });
process.stdout.on('data', (chunk) => controller.enqueue(chunk));
process.stdout.on('end', () => controller.close());
process.stdout.on('error', (err) => {
console.error('Stream error:', err);
controller.error(err);
});
}
});
}
/**
* Sanitize filename by removing unsafe characters
*/
function sanitizeFilename(name: string): string {
return name.replace(/[\/:*?"<>|]/g, '').trim();
}
export const GET: RequestHandler = async ({ url }) => {
// Get query params
const link = url.searchParams.get('link');
const format = url.searchParams.get('format'); // mp3, mp4
const source = url.searchParams.get('source'); // youtube or spotify
// Validate input
if (!link || !format || !source) {
throw error(400, 'Missing required query parameters: link, format, or source');
}
if (source !== 'youtube') {
throw error(400, 'Currently, only YouTube is supported');
}
try {
// Fetch metadata for filename
const metadata = await getYouTubeMetadata(link);
const { title, uploader } = metadata;
const safeTitle = sanitizeFilename(`${uploader} - ${title}`);
const filename = `${safeTitle}.${format}`;
console.log(filename)
// Stream video/audio
return new Response(streamYouTube(link, format), {
headers: {
'Content-Type': format === 'mp3' ? 'audio/mpeg' : 'video/mp4',
'Content-Disposition': `attachment; filename="${filename}"`
}
});
} catch (err) {
console.error('Error fetching metadata:', err);
throw error(500, 'Failed to fetch video metadata');
}
};

79
src/service-worker.js Normal file
View file

@ -0,0 +1,79 @@
import { build, files, version } from '$service-worker';
// Create a unique cache name for this deployment
const CACHE = `cache-${version}`;
const ASSETS = [
...build, // the app itself
...files // everything in `static`
];
self.addEventListener('install', (event) => {
// Create a new cache and add all files to it
async function addFilesToCache() {
const cache = await caches.open(CACHE);
await cache.addAll(ASSETS);
}
event.waitUntil(addFilesToCache());
});
self.addEventListener('activate', (event) => {
// Remove previous cached data from disk
async function deleteOldCaches() {
for (const key of await caches.keys()) {
if (key !== CACHE) await caches.delete(key);
}
}
event.waitUntil(deleteOldCaches());
});
self.addEventListener('fetch', (event) => {
// ignore POST requests etc
if (event.request.method !== 'GET' || event.request.pathname === 'download') return;
async function respond() {
const url = new URL(event.request.url);
const cache = await caches.open(CACHE);
// `build`/`files` can always be served from the cache
if (ASSETS.includes(url.pathname)) {
const response = await cache.match(url.pathname);
if (response) {
return response;
}
}
// for everything else, try the network first, but
// fall back to the cache if we're offline
try {
const response = await fetch(event.request);
// if we're offline, fetch can return a value that is not a Response
// instead of throwing - and we can't pass this non-Response to respondWith
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}
if (response.status === 200) {
cache.put(event.request, response.clone());
}
return response;
} catch (err) {
const response = await cache.match(event.request);
if (response) {
return response;
}
// if there's no cache, then just error out
// as there is nothing we can do to respond to this request
throw err;
}
}
event.respondWith(respond());
});

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

16
static/manifest.json Normal file
View file

@ -0,0 +1,16 @@
{
"name": "EmersaDownloader",
"start_url": "https://dl.emersa.it",
"theme_color": "rgb(34,197,94)",
"background": "black",
"orientation": "portrait",
"display": "fullscreen",
"short_name": "e-downloader",
"icons": [
{
"src": "favicon.png",
"type": "image/png",
"sizes": "128x128"
}
]
}

18
svelte.config.js Normal file
View file

@ -0,0 +1,18 @@
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://svelte.dev/docs/kit/integrations
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://svelte.dev/docs/kit/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

View file

@ -0,0 +1,18 @@
[Unit]
Description=Downloader
After=network.target
[Service]
User=user
Group=user
WorkingDirectory=<PROJECT_ROOT>
ExecStart=/usr/bin/node <PROJECT_ROOT>
Environment=ORIGIN=http://example.com
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=downloader
[Install]
WantedBy=multi-user.target

13
tailwind.config.ts Normal file
View file

@ -0,0 +1,13 @@
import forms from '@tailwindcss/forms';
import typography from '@tailwindcss/typography';
import type { Config } from 'tailwindcss';
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {}
},
plugins: [typography, forms]
} satisfies Config;

19
tsconfig.json Normal file
View file

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

6
vite.config.ts Normal file
View file

@ -0,0 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()]
});