-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
93 lines (69 loc) · 2.52 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import asyncio
import json
from fastapi import FastAPI, Form
from fastapi.params import Depends
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pywizlight import wizlight
from sqlalchemy.orm.session import Session
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
from database import crud
from database.database import Base, SessionLocal, engine
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
Base.metadata.create_all(bind=engine)
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/", response_class=HTMLResponse)
async def management_page(request: Request, db: Session = Depends(get_db)):
return templates.TemplateResponse(
"index.jinja",
{
"request": request,
"devices": crud.get_devices(db),
"configs": crud.get_configs(db),
"lights": crud.get_lights(db),
},
)
@app.post("/add_config", response_class=RedirectResponse)
async def add_config(
db: Session = Depends(get_db),
name: str = Form(...),
light_id: int = Form(...),
device_id: int = Form(...),
):
crud.create_config(db, name, light_id, device_id)
return RedirectResponse("/", status_code=302)
@app.delete("/delete/{config_id}")
async def delete_config(config_id: int, db: Session = Depends(get_db)):
crud.delete_config(db, config_id)
@app.post("/add_light", response_class=RedirectResponse)
async def add_light(
db: Session = Depends(get_db), name: str = Form(...), ip: str = Form(...)
):
crud.create_light(db, name, ip)
return RedirectResponse("/", status_code=302)
@app.post("/hook")
async def plex_hook(request: Request, db: Session = Depends(get_db)):
form = await request.form()
payload = json.loads(form["payload"])
client_name = payload["Player"]["title"]
client_id = payload["Player"]["uuid"]
crud.upsert_device(db, client_name, client_id)
config = crud.get_config_by_device(db, client_id)
event = payload["event"]
bulbs = [wizlight(x.ip) for x in config.lights]
tasks = []
for bulb in bulbs:
if event == "media.play" or event == "media.resume":
tasks.append(asyncio.create_task(bulb.turn_off()))
elif event == "media.pause" or event == "media.stop":
tasks.append(asyncio.create_task(bulb.turn_on()))
await asyncio.gather(*tasks)