diff --git a/assets/css/style.css b/assets/css/style.css index bf04cde..7fb0b77 100644 --- a/assets/css/style.css +++ b/assets/css/style.css @@ -10194,3 +10194,74 @@ a.hunt-review-spot-thumb { width: 64px; height: 40px; flex-shrink: 0; } .hunt-form-grid { grid-template-columns: 1fr; } .hunt-spots { grid-template-columns: 1fr; } } + +/* ===== Musik (musik.php, assets/js/music.js): den Bot im Sprachkanal steuern ===== */ +.music-page { display: flex; flex-direction: column; gap: 1rem; } +.music-connection { padding: 0.2rem 0.7rem; border-radius: 999px; background: rgba(255, 255, 255, 0.06); color: var(--text-muted); font-size: 0.82rem; } +.music-connection.is-online { background: rgba(76, 175, 80, 0.15); color: #8fdc93; } +.music-connection.is-offline { background: rgba(217, 83, 79, 0.15); color: #f2a19e; } +.music-now { display: flex; align-items: center; gap: 1.25rem; margin: 0.8rem 0 1rem; } +.music-disc { + position: relative; flex: none; width: 96px; height: 96px; border-radius: 50%; + background: repeating-radial-gradient(circle, #1b1b1b 0 2px, #262626 2px 4px); box-shadow: 0 0 0 2px rgba(201, 162, 39, 0.35), 0 6px 18px rgba(0, 0, 0, 0.45); +} +.music-disc span { position: absolute; inset: 34px; border-radius: 50%; background: radial-gradient(circle, #1a1a1a 0 18%, var(--gold) 20% 100%); } +.is-playing .music-disc { animation: music-spin 3.2s linear infinite; } +.is-playing .music-disc { box-shadow: 0 0 0 2px var(--gold), 0 0 22px rgba(201, 162, 39, 0.35); } +@keyframes music-spin { to { transform: rotate(360deg); } } +.music-now-text { display: flex; flex: 1; flex-direction: column; gap: 0.2rem; min-width: 0; } +.music-now-label { color: var(--text-muted); font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.05em; } +.music-now-title { font-size: 1.15rem; line-height: 1.3; overflow-wrap: anywhere; } +.music-now-link { width: max-content; font-size: 0.8rem; } +.music-progress { position: relative; height: 6px; margin-top: 0.45rem; border-radius: 3px; background: rgba(255, 255, 255, 0.08); overflow: hidden; } +.music-progress i { position: absolute; inset: 0 auto 0 0; width: 0; border-radius: 3px; background: linear-gradient(90deg, #a07d1c, #e3bd6e); transition: width 0.5s linear; } +.music-times { display: flex; justify-content: space-between; color: var(--text-muted); font-size: 0.75rem; } +.music-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; } +.music-btn { + display: grid; place-items: center; width: 2.6rem; height: 2.6rem; padding: 0; border: 1px solid var(--border); border-radius: 50%; + background: var(--bg-panel-alt); box-shadow: none; font-size: 1.05rem; transition: border-color 0.15s, transform 0.15s, background 0.15s; +} +.music-btn:hover { border-color: var(--gold); background: rgba(201, 162, 39, 0.1); transform: translateY(-1px); box-shadow: none; } +.music-btn.is-big { width: 3.3rem; height: 3.3rem; font-size: 1.4rem; border-color: rgba(201, 162, 39, 0.6); } +.music-btn.is-on { border-color: var(--gold); background: rgba(201, 162, 39, 0.2); } +.music-volume { display: flex; flex: 1 1 14rem; align-items: center; gap: 0.5rem; margin: 0 0 0 0.75rem; font-weight: 400; } +.music-volume input { flex: 1; width: auto; accent-color: var(--gold); } +.music-volume span { min-width: 2.8rem; color: var(--text-muted); font-size: 0.82rem; text-align: right; } +.music-error { margin: 0.8rem 0 0; padding: 0.5rem 0.75rem; border-radius: 8px; background: rgba(240, 180, 108, 0.1); color: #f0b46c; font-size: 0.85rem; } +.music-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 1rem; align-items: start; } +.music-card { margin: 0; } +.music-card h2 { margin: 0 0 0.6rem; font-size: 1.05rem; } +.music-card-head { display: flex; align-items: baseline; justify-content: space-between; gap: 0.5rem; } +.music-card-head .armory-text-button { white-space: nowrap; } +.music-row { display: flex; flex-direction: row; flex-wrap: wrap; align-items: center; gap: 0.5rem; } +.music-row select, .music-row input { flex: 1 1 12rem; width: auto; min-width: 0; } +.music-list { display: flex; flex-direction: column; gap: 0.25rem; max-height: 22rem; margin: 0; padding: 0; overflow-y: auto; list-style: none; counter-reset: music; } +.music-list li { display: flex; align-items: center; gap: 0.5rem; padding: 0.35rem 0.5rem; border-radius: 6px; background: rgba(255, 255, 255, 0.025); font-size: 0.88rem; } +.music-list li:hover { background: rgba(255, 255, 255, 0.05); } +ol.music-list li:not(.music-empty)::before { counter-increment: music; content: counter(music); min-width: 1.3rem; color: var(--text-muted); font-size: 0.75rem; text-align: right; } +.music-item-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.music-item-meta { color: var(--text-muted); font-size: 0.75rem; } +.music-item-btn { padding: 0.1rem 0.45rem; border: 1px solid transparent; background: none; box-shadow: none; color: var(--text-muted); font-size: 0.85rem; } +.music-item-btn:hover { border-color: var(--gold); background: rgba(201, 162, 39, 0.1); color: var(--text); box-shadow: none; } +.music-item-btn.is-danger:hover { border-color: var(--danger); background: rgba(217, 83, 79, 0.12); } +.music-empty { color: var(--text-muted); font-style: italic; } +.music-filter { width: 100%; margin-bottom: 0.5rem; } +.music-upload { display: flex; flex-direction: row; flex-wrap: wrap; align-items: center; gap: 0.5rem; margin-top: 0.8rem; padding-top: 0.8rem; border-top: 1px dashed var(--border); } +.music-upload input[type="text"] { flex: 1 1 10rem; width: auto; } +.music-file { position: relative; display: flex; flex: 1 1 100%; align-items: center; margin: 0; padding: 0.5rem 0.75rem; border: 1px dashed rgba(201, 162, 39, 0.5); border-radius: 8px; color: var(--text-muted); font-size: 0.85rem; font-weight: 400; cursor: pointer; } +.music-file input { position: absolute; inset: 0; opacity: 0; cursor: pointer; } +.is-busy .music-btn, .is-busy .music-item-btn { opacity: 0.6; } +.music-toast { + position: fixed; left: 50%; bottom: 1.5rem; z-index: 1200; max-width: min(92vw, 520px); padding: 0.6rem 1rem; border: 1px solid rgba(201, 162, 39, 0.5); + border-radius: 10px; background: #1d1d1d; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5); transform: translateX(-50%); font-size: 0.9rem; +} +.music-toast.is-error { border-color: rgba(217, 83, 79, 0.7); color: #f2a19e; } +@media (max-width: 560px) { + .music-now { gap: 0.9rem; } + .music-disc { width: 64px; height: 64px; } + .music-disc span { inset: 22px; } + .music-volume { flex-basis: 100%; margin-left: 0; } +} +@media (prefers-reduced-motion: reduce) { + .is-playing .music-disc { animation: none; } +} diff --git a/assets/js/music.js b/assets/js/music.js new file mode 100644 index 0000000..1bb5b8e --- /dev/null +++ b/assets/js/music.js @@ -0,0 +1,282 @@ +/** + * Musik-Seite (musik.php): Zustand des Bots alle paar Sekunden von musik_api.php holen (nur solange die Seite + * sichtbar ist), Knoepfe, Lautstaerke, Kanal waehlen, Titel/Links hinzufuegen, Warteschlange und Playlist - + * die Leitung (music.manage) laedt Titel hoch und loescht sie. Die Zeit des laufenden Titels zaehlt dazwischen weiter. + */ +(function () { + 'use strict'; + + var root = document.querySelector('[data-music]'); + if (!root || !window.fetch || !window.FormData) return; + + var csrf = (document.querySelector('meta[name="csrf-token"]') || {}).content || ''; + var canManage = root.dataset.canManage === '1'; + var POLL_MS = 3000; + var SOURCE_ICONS = { file: '📁', youtube: '▶️', spotify: '🟢', search: '🔎' }; + var state = null; + var stateAt = 0; + var busy = false; + var pollTimer = null; + var volumeTimer = null; + + var $ = function (sel) { return root.querySelector(sel); }; + var fmt = function (seconds) { + if (!seconds && seconds !== 0) return '?:??'; + seconds = Math.max(0, Math.round(seconds)); + var h = Math.floor(seconds / 3600); + var m = Math.floor(seconds % 3600 / 60); + var s = seconds % 60; + return (h ? h + ':' + String(m).padStart(2, '0') : m) + ':' + String(s).padStart(2, '0'); + }; + + var toastTimer = null; + var toast = function (text, isError) { + var box = document.querySelector('[data-music-toast]'); + if (!box || !text) return; + box.textContent = text.replace(/\*\*/g, ''); + box.classList.toggle('is-error', !!isError); + box.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(function () { box.hidden = true; }, isError ? 6000 : 3000); + }; + + var request = function (fields, file) { + var body = new FormData(); + body.append('csrf_token', csrf); + Object.keys(fields).forEach(function (key) { body.append(key, fields[key]); }); + if (file) body.append('file', file); + return fetch('/musik_api.php', { + method: 'POST', body: body, credentials: 'same-origin', + headers: { 'X-Requested-With': 'fetch', 'Accept': 'application/json' } + }).then(function (response) { return response.json(); }); + }; + + var act = function (fields, file) { + busy = true; + root.classList.add('is-busy'); + return request(fields, file) + .then(function (result) { + if (!result.ok) throw new Error(result.error || 'Hat nicht geklappt.'); + if (result.music) render(result.music); + toast(result.message); + return result; + }) + .catch(function (error) { toast(error.message, true); throw error; }) + .finally(function () { busy = false; root.classList.remove('is-busy'); }); + }; + + var poll = function () { + if (document.hidden || busy) return; + fetch('/musik_api.php?action=state', { credentials: 'same-origin', headers: { 'Accept': 'application/json' } }) + .then(function (response) { return response.json(); }) + .then(function (result) { + if (!result.ok) throw new Error(result.error || 'Bot nicht erreichbar'); + render(result.music); + }) + .catch(function (error) { + var connection = $('[data-music-connection]'); + connection.textContent = '⚠️ ' + error.message; + connection.className = 'music-connection is-offline'; + }); + }; + + var tick = function () { + if (!state || !state.current) return; + var elapsed = state.current.elapsed + (state.paused ? 0 : (Date.now() - stateAt) / 1000); + var duration = state.current.duration || 0; + if (duration) elapsed = Math.min(elapsed, duration); + $('[data-music-elapsed]').textContent = fmt(elapsed); + $('[data-music-bar]').style.width = duration ? Math.min(100, elapsed / duration * 100) + '%' : '0%'; + }; + + var listItem = function (text, meta, buttons) { + var li = document.createElement('li'); + var label = document.createElement('span'); + label.className = 'music-item-title'; + label.textContent = text; + var info = document.createElement('span'); + info.className = 'music-item-meta'; + info.textContent = meta; + li.appendChild(label); + li.appendChild(info); + buttons.forEach(function (b) { + var btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'music-item-btn' + (b.danger ? ' is-danger' : ''); + btn.textContent = b.label; + btn.title = b.title; + btn.addEventListener('click', b.onClick); + li.appendChild(btn); + }); + return li; + }; + + var renderTracks = function () { + var list = $('[data-music-tracks]'); + var filter = ($('[data-music-filter]').value || '').toLowerCase(); + var tracks = (state && state.tracks) || []; + $('[data-music-tracks-count]').textContent = tracks.length ? '(' + tracks.length + ')' : ''; + list.textContent = ''; + var shown = tracks.filter(function (t) { return t.title.toLowerCase().indexOf(filter) !== -1; }); + if (!shown.length) { + var empty = document.createElement('li'); + empty.className = 'music-empty'; + empty.textContent = tracks.length ? 'Kein Treffer.' : 'Noch keine Titel' + (canManage ? ' – lade unten welche hoch.' : '.'); + list.appendChild(empty); + return; + } + shown.forEach(function (t) { + var buttons = [{ label: '▶', title: 'In die Warteschlange', onClick: function () { act({ action: 'play', query: String(t.id) }); } }]; + if (canManage) { + buttons.push({ label: '🗑', title: 'Aus der Playlist löschen', danger: true, onClick: function () { + if (window.confirm('„' + t.title + '“ aus der Playlist löschen?')) act({ action: 'delete', track_id: String(t.id) }); + } }); + } + list.appendChild(listItem('📁 ' + t.title, fmt(t.duration), buttons)); + }); + }; + + var render = function (music) { + state = music; + stateAt = Date.now(); + var connection = $('[data-music-connection]'); + connection.textContent = music.connected ? '🟢 Im Sprachkanal ' + music.channel.name : '⚪ Nicht im Sprachkanal'; + connection.className = 'music-connection' + (music.connected ? ' is-online' : ''); + root.classList.toggle('is-playing', !!(music.current && !music.paused)); + root.classList.toggle('is-paused', !!music.paused); + + var current = music.current; + $('[data-music-status]').textContent = current ? (music.paused ? '⏸️ Pausiert' : '🎶 Läuft gerade') : 'Gerade läuft nichts'; + $('[data-music-title]').textContent = current ? (SOURCE_ICONS[current.source] || '') + ' ' + current.title : '–'; + var link = $('[data-music-link]'); + link.hidden = !(current && current.url); + if (current && current.url) link.href = current.url; + $('[data-music-duration]').textContent = current ? fmt(current.duration) : '0:00'; + if (!current) { + $('[data-music-elapsed]').textContent = '0:00'; + $('[data-music-bar]').style.width = '0%'; + } + tick(); + + root.querySelectorAll('[data-music-control="shuffle"]').forEach(function (b) { b.classList.toggle('is-on', !!music.shuffle); }); + root.querySelectorAll('[data-music-control="loop"]').forEach(function (b) { b.classList.toggle('is-on', !!music.loop); }); + var volume = $('[data-music-volume]'); + if (document.activeElement !== volume && !volumeTimer) { + volume.value = music.volume; + $('[data-music-volume-text]').textContent = music.volume + ' %'; + } + var error = $('[data-music-error]'); + error.hidden = !music.last_error; + error.textContent = music.last_error ? '⚠️ Zuletzt übersprungen: ' + music.last_error : ''; + + // Sprachkanaele + var select = $('[data-music-channels]'); + if (document.activeElement !== select) { + var chosen = select.value || (music.channel ? String(music.channel.id) : ''); + select.textContent = ''; + var first = document.createElement('option'); + first.value = ''; + first.textContent = 'Sprachkanal wählen …'; + select.appendChild(first); + (music.voice_channels || []).forEach(function (c) { + var option = document.createElement('option'); + option.value = String(c.id); + option.textContent = '🔊 ' + c.name + (c.listeners ? ' (' + c.listeners + ')' : ''); + select.appendChild(option); + }); + select.value = chosen; + } + $('[data-music-channel]').textContent = music.connected + ? 'Der Bot ist in 🔊 ' + music.channel.name + ' – ' + music.channel.listeners + ' Zuhörer' + : 'Der Bot ist in keinem Sprachkanal.'; + $('[data-music-leave]').hidden = !music.connected; + $('[data-music-join]').textContent = music.connected ? 'Umziehen' : 'Holen'; + + // Warteschlange + var queue = $('[data-music-queue]'); + queue.textContent = ''; + $('[data-music-queue-count]').textContent = music.queue_total ? '(' + music.queue_total + ')' : ''; + if (!music.queue.length) { + var empty = document.createElement('li'); + empty.className = 'music-empty'; + empty.textContent = 'Leer.'; + queue.appendChild(empty); + } + music.queue.forEach(function (item, index) { + queue.appendChild(listItem((SOURCE_ICONS[item.source] || '') + ' ' + item.title, fmt(item.duration), [ + { label: '✕', title: 'Aus der Warteschlange', onClick: function () { act({ action: 'control', control: 'remove', value: String(index) }); } } + ])); + }); + if (music.queue_total > music.queue.length) { + var more = document.createElement('li'); + more.className = 'music-empty'; + more.textContent = '… und ' + (music.queue_total - music.queue.length) + ' weitere'; + queue.appendChild(more); + } + renderTracks(); + }; + + // ---- Bedienung ---- + root.querySelectorAll('[data-music-control]').forEach(function (button) { + button.addEventListener('click', function () { + if (button.dataset.musicControl === 'clear' && !window.confirm('Warteschlange leeren?')) return; + act({ action: 'control', control: button.dataset.musicControl }); + }); + }); + var volume = $('[data-music-volume]'); + volume.addEventListener('input', function () { + $('[data-music-volume-text]').textContent = volume.value + ' %'; + clearTimeout(volumeTimer); + volumeTimer = setTimeout(function () { + volumeTimer = null; + act({ action: 'control', control: 'volume', value: volume.value }).catch(function () {}); + }, 350); + }); + $('[data-music-join]').addEventListener('click', function () { + var channel = $('[data-music-channels]').value; + if (!channel) { toast('Bitte zuerst einen Sprachkanal wählen.', true); return; } + act({ action: 'join', channel_id: channel }).catch(function () {}); + }); + $('[data-music-leave]').addEventListener('click', function () { act({ action: 'leave' }).catch(function () {}); }); + $('[data-music-add]').addEventListener('submit', function (event) { + event.preventDefault(); + var input = $('[data-music-query]'); + var query = input.value.trim(); + if (!query) return; + var button = event.target.querySelector('button'); + button.disabled = true; + button.textContent = 'Suche …'; + act({ action: 'play', query: query }) + .then(function () { input.value = ''; }) + .catch(function () {}) + .finally(function () { button.disabled = false; button.textContent = 'Abspielen'; }); + }); + $('[data-music-play-all]').addEventListener('click', function () { act({ action: 'play', query: '' }).catch(function () {}); }); + $('[data-music-filter]').addEventListener('input', renderTracks); + + var upload = $('[data-music-upload]'); + if (upload) { + var fileInput = upload.querySelector('input[type="file"]'); + fileInput.addEventListener('change', function () { + upload.querySelector('[data-music-file-label]').textContent = fileInput.files[0] ? fileInput.files[0].name : 'Datei wählen'; + }); + upload.addEventListener('submit', function (event) { + event.preventDefault(); + var file = fileInput.files[0]; + if (!file) return; + if (file.size > 25 * 1024 * 1024) { toast('Die Datei ist größer als 25 MB.', true); return; } + var button = upload.querySelector('button'); + button.disabled = true; + button.textContent = 'Lädt hoch …'; + act({ action: 'upload', title: upload.querySelector('input[name="title"]').value }, file) + .then(function () { upload.reset(); upload.querySelector('[data-music-file-label]').textContent = 'Datei wählen'; }) + .catch(function () {}) + .finally(function () { button.disabled = false; button.textContent = 'Hochladen'; }); + }); + } + + poll(); + pollTimer = setInterval(poll, POLL_MS); + setInterval(tick, 500); + document.addEventListener('visibilitychange', function () { if (!document.hidden) poll(); }); +})(); diff --git a/includes/functions.php b/includes/functions.php index a3fc6ab..b692693 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -9,7 +9,7 @@ declare(strict_types=1); const SIDEBAR_NAV_MAIN = [ '/dashboard.php', '/checklist.php', '/consilium.php', '/profile.php', '/members.php', '/gallery.php', '/contributions.php', '/shop.php', 'gap', '/wiki.php', '/raids.php', '/premades.php', '/calendar.php', '/events.php', '/hunt.php', - '/map.php', '/raidplan.php', '/gear.php', '/professions.php', '/warehouse.php', + '/map.php', '/raidplan.php', '/gear.php', '/musik.php', '/professions.php', '/warehouse.php', ]; // So viele zusaetzliche Trennlinien darf jedes Mitglied einfuegen const SIDEBAR_MAX_EXTRA_GAPS = 10; @@ -171,6 +171,7 @@ function icon(string $name): string 'book' => '', 'code' => '', 'sword' => '', + 'music' => '', 'bug' => '', 'shield-check' => '', 'hammer' => '', diff --git a/includes/header.php b/includes/header.php index 2029263..a18bc7d 100644 --- a/includes/header.php +++ b/includes/header.php @@ -21,6 +21,7 @@ $canManageDues = $currentUser && user_has_permission('dues.manage'); $canViewMap = $currentUser && user_has_permission('map.view'); $canViewWarehouse = $currentUser && user_has_permission('warehouse.view'); $canViewGear = $currentUser && user_has_permission('gear.view'); +$canPlayMusic = $currentUser && user_has_permission('music.control'); $canViewChecklist = $currentUser && user_has_permission('checklist.view'); $canViewContributions = $currentUser && user_has_permission('contributions.view'); $canViewShop = $currentUser && user_has_permission('shop.view'); @@ -83,6 +84,7 @@ $isRaidplanActive = $currentScript === 'raidplan.php'; $isWarehouseActive = $currentScript === 'warehouse.php'; $isGearActive = in_array($currentScript, ['gear.php', 'gear_items.php', 'gear_skills.php'], true); $isProfessionsActive = $currentScript === 'professions.php'; +$isMusicActive = $currentScript === 'musik.php'; $isContributionsActive = in_array($currentScript, ['contributions.php', 'contributions_award.php'], true); $isShopActive = in_array($currentScript, ['shop.php', 'shop_orders.php', 'shop_manage.php'], true); $isMembersActive = in_array($currentScript, ['members.php', 'member.php', 'member_edit.php', 'member_picture.php'], true); @@ -119,6 +121,7 @@ $pageBackgrounds = [ 'warehouse.php' => 'bg-warehouse', 'gear.php' => 'bg-warehouse', 'professions.php' => 'bg-warehouse', + 'musik.php' => 'bg-events', 'gear_items.php' => 'bg-admin', 'gear_skills.php' => 'bg-admin', 'contributions.php' => 'bg-contributions', @@ -377,6 +380,11 @@ $brandLogo = $isConsiliumOnly = icon('sword') ?>Gear-Planer + + class="sidebar-link= $isMusicActive ? ' active' : '' ?>" title="Musik: den Bot im Sprachkanal steuern"> + = icon('music') ?>Musik + + class="sidebar-link= $isProfessionsActive ? ' active' : '' ?>" title="Berufe: wer in der Legion was herstellen kann"> = icon('hammer') ?>Berufe diff --git a/includes/music.php b/includes/music.php new file mode 100644 index 0000000..0e74228 --- /dev/null +++ b/includes/music.php @@ -0,0 +1,79 @@ +|null $json JSON-Body + * @param array{0: string, 1: string, 2: string}|null $file [Pfad, Dateiname, Titel] fuer den Upload (multipart) + * @return array + * @throws RuntimeException mit verstaendlicher Meldung + */ +function music_api_request(string $method, string $path, ?array $json = null, ?array $file = null): array +{ + if (!function_exists('curl_init')) { + throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); + } + $headers = ['X-API-Key: ' . raids_api_config()['key']]; + $ch = curl_init(music_api_base() . $path); + $options = [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CUSTOMREQUEST => $method, + CURLOPT_TIMEOUT => MUSIC_API_TIMEOUT, + CURLOPT_CONNECTTIMEOUT => 5, + ]; + if ($file !== null) { + $options[CURLOPT_POSTFIELDS] = [ + 'file' => new CURLFile($file[0], 'application/octet-stream', $file[1]), + 'title' => $file[2], + 'user_id' => (string) (current_user()['discord_id'] ?? '0'), + ]; + } elseif ($json !== null) { + $headers[] = 'Content-Type: application/json'; + $options[CURLOPT_POSTFIELDS] = json_encode($json, JSON_UNESCAPED_UNICODE); + } + $options[CURLOPT_HTTPHEADER] = $headers; + curl_setopt_array($ch, $options); + $response = curl_exec($ch); + $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); + $error = curl_error($ch); + curl_close($ch); + if ($response === false) { + throw new RuntimeException('Der Bot ist gerade nicht erreichbar (' . $error . ').'); + } + $data = json_decode((string) $response, true); + if ($status < 200 || $status >= 300) { + $detail = is_array($data) ? ($data['detail'] ?? $data['message'] ?? '') : ''; + throw new RuntimeException(is_string($detail) && $detail !== '' ? $detail : 'Der Bot antwortet mit Status ' . $status . '.'); + } + if (!is_array($data)) { + throw new RuntimeException('Unerwartete Antwort vom Bot.'); + } + return $data; +} + +/** Zustand der Musik auf dem Legions-Server (Kanal, Titel, Warteschlange, Playlist). */ +function music_state(): array +{ + return (array) (music_api_request('GET', '/music/' . events_guild_id())['music'] ?? []); +} diff --git a/includes/patchnotes.php b/includes/patchnotes.php index a7310f8..5646512 100644 --- a/includes/patchnotes.php +++ b/includes/patchnotes.php @@ -19,6 +19,17 @@ const PATCHNOTE_TYPES = [ ]; const PATCHNOTES = [ + [ + 'id' => '2026-10-28-a', + 'date' => '2026-10-28', + 'title' => 'Musik im Discord', + 'summary' => 'Nezekan spielt Musik im Sprachkanal – YouTube, YouTube Music, Spotify und die Playlist der Legion, gesteuert per /musik oder über die neue Seite „Musik“.', + 'changes' => [ + ['type' => 'neu', 'area' => 'Musik', 'text' => 'Neue Seite „Musik“: Bot in einen Sprachkanal holen oder rausschicken, YouTube-/YouTube-Music-/Spotify-Links (auch Playlists und Alben) oder einfach einen Suchbegriff abspielen, Warteschlange ansehen, Titel überspringen, pausieren, Zufall, Schleife und Lautstärke.'], + ['type' => 'neu', 'area' => 'Discord', 'text' => 'Dasselbe geht im Discord mit /musik (join, play, skip, pause, weiter, stop, leave, …) – diese Befehle darf jedes Mitglied nutzen. Nach 5 Minuten allein im Kanal geht der Bot von selbst.'], + ['type' => 'neu', 'area' => 'Musik', 'audience' => 'leitung', 'text' => 'Eigene Audiodateien (mp3, ogg, m4a, wav, flac, opus – bis 25 MB) für die Playlist der Legion hochladen und löschen, auf der Seite oder mit /musik hochladen. Dafür gibt es das neue Recht „music.manage“, das die Leitung in der Rollenverwaltung vergibt.'], + ], + ], [ 'id' => '2026-10-26-a', 'date' => '2026-10-26', diff --git a/includes/permissions.php b/includes/permissions.php index 105a701..26c228e 100644 --- a/includes/permissions.php +++ b/includes/permissions.php @@ -51,6 +51,8 @@ const CORE_PERMISSIONS = [ ['key' => 'professions.manage', 'description' => 'Berufe: Zielzahlen je Beruf festlegen - was darunter liegt, sehen alle als „Gerade gesucht“'], ['key' => 'gear.view', 'description' => 'Gear-Planer: eigene Ausrüstungssets anlegen und vergleichen, freigegebene Sets anderer ansehen'], ['key' => 'gear.publish', 'description' => 'Gear-Planer: Klassenmeister - eigene Sets als öffentliche Builds in die Build-Liste stellen; wird bei der eigenen Main-Klasse als Klassenmeister angezeigt'], + ['key' => 'music.control', 'description' => 'Musik: den Bot in einen Sprachkanal holen und Musik steuern (Playlist, YouTube-/Spotify-Links, Suche, Warteschlange, Lautstärke) – auf der Seite Musik'], + ['key' => 'music.manage', 'description' => 'Musik: Titel in die Playlist der Legion hochladen und daraus löschen'], ['key' => 'checklist.view', 'description' => 'Checkliste: tägliche und wöchentliche Aufgaben der eigenen Charaktere abhaken (Seite Checkliste und Karte im Dashboard)'], ['key' => 'gear.manage', 'description' => 'Gear-Planer: Gegenstände und ihre Werte von aion2hub übernehmen, abgleichen und löschen'], ['key' => 'calendar.leadership', 'description' => 'Kalender: Termine nur für die Leitung eintragen („Nur Leitung nimmt teil“ oder „Intern“), interne Termine sehen und bei Leitungs-Terminen teilnehmen'], diff --git a/includes/schema.php b/includes/schema.php index 79ce8eb..e4f315b 100644 --- a/includes/schema.php +++ b/includes/schema.php @@ -11,7 +11,7 @@ declare(strict_types=1); */ // Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu. -const SCHEMA_VERSION = 82; +const SCHEMA_VERSION = 83; /** * Tabellen, die nachtraeglich dazugekommen sind: Tabelle => CREATE-Befehl (wie in sql/schema.sql). @@ -1414,8 +1414,8 @@ function schema_sync_core_permissions(): void $pdo->prepare('INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)') ->execute([$adminRoleId, $newPermissionId]); } - // Das Wiki, den Gear-Planer und die Checkliste sollen alle nutzen duerfen, die ins Dashboard kommen. - if (in_array($permission['key'], ['wiki.view', 'gear.view', 'checklist.view'], true)) { + // Das Wiki, den Gear-Planer, die Checkliste und die Musik sollen alle nutzen duerfen, die ins Dashboard kommen. + if (in_array($permission['key'], ['wiki.view', 'gear.view', 'checklist.view', 'music.control'], true)) { $pdo->prepare( "INSERT IGNORE INTO role_permissions (role_id, permission_id) SELECT rp.role_id, ? FROM role_permissions rp diff --git a/includes/security.php b/includes/security.php index 649df91..f7c0a22 100644 --- a/includes/security.php +++ b/includes/security.php @@ -48,6 +48,7 @@ const SECURITY_LIMITS = [ 'discord_admin' => [1500, 3600], // Discord-Abgleich aller Konten in der Benutzerverwaltung, ein Konto je Anfrage 'export' => [6, 3600], // Datenauskunft herunterladen (eigene oder fuer andere) pro Konto 'armory' => [40, 600], // Charaktersuche bei NCSoft (Live-Daten der Profilseiten) pro Konto + 'music' => [300, 300], // Musik-Steuerung (musik_api.php): Knoepfe, Lautstaerke, Titel hinzufuegen pro Konto 'login_ip' => [15, 900], // fehlgeschlagene Logins pro IP (egal welches Konto) 'login_pair' => [5, 900], // fehlgeschlagene Logins pro IP + Benutzername 'destructive' => [20, 600], // Loeschungen pro Konto, danach automatische Sperre @@ -292,6 +293,13 @@ function security_guard_post(): void } return; } + // Musik-Steuerung: viele kleine Klicks (Lautstaerke, Skip) - eigener Topf statt "post" + if ($script === 'musik_api.php') { + if (!security_throttle('music')) { + security_reject('Sehr viele Musik-Befehle in kurzer Zeit. Bitte warte kurz.'); + } + return; + } if ($script === 'discord_sync_action.php' && in_array($_POST['action'] ?? '', DISCORD_SYNC_STEPS, true)) { if (!security_throttle('discord_admin')) { security_reject('Sehr viele Discord-Abgleiche in kurzer Zeit. Bitte warte etwas und versuche es dann erneut.'); diff --git a/musik.php b/musik.php new file mode 100644 index 0000000..fa456eb --- /dev/null +++ b/musik.php @@ -0,0 +1,95 @@ + + + + + Musik + Verbinde mit dem Bot … + + + + + Gerade läuft nichts + – + auf YouTube öffnen ↗ + + 0:000:00 + + + + 🔀 + ⏯️ + ⏭️ + ⏹️ + 🔁 + 🔊 + + 50 % + + + + + + + + Sprachkanal + Der Bot ist in keinem Sprachkanal. + + Sprachkanal wählen … + Holen + Rausschicken + + + + + Hinzufügen + + + Abspielen + + YouTube, YouTube Music (auch Playlists) und Spotify (Song, Playlist, Album – gespielt wird der passende Titel von YouTube). Ohne Link wird auf YouTube gesucht. + + + + + Warteschlange + Leeren + + Leer. + + + + + Playlist der Legion + Alle abspielen + + + Noch keine Titel. + + + + + Datei wählen (mp3, ogg, m4a, wav, flac, opus – max. 25 MB) + + + Hochladen + + + + + + + + diff --git a/musik_api.php b/musik_api.php new file mode 100644 index 0000000..1820017 --- /dev/null +++ b/musik_api.php @@ -0,0 +1,120 @@ + $ok, $ok ? 'message' : 'error' => $text], $extra), JSON_UNESCAPED_UNICODE); + exit; +}; + +if (!current_user()) { + http_response_code(401); + $reply(false, 'Bitte neu anmelden.'); +} +if (!user_has_permission('music.control')) { + http_response_code(403); + $reply(false, 'Dir fehlt die Berechtigung dafür.'); +} + +$action = (string) ($_POST['action'] ?? $_GET['action'] ?? 'state'); +if ($_SERVER['REQUEST_METHOD'] === 'POST') { + verify_csrf(); +} elseif ($action !== 'state') { + http_response_code(405); + $reply(false, 'Nur per POST.'); +} +// Die Bot-API kann etwas dauern (Playlists) - andere Seiten derselben Sitzung sollen nicht warten +session_write_close(); + +$guild = '/music/' . events_guild_id(); +try { + switch ($action) { + case 'state': + $reply(true, '', ['music' => music_state()]); + + case 'join': + $channel = (string) ($_POST['channel_id'] ?? ''); + if (!ctype_digit($channel)) { + $reply(false, 'Bitte einen Sprachkanal wählen.'); + } + $data = music_api_request('POST', $guild . '/join', ['channel_id' => (int) $channel]); + $reply(true, (string) ($data['message'] ?? ''), ['music' => $data['music'] ?? null]); + + case 'leave': + $data = music_api_request('POST', $guild . '/leave', []); + $reply(true, (string) ($data['message'] ?? ''), ['music' => $data['music'] ?? null]); + + case 'play': + $query = mb_substr(trim((string) ($_POST['query'] ?? '')), 0, MUSIC_QUERY_MAX); + $data = music_api_request('POST', $guild . '/play', ['query' => $query]); + $reply(true, (string) ($data['message'] ?? ''), ['music' => $data['music'] ?? null]); + + case 'control': + $control = (string) ($_POST['control'] ?? ''); + if (!in_array($control, MUSIC_ACTIONS, true)) { + $reply(false, 'Unbekannte Aktion.'); + } + $value = isset($_POST['value']) && is_numeric($_POST['value']) ? (int) $_POST['value'] : null; + $data = music_api_request('POST', $guild . '/control', ['action' => $control, 'value' => $value]); + $reply(true, (string) ($data['message'] ?? ''), ['music' => $data['music'] ?? null]); + + case 'upload': + if (!user_has_permission('music.manage')) { + http_response_code(403); + $reply(false, 'Titel hochladen darf nur, wer die Playlist verwaltet.'); + } + $file = $_FILES['file'] ?? null; + if (!is_array($file) || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK || !is_uploaded_file($file['tmp_name'])) { + $reply(false, ($file['error'] ?? 0) === UPLOAD_ERR_INI_SIZE || ($file['error'] ?? 0) === UPLOAD_ERR_FORM_SIZE + ? 'Die Datei ist zu groß (höchstens 25 MB).' : 'Bitte eine Datei auswählen.'); + } + $extension = strtolower(pathinfo((string) $file['name'], PATHINFO_EXTENSION)); + if (!in_array($extension, MUSIC_UPLOAD_EXTENSIONS, true)) { + $reply(false, 'Bitte eine Audiodatei: ' . implode(', ', MUSIC_UPLOAD_EXTENSIONS) . '.'); + } + if ((int) $file['size'] > MUSIC_UPLOAD_MAX) { + $reply(false, 'Die Datei ist größer als 25 MB.'); + } + $title = mb_substr(trim((string) ($_POST['title'] ?? '')), 0, 100); + $name = mb_substr(basename((string) $file['name']), 0, 150); + $data = music_api_request('POST', '/music/tracks', null, [$file['tmp_name'], $name, $title]); + $track = (array) ($data['track'] ?? []); + admin_log('🎵 Musik: Titel hochgeladen', ['Titel' => (string) ($track['title'] ?? $name)], 'info', 'discord'); + $reply(true, '„' . ($track['title'] ?? $name) . '“ ist in der Playlist.', ['music' => music_state()]); + + case 'delete': + if (!user_has_permission('music.manage')) { + http_response_code(403); + $reply(false, 'Titel löschen darf nur, wer die Playlist verwaltet.'); + } + $trackId = (string) ($_POST['track_id'] ?? ''); + if (!ctype_digit($trackId)) { + $reply(false, 'Unbekannter Titel.'); + } + music_api_request('DELETE', '/music/tracks/' . $trackId); + admin_log('🎵 Musik: Titel gelöscht', ['Titel-Nr.' => $trackId], 'danger', 'discord'); + $reply(true, 'Titel gelöscht.', ['music' => music_state()]); + + default: + http_response_code(400); + $reply(false, 'Unbekannte Aktion.'); + } +} catch (RuntimeException $e) { + $reply(false, $e->getMessage()); +}
Der Bot ist in keinem Sprachkanal.
YouTube, YouTube Music (auch Playlists) und Spotify (Song, Playlist, Album – gespielt wird der passende Titel von YouTube). Ohne Link wird auf YouTube gesucht.