From e9beed9f31f7974843c8dbf489cb8ab5c9dec3ff Mon Sep 17 00:00:00 2001
From: Roman Sergienko <romasergienko@outlook.com>
Date: Sat, 10 Oct 2026 16:02:26 +0000
Subject: [PATCH] fix: формат /labmem; feat: /worldline считается из метрик чата (сообщения/участники/наказания) с полями притяжения

---
 db.py |  173 +++++++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 148 insertions(+), 25 deletions(-)

diff --git a/db.py b/db.py
index 35bd0e3..0a83bd8 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,16 @@
     "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)",
 )
 
 
@@ -151,14 +187,33 @@
         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")
 
 
 async def init_db() -> None:
@@ -177,10 +232,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 +275,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 +662,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 +737,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 +762,52 @@
         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

--
Gitblit v1.9.3