doorboy-proxy/main.py

66 lines
2.2 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
import uvloop, asyncio
from motor.motor_asyncio import AsyncIOMotorClient
import pymongo
2021-03-17 07:58:03 +00:00
import hashlib
import jinja2
import json
import os
import smtplib
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__)
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # swap default event loop to uvloop
2021-03-31 07:23:48 +00:00
#mongodb = MongoClient('mongodb://172.21.27.1,172.21.27.2,172.21.27.3:27017/', replicaSet="kspace-mongo-set").kspace_accounting
2021-04-02 09:10:34 +00:00
mongodb = AsyncIOMotorClient(const.MONGO_URI)
2021-03-31 07:23:48 +00:00
mongodb = 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:
return "how about no"
2021-04-02 09:10:34 +00:00
allowed_names = [o["_id"] for o in await mongodb.member.find({"enabled": True}).to_list()]
2021-03-17 07:58:03 +00:00
allowed_uids = []
2021-04-02 09:10:34 +00:00
for obj in await mongodb.inventory.find({"token.uid_hash": {"$exists":True}, "inventory.owner_id": {"$exists":True}, "token.enabled": True}, {"inventory.owner_id": True, "token.uid_hash": True }):
2021-03-17 07:58:03 +00:00
if obj["inventory"].pop("owner_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-02 09:10:34 +00:00
return response.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:
return "how about no"
2021-04-02 09:10:34 +00:00
async def g():
2021-03-17 07:58:03 +00:00
yield "data: response-generator-started\n\n"
pipeline = [
{
'$match': {
'operationType': "insert",
# 'component': 'doorboy',
# 'type': 'open-door'
}
}
]
try:
2021-04-02 09:10:34 +00:00
async with mongodb.eventlog.watch(pipeline) as stream:
2021-03-17 07:58:03 +00:00
yield "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":
yield "data: %s\n\n" % event["fullDocument"]["door"]
except pymongo.errors.PyMongoError:
return "urror"
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__':
app.run(debug=False, host='::')