nettsiden/www/door/index.php

93 lines
2.7 KiB
PHP
Raw Permalink Normal View History

<?php
2021-09-04 14:56:48 +02:00
require_once dirname(dirname(__DIR__)) . implode(DIRECTORY_SEPARATOR, ['', 'inc', 'include.php']);
header('Content-Type: application/json');
2021-09-04 14:56:48 +02:00
$door = new \pvv\side\Door($pdo);
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_SERVER["HTTP_AUTHORIZATION"])) {
list($type, $data) = explode(" ", $_SERVER["HTTP_AUTHORIZATION"], 2);
if (strcasecmp($type, "Bearer") == 0) {
if (hash_equals($data, $doorSensorSecret)) {
handleSetState();
} else {
echo '{"status": "error", "message": "Invalid authentication key"}';
die();
}
} else {
echo '{"status": "error", "message": "Invalid authentication method"}';
die();
}
2021-09-04 14:56:48 +02:00
} else {
echo '{"status": "error", "message": "Missing authentication"}';
die();
}
2021-09-04 14:56:48 +02:00
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($_GET["period"])) {
$period = (string)htmlspecialchars($_GET["period"]);
2021-10-11 16:23:18 +02:00
2021-09-04 14:56:48 +02:00
if ($period == "day") {
$startTime = time() - (60*60*24);
} else if ($period == "week") {
$startTime = time() - (60*60*24*7);
} else {
echo '{"status": "error", "message": "Invalid period"}';
die();
}
2021-09-04 14:56:48 +02:00
$lines = $door->getEntriesAfter($startTime);
if (isset($_GET["edgeonly"]) && (bool)htmlspecialchars($_GET["edgeonly"])) {
2021-10-11 16:23:18 +02:00
//Ignore repeats
$lines = getChanges($lines);
}
2021-09-04 14:56:48 +02:00
echo json_encode([
'status' => "OK",
'entries' => $lines
]);
} else {
//Only last entry
$line = (object)$door->getCurrent();
echo json_encode([
'status' => "OK",
'time' => $line->time,
'open' => $line->open
]);
}
}
2021-09-04 14:56:48 +02:00
function handleSetState() {
global $door;
$jsonobj = file_get_contents('php://input');
$event = json_decode($jsonobj);
if ((!isset($event->time)) || (!is_numeric($event->time))) {
echo '{"status": "error", "message": "Invalid timestamp"}';
die();
}
if ((!isset($event->isDoorOpen)) || (!is_bool($event->isDoorOpen))) {
echo '{"status": "error", "message": "Invalid door state"}';
die();
}
2021-09-04 14:56:48 +02:00
$door->createEvent((int)($event->time), (bool)($event->isDoorOpen));
echo '{"status": "OK"}';
2021-10-11 16:23:18 +02:00
}
function getChanges($items) {
$prevState = 2;
$res = [];
foreach($items as $item) {
if ($item["open"] !== $prevState) {
array_push($res, $item);
$prevState = $item["open"];
}
}
return $res;
}