Working on: The Twitch authentication

This commit is contained in:
2025-12-25 18:39:14 +01:00
parent cfc082a6f8
commit 7a18b5b402
3 changed files with 35 additions and 21 deletions

17
main.py
View File

@@ -1,4 +1,5 @@
import os
import logging
import asyncio
from fastapi import FastAPI, Request, Depends, HTTPException
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
@@ -25,9 +26,13 @@ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, "static")
TEMPLATES_DIR = os.path.join(BASE_DIR, "templates")
# --- Logging Configuration ---
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
async def background_listener_startup(app: FastAPI):
"""A non-blocking task to start listeners after the app has started."""
print("Background task: Starting listeners for all users...")
logger.info("Background task: Starting listeners for all users...")
db = SessionLocal()
users = db.query(models.User).all()
db.close()
@@ -36,23 +41,23 @@ async def background_listener_startup(app: FastAPI):
try:
await app.state.listener_manager.start_listener_for_user(user, app.state.websocket_manager)
except Exception as e:
print(f"ERROR: Failed to start listener for user {user.id} ({user.username}): {e}")
logger.error(f"Failed to start listener for user {user.id} ({user.username}): {e}")
@asynccontextmanager
async def lifespan(app: FastAPI):
# This code runs on startup
print("Application startup: Creating database tables...")
logger.info("Application startup: Creating database tables...")
app.state.websocket_manager = WebSocketManager()
app.state.listener_manager = ListenerManager()
models.Base.metadata.create_all(bind=engine)
print("Application startup: Database tables created.")
logger.info("Application startup: Database tables created.")
# Decouple listener startup from the main application startup
asyncio.create_task(background_listener_startup(app))
yield
# This code runs on shutdown
print("Application shutdown: Stopping all listeners...")
logger.info("Application shutdown: Stopping all listeners...")
manager = app.state.listener_manager
# Create a copy of keys to avoid runtime errors from changing dict size
for user_id in list(manager.active_listeners.keys()):
@@ -203,4 +208,4 @@ async def websocket_endpoint(websocket: WebSocket, user_id: int):
await websocket.receive_text()
except Exception:
manager.disconnect(user_id, websocket)
print(f"WebSocket for user {user_id} disconnected.")
logger.info(f"WebSocket for user {user_id} disconnected.")