LuminaWebsite/includes/music.php

157 lines
7.2 KiB
PHP

<?php
/**
* Musik im Discord-Sprachkanal: Steuerung von der Website aus (musik.php, musik_api.php, assets/js/music.js).
* Abspielen lassen sich die Playlist des Bots (eigene Dateien, Upload mit music.manage), YouTube-/YouTube-Music-
* Links, Spotify-Links und eine freie Suche - aufgeloest und abgespielt wird alles auf dem Bot, die Website
* schickt nur Befehle.
*
* Zwei Bots, weil ein Bot pro Discord-Server nur in einem Sprachkanal sein kann (MUSIC_BOTS):
* nezekan Nezekan (raids_api in config.php), cogs/music.py + music_api.py, Pfade /api/music/...
* siel Siel (siel_api in config.php, nur wenn eingerichtet), gleicher Code, Pfade /website-api/music/...
* Jeder Bot hat seine eigene Playlist (Dateien liegen beim jeweiligen Bot).
*
* YouTube-Anmeldung: Altersbeschraenkte Videos (und manchmal die Server-IP) verlangen bei YouTube ein angemeldetes
* Konto. Die Bots nehmen dafuer die Cookies einer Browser-Sitzung (cookies.txt, youtube_cookies.py im Bot).
* Administratoren und Entwickler laden die Datei auf der Musik-Seite hoch (music_can_manage_youtube()); sie geht
* an alle Musikbots, wird dort sofort geprueft und nie auf der Website gespeichert oder wieder angezeigt.
*/
require_once __DIR__ . '/raids_api.php';
require_once __DIR__ . '/events_api.php';
// Playlists und Spotify-Listen aufzuloesen dauert - laenger warten als bei anderen Bot-Aufrufen
const MUSIC_API_TIMEOUT = 60;
const MUSIC_UPLOAD_MAX = 25 * 1024 * 1024;
const MUSIC_UPLOAD_EXTENSIONS = ['mp3', 'ogg', 'm4a', 'wav', 'flac', 'opus'];
const MUSIC_QUERY_MAX = 500;
const MUSIC_ACTIONS = ['toggle', 'pause', 'resume', 'skip', 'previous', 'stop', 'shuffle', 'loop', 'volume', 'remove', 'clear', 'move', 'jump', 'seek'];
const MUSIC_BOTS = ['nezekan' => 'Nezekan', 'siel' => 'Siel'];
const MUSIC_COOKIES_MAX = 512 * 1024; // eine cookies.txt hat nur ein paar Kilobyte
/**
* Die Musikbots, die eingerichtet sind: Schluessel => Anzeigename. Nezekan immer, Siel nur mit siel_api in config.php.
*
* @return array<string, string>
*/
function music_bots(): array
{
$bots = ['nezekan' => MUSIC_BOTS['nezekan']];
if (siel_api_config() !== null) {
$bots['siel'] = MUSIC_BOTS['siel'];
}
return $bots;
}
/** Prueft einen Bot-Schluessel aus der Anfrage; unbekannt oder nicht eingerichtet = null. */
function music_bot_key(string $bot): ?string
{
return array_key_exists($bot, music_bots()) ? $bot : null;
}
/** Basis der Musik-API des Bots: eine Ebene ueber .../raids (Nezekan: /api, Siel: /website-api). */
function music_api_base(string $bot): string
{
$config = $bot === 'siel' ? siel_api_config() : raids_api_config();
if ($config === null) {
throw new RuntimeException('Siel ist nicht eingerichtet (config.php: siel_api).');
}
return (string) preg_replace('#/raids$#', '', $config['url']);
}
/**
* Aufruf der Musik-API eines Bots.
*
* @param string $bot 'nezekan' oder 'siel' (music_bots())
* @param array<string, mixed>|null $json JSON-Body
* @param array{0: string, 1: string, 2: string}|null $file [Pfad, Dateiname, Titel] fuer den Upload (multipart)
* @return array<string, mixed>
* @throws RuntimeException mit verstaendlicher Meldung
*/
function music_api_request(string $bot, 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.');
}
$key = $bot === 'siel' ? (string) (siel_api_config()['key'] ?? '') : (string) raids_api_config()['key'];
$headers = ['X-API-Key: ' . $key];
$ch = curl_init(music_api_base($bot) . $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(MUSIC_BOTS[$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 : MUSIC_BOTS[$bot] . ' antwortet mit Status ' . $status . '.');
}
if (!is_array($data)) {
throw new RuntimeException('Unerwartete Antwort vom Bot.');
}
return $data;
}
/** Darf das Konto die YouTube-Anmeldung der Musikbots pflegen? Nur Administratoren und Entwickler. */
function music_can_manage_youtube(?array $user = null): bool
{
$user ??= current_user();
return $user !== null && (!empty($user['is_admin']) || is_developer($user));
}
/**
* YouTube-Anmeldung bei allen Musikbots abfragen oder aendern - derselbe Aufruf geht an jeden Bot.
*
* @param string $method GET = Stand, POST = hochladen ($json: cookies, user) bzw. pruefen ($path .../test), DELETE = entfernen
* @return list<array<string, mixed>> je Bot: bot, name und entweder present, uploaded_at, uploaded_by, tested_at,
* result (none|untested|ok|no_age|expired|blocked|error), detail - oder error
*/
function music_youtube_login(string $method = 'GET', string $path = '/music/cookies', ?array $json = null): array
{
$rows = [];
foreach (music_bots() as $bot => $name) {
$row = ['bot' => $bot, 'name' => $name];
try {
$state = (array) (music_api_request($bot, $method, $path, $json)['youtube'] ?? []);
$row += [
'present' => !empty($state['present']),
'uploaded_at' => isset($state['uploaded_at']) ? (int) $state['uploaded_at'] : null,
'uploaded_by' => (string) ($state['uploaded_by'] ?? ''),
'tested_at' => isset($state['tested_at']) ? (int) $state['tested_at'] : null,
'result' => (string) ($state['result'] ?? 'none'),
'detail' => (string) ($state['detail'] ?? ''),
];
} catch (RuntimeException $e) {
// Ein Bot ohne das Update haelt "cookies" fuer eine Server-ID (422) oder kennt den Pfad nicht (404/405)
$row['error'] = preg_match('/Status (404|405|422)\.$/', $e->getMessage())
? $name . ' kennt die YouTube-Anmeldung noch nicht (Bot-Update fehlt).'
: $e->getMessage();
}
$rows[] = $row;
}
return $rows;
}
/** Zustand der Musik eines Bots auf dem Legions-Server (Kanal, Titel, Warteschlange, Verlauf, Playlist). */
function music_state(string $bot): array
{
return (array) (music_api_request($bot, 'GET', '/music/' . events_guild_id())['music'] ?? []);
}