Add MP3 URL import and analytics widgets

This commit is contained in:
Bot 2026-03-01 18:56:37 +01:00
parent e200087a73
commit 5a41b6a622
5 changed files with 380 additions and 19 deletions

View file

@ -557,6 +557,83 @@ app.get('/api/health', (_req: Request, res: Response) => {
res.json({ ok: true, totalPlays: persistedState.totalPlays ?? 0, categories: (persistedState.categories ?? []).length }); res.json({ ok: true, totalPlays: persistedState.totalPlays ?? 0, categories: (persistedState.categories ?? []).length });
}); });
type ListedSound = {
fileName: string;
name: string;
folder: string;
relativePath: string;
};
function listAllSounds(): ListedSound[] {
const rootEntries = fs.readdirSync(SOUNDS_DIR, { withFileTypes: true });
const rootFiles: ListedSound[] = rootEntries
.filter((d) => {
if (!d.isFile()) return false;
const n = d.name.toLowerCase();
return n.endsWith('.mp3') || n.endsWith('.wav');
})
.map((d) => ({
fileName: d.name,
name: path.parse(d.name).name,
folder: '',
relativePath: d.name,
}));
const folderItems: ListedSound[] = [];
const subFolders = rootEntries.filter((d) => d.isDirectory());
for (const dirent of subFolders) {
const folderName = dirent.name;
const folderPath = path.join(SOUNDS_DIR, folderName);
const entries = fs.readdirSync(folderPath, { withFileTypes: true });
for (const e of entries) {
if (!e.isFile()) continue;
const n = e.name.toLowerCase();
if (!(n.endsWith('.mp3') || n.endsWith('.wav'))) continue;
folderItems.push({
fileName: e.name,
name: path.parse(e.name).name,
folder: folderName,
relativePath: path.join(folderName, e.name),
});
}
}
return [...rootFiles, ...folderItems].sort((a, b) => a.name.localeCompare(b.name));
}
app.get('/api/analytics', (_req: Request, res: Response) => {
try {
const allItems = listAllSounds();
const byKey = new Map<string, ListedSound>();
for (const it of allItems) {
byKey.set(it.relativePath, it);
if (!byKey.has(it.fileName)) byKey.set(it.fileName, it);
}
const mostPlayed = Object.entries(persistedState.plays ?? {})
.map(([rel, count]) => {
const item = byKey.get(rel);
if (!item) return null;
return {
name: item.name,
relativePath: item.relativePath,
count: Number(count) || 0,
};
})
.filter((x): x is { name: string; relativePath: string; count: number } => !!x)
.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name))
.slice(0, 10);
res.json({
totalSounds: allItems.length,
totalPlays: persistedState.totalPlays ?? 0,
mostPlayed,
});
} catch (e: any) {
res.status(500).json({ error: e?.message ?? 'Analytics konnten nicht geladen werden' });
}
});
// --- Admin Auth --- // --- Admin Auth ---
type AdminPayload = { iat: number; exp: number }; type AdminPayload = { iat: number; exp: number };
function b64url(input: Buffer | string): string { function b64url(input: Buffer | string): string {
@ -1280,28 +1357,34 @@ app.listen(PORT, () => {
}); });
// --- Medien-URL abspielen --- // --- Medien-URL abspielen ---
// Unterstützt: direkte MP3- oder WAV-URL (Download und Ablage) // Unterstützt: direkte MP3-URL (Download und Ablage)
app.post('/api/play-url', async (req: Request, res: Response) => { app.post('/api/play-url', async (req: Request, res: Response) => {
try { try {
const { url, guildId, channelId, volume } = req.body as { url?: string; guildId?: string; channelId?: string; volume?: number }; const { url, guildId, channelId, volume } = req.body as { url?: string; guildId?: string; channelId?: string; volume?: number };
if (!url || !guildId || !channelId) return res.status(400).json({ error: 'url, guildId, channelId erforderlich' }); if (!url || !guildId || !channelId) return res.status(400).json({ error: 'url, guildId, channelId erforderlich' });
const lower = url.toLowerCase(); let parsed: URL;
if (lower.endsWith('.mp3') || lower.endsWith('.wav')) { try {
const fileName = path.basename(new URL(url).pathname); parsed = new URL(url);
const dest = path.join(SOUNDS_DIR, fileName); } catch {
const r = await fetch(url); return res.status(400).json({ error: 'Ungültige URL' });
if (!r.ok) return res.status(400).json({ error: 'Download fehlgeschlagen' });
const buf = Buffer.from(await r.arrayBuffer());
fs.writeFileSync(dest, buf);
try {
await playFilePath(guildId, channelId, dest, volume, path.basename(dest));
} catch {
return res.status(500).json({ error: 'Abspielen fehlgeschlagen' });
}
return res.json({ ok: true, saved: path.basename(dest) });
} }
return res.status(400).json({ error: 'Nur MP3- oder WAV-Links werden unterstützt.' }); const pathname = parsed.pathname.toLowerCase();
if (!pathname.endsWith('.mp3')) {
return res.status(400).json({ error: 'Nur direkte MP3-Links werden unterstützt.' });
}
const fileName = path.basename(parsed.pathname);
const dest = path.join(SOUNDS_DIR, fileName);
const r = await fetch(url);
if (!r.ok) return res.status(400).json({ error: 'Download fehlgeschlagen' });
const buf = Buffer.from(await r.arrayBuffer());
fs.writeFileSync(dest, buf);
try {
await playFilePath(guildId, channelId, dest, volume, path.basename(dest));
} catch {
return res.status(500).json({ error: 'Abspielen fehlgeschlagen' });
}
return res.json({ ok: true, saved: path.basename(dest) });
} catch (e: any) { } catch (e: any) {
console.error('play-url error:', e); console.error('play-url error:', e);
return res.status(500).json({ error: e?.message ?? 'Unbekannter Fehler' }); return res.status(500).json({ error: e?.message ?? 'Unbekannter Fehler' });

View file

@ -1,11 +1,11 @@
import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react'; import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { import {
fetchChannels, fetchSounds, playSound, setVolumeLive, getVolume, fetchChannels, fetchSounds, fetchAnalytics, playSound, playUrl, setVolumeLive, getVolume,
adminStatus, adminLogin, adminLogout, adminDelete, adminRename, adminStatus, adminLogin, adminLogout, adminDelete, adminRename,
fetchCategories, partyStart, partyStop, subscribeEvents, fetchCategories, partyStart, partyStop, subscribeEvents,
getSelectedChannels, setSelectedChannel, getSelectedChannels, setSelectedChannel,
} from './api'; } from './api';
import type { VoiceChannelInfo, Sound, Category } from './types'; import type { VoiceChannelInfo, Sound, Category, AnalyticsResponse } from './types';
import { getCookie, setCookie } from './cookies'; import { getCookie, setCookie } from './cookies';
const THEMES = [ const THEMES = [
@ -30,11 +30,18 @@ export default function App() {
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const [folders, setFolders] = useState<Array<{ key: string; name: string; count: number }>>([]); const [folders, setFolders] = useState<Array<{ key: string; name: string; count: number }>>([]);
const [categories, setCategories] = useState<Category[]>([]); const [categories, setCategories] = useState<Category[]>([]);
const [analytics, setAnalytics] = useState<AnalyticsResponse>({
totalSounds: 0,
totalPlays: 0,
mostPlayed: [],
});
/* ── Navigation ── */ /* ── Navigation ── */
const [activeTab, setActiveTab] = useState<Tab>('all'); const [activeTab, setActiveTab] = useState<Tab>('all');
const [activeFolder, setActiveFolder] = useState(''); const [activeFolder, setActiveFolder] = useState('');
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const [importUrl, setImportUrl] = useState('');
const [importBusy, setImportBusy] = useState(false);
/* ── Channels ── */ /* ── Channels ── */
const [channels, setChannels] = useState<VoiceChannelInfo[]>([]); const [channels, setChannels] = useState<VoiceChannelInfo[]>([]);
@ -83,6 +90,14 @@ export default function App() {
setTimeout(() => setNotification(null), 3000); setTimeout(() => setNotification(null), 3000);
}, []); }, []);
const soundKey = useCallback((s: Sound) => s.relativePath ?? s.fileName, []); const soundKey = useCallback((s: Sound) => s.relativePath ?? s.fileName, []);
const isMp3Url = useCallback((value: string) => {
try {
const parsed = new URL(value.trim());
return parsed.pathname.toLowerCase().endsWith('.mp3');
} catch {
return false;
}
}, []);
const guildId = selected ? selected.split(':')[0] : ''; const guildId = selected ? selected.split(':')[0] : '';
const channelId = selected ? selected.split(':')[1] : ''; const channelId = selected ? selected.split(':')[1] : '';
@ -199,6 +214,10 @@ export default function App() {
})(); })();
}, [activeTab, activeFolder, query, refreshKey]); }, [activeTab, activeFolder, query, refreshKey]);
useEffect(() => {
void loadAnalytics();
}, [refreshKey]);
/* ── Favs persistence ── */ /* ── Favs persistence ── */
useEffect(() => { useEffect(() => {
const c = getCookie('favs'); const c = getCookie('favs');
@ -232,14 +251,41 @@ export default function App() {
}, [showAdmin, isAdmin]); }, [showAdmin, isAdmin]);
/* ── Actions ── */ /* ── Actions ── */
async function loadAnalytics() {
try {
const data = await fetchAnalytics();
setAnalytics(data);
} catch { }
}
async function handlePlay(s: Sound) { async function handlePlay(s: Sound) {
if (!selected) return notify('Bitte einen Voice-Channel auswählen', 'error'); if (!selected) return notify('Bitte einen Voice-Channel auswählen', 'error');
try { try {
await playSound(s.name, guildId, channelId, volume, s.relativePath); await playSound(s.name, guildId, channelId, volume, s.relativePath);
setLastPlayed(s.name); setLastPlayed(s.name);
void loadAnalytics();
} catch (e: any) { notify(e?.message || 'Play fehlgeschlagen', 'error'); } } catch (e: any) { notify(e?.message || 'Play fehlgeschlagen', 'error'); }
} }
async function handleUrlImport() {
const trimmed = importUrl.trim();
if (!trimmed) return notify('Bitte einen MP3-Link eingeben', 'error');
if (!selected) return notify('Bitte einen Voice-Channel auswählen', 'error');
if (!isMp3Url(trimmed)) return notify('Nur direkte MP3-Links sind erlaubt', 'error');
setImportBusy(true);
try {
await playUrl(trimmed, guildId, channelId, volume);
setImportUrl('');
notify('MP3 importiert und abgespielt');
setRefreshKey(k => k + 1);
await loadAnalytics();
} catch (e: any) {
notify(e?.message || 'URL-Import fehlgeschlagen', 'error');
} finally {
setImportBusy(false);
}
}
async function handleStop() { async function handleStop() {
if (!selected) return; if (!selected) return;
setLastPlayed(''); setLastPlayed('');
@ -410,6 +456,8 @@ export default function App() {
[adminFilteredSounds, adminSelection, soundKey]); [adminFilteredSounds, adminSelection, soundKey]);
const allVisibleSelected = adminFilteredSounds.length > 0 && selectedVisibleCount === adminFilteredSounds.length; const allVisibleSelected = adminFilteredSounds.length > 0 && selectedVisibleCount === adminFilteredSounds.length;
const analyticsTop = analytics.mostPlayed.slice(0, 3);
const totalSoundsDisplay = analytics.totalSounds || total;
const clockMain = clock.slice(0, 5); const clockMain = clock.slice(0, 5);
const clockSec = clock.slice(5); const clockSec = clock.slice(5);
@ -538,6 +586,26 @@ export default function App() {
)} )}
</div> </div>
<div className="url-import-wrap">
<span className="material-icons url-import-icon">link</span>
<input
className="url-import-input"
type="url"
placeholder="MP3-URL einfügen..."
value={importUrl}
onChange={e => setImportUrl(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleUrlImport(); }}
/>
<button
className="url-import-btn"
onClick={() => { void handleUrlImport(); }}
disabled={importBusy}
title="MP3 importieren"
>
{importBusy ? 'Lädt...' : 'Download'}
</button>
</div>
<div className="toolbar-spacer" /> <div className="toolbar-spacer" />
<div className="volume-control"> <div className="volume-control">
@ -612,6 +680,34 @@ export default function App() {
</div> </div>
</div> </div>
<div className="analytics-strip">
<div className="analytics-card">
<span className="material-icons analytics-icon">library_music</span>
<div className="analytics-copy">
<span className="analytics-label">Sounds gesamt</span>
<strong className="analytics-value">{totalSoundsDisplay}</strong>
</div>
</div>
<div className="analytics-card analytics-wide">
<span className="material-icons analytics-icon">leaderboard</span>
<div className="analytics-copy">
<span className="analytics-label">Most Played</span>
<div className="analytics-top-list">
{analyticsTop.length === 0 ? (
<span className="analytics-muted">Noch keine Plays</span>
) : (
analyticsTop.map((item, idx) => (
<span className="analytics-chip" key={item.relativePath}>
{idx + 1}. {item.name} ({item.count})
</span>
))
)}
</div>
</div>
</div>
</div>
{/* ═══ FOLDER CHIPS ═══ */} {/* ═══ FOLDER CHIPS ═══ */}
{activeTab === 'all' && visibleFolders.length > 0 && ( {activeTab === 'all' && visibleFolders.length > 0 && (
<div className="category-strip"> <div className="category-strip">

View file

@ -1,4 +1,4 @@
import type { Sound, SoundsResponse, VoiceChannelInfo } from './types'; import type { AnalyticsResponse, Sound, SoundsResponse, VoiceChannelInfo } from './types';
const API_BASE = import.meta.env.VITE_API_BASE_URL || '/api'; const API_BASE = import.meta.env.VITE_API_BASE_URL || '/api';
@ -13,6 +13,12 @@ export async function fetchSounds(q?: string, folderKey?: string, categoryId?: s
return res.json(); return res.json();
} }
export async function fetchAnalytics(): Promise<AnalyticsResponse> {
const res = await fetch(`${API_BASE}/analytics`);
if (!res.ok) throw new Error('Fehler beim Laden der Analytics');
return res.json();
}
// Kategorien // Kategorien
export async function fetchCategories() { export async function fetchCategories() {
const res = await fetch(`${API_BASE}/categories`, { credentials: 'include' }); const res = await fetch(`${API_BASE}/categories`, { credentials: 'include' });

View file

@ -497,6 +497,66 @@ input, select {
flex: 1; flex: 1;
} }
/* ── URL Import ── */
.url-import-wrap {
display: flex;
align-items: center;
gap: 6px;
min-width: 240px;
max-width: 460px;
flex: 1;
padding: 4px 6px 4px 8px;
border-radius: 20px;
background: var(--bg-secondary);
border: 1px solid rgba(255, 255, 255, .08);
}
.url-import-icon {
font-size: 15px;
color: var(--text-faint);
flex-shrink: 0;
}
.url-import-input {
flex: 1;
min-width: 0;
height: 26px;
border: none;
background: transparent;
color: var(--text-normal);
font-size: 12px;
font-family: var(--font);
outline: none;
}
.url-import-input::placeholder {
color: var(--text-faint);
}
.url-import-btn {
height: 24px;
padding: 0 10px;
border-radius: 14px;
border: 1px solid rgba(var(--accent-rgb, 88, 101, 242), .45);
background: rgba(var(--accent-rgb, 88, 101, 242), .12);
color: var(--accent);
font-size: 11px;
font-weight: 700;
white-space: nowrap;
transition: all var(--transition);
}
.url-import-btn:hover {
background: var(--accent);
border-color: var(--accent);
color: var(--white);
}
.url-import-btn:disabled {
opacity: .5;
pointer-events: none;
}
/* ── Toolbar Buttons ── */ /* ── Toolbar Buttons ── */
.tb-btn { .tb-btn {
display: flex; display: flex;
@ -649,6 +709,90 @@ input, select {
box-shadow: 0 0 6px rgba(255, 255, 255, .3); box-shadow: 0 0 6px rgba(255, 255, 255, .3);
} }
/* ── Analytics Strip ── */
.analytics-strip {
display: flex;
align-items: stretch;
gap: 8px;
padding: 8px 20px;
background: var(--bg-primary);
border-bottom: 1px solid rgba(0, 0, 0, .12);
flex-shrink: 0;
}
.analytics-card {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-radius: 12px;
background: var(--bg-secondary);
border: 1px solid rgba(255, 255, 255, .08);
}
.analytics-card.analytics-wide {
flex: 1;
min-width: 0;
}
.analytics-icon {
font-size: 18px;
color: var(--accent);
flex-shrink: 0;
}
.analytics-copy {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.analytics-label {
font-size: 10px;
font-weight: 700;
letter-spacing: .04em;
text-transform: uppercase;
color: var(--text-faint);
}
.analytics-value {
font-size: 18px;
line-height: 1;
font-weight: 800;
color: var(--text-normal);
}
.analytics-top-list {
display: flex;
align-items: center;
gap: 6px;
overflow-x: auto;
scrollbar-width: none;
}
.analytics-top-list::-webkit-scrollbar {
display: none;
}
.analytics-chip {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
border-radius: 999px;
background: rgba(var(--accent-rgb, 88, 101, 242), .15);
color: var(--accent);
font-size: 11px;
font-weight: 600;
white-space: nowrap;
}
.analytics-muted {
color: var(--text-muted);
font-size: 12px;
}
/* /*
Category / Folder Strip Category / Folder Strip
*/ */
@ -1544,6 +1688,12 @@ input, select {
order: -1; order: -1;
} }
.url-import-wrap {
max-width: 100%;
min-width: 100%;
order: -1;
}
.size-control, .size-control,
.theme-selector { .theme-selector {
display: none; display: none;
@ -1576,6 +1726,16 @@ input, select {
display: none; display: none;
} }
.analytics-strip {
padding: 8px 12px;
flex-direction: column;
gap: 6px;
}
.analytics-card.analytics-wide {
width: 100%;
}
.admin-panel { .admin-panel {
width: 96%; width: 96%;
padding: 16px; padding: 16px;
@ -1612,6 +1772,10 @@ input, select {
.toolbar .tb-btn { .toolbar .tb-btn {
padding: 6px 8px; padding: 6px 8px;
} }
.url-import-btn {
padding: 0 8px;
}
} }
/* /*

View file

@ -25,6 +25,18 @@ export type VoiceChannelInfo = {
export type Category = { id: string; name: string; color?: string; sort?: number }; export type Category = { id: string; name: string; color?: string; sort?: number };
export type AnalyticsItem = {
name: string;
relativePath: string;
count: number;
};
export type AnalyticsResponse = {
totalSounds: number;
totalPlays: number;
mostPlayed: AnalyticsItem[];
};