HifiPlanet-Website/hifi-src/src/pages/admin/Downloads.jsx
Maaxxs 54928d1411 Add package badges/visibility and a download area, speed up the site
Customer feedback round (4 items):

- Packages: one-click "Sichtbar/Ausgeblendet" toggle per package (saved
  immediately). Hidden packages disappear from the model page; the tier
  look of the remaining cards is ranked across all packages so it stays
  stable.
- Packages: badge per card (Empfohlen, Am beliebtesten, Tipp, Coming soon
  or custom text) plus an optional video link shown as "Zum Video". Legacy
  is_featured maps to "Empfohlen".
- New download area (/downloads + Admin -> Downloads): upload with
  progress, inline audio player, allow-listed file types, optional access
  password, new permission downloads.manage. Files live in
  api/uploads/downloads/ (gitignored, created at runtime).
- Performance:
  - SetupGate no longer refetches and remounts the whole app on every
    navigation.
  - Page loader waits only for pending API calls and above-the-fold images
    (fixes an 8 s hang on /leistungen caused by lazy images inside the
    hidden container).
  - Admin pages lazy-loaded; icon library moved out of the main bundle
    (initial JS 2.2 MB -> 0.48 MB).
  - Background video loads only near the viewport and was re-encoded to
    720p (32 MB -> 8.5 MB).
  - Visitors without a session cookie get no PHP session, so their parallel
    API requests no longer queue on the session lock.
  - index.html is served with Cache-Control: no-cache so browsers don't
    keep a stale build after deploys.
- Fonts (Barlow, Barlow Condensed, Michroma) are self-hosted instead of
  loaded from Google Fonts; the default privacy policy mentions this, lists
  all local storage uses and uses the new TDDDG name.
- A code update that adds a table no longer sends the site into the setup
  wizard while an admin exists.

Run "Datenbankstruktur aktualisieren" after deploying (new package
columns, downloads table, app_settings.downloads_password).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:15:48 +02:00

