Hochladen mit Upload-Code, kurzer Link zum Herunterladen, automatische Löschung nach Ablauf der Frist. Node.js ohne zusätzliche Pakete. - src/: HTTP-Server, Ablage auf der Platte, Zugriffsbegrenzung - pages/, public/: Oberfläche in Deutsch und Englisch - tools/: Transfers auflisten und löschen - test/: 34 automatische Tests - Dockerfile, compose.yaml: Betrieb als Container auf 127.0.0.1:8083 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
180 lines
5.3 KiB
JavaScript
180 lines
5.3 KiB
JavaScript
// Gemeinsames für alle Seiten: Sprachumschalter, Formatierung, Aufrufe an den Server.
|
||
|
||
const root = document.documentElement;
|
||
const siteName = document.querySelector('meta[name="application-name"]')?.content ?? '';
|
||
|
||
// ---------------------------------------------------------------- Sprache
|
||
|
||
export function getLang() {
|
||
return root.lang === 'en' ? 'en' : 'de';
|
||
}
|
||
|
||
const listeners = new Set();
|
||
|
||
/** Meldet eine Funktion an, die nach einem Sprachwechsel neu zeichnet. */
|
||
export function onLangChange(fn) {
|
||
listeners.add(fn);
|
||
}
|
||
|
||
function applyLang() {
|
||
const lang = getLang();
|
||
for (const button of document.querySelectorAll('[data-set-lang]')) {
|
||
button.setAttribute('aria-pressed', String(button.dataset.setLang === lang));
|
||
}
|
||
const title = lang === 'en' ? root.dataset.titleEn : root.dataset.titleDe;
|
||
if (title) document.title = siteName ? `${title} – ${siteName}` : title;
|
||
}
|
||
|
||
export function setLang(lang) {
|
||
root.lang = lang === 'en' ? 'en' : 'de';
|
||
try {
|
||
localStorage.setItem('lang', root.lang);
|
||
} catch {
|
||
// Ohne Speicher gilt die Wahl nur für diese Seite.
|
||
}
|
||
applyLang();
|
||
for (const fn of listeners) fn(root.lang);
|
||
}
|
||
|
||
for (const button of document.querySelectorAll('[data-set-lang]')) {
|
||
button.addEventListener('click', () => setLang(button.dataset.setLang));
|
||
}
|
||
applyLang();
|
||
|
||
/** Setzt Platzhalter wie {name} in einen Text ein. */
|
||
export function fill(template, params = {}) {
|
||
return template.replace(/\{(\w+)\}/g, (match, key) => (key in params ? String(params[key]) : match));
|
||
}
|
||
|
||
// ----------------------------------------------------------- Formatierung
|
||
|
||
function locale() {
|
||
if (getLang() === 'de') return 'de-DE';
|
||
return /^en\b/i.test(navigator.language ?? '') ? navigator.language : 'en-GB';
|
||
}
|
||
|
||
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||
|
||
/** 1536 -> "1,5 KB" (1 KB = 1024 B, wie es der Server rechnet). */
|
||
export function formatBytes(bytes) {
|
||
let value = bytes;
|
||
let unit = 0;
|
||
const digits = () => (unit === 0 || value >= 100 ? 0 : 1);
|
||
while (unit < UNITS.length - 1 && Number(value.toFixed(digits())) >= 1024) {
|
||
value /= 1024;
|
||
unit += 1;
|
||
}
|
||
const number = new Intl.NumberFormat(locale(), { maximumFractionDigits: digits() }).format(value);
|
||
return `${number}\u00a0${UNITS[unit]}`;
|
||
}
|
||
|
||
export function formatDate(timestamp) {
|
||
return new Intl.DateTimeFormat(locale(), { dateStyle: 'long', timeStyle: 'short' }).format(new Date(timestamp));
|
||
}
|
||
|
||
/** Grobe Dauer für Restzeiten: "20 Sekunden", "3 Minuten", "1 Std. 10 Min.". */
|
||
export function formatDuration(seconds) {
|
||
const de = getLang() === 'de';
|
||
if (seconds < 50) {
|
||
const s = Math.max(5, Math.round(seconds / 5) * 5);
|
||
return de ? `${s} Sekunden` : `${s} seconds`;
|
||
}
|
||
const minutes = Math.round(seconds / 60);
|
||
if (minutes < 60) {
|
||
if (minutes === 1) return de ? '1 Minute' : '1 minute';
|
||
return de ? `${minutes} Minuten` : `${minutes} minutes`;
|
||
}
|
||
const hours = Math.floor(minutes / 60);
|
||
const rest = minutes % 60;
|
||
return de ? `${hours} Std. ${rest} Min.` : `${hours} h ${rest} min`;
|
||
}
|
||
|
||
/**
|
||
* Baut die Anzeige eines Dateinamens: Ist er zu lang, wird in der Mitte
|
||
* gekürzt, die Endung bleibt immer sichtbar.
|
||
*/
|
||
export function fileNameElement(name) {
|
||
const dot = name.lastIndexOf('.');
|
||
const hasExt = dot > 0 && name.length - dot <= 11;
|
||
const wrap = document.createElement('span');
|
||
wrap.className = 'file-name';
|
||
wrap.title = name;
|
||
const stem = document.createElement('span');
|
||
stem.className = 'file-stem';
|
||
stem.textContent = hasExt ? name.slice(0, dot) : name;
|
||
wrap.append(stem);
|
||
if (hasExt) {
|
||
const ext = document.createElement('span');
|
||
ext.className = 'file-ext';
|
||
ext.textContent = name.slice(dot);
|
||
wrap.append(ext);
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Server
|
||
|
||
/** Fehler eines Aufrufs. status 0 heißt: Server gar nicht erreicht. */
|
||
export class ApiError extends Error {
|
||
constructor(status, body) {
|
||
super(body?.error ?? `http_${status}`);
|
||
this.name = 'ApiError';
|
||
this.status = status;
|
||
this.code = body?.error ?? null;
|
||
this.body = body ?? {};
|
||
}
|
||
}
|
||
|
||
export async function api(method, url, { json, token } = {}) {
|
||
const headers = {};
|
||
if (json !== undefined) headers['Content-Type'] = 'application/json';
|
||
if (token) headers.Authorization = `Bearer ${token}`;
|
||
|
||
let response;
|
||
try {
|
||
response = await fetch(url, {
|
||
method,
|
||
headers,
|
||
body: json === undefined ? undefined : JSON.stringify(json),
|
||
cache: 'no-store',
|
||
});
|
||
} catch {
|
||
throw new ApiError(0, { error: 'network' });
|
||
}
|
||
|
||
let body = null;
|
||
if (response.status !== 204) {
|
||
try {
|
||
body = await response.json();
|
||
} catch {
|
||
body = null;
|
||
}
|
||
}
|
||
if (!response.ok) throw new ApiError(response.status, body);
|
||
return body;
|
||
}
|
||
|
||
/** Kopiert Text in die Zwischenablage; gibt zurück, ob es geklappt hat. */
|
||
export async function copyText(text) {
|
||
try {
|
||
await navigator.clipboard.writeText(text);
|
||
return true;
|
||
} catch {
|
||
// Ältere Browser oder fehlende Berechtigung: klassischer Weg.
|
||
}
|
||
const area = document.createElement('textarea');
|
||
area.value = text;
|
||
area.readOnly = true;
|
||
area.className = 'visually-hidden';
|
||
document.body.append(area);
|
||
area.select();
|
||
let ok = false;
|
||
try {
|
||
ok = document.execCommand('copy');
|
||
} catch {
|
||
ok = false;
|
||
}
|
||
area.remove();
|
||
return ok;
|
||
}
|