spaceapi/app.py

60 lines
1.7 KiB
Python

from functools import lru_cache
import json
import time
import urllib.request
from flask import Flask, jsonify
app = Flask(__name__)
@lru_cache(maxsize=1)
def get_jitsi_status(ttl_hash : int = 0) -> bool | None:
# ttl_hash is used to cache the result for a certain amount of time.
# This is done to rate-limit the outgoing requests to the jitsi server.
# Inspired by https://stackoverflow.com/a/55900800
# The jitsi server uses mod_census to provide a JSON representation of all
# currently active rooms. We can use this to check if the lounge is currently
# occupied.
try:
content = urllib.request.urlopen("https://talk.chaoswest.tv/room-census").read()
census = json.loads(content)
return any(room["room_name"] == "cws-lounge@muc.meet.jitsi" for room in census.get("room_census", []))
except Exception as e:
print("shit got fucked up:")
print(e)
return None
def get_ttl_hash(seconds : int = 1) -> int:
# Generates a monotonically increasing "hash" as time progresses
return round(time.time() / seconds)
@app.route("/spaceapi")
def spaceapi():
result = {
'api': '0.13',
'api_compatibility': ['14'],
'space': 'chaoswest.tv',
'logo': 'https://chaoswest.tv/logo.png',
'url': 'https://chaoswest.tv',
'location': {
'lat': 50.47718,
'lon': 12.33427,
'address': 'FSN1-DC14',
},
'contact': {
'mastodon': '@chaoswesttv@chaos.social',
}
}
status = get_jitsi_status(get_ttl_hash())
if status is not None:
result["state"] = {
'open': status
}
return jsonify(result)