aboutsummaryrefslogtreecommitdiffstats
path: root/api/nowplaying.php
blob: 1faf01683d2244ef8901a772625a91353814e08e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
require_once __DIR__ . '/../partials/proxy_helpers.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: public, max-age=10');

$cacheFile = sys_get_temp_dir() . '/sillylaird_nowplaying.json';
$ttl       = 10;

if (is_file($cacheFile) && (time() - filemtime($cacheFile)) < $ttl) {
    readfile($cacheFile);
    exit;
}

if (!proxy_rate_limit('nowplaying', 30, 60)) {
    http_response_code(429);
    echo json_encode(['error' => 'rate limited']);
    exit;
}

$ctx = stream_context_create(['http' => [
    'timeout' => 4,
    'header'  => "User-Agent: sillylaird-nowplaying/1.0\r\n",
]]);

$raw = @file_get_contents('https://radio.sillylaird.ca/status-json.xsl', false, $ctx);
if ($raw === false) {
    if (is_file($cacheFile)) { readfile($cacheFile); exit; }
    http_response_code(502);
    echo json_encode(['error' => 'upstream']);
    exit;
}

$data = json_decode($raw, true);
$src  = $data['icestats']['source'] ?? null;
if (is_array($src) && isset($src[0])) $src = $src[0];

$out = json_encode([
    'title'   => $src['title'] ?? ($src['yp_currently_playing'] ?? null),
    'name'    => $src['server_name'] ?? null,
    'online'  => isset($src['title']) || isset($src['yp_currently_playing']),
    'fetched' => time(),
]);

@file_put_contents($cacheFile . '.tmp', $out, LOCK_EX);
@rename($cacheFile . '.tmp', $cacheFile);
echo $out;