From 47fba49d1835442f096739b92a3dd3ed9476470b Mon Sep 17 00:00:00 2001
From: Roman Sergienko <romasergienko@outlook.com>
Date: Fri, 04 Dec 2026 11:14:16 +0000
Subject: [PATCH] Fix API error handling: return JSON on auth failure for API routes

---
 db.py |  328 ++++++++++++++++++++++++++++++++++++++++++++++++++----
 1 files changed, 303 insertions(+), 25 deletions(-)

diff --git a/db.py b/db.py
index 35bd0e3..22994a7 100644
--- a/db.py
+++ b/db.py
@@ -9,7 +9,15 @@
     DB_DIR,
     DB_PATH,
     DEF_BTN_COUNT,
+    DEF_FLOOD_ALARM_MUTE,
+    DEF_FLOOD_COUNT,
+    DEF_FLOOD_ENABLED,
+    DEF_FLOOD_MUTE,
+    DEF_FLOOD_WINDOW,
     DEF_MAX_ATTEMPTS,
+    DEF_NEW_MEMBER_DAYS,
+    DEF_NO_LINKS,
+    DEF_SLOW_MODE,
     DEF_TIMEOUT,
     DEF_WARN_ACTION,
     DEF_WARN_DURATION,
@@ -25,6 +33,14 @@
     "warn_limit",
     "warn_action",
     "warn_duration",
+    "flood_enabled",
+    "flood_count",
+    "flood_window",
+    "flood_mute",
+    "flood_alarm_mute",
+    "new_member_days",
+    "no_links",
+    "slow_mode",
 )
 
 SQL_TABLES = (
@@ -35,14 +51,23 @@
     "max_attempts INTEGER DEFAULT 3, "
     "warn_limit INTEGER DEFAULT 3, "
     "warn_action TEXT DEFAULT 'mute', "
-    "warn_duration INTEGER DEFAULT 3600)",
+    "warn_duration INTEGER DEFAULT 3600, "
+    "flood_enabled INTEGER DEFAULT 1, "
+    "flood_count INTEGER DEFAULT 10, "
+    "flood_window INTEGER DEFAULT 5, "
+    "flood_mute INTEGER DEFAULT 30, "
+    "flood_alarm_mute INTEGER DEFAULT 86400, "
+    "new_member_days INTEGER DEFAULT 7, "
+    "no_links INTEGER DEFAULT 0, "
+    "slow_mode INTEGER DEFAULT 10)",
     "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)",
+    "active INTEGER DEFAULT 1, "
+    "msgs INTEGER DEFAULT 0)",
     "CREATE TABLE IF NOT EXISTS usr_fails ("
     "user_id INTEGER, "
     "chat_id INTEGER, "
@@ -105,7 +130,9 @@
     "target_id INTEGER, "
     "text TEXT, "
     "created_at INTEGER, "
-    "status TEXT DEFAULT 'new')",
+    "status TEXT DEFAULT 'new', "
+    "target_msg_id INTEGER DEFAULT 0, "
+    "target_text TEXT DEFAULT '')",
     "CREATE TABLE IF NOT EXISTS report_block ("
     "user_id INTEGER, "
     "chat_id INTEGER, "
@@ -116,7 +143,38 @@
     "enabled INTEGER DEFAULT 0, "
     "enabled_by INTEGER, "
     "enabled_at INTEGER, "
-    "raid_until INTEGER)",
+    "raid_until INTEGER, "
+    "until INTEGER DEFAULT 0)",
+    "CREATE TABLE IF NOT EXISTS member_join ("
+    "chat_id INTEGER, "
+    "user_id INTEGER, "
+    "joined_at INTEGER, "
+    "PRIMARY KEY (chat_id, user_id))",
+    "CREATE TABLE IF NOT EXISTS dm_users ("
+    "user_id INTEGER PRIMARY KEY, "
+    "ts INTEGER)",
+    "CREATE TABLE IF NOT EXISTS messages ("
+    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+    "chat_id INTEGER, "
+    "user_id INTEGER, "
+    "name TEXT, "
+    "text TEXT, "
+    "created_at INTEGER, "
+    "tg_msg_id INTEGER DEFAULT 0, "
+    "media_type TEXT DEFAULT '', "
+    "media_file_id TEXT DEFAULT '', "
+    "reply_to_tg INTEGER DEFAULT 0, "
+    "reply_to_name TEXT DEFAULT '', "
+    "reply_to_text TEXT DEFAULT '')",
+    "CREATE TABLE IF NOT EXISTS rp_actions ("
+    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+    "chat_id INTEGER, "
+    "trigger TEXT COLLATE NOCASE, "
+    "response_text TEXT, "
+    "gif_file_id TEXT, "
+    "enabled INTEGER DEFAULT 1, "
+    "created_at INTEGER, "
+    "UNIQUE(chat_id, trigger))",
 )
 
 
