doorboy-proxy/doorboy.py

75 lines
2.3 KiB
Python
Raw Normal View History

2022-02-21 20:10:57 +00:00
from sanic import Sanic
from sanic.response import text, json
2021-04-02 09:10:34 +00:00
from motor.motor_asyncio import AsyncIOMotorClient
import pymongo
2021-03-17 07:58:03 +00:00
import os
2021-04-02 09:10:34 +00:00
app = Sanic(__name__)
2021-03-17 07:58:03 +00:00
DOORBOY_SECRET = os.environ["DOORBOY_SECRET"]
2022-02-21 20:10:57 +00:00
MONGO_URI = os.getenv("MONGO_URI",
"mongodb://127.0.0.1:27017/default?replicaSet=rs0")
2021-03-17 07:58:03 +00:00
2022-02-21 20:10:57 +00:00
assert len(DOORBOY_SECRET) >= 10
2021-03-17 07:58:03 +00:00
2021-10-26 17:17:48 +00:00
@app.listener("before_server_start")
async def setup_db(app, loop):
# TODO: find cleaner way to do this, for more see
# https://github.com/sanic-org/sanic/issues/919
2022-02-21 20:10:57 +00:00
app.ctx.db = AsyncIOMotorClient(MONGO_URI).get_default_database()
2021-10-26 17:17:48 +00:00
2021-03-17 07:58:03 +00:00
@app.route("/allowed")
2021-04-02 09:10:34 +00:00
async def view_doorboy_uids(request):
2022-02-21 20:10:57 +00:00
if request.headers.get("KEY") != DOORBOY_SECRET:
2021-04-03 14:09:51 +00:00
return text("how about no")
allowed_names = []
2022-02-21 20:10:57 +00:00
async for obj in app.ctx.db.member.find({"enabled": True}):
2021-04-03 14:09:51 +00:00
allowed_names.append(obj["_id"])
2021-03-17 07:58:03 +00:00
allowed_uids = []
2022-02-21 20:10:57 +00:00
flt = {
"token.uid_hash": {"$exists": True},
"inventory.owner": {"$exists": True},
"token.enabled": {"$exists": True}
}
prj = {
"inventory.owner": True,
"token.uid_hash": True
}
async for obj in app.ctx.db.inventory.find(flt, prj):
if obj["inventory"].pop("owner").get("foreign_id") in allowed_names:
2021-04-02 09:10:34 +00:00
del obj["_id"]
del obj["inventory"]
2021-03-17 07:58:03 +00:00
allowed_uids.append(obj)
2021-04-03 14:09:51 +00:00
return json({"allowed_uids": allowed_uids})
2021-03-17 07:58:03 +00:00
2022-02-21 20:10:57 +00:00
@app.route("/longpoll", stream=True)
2021-04-02 09:10:34 +00:00
async def view_longpoll(request):
2022-02-21 20:10:57 +00:00
response = await request.respond(content_type="text/event-stream")
if request.headers.get("KEY") != DOORBOY_SECRET:
return text("Invalid token")
await response.send("data: response-generator-started\n\n")
pipeline = [
{
"$match": {
"operationType": "insert",
}
}
]
try:
async with app.ctx.db.eventlog.watch(pipeline) as stream:
await response.send("data: watch-stream-opened\n\n")
async for event in stream:
if event["fullDocument"].get("type") == "open-door":
await response.send("data: %s\n\n" %
event["fullDocument"]["door"])
except pymongo.errors.PyMongoError:
return
2021-03-17 07:58:03 +00:00
2022-02-21 20:10:57 +00:00
if __name__ == "__main__":
app.run(debug=False, host="0.0.0.0", port=5000)