390 lines
19 KiB
JavaScript
390 lines
19 KiB
JavaScript
/**
|
||
* Musik-Seite (musik.php): Zustand des Bots alle paar Sekunden von musik_api.php holen (nur solange die Seite
|
||
* sichtbar ist), Knoepfe, Lautstaerke, Spulen im Fortschrittsbalken, Kanal waehlen, Titel/Links hinzufuegen,
|
||
* Warteschlange (umsortieren, hinspringen), Verlauf und Playlist - die Leitung (music.manage) laedt Titel hoch
|
||
* und loescht sie. Die Zeit des laufenden Titels zaehlt zwischen zwei Abfragen weiter. Listen werden nur neu
|
||
* aufgebaut, wenn sich ihr Inhalt geaendert hat, damit Scrollposition und Klicks nicht verloren gehen.
|
||
*/
|
||
(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_NAMES = { file: 'Playlist der Legion', youtube: 'YouTube', spotify: 'Spotify', search: 'YouTube-Suche' };
|
||
// Kleine Icons fuer die Listen (gleiche Pfade wie icon() in includes/functions.php)
|
||
var ICON_PATHS = {
|
||
play: '<path d="M8 5v14l11-7z"/>',
|
||
trash: '<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>',
|
||
x: '<line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/>',
|
||
up: '<line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/>',
|
||
replay: '<polyline points="1 4 1 10 7 10"/><path d="M3.5 15a9 9 0 1 0 2.1-9.4L1 10"/>'
|
||
};
|
||
var svg = function (name) {
|
||
return '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + ICON_PATHS[name] + '</svg>';
|
||
};
|
||
var state = null;
|
||
var stateAt = 0;
|
||
var busy = false;
|
||
var volumeTimer = null;
|
||
var signatures = {};
|
||
|
||
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 sourceDot = function (source) {
|
||
var dot = document.createElement('i');
|
||
dot.className = 'music-src is-' + (source || 'file');
|
||
dot.title = SOURCE_NAMES[source] || '';
|
||
return dot;
|
||
};
|
||
|
||
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) { if (fields[key] !== null && fields[key] !== undefined) 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 control = function (name, value) {
|
||
return act({ action: 'control', control: name, value: value === undefined ? null : String(value) }).catch(function () {});
|
||
};
|
||
// Abspielen: ist der Bot in keinem Kanal, kommt der gewaehlte Kanal mit (der Bot geht dann selbst hinein)
|
||
var play = function (query) {
|
||
var channel = $('[data-music-channels]').value;
|
||
if (state && !state.connected && !channel) {
|
||
toast('Bitte zuerst oben einen Sprachkanal wählen.', true);
|
||
return Promise.reject(new Error('kein Kanal'));
|
||
}
|
||
return act({ action: 'play', query: query, channel_id: state && !state.connected ? channel : null });
|
||
};
|
||
|
||
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 (item, meta, buttons, by) {
|
||
var li = document.createElement('li');
|
||
var art = document.createElement('span');
|
||
art.className = 'music-item-art';
|
||
if (item.thumbnail) {
|
||
var img = document.createElement('img');
|
||
img.src = item.thumbnail;
|
||
img.alt = '';
|
||
img.loading = 'lazy';
|
||
art.appendChild(img);
|
||
} else {
|
||
art.appendChild(sourceDot(item.source));
|
||
}
|
||
li.appendChild(art);
|
||
var text = item.title;
|
||
var label = document.createElement('span');
|
||
label.className = 'music-item-title';
|
||
label.textContent = text;
|
||
label.title = text;
|
||
var info = document.createElement('span');
|
||
info.className = 'music-item-meta';
|
||
info.textContent = meta;
|
||
li.appendChild(label);
|
||
if (by) {
|
||
var who = document.createElement('span');
|
||
who.className = 'music-item-by';
|
||
who.textContent = by;
|
||
who.title = 'Gewünscht von ' + by;
|
||
li.appendChild(who);
|
||
}
|
||
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.innerHTML = svg(b.icon);
|
||
btn.title = b.title;
|
||
btn.addEventListener('click', b.onClick);
|
||
li.appendChild(btn);
|
||
});
|
||
return li;
|
||
};
|
||
var emptyItem = function (text) {
|
||
var li = document.createElement('li');
|
||
li.className = 'music-empty';
|
||
li.textContent = text;
|
||
return li;
|
||
};
|
||
// Liste nur neu aufbauen, wenn sich ihr Inhalt geaendert hat (sonst springt die Scrollposition alle 3 s)
|
||
var changed = function (key, data) {
|
||
var signature = JSON.stringify(data);
|
||
if (signatures[key] === signature) return false;
|
||
signatures[key] = signature;
|
||
return true;
|
||
};
|
||
|
||
var renderTracks = function () {
|
||
var filter = ($('[data-music-filter]').value || '').toLowerCase();
|
||
var tracks = (state && state.tracks) || [];
|
||
if (!changed('tracks', [tracks, filter])) return;
|
||
var list = $('[data-music-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) {
|
||
list.appendChild(emptyItem(tracks.length ? 'Kein Treffer.' : 'Noch keine eigenen Titel' + (canManage ? ' – lade unten welche hoch.' : '.')));
|
||
return;
|
||
}
|
||
shown.forEach(function (t) {
|
||
var buttons = [{ icon: 'play', title: 'In die Warteschlange', onClick: function () { play(String(t.id)).catch(function () {}); } }];
|
||
if (canManage) {
|
||
buttons.push({ icon: 'trash', 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) }).catch(function () {});
|
||
} });
|
||
}
|
||
list.appendChild(listItem({ title: t.title, source: 'file' }, fmt(t.duration), buttons));
|
||
});
|
||
};
|
||
|
||
var renderQueue = function (music) {
|
||
$('[data-music-queue-count]').textContent = music.queue_total ? '(' + music.queue_total + ')' : '';
|
||
if (!changed('queue', [music.queue, music.queue_total])) return;
|
||
var queue = $('[data-music-queue]');
|
||
queue.textContent = '';
|
||
if (!music.queue.length) queue.appendChild(emptyItem('Nichts in der Warteschlange – füg oben etwas hinzu.'));
|
||
music.queue.forEach(function (item, index) {
|
||
var buttons = [];
|
||
if (index > 0) buttons.push({ icon: 'up', title: 'Als Nächstes', onClick: function () { control('move', index); } });
|
||
buttons.push({ icon: 'play', title: 'Jetzt abspielen', onClick: function () { control('jump', index); } });
|
||
buttons.push({ icon: 'x', title: 'Aus der Warteschlange', danger: true, onClick: function () { control('remove', index); } });
|
||
queue.appendChild(listItem(item, fmt(item.duration), buttons, item.added_by));
|
||
});
|
||
if (music.queue_total > music.queue.length) {
|
||
queue.appendChild(emptyItem('… und ' + (music.queue_total - music.queue.length) + ' weitere'));
|
||
}
|
||
};
|
||
|
||
var renderHistory = function (music) {
|
||
var history = music.history || [];
|
||
$('[data-music-history-card]').hidden = !history.length;
|
||
if (!changed('history', history)) return;
|
||
var list = $('[data-music-history]');
|
||
list.textContent = '';
|
||
history.forEach(function (item) {
|
||
list.appendChild(listItem(item, fmt(item.duration), [
|
||
{ icon: 'replay', title: 'Noch einmal in die Warteschlange', onClick: function () { play(item.replay).catch(function () {}); } }
|
||
], item.added_by));
|
||
});
|
||
};
|
||
|
||
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') + ' · ' + (SOURCE_NAMES[current.source] || '')
|
||
: 'Gerade läuft nichts';
|
||
$('[data-music-title]').textContent = current ? current.title : (music.connected ? 'Such dir unten etwas aus' : 'Hol den Bot in einen Sprachkanal');
|
||
var by = $('[data-music-by]');
|
||
by.hidden = !(current && current.added_by);
|
||
by.textContent = current && current.added_by ? 'von ' + current.added_by : '';
|
||
var link = $('[data-music-link]');
|
||
link.hidden = !(current && current.url);
|
||
if (current && current.url) link.href = current.url;
|
||
var cover = $('[data-music-cover]');
|
||
var coverUrl = current && current.thumbnail ? current.thumbnail : '';
|
||
if (cover.getAttribute('src') !== coverUrl) {
|
||
if (coverUrl) cover.src = coverUrl; else cover.removeAttribute('src');
|
||
}
|
||
cover.hidden = !coverUrl;
|
||
$('[data-music-duration]').textContent = current ? fmt(current.duration) : '0:00';
|
||
$('[data-music-progress]').classList.toggle('is-seekable', !!(current && current.duration));
|
||
if (!current) {
|
||
$('[data-music-elapsed]').textContent = '0:00';
|
||
$('[data-music-bar]').style.width = '0%';
|
||
}
|
||
tick();
|
||
var next = $('[data-music-next]');
|
||
next.hidden = !music.queue.length;
|
||
next.textContent = music.queue.length ? 'Als Nächstes: ' + music.queue[0].title : '';
|
||
$('[data-music-volume]').style.setProperty('--v', music.volume + '%');
|
||
|
||
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 + ' %';
|
||
} else {
|
||
volume.style.setProperty('--v', volume.value + '%');
|
||
}
|
||
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 && changed('channels', [music.voice_channels, music.channel])) {
|
||
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 + ' drin' : '');
|
||
select.appendChild(option);
|
||
});
|
||
select.value = chosen;
|
||
}
|
||
$('[data-music-channel] span').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';
|
||
|
||
renderQueue(music);
|
||
renderHistory(music);
|
||
renderTracks();
|
||
};
|
||
|
||
// ---- Bedienung ----
|
||
root.querySelectorAll('[data-music-control]').forEach(function (button) {
|
||
button.addEventListener('click', function () {
|
||
if (button.dataset.musicControl === 'clear' && !window.confirm('Warteschlange leeren?')) return;
|
||
control(button.dataset.musicControl);
|
||
});
|
||
});
|
||
var volume = $('[data-music-volume]');
|
||
volume.addEventListener('input', function () {
|
||
$('[data-music-volume-text]').textContent = volume.value + ' %';
|
||
volume.style.setProperty('--v', volume.value + '%');
|
||
clearTimeout(volumeTimer);
|
||
volumeTimer = setTimeout(function () {
|
||
volumeTimer = null;
|
||
control('volume', volume.value);
|
||
}, 350);
|
||
});
|
||
// Spulen: Klick in den Fortschrittsbalken
|
||
$('[data-music-progress]').addEventListener('click', function (event) {
|
||
if (!state || !state.current || !state.current.duration) return;
|
||
var rect = event.currentTarget.getBoundingClientRect();
|
||
var ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
|
||
control('seek', Math.floor(ratio * state.current.duration));
|
||
});
|
||
// Tastatur: Leertaste = Pause/Weiter, N = naechster Titel (nicht in Eingabefeldern)
|
||
document.addEventListener('keydown', function (event) {
|
||
var tag = (event.target.tagName || '').toLowerCase();
|
||
if (tag === 'input' || tag === 'textarea' || tag === 'select' || event.ctrlKey || event.altKey || event.metaKey) return;
|
||
if (event.key === ' ') { event.preventDefault(); control('toggle'); }
|
||
if (event.key === 'n' || event.key === 'N') control('skip');
|
||
});
|
||
$('[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 …';
|
||
play(query)
|
||
.then(function () { input.value = ''; })
|
||
.catch(function () {})
|
||
.finally(function () { button.disabled = false; button.textContent = 'Abspielen'; });
|
||
});
|
||
$('[data-music-play-all]').addEventListener('click', function () { play('').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 : 'Audiodatei 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 = 'Audiodatei wählen'; })
|
||
.catch(function () {})
|
||
.finally(function () { button.disabled = false; button.textContent = 'Hochladen'; });
|
||
});
|
||
}
|
||
|
||
poll();
|
||
setInterval(poll, POLL_MS);
|
||
setInterval(tick, 500);
|
||
document.addEventListener('visibilitychange', function () { if (!document.hidden) poll(); });
|
||
})();
|