@@ -151,14 +209,45 @@
         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 колонками системы предупреждений.
+    # Дополняем 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")
+        add_cols = {
+            "warn_limit": "INTEGER DEFAULT 3",
+            "warn_action": "TEXT DEFAULT 'mute'",
+            "warn_duration": "INTEGER DEFAULT 3600",
+            "flood_enabled": "INTEGER DEFAULT 1",
+            "flood_count": "INTEGER DEFAULT 10",
+            "flood_window": "INTEGER DEFAULT 5",
+            "flood_mute": "INTEGER DEFAULT 30",
+            "flood_alarm_mute": "INTEGER DEFAULT 86400",
+            "new_member_days": "INTEGER DEFAULT 7",
+            "no_links": "INTEGER DEFAULT 0",
+            "slow_mode": "INTEGER DEFAULT 10",
+        }
+        for col, ddl in add_cols.items():
+            if not await col_exists(db, "chat_cfg", col):
+                await db.execute(f"ALTER TABLE chat_cfg ADD COLUMN {col} {ddl}")
+    if await tbl_exists(db, "alarm") and not await col_exists(db, "alarm", "until"):
+        await db.execute("ALTER TABLE alarm ADD COLUMN until INTEGER DEFAULT 0")
+    if await tbl_exists(db, "reports"):
+        if not await col_exists(db, "reports", "target_msg_id"):
+            await db.execute("ALTER TABLE reports ADD COLUMN target_msg_id INTEGER DEFAULT 0")
+        if not await col_exists(db, "reports", "target_text"):
+            await db.execute("ALTER TABLE reports ADD COLUMN target_text TEXT DEFAULT ''")
+    if await tbl_exists(db, "chats") and not await col_exists(db, "chats", "msgs"):
+        await db.execute("ALTER TABLE chats ADD COLUMN msgs INTEGER DEFAULT 0")
+    if await tbl_exists(db, "messages"):
+        msg_cols = {
+            "tg_msg_id": "INTEGER DEFAULT 0",
+            "media_type": "TEXT DEFAULT ''",
+            "media_file_id": "TEXT DEFAULT ''",
+            "reply_to_tg": "INTEGER DEFAULT 0",
+            "reply_to_name": "TEXT DEFAULT ''",
+            "reply_to_text": "TEXT DEFAULT ''",
+        }
+        for col, ddl in msg_cols.items():
+            if not await col_exists(db, "messages", col):
+                await db.execute(f"ALTER TABLE messages ADD COLUMN {col} {ddl}")
 
 
 async def init_db() -> None:
@@ -177,10 +266,11 @@
 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) "
+            "INSERT INTO chats (chat_id, title, type, added_at, updated_at, active, msgs) "
+            "VALUES (?, ?, ?, ?, ?, 1, 1) "
             "ON CONFLICT(chat_id) DO UPDATE SET "
-            "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, active=1",
+            "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, "
+            "active=1, msgs=msgs+1",
             (chat_id, title, ctype, ts, ts),
         )
         await db.commit()
@@ -219,6 +309,14 @@
         "warn_limit": DEF_WARN_LIMIT,
         "warn_action": DEF_WARN_ACTION,
         "warn_duration": DEF_WARN_DURATION,
+        "flood_enabled": DEF_FLOOD_ENABLED,
+        "flood_count": DEF_FLOOD_COUNT,
+        "flood_window": DEF_FLOOD_WINDOW,
+        "flood_mute": DEF_FLOOD_MUTE,
+        "flood_alarm_mute": DEF_FLOOD_ALARM_MUTE,
+        "new_member_days": DEF_NEW_MEMBER_DAYS,
+        "no_links": DEF_NO_LINKS,
+        "slow_mode": DEF_SLOW_MODE,
     }
 
 
@@ -598,15 +696,28 @@
 
 # --- Репорты ---
 
