feat(*.php): refactor, clean up and abstract dynamic page code

This commit is contained in:
Cory Dransfeldt 2025-05-14 17:22:35 -07:00
parent 2f9038dccb
commit 60be0ed01d
No known key found for this signature in database
30 changed files with 318 additions and 401 deletions

View file

@ -1,84 +1,35 @@
<?php
require __DIR__ . "/../../vendor/autoload.php";
require __DIR__ . "/../../server/utils/init.php";
use GuzzleHttp\Client;
use App\Classes\ArtistFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
$postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL");
$postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY");
if (strpos($url, "music/artists/") !== 0) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$cacheKey = "artist_" . md5($url);
$artist = null;
$useRedis = false;
$fetcher = new ArtistFetcher();
$artist = $fetcher->fetch($url);
try {
if (extension_loaded('redis')) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$useRedis = true;
}
} catch (Exception $e) {
error_log("Redis not available: " . $e->getMessage());
}
if ($useRedis && $redis->exists($cacheKey)) {
$artist = json_decode($redis->get($cacheKey), true);
} else {
$apiUrl = "$postgrestUrl/optimized_artists?url=eq./" . $url;
$client = new Client();
try {
$response = $client->request("GET", $apiUrl, [
"headers" => [
"Accept" => "application/json",
"Authorization" => "Bearer {$postgrestApiKey}",
],
]);
$artistData = json_decode($response->getBody(), true);
if (!$artistData) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$artist = $artistData[0];
if ($useRedis) {
$redis->setex($cacheKey, 3600, json_encode($artist));
}
} catch (Exception $e) {
error_log($e->getMessage());
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
if (!$artist) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$artist["description"] = parseMarkdown($artist["description"]);
$pageTitle = htmlspecialchars(
"Artists • " . $artist["name"],
ENT_QUOTES,
"UTF-8"
);
$pageDescription = truncateText(htmlspecialchars(
strip_tags($artist["description"]),
ENT_QUOTES,
"UTF-8"
), 250);
$pageTitle = htmlspecialchars("Artists • " . $artist["name"], ENT_QUOTES, "UTF-8");
$pageDescription = truncateText(htmlspecialchars(strip_tags($artist["description"]), ENT_QUOTES, "UTF-8"), 250);
$ogImage = htmlspecialchars($artist["image"], ENT_QUOTES, "UTF-8");
$fullUrl = "https://www.coryd.dev" . $requestUri;
$oembedUrl = "https://www.coryd.dev/oembed" . $requestUri;
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
?>

View file

@ -1,14 +1,13 @@
<?php
require __DIR__ . "/../vendor/autoload.php";
require __DIR__ . "/../server/utils/init.php";
use GuzzleHttp\Client;
use App\Classes\BookFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
$postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL");
$postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY");
if (preg_match('/^books\/years\/(\d{4})$/', $url, $matches)) {
$year = $matches[1];
@ -23,13 +22,9 @@
}
}
if ($url === "books/years") {
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
if ($url === "books") {
readfile("index.html");
if ($url === "books/years" || $url === "books") {
$indexPath = $url === "books" ? "index.html" : __DIR__ . "/../404/index.html";
readfile($indexPath);
exit();
}
@ -38,70 +33,22 @@
exit();
}
$cacheKey = "book_" . md5($url);
$fetcher = new BookFetcher();
$book = $fetcher->fetch($url);
$book = null;
$useRedis = false;
try {
if (extension_loaded('redis')) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$useRedis = true;
}
} catch (Exception $e) {
error_log("Redis not available: " . $e->getMessage());
}
if ($useRedis && $redis->exists($cacheKey)) {
$book = json_decode($redis->get($cacheKey), true);
} else {
$apiUrl = "$postgrestUrl/optimized_books?url=eq./" . $url;
$client = new Client();
try {
$response = $client->request("GET", $apiUrl, [
"headers" => [
"Accept" => "application/json",
"Authorization" => "Bearer {$postgrestApiKey}",
],
]);
$bookData = json_decode($response->getBody(), true);
if (!$bookData) {
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
$book = $bookData[0];
if ($useRedis) {
$redis->setex($cacheKey, 3600, json_encode($book));
}
} catch (Exception $e) {
error_log($e->getMessage());
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
if (!$book) {
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
$book["description"] = parseMarkdown($book["description"]);
$pageTitle = htmlspecialchars(
"Books • " . $book["title"] . " by " . $book["author"],
ENT_QUOTES,
"UTF-8"
);
$pageDescription = truncateText(htmlspecialchars(
strip_tags($book["description"]),
ENT_QUOTES,
"UTF-8"
), 250);
$pageTitle = htmlspecialchars("Books • {$book["title"]} by {$book["author"]}", ENT_QUOTES, "UTF-8");
$pageDescription = truncateText(htmlspecialchars(strip_tags($book["description"]), ENT_QUOTES, "UTF-8"), 250);
$ogImage = htmlspecialchars($book["image"], ENT_QUOTES, "UTF-8");
$fullUrl = "https://www.coryd.dev" . $requestUri;
$oembedUrl = "https://www.coryd.dev/oembed" . $requestUri;
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
?>

View file

@ -1,75 +1,37 @@
<?php
require __DIR__ . "/../../vendor/autoload.php";
require __DIR__ . "/../../server/utils/init.php";
use GuzzleHttp\Client;
use App\Classes\GenreFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
$postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL");
$postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY");
if (!preg_match('/^music\/genres\/[\w-]+$/', $url)) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$cacheKey = "genre_" . md5($url);
$genre = null;
$useRedis = false;
$fetcher = new GenreFetcher();
$genre = $fetcher->fetch($url);
try {
if (extension_loaded('redis')) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$useRedis = true;
}
} catch (Exception $e) {
error_log("Redis not available: " . $e->getMessage());
}
if ($useRedis && $redis->exists($cacheKey)) {
$genre = json_decode($redis->get($cacheKey), true);
} else {
$apiUrl = "$postgrestUrl/optimized_genres?url=eq./" . $url;
$client = new Client();
try {
$response = $client->request("GET", $apiUrl, [
"headers" => [
"Accept" => "application/json",
"Authorization" => "Bearer {$postgrestApiKey}",
],
]);
$genreData = json_decode($response->getBody(), true);
if (!$genreData) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$genre = $genreData[0];
if ($useRedis) {
$redis->setex($cacheKey, 3600, json_encode($genre));
}
} catch (Exception $e) {
error_log($e->getMessage());
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
if (!$genre) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$pageTitle = htmlspecialchars("Genres • " . $genre["name"], ENT_QUOTES, "UTF-8");
$pageDescription = truncateText(htmlspecialchars(strip_tags($genre["description"]), ENT_QUOTES, "UTF-8"), 250);
$ogImage = htmlspecialchars($genre["artists"][0]["image"], ENT_QUOTES, "UTF-8");
$pageDescription = truncateText(
htmlspecialchars(strip_tags($genre["description"]), ENT_QUOTES, "UTF-8"),
250
);
$ogImage = htmlspecialchars($genre["artists"][0]["image"] ?? "", ENT_QUOTES, "UTF-8");
$fullUrl = "https://www.coryd.dev" . $requestUri;
$oembedUrl = "https://www.coryd.dev/oembed" . $requestUri;
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
?>

View file

@ -1,84 +1,35 @@
<?php
require __DIR__ . "/../../vendor/autoload.php";
require __DIR__ . "/../../server/utils/init.php";
use GuzzleHttp\Client;
use App\Classes\MovieFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
$postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL");
$postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY");
if (!preg_match('/^watching\/movies\/[\w-]+$/', $url)) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$cacheKey = "movie_" . md5($url);
$movie = null;
$useRedis = false;
$fetcher = new MovieFetcher();
$movie = $fetcher->fetch($url);
try {
if (extension_loaded('redis')) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$useRedis = true;
}
} catch (Exception $e) {
error_log("Redis not available: " . $e->getMessage());
}
if ($useRedis && $redis->exists($cacheKey)) {
$movie = json_decode($redis->get($cacheKey), true);
} else {
$apiUrl = "$postgrestUrl/optimized_movies?url=eq./" . $url;
$client = new Client();
try {
$response = $client->request("GET", $apiUrl, [
"headers" => [
"Accept" => "application/json",
"Authorization" => "Bearer {$postgrestApiKey}",
],
]);
$movieData = json_decode($response->getBody(), true);
if (!$movieData) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$movie = $movieData[0];
if ($useRedis) {
$redis->setex($cacheKey, 3600, json_encode($movie));
}
} catch (Exception $e) {
error_log($e->getMessage());
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
if (!$movie) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$movie["description"] = parseMarkdown($movie["description"]);
$pageTitle = htmlspecialchars(
"Movies • " . $movie["title"],
ENT_QUOTES,
"UTF-8"
);
$pageDescription = truncateText(htmlspecialchars(
strip_tags($movie["description"]),
ENT_QUOTES,
"UTF-8"
), 250);
$pageTitle = htmlspecialchars("Movies • " . $movie["title"], ENT_QUOTES, "UTF-8");
$pageDescription = truncateText(htmlspecialchars(strip_tags($movie["description"]), ENT_QUOTES, "UTF-8"), 250);
$ogImage = htmlspecialchars($movie["backdrop"], ENT_QUOTES, "UTF-8");
$fullUrl = "https://www.coryd.dev" . $requestUri;
$oembedUrl = "https://www.coryd.dev/oembed" . $requestUri;
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
?>

View file

@ -1,75 +1,37 @@
<?php
require __DIR__ . "/../../vendor/autoload.php";
require __DIR__ . "/../../server/utils/init.php";
use GuzzleHttp\Client;
use App\Classes\ShowFetcher;
use voku\helper\HtmlMin;
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
$postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL");
$postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY");
if (!preg_match('/^watching\/shows\/[\w-]+$/', $url)) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$cacheKey = "show_" . md5($url);
$show = null;
$useRedis = false;
$fetcher = new ShowFetcher();
$show = $fetcher->fetch($url);
try {
if (extension_loaded('redis')) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$useRedis = true;
}
} catch (Exception $e) {
error_log("Redis not available: " . $e->getMessage());
}
if ($useRedis && $redis->exists($cacheKey)) {
$show = json_decode($redis->get($cacheKey), true);
} else {
$apiUrl = "$postgrestUrl/optimized_shows?url=eq./" . $url;
$client = new Client();
try {
$response = $client->request("GET", $apiUrl, [
"headers" => [
"Accept" => "application/json",
"Authorization" => "Bearer {$postgrestApiKey}",
],
]);
$showData = json_decode($response->getBody(), true);
if (!$showData) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$show = $showData[0];
if ($useRedis) {
$redis->setex($cacheKey, 3600, json_encode($show));
}
} catch (Exception $e) {
error_log($e->getMessage());
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
if (!$show) {
echo file_get_contents(__DIR__ . "/../../404/index.html");
exit();
}
$pageTitle = htmlspecialchars("Show • " . $show["title"], ENT_QUOTES, "UTF-8");
$pageDescription = truncateText(htmlspecialchars(strip_tags($show["description"]), ENT_QUOTES, "UTF-8"), 250);
$pageDescription = truncateText(
htmlspecialchars(strip_tags($show["description"]), ENT_QUOTES, "UTF-8"),
250
);
$ogImage = htmlspecialchars($show["image"], ENT_QUOTES, "UTF-8");
$fullUrl = "https://www.coryd.dev" . $requestUri;
$oembedUrl = "https://www.coryd.dev/oembed" . $requestUri;
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
?>

View file

@ -1,109 +1,64 @@
<?php
require __DIR__ . "/../vendor/autoload.php";
require __DIR__ . "/../server/utils/init.php";
use GuzzleHttp\Client;
use voku\helper\HtmlMin;
require __DIR__ . "/../vendor/autoload.php";
require __DIR__ . "/../server/utils/init.php";
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
$postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL");
$postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY");
use App\Classes\TagFetcher;
use voku\helper\HtmlMin;
if ($url === "tags") {
readfile("index.html");
exit();
}
$requestUri = $_SERVER["REQUEST_URI"];
$url = trim(parse_url($requestUri, PHP_URL_PATH), "/");
if (!preg_match('/^tags\/(.+?)(?:\/(\d+))?$/', $url, $matches)) {
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
if (isset($matches[2]) && (int)$matches[2] === 1) {
header("Location: /tags/{$matches[1]}", true, 301);
exit();
}
$tag = strtolower(urldecode($matches[1]));
if (!preg_match('/^[\p{L}\p{N} _\.\-\&]+$/u', $tag)) {
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
$pageParam = isset($matches[2]) ? (int)$matches[2] : 0;
$page = max($pageParam, 1);
$pageSize = 20;
$offset = ($page - 1) * $pageSize;
$cacheKey = "tag_{$tag}_{$page}";
$useRedis = false;
$tagged = null;
try {
if (extension_loaded('redis')) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$useRedis = true;
if ($url === "tags") {
readfile("index.html");
exit();
}
} catch (Exception $e) {
error_log("Redis not available: " . $e->getMessage());
}
if ($useRedis && $redis->exists($cacheKey)) {
$tagged = json_decode($redis->get($cacheKey), true);
} else {
$client = new Client();
try {
$response = $client->post($postgrestUrl . '/rpc/get_tagged_content', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => "Bearer {$postgrestApiKey}",
],
'json' => [
'tag_query' => $tag,
'page_size' => $pageSize,
'page_offset' => $offset
]
]);
if (!preg_match('/^tags\/(.+?)(?:\/(\d+))?$/', $url, $matches)) {
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
$tagged = json_decode($response->getBody(), true);
if ($useRedis) {
$redis->setex($cacheKey, 3600, json_encode($tagged));
}
} catch (Exception $e) {
error_log($e->getMessage());
if (isset($matches[2]) && (int)$matches[2] === 1) {
header("Location: /tags/{$matches[1]}", true, 301);
exit();
}
$tag = strtolower(urldecode($matches[1]));
if (!preg_match('/^[\p{L}\p{N} _\.\-\&]+$/u', $tag)) {
echo file_get_contents(__DIR__ . "/../404/index.html");
exit();
}
$page = isset($matches[2]) ? max(1, (int)$matches[2]) : 1;
$pageSize = 20;
$fetcher = new TagFetcher();
$tagged = $fetcher->fetch($tag, $page, $pageSize);
if (!$tagged || count($tagged) === 0) {
echo file_get_contents(__DIR__ . '/../404/index.html');
exit();
}
}
if (!$tagged || count($tagged) === 0) {
echo file_get_contents(__DIR__ . '/../404/index.html');
exit();
}
$totalCount = $tagged[0]['total_count'] ?? 0;
$totalPages = max(ceil($totalCount / $pageSize), 1);
$pagination = [
'pageNumber' => $page,
'pages' => range(1, $totalPages),
'href' => [
'previous' => $page > 1 ? "/tags/{$tag}/" . ($page - 1) : null,
'next' => $page < $totalPages ? "/tags/{$tag}/" . ($page + 1) : null
],
'links' => range(1, $totalPages)
];
$totalCount = $tagged[0]['total_count'] ?? 0;
$totalPages = max(ceil($totalCount / $pageSize), 1);
$pagination = [
'pageNumber' => $page,
'pages' => range(1, $totalPages),
'href' => [
'previous' => $page > 1 ? "/tags/{$tag}/" . ($page - 1) : null,
'next' => $page < $totalPages ? "/tags/{$tag}/" . ($page + 1) : null
],
'links' => range(1, $totalPages)
];
$pageTitle = "#" . strtolower(ucfirst($tag)) . "";
$pageDescription = "All content tagged with #" . strtolower(ucfirst($tag)) . ".";
$fullUrl = "https://www.coryd.dev" . $requestUri;
$oembedUrl = "https://www.coryd.dev/oembed" . $requestUri;
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
$pageTitle = "#" . strtolower(ucfirst($tag));
$pageDescription = "All content tagged with #" . strtolower(ucfirst($tag)) . ".";
$fullUrl = "https://www.coryd.dev" . $requestUri;
$oembedUrl = "https://www.coryd.dev/oembed" . $requestUri;
ob_start();
header("Cache-Control: public, max-age=3600");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
?>

View file

@ -28,7 +28,7 @@
eleventy:eleventy
%}
<script defer src="/assets/scripts/index.js?v={% appVersion %}"></script>
<script defer src="https://stats.apps.coryd.dev/script.js?v={% appVersion %}" data-website-id="a30f4735-6c27-4761-b180-a8f247a4a3a3"></script>
<script defer src="/assets/scripts/util.js?v={% appVersion %}" data-host-url="https://stats.apps.coryd.dev" data-website-id="a30f4735-6c27-4761-b180-a8f247a4a3a3"></script>
</head>
<body>
<div class="main-wrapper">

View file

@ -59,6 +59,9 @@ RewriteRule ^og/([a-z0-9\-]+)/([\d\.]+)/([a-f0-9\-]+)\.([a-z0-9]+)$ /api/og-imag
RewriteRule ^oembed/?$ /api/oembed.php [L]
RewriteRule ^oembed/(.+)$ /api/oembed.php?url=https://www.coryd.dev/$1 [L,QSA]
## analytics
RewriteRule ^assets/scripts/util\.js$ /api/umami.php [L]
{% for redirect in redirects -%}
Redirect {{ redirect.status_code | default: "301" }} {{ redirect.source_url }} {{ redirect.destination_url }}
{% endfor -%}