38428-vm/api/current_song.php
2026-02-25 20:09:50 +00:00

89 lines
3.4 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
try {
$db = db();
// Check for a local "played" song that is currently within its duration
$stmt = $db->query("SELECT artist, song, requester, youtube_url, duration, UNIX_TIMESTAMP(created_at) as started_at FROM song_requests WHERE status = 'played' ORDER BY created_at DESC LIMIT 1");
$override = $stmt->fetch();
if ($override) {
$duration = (int)($override['duration'] ?? 240);
$startedAt = $override['started_at'];
$endAt = $startedAt + $duration;
$remaining = $endAt - time();
if ($remaining > 0) {
// Find next track for local requests
$stmtNext = $db->query("SELECT artist, song FROM song_requests WHERE status = 'pending' ORDER BY is_priority DESC, created_at ASC LIMIT 1");
$nextTrack = $stmtNext->fetch();
$nextInfo = null;
if ($nextTrack) {
$nextInfo = ['artist' => $nextTrack['artist'], 'title' => $nextTrack['song']];
}
echo json_encode([
'success' => true,
'source' => 'local_request',
'artist' => $override['artist'],
'title' => $override['song'],
'requester' => $override['requester'],
'youtube_url' => $override['youtube_url'],
'duration' => $duration,
'started_at' => date('c', $startedAt),
'end_at' => date('c', $endAt),
'remaining' => $remaining,
'next_track' => $nextInfo,
'cover' => './assets/pasted-20260215-163754-def41f49.png'
]);
exit;
}
}
// Fallback: Proxy RadioKing metadata
$radioKingUrl = 'https://www.radioking.com/widgets/api/v1/radio/828046/track/current';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $radioKingUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$resp = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $resp) {
$data = json_decode($resp, true);
$duration = $data['duration'] ?? 0;
$endAt = $data['end_at'] ?? null;
$startedAt = null;
if ($endAt && $duration) {
$startedAt = date('c', strtotime($endAt) - $duration);
}
// For RadioKing source, check if there's a pending local request (it will be next)
$nextInfo = $data['next_track'] ?? null;
$stmtNext = $db->query("SELECT artist, song FROM song_requests WHERE status = 'pending' ORDER BY is_priority DESC, created_at ASC LIMIT 1");
$localNext = $stmtNext->fetch();
if ($localNext) {
$nextInfo = ['artist' => $localNext['artist'], 'title' => $localNext['song']];
}
echo json_encode([
'success' => true,
'source' => 'radioking',
'artist' => $data['artist'] ?? 'Lili Records',
'title' => $data['title'] ?? 'La mejor música',
'cover' => $data['cover'] ?? './assets/pasted-20260215-163754-def41f49.png',
'duration' => $duration,
'started_at' => $startedAt,
'end_at' => $endAt,
'next_track' => $nextInfo
]);
}
} catch (Exception $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}