-async def add_report(chat_id: int, user_id: int, target_id: int, text: str, ts: int) -> int:
+async def add_report(chat_id: int, user_id: int, target_id: int, text: str, ts: int, target_msg_id: int = 0, target_text: str = "") -> 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),
+            "INSERT INTO reports (chat_id, user_id, target_id, text, created_at, status, target_msg_id, target_text) "
+            "VALUES (?, ?, ?, ?, ?, 'new', ?, ?)",
+            (chat_id, user_id, target_id, text, ts, target_msg_id, target_text),
         )
         await db.commit()
         return cur.lastrowid
+
+
+async def get_report(report_id: int) -> Optional[dict]:
+    async with db_conn() as db:
+        async with db.execute("SELECT * FROM reports WHERE id=?", (report_id,)) as cur:
+            row = await cur.fetchone()
+    return dict(row) if row else None
+
+
+async def clr_reports(chat_id: int) -> None:
+    async with db_conn() as db:
+        await db.execute("DELETE FROM reports WHERE chat_id=?", (chat_id,))
+        await db.commit()
 
 
 async def list_reports(chat_id: int, limit: int = 200) -> List[dict]:
@@ -660,19 +771,20 @@
             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}
+    return {"chat_id": chat_id, "enabled": 0, "enabled_by": 0, "enabled_at": 0, "raid_until": 0, "until": 0}
 
 
-async def set_alarm(chat_id: int, enabled: bool, by: int, ts: int) -> None:
+async def set_alarm(chat_id: int, enabled: bool, by: int, ts: int, until: int = 0) -> None:
     async with db_conn() as db:
         await db.execute(
-            "INSERT INTO alarm (chat_id, enabled, enabled_by, enabled_at, raid_until) "
-            "VALUES (?, ?, ?, ?, 0) "
+            "INSERT INTO alarm (chat_id, enabled, enabled_by, enabled_at, raid_until, 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),
+            "enabled=excluded.enabled, enabled_by=excluded.enabled_by, "
+            "enabled_at=excluded.enabled_at, until=excluded.until",
+            (chat_id, 1 if enabled else 0, by, ts, until if enabled else 0),
         )
-        # При выключении сбрасываем принудительный кик.
+        # При выключении сбрасываем авто-кик.
         if not enabled:
             await db.execute("UPDATE alarm SET raid_until=0 WHERE chat_id=?", (chat_id,))
         await db.commit()
@@ -684,7 +796,173 @@
         await db.commit()
 
 
+async def expired_alarms(ts: int) -> List[dict]:
+    async with db_conn() as db:
+        async with db.execute(
+            "SELECT * FROM alarm WHERE enabled=1 AND until > 0 AND until <= ?", (ts,)
+        ) as cur:
+            return [dict(r) for r in await cur.fetchall()]
+
+
 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()]
