102 lines
2.4 KiB
PHP
102 lines
2.4 KiB
PHP
<?php
|
|
header("Cache-Control: max-age=10, must-revalidate");
|
|
header("Content-Type: text/css");
|
|
|
|
enum SpaceState {
|
|
case Open;
|
|
case Closed;
|
|
case Unknown;
|
|
}
|
|
|
|
const CACHE_KEY = "techinc_spacestate";
|
|
const CACHE_TTL = 10;
|
|
|
|
function getSpaceState() {
|
|
$in_cache = false;
|
|
$spacestate = apcu_fetch(CACHE_KEY, $in_cache);
|
|
|
|
if ($in_cache) {
|
|
return $spacestate;
|
|
}
|
|
|
|
$spacestate = SpaceState::Unknown;
|
|
|
|
$ch = curl_init();
|
|
curl_setopt_array($ch, array(
|
|
CURLOPT_URL => "https://techinc.nl/space/spacestate.json",
|
|
CURLOPT_TIMEOUT => 1,
|
|
CURLOPT_FORBID_REUSE => true,
|
|
CURLOPT_RETURNTRANSFER => true
|
|
));
|
|
|
|
$request = curl_exec($ch);
|
|
|
|
// Request failed either because the server is offline, or it took too long to respond.
|
|
// In that case, just return the default response of Unknown. Also cache this result
|
|
// to make sure we are not hammering the space state endpoint when it failed.
|
|
if ($request === false) {
|
|
apcu_store(CACHE_KEY, $spacestate, CACHE_TTL);
|
|
return $spacestate;
|
|
}
|
|
|
|
// The returned JSON failed to be parsed somehow.
|
|
// This should never happen if the spacestate outputs correct JSON.
|
|
$json = json_decode($request);
|
|
if (is_null($json)) {
|
|
apcu_store(CACHE_KEY, $spacestate, CACHE_TTL);
|
|
return $spacestate;
|
|
}
|
|
|
|
// Retrieve the state from the 'open' key in the JSON. If it does not exist,
|
|
// the space state JSON is incorrect and we don't actually know what the spacestate is.
|
|
$state = $json?->state ?? SpaceState::Unknown;
|
|
if ($state === SpaceState::Unknown) {
|
|
apcu_store(CACHE_KEY, $spacestate, CACHE_TTL);
|
|
return $spacestate;
|
|
}
|
|
|
|
$spacestate = $state?->open ?? SpaceState::Unknown;
|
|
if ($spacestate === SpaceState::Unknown) {
|
|
apcu_store(CACHE_KEY, $spacestate, CACHE_TTL);
|
|
return $spacestate;
|
|
}
|
|
|
|
if ($spacestate) {
|
|
$spacestate = SpaceState::Open;
|
|
} else {
|
|
$spacestate = SpaceState::Closed;
|
|
}
|
|
|
|
apcu_store(CACHE_KEY, $spacestate, CACHE_TTL);
|
|
|
|
return $spacestate;
|
|
}
|
|
|
|
$spaceState = getSpaceState();
|
|
|
|
if ($spaceState !== SpaceState::Unknown) {
|
|
?>
|
|
#p-navigation:before {
|
|
content: " ";
|
|
white-space: pre;
|
|
}
|
|
|
|
<?php if ($spaceState === SpaceState::Open) { ?>
|
|
#p-logo:after {
|
|
content: "OPEN" ;
|
|
border-radius: 3px;
|
|
background: green;
|
|
color: white;
|
|
margin-left: 51px;
|
|
padding: 3px 7px;
|
|
}
|
|
<?php } else if ($spaceState === SpaceState::Closed) { ?>
|
|
#p-logo:after {
|
|
content: "CLOSED" ;
|
|
border-radius: 3px;
|
|
background: red;
|
|
color: white;
|
|
margin-left: 43px;
|
|
padding: 3px 7px;
|
|
}
|
|
<?php } } ?>
|