Files
html/api/blade-poll.php
2026-04-12 22:57:03 +02:00

61 lines
1.9 KiB
PHP

<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
$KEY = "BLADE2026";
$DIR = "/var/www/html/api/blade-tasks";
$k = $_REQUEST["k"] ?? "";
if ($k !== $KEY) { http_response_code(403); die(json_encode(["error"=>"auth"])); }
$action = $_REQUEST["action"] ?? "poll";
if ($action === "poll") {
$next = null;
$pending = 0;
$files = glob("$DIR/task_*.json");
sort($files);
foreach ($files as $f) {
$d = @json_decode(@file_get_contents($f), true);
if (!$d) continue;
if (($d["status"] ?? "") === "pending") {
if (!$next) {
$next = $d;
$next["_file"] = basename($f);
$d["status"] = "dispatched";
$d["dispatched_at"] = date("c");
@file_put_contents($f, json_encode($d, JSON_PRETTY_PRINT));
} else {
$pending++;
}
}
}
echo json_encode(["task"=>$next,"pending"=>$pending]);
exit;
}
if ($action === "done") {
$tf = basename($_REQUEST["file"] ?? "");
$result = $_REQUEST["result"] ?? $_POST["result"] ?? "";
$path = "$DIR/$tf";
if ($tf && file_exists($path)) {
$d = json_decode(file_get_contents($path), true);
$d["status"] = "done";
$d["completed_at"] = date("c");
$d["result"] = substr($result, 0, 2000);
file_put_contents($path, json_encode($d, JSON_PRETTY_PRINT));
echo json_encode(["ok"=>true]);
} else {
echo json_encode(["error"=>"not found"]);
}
exit;
}
// Status
$files = glob("$DIR/task_*.json");
$stats = ["pending"=>0,"dispatched"=>0,"done"=>0,"total"=>count($files)];
foreach ($files as $f) {
$d = @json_decode(@file_get_contents($f), true);
$s = $d["status"] ?? "?";
if (isset($stats[$s])) $stats[$s]++;
}
$hb = @json_decode(@file_get_contents("$DIR/heartbeat.json"), true);
echo json_encode(["stats"=>$stats,"heartbeat"=>$hb]);