LuminaWebsite/musik_api.php

196 lines
11 KiB
PHP
Raw Permalink 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.

<?php
/**
* Musik-Steuerung der Seite musik.php (assets/js/music.js) - leitet an die Musik-API des Bots weiter
* (includes/music.php). Antwortet immer mit JSON {ok, message|error, music}.
*
* Jede Anfrage traegt bot=nezekan|siel (music_bots(); fehlt es, Nezekan).
* GET ?action=state Zustand (Kanal, Titel, Warteschlange, Sprachkanaele, Playlist)
* POST action=join, channel_id Bot in einen Sprachkanal holen
* POST action=leave Bot aus dem Sprachkanal schicken
* POST action=play, query, channel_id Titel-ID, YouTube-/Spotify-Link, Suche oder leer = ganze Playlist (channel_id: Kanal, falls der Bot in keinem ist)
* POST action=control, control, value toggle, skip, stop, shuffle, loop, volume (0-100), remove/move/jump (Index), seek (Sekunde), clear
* POST action=upload, file, title Datei in die Playlist (music.manage)
* POST action=delete, track_id Titel aus der Playlist (music.manage)
* Steuern: music.control, Playlist verwalten: music.manage. POST mit CSRF-Token.
*
* YouTube-Anmeldung der Bots (nur Administratoren und Entwickler, music_can_manage_youtube()) - gilt immer fuer alle
* Musikbots, Antwort zusaetzlich mit youtube = Stand je Bot (music_youtube_login()):
* GET ?action=youtube Stand
* POST action=youtube_upload, file cookies.txt an die Bots geben (wird dort abgelegt und geprueft)
* POST action=youtube_test erneut pruefen
* POST action=youtube_delete bei den Bots entfernen
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/music.php';
require_once __DIR__ . '/includes/admin_log.php';
header('Content-Type: application/json; charset=UTF-8');
$reply = static function (bool $ok, string $text = '', array $extra = []): void {
echo json_encode(array_merge(['ok' => $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') {
// Passt das Token nicht (Sitzung zwischendurch erneuert, Seite lange offen): als JSON melden, nicht als Klartext -
// das Skript holt sich mit dem naechsten Zustand das aktuelle Token (siehe 'csrf' unten) und bittet um einen neuen Versuch
if (!hash_equals($_SESSION['csrf_token'] ?? '', (string) ($_POST['csrf_token'] ?? ''))) {
http_response_code(400);
$reply(false, 'Die Seite war zu lange offen – bitte noch einmal klicken.', ['stale' => true, 'csrf' => csrf_token()]);
}
verify_csrf();
} elseif (!in_array($action, ['state', 'youtube'], true)) {
http_response_code(405);
$reply(false, 'Nur per POST.');
}
$bot = music_bot_key((string) ($_POST['bot'] ?? $_GET['bot'] ?? 'nezekan'));
if ($bot === null) {
http_response_code(400);
$reply(false, 'Diesen Musikbot gibt es nicht.');
}
// 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($bot), 'bot' => $bot, 'csrf' => csrf_token()]);
case 'join':
$channel = (string) ($_POST['channel_id'] ?? '');
if (!ctype_digit($channel)) {
$reply(false, 'Bitte einen Sprachkanal wählen.');
}
$data = music_api_request($bot, 'POST', $guild . '/join', ['channel_id' => (int) $channel]);
$reply(true, (string) ($data['message'] ?? ''), ['music' => $data['music'] ?? null]);
case 'leave':
$data = music_api_request($bot, 'POST', $guild . '/leave', []);
$reply(true, (string) ($data['message'] ?? ''), ['music' => $data['music'] ?? null]);
case 'play':
// Ist der Bot noch in keinem Sprachkanal, holt ihn der gewaehlte Kanal gleich mit
$query = mb_substr(trim((string) ($_POST['query'] ?? '')), 0, MUSIC_QUERY_MAX);
$channel = (string) ($_POST['channel_id'] ?? '');
$user = current_user();
$data = music_api_request($bot, 'POST', $guild . '/play', [
'query' => $query,
'user' => (string) ($user['display_name'] !== '' ? $user['display_name'] : $user['username']),
'channel_id' => ctype_digit($channel) ? (int) $channel : null,
]);
$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($bot, '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($bot, 'POST', '/music/tracks', null, [$file['tmp_name'], $name, $title]);
$track = (array) ($data['track'] ?? []);
admin_log('🎵 Musik: Titel hochgeladen', ['Titel' => (string) ($track['title'] ?? $name), 'Bot' => MUSIC_BOTS[$bot]], 'info', 'discord');
$reply(true, '„' . ($track['title'] ?? $name) . '“ ist in der Playlist.', ['music' => music_state($bot)]);
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($bot, 'DELETE', '/music/tracks/' . $trackId);
admin_log('🎵 Musik: Titel gelöscht', ['Titel-Nr.' => $trackId, 'Bot' => MUSIC_BOTS[$bot]], 'danger', 'discord');
$reply(true, 'Titel gelöscht.', ['music' => music_state($bot)]);
case 'youtube':
case 'youtube_upload':
case 'youtube_test':
case 'youtube_delete':
if (!music_can_manage_youtube()) {
http_response_code(403);
$reply(false, 'Die YouTube-Anmeldung pflegen nur Administratoren und Entwickler.');
}
// Kurzfassung fuers Log: "Nezekan: ok, Siel: expired"
$summary = static fn (array $rows): string => implode(', ', array_map(
static fn (array $row): string => $row['name'] . ': ' . (isset($row['error']) ? 'Fehler' : $row['result']),
$rows
));
if ($action === 'youtube') {
$reply(true, '', ['youtube' => music_youtube_login()]);
}
if ($action === 'youtube_test') {
$reply(true, 'Geprüft.', ['youtube' => music_youtube_login('POST', '/music/cookies/test', [])]);
}
if ($action === 'youtube_delete') {
$rows = music_youtube_login('DELETE');
admin_log('🎵 Musik: YouTube-Anmeldung entfernt', ['Bots' => $summary($rows)], 'danger', 'discord');
$reply(true, 'YouTube-Anmeldung entfernt.', ['youtube' => $rows]);
}
$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, 'Bitte die exportierte cookies.txt auswählen.');
}
if ((int) $file['size'] > MUSIC_COOKIES_MAX) {
$reply(false, 'Die Datei ist zu groß – eine cookies.txt hat nur ein paar Kilobyte.');
}
// Der Inhalt geht nur an die Bots weiter - die Website speichert und loggt ihn nicht
$cookies = (string) file_get_contents($file['tmp_name']);
if (!mb_check_encoding($cookies, 'UTF-8') || stripos($cookies, 'youtube.com') === false) {
$reply(false, 'Das ist keine cookies.txt von youtube.com (Export im Format „Netscape“).');
}
$user = current_user();
$rows = music_youtube_login('POST', '/music/cookies', [
'cookies' => $cookies,
'user' => (string) ($user['display_name'] !== '' ? $user['display_name'] : $user['username']),
]);
$failed = array_filter($rows, static fn (array $row): bool => isset($row['error']));
if (count($failed) === count($rows)) {
// Kein Bot hat die Datei genommen (z. B. keine Anmeldung in den Cookies) - Meldung des ersten reicht
$reply(false, (string) reset($failed)['error'], ['youtube' => music_youtube_login()]);
}
admin_log('🎵 Musik: YouTube-Anmeldung hinterlegt', ['Bots' => $summary($rows)], 'info', 'discord');
$allOk = !$failed && !array_filter($rows, static fn (array $row): bool => $row['result'] !== 'ok');
$reply(true, $allOk ? 'YouTube-Anmeldung hinterlegt – sie funktioniert.' : 'Hochgeladen – das Ergebnis steht bei jedem Bot.', ['youtube' => $rows]);
default:
http_response_code(400);
$reply(false, 'Unbekannte Aktion.');
}
} catch (RuntimeException $e) {
$reply(false, $e->getMessage());
}