ENable webscoket

This commit is contained in:
Nexus 2023-06-29 12:54:47 +01:00
parent 5c78bd00b9
commit bd62dfdd4b
Signed by: nex
GPG key ID: 0FA334385D0B689F
2 changed files with 43 additions and 23 deletions

View file

@ -61,6 +61,7 @@ class Events(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.http = httpx.AsyncClient()
self.bot.bridge_queue = asyncio.Queue()
self.fetch_discord_atom_feed.start()
def cog_unload(self):
@ -366,10 +367,10 @@ class Events(commands.Cog):
return
if message.channel.name == "femboy-hole":
if Path("/tmp/jimmy-bridge").exists():
payload = {
"author": str(message.user),
"content": message.content,
"at": message.created_at.timestamp(),
"attachments": [
{
"url": a.url,
@ -382,11 +383,8 @@ class Events(commands.Cog):
for a in message.attachments
]
}
dumped = json.dumps(payload, separators=(",", ":")).encode()
buffer_need = 8192 - len(dumped)
if buffer_need > 0:
dumped += b"\0" * buffer_need
Path("/tmp/jimmy-bridge").write_bytes(dumped)
# dumped = json.dumps(payload, separators=(",", ":"))
self.bot.bridge_queue.put_nowait(payload)
if message.channel.name == "pinboard":
if message.type == discord.MessageType.pins_add:

View file

@ -8,9 +8,12 @@ from pathlib import Path
from datetime import datetime, timezone
from hashlib import sha512
from fastapi import FastAPI, HTTPException, Request
from fastapi import FastAPI, HTTPException, Request, Header
from fastapi.responses import JSONResponse, RedirectResponse, HTMLResponse
from http import HTTPStatus
from starlette.websockets import WebSocket, WebSocketDisconnect
from utils import Student, get_or_none, VerifyCode, console, BannedStudentID
from utils.db import AccessTokens
from config import guilds
@ -283,7 +286,7 @@ async def verify(code: str):
)
@app.post("/bridge")
@app.post("/bridge", include_in_schema=False)
async def bridge(req: Request):
body = await req.json()
if body["secret"] != app.state.bot.http.token:
@ -303,3 +306,22 @@ async def bridge(req: Request):
f"**{body['sender']}**:\n>>> {body['message']}"
)
return {"status": "ok"}
@app.websocket('/bridge/recv')
def bridge_recv(ws: WebSocket, secret: str = Header(None)):
if secret != app.state.bot.http.token:
raise HTTPException(
status_code=401,
detail="Invalid secret."
)
await ws.accept()
while True:
data = await app.state.bot.bridge_queue.get()
try:
await ws.send_json(data)
except WebSocketDisconnect:
break
finally:
app.state.bot.bridge_queue.job_done()