+
+
+# --- Время входа и ЛС-подписка ---
+
+async def set_join(chat_id: int, user_id: int, ts: int) -> None:
+    async with db_conn() as db:
+        await db.execute(
+            "INSERT INTO member_join (chat_id, user_id, joined_at) VALUES (?, ?, ?) "
+            "ON CONFLICT(chat_id, user_id) DO UPDATE SET joined_at=excluded.joined_at",
+            (chat_id, user_id, ts),
+        )
+        await db.commit()
+
+
+async def get_join(chat_id: int, user_id: int) -> int:
+    async with db_conn() as db:
+        async with db.execute(
+            "SELECT joined_at FROM member_join 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 add_dm(user_id: int, ts: int) -> None:
+    async with db_conn() as db:
+        await db.execute(
+            "INSERT INTO dm_users (user_id, ts) VALUES (?, ?) "
+            "ON CONFLICT(user_id) DO UPDATE SET ts=excluded.ts",
+            (user_id, ts),
+        )
+        await db.commit()
+
+
+async def has_dm(user_id: int) -> bool:
+    async with db_conn() as db:
+        async with db.execute("SELECT 1 FROM dm_users WHERE user_id=?", (user_id,)) as cur:
+            return await cur.fetchone() is not None
+
+
+# --- Последние сообщения чата ---
+
+async def add_msg(
+    chat_id: int,
+    user_id: int,
+    name: str,
+    text: str,
+    ts: int,
+    tg_msg_id: int = 0,
+    media_type: str = "",
+    media_file_id: str = "",
+    reply_to_tg: int = 0,
+    reply_to_name: str = "",
+    reply_to_text: str = "",
+    keep: int = 200,
+) -> int:
+    # Храним последние keep сообщений на чат.
+    async with db_conn() as db:
+        cur = await db.execute(
+            "INSERT INTO messages "
+            "(chat_id, user_id, name, text, created_at, tg_msg_id, media_type, media_file_id, reply_to_tg, reply_to_name, reply_to_text) "
+            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+            (chat_id, user_id, name, text, ts, tg_msg_id, media_type, media_file_id, reply_to_tg, reply_to_name, reply_to_text),
+        )
+        await db.execute(
+            "DELETE FROM messages WHERE chat_id=? AND id NOT IN "
+            "(SELECT id FROM messages WHERE chat_id=? ORDER BY id DESC LIMIT ?)",
+            (chat_id, chat_id, keep),
+        )
+        await db.commit()
+        return cur.lastrowid
+
+
+async def get_msg(msg_id: int) -> Optional[dict]:
+    async with db_conn() as db:
+        async with db.execute("SELECT * FROM messages WHERE id=?", (msg_id,)) as cur:
+            row = await cur.fetchone()
+    return dict(row) if row else None
+
+
+async def find_msg_by_tg(chat_id: int, tg_msg_id: int) -> Optional[dict]:
+    async with db_conn() as db:
+        async with db.execute(
+            "SELECT * FROM messages WHERE chat_id=? AND tg_msg_id=? ORDER BY id DESC LIMIT 1",
+            (chat_id, tg_msg_id),
+        ) as cur:
+            row = await cur.fetchone()
+    return dict(row) if row else None
+
+
+async def list_msgs(chat_id: int, limit: int = 100) -> List[dict]:
+    async with db_conn() as db:
+        async with db.execute(
+            "SELECT * FROM messages WHERE chat_id=? ORDER BY id DESC LIMIT ?", (chat_id, limit)
+        ) as cur:
+            rows = [dict(r) for r in await cur.fetchall()]
+    return rows[::-1]
+
+
+async def list_msgs_after(chat_id: int, after_id: int, limit: int = 100) -> List[dict]:
+    async with db_conn() as db:
+        async with db.execute(
+            "SELECT * FROM messages WHERE chat_id=? AND id > ? ORDER BY id ASC LIMIT ?",
+            (chat_id, after_id, limit),
+        ) as cur:
+            return [dict(r) for r in await cur.fetchall()]
+
+
+# --- RP Actions ---
+
+async def add_rp_action(chat_id: int, trigger: str, response_text: str, gif_file_id: Optional[str], ts: int) -> Optional[int]:
+    async with db_conn() as db:
+        try:
+            await db.execute(
+                "INSERT INTO rp_actions (chat_id, trigger, response_text, gif_file_id, enabled, created_at) "
+                "VALUES (?, ?, ?, ?, 1, ?)",
+                (chat_id, trigger, response_text, gif_file_id, ts),
+            )
+            await db.commit()
+            return (await db.execute("SELECT last_insert_rowid()")).fetchone()[0]
+        except Exception:
+            return None
+
+
+async def list_rp_actions(chat_id: int) -> List[dict]:
+    async with db_conn() as db:
+        async with db.execute(
+            "SELECT * FROM rp_actions WHERE chat_id=? AND enabled=1 ORDER BY created_at",
+            (chat_id,),
+        ) as cur:
+            return [dict(r) for r in await cur.fetchall()]
+
+
+async def get_rp_action(action_id: int) -> Optional[dict]:
+    async with db_conn() as db:
+        async with db.execute("SELECT * FROM rp_actions WHERE id=?", (action_id,)) as cur:
+            row = await cur.fetchone()
+    return dict(row) if row else None
+
+
+async def delete_rp_action(action_id: int) -> bool:
+    async with db_conn() as db:
+        await db.execute("DELETE FROM rp_actions WHERE id=?", (action_id,))
+        await db.commit()
+    return True
+
+
+async def check_rp_trigger(chat_id: int, text: str) -> Optional[dict]:
+    text_upper = text.upper()
+    async with db_conn() as db:
+        async with db.execute(
+            "SELECT * FROM rp_actions WHERE chat_id=? AND enabled=1",
+            (chat_id,),
+        ) as cur:
+            rows = await cur.fetchall()
+    for row in rows:
+        if row["trigger"].upper() in text_upper:
+            return dict(row)
+    return None

--
Gitblit v1.9.3