protected-resources-list/classes/WebRouter.php

85 lines
2.4 KiB
PHP

<?php
class WebRouter
{
private string $requestBody;
private string $requestedFile;
private string $URI;
public function __construct()
{
$this->requestBody = @file_get_contents('php://input');
$this->requestedFile = dirname(__DIR__) . "/" . $_SERVER["REQUEST_URI"];
$this->URI = $_SERVER["REQUEST_URI"];
}
public function handleRequest(): void
{
@session_start();
try {
if (str_starts_with($this->URI, "/assets") or str_starts_with($this->URI, "/plugins") and str_ends_with($this->URI, ".js")) {
$this->handleAsset();
} elseif (!str_starts_with($this->URI, "/rpc")) {
$this->redirect("/assets/index.html");
} else {
$this->handleJRPC();
}
} finally {
session_write_close();
}
}
private function handleJRPC(): void
{
try {
$request = @json_decode($this->requestBody, true);
if ($request === null) {
throw new RuntimeException("Failed to parse JRPC");
}
foreach (["id", "jsonrpc", "method", "params"] as $param) {
if (!isset($request[$param])) {
throw new RuntimeException("Bad JRPC structure");
}
}
$rpc = new RPC();
$response = $rpc($request["method"], $request["params"]);
header("content-type: application/json");
echo json_encode([
"jsonrpc" => "2.0",
"id" => $request["id"] ?? 0,
"result" => $response
]);
} catch (Error $e) {
http_response_code(500);
echo json_encode([
"jsonrpc" => "2.0",
"id" => $request["id"],
"error" => $e->getMessage()
]);
}
}
private function handleAsset(): void
{
if (!file_exists($this->requestedFile)) {
http_response_code(404);
echo "File not found: " . $this->URI;
} else {
header("content-type: " . mime_content_type($this->requestedFile));
echo file_get_contents($this->requestedFile);
}
}
private function redirect($where): void
{
http_response_code(302);
header("location: " . $where);
}
}