chore(*.php): use pint for php formatting

This commit is contained in:
Cory Dransfeldt 2025-06-14 16:55:03 -07:00
parent bd1855a65e
commit 753f3433ce
No known key found for this signature in database
40 changed files with 2261 additions and 1900 deletions

View file

@ -13,3 +13,6 @@ vendor/
# env # env
.env .env
# php
*.php

View file

@ -8,8 +8,11 @@ use GuzzleHttp\Client;
class ArtistImportHandler extends ApiHandler class ArtistImportHandler extends ApiHandler
{ {
private string $artistImportToken; private string $artistImportToken;
private string $placeholderImageId = "4cef75db-831f-4f5d-9333-79eaa5bb55ee";
private string $placeholderImageId = '4cef75db-831f-4f5d-9333-79eaa5bb55ee';
private string $navidromeApiUrl; private string $navidromeApiUrl;
private string $navidromeAuthToken; private string $navidromeAuthToken;
public function __construct() public function __construct()
@ -17,41 +20,49 @@ class ArtistImportHandler extends ApiHandler
parent::__construct(); parent::__construct();
$this->ensureCliAccess(); $this->ensureCliAccess();
$this->artistImportToken = getenv("ARTIST_IMPORT_TOKEN"); $this->artistImportToken = getenv('ARTIST_IMPORT_TOKEN');
$this->navidromeApiUrl = getenv("NAVIDROME_API_URL"); $this->navidromeApiUrl = getenv('NAVIDROME_API_URL');
$this->navidromeAuthToken = getenv("NAVIDROME_API_TOKEN"); $this->navidromeAuthToken = getenv('NAVIDROME_API_TOKEN');
} }
public function handleRequest(): void public function handleRequest(): void
{ {
$input = json_decode(file_get_contents("php://input"), true); $input = json_decode(file_get_contents('php://input'), true);
if (!$input) $this->sendJsonResponse("error", "Invalid or missing JSON body", 400); if (! $input) {
$this->sendJsonResponse('error', 'Invalid or missing JSON body', 400);
}
$providedToken = $input["token"] ?? null; $providedToken = $input['token'] ?? null;
$artistId = $input["artistId"] ?? null; $artistId = $input['artistId'] ?? null;
if ($providedToken !== $this->artistImportToken) $this->sendJsonResponse("error", "Unauthorized access", 401); if ($providedToken !== $this->artistImportToken) {
if (!$artistId) $this->sendJsonResponse("error", "Artist ID is required", 400); $this->sendJsonResponse('error', 'Unauthorized access', 401);
}
if (! $artistId) {
$this->sendJsonResponse('error', 'Artist ID is required', 400);
}
try { try {
$artistData = $this->fetchNavidromeArtist($artistId); $artistData = $this->fetchNavidromeArtist($artistId);
$albumData = $this->fetchNavidromeAlbums($artistId); $albumData = $this->fetchNavidromeAlbums($artistId);
$genre = $albumData[0]["genre"] ?? ($albumData[0]["genres"][0]["name"] ?? ""); $genre = $albumData[0]['genre'] ?? ($albumData[0]['genres'][0]['name'] ?? '');
$artistExists = $this->processArtist($artistData, $genre); $artistExists = $this->processArtist($artistData, $genre);
if ($artistExists) $this->processAlbums($artistId, $artistData->name, $albumData); if ($artistExists) {
$this->processAlbums($artistId, $artistData->name, $albumData);
}
$this->sendJsonResponse("message", "Artist and albums synced successfully", 200); $this->sendJsonResponse('message', 'Artist and albums synced successfully', 200);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->sendJsonResponse("error", "Error: " . $e->getMessage(), 500); $this->sendJsonResponse('error', 'Error: '.$e->getMessage(), 500);
} }
} }
private function sendJsonResponse(string $key, string $message, int $statusCode): void private function sendJsonResponse(string $key, string $message, int $statusCode): void
{ {
http_response_code($statusCode); http_response_code($statusCode);
header("Content-Type: application/json"); header('Content-Type: application/json');
echo json_encode([$key => $message]); echo json_encode([$key => $message]);
@ -62,10 +73,10 @@ class ArtistImportHandler extends ApiHandler
{ {
$client = new Client(); $client = new Client();
$response = $client->get("{$this->navidromeApiUrl}/api/artist/{$artistId}", [ $response = $client->get("{$this->navidromeApiUrl}/api/artist/{$artistId}", [
"headers" => [ 'headers' => [
"x-nd-authorization" => "Bearer {$this->navidromeAuthToken}", 'x-nd-authorization' => "Bearer {$this->navidromeAuthToken}",
"Accept" => "application/json" 'Accept' => 'application/json',
] ],
]); ]);
return json_decode($response->getBody()); return json_decode($response->getBody());
@ -75,49 +86,53 @@ class ArtistImportHandler extends ApiHandler
{ {
$client = new Client(); $client = new Client();
$response = $client->get("{$this->navidromeApiUrl}/api/album", [ $response = $client->get("{$this->navidromeApiUrl}/api/album", [
"query" => [ 'query' => [
"_end" => 0, '_end' => 0,
"_order" => "ASC", '_order' => 'ASC',
"_sort" => "max_year", '_sort' => 'max_year',
"_start" => 0, '_start' => 0,
"artist_id" => $artistId 'artist_id' => $artistId,
],
'headers' => [
'x-nd-authorization' => "Bearer {$this->navidromeAuthToken}",
'Accept' => 'application/json',
], ],
"headers" => [
"x-nd-authorization" => "Bearer {$this->navidromeAuthToken}",
"Accept" => "application/json"
]
]); ]);
return json_decode($response->getBody(), true); return json_decode($response->getBody(), true);
} }
private function processArtist(object $artistData, string $genreName = ""): bool private function processArtist(object $artistData, string $genreName = ''): bool
{ {
$artistName = $artistData->name ?? ""; $artistName = $artistData->name ?? '';
if (!$artistName) throw new \Exception("Artist name is missing."); if (! $artistName) {
throw new \Exception('Artist name is missing.');
}
$existingArtist = $this->getArtistByName($artistName); $existingArtist = $this->getArtistByName($artistName);
if ($existingArtist) return true; if ($existingArtist) {
return true;
}
$artistKey = sanitizeMediaString($artistName); $artistKey = sanitizeMediaString($artistName);
$slug = "/music/artists/{$artistKey}"; $slug = "/music/artists/{$artistKey}";
$description = strip_tags($artistData->biography ?? ""); $description = strip_tags($artistData->biography ?? '');
$genre = $this->resolveGenreId(strtolower($genreName)); $genre = $this->resolveGenreId(strtolower($genreName));
$starred = $artistData->starred ?? false; $starred = $artistData->starred ?? false;
$artistPayload = [ $artistPayload = [
"name_string" => $artistName, 'name_string' => $artistName,
"slug" => $slug, 'slug' => $slug,
"description" => $description, 'description' => $description,
"tentative" => true, 'tentative' => true,
"art" => $this->placeholderImageId, 'art' => $this->placeholderImageId,
"mbid" => "", 'mbid' => '',
"favorite" => $starred, 'favorite' => $starred,
"genres" => $genre, 'genres' => $genre,
]; ];
$this->makeRequest("POST", "artists", ["json" => $artistPayload]); $this->makeRequest('POST', 'artists', ['json' => $artistPayload]);
return true; return true;
} }
@ -126,38 +141,43 @@ class ArtistImportHandler extends ApiHandler
{ {
$artist = $this->getArtistByName($artistName); $artist = $this->getArtistByName($artistName);
if (!$artist) throw new \Exception("Artist not found after insert."); if (! $artist) {
throw new \Exception('Artist not found after insert.');
}
$existingAlbums = $this->getExistingAlbums($artist["id"]); $existingAlbums = $this->getExistingAlbums($artist['id']);
$existingAlbumKeys = array_column($existingAlbums, "key"); $existingAlbumKeys = array_column($existingAlbums, 'key');
foreach ($albumData as $album) { foreach ($albumData as $album) {
$albumName = $album["name"] ?? ""; $albumName = $album['name'] ?? '';
$releaseYearRaw = $album["date"] ?? null; $releaseYearRaw = $album['date'] ?? null;
$releaseYear = null; $releaseYear = null;
if ($releaseYearRaw && preg_match('/^\d{4}/', $releaseYearRaw, $matches)) $releaseYear = (int)$matches[0]; if ($releaseYearRaw && preg_match('/^\d{4}/', $releaseYearRaw, $matches)) {
$releaseYear = (int) $matches[0];
}
$artistKey = sanitizeMediaString($artistName); $artistKey = sanitizeMediaString($artistName);
$albumKey = "{$artistKey}-".sanitizeMediaString($albumName); $albumKey = "{$artistKey}-".sanitizeMediaString($albumName);
if (in_array($albumKey, $existingAlbumKeys)) { if (in_array($albumKey, $existingAlbumKeys)) {
error_log("Skipping existing album: {$albumName}"); error_log("Skipping existing album: {$albumName}");
continue; continue;
} }
try { try {
$albumPayload = [ $albumPayload = [
"name" => $albumName, 'name' => $albumName,
"key" => $albumKey, 'key' => $albumKey,
"release_year" => $releaseYear, 'release_year' => $releaseYear,
"artist" => $artist["id"], 'artist' => $artist['id'],
"artist_name" => $artistName, 'artist_name' => $artistName,
"art" => $this->placeholderImageId, 'art' => $this->placeholderImageId,
"tentative" => true, 'tentative' => true,
]; ];
$this->makeRequest("POST", "albums", ["json" => $albumPayload]); $this->makeRequest('POST', 'albums', ['json' => $albumPayload]);
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("Error adding album '{$albumName}': ".$e->getMessage()); error_log("Error adding album '{$albumName}': ".$e->getMessage());
} }
@ -166,21 +186,21 @@ class ArtistImportHandler extends ApiHandler
private function getArtistByName(string $nameString): ?array private function getArtistByName(string $nameString): ?array
{ {
$response = $this->fetchFromApi("artists", "name_string=eq." . urlencode($nameString)); $response = $this->fetchFromApi('artists', 'name_string=eq.'.urlencode($nameString));
return $response[0] ?? null; return $response[0] ?? null;
} }
private function getExistingAlbums(string $artistId): array private function getExistingAlbums(string $artistId): array
{ {
return $this->fetchFromApi("albums", "artist=eq." . urlencode($artistId)); return $this->fetchFromApi('albums', 'artist=eq.'.urlencode($artistId));
} }
private function resolveGenreId(string $genreName): ?string private function resolveGenreId(string $genreName): ?string
{ {
$genres = $this->fetchFromApi("genres", "name=eq." . urlencode(strtolower($genreName))); $genres = $this->fetchFromApi('genres', 'name=eq.'.urlencode(strtolower($genreName)));
return $genres[0]["id"] ?? null; return $genres[0]['id'] ?? null;
} }
} }

View file

@ -14,46 +14,54 @@ class BookImportHandler extends ApiHandler
parent::__construct(); parent::__construct();
$this->ensureCliAccess(); $this->ensureCliAccess();
$this->bookImportToken = $_ENV["BOOK_IMPORT_TOKEN"] ?? getenv("BOOK_IMPORT_TOKEN"); $this->bookImportToken = $_ENV['BOOK_IMPORT_TOKEN'] ?? getenv('BOOK_IMPORT_TOKEN');
} }
public function handleRequest(): void public function handleRequest(): void
{ {
$input = json_decode(file_get_contents("php://input"), true); $input = json_decode(file_get_contents('php://input'), true);
if (!$input) $this->sendErrorResponse("Invalid or missing JSON body", 400); if (! $input) {
$this->sendErrorResponse('Invalid or missing JSON body', 400);
}
$providedToken = $input["token"] ?? null; $providedToken = $input['token'] ?? null;
$isbn = $input["isbn"] ?? null; $isbn = $input['isbn'] ?? null;
if ($providedToken !== $this->bookImportToken) $this->sendErrorResponse("Unauthorized access", 401); if ($providedToken !== $this->bookImportToken) {
if (!$isbn) $this->sendErrorResponse("isbn parameter is required", 400); $this->sendErrorResponse('Unauthorized access', 401);
}
if (! $isbn) {
$this->sendErrorResponse('isbn parameter is required', 400);
}
try { try {
$bookData = $this->fetchBookData($isbn); $bookData = $this->fetchBookData($isbn);
$this->processBook($bookData); $this->processBook($bookData);
$this->sendResponse(["message" => "Book imported successfully"], 200); $this->sendResponse(['message' => 'Book imported successfully'], 200);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->sendErrorResponse("Error: " . $e->getMessage(), 500); $this->sendErrorResponse('Error: '.$e->getMessage(), 500);
} }
} }
private function fetchBookData(string $isbn): array private function fetchBookData(string $isbn): array
{ {
$client = new Client(); $client = new Client();
$response = $client->get("https://openlibrary.org/api/books", [ $response = $client->get('https://openlibrary.org/api/books', [
"query" => [ 'query' => [
"bibkeys" => "ISBN:{$isbn}", 'bibkeys' => "ISBN:{$isbn}",
"format" => "json", 'format' => 'json',
"jscmd" => "data", 'jscmd' => 'data',
], ],
"headers" => ["Accept" => "application/json"], 'headers' => ['Accept' => 'application/json'],
]); ]);
$data = json_decode($response->getBody(), true); $data = json_decode($response->getBody(), true);
$bookKey = "ISBN:{$isbn}"; $bookKey = "ISBN:{$isbn}";
if (empty($data[$bookKey])) throw new \Exception("Book data not found for ISBN: {$isbn}"); if (empty($data[$bookKey])) {
throw new \Exception("Book data not found for ISBN: {$isbn}");
}
return $data[$bookKey]; return $data[$bookKey];
} }
@ -61,33 +69,37 @@ class BookImportHandler extends ApiHandler
private function processBook(array $bookData): void private function processBook(array $bookData): void
{ {
$isbn = $isbn =
$bookData["identifiers"]["isbn_13"][0] ?? $bookData['identifiers']['isbn_13'][0] ??
($bookData["identifiers"]["isbn_10"][0] ?? null); ($bookData['identifiers']['isbn_10'][0] ?? null);
$title = $bookData["title"] ?? null; $title = $bookData['title'] ?? null;
$author = $bookData["authors"][0]["name"] ?? null; $author = $bookData['authors'][0]['name'] ?? null;
$description = $bookData["description"] ?? ($bookData["notes"] ?? ""); $description = $bookData['description'] ?? ($bookData['notes'] ?? '');
if (!$isbn || !$title || !$author) throw new \Exception("Missing essential book data (title, author, or ISBN)."); if (! $isbn || ! $title || ! $author) {
throw new \Exception('Missing essential book data (title, author, or ISBN).');
}
$existingBook = $this->getBookByISBN($isbn); $existingBook = $this->getBookByISBN($isbn);
if ($existingBook) throw new \Exception("Book with ISBN {$isbn} already exists."); if ($existingBook) {
throw new \Exception("Book with ISBN {$isbn} already exists.");
}
$bookPayload = [ $bookPayload = [
"isbn" => $isbn, 'isbn' => $isbn,
"title" => $title, 'title' => $title,
"author" => $author, 'author' => $author,
"description" => $description, 'description' => $description,
"read_status" => "want to read", 'read_status' => 'want to read',
"slug" => "/reading/books/" . $isbn, 'slug' => '/reading/books/'.$isbn,
]; ];
$this->makeRequest("POST", "books", ["json" => $bookPayload]); $this->makeRequest('POST', 'books', ['json' => $bookPayload]);
} }
private function getBookByISBN(string $isbn): ?array private function getBookByISBN(string $isbn): ?array
{ {
$response = $this->fetchFromApi("books", "isbn=eq." . urlencode($isbn)); $response = $this->fetchFromApi('books', 'isbn=eq.'.urlencode($isbn));
return $response[0] ?? null; return $response[0] ?? null;
} }

View file

@ -8,8 +8,11 @@ use GuzzleHttp\Client;
class ContactHandler extends BaseHandler class ContactHandler extends BaseHandler
{ {
protected string $postgrestUrl; protected string $postgrestUrl;
protected string $postgrestApiKey; protected string $postgrestApiKey;
private string $forwardEmailApiKey; private string $forwardEmailApiKey;
private Client $httpClient; private Client $httpClient;
public function __construct(?Client $httpClient = null) public function __construct(?Client $httpClient = null)
@ -17,7 +20,7 @@ class ContactHandler extends BaseHandler
parent::__construct(); parent::__construct();
$this->httpClient = $httpClient ?? new Client(); $this->httpClient = $httpClient ?? new Client();
$this->forwardEmailApiKey = $_ENV["FORWARDEMAIL_API_KEY"] ?? getenv("FORWARDEMAIL_API_KEY"); $this->forwardEmailApiKey = $_ENV['FORWARDEMAIL_API_KEY'] ?? getenv('FORWARDEMAIL_API_KEY');
} }
public function handleRequest(): void public function handleRequest(): void
@ -27,57 +30,73 @@ class ContactHandler extends BaseHandler
$this->checkRateLimit(); $this->checkRateLimit();
$this->enforceHttps(); $this->enforceHttps();
$contentType = $_SERVER["CONTENT_TYPE"] ?? ""; $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
$formData = null; $formData = null;
if (strpos($contentType, "application/json") !== false) { if (strpos($contentType, 'application/json') !== false) {
$rawBody = file_get_contents("php://input"); $rawBody = file_get_contents('php://input');
$formData = json_decode($rawBody, true); $formData = json_decode($rawBody, true);
if (!$formData || !isset($formData["data"])) throw new \Exception("Invalid JSON payload."); if (! $formData || ! isset($formData['data'])) {
throw new \Exception('Invalid JSON payload.');
}
$formData = $formData["data"]; $formData = $formData['data'];
} elseif ( } elseif (
strpos($contentType, "application/x-www-form-urlencoded") !== false strpos($contentType, 'application/x-www-form-urlencoded') !== false
) { ) {
$formData = $_POST; $formData = $_POST;
} else { } else {
$this->sendErrorResponse("Unsupported Content-Type. Use application/json or application/x-www-form-urlencoded.", 400); $this->sendErrorResponse('Unsupported Content-Type. Use application/json or application/x-www-form-urlencoded.', 400);
} }
if (!empty($formData["hp_name"])) $this->sendErrorResponse("Invalid submission.", 400); if (! empty($formData['hp_name'])) {
$this->sendErrorResponse('Invalid submission.', 400);
}
$name = htmlspecialchars( $name = htmlspecialchars(
trim($formData["name"] ?? ""), trim($formData['name'] ?? ''),
ENT_QUOTES, ENT_QUOTES,
"UTF-8" 'UTF-8'
); );
$email = filter_var($formData["email"] ?? "", FILTER_VALIDATE_EMAIL); $email = filter_var($formData['email'] ?? '', FILTER_VALIDATE_EMAIL);
$message = htmlspecialchars( $message = htmlspecialchars(
trim($formData["message"] ?? ""), trim($formData['message'] ?? ''),
ENT_QUOTES, ENT_QUOTES,
"UTF-8" 'UTF-8'
); );
if (empty($name)) $this->sendErrorResponse("Name is required.", 400); if (empty($name)) {
if (!$email) $this->sendErrorResponse("Valid email is required.", 400); $this->sendErrorResponse('Name is required.', 400);
if (empty($message)) $this->sendErrorResponse("Message is required.", 400); }
if (strlen($name) > 100) $this->sendErrorResponse("Name is too long. Max 100 characters allowed.", 400); if (! $email) {
if (strlen($message) > 1000) $this->sendErrorResponse("Message is too long. Max 1000 characters allowed.", 400); $this->sendErrorResponse('Valid email is required.', 400);
if ($this->isBlockedDomain($email)) $this->sendErrorResponse("Submission from blocked domain.", 400); }
if (empty($message)) {
$this->sendErrorResponse('Message is required.', 400);
}
if (strlen($name) > 100) {
$this->sendErrorResponse('Name is too long. Max 100 characters allowed.', 400);
}
if (strlen($message) > 1000) {
$this->sendErrorResponse('Message is too long. Max 1000 characters allowed.', 400);
}
if ($this->isBlockedDomain($email)) {
$this->sendErrorResponse('Submission from blocked domain.', 400);
}
$contactData = [ $contactData = [
"name" => $name, 'name' => $name,
"email" => $email, 'email' => $email,
"message" => $message, 'message' => $message,
"replied" => false, 'replied' => false,
]; ];
$this->saveToDatabase($contactData); $this->saveToDatabase($contactData);
$this->sendNotificationEmail($contactData); $this->sendNotificationEmail($contactData);
$this->sendRedirect("/contact/success"); $this->sendRedirect('/contact/success');
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("Error handling contact form submission: " . $e->getMessage()); error_log('Error handling contact form submission: '.$e->getMessage());
$this->sendErrorResponse($e->getMessage(), 400); $this->sendErrorResponse($e->getMessage(), 400);
} }
@ -85,30 +104,32 @@ class ContactHandler extends BaseHandler
private function validateReferer(): void private function validateReferer(): void
{ {
$referer = $_SERVER["HTTP_REFERER"] ?? ""; $referer = $_SERVER['HTTP_REFERER'] ?? '';
$allowedDomain = "coryd.dev"; $allowedDomain = 'coryd.dev';
if (!str_contains($referer, $allowedDomain)) throw new \Exception("Invalid submission origin."); if (! str_contains($referer, $allowedDomain)) {
throw new \Exception('Invalid submission origin.');
}
} }
private function checkRateLimit(): void private function checkRateLimit(): void
{ {
$ipAddress = $_SERVER["REMOTE_ADDR"] ?? "unknown"; $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$cacheFile = sys_get_temp_dir() . "/rate_limit_" . md5($ipAddress); $cacheFile = sys_get_temp_dir().'/rate_limit_'.md5($ipAddress);
$rateLimitDuration = 60; $rateLimitDuration = 60;
$maxRequests = 5; $maxRequests = 5;
if (file_exists($cacheFile)) { if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true); $data = json_decode(file_get_contents($cacheFile), true);
if ($data["timestamp"] + $rateLimitDuration > time() && $data["count"] >= $maxRequests) { if (time() < $data['timestamp'] + $rateLimitDuration && $data['count'] >= $maxRequests) {
header("Location: /429", true, 302); header('Location: /429', true, 302);
exit(); exit();
} }
$data["count"]++; $data['count']++;
} else { } else {
$data = ["count" => 1, "timestamp" => time()]; $data = ['count' => 1, 'timestamp' => time()];
} }
file_put_contents($cacheFile, json_encode($data)); file_put_contents($cacheFile, json_encode($data));
@ -116,25 +137,29 @@ class ContactHandler extends BaseHandler
private function enforceHttps(): void private function enforceHttps(): void
{ {
if (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] !== "on") throw new \Exception("Secure connection required. Use HTTPS."); if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
throw new \Exception('Secure connection required. Use HTTPS.');
}
} }
private function isBlockedDomain(string $email): bool private function isBlockedDomain(string $email): bool
{ {
$domain = substr(strrchr($email, "@"), 1); $domain = substr(strrchr($email, '@'), 1);
if (!$domain) return false; if (! $domain) {
return false;
}
$response = $this->httpClient->get( $response = $this->httpClient->get(
"{$this->postgrestUrl}/blocked_domains", "{$this->postgrestUrl}/blocked_domains",
[ [
"headers" => [ 'headers' => [
"Content-Type" => "application/json", 'Content-Type' => 'application/json',
"Authorization" => "Bearer {$this->postgrestApiKey}", 'Authorization' => "Bearer {$this->postgrestApiKey}",
], ],
"query" => [ 'query' => [
"domain_name" => "eq.{$domain}", 'domain_name' => "eq.{$domain}",
"limit" => 1, 'limit' => 1,
], ],
] ]
); );
@ -146,53 +171,55 @@ class ContactHandler extends BaseHandler
private function saveToDatabase(array $contactData): void private function saveToDatabase(array $contactData): void
{ {
$response = $this->httpClient->post("{$this->postgrestUrl}/contacts", [ $response = $this->httpClient->post("{$this->postgrestUrl}/contacts", [
"headers" => [ 'headers' => [
"Content-Type" => "application/json", 'Content-Type' => 'application/json',
"Authorization" => "Bearer {$this->postgrestApiKey}", 'Authorization' => "Bearer {$this->postgrestApiKey}",
], ],
"json" => $contactData, 'json' => $contactData,
]); ]);
if ($response->getStatusCode() >= 400) { if ($response->getStatusCode() >= 400) {
$errorResponse = json_decode($response->getBody(), true); $errorResponse = json_decode($response->getBody(), true);
throw new \Exception("PostgREST error: " . ($errorResponse["message"] ?? "Unknown error")); throw new \Exception('PostgREST error: '.($errorResponse['message'] ?? 'Unknown error'));
} }
} }
private function sendNotificationEmail(array $contactData): void private function sendNotificationEmail(array $contactData): void
{ {
$authHeader = "Basic " . base64_encode("{$this->forwardEmailApiKey}:"); $authHeader = 'Basic '.base64_encode("{$this->forwardEmailApiKey}:");
$emailSubject = "Contact form submission"; $emailSubject = 'Contact form submission';
$emailText = sprintf( $emailText = sprintf(
"Name: %s\nEmail: %s\nMessage: %s\n", "Name: %s\nEmail: %s\nMessage: %s\n",
$contactData["name"], $contactData['name'],
$contactData["email"], $contactData['email'],
$contactData["message"] $contactData['message']
); );
$response = $this->httpClient->post( $response = $this->httpClient->post(
"https://api.forwardemail.net/v1/emails", 'https://api.forwardemail.net/v1/emails',
[ [
"headers" => [ 'headers' => [
"Content-Type" => "application/x-www-form-urlencoded", 'Content-Type' => 'application/x-www-form-urlencoded',
"Authorization" => $authHeader, 'Authorization' => $authHeader,
], ],
"form_params" => [ 'form_params' => [
"from" => "coryd.dev <hi@admin.coryd.dev>", 'from' => 'coryd.dev <hi@admin.coryd.dev>',
"to" => "hi@coryd.dev", 'to' => 'hi@coryd.dev',
"subject" => $emailSubject, 'subject' => $emailSubject,
"text" => $emailText, 'text' => $emailText,
"replyTo" => $contactData["email"], 'replyTo' => $contactData['email'],
], ],
] ]
); );
if ($response->getStatusCode() >= 400) throw new \Exception("Failed to send email notification."); if ($response->getStatusCode() >= 400) {
throw new \Exception('Failed to send email notification.');
}
} }
private function sendRedirect(string $path): void private function sendRedirect(string $path): void
{ {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http"; $protocol = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST']; $host = $_SERVER['HTTP_HOST'];
$redirectUrl = "{$protocol}://{$host}{$path}"; $redirectUrl = "{$protocol}://{$host}{$path}";
@ -206,9 +233,9 @@ try {
$handler = new ContactHandler(); $handler = new ContactHandler();
$handler->handleRequest(); $handler->handleRequest();
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("Contact form error: " . $e->getMessage()); error_log('Contact form error: '.$e->getMessage());
echo json_encode(["error" => $e->getMessage()]); echo json_encode(['error' => $e->getMessage()]);
http_response_code(500); http_response_code(500);
} }

View file

@ -8,9 +8,13 @@ use GuzzleHttp\Client;
class MastodonPostHandler extends ApiHandler class MastodonPostHandler extends ApiHandler
{ {
private string $mastodonAccessToken; private string $mastodonAccessToken;
private string $rssFeedUrl = "https://www.coryd.dev/feeds/syndication.xml";
private string $baseUrl = "https://www.coryd.dev"; private string $rssFeedUrl = 'https://www.coryd.dev/feeds/syndication.xml';
private const MASTODON_API_STATUS = "https://follow.coryd.dev/api/v1/statuses";
private string $baseUrl = 'https://www.coryd.dev';
private const MASTODON_API_STATUS = 'https://follow.coryd.dev/api/v1/statuses';
private Client $httpClient; private Client $httpClient;
public function __construct(?Client $httpClient = null) public function __construct(?Client $httpClient = null)
@ -18,19 +22,19 @@ class MastodonPostHandler extends ApiHandler
parent::__construct(); parent::__construct();
$this->ensureCliAccess(); $this->ensureCliAccess();
$this->mastodonAccessToken = getenv("MASTODON_ACCESS_TOKEN") ?: $_ENV["MASTODON_ACCESS_TOKEN"] ?? ""; $this->mastodonAccessToken = getenv('MASTODON_ACCESS_TOKEN') ?: $_ENV['MASTODON_ACCESS_TOKEN'] ?? '';
$this->httpClient = $httpClient ?: new Client(); $this->httpClient = $httpClient ?: new Client();
$this->validateAuthorization(); $this->validateAuthorization();
} }
private function validateAuthorization(): void private function validateAuthorization(): void
{ {
$authHeader = $_SERVER["HTTP_AUTHORIZATION"] ?? ""; $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$expectedToken = "Bearer " . getenv("MASTODON_SYNDICATION_TOKEN"); $expectedToken = 'Bearer '.getenv('MASTODON_SYNDICATION_TOKEN');
if ($authHeader !== $expectedToken) { if ($authHeader !== $expectedToken) {
http_response_code(401); http_response_code(401);
echo json_encode(["error" => "Unauthorized"]); echo json_encode(['error' => 'Unauthorized']);
exit(); exit();
} }
} }
@ -39,35 +43,39 @@ class MastodonPostHandler extends ApiHandler
{ {
if (! $this->isDatabaseAvailable()) { if (! $this->isDatabaseAvailable()) {
echo "Database is unavailable. Exiting.\n"; echo "Database is unavailable. Exiting.\n";
return; return;
} }
$latestItems = $this->fetchRSSFeed($this->rssFeedUrl); $latestItems = $this->fetchRSSFeed($this->rssFeedUrl);
foreach (array_reverse($latestItems) as $item) { foreach (array_reverse($latestItems) as $item) {
$existing = $this->fetchFromApi("mastodon_posts", "link=eq." . urlencode($item["link"])); $existing = $this->fetchFromApi('mastodon_posts', 'link=eq.'.urlencode($item['link']));
if (!empty($existing)) continue; if (! empty($existing)) {
$content = $this->truncateContent(
$item["title"],
strip_tags($item["description"]),
$item["link"],
500
);
$timestamp = date("Y-m-d H:i:s");
if (!$this->storeInDatabase($item["link"], $timestamp)) {
echo "Skipping post: database write failed for {$item["link"]}\n";
continue; continue;
} }
$postedUrl = $this->postToMastodon($content, $item["image"] ?? null); $content = $this->truncateContent(
$item['title'],
strip_tags($item['description']),
$item['link'],
500
);
$timestamp = date('Y-m-d H:i:s');
if (! $this->storeInDatabase($item['link'], $timestamp)) {
echo "Skipping post: database write failed for {$item['link']}\n";
continue;
}
$postedUrl = $this->postToMastodon($content, $item['image'] ?? null);
if ($postedUrl) { if ($postedUrl) {
echo "Posted: {$postedUrl}\n"; echo "Posted: {$postedUrl}\n";
} else { } else {
echo "Failed to post to Mastodon for: {$item["link"]}\n"; echo "Failed to post to Mastodon for: {$item['link']}\n";
} }
} }
@ -78,16 +86,18 @@ class MastodonPostHandler extends ApiHandler
{ {
$rssText = file_get_contents($rssFeedUrl); $rssText = file_get_contents($rssFeedUrl);
if (!$rssText) throw new \Exception("Failed to fetch RSS feed."); if (! $rssText) {
throw new \Exception('Failed to fetch RSS feed.');
}
$rss = new \SimpleXMLElement($rssText); $rss = new \SimpleXMLElement($rssText);
$items = []; $items = [];
foreach ($rss->channel->item as $item) { foreach ($rss->channel->item as $item) {
$items[] = [ $items[] = [
"title" => $this->cleanText((string) $item->title), 'title' => $this->cleanText((string) $item->title),
"link" => (string) $item->link, 'link' => (string) $item->link,
"description" => $this->cleanText((string) $item->description), 'description' => $this->cleanText((string) $item->description),
]; ];
} }
@ -97,41 +107,44 @@ class MastodonPostHandler extends ApiHandler
private function cleanText(string $text): string private function cleanText(string $text): string
{ {
$decoded = html_entity_decode($text, ENT_QUOTES | ENT_XML1, 'UTF-8'); $decoded = html_entity_decode($text, ENT_QUOTES | ENT_XML1, 'UTF-8');
return mb_convert_encoding($decoded, 'UTF-8', 'UTF-8'); return mb_convert_encoding($decoded, 'UTF-8', 'UTF-8');
} }
private function postToMastodon(string $content): ?string private function postToMastodon(string $content): ?string
{ {
$headers = [ $headers = [
"Authorization" => "Bearer {$this->mastodonAccessToken}", 'Authorization' => "Bearer {$this->mastodonAccessToken}",
"Content-Type" => "application/json", 'Content-Type' => 'application/json',
]; ];
$postData = ["status" => $content]; $postData = ['status' => $content];
$response = $this->httpClient->request("POST", self::MASTODON_API_STATUS, [ $response = $this->httpClient->request('POST', self::MASTODON_API_STATUS, [
"headers" => $headers, 'headers' => $headers,
"json" => $postData 'json' => $postData,
]); ]);
if ($response->getStatusCode() >= 400) throw new \Exception("Mastodon post failed: {$response->getBody()}"); if ($response->getStatusCode() >= 400) {
throw new \Exception("Mastodon post failed: {$response->getBody()}");
}
$body = json_decode($response->getBody()->getContents(), true); $body = json_decode($response->getBody()->getContents(), true);
return $body["url"] ?? null; return $body['url'] ?? null;
} }
private function storeInDatabase(string $link, string $timestamp): bool private function storeInDatabase(string $link, string $timestamp): bool
{ {
try { try {
$this->makeRequest("POST", "mastodon_posts", [ $this->makeRequest('POST', 'mastodon_posts', [
"json" => [ 'json' => [
"link" => $link, 'link' => $link,
"created_at" => $timestamp 'created_at' => $timestamp,
] ],
]); ]);
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
echo "Error storing post in DB: " . $e->getMessage() . "\n"; echo 'Error storing post in DB: '.$e->getMessage()."\n";
return false; return false;
} }
@ -140,11 +153,11 @@ class MastodonPostHandler extends ApiHandler
private function isDatabaseAvailable(): bool private function isDatabaseAvailable(): bool
{ {
try { try {
$response = $this->fetchFromApi("mastodon_posts", "limit=1"); $response = $this->fetchFromApi('mastodon_posts', 'limit=1');
return is_array($response); return is_array($response);
} catch (\Exception $e) { } catch (\Exception $e) {
echo "Database check failed: " . $e->getMessage() . "\n"; echo 'Database check failed: '.$e->getMessage()."\n";
return false; return false;
} }
@ -157,7 +170,7 @@ class MastodonPostHandler extends ApiHandler
if (strlen($description) > $available) { if (strlen($description) > $available) {
$description = substr($description, 0, $available); $description = substr($description, 0, $available);
$description = preg_replace('/\s+\S*$/', "", $description) . "..."; $description = preg_replace('/\s+\S*$/', '', $description).'...';
} }
return "$title\n\n$description\n\n$link"; return "$title\n\n$description\n\n$link";
@ -170,5 +183,5 @@ try {
} catch (\Exception $e) { } catch (\Exception $e) {
http_response_code(500); http_response_code(500);
echo json_encode(["error" => $e->getMessage()]); echo json_encode(['error' => $e->getMessage()]);
} }

View file

@ -3,7 +3,6 @@
require_once __DIR__.'/../bootstrap.php'; require_once __DIR__.'/../bootstrap.php';
use App\Classes\BaseHandler; use App\Classes\BaseHandler;
use GuzzleHttp\Client;
class OembedHandler extends BaseHandler class OembedHandler extends BaseHandler
{ {
@ -14,19 +13,25 @@ class OembedHandler extends BaseHandler
$parsed = $requestUrl ? parse_url($requestUrl) : null; $parsed = $requestUrl ? parse_url($requestUrl) : null;
$relativePath = $parsed['path'] ?? null; $relativePath = $parsed['path'] ?? null;
if (!$requestUrl || $relativePath === '/') $this->sendResponse($this->buildResponse( if (! $requestUrl || $relativePath === '/') {
$this->sendResponse($this->buildResponse(
$globals['site_name'], $globals['site_name'],
$globals['url'], $globals['url'],
$globals['metadata']['open_graph_image'], $globals['metadata']['open_graph_image'],
$globals, $globals,
$globals['site_description'] $globals['site_description']
)); ));
}
if (!$relativePath) $this->sendErrorResponse('Invalid url', 400); if (! $relativePath) {
$this->sendErrorResponse('Invalid url', 400);
}
$relativePath = '/'.ltrim($relativePath ?? '', '/'); $relativePath = '/'.ltrim($relativePath ?? '', '/');
if ($relativePath !== '/' && str_ends_with($relativePath, '/')) $relativePath = rtrim($relativePath, '/'); if ($relativePath !== '/' && str_ends_with($relativePath, '/')) {
$relativePath = rtrim($relativePath, '/');
}
$cacheKey = 'oembed:'.md5($relativePath); $cacheKey = 'oembed:'.md5($relativePath);
@ -47,7 +52,9 @@ class OembedHandler extends BaseHandler
if (! empty($results)) { if (! empty($results)) {
$item = $results[0]; $item = $results[0];
if ($this->cache) $this->cache->setex($cacheKey, 300, json_encode($item)); if ($this->cache) {
$this->cache->setex($cacheKey, 300, json_encode($item));
}
$this->sendResponse($this->buildResponse( $this->sendResponse($this->buildResponse(
$item['title'], $item['title'],
@ -79,7 +86,9 @@ class OembedHandler extends BaseHandler
$safeDescription = truncateText(strip_tags(parseMarkdown($description)), 175); $safeDescription = truncateText(strip_tags(parseMarkdown($description)), 175);
$html = '<p><a href="'.htmlspecialchars($url).'">'.htmlspecialchars($title).'</a></p>'; $html = '<p><a href="'.htmlspecialchars($url).'">'.htmlspecialchars($title).'</a></p>';
if ($description) $html .= '<p>' . htmlspecialchars($safeDescription, ENT_QUOTES, 'UTF-8') . '</p>'; if ($description) {
$html .= '<p>'.htmlspecialchars($safeDescription, ENT_QUOTES, 'UTF-8').'</p>';
}
return [ return [
'version' => '1.0', 'version' => '1.0',
@ -98,11 +107,15 @@ class OembedHandler extends BaseHandler
{ {
$cacheKey = 'globals_data'; $cacheKey = 'globals_data';
if ($this->cache && $this->cache->exists($cacheKey)) return json_decode($this->cache->get($cacheKey), true); if ($this->cache && $this->cache->exists($cacheKey)) {
return json_decode($this->cache->get($cacheKey), true);
}
$globals = $this->fetchFromApi('optimized_globals', 'limit=1')[0]; $globals = $this->fetchFromApi('optimized_globals', 'limit=1')[0];
if ($this->cache) $this->cache->setex($cacheKey, 3600, json_encode($globals)); if ($this->cache) {
$this->cache->setex($cacheKey, 3600, json_encode($globals));
}
return $globals; return $globals;
} }

View file

@ -8,7 +8,9 @@
$isValidId = is_string($id) && preg_match('/^[a-f0-9\-]{36}$/', $id); $isValidId = is_string($id) && preg_match('/^[a-f0-9\-]{36}$/', $id);
$isValidClass = is_string($class) && preg_match('/^w\d{2,4}$/', $class); $isValidClass = is_string($class) && preg_match('/^w\d{2,4}$/', $class);
if (!$isValidId || !$isValidClass) redirectTo404(); if (! $isValidId || ! $isValidClass) {
redirectTo404();
}
$cdnUrl = "https://cdn.coryd.dev/$id.$extension?class=$class"; $cdnUrl = "https://cdn.coryd.dev/$id.$extension?class=$class";
$ch = curl_init($cdnUrl); $ch = curl_init($cdnUrl);
@ -23,7 +25,9 @@
curl_close($ch); curl_close($ch);
if ($httpCode !== 200 || $image === false || strpos($contentType, 'image/') !== 0) redirectTo404(); if ($httpCode !== 200 || $image === false || strpos($contentType, 'image/') !== 0) {
redirectTo404();
}
header("Content-Type: $contentType"); header("Content-Type: $contentType");

View file

@ -19,15 +19,17 @@ class QueryHandler extends BaseHandler
$referer = $_SERVER['HTTP_REFERER'] ?? ''; $referer = $_SERVER['HTTP_REFERER'] ?? '';
$hostAllowed = fn ($url) => in_array(parse_url($url, PHP_URL_HOST), $allowedHosts, true); $hostAllowed = fn ($url) => in_array(parse_url($url, PHP_URL_HOST), $allowedHosts, true);
if (!$hostAllowed($origin) && !$hostAllowed($referer)) $this->sendErrorResponse("Forbidden: invalid origin", 403); if (! $hostAllowed($origin) && ! $hostAllowed($referer)) {
$this->sendErrorResponse('Forbidden: invalid origin', 403);
}
$allowedSource = $origin ?: $referer; $allowedSource = $origin ?: $referer;
$scheme = parse_url($allowedSource, PHP_URL_SCHEME) ?? 'https'; $scheme = parse_url($allowedSource, PHP_URL_SCHEME) ?? 'https';
$host = parse_url($allowedSource, PHP_URL_HOST); $host = parse_url($allowedSource, PHP_URL_HOST);
header("Access-Control-Allow-Origin: {$scheme}://{$host}"); header("Access-Control-Allow-Origin: {$scheme}://{$host}");
header("Access-Control-Allow-Headers: Content-Type"); header('Access-Control-Allow-Headers: Content-Type');
header("Access-Control-Allow-Methods: GET, POST"); header('Access-Control-Allow-Methods: GET, POST');
} }
public function handleRequest(): void public function handleRequest(): void
@ -36,7 +38,9 @@ class QueryHandler extends BaseHandler
$id = $_GET['id'] ?? null; $id = $_GET['id'] ?? null;
$cacheDuration = intval($_GET['cacheDuration'] ?? 3600); $cacheDuration = intval($_GET['cacheDuration'] ?? 3600);
if (!$data) $this->sendErrorResponse("Missing 'data' parameter", 400); if (! $data) {
$this->sendErrorResponse("Missing 'data' parameter", 400);
}
$cacheKey = $this->buildCacheKey($data, $id); $cacheKey = $this->buildCacheKey($data, $id);
@ -50,42 +54,52 @@ class QueryHandler extends BaseHandler
} }
} }
$query = $id ? "id=eq.$id" : ""; $query = $id ? "id=eq.$id" : '';
try { try {
$response = $this->fetchFromApi($data, $query); $response = $this->fetchFromApi($data, $query);
$markdownFields = $this->getMarkdownFieldsFromQuery(); $markdownFields = $this->getMarkdownFieldsFromQuery();
if (!empty($response) && !empty($markdownFields)) $response = $this->parseMarkdownFields($response, $markdownFields); if (! empty($response) && ! empty($markdownFields)) {
$response = $this->parseMarkdownFields($response, $markdownFields);
}
$json = json_encode($response); $json = json_encode($response);
if ($this->cache) $this->cache->setex($cacheKey, $cacheDuration, $json); if ($this->cache) {
$this->cache->setex($cacheKey, $cacheDuration, $json);
}
header('Content-Type: application/json'); header('Content-Type: application/json');
echo $json; echo $json;
} catch (\Exception $e) { } catch (\Exception $e) {
$this->sendErrorResponse("PostgREST fetch failed: " . $e->getMessage(), 500); $this->sendErrorResponse('PostgREST fetch failed: '.$e->getMessage(), 500);
} }
} }
private function buildCacheKey(string $data, ?string $id): string private function buildCacheKey(string $data, ?string $id): string
{ {
return "proxy_{$data}" . ($id ? "_{$id}" : ""); return "proxy_{$data}".($id ? "_{$id}" : '');
} }
private function getMarkdownFieldsFromQuery(): array { private function getMarkdownFieldsFromQuery(): array
{
$fields = $_GET['markdown'] ?? []; $fields = $_GET['markdown'] ?? [];
if (!is_array($fields)) $fields = explode(',', $fields); if (! is_array($fields)) {
$fields = explode(',', $fields);
}
return array_map('trim', array_filter($fields)); return array_map('trim', array_filter($fields));
} }
private function parseMarkdownFields(array $data, array $fields): array { private function parseMarkdownFields(array $data, array $fields): array
{
foreach ($data as &$item) { foreach ($data as &$item) {
foreach ($fields as $field) { foreach ($fields as $field) {
if (!empty($item[$field])) $item["{$field}_html"] = parseMarkdown($item[$field]); if (! empty($item[$field])) {
$item["{$field}_html"] = parseMarkdown($item[$field]);
}
} }
} }

View file

@ -5,14 +5,18 @@ require_once __DIR__ . '/../bootstrap.php';
use App\Classes\ApiHandler; use App\Classes\ApiHandler;
use GuzzleHttp\Client; use GuzzleHttp\Client;
header("Content-Type: application/json"); header('Content-Type: application/json');
class NavidromeScrobbleHandler extends ApiHandler class NavidromeScrobbleHandler extends ApiHandler
{ {
private string $navidromeApiUrl; private string $navidromeApiUrl;
private string $navidromeAuthToken; private string $navidromeAuthToken;
private string $forwardEmailApiKey; private string $forwardEmailApiKey;
private array $artistCache = []; private array $artistCache = [];
private array $albumCache = []; private array $albumCache = [];
public function __construct() public function __construct()
@ -25,20 +29,20 @@ class NavidromeScrobbleHandler extends ApiHandler
private function loadExternalServiceKeys(): void private function loadExternalServiceKeys(): void
{ {
$this->navidromeApiUrl = getenv("NAVIDROME_API_URL"); $this->navidromeApiUrl = getenv('NAVIDROME_API_URL');
$this->navidromeAuthToken = getenv("NAVIDROME_API_TOKEN"); $this->navidromeAuthToken = getenv('NAVIDROME_API_TOKEN');
$this->forwardEmailApiKey = getenv("FORWARDEMAIL_API_KEY"); $this->forwardEmailApiKey = getenv('FORWARDEMAIL_API_KEY');
} }
private function validateAuthorization(): void private function validateAuthorization(): void
{ {
$authHeader = $_SERVER["HTTP_AUTHORIZATION"] ?? ""; $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$expectedToken = "Bearer " . getenv("NAVIDROME_SCROBBLE_TOKEN"); $expectedToken = 'Bearer '.getenv('NAVIDROME_SCROBBLE_TOKEN');
if ($authHeader !== $expectedToken) { if ($authHeader !== $expectedToken) {
http_response_code(401); http_response_code(401);
echo json_encode(["error" => "Unauthorized."]); echo json_encode(['error' => 'Unauthorized.']);
exit(); exit();
} }
@ -48,10 +52,14 @@ class NavidromeScrobbleHandler extends ApiHandler
{ {
$recentTracks = $this->fetchRecentlyPlayed(); $recentTracks = $this->fetchRecentlyPlayed();
if (empty($recentTracks)) return; if (empty($recentTracks)) {
return;
}
foreach ($recentTracks as $track) { foreach ($recentTracks as $track) {
if ($this->isTrackAlreadyScrobbled($track)) continue; if ($this->isTrackAlreadyScrobbled($track)) {
continue;
}
$this->handleTrackScrobble($track); $this->handleTrackScrobble($track);
} }
@ -62,25 +70,25 @@ class NavidromeScrobbleHandler extends ApiHandler
$client = new Client(); $client = new Client();
try { try {
$response = $client->request("GET", "{$this->navidromeApiUrl}/api/song", [ $response = $client->request('GET', "{$this->navidromeApiUrl}/api/song", [
"query" => [ 'query' => [
"_end" => 20, '_end' => 20,
"_order" => "DESC", '_order' => 'DESC',
"_sort" => "play_date", '_sort' => 'play_date',
"_start" => 0, '_start' => 0,
"recently_played" => "true" 'recently_played' => 'true',
],
'headers' => [
'x-nd-authorization' => "Bearer {$this->navidromeAuthToken}",
'Accept' => 'application/json',
], ],
"headers" => [
"x-nd-authorization" => "Bearer {$this->navidromeAuthToken}",
"Accept" => "application/json"
]
]); ]);
$data = json_decode($response->getBody()->getContents(), true); $data = json_decode($response->getBody()->getContents(), true);
return $data ?? []; return $data ?? [];
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("Error fetching tracks: " . $e->getMessage()); error_log('Error fetching tracks: '.$e->getMessage());
return []; return [];
} }
@ -88,105 +96,128 @@ class NavidromeScrobbleHandler extends ApiHandler
private function isTrackAlreadyScrobbled(array $track): bool private function isTrackAlreadyScrobbled(array $track): bool
{ {
$playDateString = $track["playDate"] ?? null; $playDateString = $track['playDate'] ?? null;
if (!$playDateString) return false; if (! $playDateString) {
return false;
}
$playDate = strtotime($playDateString); $playDate = strtotime($playDateString);
if ($playDate === false) return false; if ($playDate === false) {
return false;
}
$existingListen = $this->fetchFromApi("listens", "listened_at=eq.{$playDate}&limit=1"); $existingListen = $this->fetchFromApi('listens', "listened_at=eq.{$playDate}&limit=1");
return ! empty($existingListen); return ! empty($existingListen);
} }
private function handleTrackScrobble(array $track): void private function handleTrackScrobble(array $track): void
{ {
$artistData = $this->getOrCreateArtist($track["artist"]); $artistData = $this->getOrCreateArtist($track['artist']);
if (empty($artistData)) { if (empty($artistData)) {
error_log("Failed to retrieve or create artist: " . $track["artist"]); error_log('Failed to retrieve or create artist: '.$track['artist']);
return; return;
} }
$albumData = $this->getOrCreateAlbum($track["album"], $artistData); $albumData = $this->getOrCreateAlbum($track['album'], $artistData);
if (empty($albumData)) { if (empty($albumData)) {
error_log("Failed to retrieve or create album: " . $track["album"]); error_log('Failed to retrieve or create album: '.$track['album']);
return; return;
} }
$this->insertListen($track, $albumData["key"]); $this->insertListen($track, $albumData['key']);
} }
private function getOrCreateArtist(string $artistName): array private function getOrCreateArtist(string $artistName): array
{ {
if (!$this->isDatabaseAvailable()) return []; if (! $this->isDatabaseAvailable()) {
if (isset($this->artistCache[$artistName])) return $this->artistCache[$artistName]; return [];
}
if (isset($this->artistCache[$artistName])) {
return $this->artistCache[$artistName];
}
$encodedArtist = rawurlencode($artistName); $encodedArtist = rawurlencode($artistName);
$existingArtist = $this->fetchFromApi("artists", "name_string=eq.{$encodedArtist}&limit=1"); $existingArtist = $this->fetchFromApi('artists', "name_string=eq.{$encodedArtist}&limit=1");
if (!empty($existingArtist)) return $this->artistCache[$artistName] = $existingArtist[0]; if (! empty($existingArtist)) {
return $this->artistCache[$artistName] = $existingArtist[0];
}
$response = $this->makeRequest("POST", "artists", [ $response = $this->makeRequest('POST', 'artists', [
"json" => [ 'json' => [
"mbid" => "", 'mbid' => '',
"art" => "4cef75db-831f-4f5d-9333-79eaa5bb55ee", 'art' => '4cef75db-831f-4f5d-9333-79eaa5bb55ee',
"name_string" => $artistName, 'name_string' => $artistName,
"slug" => "/music", 'slug' => '/music',
"country" => "", 'country' => '',
"description" => "", 'description' => '',
"tentative" => true, 'tentative' => true,
"favorite" => false, 'favorite' => false,
"tattoo" => false, 'tattoo' => false,
"total_plays" => 0 'total_plays' => 0,
], ],
"headers" => ["Prefer" => "return=representation"] 'headers' => ['Prefer' => 'return=representation'],
]); ]);
$inserted = $response[0] ?? null; $inserted = $response[0] ?? null;
if ($inserted) $this->sendFailureEmail("New tentative artist record", "A new tentative artist record was inserted for: $artistName"); if ($inserted) {
$this->sendFailureEmail('New tentative artist record', "A new tentative artist record was inserted for: $artistName");
}
return $this->artistCache[$artistName] = $inserted ?? []; return $this->artistCache[$artistName] = $inserted ?? [];
} }
private function getOrCreateAlbum(string $albumName, array $artistData): array private function getOrCreateAlbum(string $albumName, array $artistData): array
{ {
if (!$this->isDatabaseAvailable()) return []; if (! $this->isDatabaseAvailable()) {
$albumKey = $this->generateAlbumKey($artistData["name_string"], $albumName);
if (isset($this->albumCache[$albumKey])) return $this->albumCache[$albumKey];
$encodedAlbumKey = rawurlencode($albumKey);
$existingAlbum = $this->fetchFromApi("albums", "key=eq.{$encodedAlbumKey}&limit=1");
if (!empty($existingAlbum)) return $this->albumCache[$albumKey] = $existingAlbum[0];
$artistId = $artistData["id"] ?? null;
if (!$artistId) {
error_log("Artist ID missing for album creation: " . $albumName);
return []; return [];
} }
$response = $this->makeRequest("POST", "albums", [ $albumKey = $this->generateAlbumKey($artistData['name_string'], $albumName);
"json" => [
"mbid" => null, if (isset($this->albumCache[$albumKey])) {
"art" => "4cef75db-831f-4f5d-9333-79eaa5bb55ee", return $this->albumCache[$albumKey];
"key" => $albumKey, }
"name" => $albumName,
"tentative" => true, $encodedAlbumKey = rawurlencode($albumKey);
"total_plays" => 0, $existingAlbum = $this->fetchFromApi('albums', "key=eq.{$encodedAlbumKey}&limit=1");
"artist" => $artistId
if (! empty($existingAlbum)) {
return $this->albumCache[$albumKey] = $existingAlbum[0];
}
$artistId = $artistData['id'] ?? null;
if (! $artistId) {
error_log('Artist ID missing for album creation: '.$albumName);
return [];
}
$response = $this->makeRequest('POST', 'albums', [
'json' => [
'mbid' => null,
'art' => '4cef75db-831f-4f5d-9333-79eaa5bb55ee',
'key' => $albumKey,
'name' => $albumName,
'tentative' => true,
'total_plays' => 0,
'artist' => $artistId,
], ],
"headers" => ["Prefer" => "return=representation"] 'headers' => ['Prefer' => 'return=representation'],
]); ]);
$inserted = $response[0] ?? null; $inserted = $response[0] ?? null;
if ($inserted) $this->sendFailureEmail("New tentative album record", "A new tentative album record was inserted:\n\nAlbum: $albumName\nKey: $albumKey"); if ($inserted) {
$this->sendFailureEmail('New tentative album record', "A new tentative album record was inserted:\n\nAlbum: $albumName\nKey: $albumKey");
}
return $this->albumCache[$albumKey] = $inserted ?? []; return $this->albumCache[$albumKey] = $inserted ?? [];
} }
@ -194,23 +225,26 @@ class NavidromeScrobbleHandler extends ApiHandler
private function insertListen(array $track, string $albumKey): void private function insertListen(array $track, string $albumKey): void
{ {
$payload = [ $payload = [
"artist_name" => $track["artist"], 'artist_name' => $track['artist'],
"album_name" => $track["album"], 'album_name' => $track['album'],
"track_name" => $track["title"], 'track_name' => $track['title'],
"album_key" => $albumKey 'album_key' => $albumKey,
]; ];
if (!empty($track["playDate"])) { if (! empty($track['playDate'])) {
$playDate = strtotime($track["playDate"]); $playDate = strtotime($track['playDate']);
if ($playDate !== false) $payload["listened_at"] = $playDate; if ($playDate !== false) {
$payload['listened_at'] = $playDate;
}
} }
if (!isset($payload["listened_at"])) { if (! isset($payload['listened_at'])) {
error_log("Skipping track due to missing or invalid listened_at: " . json_encode($track)); error_log('Skipping track due to missing or invalid listened_at: '.json_encode($track));
return; return;
} }
$this->makeRequest("POST", "listens", ["json" => $payload]); $this->makeRequest('POST', 'listens', ['json' => $payload]);
} }
private function generateAlbumKey(string $artistName, string $albumName): string private function generateAlbumKey(string $artistName, string $albumName): string
@ -223,41 +257,45 @@ class NavidromeScrobbleHandler extends ApiHandler
private function sendFailureEmail(string $subject, string $message): void private function sendFailureEmail(string $subject, string $message): void
{ {
if (!$this->isDatabaseAvailable()) return; if (! $this->isDatabaseAvailable()) {
return;
}
$authHeader = "Basic " . base64_encode($this->forwardEmailApiKey . ":"); $authHeader = 'Basic '.base64_encode($this->forwardEmailApiKey.':');
$client = new Client(["base_uri" => "https://api.forwardemail.net/"]); $client = new Client(['base_uri' => 'https://api.forwardemail.net/']);
try { try {
$client->post("v1/emails", [ $client->post('v1/emails', [
"headers" => [ 'headers' => [
"Authorization" => $authHeader, 'Authorization' => $authHeader,
"Content-Type" => "application/x-www-form-urlencoded", 'Content-Type' => 'application/x-www-form-urlencoded',
], ],
"form_params" => [ 'form_params' => [
"from" => "coryd.dev <hi@admin.coryd.dev>", 'from' => 'coryd.dev <hi@admin.coryd.dev>',
"to" => "hi@coryd.dev", 'to' => 'hi@coryd.dev',
"subject" => $subject, 'subject' => $subject,
"text" => $message, 'text' => $message,
], ],
]); ]);
} catch (\GuzzleHttp\Exception\RequestException $e) { } catch (\GuzzleHttp\Exception\RequestException $e) {
error_log("Request Exception: " . $e->getMessage()); error_log('Request Exception: '.$e->getMessage());
if ($e->hasResponse()) error_log("Error Response: " . (string) $e->getResponse()->getBody()); if ($e->hasResponse()) {
error_log('Error Response: '.(string) $e->getResponse()->getBody());
}
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("General Exception: " . $e->getMessage()); error_log('General Exception: '.$e->getMessage());
} }
} }
private function isDatabaseAvailable(): bool private function isDatabaseAvailable(): bool
{ {
try { try {
$response = $this->fetchFromApi("listens", "limit=1"); $response = $this->fetchFromApi('listens', 'limit=1');
return is_array($response); return is_array($response);
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("Database check failed: " . $e->getMessage()); error_log('Database check failed: '.$e->getMessage());
return false; return false;
} }
@ -270,5 +308,5 @@ try {
} catch (\Exception $e) { } catch (\Exception $e) {
http_response_code(500); http_response_code(500);
echo json_encode(["error" => $e->getMessage()]); echo json_encode(['error' => $e->getMessage()]);
} }

View file

@ -17,65 +17,76 @@ class SearchHandler extends BaseHandler
public function handleRequest(): void public function handleRequest(): void
{ {
try { try {
$query = $this->validateAndSanitizeQuery($_GET["q"] ?? null); $query = $this->validateAndSanitizeQuery($_GET['q'] ?? null);
$sections = $this->validateAndSanitizeSections($_GET["section"] ?? ""); $sections = $this->validateAndSanitizeSections($_GET['section'] ?? '');
$page = isset($_GET["page"]) ? intval($_GET["page"]) : 1; $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$pageSize = isset($_GET["pageSize"]) ? intval($_GET["pageSize"]) : 10; $pageSize = isset($_GET['pageSize']) ? intval($_GET['pageSize']) : 10;
$offset = ($page - 1) * $pageSize; $offset = ($page - 1) * $pageSize;
$cacheKey = $this->generateCacheKey($query, $sections, $page, $pageSize); $cacheKey = $this->generateCacheKey($query, $sections, $page, $pageSize);
$results = []; $results = [];
$results = $this->getCachedResults($cacheKey) ?? $this->fetchSearchResults($query, $sections, $pageSize, $offset); $results = $this->getCachedResults($cacheKey) ?? $this->fetchSearchResults($query, $sections, $pageSize, $offset);
if (empty($results) || empty($results["data"])) { if (empty($results) || empty($results['data'])) {
$this->sendResponse(["results" => [], "total" => 0, "page" => $page, "pageSize" => $pageSize], 200); $this->sendResponse(['results' => [], 'total' => 0, 'page' => $page, 'pageSize' => $pageSize], 200);
return; return;
} }
$this->cacheResults($cacheKey, $results); $this->cacheResults($cacheKey, $results);
$this->sendResponse( $this->sendResponse(
[ [
"results" => $results["data"], 'results' => $results['data'],
"total" => $results["total"], 'total' => $results['total'],
"page" => $page, 'page' => $page,
"pageSize" => $pageSize, 'pageSize' => $pageSize,
], ],
200 200
); );
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("Search API Error: " . $e->getMessage()); error_log('Search API Error: '.$e->getMessage());
$this->sendErrorResponse("Invalid request. Please check your query and try again.", 400); $this->sendErrorResponse('Invalid request. Please check your query and try again.', 400);
} }
} }
private function validateAndSanitizeQuery(?string $query): string private function validateAndSanitizeQuery(?string $query): string
{ {
if (empty($query) || !is_string($query)) throw new \Exception("Invalid 'q' parameter. Must be a non-empty string."); if (empty($query) || ! is_string($query)) {
throw new \Exception("Invalid 'q' parameter. Must be a non-empty string.");
}
$query = trim($query); $query = trim($query);
if (strlen($query) > 255) throw new \Exception("Invalid 'q' parameter. Exceeds maximum length of 255 characters."); if (strlen($query) > 255) {
if (!preg_match('/^[a-zA-Z0-9\s\-_\'"]+$/', $query)) throw new \Exception("Invalid 'q' parameter. Contains unsupported characters."); throw new \Exception("Invalid 'q' parameter. Exceeds maximum length of 255 characters.");
}
if (! preg_match('/^[a-zA-Z0-9\s\-_\'"]+$/', $query)) {
throw new \Exception("Invalid 'q' parameter. Contains unsupported characters.");
}
$query = preg_replace("/\s+/", " ", $query); $query = preg_replace("/\s+/", ' ', $query);
return $query; return $query;
} }
private function validateAndSanitizeSections(string $rawSections): ?array private function validateAndSanitizeSections(string $rawSections): ?array
{ {
$allowedSections = ["post", "artist", "genre", "book", "movie", "show"]; $allowedSections = ['post', 'artist', 'genre', 'book', 'movie', 'show'];
if (empty($rawSections)) return null; if (empty($rawSections)) {
return null;
}
$sections = array_map( $sections = array_map(
fn ($section) => strtolower( fn ($section) => strtolower(
trim(htmlspecialchars($section, ENT_QUOTES, "UTF-8")) trim(htmlspecialchars($section, ENT_QUOTES, 'UTF-8'))
), ),
explode(",", $rawSections) explode(',', $rawSections)
); );
$invalidSections = array_diff($sections, $allowedSections); $invalidSections = array_diff($sections, $allowedSections);
if (!empty($invalidSections)) throw new Exception("Invalid 'section' parameter. Unsupported sections: " . implode(", ", $invalidSections)); if (! empty($invalidSections)) {
throw new Exception("Invalid 'section' parameter. Unsupported sections: ".implode(', ', $invalidSections));
}
return $sections; return $sections;
} }
@ -86,25 +97,27 @@ class SearchHandler extends BaseHandler
int $pageSize, int $pageSize,
int $offset int $offset
): array { ): array {
$sectionsParam = $sections && count($sections) > 0 ? "%7B" . implode(",", $sections) . "%7D" : ""; $sectionsParam = $sections && count($sections) > 0 ? '%7B'.implode(',', $sections).'%7D' : '';
$endpoint = "rpc/search_optimized_index"; $endpoint = 'rpc/search_optimized_index';
$queryString = $queryString =
"search_query=" . 'search_query='.
urlencode($query). urlencode($query).
"&page_size={$pageSize}&page_offset={$offset}". "&page_size={$pageSize}&page_offset={$offset}".
($sectionsParam ? "&sections={$sectionsParam}" : ""); ($sectionsParam ? "&sections={$sectionsParam}" : '');
$data = $this->makeRequest("GET", "{$endpoint}?{$queryString}"); $data = $this->makeRequest('GET', "{$endpoint}?{$queryString}");
$total = count($data) > 0 ? $data[0]["total_count"] : 0; $total = count($data) > 0 ? $data[0]['total_count'] : 0;
$results = array_map(function ($item) { $results = array_map(function ($item) {
unset($item["total_count"]); unset($item['total_count']);
if (!empty($item["description"])) $item["description"] = truncateText(strip_tags(parseMarkdown($item["description"])), 225); if (! empty($item['description'])) {
$item['description'] = truncateText(strip_tags(parseMarkdown($item['description'])), 225);
}
return $item; return $item;
}, $data); }, $data);
return ["data" => $results, "total" => $total]; return ['data' => $results, 'total' => $total];
} }
private function generateCacheKey( private function generateCacheKey(
@ -113,10 +126,10 @@ class SearchHandler extends BaseHandler
int $page, int $page,
int $pageSize int $pageSize
): string { ): string {
$sectionsKey = $sections ? implode(",", $sections) : "all"; $sectionsKey = $sections ? implode(',', $sections) : 'all';
return sprintf( return sprintf(
"search:%s:sections:%s:page:%d:pageSize:%d", 'search:%s:sections:%s:page:%d:pageSize:%d',
md5($query), md5($query),
$sectionsKey, $sectionsKey,
$page, $page,
@ -133,6 +146,7 @@ class SearchHandler extends BaseHandler
} elseif (is_array($this->cache)) { } elseif (is_array($this->cache)) {
return $this->cache[$cacheKey] ?? null; return $this->cache[$cacheKey] ?? null;
} }
return null; return null;
} }

View file

@ -8,6 +8,7 @@ use GuzzleHttp\Client;
class SeasonImportHandler extends ApiHandler class SeasonImportHandler extends ApiHandler
{ {
private string $tmdbApiKey; private string $tmdbApiKey;
private string $seasonsImportToken; private string $seasonsImportToken;
public function __construct() public function __construct()
@ -15,50 +16,61 @@ class SeasonImportHandler extends ApiHandler
parent::__construct(); parent::__construct();
$this->ensureCliAccess(); $this->ensureCliAccess();
$this->tmdbApiKey = getenv("TMDB_API_KEY") ?: $_ENV["TMDB_API_KEY"]; $this->tmdbApiKey = getenv('TMDB_API_KEY') ?: $_ENV['TMDB_API_KEY'];
$this->seasonsImportToken = getenv("SEASONS_IMPORT_TOKEN") ?: $_ENV["SEASONS_IMPORT_TOKEN"]; $this->seasonsImportToken = getenv('SEASONS_IMPORT_TOKEN') ?: $_ENV['SEASONS_IMPORT_TOKEN'];
$this->authenticateRequest(); $this->authenticateRequest();
} }
private function authenticateRequest(): void private function authenticateRequest(): void
{ {
if ($_SERVER["REQUEST_METHOD"] !== "POST") $this->sendErrorResponse("Method Not Allowed", 405); if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$this->sendErrorResponse('Method Not Allowed', 405);
}
$authHeader = $_SERVER["HTTP_AUTHORIZATION"] ?? ""; $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/Bearer\s+(.+)/', $authHeader, $matches)) $this->sendErrorResponse("Unauthorized", 401); if (! preg_match('/Bearer\s+(.+)/', $authHeader, $matches)) {
$this->sendErrorResponse('Unauthorized', 401);
}
$providedToken = trim($matches[1]); $providedToken = trim($matches[1]);
if ($providedToken !== $this->seasonsImportToken) $this->sendErrorResponse("Forbidden", 403); if ($providedToken !== $this->seasonsImportToken) {
$this->sendErrorResponse('Forbidden', 403);
}
} }
public function importSeasons(): void public function importSeasons(): void
{ {
$ongoingShows = $this->fetchFromApi("optimized_shows", "ongoing=eq.true"); $ongoingShows = $this->fetchFromApi('optimized_shows', 'ongoing=eq.true');
if (empty($ongoingShows)) $this->sendResponse(["message" => "No ongoing shows to update"], 200); if (empty($ongoingShows)) {
$this->sendResponse(['message' => 'No ongoing shows to update'], 200);
}
foreach ($ongoingShows as $show) { foreach ($ongoingShows as $show) {
$this->processShowSeasons($show); $this->processShowSeasons($show);
} }
$this->sendResponse(["message" => "Season import completed"], 200); $this->sendResponse(['message' => 'Season import completed'], 200);
} }
private function processShowSeasons(array $show): void private function processShowSeasons(array $show): void
{ {
$tmdbId = $show["tmdb_id"] ?? null; $tmdbId = $show['tmdb_id'] ?? null;
$showId = $show["id"] ?? null; $showId = $show['id'] ?? null;
if (!$tmdbId || !$showId) return; if (! $tmdbId || ! $showId) {
return;
}
$tmdbShowData = $this->fetchShowDetails($tmdbId); $tmdbShowData = $this->fetchShowDetails($tmdbId);
$seasons = $tmdbShowData["seasons"] ?? []; $seasons = $tmdbShowData['seasons'] ?? [];
$status = $tmdbShowData["status"] ?? "Unknown"; $status = $tmdbShowData['status'] ?? 'Unknown';
if (empty($seasons) && ! $this->shouldKeepOngoing($status)) { if (empty($seasons) && ! $this->shouldKeepOngoing($status)) {
$this->disableOngoingStatus($showId); $this->disableOngoingStatus($showId);
return; return;
} }
@ -69,7 +81,7 @@ class SeasonImportHandler extends ApiHandler
private function shouldKeepOngoing(string $status): bool private function shouldKeepOngoing(string $status): bool
{ {
return in_array($status, ["Returning Series", "In Production"]); return in_array($status, ['Returning Series', 'In Production']);
} }
private function fetchShowDetails(string $tmdbId): array private function fetchShowDetails(string $tmdbId): array
@ -78,7 +90,7 @@ class SeasonImportHandler extends ApiHandler
$url = "https://api.themoviedb.org/3/tv/{$tmdbId}?api_key={$this->tmdbApiKey}&append_to_response=seasons"; $url = "https://api.themoviedb.org/3/tv/{$tmdbId}?api_key={$this->tmdbApiKey}&append_to_response=seasons";
try { try {
$response = $client->get($url, ["headers" => ["Accept" => "application/json"]]); $response = $client->get($url, ['headers' => ['Accept' => 'application/json']]);
return json_decode($response->getBody(), true) ?? []; return json_decode($response->getBody(), true) ?? [];
} catch (\Exception $e) { } catch (\Exception $e) {
@ -88,44 +100,58 @@ class SeasonImportHandler extends ApiHandler
private function fetchWatchedEpisodes(int $showId): array private function fetchWatchedEpisodes(int $showId): array
{ {
$episodes = $this->fetchFromApi("optimized_last_watched_episodes", "show_id=eq.{$showId}&order=last_watched_at.desc&limit=1"); $episodes = $this->fetchFromApi('optimized_last_watched_episodes', "show_id=eq.{$showId}&order=last_watched_at.desc&limit=1");
if (empty($episodes)) return []; if (empty($episodes)) {
return [];
}
return [ return [
"season_number" => (int) $episodes[0]["season_number"], 'season_number' => (int) $episodes[0]['season_number'],
"episode_number" => (int) $episodes[0]["episode_number"], 'episode_number' => (int) $episodes[0]['episode_number'],
]; ];
} }
private function processSeasonEpisodes(int $showId, string $tmdbId, array $season): void private function processSeasonEpisodes(int $showId, string $tmdbId, array $season): void
{ {
$seasonNumber = $season["season_number"] ?? null; $seasonNumber = $season['season_number'] ?? null;
if ($seasonNumber === null || $seasonNumber == 0) return; if ($seasonNumber === null || $seasonNumber == 0) {
return;
}
$episodes = $this->fetchSeasonEpisodes($tmdbId, $seasonNumber); $episodes = $this->fetchSeasonEpisodes($tmdbId, $seasonNumber);
if (empty($episodes)) return; if (empty($episodes)) {
return;
}
$watched = $this->fetchWatchedEpisodes($showId); $watched = $this->fetchWatchedEpisodes($showId);
$lastWatchedSeason = $watched["season_number"] ?? null; $lastWatchedSeason = $watched['season_number'] ?? null;
$lastWatchedEpisode = $watched["episode_number"] ?? null; $lastWatchedEpisode = $watched['episode_number'] ?? null;
$scheduled = $this->fetchFromApi( $scheduled = $this->fetchFromApi(
"optimized_scheduled_episodes", 'optimized_scheduled_episodes',
"show_id=eq.{$showId}&season_number=eq.{$seasonNumber}" "show_id=eq.{$showId}&season_number=eq.{$seasonNumber}"
); );
$scheduledEpisodeNumbers = array_column($scheduled, "episode_number"); $scheduledEpisodeNumbers = array_column($scheduled, 'episode_number');
foreach ($episodes as $episode) { foreach ($episodes as $episode) {
$episodeNumber = $episode["episode_number"] ?? null; $episodeNumber = $episode['episode_number'] ?? null;
if ($episodeNumber === null) continue; if ($episodeNumber === null) {
if (in_array($episodeNumber, $scheduledEpisodeNumbers)) continue; continue;
if ($lastWatchedSeason !== null && $seasonNumber < $lastWatchedSeason) return; }
if ($seasonNumber == $lastWatchedSeason && $episodeNumber <= $lastWatchedEpisode) continue; if (in_array($episodeNumber, $scheduledEpisodeNumbers)) {
continue;
}
if ($lastWatchedSeason !== null && $seasonNumber < $lastWatchedSeason) {
return;
}
if ($seasonNumber == $lastWatchedSeason && $episodeNumber <= $lastWatchedEpisode) {
continue;
}
$this->addEpisodeToSchedule($showId, $seasonNumber, $episode); $this->addEpisodeToSchedule($showId, $seasonNumber, $episode);
} }
@ -137,9 +163,9 @@ class SeasonImportHandler extends ApiHandler
$url = "https://api.themoviedb.org/3/tv/{$tmdbId}/season/{$seasonNumber}?api_key={$this->tmdbApiKey}"; $url = "https://api.themoviedb.org/3/tv/{$tmdbId}/season/{$seasonNumber}?api_key={$this->tmdbApiKey}";
try { try {
$response = $client->get($url, ["headers" => ["Accept" => "application/json"]]); $response = $client->get($url, ['headers' => ['Accept' => 'application/json']]);
return json_decode($response->getBody(), true)["episodes"] ?? []; return json_decode($response->getBody(), true)['episodes'] ?? [];
} catch (\Exception $e) { } catch (\Exception $e) {
return []; return [];
} }
@ -147,21 +173,23 @@ class SeasonImportHandler extends ApiHandler
private function addEpisodeToSchedule(int $showId, int $seasonNumber, array $episode): void private function addEpisodeToSchedule(int $showId, int $seasonNumber, array $episode): void
{ {
$airDate = $episode["air_date"] ?? null; $airDate = $episode['air_date'] ?? null;
if (!$airDate) return; if (! $airDate) {
return;
}
$today = date("Y-m-d"); $today = date('Y-m-d');
$status = ($airDate < $today) ? "aired" : "upcoming"; $status = ($airDate < $today) ? 'aired' : 'upcoming';
$payload = [ $payload = [
"show_id" => $showId, 'show_id' => $showId,
"season_number" => $seasonNumber, 'season_number' => $seasonNumber,
"episode_number" => $episode["episode_number"], 'episode_number' => $episode['episode_number'],
"air_date" => $airDate, 'air_date' => $airDate,
"status" => $status, 'status' => $status,
]; ];
$this->makeRequest("POST", "scheduled_episodes", ["json" => $payload]); $this->makeRequest('POST', 'scheduled_episodes', ['json' => $payload]);
} }
} }

View file

@ -27,10 +27,12 @@
$redis = new Redis(); $redis = new Redis();
$redis->connect('127.0.0.1', 6379); $redis->connect('127.0.0.1', 6379);
if ($redis->exists($cacheKey)) $js = $redis->get($cacheKey); if ($redis->exists($cacheKey)) {
$js = $redis->get($cacheKey);
}
} }
} catch (Exception $e) { } catch (Exception $e) {
error_log("Redis unavailable: " . $e->getMessage()); error_log('Redis unavailable: '.$e->getMessage());
} }
if (! is_string($js)) { if (! is_string($js)) {
@ -44,7 +46,9 @@
curl_close($ch); curl_close($ch);
if ($redis && $code === 200 && $js) $redis->setex($cacheKey, $ttl, $js); if ($redis && $code === 200 && $js) {
$redis->setex($cacheKey, $ttl, $js);
}
} }
if (! is_string($js) || trim($js) === '') { if (! is_string($js) || trim($js) === '') {
@ -63,7 +67,9 @@
'Accept: application/json', 'Accept: application/json',
]; ];
if (isset($_SERVER['HTTP_USER_AGENT'])) $headers[] = 'User-Agent: ' . $_SERVER['HTTP_USER_AGENT']; if (isset($_SERVER['HTTP_USER_AGENT'])) {
$headers[] = 'User-Agent: '.$_SERVER['HTTP_USER_AGENT'];
}
$ch = curl_init($targetUrl); $ch = curl_init($targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@ -72,9 +78,11 @@
$body = file_get_contents('php://input'); $body = file_get_contents('php://input');
$data = json_decode($body, true); $data = json_decode($body, true);
if (strpos($forwardPath, '/api/send') === 0 && is_array($data)) $data['payload'] = array_merge($data['payload'] ?? [], [ if (strpos($forwardPath, '/api/send') === 0 && is_array($data)) {
$data['payload'] = array_merge($data['payload'] ?? [], [
'ip' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0', 'ip' => $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0',
]); ]);
}
curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
@ -90,6 +98,8 @@
curl_close($ch); curl_close($ch);
http_response_code($httpCode); http_response_code($httpCode);
if ($contentType) header("Content-Type: $contentType"); if ($contentType) {
header("Content-Type: $contentType");
}
echo $response ?: ''; echo $response ?: '';

View file

@ -8,6 +8,7 @@ use GuzzleHttp\Client;
class WatchingImportHandler extends ApiHandler class WatchingImportHandler extends ApiHandler
{ {
private string $tmdbApiKey; private string $tmdbApiKey;
private string $tmdbImportToken; private string $tmdbImportToken;
public function __construct() public function __construct()
@ -15,34 +16,36 @@ class WatchingImportHandler extends ApiHandler
parent::__construct(); parent::__construct();
$this->ensureCliAccess(); $this->ensureCliAccess();
$this->tmdbApiKey = $_ENV["TMDB_API_KEY"] ?? getenv("TMDB_API_KEY"); $this->tmdbApiKey = $_ENV['TMDB_API_KEY'] ?? getenv('TMDB_API_KEY');
$this->tmdbImportToken = $_ENV["WATCHING_IMPORT_TOKEN"] ?? getenv("WATCHING_IMPORT_TOKEN"); $this->tmdbImportToken = $_ENV['WATCHING_IMPORT_TOKEN'] ?? getenv('WATCHING_IMPORT_TOKEN');
} }
public function handleRequest(): void public function handleRequest(): void
{ {
$input = json_decode(file_get_contents("php://input"), true); $input = json_decode(file_get_contents('php://input'), true);
if (!$input) $this->sendErrorResponse("Invalid or missing JSON body", 400); if (! $input) {
$this->sendErrorResponse('Invalid or missing JSON body', 400);
}
$providedToken = $input["token"] ?? null; $providedToken = $input['token'] ?? null;
$tmdbId = $input["tmdb_id"] ?? null; $tmdbId = $input['tmdb_id'] ?? null;
$mediaType = $input["media_type"] ?? null; $mediaType = $input['media_type'] ?? null;
if ($providedToken !== $this->tmdbImportToken) { if ($providedToken !== $this->tmdbImportToken) {
$this->sendErrorResponse("Unauthorized access", 401); $this->sendErrorResponse('Unauthorized access', 401);
} }
if (! $tmdbId || ! $mediaType) { if (! $tmdbId || ! $mediaType) {
$this->sendErrorResponse("tmdb_id and media_type are required", 400); $this->sendErrorResponse('tmdb_id and media_type are required', 400);
} }
try { try {
$mediaData = $this->fetchTMDBData($tmdbId, $mediaType); $mediaData = $this->fetchTMDBData($tmdbId, $mediaType);
$this->processMedia($mediaData, $mediaType); $this->processMedia($mediaData, $mediaType);
$this->sendResponse(["message" => "Media imported successfully"], 200); $this->sendResponse(['message' => 'Media imported successfully'], 200);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->sendErrorResponse("Error: " . $e->getMessage(), 500); $this->sendErrorResponse('Error: '.$e->getMessage(), 500);
} }
} }
@ -52,49 +55,55 @@ class WatchingImportHandler extends ApiHandler
$url = "https://api.themoviedb.org/3/{$mediaType}/{$tmdbId}"; $url = "https://api.themoviedb.org/3/{$mediaType}/{$tmdbId}";
$response = $client->get($url, [ $response = $client->get($url, [
"query" => ["api_key" => $this->tmdbApiKey], 'query' => ['api_key' => $this->tmdbApiKey],
"headers" => ["Accept" => "application/json"], 'headers' => ['Accept' => 'application/json'],
]); ]);
$data = json_decode($response->getBody(), true); $data = json_decode($response->getBody(), true);
if (empty($data)) throw new \Exception("No data found for TMDB ID: {$tmdbId}"); if (empty($data)) {
throw new \Exception("No data found for TMDB ID: {$tmdbId}");
}
return $data; return $data;
} }
private function processMedia(array $mediaData, string $mediaType): void private function processMedia(array $mediaData, string $mediaType): void
{ {
$tagline = $mediaData["tagline"] ?? null; $tagline = $mediaData['tagline'] ?? null;
$overview = $mediaData["overview"] ?? null; $overview = $mediaData['overview'] ?? null;
$description = ""; $description = '';
if (!empty($tagline)) $description .= "> " . trim($tagline) . "\n\n"; if (! empty($tagline)) {
if (!empty($overview)) $description .= trim($overview); $description .= '> '.trim($tagline)."\n\n";
}
if (! empty($overview)) {
$description .= trim($overview);
}
$id = $mediaData["id"]; $id = $mediaData['id'];
$title = $mediaType === "movie" ? $mediaData["title"] : $mediaData["name"]; $title = $mediaType === 'movie' ? $mediaData['title'] : $mediaData['name'];
$year = $mediaData["release_date"] ?? $mediaData["first_air_date"] ?? null; $year = $mediaData['release_date'] ?? $mediaData['first_air_date'] ?? null;
$year = $year ? substr($year, 0, 4) : null; $year = $year ? substr($year, 0, 4) : null;
$tags = array_map( $tags = array_map(
fn($genre) => strtolower(trim($genre["name"])), fn ($genre) => strtolower(trim($genre['name'])),
$mediaData["genres"] ?? [] $mediaData['genres'] ?? []
); );
$slug = $mediaType === "movie" $slug = $mediaType === 'movie'
? "/watching/movies/{$id}" ? "/watching/movies/{$id}"
: "/watching/shows/{$id}"; : "/watching/shows/{$id}";
$payload = [ $payload = [
"title" => $title, 'title' => $title,
"year" => $year, 'year' => $year,
"description" => $description, 'description' => $description,
"tmdb_id" => $id, 'tmdb_id' => $id,
"slug" => $slug, 'slug' => $slug,
]; ];
$table = $mediaType === "movie" ? "movies" : "shows"; $table = $mediaType === 'movie' ? 'movies' : 'shows';
try { try {
$response = $this->makeRequest("POST", $table, [ $response = $this->makeRequest('POST', $table, [
"json" => $payload, 'json' => $payload,
"headers" => ["Prefer" => "return=representation"] 'headers' => ['Prefer' => 'return=representation'],
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$response = $this->fetchFromApi($table, "tmdb_id=eq.{$id}")[0] ?? []; $response = $this->fetchFromApi($table, "tmdb_id=eq.{$id}")[0] ?? [];
@ -102,10 +111,12 @@ class WatchingImportHandler extends ApiHandler
$record = $response[0] ?? []; $record = $response[0] ?? [];
if (!empty($record["id"])) { if (! empty($record['id'])) {
$mediaId = $record["id"]; $mediaId = $record['id'];
$tagIds = $this->getTagIds($tags); $tagIds = $this->getTagIds($tags);
if (!empty($tagIds)) $this->associateTagsWithMedia($mediaType, $mediaId, array_values($tagIds)); if (! empty($tagIds)) {
$this->associateTagsWithMedia($mediaType, $mediaId, array_values($tagIds));
}
} }
} }
@ -114,9 +125,9 @@ class WatchingImportHandler extends ApiHandler
$map = []; $map = [];
foreach ($tags as $tag) { foreach ($tags as $tag) {
$response = $this->fetchFromApi("tags", "name=ilike." . urlencode($tag)); $response = $this->fetchFromApi('tags', 'name=ilike.'.urlencode($tag));
if (!empty($response[0]["id"])) { if (! empty($response[0]['id'])) {
$map[strtolower($tag)] = $response[0]["id"]; $map[strtolower($tag)] = $response[0]['id'];
} }
} }
@ -125,13 +136,13 @@ class WatchingImportHandler extends ApiHandler
private function associateTagsWithMedia(string $mediaType, int $mediaId, array $tagIds): void private function associateTagsWithMedia(string $mediaType, int $mediaId, array $tagIds): void
{ {
$junction = $mediaType === "movie" ? "movies_tags" : "shows_tags"; $junction = $mediaType === 'movie' ? 'movies_tags' : 'shows_tags';
$mediaColumn = $mediaType === "movie" ? "movies_id" : "shows_id"; $mediaColumn = $mediaType === 'movie' ? 'movies_id' : 'shows_id';
foreach ($tagIds as $tagId) { foreach ($tagIds as $tagId) {
$this->makeRequest("POST", $junction, ["json" => [ $this->makeRequest('POST', $junction, ['json' => [
$mediaColumn => $mediaId, $mediaColumn => $mediaId,
"tags_id" => $tagId 'tags_id' => $tagId,
]]); ]]);
} }
} }

View file

@ -6,6 +6,8 @@
{ {
protected function ensureCliAccess(): void protected function ensureCliAccess(): void
{ {
if (php_sapi_name() !== 'cli' && $_SERVER['REQUEST_METHOD'] !== 'POST') redirectTo404(); if (php_sapi_name() !== 'cli' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
redirectTo404();
}
} }
} }

View file

@ -6,14 +6,18 @@
{ {
public function fetch(string $url): ?array public function fetch(string $url): ?array
{ {
$cacheKey = "artist_" . md5($url); $cacheKey = 'artist_'.md5($url);
$cached = $this->cacheGet($cacheKey); $cached = $this->cacheGet($cacheKey);
if ($cached) return $cached; if ($cached) {
return $cached;
}
$artist = $this->fetchSingleFromApi("optimized_artists", $url); $artist = $this->fetchSingleFromApi('optimized_artists', $url);
if (!$artist) return null; if (! $artist) {
return null;
}
$artist['globals'] = $this->getGlobals(); $artist['globals'] = $this->getGlobals();

View file

@ -8,7 +8,9 @@
abstract class BaseHandler abstract class BaseHandler
{ {
protected string $postgrestUrl; protected string $postgrestUrl;
protected string $postgrestApiKey; protected string $postgrestApiKey;
protected ?\Redis $cache = null; protected ?\Redis $cache = null;
public function __construct() public function __construct()
@ -19,25 +21,25 @@
private function loadEnvironment(): void private function loadEnvironment(): void
{ {
$this->postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL") ?? ""; $this->postgrestUrl = $_ENV['POSTGREST_URL'] ?? getenv('POSTGREST_URL') ?? '';
$this->postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY") ?? ""; $this->postgrestApiKey = $_ENV['POSTGREST_API_KEY'] ?? getenv('POSTGREST_API_KEY') ?? '';
} }
protected function initializeCache(): void protected function initializeCache(): void
{ {
if (class_exists("Redis")) { if (class_exists('Redis')) {
try { try {
$redis = new \Redis(); $redis = new \Redis();
$redis->connect("127.0.0.1", 6379); $redis->connect('127.0.0.1', 6379);
$this->cache = $redis; $this->cache = $redis;
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("Redis connection failed: " . $e->getMessage()); error_log('Redis connection failed: '.$e->getMessage());
$this->cache = null; $this->cache = null;
} }
} else { } else {
error_log("Redis extension not found — caching disabled."); error_log('Redis extension not found — caching disabled.');
$this->cache = null; $this->cache = null;
} }
@ -46,23 +48,27 @@
protected function makeRequest(string $method, string $endpoint, array $options = []): array protected function makeRequest(string $method, string $endpoint, array $options = []): array
{ {
$client = new Client(); $client = new Client();
$url = rtrim($this->postgrestUrl, "/") . "/" . ltrim($endpoint, "/"); $url = rtrim($this->postgrestUrl, '/').'/'.ltrim($endpoint, '/');
try { try {
$response = $client->request($method, $url, array_merge_recursive([ $response = $client->request($method, $url, array_merge_recursive([
"headers" => [ 'headers' => [
"Authorization" => "Bearer {$this->postgrestApiKey}", 'Authorization' => "Bearer {$this->postgrestApiKey}",
"Content-Type" => "application/json", 'Content-Type' => 'application/json',
] ],
], $options)); ], $options));
$responseBody = $response->getBody()->getContents(); $responseBody = $response->getBody()->getContents();
if (empty($responseBody)) return []; if (empty($responseBody)) {
return [];
}
$data = json_decode($responseBody, true); $data = json_decode($responseBody, true);
if (json_last_error() !== JSON_ERROR_NONE) throw new \Exception("Invalid JSON: " . json_last_error_msg()); if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception('Invalid JSON: '.json_last_error_msg());
}
return $data; return $data;
} catch (RequestException $e) { } catch (RequestException $e) {
@ -72,21 +78,21 @@
throw new \Exception("HTTP {$method} {$url} failed with status {$statusCode}: {$responseBody}"); throw new \Exception("HTTP {$method} {$url} failed with status {$statusCode}: {$responseBody}");
} catch (\Exception $e) { } catch (\Exception $e) {
throw new \Exception("Request error: " . $e->getMessage()); throw new \Exception('Request error: '.$e->getMessage());
} }
} }
protected function fetchFromApi(string $endpoint, string $query = ""): array protected function fetchFromApi(string $endpoint, string $query = ''): array
{ {
$url = $endpoint . ($query ? "?{$query}" : ""); $url = $endpoint.($query ? "?{$query}" : '');
return $this->makeRequest("GET", $url); return $this->makeRequest('GET', $url);
} }
protected function sendResponse(array $data, int $statusCode = 200): void protected function sendResponse(array $data, int $statusCode = 200): void
{ {
http_response_code($statusCode); http_response_code($statusCode);
header("Content-Type: application/json"); header('Content-Type: application/json');
echo json_encode($data); echo json_encode($data);
@ -95,6 +101,6 @@
protected function sendErrorResponse(string $message, int $statusCode = 500): void protected function sendErrorResponse(string $message, int $statusCode = 500): void
{ {
$this->sendResponse(["error" => $message], $statusCode); $this->sendResponse(['error' => $message], $statusCode);
} }
} }

View file

@ -6,14 +6,18 @@
{ {
public function fetch(string $url): ?array public function fetch(string $url): ?array
{ {
$cacheKey = "book_" . md5($url); $cacheKey = 'book_'.md5($url);
$cached = $this->cacheGet($cacheKey); $cached = $this->cacheGet($cacheKey);
if ($cached) return $cached; if ($cached) {
return $cached;
}
$book = $this->fetchSingleFromApi("optimized_books", $url); $book = $this->fetchSingleFromApi('optimized_books', $url);
if (!$book) return null; if (! $book) {
return null;
}
$book['globals'] = $this->getGlobals(); $book['globals'] = $this->getGlobals();

View file

@ -6,14 +6,18 @@
{ {
public function fetch(string $url): ?array public function fetch(string $url): ?array
{ {
$cacheKey = "genre_" . md5($url); $cacheKey = 'genre_'.md5($url);
$cached = $this->cacheGet($cacheKey); $cached = $this->cacheGet($cacheKey);
if ($cached) return $cached; if ($cached) {
return $cached;
}
$genre = $this->fetchSingleFromApi("optimized_genres", $url); $genre = $this->fetchSingleFromApi('optimized_genres', $url);
if (!$genre) return null; if (! $genre) {
return null;
}
$genre['globals'] = $this->getGlobals(); $genre['globals'] = $this->getGlobals();

View file

@ -6,14 +6,18 @@
{ {
public function fetch(): ?array public function fetch(): ?array
{ {
$cacheKey = "globals"; $cacheKey = 'globals';
$cached = $this->cacheGet($cacheKey); $cached = $this->cacheGet($cacheKey);
if ($cached) return $cached; if ($cached) {
return $cached;
}
$globals = $this->fetchFromApi("optimized_globals"); $globals = $this->fetchFromApi('optimized_globals');
if (empty($globals)) return null; if (empty($globals)) {
return null;
}
$this->cacheSet($cacheKey, $globals[0]); $this->cacheSet($cacheKey, $globals[0]);

View file

@ -2,8 +2,6 @@
namespace App\Classes; namespace App\Classes;
use App\Classes\BaseHandler;
class LatestListenHandler extends BaseHandler class LatestListenHandler extends BaseHandler
{ {
protected int $cacheTTL = 60; protected int $cacheTTL = 60;
@ -19,7 +17,7 @@ class LatestListenHandler extends BaseHandler
$data = $this->getLatestListen(); $data = $this->getLatestListen();
if (! $data) { if (! $data) {
$this->sendResponse(["message" => "No recent tracks found"], 404); $this->sendResponse(['message' => 'No recent tracks found'], 404);
return; return;
} }
@ -30,34 +28,41 @@ class LatestListenHandler extends BaseHandler
public function getLatestListen(): ?array public function getLatestListen(): ?array
{ {
try { try {
$cachedData = $this->cache ? $this->cache->get("latest_listen") : null; $cachedData = $this->cache ? $this->cache->get('latest_listen') : null;
if ($cachedData) return json_decode($cachedData, true); if ($cachedData) {
return json_decode($cachedData, true);
}
$data = $this->makeRequest("GET", "optimized_latest_listen?select=*"); $data = $this->makeRequest('GET', 'optimized_latest_listen?select=*');
if (!is_array($data) || empty($data[0])) return null; if (! is_array($data) || empty($data[0])) {
return null;
}
$latestListen = $this->formatLatestListen($data[0]); $latestListen = $this->formatLatestListen($data[0]);
if ($this->cache) $this->cache->set("latest_listen", json_encode($latestListen), $this->cacheTTL); if ($this->cache) {
$this->cache->set('latest_listen', json_encode($latestListen), $this->cacheTTL);
}
return $latestListen; return $latestListen;
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("LatestListenHandler::getLatestListen error: " . $e->getMessage()); error_log('LatestListenHandler::getLatestListen error: '.$e->getMessage());
return null; return null;
} }
} }
private function formatLatestListen(array $latestListen): array private function formatLatestListen(array $latestListen): array
{ {
$emoji = $latestListen["artist_emoji"] ?? ($latestListen["genre_emoji"] ?? "🎧"); $emoji = $latestListen['artist_emoji'] ?? ($latestListen['genre_emoji'] ?? '🎧');
$trackName = htmlspecialchars($latestListen["track_name"] ?? "Unknown Track", ENT_QUOTES, "UTF-8"); $trackName = htmlspecialchars($latestListen['track_name'] ?? 'Unknown Track', ENT_QUOTES, 'UTF-8');
$artistName = htmlspecialchars($latestListen["artist_name"] ?? "Unknown Artist", ENT_QUOTES, "UTF-8"); $artistName = htmlspecialchars($latestListen['artist_name'] ?? 'Unknown Artist', ENT_QUOTES, 'UTF-8');
$url = htmlspecialchars($latestListen["url"] ?? "/", ENT_QUOTES, "UTF-8"); $url = htmlspecialchars($latestListen['url'] ?? '/', ENT_QUOTES, 'UTF-8');
return [ return [
"content" => sprintf( 'content' => sprintf(
'%s %s by <a href="%s">%s</a>', '%s %s by <a href="%s">%s</a>',
$emoji, $emoji,
$trackName, $trackName,

View file

@ -6,14 +6,18 @@
{ {
public function fetch(string $url): ?array public function fetch(string $url): ?array
{ {
$cacheKey = "movie_" . md5($url); $cacheKey = 'movie_'.md5($url);
$cached = $this->cacheGet($cacheKey); $cached = $this->cacheGet($cacheKey);
if ($cached) return $cached; if ($cached) {
return $cached;
}
$movie = $this->fetchSingleFromApi("optimized_movies", $url); $movie = $this->fetchSingleFromApi('optimized_movies', $url);
if (!$movie) return null; if (! $movie) {
return null;
}
$movie['globals'] = $this->getGlobals(); $movie['globals'] = $this->getGlobals();

View file

@ -11,7 +11,9 @@ class MusicDataHandler extends BaseHandler
$cacheKey = 'music_week_data'; $cacheKey = 'music_week_data';
$cached = $this->cache ? $this->cache->get($cacheKey) : null; $cached = $this->cache ? $this->cache->get($cacheKey) : null;
if ($cached) return json_decode($cached, true); if ($cached) {
return json_decode($cached, true);
}
$response = $this->makeRequest('GET', 'optimized_week_music?select=*'); $response = $this->makeRequest('GET', 'optimized_week_music?select=*');
$music = $response[0]['week_music'] ?? []; $music = $response[0]['week_music'] ?? [];
@ -19,7 +21,9 @@ class MusicDataHandler extends BaseHandler
$music['total_artists'] = $music['week_summary']['total_artists'] ?? 0; $music['total_artists'] = $music['week_summary']['total_artists'] ?? 0;
$music['total_albums'] = $music['week_summary']['total_albums'] ?? 0; $music['total_albums'] = $music['week_summary']['total_albums'] ?? 0;
if ($this->cache) $this->cache->set($cacheKey, json_encode($music), $this->cacheTTL); if ($this->cache) {
$this->cache->set($cacheKey, json_encode($music), $this->cacheTTL);
}
return $music; return $music;
} }

View file

@ -2,9 +2,6 @@
namespace App\Classes; namespace App\Classes;
use App\Classes\BaseHandler;
use App\Classes\GlobalsFetcher;
abstract class PageFetcher extends BaseHandler abstract class PageFetcher extends BaseHandler
{ {
protected ?array $globals = null; protected ?array $globals = null;
@ -16,7 +13,9 @@ abstract class PageFetcher extends BaseHandler
protected function cacheSet(string $key, mixed $value, int $ttl = 300): void protected function cacheSet(string $key, mixed $value, int $ttl = 300): void
{ {
if ($this->cache) $this->cache->setex($key, $ttl, json_encode($value)); if ($this->cache) {
$this->cache->setex($key, $ttl, json_encode($value));
}
} }
protected function fetchSingleFromApi(string $endpoint, string $url): ?array protected function fetchSingleFromApi(string $endpoint, string $url): ?array
@ -28,12 +27,14 @@ abstract class PageFetcher extends BaseHandler
protected function fetchPostRpc(string $endpoint, array $body): ?array protected function fetchPostRpc(string $endpoint, array $body): ?array
{ {
return $this->makeRequest("POST", $endpoint, ['json' => $body]); return $this->makeRequest('POST', $endpoint, ['json' => $body]);
} }
public function getGlobals(): ?array public function getGlobals(): ?array
{ {
if ($this->globals !== null) return $this->globals; if ($this->globals !== null) {
return $this->globals;
}
$fetcher = new GlobalsFetcher(); $fetcher = new GlobalsFetcher();

View file

@ -14,21 +14,25 @@ class RecentMediaHandler extends BaseHandler
if ($this->cache) { if ($this->cache) {
$cached = $this->cache->get($cacheKey); $cached = $this->cache->get($cacheKey);
if ($cached) return json_decode($cached, true); if ($cached) {
return json_decode($cached, true);
}
} }
$response = $this->makeRequest("GET", "optimized_recent_media?select=*"); $response = $this->makeRequest('GET', 'optimized_recent_media?select=*');
$activity = $response[0]['recent_activity'] ?? []; $activity = $response[0]['recent_activity'] ?? [];
$data = [ $data = [
'recentMusic' => $activity['recentMusic'] ?? [], 'recentMusic' => $activity['recentMusic'] ?? [],
'recentWatchedRead' => $activity['recentWatchedRead'] ?? [], 'recentWatchedRead' => $activity['recentWatchedRead'] ?? [],
]; ];
if ($this->cache) $this->cache->set($cacheKey, json_encode($data), $this->cacheTTL); if ($this->cache) {
$this->cache->set($cacheKey, json_encode($data), $this->cacheTTL);
}
return $data; return $data;
} catch (\Exception $e) { } catch (\Exception $e) {
error_log("RecentMediaHandler error: " . $e->getMessage()); error_log('RecentMediaHandler error: '.$e->getMessage());
return ['recentMusic' => [], 'recentWatchedRead' => []]; return ['recentMusic' => [], 'recentWatchedRead' => []];
} }

View file

@ -6,14 +6,18 @@
{ {
public function fetch(string $url): ?array public function fetch(string $url): ?array
{ {
$cacheKey = "show_" . md5($url); $cacheKey = 'show_'.md5($url);
$cached = $this->cacheGet($cacheKey); $cached = $this->cacheGet($cacheKey);
if ($cached) return $cached; if ($cached) {
return $cached;
}
$show = $this->fetchSingleFromApi("optimized_shows", $url); $show = $this->fetchSingleFromApi('optimized_shows', $url);
if (!$show) return null; if (! $show) {
return null;
}
$show['globals'] = $this->getGlobals(); $show['globals'] = $this->getGlobals();

View file

@ -7,18 +7,22 @@ class TagFetcher extends PageFetcher
public function fetch(string $tag, int $page = 1, int $pageSize = 20): ?array public function fetch(string $tag, int $page = 1, int $pageSize = 20): ?array
{ {
$offset = ($page - 1) * $pageSize; $offset = ($page - 1) * $pageSize;
$cacheKey = "tag_" . md5("{$tag}_{$page}"); $cacheKey = 'tag_'.md5("{$tag}_{$page}");
$cached = $this->cacheGet($cacheKey); $cached = $this->cacheGet($cacheKey);
if ($cached) return $cached; if ($cached) {
return $cached;
}
$results = $this->fetchPostRpc("rpc/get_tagged_content", [ $results = $this->fetchPostRpc('rpc/get_tagged_content', [
"tag_query" => $tag, 'tag_query' => $tag,
"page_size" => $pageSize, 'page_size' => $pageSize,
"page_offset" => $offset 'page_offset' => $offset,
]); ]);
if (!$results || count($results) === 0) return null; if (! $results || count($results) === 0) {
return null;
}
$results[0]['globals'] = $this->getGlobals(); $results[0]['globals'] = $this->getGlobals();

View file

@ -12,7 +12,7 @@
'headphones' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-headphones"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 13m0 2a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2z" /><path d="M15 13m0 2a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2z" /><path d="M4 15v-3a8 8 0 0 1 16 0v3" /></svg>', 'headphones' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-headphones"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 13m0 2a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2z" /><path d="M15 13m0 2a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v3a2 2 0 0 1 -2 2h-1a2 2 0 0 1 -2 -2z" /><path d="M4 15v-3a8 8 0 0 1 16 0v3" /></svg>',
'movie' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-movie"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z" /><path d="M8 4l0 16" /><path d="M16 4l0 16" /><path d="M4 8l4 0" /><path d="M4 16l4 0" /><path d="M4 12l16 0" /><path d="M16 8l4 0" /><path d="M16 16l4 0" /></svg>', 'movie' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-movie"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z" /><path d="M8 4l0 16" /><path d="M16 4l0 16" /><path d="M4 8l4 0" /><path d="M4 16l4 0" /><path d="M4 12l16 0" /><path d="M16 8l4 0" /><path d="M16 16l4 0" /></svg>',
'star' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-star"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 17.75l-6.172 3.245l1.179 -6.873l-5 -4.867l6.9 -1l3.086 -6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z" /></svg>', 'star' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-star"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 17.75l-6.172 3.245l1.179 -6.873l-5 -4.867l6.9 -1l3.086 -6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z" /></svg>',
'vinyl' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-vinyl"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M16 3.937a9 9 0 1 0 5 8.063" /><path d="M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" /><path d="M20 4m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" /><path d="M20 4l-3.5 10l-2.5 2" /></svg>' 'vinyl' => '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-vinyl"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M16 3.937a9 9 0 1 0 5 8.063" /><path d="M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" /><path d="M20 4m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" /><path d="M20 4l-3.5 10l-2.5 2" /></svg>',
]; ];
return $icons[$iconName] ?? '<span class="icon-placeholder">[Missing: '.htmlspecialchars($iconName).']</span>'; return $icons[$iconName] ?? '<span class="icon-placeholder">[Missing: '.htmlspecialchars($iconName).']</span>';

View file

@ -1,4 +1,5 @@
<?php <?php
require_once __DIR__.'/icons.php'; require_once __DIR__.'/icons.php';
require_once __DIR__.'/media.php'; require_once __DIR__.'/media.php';
require_once __DIR__.'/metadata.php'; require_once __DIR__.'/metadata.php';

View file

@ -30,8 +30,12 @@
if ($title || $subtext) { if ($title || $subtext) {
echo '<div class="meta-text media-highlight">'; echo '<div class="meta-text media-highlight">';
if ($title) echo '<div class="header">' . $title . '</div>'; if ($title) {
if ($subtext) echo '<div class="subheader">' . $subtext . '</div>'; echo '<div class="header">'.$title.'</div>';
}
if ($subtext) {
echo '<div class="subheader">'.$subtext.'</div>';
}
echo '</div>'; echo '</div>';
} }
@ -62,15 +66,14 @@
array $movies = [], array $movies = [],
array $posts = [], array $posts = [],
array $shows = [], array $shows = [],
) ) {
{
$sections = [ $sections = [
"artists" => ["icon" => "headphones", "css_class" => "music", "label" => "Related artist(s)", "hasGrid" => true], 'artists' => ['icon' => 'headphones', 'css_class' => 'music', 'label' => 'Related artist(s)', 'hasGrid' => true],
"books" => ["icon" => "books", "css_class" => "books", "label" => "Related book(s)", "hasGrid" => true], 'books' => ['icon' => 'books', 'css_class' => 'books', 'label' => 'Related book(s)', 'hasGrid' => true],
"genres" => ["icon" => "headphones", "css_class" => "music", "label" => "Related genre(s)", "hasGrid" => false], 'genres' => ['icon' => 'headphones', 'css_class' => 'music', 'label' => 'Related genre(s)', 'hasGrid' => false],
"movies" => ["icon" => "movie", "css_class" => "movies", "label" => "Related movie(s)", "hasGrid" => true], 'movies' => ['icon' => 'movie', 'css_class' => 'movies', 'label' => 'Related movie(s)', 'hasGrid' => true],
"posts" => ["icon" => "article", "css_class" => "article", "label" => "Related post(s)", "hasGrid" => false], 'posts' => ['icon' => 'article', 'css_class' => 'article', 'label' => 'Related post(s)', 'hasGrid' => false],
"shows" => ["icon" => "device-tv-old", "css_class" => "tv", "label" => "Related show(s)", "hasGrid" => true] 'shows' => ['icon' => 'device-tv-old', 'css_class' => 'tv', 'label' => 'Related show(s)', 'hasGrid' => true],
]; ];
$allMedia = compact('artists', 'books', 'genres', 'movies', 'posts', 'shows'); $allMedia = compact('artists', 'books', 'genres', 'movies', 'posts', 'shows');
@ -80,7 +83,9 @@
foreach ($sections as $key => $section) { foreach ($sections as $key => $section) {
$items = $allMedia[$key]; $items = $allMedia[$key];
if (empty($items)) continue; if (empty($items)) {
continue;
}
echo '<h3 id="'.htmlspecialchars($key).'" class="'.htmlspecialchars($section['css_class']).'">'; echo '<h3 id="'.htmlspecialchars($key).'" class="'.htmlspecialchars($section['css_class']).'">';
echo getTablerIcon($section['icon']); echo getTablerIcon($section['icon']);
@ -95,14 +100,14 @@
echo '<li class="'.htmlspecialchars($section['css_class']).'">'; echo '<li class="'.htmlspecialchars($section['css_class']).'">';
echo '<a href="'.htmlspecialchars($item['url']).'">'.htmlspecialchars($item['title'] ?? $item['name'] ?? '').'</a>'; echo '<a href="'.htmlspecialchars($item['url']).'">'.htmlspecialchars($item['title'] ?? $item['name'] ?? '').'</a>';
if ($key === "artists" && isset($item['total_plays']) && $item['total_plays'] > 0) { if ($key === 'artists' && isset($item['total_plays']) && $item['total_plays'] > 0) {
echo ' ('.htmlspecialchars($item['total_plays']).' play'.($item['total_plays'] > 1 ? 's' : '').')'; echo ' ('.htmlspecialchars($item['total_plays']).' play'.($item['total_plays'] > 1 ? 's' : '').')';
} elseif ($key === "books" && isset($item['author'])) { } elseif ($key === 'books' && isset($item['author'])) {
echo ' by '.htmlspecialchars($item['author']); echo ' by '.htmlspecialchars($item['author']);
} elseif (($key === "movies" || $key === "shows") && isset($item['year'])) { } elseif (($key === 'movies' || $key === 'shows') && isset($item['year'])) {
echo ' ('.htmlspecialchars($item['year']).')'; echo ' ('.htmlspecialchars($item['year']).')';
} elseif ($key === "posts" && isset($item['date'])) { } elseif ($key === 'posts' && isset($item['date'])) {
echo ' (' . date("F j, Y", strtotime($item['date'])) . ')'; echo ' ('.date('F j, Y', strtotime($item['date'])).')';
} }
echo '</li>'; echo '</li>';
@ -116,30 +121,38 @@
} }
if (! function_exists('renderMediaLinks')) { if (! function_exists('renderMediaLinks')) {
function renderMediaLinks(array $data, string $type, int $count = 10): string { function renderMediaLinks(array $data, string $type, int $count = 10): string
if (empty($data) || empty($type)) return ""; {
if (empty($data) || empty($type)) {
return '';
}
$slice = array_slice($data, 0, $count); $slice = array_slice($data, 0, $count);
if (count($slice) === 0) return ""; if (count($slice) === 0) {
return '';
}
$buildLink = function ($item) use ($type) { $buildLink = function ($item) use ($type) {
switch ($type) { switch ($type) {
case "genre": case 'genre':
return '<a href="'.htmlspecialchars($item['genre_url']).'">'.htmlspecialchars($item['genre_name']).'</a>'; return '<a href="'.htmlspecialchars($item['genre_url']).'">'.htmlspecialchars($item['genre_name']).'</a>';
case "artist": case 'artist':
return '<a href="'.htmlspecialchars($item['url']).'">'.htmlspecialchars($item['name']).'</a>'; return '<a href="'.htmlspecialchars($item['url']).'">'.htmlspecialchars($item['name']).'</a>';
case "book": case 'book':
return '<a href="'.htmlspecialchars($item['url']).'">'.htmlspecialchars($item['title']).'</a>'; return '<a href="'.htmlspecialchars($item['url']).'">'.htmlspecialchars($item['title']).'</a>';
default: default:
return ''; return '';
} }
}; };
if (count($slice) === 1) return $buildLink($slice[0]); if (count($slice) === 1) {
return $buildLink($slice[0]);
}
$links = array_map($buildLink, $slice); $links = array_map($buildLink, $slice);
$last = array_pop($links); $last = array_pop($links);
return implode(', ', $links).' and '.$last; return implode(', ', $links).' and '.$last;
} }
} }
@ -147,8 +160,8 @@
if (! function_exists('sanitizeMediaString')) { if (! function_exists('sanitizeMediaString')) {
function sanitizeMediaString(string $str): string function sanitizeMediaString(string $str): string
{ {
$sanitizedString = preg_replace("/[^a-zA-Z0-9\s-]/", "", iconv("UTF-8", "ASCII//TRANSLIT", $str)); $sanitizedString = preg_replace("/[^a-zA-Z0-9\s-]/", '', iconv('UTF-8', 'ASCII//TRANSLIT', $str));
return strtolower(trim(preg_replace("/[\s-]+/", "-", $sanitizedString), "-")); return strtolower(trim(preg_replace("/[\s-]+/", '-', $sanitizedString), '-'));
} }
} }

View file

@ -5,15 +5,15 @@
{ {
$globals = $page['globals'] ?? []; $globals = $page['globals'] ?? [];
$title = htmlspecialchars($page["metadata"]["title"] ?? "", ENT_QUOTES, "UTF-8"); $title = htmlspecialchars($page['metadata']['title'] ?? '', ENT_QUOTES, 'UTF-8');
$description = htmlspecialchars($page["metadata"]["description"] ?? "", ENT_QUOTES, "UTF-8"); $description = htmlspecialchars($page['metadata']['description'] ?? '', ENT_QUOTES, 'UTF-8');
$image = htmlspecialchars( $image = htmlspecialchars(
$page["metadata"]["open_graph_image"] ?? $globals["metadata"]["open_graph_image"] ?? "", $page['metadata']['open_graph_image'] ?? $globals['metadata']['open_graph_image'] ?? '',
ENT_QUOTES, ENT_QUOTES,
"UTF-8" 'UTF-8'
); );
$fullUrl = $globals["url"] . $requestUri; $fullUrl = $globals['url'].$requestUri;
$oembedUrl = $globals["url"] . "/oembed" . $requestUri; $oembedUrl = $globals['url'].'/oembed'.$requestUri;
return [ return [
'pageTitle' => $title, 'pageTitle' => $title,
@ -21,7 +21,7 @@
'ogImage' => $image, 'ogImage' => $image,
'fullUrl' => $fullUrl, 'fullUrl' => $fullUrl,
'oembedUrl' => $oembedUrl, 'oembedUrl' => $oembedUrl,
'globals' => $globals 'globals' => $globals,
]; ];
} }
} }
@ -32,6 +32,7 @@
$value = trim($value ?? ''); $value = trim($value ?? '');
$value = str_replace(["\r", "\n"], ' ', $value); $value = str_replace(["\r", "\n"], ' ', $value);
$value = preg_replace('/\s+/', ' ', $value); $value = preg_replace('/\s+/', ' ', $value);
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
} }
} }

View file

@ -3,37 +3,39 @@
if (! function_exists('renderPaginator')) { if (! function_exists('renderPaginator')) {
function renderPaginator(array $pagination, int $totalPages): void function renderPaginator(array $pagination, int $totalPages): void
{ {
if (!$pagination || $totalPages <= 1) return; if (! $pagination || $totalPages <= 1) {
return;
}
?> ?>
<script type="module" src="/assets/scripts/components/select-pagination.js" defer></script> <script type="module" src="/assets/scripts/components/select-pagination.js" defer></script>
<nav aria-label="Pagination" class="pagination"> <nav aria-label="Pagination" class="pagination">
<?php if (!empty($pagination['href']['previous'])): ?> <?php if (! empty($pagination['href']['previous'])) { ?>
<a href="<?= $pagination['href']['previous'] ?>" aria-label="Previous page"> <a href="<?= $pagination['href']['previous'] ?>" aria-label="Previous page">
<?= getTablerIcon('arrow-left') ?> <?= getTablerIcon('arrow-left') ?>
</a> </a>
<?php else: ?> <?php } else { ?>
<span><?= getTablerIcon('arrow-left') ?></span> <span><?= getTablerIcon('arrow-left') ?></span>
<?php endif; ?> <?php } ?>
<select-pagination data-base-index="1"> <select-pagination data-base-index="1">
<select class="client-side" aria-label="Page selection"> <select class="client-side" aria-label="Page selection">
<?php foreach ($pagination['pages'] as $i): ?> <?php foreach ($pagination['pages'] as $i) { ?>
<option value="<?= $i ?>" <?= ($pagination['pageNumber'] === $i) ? 'selected' : '' ?>> <option value="<?= $i ?>" <?= ($pagination['pageNumber'] === $i) ? 'selected' : '' ?>>
<?= $i ?> of <?= $totalPages ?> <?= $i ?> of <?= $totalPages ?>
</option> </option>
<?php endforeach; ?> <?php } ?>
</select> </select>
<noscript> <noscript>
<p><span aria-current="page"><?= $pagination['pageNumber'] ?></span> of <?= $totalPages ?></p> <p><span aria-current="page"><?= $pagination['pageNumber'] ?></span> of <?= $totalPages ?></p>
</noscript> </noscript>
</select-pagination> </select-pagination>
<?php if (!empty($pagination['href']['next'])): ?> <?php if (! empty($pagination['href']['next'])) { ?>
<a href="<?= $pagination['href']['next'] ?>" aria-label="Next page"> <a href="<?= $pagination['href']['next'] ?>" aria-label="Next page">
<?= getTablerIcon('arrow-right') ?> <?= getTablerIcon('arrow-right') ?>
</a> </a>
<?php else: ?> <?php } else { ?>
<span><?= getTablerIcon('arrow-right') ?></span> <span><?= getTablerIcon('arrow-right') ?></span>
<?php endif; ?> <?php } ?>
</nav> </nav>
<?php <?php

View file

@ -3,7 +3,7 @@
if (! function_exists('redirectTo404')) { if (! function_exists('redirectTo404')) {
function redirectTo404(): void function redirectTo404(): void
{ {
header("Location: /404/", true, 302); header('Location: /404/', true, 302);
exit(); exit();
} }
} }

View file

@ -4,14 +4,18 @@
use Kaoken\MarkdownIt\Plugins\MarkdownItFootnote; use Kaoken\MarkdownIt\Plugins\MarkdownItFootnote;
if (! function_exists('truncateText')) { if (! function_exists('truncateText')) {
function truncateText($text, $limit = 50, $ellipsis = "...") function truncateText($text, $limit = 50, $ellipsis = '...')
{ {
if (mb_strwidth($text, "UTF-8") <= $limit) return $text; if (mb_strwidth($text, 'UTF-8') <= $limit) {
return $text;
}
$truncated = mb_substr($text, 0, $limit, "UTF-8"); $truncated = mb_substr($text, 0, $limit, 'UTF-8');
$lastSpace = mb_strrpos($truncated, " ", 0, "UTF-8"); $lastSpace = mb_strrpos($truncated, ' ', 0, 'UTF-8');
if ($lastSpace !== false) $truncated = mb_substr($truncated, 0, $lastSpace, "UTF-8"); if ($lastSpace !== false) {
$truncated = mb_substr($truncated, 0, $lastSpace, 'UTF-8');
}
return $truncated.$ellipsis; return $truncated.$ellipsis;
} }
@ -20,11 +24,13 @@
if (! function_exists('parseMarkdown')) { if (! function_exists('parseMarkdown')) {
function parseMarkdown($markdown) function parseMarkdown($markdown)
{ {
if (empty($markdown)) return ''; if (empty($markdown)) {
return '';
}
$md = new MarkdownIt([ $md = new MarkdownIt([
"html" => true, 'html' => true,
"linkify" => true, 'linkify' => true,
]); ]);
$md->plugin(new MarkdownItFootnote()); $md->plugin(new MarkdownItFootnote());
@ -36,7 +42,9 @@
if (! function_exists('parseCountryField')) { if (! function_exists('parseCountryField')) {
function parseCountryField($countryField) function parseCountryField($countryField)
{ {
if (empty($countryField)) return null; if (empty($countryField)) {
return null;
}
$delimiters = [',', '/', '&', ' and ']; $delimiters = [',', '/', '&', ' and '];
$countries = [$countryField]; $countries = [$countryField];
@ -66,7 +74,9 @@
$countries = $isoCodes->getCountries(); $countries = $isoCodes->getCountries();
$country = $countries->getByAlpha2($countryName); $country = $countries->getByAlpha2($countryName);
if ($country) return $country->getName(); if ($country) {
return $country->getName();
}
return ucfirst(strtolower($countryName)); return ucfirst(strtolower($countryName));
} }
@ -75,7 +85,9 @@
if (! function_exists('pluralize')) { if (! function_exists('pluralize')) {
function pluralize($count, $string, $trailing = '') function pluralize($count, $string, $trailing = '')
{ {
if ((int)$count === 1) return $string; if ((int) $count === 1) {
return $string;
}
return $string.'s'.($trailing ? $trailing : ''); return $string.'s'.($trailing ? $trailing : '');
} }

View file

@ -3,7 +3,9 @@
if (! function_exists('renderTags')) { if (! function_exists('renderTags')) {
function renderTags(array $tags): void function renderTags(array $tags): void
{ {
if (empty($tags)) return; if (empty($tags)) {
return;
}
echo '<div class="tags">'; echo '<div class="tags">';

View file

@ -9,10 +9,11 @@
"sokil/php-isocodes": "^4.2", "sokil/php-isocodes": "^4.2",
"sokil/php-isocodes-db-only": "^4.0" "sokil/php-isocodes-db-only": "^4.0"
}, },
"require-dev": {
"laravel/pint": "^1.22"
},
"scripts": { "scripts": {
"start": [ "format:php": "vendor/bin/pint"
"@php -S localhost:8000 -t dist"
]
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

71
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "d44329419cf23b795cc4babc3b019b70", "content-hash": "e9a46ab9eab33e697fc595a420b63325",
"packages": [ "packages": [
{ {
"name": "guzzlehttp/guzzle", "name": "guzzlehttp/guzzle",
@ -754,7 +754,74 @@
"time": "2024-09-25T14:21:43+00:00" "time": "2024-09-25T14:21:43+00:00"
} }
], ],
"packages-dev": [], "packages-dev": [
{
"name": "laravel/pint",
"version": "v1.22.1",
"source": {
"type": "git",
"url": "https://github.com/laravel/pint.git",
"reference": "941d1927c5ca420c22710e98420287169c7bcaf7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/pint/zipball/941d1927c5ca420c22710e98420287169c7bcaf7",
"reference": "941d1927c5ca420c22710e98420287169c7bcaf7",
"shasum": ""
},
"require": {
"ext-json": "*",
"ext-mbstring": "*",
"ext-tokenizer": "*",
"ext-xml": "*",
"php": "^8.2.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.75.0",
"illuminate/view": "^11.44.7",
"larastan/larastan": "^3.4.0",
"laravel-zero/framework": "^11.36.1",
"mockery/mockery": "^1.6.12",
"nunomaduro/termwind": "^2.3.1",
"pestphp/pest": "^2.36.0"
},
"bin": [
"builds/pint"
],
"type": "project",
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Seeders\\": "database/seeders/",
"Database\\Factories\\": "database/factories/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nuno Maduro",
"email": "enunomaduro@gmail.com"
}
],
"description": "An opinionated code formatter for PHP.",
"homepage": "https://laravel.com",
"keywords": [
"format",
"formatter",
"lint",
"linter",
"php"
],
"support": {
"issues": "https://github.com/laravel/pint/issues",
"source": "https://github.com/laravel/pint"
},
"time": "2025-05-08T08:38:12+00:00"
}
],
"aliases": [], "aliases": [],
"minimum-stability": "stable", "minimum-stability": "stable",
"stability-flags": {}, "stability-flags": {},

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "10.1.4", "version": "10.2.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coryd.dev", "name": "coryd.dev",
"version": "10.1.4", "version": "10.2.4",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"minisearch": "^7.1.2", "minisearch": "^7.1.2",

View file

@ -1,6 +1,6 @@
{ {
"name": "coryd.dev", "name": "coryd.dev",
"version": "10.1.4", "version": "10.2.4",
"description": "The source for my personal site. Built using 11ty (and other tools).", "description": "The source for my personal site. Built using 11ty (and other tools).",
"type": "module", "type": "module",
"engines": { "engines": {
@ -13,14 +13,15 @@
"php": "export $(grep -v '^#' .env | xargs) && php -d error_reporting=E_ALL^E_DEPRECATED -S localhost:8080 -t dist", "php": "export $(grep -v '^#' .env | xargs) && php -d error_reporting=E_ALL^E_DEPRECATED -S localhost:8080 -t dist",
"build": "eleventy", "build": "eleventy",
"clean": "rimraf dist .cache", "clean": "rimraf dist .cache",
"format": "npx prettier --write '**/*.{js,ts,json,css,md}'", "format": "npx prettier --write '**/*.{js,ts,json,css,md}' && composer format:php",
"update": "composer update && npm upgrade && npm --prefix cli upgrade && ncu && ncu --cwd cli", "update": "composer update && npm upgrade && npm --prefix cli upgrade && ncu && ncu --cwd cli",
"setup": "sh ./scripts/setup.sh", "setup": "sh ./scripts/setup.sh",
"setup:deploy": "sh ./scripts/setup.sh --deploy", "setup:deploy": "sh ./scripts/setup.sh --deploy",
"prepare": "husky" "prepare": "husky"
}, },
"lint-staged": { "lint-staged": {
"*.{js,json,css,md}": "prettier --write" "*.{js,json,css,md}": "prettier --write",
"*.php": "composer format:php"
}, },
"keywords": [ "keywords": [
"11ty", "11ty",

4
pint.json Normal file
View file

@ -0,0 +1,4 @@
{
"preset": "psr12",
"exclude": ["dist"]
}