import asyncio import mimetypes import os import re import secrets import sqlite3 import time from contextlib import suppress from pathlib import Path from typing import ( Any, Callable, MutableMapping, Optional, ) from fastapi import ( APIRouter, File, Form, HTTPException, UploadFile, Cookie, ) from fastapi.responses import FileResponse from accounts import get_session_user, room_record_for_user # --------------------------------------------------------- # Public router # --------------------------------------------------------- chat_files_router = APIRouter() # --------------------------------------------------------- # Configuration # --------------------------------------------------------- BASE_DIR = Path(__file__).resolve().parent CHAT_UPLOAD_DIRECTORY = Path( os.getenv( "CHAT_UPLOAD_DIRECTORY", str( BASE_DIR / "chat_uploads" ), ) ).resolve() CHAT_FILE_RETENTION_DAYS = int( os.getenv( "CHAT_FILE_RETENTION_DAYS", "14", ) ) CHAT_FILE_RETENTION_SECONDS = ( CHAT_FILE_RETENTION_DAYS * 24 * 60 * 60 ) CHAT_FILE_MAX_SIZE_MB = int( os.getenv( "CHAT_FILE_MAX_SIZE_MB", "25", ) ) CHAT_FILE_MAX_SIZE_BYTES = ( CHAT_FILE_MAX_SIZE_MB * 1024 * 1024 ) CHAT_FILE_CLEANUP_INTERVAL_SECONDS = int( os.getenv( "CHAT_FILE_CLEANUP_INTERVAL_SECONDS", "3600", ) ) CHAT_FILE_CHUNK_SIZE = ( 1024 * 1024 ) CHAT_UPLOAD_HOURLY_MB = max(1, int(os.getenv("CHAT_UPLOAD_HOURLY_MB", "200"))) CHAT_UPLOAD_HOURLY_FILES = max(1, int(os.getenv("CHAT_UPLOAD_HOURLY_FILES", "40"))) CHAT_FILE_ID_PATTERN = re.compile( r"^[A-Za-z0-9_-]{20,128}$" ) # --------------------------------------------------------- # Runtime dependencies supplied by server.py # --------------------------------------------------------- _database_path: Optional[Path] = None _chat_history: Optional[ MutableMapping[ str, Any, ] ] = None _normalize_room_name: Optional[ Callable[ [str], str, ] ] = None _normalize_user_name: Optional[ Callable[ [str], str, ] ] = None _room_exists: Optional[ Callable[ [str], bool, ] ] = None def configure_chat_files( *, database_path: Path, chat_history: MutableMapping[ str, Any, ], normalize_room_name: Callable[ [str], str, ], normalize_user_name: Callable[ [str], str, ], room_exists: Callable[ [str], bool, ], ) -> None: """ Configure this module from server.py. Call this once before the FastAPI application begins accepting requests. """ global _database_path global _chat_history global _normalize_room_name global _normalize_user_name global _room_exists _database_path = Path( database_path ).resolve() _chat_history = chat_history _normalize_room_name = ( normalize_room_name ) _normalize_user_name = ( normalize_user_name ) _room_exists = room_exists def ensure_configured() -> None: """ Fail clearly if server.py forgot to configure the module before using it. """ if _database_path is None: raise RuntimeError( "chat_files.py has not been configured: " "database_path is missing." ) if _chat_history is None: raise RuntimeError( "chat_files.py has not been configured: " "chat_history is missing." ) if _normalize_room_name is None: raise RuntimeError( "chat_files.py has not been configured: " "normalize_room_name is missing." ) if _normalize_user_name is None: raise RuntimeError( "chat_files.py has not been configured: " "normalize_user_name is missing." ) if _room_exists is None: raise RuntimeError( "chat_files.py has not been configured: " "room_exists is missing." ) # --------------------------------------------------------- # Database helpers # --------------------------------------------------------- def open_database() -> sqlite3.Connection: ensure_configured() connection = sqlite3.connect( _database_path, timeout=15, ) connection.row_factory = ( sqlite3.Row ) connection.execute( "PRAGMA foreign_keys = ON" ) connection.execute( "PRAGMA busy_timeout = 15000" ) return connection def initialize_chat_file_storage() -> None: """ Create the upload directory and SQLite metadata table. """ ensure_configured() CHAT_UPLOAD_DIRECTORY.mkdir( parents=True, exist_ok=True, ) with open_database() as connection: connection.execute( """ CREATE TABLE IF NOT EXISTS chat_files ( file_id TEXT PRIMARY KEY, message_id TEXT NOT NULL UNIQUE, room_name TEXT NOT NULL COLLATE NOCASE, sender TEXT NOT NULL, original_name TEXT NOT NULL, stored_name TEXT NOT NULL UNIQUE, mime_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ) """ ) connection.execute( """ CREATE INDEX IF NOT EXISTS idx_chat_files_room_name ON chat_files ( room_name ) """ ) connection.execute( """ CREATE INDEX IF NOT EXISTS idx_chat_files_expires_at ON chat_files ( expires_at ) """ ) connection.commit() def get_chat_file_record( connection: sqlite3.Connection, file_id: str, ) -> Optional[sqlite3.Row]: return connection.execute( """ SELECT file_id, message_id, room_name, sender, original_name, stored_name, mime_type, size_bytes, created_at, expires_at FROM chat_files WHERE file_id = ? """, ( file_id, ), ).fetchone() # --------------------------------------------------------- # Validation and path helpers # --------------------------------------------------------- def sanitize_original_filename( filename: Optional[str], ) -> str: """ Keep the original display name, but remove path traversal and control characters. """ clean_name = Path( filename or "shared-file" ).name clean_name = re.sub( r"[\x00-\x1f\x7f]", "", clean_name, ).strip() clean_name = clean_name.replace( "/", "_", ) clean_name = clean_name.replace( "\\", "_", ) if not clean_name: clean_name = "shared-file" return clean_name[:180] def get_safe_file_extension( filename: str, ) -> str: suffix = Path( filename ).suffix.lower() if not suffix: return "" suffix = re.sub( r"[^a-z0-9.]", "", suffix, ) return suffix[:16] def generate_chat_file_id() -> str: return secrets.token_urlsafe( 32 ) def generate_chat_message_id() -> str: return ( "file-" + secrets.token_urlsafe( 24 ) ) def resolve_chat_file_path( stored_name: str, ) -> Path: """ Resolve a stored filename while ensuring it cannot escape CHAT_UPLOAD_DIRECTORY. """ candidate = ( CHAT_UPLOAD_DIRECTORY / stored_name ).resolve() try: candidate.relative_to( CHAT_UPLOAD_DIRECTORY ) except ValueError as error: raise RuntimeError( "Stored chat file path escaped " "the upload directory." ) from error return candidate def build_file_message( *, message_id: str, room_name: str, sender_name: str, file_id: str, original_name: str, mime_type: str, total_size: int, created_at: int, expires_at: int, ) -> dict[str, Any]: return { "id": message_id, "room": room_name, "sender": sender_name, "text": "", "createdAt": created_at * 1000, "messageType": "file", "fileId": file_id, "fileName": original_name, "fileSize": total_size, "fileMimeType": mime_type, "fileUrl": ( "/api/chat/files/" + file_id ), "fileExpiresAt": expires_at * 1000, } # --------------------------------------------------------- # Cleanup helpers # --------------------------------------------------------- def cleanup_expired_chat_files( now: Optional[int] = None, ) -> int: """ Delete files and database rows whose 14-day retention period has expired. """ ensure_configured() current_time = ( int(time.time()) if now is None else int(now) ) removed_count = 0 with open_database() as connection: expired_records = ( connection.execute( """ SELECT file_id, stored_name FROM chat_files WHERE expires_at <= ? """, ( current_time, ), ).fetchall() ) for record in expired_records: file_path = resolve_chat_file_path( record[ "stored_name" ] ) try: file_path.unlink( missing_ok=True ) except OSError as error: print( "Could not delete expired " f"chat file {file_path}: " f"{error}" ) continue connection.execute( """ DELETE FROM chat_files WHERE file_id = ? """, ( record[ "file_id" ], ), ) removed_count += 1 connection.commit() return removed_count def delete_room_chat_files( room_name: str, ) -> int: """ Delete every stored file belonging to a room. server.py should call this after a room is deleted. """ ensure_configured() normalized_room = ( _normalize_room_name( room_name ) ) removed_count = 0 with open_database() as connection: records = connection.execute( """ SELECT file_id, stored_name FROM chat_files WHERE room_name = ? """, ( normalized_room, ), ).fetchall() for record in records: file_path = resolve_chat_file_path( record[ "stored_name" ] ) try: file_path.unlink( missing_ok=True ) except OSError as error: print( "Could not delete room " f"chat file {file_path}: " f"{error}" ) cursor = connection.execute( """ DELETE FROM chat_files WHERE room_name = ? """, ( normalized_room, ), ) removed_count = max( 0, cursor.rowcount, ) connection.commit() return removed_count async def chat_file_cleanup_loop() -> None: """ Run cleanup repeatedly until the task is cancelled. """ while True: try: removed_count = ( cleanup_expired_chat_files() ) if removed_count: print( "Removed " f"{removed_count} expired " "chat file(s)." ) except Exception as error: print( "Chat file cleanup failed: " f"{error}" ) await asyncio.sleep( CHAT_FILE_CLEANUP_INTERVAL_SECONDS ) def start_chat_file_cleanup() -> asyncio.Task: """ Run one cleanup immediately, then start the recurring cleanup task. """ removed_count = ( cleanup_expired_chat_files() ) if removed_count: print( "Removed " f"{removed_count} expired " "chat file(s) during startup." ) return asyncio.create_task( chat_file_cleanup_loop() ) async def stop_chat_file_cleanup( cleanup_task: Optional[asyncio.Task], ) -> None: if cleanup_task is None: return cleanup_task.cancel() with suppress( asyncio.CancelledError ): await cleanup_task # --------------------------------------------------------- # API endpoints # --------------------------------------------------------- @chat_files_router.post( "/api/chat/files" ) async def upload_chat_file( room: str = Form(...), sender: str = Form(""), # backward-compatible; not trusted file: UploadFile = File(...), kronick_session: Optional[str] = Cookie(default=None), ): """ Upload one file and append a file-type message to the room's existing in-memory chat history. """ ensure_configured() room_name = _normalize_room_name( room ) user = get_session_user(kronick_session) if room_record_for_user(int(user["id"]), room_name) is None: raise HTTPException(status_code=403, detail="Room access denied.") sender_name = _normalize_user_name(str(user["username"])) # Bound authenticated abuse as well as anonymous abuse. Quotas are scoped # to this sender's uploads across every room over the preceding hour. with open_database() as connection: usage = connection.execute( "SELECT COUNT(*), COALESCE(SUM(size_bytes), 0) FROM chat_files " "WHERE sender=? AND created_at>=?", (sender_name, int(time.time()) - 3600), ).fetchone() if int(usage[0]) >= CHAT_UPLOAD_HOURLY_FILES or int(usage[1]) >= CHAT_UPLOAD_HOURLY_MB * 1024 * 1024: raise HTTPException(status_code=429, detail="Hourly file upload quota exceeded.") original_name = ( sanitize_original_filename( file.filename ) ) now = int( time.time() ) expires_at = ( now + CHAT_FILE_RETENTION_SECONDS ) file_id = generate_chat_file_id() message_id = ( generate_chat_message_id() ) extension = ( get_safe_file_extension( original_name ) ) stored_name = ( file_id + extension ) destination = ( resolve_chat_file_path( stored_name ) ) mime_type = ( file.content_type or mimetypes.guess_type( original_name )[0] or "application/octet-stream" ) total_size = 0 try: with destination.open( "xb" ) as output_file: while True: chunk = await file.read( CHAT_FILE_CHUNK_SIZE ) if not chunk: break total_size += len( chunk ) if ( total_size > CHAT_FILE_MAX_SIZE_BYTES ): raise HTTPException( status_code=413, detail=( "The file exceeds the " f"{CHAT_FILE_MAX_SIZE_MB} " "MB upload limit." ), ) output_file.write( chunk ) except HTTPException: destination.unlink( missing_ok=True ) raise except FileExistsError as error: destination.unlink( missing_ok=True ) raise HTTPException( status_code=409, detail=( "A file identifier collision " "occurred. Try the upload again." ), ) from error except OSError as error: destination.unlink( missing_ok=True ) raise HTTPException( status_code=500, detail=( "The server could not save " "the uploaded file." ), ) from error finally: await file.close() if total_size <= 0: destination.unlink( missing_ok=True ) raise HTTPException( status_code=400, detail="The uploaded file is empty.", ) try: with open_database() as connection: connection.execute( """ INSERT INTO chat_files ( file_id, message_id, room_name, sender, original_name, stored_name, mime_type, size_bytes, created_at, expires_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( file_id, message_id, room_name, sender_name, original_name, stored_name, mime_type, total_size, now, expires_at, ), ) connection.commit() except sqlite3.IntegrityError as error: destination.unlink( missing_ok=True ) raise HTTPException( status_code=409, detail=( "The upload could not be registered. " "Try the upload again." ), ) from error file_message = build_file_message( message_id= message_id, room_name= room_name, sender_name= sender_name, file_id= file_id, original_name= original_name, mime_type= mime_type, total_size= total_size, created_at= now, expires_at= expires_at, ) _chat_history[ room_name ].append( file_message ) return { "ok": True, "room": room_name, "message": file_message, } @chat_files_router.get( "/api/chat/files/{file_id}" ) async def download_chat_file( file_id: str, kronick_session: Optional[str] = Cookie(default=None), ): """ Download a previously uploaded file. Files are served as attachments rather than inline content so HTML, JavaScript, SVG, and similar formats do not execute inside the site. """ ensure_configured() normalized_file_id = str( file_id or "" ).strip() if not CHAT_FILE_ID_PATTERN.fullmatch( normalized_file_id ): raise HTTPException( status_code=400, detail="The file identifier is invalid.", ) now = int( time.time() ) with open_database() as connection: record = get_chat_file_record( connection, normalized_file_id, ) if not record: raise HTTPException(status_code=404, detail="The shared file was not found.") user = get_session_user(kronick_session) if room_record_for_user(int(user["id"]), str(record["room_name"])) is None: raise HTTPException(status_code=403, detail="Room access denied.") if int( record[ "expires_at" ] ) <= now: cleanup_expired_chat_files( now ) raise HTTPException( status_code=410, detail=( "The shared file has expired." ), ) file_path = resolve_chat_file_path( record[ "stored_name" ] ) if not file_path.is_file(): with open_database() as connection: connection.execute( """ DELETE FROM chat_files WHERE file_id = ? """, ( normalized_file_id, ), ) connection.commit() raise HTTPException( status_code=404, detail=( "The shared file is no longer " "available." ), ) return FileResponse( path= file_path, media_type= record[ "mime_type" ], filename= record[ "original_name" ], content_disposition_type= "attachment", headers={ "Cache-Control": "private, max-age=300", "X-Content-Type-Options": "nosniff", }, )