344 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useRef, useState } from 'react';
import { Eye, EyeOff } from 'lucide-react';
import { api, API_BASE } from '../../api/client.js';
import { ALLOWED_DOWNLOAD_EXTENSIONS, formatFileSize } from '../../utils/downloads.js';
const inputCls =
'w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-900';
const emptyForm = { title: '', description: '', sort_order: 0 };
// fetch() meldet keinen Upload-Fortschritt - bei Songs mit 50+ MB soll man aber sehen, dass
// etwas passiert. Daher hier XMLHttpRequest statt api.post.
function uploadWithProgress(path, formData, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', `${API_BASE}${path}`);
xhr.withCredentials = true;
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(e.loaded / e.total);
};
xhr.onload = () => {
let data = null;
try {
data = JSON.parse(xhr.responseText);
} catch {
// kein JSON - z. B. eine HTML-Fehlerseite des Webservers bei zu grossen Dateien
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve(data);
} else {
reject(new Error(data?.error || (xhr.status === 413 ? 'Die Datei ist zu groß für diesen Server.' : `Fehler ${xhr.status}`)));
}
};
xhr.onerror = () => reject(new Error('Netzwerkfehler beim Hochladen'));
xhr.send(formData);
});
}
// Optionales Zugangspasswort fuer /downloads (app_settings.downloads_password, leer =
// oeffentlich) - bewusst im Klartext einsehbar, es ist ein Code zum Weitergeben an Kunden.
function AccessSettings() {
const [saved, setSaved] = useState(undefined); // undefined = laedt, null = oeffentlich
const [value, setValue] = useState('');
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState(null); // { kind: 'ok' | 'error', text }
useEffect(() => {
api
.get('/settings/downloads')
.then((res) => {
setSaved(res.password);
setValue(res.password || '');
})
.catch((err) => setMessage({ kind: 'error', text: err.message }));
}, []);
const handleSave = async (e) => {
e.preventDefault();
setBusy(true);
setMessage(null);
try {
const res = await api.put('/settings/downloads', { password: value });
setSaved(res.password);
setValue(res.password || '');
setMessage({
kind: 'ok',
text: res.password ? 'Gespeichert – der Bereich ist jetzt geschützt.' : 'Gespeichert – der Bereich ist jetzt öffentlich.',
});
} catch (err) {
setMessage({ kind: 'error', text: err.message });
} finally {
setBusy(false);
}
};
return (
<form onSubmit={handleSave} className="space-y-3 rounded-xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-900">
<h2 className="font-bold text-neutral-900 dark:text-white">Zugriffsschutz</h2>
<p className="text-sm text-neutral-600 dark:text-neutral-300">
{saved === undefined && 'Lädt…'}
{saved === null && 'Öffentlich – jeder, der die Seite aufruft, sieht die Dateien.'}
{typeof saved === 'string' && 'Geschützt – Besucher müssen zuerst das Passwort eingeben.'}
</p>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Zugangspasswort (leer = öffentlich)
</label>
<input value={value} maxLength={100} autoComplete="off" onChange={(e) => setValue(e.target.value)} className={inputCls} />
<p className="mt-1 text-xs text-neutral-400">
Das Passwort an die Kunden weitergeben – es bleibt hier jederzeit einsehbar. Direkte Links zu einzelnen
Dateien funktionieren auch ohne Passwort; wer freigeschaltet hat, könnte sie also weitergeben.
</p>
</div>
{message && (
<p className={`text-sm ${message.kind === 'error' ? 'text-red-600' : 'text-brand-600 dark:text-brand-400'}`}>{message.text}</p>
)}
<button
type="submit"
disabled={busy || saved === undefined}
className="rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600 disabled:opacity-50"
>
Speichern
</button>
</form>
);
}
export default function Downloads() {
const [downloads, setDownloads] = useState([]);
const [form, setForm] = useState(emptyForm);
const [file, setFile] = useState(null);
const [editingId, setEditingId] = useState(null);
const [progress, setProgress] = useState(null); // 0..1 waehrend eines Uploads
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [visibilityBusyId, setVisibilityBusyId] = useState(null);
const fileInputRef = useRef(null);
const load = () => api.get('/downloads/manage').then(setDownloads);
useEffect(() => {
load();
}, []);
const resetForm = () => {
setEditingId(null);
setForm(emptyForm);
setFile(null);
setError('');
if (fileInputRef.current) fileInputRef.current.value = '';
};
const startEdit = (item) => {
resetForm();
setEditingId(item.id);
setForm({ title: item.title, description: item.description || '', sort_order: item.sort_order });
window.scrollTo({ top: 0, behavior: 'smooth' });
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!editingId && !file) {
setError('Bitte eine Datei auswählen.');
return;
}
setBusy(true);
setError('');
try {
if (editingId) {
await api.put(`/downloads/${editingId}`, form);
if (file) {
const data = new FormData();
data.append('file', file);
setProgress(0);
await uploadWithProgress(`/downloads/${editingId}/file`, data, setProgress);
}
} else {
const data = new FormData();
data.append('file', file);
data.append('title', form.title);
data.append('description', form.description);
setProgress(0);
await uploadWithProgress('/downloads', data, setProgress);
}
resetForm();
load();
} catch (err) {
setError(err.message);
} finally {
setBusy(false);
setProgress(null);
}
};
const toggleVisibility = async (item) => {
setVisibilityBusyId(item.id);
try {
const res = await api.patch(`/downloads/${item.id}/visibility`, { is_hidden: !item.is_hidden });
setDownloads((ds) => ds.map((d) => (d.id === item.id ? { ...d, is_hidden: res.is_hidden } : d)));
} catch (err) {
alert(`Sichtbarkeit konnte nicht geändert werden: ${err.message}`);
} finally {
setVisibilityBusyId(null);
}
};
const handleDelete = async (item) => {
if (!confirm(`"${item.title}" inkl. Datei wirklich löschen?`)) return;
await api.delete(`/downloads/${item.id}`);
if (editingId === item.id) resetForm();
load();
};
return (
<div className="grid gap-6 lg:grid-cols-3">
<div className="lg:col-span-2">
<h1 className="mb-4 text-xl font-bold text-neutral-900 dark:text-white">Downloads</h1>
<p className="mb-4 text-sm text-neutral-500 dark:text-neutral-400">
Dateien, die Kunden auf der Seite{' '}
<a href="/downloads" target="_blank" rel="noopener noreferrer" className="text-brand-600 hover:underline">/downloads</a>{' '}
anhören bzw. herunterladen können, z. B. Songs oder Anleitungen. Der Menüpunkt „Downloads“ erscheint auf
der Website automatisch, sobald mindestens eine Datei sichtbar ist. Ohne Zugangspasswort (siehe
„Zugriffsschutz“) ist die Seite öffentlich.
</p>
<div className="overflow-hidden rounded-xl border border-neutral-200 dark:border-neutral-800">
<table className="w-full text-left text-sm">
<thead className="bg-neutral-50 text-neutral-500 dark:bg-neutral-900 dark:text-neutral-400">
<tr>
<th className="px-4 py-2">Titel / Datei</th>
<th className="px-4 py-2">Größe</th>
<th className="px-4 py-2">Website</th>
<th className="px-4 py-2 text-right">Aktionen</th>
</tr>
</thead>
<tbody className="divide-y divide-neutral-100 dark:divide-neutral-800">
{downloads.map((item) => (
<tr key={item.id} className="bg-white dark:bg-neutral-950">
<td className={`px-4 py-2 ${item.is_hidden ? 'opacity-60' : ''}`}>
<p className="font-medium text-neutral-800 dark:text-neutral-100">{item.title}</p>
<a
href={item.file_path}
target="_blank"
rel="noopener noreferrer"
className="break-all text-xs text-neutral-500 hover:text-brand-600 dark:text-neutral-400"
>
{item.file_name}
</a>
</td>
<td className="whitespace-nowrap px-4 py-2 text-neutral-500 dark:text-neutral-400">{formatFileSize(item.file_size)}</td>
<td className="px-4 py-2">
<button
type="button"
onClick={() => toggleVisibility(item)}
disabled={visibilityBusyId === item.id}
title={item.is_hidden ? 'Wieder auf der Website anzeigen' : 'Auf der Website ausblenden'}
className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-semibold transition disabled:opacity-50 ${
item.is_hidden
? 'border-amber-300 bg-amber-50 text-amber-800 hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-900/30 dark:text-amber-300'
: 'border-neutral-300 text-neutral-600 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800'
}`}
>
{item.is_hidden ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
{item.is_hidden ? 'Ausgeblendet' : 'Sichtbar'}
</button>
</td>
<td className="whitespace-nowrap px-4 py-2 text-right">
<button onClick={() => startEdit(item)} className="mr-3 text-brand-600 hover:underline">Bearbeiten</button>
<button onClick={() => handleDelete(item)} className="text-red-600 hover:underline">Löschen</button>
</td>
</tr>
))}
{downloads.length === 0 && (
<tr><td colSpan={4} className="px-4 py-6 text-center text-neutral-400">Noch keine Dateien hochgeladen.</td></tr>
)}
</tbody>
</table>
</div>
</div>
<div className="h-fit space-y-6">
<form onSubmit={handleSubmit} className="space-y-4 rounded-xl border border-neutral-200 bg-white p-5 dark:border-neutral-800 dark:bg-neutral-900">
<h2 className="font-bold text-neutral-900 dark:text-white">{editingId ? 'Download bearbeiten' : 'Neue Datei hochladen'}</h2>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">
{editingId ? 'Datei ersetzen (optional)' : 'Datei *'}
</label>
<input
ref={fileInputRef}
type="file"
accept={ALLOWED_DOWNLOAD_EXTENSIONS.map((ext) => `.${ext}`).join(',')}
onChange={(e) => setFile(e.target.files?.[0] || null)}
className="block w-full text-sm text-neutral-600 file:mr-3 file:rounded-md file:border-0 file:bg-brand-500 file:px-3 file:py-2 file:text-sm file:font-semibold file:text-white hover:file:bg-brand-600 dark:text-neutral-300"
/>
<p className="mt-1 text-xs text-neutral-400">
Musik (MP3, WAV, FLAC, …), Videos, PDFs, Bilder, Office-Dokumente oder ZIP-Archive. Andere Dateitypen bitte als ZIP hochladen.
</p>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">
Titel {editingId ? '*' : '(optional)'}
</label>
<input
required={!!editingId}
value={form.title}
maxLength={150}
onChange={(e) => setForm({ ...form, title: e.target.value })}
placeholder={editingId ? '' : 'Leer lassen = Dateiname'}
className={inputCls}
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">Beschreibung (optional)</label>
<textarea
rows={3}
value={form.description}
onChange={(e) => setForm({ ...form, description: e.target.value })}
className={inputCls}
/>
</div>
{editingId && (
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700 dark:text-neutral-300">Sortierung</label>
<input
type="number"
value={form.sort_order}
onChange={(e) => setForm({ ...form, sort_order: Number(e.target.value) })}
className={inputCls}
/>
</div>
)}
{progress !== null && (
<div>
<div className="h-2 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-800">
<div className="h-full rounded-full bg-brand-500 transition-[width]" style={{ width: `${Math.round(progress * 100)}%` }} />
</div>
<p className="mt-1 text-xs text-neutral-500 dark:text-neutral-400">
{progress < 1 ? `Wird hochgeladen … ${Math.round(progress * 100)} %` : 'Wird gespeichert …'}
</p>
</div>
)}
{error && <p className="text-sm text-red-600">{error}</p>}
<div className="flex gap-2">
<button
type="submit"
disabled={busy}
className="rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600 disabled:opacity-50"
>
{editingId ? 'Speichern' : 'Hochladen'}
</button>
{editingId && (
<button type="button" onClick={resetForm} disabled={busy} className="rounded-md border border-neutral-300 px-4 py-2 text-sm dark:border-neutral-700">
Abbrechen
</button>
)}
</div>
</form>
<AccessSettings />
</div>
</div>
);
}