coryd.dev/api/playing.php

82 lines
1.9 KiB
PHP

<?php
namespace App\Handlers;
require __DIR__ . "/Classes/BaseHandler.php";
use App\Classes\BaseHandler;
class LatestListenHandler extends BaseHandler
{
protected int $cacheTTL = 60;
public function __construct()
{
parent::__construct();
$this->initializeCache();
}
public function handleRequest(): void
{
try {
$cachedData = $this->cache ? $this->cache->get("latest_listen") : null;
if ($cachedData) {
$this->sendResponse(json_decode($cachedData, true));
return;
}
$data = $this->makeRequest("GET", "optimized_latest_listen?select=*");
if (!is_array($data) || empty($data[0])) {
$this->sendResponse(["message" => "No recent tracks found"], 404);
return;
}
$latestListen = $this->formatLatestListen($data[0]);
if ($this->cache) $this->cache->set(
"latest_listen",
json_encode($latestListen),
$this->cacheTTL
);
$this->sendResponse($latestListen);
} catch (Exception $e) {
error_log("LatestListenHandler Error: " . $e->getMessage());
$this->sendErrorResponse(
"Internal Server Error: " . $e->getMessage(),
500
);
}
}
private function formatLatestListen(array $latestListen): array
{
$emoji =
$latestListen["artist_emoji"] ?? ($latestListen["genre_emoji"] ?? "🎧");
$trackName = htmlspecialchars(
$latestListen["track_name"] ?? "Unknown Track",
ENT_QUOTES,
"UTF-8"
);
$artistName = htmlspecialchars(
$latestListen["artist_name"] ?? "Unknown Artist",
ENT_QUOTES,
"UTF-8"
);
$url = htmlspecialchars($latestListen["url"] ?? "/", ENT_QUOTES, "UTF-8");
return [
"content" => sprintf(
'%s %s by <a href="https://www.coryd.dev%s">%s</a>',
$emoji,
$trackName,
$url,
$artistName
),
];
}
}
$handler = new LatestListenHandler();
$handler->handleRequest();