doorboy-proxy/doorboy.py

63 lines
2.1 KiB
Python
Raw Normal View History

2021-03-17 07:58:03 +00:00
from datetime import datetime
2021-04-02 09:10:34 +00:00
from sanic import Sanic, response
2021-04-03 14:09:51 +00:00
from sanic.response import text, json, stream
2021-04-02 09:10:34 +00:00
from motor.motor_asyncio import AsyncIOMotorClient
import asyncio
2021-04-02 09:10:34 +00:00
import pymongo
2021-03-17 07:58:03 +00:00
import os
2021-03-31 07:23:48 +00:00
import const
2021-03-17 07:58:03 +00:00
2021-04-02 09:10:34 +00:00
app = Sanic(__name__)
mongodb = AsyncIOMotorClient(const.MONGO_URI)
2021-04-04 08:58:45 +00:00
db = mongodb.get_default_database()
2021-03-17 07:58:03 +00:00
DOORBOY_SECRET = os.environ["DOORBOY_SECRET"]
assert len(DOORBOY_SECRET) > 10
@app.route("/allowed")
2021-04-02 09:10:34 +00:00
async def view_doorboy_uids(request):
2021-03-17 07:58:03 +00:00
if request.headers.get('KEY') != DOORBOY_SECRET:
2021-04-03 14:09:51 +00:00
return text("how about no")
allowed_names = []
2021-04-04 08:58:45 +00:00
async for obj in 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 = []
async for obj in db.inventory.find({"token.uid_hash": {"$exists":True}, "inventory.owner": {"$exists":True}, "token.enabled": {"$exists":True}}, {"inventory.owner": True, "token.uid_hash": True }):
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
@app.route("/longpoll")
2021-04-02 09:10:34 +00:00
async def view_longpoll(request):
2021-03-17 07:58:03 +00:00
if request.headers.get('KEY') != DOORBOY_SECRET:
2021-04-03 14:09:51 +00:00
return text("how about no")
2021-03-17 07:58:03 +00:00
2021-04-03 14:09:51 +00:00
async def g(response):
await response.write("data: response-generator-started\n\n")
2021-03-17 07:58:03 +00:00
pipeline = [
{
'$match': {
'operationType': "insert",
# 'component': 'doorboy',
# 'type': 'open-door'
}
}
]
try:
2021-04-04 08:58:45 +00:00
async with db.eventlog.watch(pipeline) as stream:
2021-04-03 14:09:51 +00:00
await response.write("data: watch-stream-opened\n\n")
2021-04-02 09:10:34 +00:00
async for event in stream:
2021-03-17 07:58:03 +00:00
if event["fullDocument"].get("type") == "open-door":
2021-04-03 14:09:51 +00:00
await response.write("data: %s\n\n" % event["fullDocument"]["door"])
2021-03-17 07:58:03 +00:00
except pymongo.errors.PyMongoError:
2021-04-03 14:09:51 +00:00
return
2021-04-02 09:10:34 +00:00
return stream(g, content_type="text/event-stream")
2021-03-17 07:58:03 +00:00
if __name__ == '__main__':
2021-10-26 15:01:56 +00:00
app.run(debug=False, port=5000)