lnbits-legend/lnbits/extensions/copilot/views.py

63 lines
2 KiB
Python
Raw Normal View History

from quart import g, abort, render_template, jsonify, websocket
2021-04-12 20:31:39 +01:00
from http import HTTPStatus
2021-04-19 09:32:41 +01:00
import httpx
2021-06-23 11:14:06 +01:00
from collections import defaultdict
2021-04-12 20:31:39 +01:00
from lnbits.decorators import check_user_exists, validate_uuids
from . import copilot_ext
from .crud import get_copilot
from quart import g, abort, render_template, jsonify, websocket
from functools import wraps
2021-04-16 12:20:05 +01:00
import trio
import shortuuid
from . import copilot_ext
2021-08-21 01:55:07 +01:00
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
2021-08-21 01:55:07 +01:00
templates = Jinja2Templates(directory="templates")
2021-06-24 01:26:49 +01:00
2021-04-12 20:31:39 +01:00
@copilot_ext.route("/")
@validate_uuids(["usr"], required=True)
@check_user_exists()
2021-08-21 01:55:07 +01:00
async def index(request: Request):
return await templates.TemplateResponse("copilot/index.html", {"request": request, "user":g.user})
2021-06-24 01:26:49 +01:00
2021-04-20 14:33:41 +01:00
@copilot_ext.route("/cp/")
2021-08-21 01:55:07 +01:00
async def compose(request: Request):
return await templates.TemplateResponse("copilot/compose.html", {"request": request})
2021-04-20 14:33:41 +01:00
@copilot_ext.route("/pn/")
2021-08-21 01:55:07 +01:00
async def panel(request: Request):
return await templates.TemplateResponse("copilot/panel.html", {"request": request})
2021-04-20 00:37:51 +01:00
2021-04-20 08:50:53 +01:00
##################WEBSOCKET ROUTES########################
# socket_relay is a list where the control panel or
# lnurl endpoints can leave a message for the compose window
2021-06-23 11:14:06 +01:00
connected_websockets = defaultdict(set)
2021-06-24 01:26:49 +01:00
2021-06-23 11:14:06 +01:00
@copilot_ext.websocket("/ws/<id>/")
async def wss(id):
copilot = await get_copilot(id)
if not copilot:
return "", HTTPStatus.FORBIDDEN
global connected_websockets
send_channel, receive_channel = trio.open_memory_channel(0)
connected_websockets[id].add(send_channel)
try:
while True:
data = await receive_channel.receive()
await websocket.send(data)
finally:
connected_websockets[id].remove(send_channel)
2021-06-24 01:26:49 +01:00
2021-06-23 11:14:06 +01:00
async def updater(copilot_id, data, comment):
copilot = await get_copilot(copilot_id)
if not copilot:
return
for queue in connected_websockets[copilot_id]:
2021-06-24 01:26:49 +01:00
await queue.send(f"{data + '-' + comment}")