""" Database setup: SQLAlchemy async engine + raw SQLite FTS5 for full-text search. Schema: media — canonical media entry (one per unique title+year) media_files — individual Telegram files (multiple per media: qualities, dubs) channels — indexed channel registry index_state — per-channel last-indexed message ID for incremental indexing thumbnails — cached thumbnail metadata """ from __future__ import annotations import logging from pathlib import Path import aiosqlite from sqlalchemy import event, text from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase from app.core.config import DB_PATH, DATA_DIR, SESSIONS_DIR, THUMBNAILS_DIR, CACHE_DIR, get_settings log = logging.getLogger(__name__) # ── SQLAlchemy async engine ──────────────────────────────────────────────────── def _get_engine(): settings = get_settings() engine = create_async_engine( settings.db_url, echo=settings.debug, connect_args={ "check_same_thread": False, "timeout": 30, }, ) return engine engine = _get_engine() AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) class Base(DeclarativeBase): pass async def get_db() -> AsyncSession: """FastAPI dependency: yields an async DB session.""" async with AsyncSessionLocal() as session: try: yield session except Exception: await session.rollback() raise finally: await session.close() # ── Schema creation ──────────────────────────────────────────────────────────── SCHEMA_SQL = """ PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA cache_size=-32000; -- 32 MB page cache -- Canonical media entries (movies, series, files) CREATE TABLE IF NOT EXISTS media ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, clean_title TEXT NOT NULL, -- normalized for dedup year INTEGER, media_type TEXT DEFAULT 'unknown', -- movie | series | music | document | other genre TEXT, description TEXT, poster_path TEXT, -- local thumbnail path imdb_id TEXT, tmdb_id INTEGER, language TEXT, rating REAL, duration_secs INTEGER, created_at REAL DEFAULT (unixepoch('now')), updated_at REAL DEFAULT (unixepoch('now')) ); -- Individual Telegram files (many per media entry) CREATE TABLE IF NOT EXISTS media_files ( id INTEGER PRIMARY KEY AUTOINCREMENT, media_id INTEGER NOT NULL REFERENCES media(id) ON DELETE CASCADE, channel_id TEXT NOT NULL, message_id INTEGER NOT NULL, file_id TEXT, -- Telegram file_id (for caching) file_unique_id TEXT UNIQUE, file_name TEXT, file_size INTEGER, mime_type TEXT, duration_secs INTEGER, width INTEGER, height INTEGER, resolution TEXT, -- e.g. 1080p, 4K codec TEXT, -- x264, x265, AV1 audio_codec TEXT, language TEXT, subtitles TEXT, -- JSON array of language codes release_group TEXT, quality_score INTEGER DEFAULT 0, -- higher = better quality caption TEXT, has_thumbnail INTEGER DEFAULT 0, indexed_at REAL DEFAULT (unixepoch('now')), UNIQUE(channel_id, message_id) ); -- Registered channels CREATE TABLE IF NOT EXISTS channels ( id TEXT PRIMARY KEY, -- username or numeric ID as string title TEXT, username TEXT, member_count INTEGER, is_active INTEGER DEFAULT 1, last_indexed_at REAL, total_media INTEGER DEFAULT 0, created_at REAL DEFAULT (unixepoch('now')) ); -- Incremental index state: remember last message_id per channel CREATE TABLE IF NOT EXISTS index_state ( channel_id TEXT PRIMARY KEY REFERENCES channels(id), last_message_id INTEGER DEFAULT 0, total_indexed INTEGER DEFAULT 0, updated_at REAL DEFAULT (unixepoch('now')) ); -- Standard indexes CREATE INDEX IF NOT EXISTS idx_media_files_media_id ON media_files(media_id); CREATE INDEX IF NOT EXISTS idx_media_files_channel ON media_files(channel_id); CREATE INDEX IF NOT EXISTS idx_media_type ON media(media_type); CREATE INDEX IF NOT EXISTS idx_media_year ON media(year); CREATE INDEX IF NOT EXISTS idx_media_updated ON media(updated_at DESC); CREATE INDEX IF NOT EXISTS idx_media_clean_title ON media(clean_title); CREATE INDEX IF NOT EXISTS idx_files_quality ON media_files(quality_score DESC); -- FTS5 virtual table for full-text search (ranks by BM25 automatically) CREATE VIRTUAL TABLE IF NOT EXISTS media_fts USING fts5( title, description, genre, language, content='media', content_rowid='id', tokenize='porter ascii' ); -- Triggers to keep FTS in sync CREATE TRIGGER IF NOT EXISTS media_ai AFTER INSERT ON media BEGIN INSERT INTO media_fts(rowid, title, description, genre, language) VALUES (new.id, new.title, new.description, new.genre, new.language); END; CREATE TRIGGER IF NOT EXISTS media_ad AFTER DELETE ON media BEGIN INSERT INTO media_fts(media_fts, rowid, title, description, genre, language) VALUES ('delete', old.id, old.title, old.description, old.genre, old.language); END; CREATE TRIGGER IF NOT EXISTS media_au AFTER UPDATE ON media BEGIN INSERT INTO media_fts(media_fts, rowid, title, description, genre, language) VALUES ('delete', old.id, old.title, old.description, old.genre, old.language); INSERT INTO media_fts(rowid, title, description, genre, language) VALUES (new.id, new.title, new.description, new.genre, new.language); END; """ async def init_db() -> None: """Create directories, apply schema, ensure FTS is populated.""" # Ensure data directories exist for d in [DATA_DIR, SESSIONS_DIR, THUMBNAILS_DIR, CACHE_DIR]: d.mkdir(parents=True, exist_ok=True) # Apply schema via raw aiosqlite (DDL with FTS5 needs raw SQLite) async with aiosqlite.connect(DB_PATH) as db: await db.executescript(SCHEMA_SQL) await db.commit() log.info("Database initialized at %s", DB_PATH)