Merge binary bs into main

This commit is contained in:
2025-05-03 17:16:13 +02:00

28
main.py
View File

@@ -34,6 +34,7 @@ MEDIA_DIR = Path("./media")
os.makedirs(MEDIA_DIR, exist_ok=True)
# Store for connected websocket clients
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
@@ -51,6 +52,29 @@ class ConnectionManager:
for connection in self.active_connections:
await connection.send_text(message)
async def broadcast_binary(self, data_dict: dict):
"""
Broadcasts a message to all connections as binary data.
"""
if not self.active_connections:
return
json_str = json.dumps(data_dict)
json_bytes = json_str.encode('utf-8')
json_length = len(json_bytes)
# 4-byte unsigned integer (uint32)
length_bytes = struct.pack('!I', json_length)
message_bytes = length_bytes + json_bytes
for connection in self.active_connections:
try:
await connection.send_bytes(message_bytes)
logger.debug(f"Sent binary message ({json_length} bytes) to a client")
except Exception as e:
logger.error(f"Failed to send binary message: {str(e)}")
manager = ConnectionManager()
# Static files
@@ -157,7 +181,7 @@ async def process_subtitles(request: Request, sub_type: str):
logger.info(f"Received subtitle text: {subtitle_text}, request type: {sub_type}")
if manager.active_connections:
await manager.broadcast(json.dumps({"type": f"subtitle_{sub_type}", "text": subtitle_text}))
await manager.broadcast_binary({"type": f"subtitle_{sub_type}", "text": subtitle_text})
return JSONResponse(
status_code=200,
@@ -198,7 +222,7 @@ async def process_selected_message(message: str):
"""
logger.info(f"Processing message: {message}")
if manager.active_connections:
await manager.broadcast(json.dumps({"type": "selectedmessage", "message": message}))
await manager.broadcast_binary({"type": "selectedmessage", "message": message})
async def periodic_message_check():
"""Periodically checks for new messages."""