import os import secrets from contextlib import asynccontextmanager from typing import AsyncIterator, Dict, List, Optional import aiosqlite from cfg import ( DB_DIR, DB_PATH, DEF_BTN_COUNT, DEF_MAX_ATTEMPTS, DEF_TIMEOUT, DEF_WARN_ACTION, DEF_WARN_DURATION, DEF_WARN_EXPIRE, DEF_WARN_LIMIT, ) # Колонки настроек чата, которые можно менять. CFG_COLS = ( "btn_count", "timeout", "max_attempts", "warn_limit", "warn_action", "warn_duration", ) SQL_TABLES = ( "CREATE TABLE IF NOT EXISTS chat_cfg (" "chat_id INTEGER PRIMARY KEY, " "btn_count INTEGER DEFAULT 3, " "timeout INTEGER DEFAULT 30, " "max_attempts INTEGER DEFAULT 3, " "warn_limit INTEGER DEFAULT 3, " "warn_action TEXT DEFAULT 'mute', " "warn_duration INTEGER DEFAULT 3600)", "CREATE TABLE IF NOT EXISTS chats (" "chat_id INTEGER PRIMARY KEY, " "title TEXT, " "type TEXT, " "added_at INTEGER, " "updated_at INTEGER, " "active INTEGER DEFAULT 1)", "CREATE TABLE IF NOT EXISTS usr_fails (" "user_id INTEGER, " "chat_id INTEGER, " "fail_count INTEGER DEFAULT 0, " "PRIMARY KEY (user_id, chat_id))", "CREATE TABLE IF NOT EXISTS warns (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "chat_id INTEGER, " "user_id INTEGER, " "admin_id INTEGER, " "reason TEXT, " "created_at INTEGER, " "expires_at INTEGER)", "CREATE TABLE IF NOT EXISTS punish (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "chat_id INTEGER, " "user_id INTEGER, " "kind TEXT, " "admin_id INTEGER, " "reason TEXT, " "created_at INTEGER, " "until INTEGER, " "active INTEGER DEFAULT 1)", "CREATE TABLE IF NOT EXISTS mod_log (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "chat_id INTEGER, " "admin_id INTEGER, " "target_id INTEGER, " "action TEXT, " "reason TEXT, " "created_at INTEGER)", "CREATE TABLE IF NOT EXISTS adm_perms (" "chat_id INTEGER, " "user_id INTEGER, " "perm TEXT, " "allow INTEGER, " "PRIMARY KEY (chat_id, user_id, perm))", "CREATE TABLE IF NOT EXISTS web_sessions (" "token TEXT PRIMARY KEY, " "user_id INTEGER, " "created_at INTEGER, " "expires_at INTEGER)", "CREATE TABLE IF NOT EXISTS web_users (" "user_id INTEGER PRIMARY KEY, " "first_name TEXT, " "last_name TEXT, " "username TEXT, " "photo_url TEXT, " "last_login INTEGER)", "CREATE TABLE IF NOT EXISTS users (" "user_id INTEGER PRIMARY KEY, " "username TEXT, " "first_name TEXT, " "last_name TEXT, " "updated_at INTEGER)", "CREATE TABLE IF NOT EXISTS reports (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "chat_id INTEGER, " "user_id INTEGER, " "target_id INTEGER, " "text TEXT, " "created_at INTEGER, " "status TEXT DEFAULT 'new')", "CREATE TABLE IF NOT EXISTS report_block (" "user_id INTEGER, " "chat_id INTEGER, " "until INTEGER, " "PRIMARY KEY (user_id, chat_id))", "CREATE TABLE IF NOT EXISTS alarm (" "chat_id INTEGER PRIMARY KEY, " "enabled INTEGER DEFAULT 0, " "enabled_by INTEGER, " "enabled_at INTEGER, " "raid_until INTEGER)", ) @asynccontextmanager async def db_conn() -> AsyncIterator[aiosqlite.Connection]: # busy_timeout предотвращает ошибку "database is locked" при параллельных апдейтах. conn = await aiosqlite.connect(DB_PATH) conn.row_factory = aiosqlite.Row try: await conn.execute("PRAGMA busy_timeout=5000") yield conn finally: await conn.close() async def tbl_exists(db: aiosqlite.Connection, name: str) -> bool: async with db.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,) ) as cur: return await cur.fetchone() is not None async def col_exists(db: aiosqlite.Connection, table: str, col: str) -> bool: async with db.execute(f"PRAGMA table_info({table})") as cur: cols = [r[1] for r in await cur.fetchall()] return col in cols async def migrate_db(db: aiosqlite.Connection) -> None: # Обратная совместимость: таблицы переименованы при рефакторинге. if await tbl_exists(db, "chat_settings") and not await tbl_exists(db, "chat_cfg"): await db.execute("ALTER TABLE chat_settings RENAME TO chat_cfg") if await tbl_exists(db, "user_violations") and not await tbl_exists(db, "usr_fails"): await db.execute("ALTER TABLE user_violations RENAME TO usr_fails") # Дополняем chat_cfg колонками системы предупреждений. if await tbl_exists(db, "chat_cfg"): if not await col_exists(db, "chat_cfg", "warn_limit"): await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_limit INTEGER DEFAULT 3") if not await col_exists(db, "chat_cfg", "warn_action"): await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_action TEXT DEFAULT 'mute'") if not await col_exists(db, "chat_cfg", "warn_duration"): await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_duration INTEGER DEFAULT 3600") async def init_db() -> None: # Создание каталога обязательно: без него sqlite не откроет файл БД. os.makedirs(DB_DIR, exist_ok=True) async with aiosqlite.connect(DB_PATH) as db: await db.execute("PRAGMA journal_mode=WAL") await migrate_db(db) for sql in SQL_TABLES: await db.execute(sql) await db.commit() # --- Чаты --- async def upsert_chat(chat_id: int, title: Optional[str], ctype: Optional[str], ts: int) -> None: async with db_conn() as db: await db.execute( "INSERT INTO chats (chat_id, title, type, added_at, updated_at, active) " "VALUES (?, ?, ?, ?, ?, 1) " "ON CONFLICT(chat_id) DO UPDATE SET " "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, active=1", (chat_id, title, ctype, ts, ts), ) await db.commit() async def set_chat_active(chat_id: int, active: int) -> None: async with db_conn() as db: await db.execute("UPDATE chats SET active=? WHERE chat_id=?", (active, chat_id)) await db.commit() async def list_chats(active_only: bool = True) -> List[dict]: q = "SELECT * FROM chats" if active_only: q += " WHERE active=1" q += " ORDER BY title COLLATE NOCASE" async with db_conn() as db: async with db.execute(q) as cur: return [dict(r) for r in await cur.fetchall()] async def get_chat(chat_id: int) -> Optional[dict]: async with db_conn() as db: async with db.execute("SELECT * FROM chats WHERE chat_id=?", (chat_id,)) as cur: row = await cur.fetchone() return dict(row) if row else None # --- Настройки чата --- def _cfg_defaults() -> Dict: return { "btn_count": DEF_BTN_COUNT, "timeout": DEF_TIMEOUT, "max_attempts": DEF_MAX_ATTEMPTS, "warn_limit": DEF_WARN_LIMIT, "warn_action": DEF_WARN_ACTION, "warn_duration": DEF_WARN_DURATION, } async def get_chat_cfg(chat_id: int) -> Dict: async with db_conn() as db: async with db.execute("SELECT * FROM chat_cfg WHERE chat_id=?", (chat_id,)) as cur: row = await cur.fetchone() cfg = _cfg_defaults() if row: for key in CFG_COLS: if row[key] is not None: cfg[key] = row[key] return cfg async def save_chat_cfg(chat_id: int, **fields) -> None: # Частичный upsert: обновляются только переданные колонки. data = {k: v for k, v in fields.items() if k in CFG_COLS} if not data: return cols = ["chat_id"] + list(data) marks = ",".join("?" for _ in cols) updates = ",".join(f"{k}=excluded.{k}" for k in data) async with db_conn() as db: await db.execute( f"INSERT INTO chat_cfg ({','.join(cols)}) VALUES ({marks}) " f"ON CONFLICT(chat_id) DO UPDATE SET {updates}", [chat_id] + list(data.values()), ) await db.commit() # --- Нарушения капчи --- async def get_fail_cnt(user_id: int, chat_id: int) -> int: async with db_conn() as db: async with db.execute( "SELECT fail_count FROM usr_fails WHERE user_id=? AND chat_id=?", (user_id, chat_id), ) as cur: row = await cur.fetchone() return row[0] if row else 0 async def inc_fail_cnt(user_id: int, chat_id: int) -> None: async with db_conn() as db: await db.execute( "INSERT INTO usr_fails (user_id, chat_id, fail_count) VALUES (?, ?, 1) " "ON CONFLICT(user_id, chat_id) DO UPDATE SET fail_count = fail_count + 1", (user_id, chat_id), ) await db.commit() async def rst_fail_cnt(user_id: int, chat_id: int) -> None: async with db_conn() as db: await db.execute( "DELETE FROM usr_fails WHERE user_id=? AND chat_id=?", (user_id, chat_id) ) await db.commit() # --- Варны --- async def add_warn(chat_id: int, user_id: int, admin_id: int, reason: str, ts: int, expire: int) -> int: async with db_conn() as db: cur = await db.execute( "INSERT INTO warns (chat_id, user_id, admin_id, reason, created_at, expires_at) " "VALUES (?, ?, ?, ?, ?, ?)", (chat_id, user_id, admin_id, reason, ts, ts + expire), ) await db.commit() return cur.lastrowid async def cnt_warns(chat_id: int, user_id: int, ts: int) -> int: async with db_conn() as db: async with db.execute( "SELECT COUNT(*) FROM warns WHERE chat_id=? AND user_id=? AND (expires_at IS NULL OR expires_at > ?)", (chat_id, user_id, ts), ) as cur: return (await cur.fetchone())[0] async def list_warns(chat_id: int, user_id: Optional[int] = None) -> List[dict]: q = "SELECT * FROM warns WHERE chat_id=?" args: list = [chat_id] if user_id is not None: q += " AND user_id=?" args.append(user_id) q += " ORDER BY created_at DESC" async with db_conn() as db: async with db.execute(q, args) as cur: return [dict(r) for r in await cur.fetchall()] async def del_last_warn(chat_id: int, user_id: int) -> bool: async with db_conn() as db: async with db.execute( "SELECT id FROM warns WHERE chat_id=? AND user_id=? ORDER BY created_at DESC, id DESC LIMIT 1", (chat_id, user_id), ) as cur: row = await cur.fetchone() if not row: return False await db.execute("DELETE FROM warns WHERE id=?", (row["id"],)) await db.commit() return True async def clr_warns(chat_id: int, user_id: int) -> None: async with db_conn() as db: await db.execute("DELETE FROM warns WHERE chat_id=? AND user_id=?", (chat_id, user_id)) await db.commit() async def exp_warns(ts: int) -> None: # Уборка просроченных варнов. async with db_conn() as db: await db.execute("DELETE FROM warns WHERE expires_at IS NOT NULL AND expires_at <= ?", (ts,)) await db.commit() # --- Наказания (муты/баны) --- async def add_punish(chat_id: int, user_id: int, kind: str, admin_id: int, reason: str, ts: int, until: Optional[int]) -> int: async with db_conn() as db: await db.execute( "UPDATE punish SET active=0 WHERE chat_id=? AND user_id=? AND kind=? AND active=1", (chat_id, user_id, kind), ) cur = await db.execute( "INSERT INTO punish (chat_id, user_id, kind, admin_id, reason, created_at, until, active) " "VALUES (?, ?, ?, ?, ?, ?, ?, 1)", (chat_id, user_id, kind, admin_id, reason, ts, until), ) await db.commit() return cur.lastrowid async def end_punish(chat_id: int, user_id: int, kind: str) -> None: async with db_conn() as db: await db.execute( "UPDATE punish SET active=0 WHERE chat_id=? AND user_id=? AND kind=? AND active=1", (chat_id, user_id, kind), ) await db.commit() async def get_punish(chat_id: int, user_id: int, kind: str) -> Optional[dict]: async with db_conn() as db: async with db.execute( "SELECT * FROM punish WHERE chat_id=? AND user_id=? AND kind=? AND active=1 " "ORDER BY id DESC LIMIT 1", (chat_id, user_id, kind), ) as cur: row = await cur.fetchone() return dict(row) if row else None async def list_punish(chat_id: Optional[int] = None, active_only: bool = True) -> List[dict]: q = "SELECT * FROM punish WHERE 1=1" args: list = [] if chat_id is not None: q += " AND chat_id=?" args.append(chat_id) if active_only: q += " AND active=1" q += " ORDER BY created_at DESC" async with db_conn() as db: async with db.execute(q, args) as cur: return [dict(r) for r in await cur.fetchall()] async def due_unbans(ts: int) -> List[dict]: # Активные наказания, срок которых истёк и которые нужно снять. async with db_conn() as db: async with db.execute( "SELECT * FROM punish WHERE active=1 AND until IS NOT NULL AND until <= ?", (ts,) ) as cur: return [dict(r) for r in await cur.fetchall()] async def hist_punish(chat_id: int, user_id: int) -> List[dict]: # Полная история мутов/банов пользователя в чате. async with db_conn() as db: async with db.execute( "SELECT * FROM punish WHERE chat_id=? AND user_id=? ORDER BY created_at DESC", (chat_id, user_id), ) as cur: return [dict(r) for r in await cur.fetchall()] async def stats(ts: int) -> dict: # Сводная статистика для дашборда панели. async with db_conn() as db: async def one(q: str, args: tuple = ()): async with db.execute(q, args) as cur: return (await cur.fetchone())[0] return { "chats": await one("SELECT COUNT(*) FROM chats WHERE active=1"), "warns": await one( "SELECT COUNT(*) FROM warns WHERE expires_at IS NULL OR expires_at > ?", (ts,) ), "mutes": await one("SELECT COUNT(*) FROM punish WHERE active=1 AND kind='mute'"), "bans": await one("SELECT COUNT(*) FROM punish WHERE active=1 AND kind='ban'"), "logs": await one("SELECT COUNT(*) FROM mod_log"), "web_users": await one("SELECT COUNT(*) FROM web_users"), } async def stats_scoped(ids, ts: int) -> dict: # Статистика только по доступным пользователю чатам (для дашборда). result = {"chats": len(ids), "warns": 0, "mutes": 0, "bans": 0, "logs": 0} ids = list(ids) if not ids: return result ph = ",".join("?" for _ in ids) async with db_conn() as db: async def one(q: str, args: tuple): async with db.execute(q, args) as cur: return (await cur.fetchone())[0] result["warns"] = await one( f"SELECT COUNT(*) FROM warns WHERE chat_id IN ({ph}) " f"AND (expires_at IS NULL OR expires_at > ?)", tuple(ids) + (ts,), ) result["mutes"] = await one( f"SELECT COUNT(*) FROM punish WHERE chat_id IN ({ph}) AND active=1 AND kind='mute'", tuple(ids), ) result["bans"] = await one( f"SELECT COUNT(*) FROM punish WHERE chat_id IN ({ph}) AND active=1 AND kind='ban'", tuple(ids), ) result["logs"] = await one( f"SELECT COUNT(*) FROM mod_log WHERE chat_id IN ({ph})", tuple(ids) ) return result async def add_log(chat_id: int, admin_id: int, target_id: int, action: str, reason: str, ts: int) -> None: async with db_conn() as db: await db.execute( "INSERT INTO mod_log (chat_id, admin_id, target_id, action, reason, created_at) " "VALUES (?, ?, ?, ?, ?, ?)", (chat_id, admin_id, target_id, action, reason or "", ts), ) await db.commit() async def list_log(chat_id: Optional[int] = None, limit: int = 100) -> List[dict]: if chat_id is None: q = "SELECT * FROM mod_log ORDER BY created_at DESC LIMIT ?" args: list = [limit] else: q = "SELECT * FROM mod_log WHERE chat_id=? ORDER BY created_at DESC LIMIT ?" args = [chat_id, limit] async with db_conn() as db: async with db.execute(q, args) as cur: return [dict(r) for r in await cur.fetchall()] # --- Права администраторов --- async def set_perm(chat_id: int, user_id: int, perm: str, allow: bool) -> None: async with db_conn() as db: await db.execute( "INSERT INTO adm_perms (chat_id, user_id, perm, allow) VALUES (?, ?, ?, ?) " "ON CONFLICT(chat_id, user_id, perm) DO UPDATE SET allow=excluded.allow", (chat_id, user_id, perm, 1 if allow else 0), ) await db.commit() async def get_perm_row(chat_id: int, user_id: int, perm: str) -> Optional[int]: async with db_conn() as db: async with db.execute( "SELECT allow FROM adm_perms WHERE chat_id=? AND user_id=? AND perm=?", (chat_id, user_id, perm), ) as cur: row = await cur.fetchone() return row[0] if row else None async def list_perm_rows(chat_id: int) -> List[dict]: async with db_conn() as db: async with db.execute("SELECT * FROM adm_perms WHERE chat_id=?", (chat_id,)) as cur: return [dict(r) for r in await cur.fetchall()] async def del_user_perms(chat_id: int, user_id: int) -> None: async with db_conn() as db: await db.execute("DELETE FROM adm_perms WHERE chat_id=? AND user_id=?", (chat_id, user_id)) await db.commit() # --- Веб-сессии и пользователи панели --- async def create_sess(user_id: int, ts: int, ttl: int) -> str: token = secrets.token_urlsafe(32) async with db_conn() as db: await db.execute( "INSERT INTO web_sessions (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)", (token, user_id, ts, ts + ttl), ) await db.commit() return token async def get_sess(token: str, ts: int) -> Optional[dict]: async with db_conn() as db: async with db.execute( "SELECT * FROM web_sessions WHERE token=? AND expires_at > ?", (token, ts) ) as cur: row = await cur.fetchone() return dict(row) if row else None async def del_sess(token: str) -> None: async with db_conn() as db: await db.execute("DELETE FROM web_sessions WHERE token=?", (token,)) await db.commit() async def upsert_web_user(user_id: int, first_name: str, last_name: str, username: str, photo_url: str, ts: int) -> None: async with db_conn() as db: await db.execute( "INSERT INTO web_users (user_id, first_name, last_name, username, photo_url, last_login) " "VALUES (?, ?, ?, ?, ?, ?) " "ON CONFLICT(user_id) DO UPDATE SET " "first_name=excluded.first_name, last_name=excluded.last_name, " "username=excluded.username, photo_url=excluded.photo_url, last_login=excluded.last_login", (user_id, first_name, last_name, username, photo_url, ts), ) await db.commit() async def get_web_user(user_id: int) -> Optional[dict]: async with db_conn() as db: async with db.execute("SELECT * FROM web_users WHERE user_id=?", (user_id,)) as cur: row = await cur.fetchone() return dict(row) if row else None # --- Кеш пользователей (для поиска по @username) --- async def upsert_user(user_id: int, username: Optional[str], first_name: Optional[str], last_name: Optional[str], ts: int) -> None: async with db_conn() as db: await db.execute( "INSERT INTO users (user_id, username, first_name, last_name, updated_at) " "VALUES (?, ?, ?, ?, ?) " "ON CONFLICT(user_id) DO UPDATE SET " "username=excluded.username, first_name=excluded.first_name, " "last_name=excluded.last_name, updated_at=excluded.updated_at", (user_id, username, first_name, last_name, ts), ) await db.commit() async def find_user_by_username(username: str) -> Optional[dict]: async with db_conn() as db: async with db.execute( "SELECT * FROM users WHERE lower(username)=lower(?) ORDER BY updated_at DESC LIMIT 1", (username.lstrip("@"),), ) as cur: row = await cur.fetchone() return dict(row) if row else None async def get_user(user_id: int) -> Optional[dict]: async with db_conn() as db: async with db.execute("SELECT * FROM users WHERE user_id=?", (user_id,)) as cur: row = await cur.fetchone() return dict(row) if row else None # --- Репорты --- async def add_report(chat_id: int, user_id: int, target_id: int, text: str, ts: int) -> int: async with db_conn() as db: cur = await db.execute( "INSERT INTO reports (chat_id, user_id, target_id, text, created_at, status) " "VALUES (?, ?, ?, ?, ?, 'new')", (chat_id, user_id, target_id, text, ts), ) await db.commit() return cur.lastrowid async def list_reports(chat_id: int, limit: int = 200) -> List[dict]: async with db_conn() as db: async with db.execute( "SELECT * FROM reports WHERE chat_id=? ORDER BY created_at DESC LIMIT ?", (chat_id, limit), ) as cur: return [dict(r) for r in await cur.fetchall()] async def cnt_reports_since(chat_id: int, user_id: int, since: int) -> int: async with db_conn() as db: async with db.execute( "SELECT COUNT(*) FROM reports WHERE chat_id=? AND user_id=? AND created_at >= ?", (chat_id, user_id, since), ) as cur: return (await cur.fetchone())[0] async def close_report(report_id: int) -> None: async with db_conn() as db: await db.execute("UPDATE reports SET status='closed' WHERE id=?", (report_id,)) await db.commit() async def report_block_until(chat_id: int, user_id: int) -> int: async with db_conn() as db: async with db.execute( "SELECT until FROM report_block WHERE chat_id=? AND user_id=?", (chat_id, user_id) ) as cur: row = await cur.fetchone() return row[0] if row else 0 async def set_report_block(chat_id: int, user_id: int, until: int) -> None: async with db_conn() as db: await db.execute( "INSERT INTO report_block (user_id, chat_id, until) VALUES (?, ?, ?) " "ON CONFLICT(user_id, chat_id) DO UPDATE SET until=excluded.until", (user_id, chat_id, until), ) await db.commit() # --- Режим тревоги --- async def get_alarm(chat_id: int) -> dict: async with db_conn() as db: async with db.execute("SELECT * FROM alarm WHERE chat_id=?", (chat_id,)) as cur: row = await cur.fetchone() if row: return dict(row) return {"chat_id": chat_id, "enabled": 0, "enabled_by": 0, "enabled_at": 0, "raid_until": 0} async def set_alarm(chat_id: int, enabled: bool, by: int, ts: int) -> None: async with db_conn() as db: await db.execute( "INSERT INTO alarm (chat_id, enabled, enabled_by, enabled_at, raid_until) " "VALUES (?, ?, ?, ?, 0) " "ON CONFLICT(chat_id) DO UPDATE SET " "enabled=excluded.enabled, enabled_by=excluded.enabled_by, enabled_at=excluded.enabled_at", (chat_id, 1 if enabled else 0, by, ts), ) # При выключении сбрасываем принудительный кик. if not enabled: await db.execute("UPDATE alarm SET raid_until=0 WHERE chat_id=?", (chat_id,)) await db.commit() async def set_raid_until(chat_id: int, until: int) -> None: async with db_conn() as db: await db.execute("UPDATE alarm SET raid_until=? WHERE chat_id=?", (until, chat_id)) await db.commit() async def list_alarm_chats() -> List[dict]: async with db_conn() as db: async with db.execute("SELECT * FROM alarm WHERE enabled=1") as cur: return [dict(r) for r in await cur.fetchall()]