Skip to content

Instantly share code, notes, and snippets.

@Gregoor
Created December 5, 2016 00:27
Show Gist options
  • Save Gregoor/fa59ed3ff2b095817b0458bb2dfb3ff4 to your computer and use it in GitHub Desktop.
Save Gregoor/fa59ed3ff2b095817b0458bb2dfb3ff4 to your computer and use it in GitHub Desktop.
"""
Implement the SpaceApi (<https://github.com/SpaceApi/SpaceApi>)
for Chaos Darmstadt (<https://www.chaos-darmstadt.de/>).
"""
import falcon
import os
import json
import time
static_info = {
"address": "Wilhelminenstra\u00dfe 17, 64283 Darmstadt, Germany",
"api": "0.12",
"contact": {
"email": "info@chaos-darmstadt.de",
"issue_mail": "noc@chaos-darmstadt.de",
"irc": "irc://hackint/#chaos-darmstadt",
"ml": "public@darmstadt.ccc.de",
"phone": "+49 6151 6274854",
"twitter": "@chaosdarmstadt",
"twitter2": "@trollhoehle",
"facebook": "Chaos-Darmstadt-476384005725422",
},
"icon": {
# TODO: icons
"closed": "http://status.chaos-darmstadt.de/cda_closed.png",
"open": "http://status.chaos-darmstadt.de/cda_open.png",
},
"logo": "http://status.chaos-darmstadt.de/cda_logo_plain.png",
"lat": 49.87065,
"lon": 8.65146,
"space": "Chaos Darmstadt",
"url": "https://www.chaos-darmstadt.de",
"issue_report_channels": [
"issue_mail",
],
}
# duplicate some information to comply with SpaceApi v0.13
static_info["location"] = {
"address": static_info["address"],
"lat": static_info["lat"],
"lon": static_info["lon"],
}
static_info["state"] = {
"icon": static_info["icon"],
}
STATE_FILE_NAME = "state.json"
class HackspaceStatus:
def __init__(self):
if os.path.isfile(STATE_FILE_NAME):
with open(STATE_FILE_NAME) as state_file:
last_status = json.load(state_file)
self.space_status = last_status["status"]
self.last_change = last_status["last_change"]
else:
self.space_status = False
self.last_change = time.time()
def on_get(self, req, resp, name):
if not name or name == 'plain':
resp.content_type = 'text/plain'
resp.body = str(bool(self.space_status))
elif name == 'json':
data = dict(static_info)
data["state"]["open"] = data["open"] = bool(self.space_status)
data["lastchange"] = int(self.last_change)
resp.body = json.dumps(data)
else:
raise falcon.HTTPNotFound()
resp.cache_control = ["no-cache"]
def on_put(self, req, resp, name):
# ignore name here
self.space_status = req.get_param_as_bool("status", required=True)
self.last_change = time.time()
# using query parameters is much easier than parsing "status=x" from req.stream.read()
with open(STATE_FILE_NAME, "w+") as state_file:
json.dump({
"status": self.space_status,
"last_change": self.last_change
}, state_file)
app = falcon.API()
app.add_route('/{name}', HackspaceStatus())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment