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

View file

@ -8,9 +8,12 @@ from pathlib import Path
from datetime import datetime, timezone from datetime import datetime, timezone
from hashlib import sha512 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 fastapi.responses import JSONResponse, RedirectResponse, HTMLResponse
from http import HTTPStatus from http import HTTPStatus
from starlette.websockets import WebSocket, WebSocketDisconnect
from utils import Student, get_or_none, VerifyCode, console, BannedStudentID from utils import Student, get_or_none, VerifyCode, console, BannedStudentID
from utils.db import AccessTokens from utils.db import AccessTokens
from config import guilds 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): async def bridge(req: Request):
body = await req.json() body = await req.json()
if body["secret"] != app.state.bot.http.token: if body["secret"] != app.state.bot.http.token:
@ -303,3 +306,22 @@ async def bridge(req: Request):
f"**{body['sender']}**:\n>>> {body['message']}" f"**{body['sender']}**:\n>>> {body['message']}"
) )
return {"status": "ok"} 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()