Add few changes

This commit is contained in:
2025-05-04 17:27:39 +02:00
parent a469496269
commit e3a76da156
2 changed files with 158 additions and 20 deletions

81
main.py
View File

@@ -27,6 +27,8 @@ app = FastAPI(title="Pythagoras", description="A proxy service handling HTTP and
app.state.auto_polling = False
app.state.polling_rate = 5
app.state.enable_libretranslate = True
app.state.client_state = "idle"
app.state.latest_message = ""
# Define the media directory
MEDIA_DIR = Path("./media")
@@ -43,11 +45,23 @@ class ConnectionManager:
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
await setscreen_single(websocket, app.state.client_state) # Send the latest client state to any new client
await self.singlecast_binary({"type": "selectedmessage", "message": app.state.latest_message}, websocket) # Broadcast latest message to all clients
logger.info(f"WebSocket client connected. Total connections: {len(self.active_connections)}")
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
logger.info(f"WebSocket client disconnected. Total connections: {len(self.active_connections)}")
def json_to_binary(self, json_str: str):
json_bytes = json_str.encode('utf-8')
json_length = len(json_bytes)
# 4-byte unsigned integer (uint32)
length_bytes = struct.pack('!I', json_length)
return length_bytes + json_bytes
async def broadcast(self, message: str):
for connection in self.active_connections:
@@ -61,21 +75,29 @@ class ConnectionManager:
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
message_bytes = self.json_to_binary(json_str)
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")
logger.debug(f"Sent binary message ({len(message_bytes)} bytes) to a client")
except Exception as e:
logger.error(f"Failed to send binary message: {str(e)}")
async def singlecast_binary(self, data_dict: dict, ws: WebSocket):
"""
I love code duplication
"""
json_str = json.dumps(data_dict)
message_bytes = self.json_to_binary(json_str)
try:
await ws.send_bytes(message_bytes)
logger.debug(f"Sent binary message ({len(message_bytes)} bytes) to a client")
except Exception as e:
logger.error(f"Failed to send binary message: {str(e)}")
manager = ConnectionManager()
# Static files
@@ -126,6 +148,33 @@ async def control_endpoint(request: Request):
app.state.polling_rate = new_rate
logger.info(f"Auto-polling rate change requested: {new_rate} seconds")
elif data['command'] == "playvideo" and 'filename' in data:
filename = data['filename']
await playvideo(filename)
logger.info(f"Video playback requested: {filename}")
elif data['command'] == "seekvideo" and 'timestamp' in data:
timestamp = data['timestamp']
await seekvideo(timestamp)
logger.info(f"Seeking of the currently playing video requested to {timestamp} seconds")
elif data['command'] == "setscreen_main":
await setscreen("main")
app.state.client_state = "main"
logger.info(f"Setting the client screen to main view.")
elif data['command'] == "setscreen_video":
await setscreen("video")
app.state.client_state = "video"
logger.info(f"Setting the client screen to video playback.")
elif data['command'] == "setscreen_idle":
await setscreen("idle")
app.state.client_state = "idle"
logger.info(f"Setting the client screen to idle.")
return JSONResponse(
status_code=200,
@@ -245,6 +294,19 @@ async def translate_to_cs_libre(text: str):
except Exception as e:
logger.error(f"Translation error: {str(e)}")
return text
async def setscreen_single(ws: WebSocket, screen: str):
return await manager.singlecast_binary({"type": "setscreen", "screen": screen}, ws)
async def setscreen(screen: str):
return await manager.broadcast_binary({"type": "setscreen", "screen": screen})
async def playvideo(filename: str):
return await manager.broadcast_binary({"type": "playvideo", "filename": filename})
async def seekvideo(timestamp: int):
return await manager.broadcast_binary({"type": "seekvideo", "timestamp": timestamp})
@@ -272,9 +334,10 @@ async def fetch_selected_message():
async def process_selected_message(message: str):
"""
Processes the selected message.
Processes the selected message and saves it to cache.
"""
logger.info(f"Processing message: {message}")
app.state.latest_message = message
if manager.active_connections:
await manager.broadcast_binary({"type": "selectedmessage", "message": message})