ccchh-website/themes/ccchh/assets/js/roomstate.js
dario 8a66b0a361
All checks were successful
/ build (pull_request) Successful in 40s
/ cleanup-staging (pull_request) Successful in 2s
/ build (push) Successful in 13s
fix doorstatus not updating every minute
roomstate.js incorrectly used setTimeout() instead of setInterval() to
call the door status. This caused the status to only be updated once
after the initial page load, instead of once every minute
2024-02-02 15:44:59 +01:00

80 lines
2.2 KiB
JavaScript

import timeDistance, { deLocale } from 'js/util/timeDistance'
const spaceapiUrl = "https://spaceapi.hamburg.ccc.de"
const interval_ms = 60000
const classNameOpen = "open"
const classNameClosed = "closed"
function updateRoomState(openState, lastChangeTimestamp) {
console.debug("SpaceAPI: Setting room " + openState + " since " + lastChangeTimestamp)
const roomstate = document.querySelector('#roomstate')
var statusItem = roomstate.querySelector(".state")
var durationItem = roomstate.querySelector(".duration")
if (openState === null || lastChangeTimestamp === null) {
console.warn("SpaceAPI: Room state unknown");
statusItem.textContent = "unbekannt"
roomstate.classList.remove(classNameOpen)
roomstate.classList.remove(classNameClosed)
durationItem.textContent = "(seit unbekannt)"
} else {
if (openState) {
statusItem.textContent = "offen"
roomstate.classList.remove(classNameClosed)
roomstate.classList.add(classNameOpen)
} else {
statusItem.textContent = "geschlossen"
roomstate.classList.remove(classNameOpen)
roomstate.classList.add(classNameClosed)
}
const changeDate = new Date(lastChangeTimestamp * 1000)
const changeText = timeDistance(deLocale).inWords(changeDate)
durationItem.textContent = "(" + changeText + ")"
}
}
function parseResponse(apiJson) {
console.debug('SpaceAPI got:', apiJson)
if (typeof apiJson.state === "undefined") {
console.error("SpaceAPI JSON invalid: 'state' item not present")
return [null, null]
}
if (typeof apiJson.state.open === "undefined") {
console.error("SpaceAPI JSON invalid: 'state.open' item not present")
return [null, null]
}
console.debug('SpaceAPI state:', apiJson.state)
var openState = (apiJson.state.open == true)
var lastchange = null
if (apiJson.state.lastchange !== "undefined") {
lastchange = apiJson.state.lastchange
}
return [openState, lastchange]
}
function update() {
fetch(spaceapiUrl)
.then(resp => resp.json())
.then(function (data) {
var state = parseResponse(data)
updateRoomState(state[0], state[1])
})
.catch(err => { throw err });
}
window.onload = function () {
update()
window.setInterval(update, interval_ms)
}