Add door open events endpoint
All checks were successful
ci/woodpecker/manual/woodpecker Pipeline was successful

This commit is contained in:
Madis Mägi 2024-10-04 21:40:02 +03:00
parent a961f170d9
commit 8b7e220ec4
2 changed files with 46 additions and 0 deletions

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python3
from datetime import date, datetime
from sanic import Sanic
from sanic.response import text, json
from sanic_prometheus import monitor
@ -13,6 +14,7 @@ monitor(app).expose_endpoint()
INVENTORY_API_KEY = os.environ["INVENTORY_API_KEY"]
DOORBOY_SECRET_FLOOR = os.environ["DOORBOY_SECRET_FLOOR"]
DOORBOY_SECRET_WORKSHOP = os.environ["DOORBOY_SECRET_WORKSHOP"]
DOORBOY_SECRET_OPEN_EVENTS = os.environ["DOORBOY_SECRET_OPEN_EVENTS"]
CARD_URI = os.environ["CARD_URI"]
FLOOR_ACCESS_GROUP = os.environ["FLOOR_ACCESS_GROUP"]
WORKSHOP_ACCESS_GROUP = os.environ["WORKSHOP_ACCESS_GROUP"]
@ -57,6 +59,49 @@ async def view_doorboy_uids(request):
})
return json({"allowed_uids": allowed_uids})
def datetime_to_json_formatting(o):
if isinstance(o, (date, datetime)):
return o.isoformat()
@app.route("/open-door-events")
async def view_open_door_events(request):
key = request.headers.get("KEY")
if not key or key != DOORBOY_SECRET_OPEN_EVENTS:
return text("Invalid token")
results = await app.ctx.db.eventlog.find({
"component": "doorboy",
"type": "open-door",
"$or": [
{ "approved": True },
{ "success": True },
],
"$or": [
{ "type": "open-door" },
{ "event": "card-swiped" },
],
"door": { "$exists": True },
"timestamp": { "$exists": True }
}).sort("timestamp", -1).to_list(length=None)
transformed = []
for r in results:
if r.get("type") == "open-door" and r.get("approved") and r.get("method"):
transformed.append({
"method": r.get("method"),
"door": r["door"],
"timestamp": r.get("timestamp"),
"member": r.get("member"),
})
if r.get("event") == "card-swiped" and r.get("success"):
transformed.append({
"method": "card-swiped",
"door": r["door"],
"timestamp": r.get("timestamp"),
"member": r.get("inventory", {}).get("owner")
})
return json(transformed, default=datetime_to_json_formatting)
@app.route("/longpoll", stream=True)
async def view_longpoll(request):

View File

@ -27,6 +27,7 @@ services:
INVENTORY_API_KEY: "sptWL6XFxl4b8"
DOORBOY_SECRET_FLOOR: "0123456789"
DOORBOY_SECRET_WORKSHOP: "9999999999"
DOORBOY_SECRET_OPEN_EVENTS: "1111111111"
FLOOR_ACCESS_GROUP: "k-space:floor"
WORKSHOP_ACCESS_GROUP: "k-space:workshop"
CARD_URI: "https://inventory-app-72zn4.codemowers.ee/cards"