Files
radio-free-elsewhere/includes/icecast.php
T
2026-10-30 08:37:10 -05:00

63 lines
2.4 KiB
PHP

<?php
// Shared Icecast helpers: fetching and parsing the current track, album art and Last.fm links.
if (basename($_SERVER['SCRIPT_FILENAME'] ?? '') === basename(__FILE__)) {
http_response_code(403);
exit;
}
const ICECAST_STATUS_URL = 'https://radio.cyberpunklibrarian.nohost.me/status-json.xsl';
// Undo double-encoding: strip the outer UTF-8 layer to recover the original correct UTF-8 byte sequence
function decodeMetaField(array $stream, string $key): string {
if (!isset($stream[$key]) || $stream[$key] === '') return '';
return mb_convert_encoding($stream[$key], 'ISO-8859-1', 'UTF-8');
}
function httpGet(string $url) {
$context = stream_context_create(['http' => ['timeout' => 10]]);
return @file_get_contents($url, false, $context);
}
// Returns ['title', 'artist', 'album'] while streaming, null when offline,
// or false when the status API could not be reached.
function fetchCurrentTrack() {
$response = httpGet(ICECAST_STATUS_URL);
if ($response === false) return false;
$data = json_decode($response, true);
if (!isset($data['icestats']['source'])) return null;
$source = $data['icestats']['source'];
$currentStream = (!is_array($source) || isset($source['title'])) ? $source : $source[0];
$raw = decodeMetaField($currentStream, 'title');
$parts = array_map('trim', explode(' - ', $raw, 3));
return [
'title' => $parts[0] ?? '',
'artist' => $parts[1] ?? '',
'album' => $parts[2] ?? '',
];
}
// Look up album art from iTunes Search API
function lookupAlbumArt(string $artist, string $album): string {
if ($artist === '' || $album === '') return '';
$query = urlencode($artist . ' ' . $album);
$itunesResponse = httpGet("https://itunes.apple.com/search?term={$query}&entity=album&media=music&limit=1");
if ($itunesResponse === false) return '';
$itunesData = json_decode($itunesResponse, true);
if (empty($itunesData['results'][0]['artworkUrl100'])) return '';
return str_replace('100x100bb', '400x400bb', $itunesData['results'][0]['artworkUrl100']);
}
function lastfmTrackUrl(string $artist, string $title): string {
return 'https://www.last.fm/music/' . rawurlencode($artist) . '/_/' . rawurlencode($title);
}
function lastfmAlbumUrl(string $artist, string $album): string {
return 'https://www.last.fm/music/' . rawurlencode($artist) . '/' . rawurlencode($album);
}