Бот для капчи в чатах
feat web: мобильная переработка (нижняя навигация, карточки), статистика по доступным чатам, уведомления об изменениях из панели
8 files modified
535 ■■■■■ changed files
db.py 30 ●●●●● patch | view | raw | blame | history
web/templates/base.html 72 ●●●●● patch | view | raw | blame | history
web/templates/captcha.html 35 ●●●●● patch | view | raw | blame | history
web/templates/chat.html 141 ●●●●● patch | view | raw | blame | history
web/templates/chats.html 60 ●●●●● patch | view | raw | blame | history
web/templates/log.html 44 ●●●●● patch | view | raw | blame | history
web/templates/users.html 93 ●●●●● patch | view | raw | blame | history
web/views.py 60 ●●●●● patch | view | raw | blame | history
db.py
@@ -405,6 +405,36 @@
        }
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(
web/templates/base.html
@@ -32,22 +32,14 @@
</head>
<body class="min-h-screen bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-100 font-sans antialiased">
<div class="flex min-h-screen">
    <!-- Затемнение под мобильным меню -->
    <div id="backdrop" class="fixed inset-0 z-30 hidden bg-black/50 md:hidden"></div>
    <aside id="sidebar"
           class="fixed inset-y-0 left-0 z-40 flex w-64 shrink-0 -translate-x-full flex-col border-r border-gray-200 bg-white transition-transform duration-200 dark:border-gray-800 dark:bg-gray-900 md:static md:translate-x-0">
        <div class="flex h-16 items-center justify-between gap-2 border-b border-gray-200 px-5 dark:border-gray-800">
            <div class="flex items-center gap-2">
                <span class="relative inline-flex h-8 w-8 items-center justify-center overflow-hidden rounded-lg bg-brand-600 font-bold text-white">
                    A
                    <img src="/avatar/bot" alt="" class="absolute inset-0 h-full w-full object-cover" onerror="this.remove()">
                </span>
                <span class="text-lg font-semibold">Amadeus</span>
            </div>
            <button id="sidebar-close" class="rounded-lg p-1.5 text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800 md:hidden" aria-label="Закрыть меню">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
    <!-- Сайдбар: только на десктопе -->
    <aside class="hidden w-64 shrink-0 flex-col border-r border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900 md:flex">
        <div class="flex h-16 items-center gap-2 border-b border-gray-200 px-5 dark:border-gray-800">
            <span class="relative inline-flex h-8 w-8 items-center justify-center overflow-hidden rounded-lg bg-brand-600 font-bold text-white">
                A
                <img src="/avatar/bot" alt="" class="absolute inset-0 h-full w-full object-cover" onerror="this.remove()">
            </span>
            <span class="text-lg font-semibold">Amadeus</span>
        </div>
        <nav class="flex-1 space-y-1 overflow-y-auto p-3 text-sm">
            {% set items = [
@@ -58,7 +50,7 @@
                ("log", "/log", "Журнал")
            ] %}
            {% for key, href, label in items %}
            <a href="{{ href }}" onclick="closeSidebar()"
            <a href="{{ href }}"
               class="flex items-center rounded-lg px-3 py-2.5 transition
               {% if active == key %}bg-brand-600 text-white shadow{% else %}text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800{% endif %}">
                {{ label }}
@@ -84,23 +76,41 @@
    </aside>
    <div class="flex min-w-0 flex-1 flex-col">
        <header class="sticky top-0 z-20 flex h-16 items-center justify-between gap-3 border-b border-gray-200 bg-white/80 px-4 backdrop-blur dark:border-gray-800 dark:bg-gray-900/80 md:px-6">
        <header class="sticky top-0 z-20 flex h-14 items-center justify-between gap-3 border-b border-gray-200 bg-white/80 px-4 backdrop-blur dark:border-gray-800 dark:bg-gray-900/80 md:h-16 md:px-6">
            <div class="flex min-w-0 items-center gap-3">
                <button id="sidebar-open" class="rounded-lg border border-gray-200 p-2 text-gray-600 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800 md:hidden" aria-label="Открыть меню">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"/></svg>
                </button>
                <h1 class="truncate text-lg font-semibold">{% block header %}{% endblock %}</h1>
                <span class="relative inline-flex h-8 w-8 items-center justify-center overflow-hidden rounded-lg bg-brand-600 font-bold text-white md:hidden">
                    A
                    <img src="/avatar/bot" alt="" class="absolute inset-0 h-full w-full object-cover" onerror="this.remove()">
                </span>
                <h1 class="truncate text-base font-semibold md:text-lg">{% block header %}{% endblock %}</h1>
            </div>
            <div class="flex items-center gap-2">
                <button id="theme-toggle" class="rounded-lg border border-gray-200 px-3 py-1.5 text-sm hover:bg-gray-100 dark:border-gray-700 dark:hover:bg-gray-800">Тема</button>
                <a href="/logout" class="rounded-lg border border-gray-200 px-3 py-1.5 text-sm hover:bg-gray-100 dark:border-gray-700 dark:hover:bg-gray-800 md:hidden">Выйти</a>
            </div>
        </header>
        <main class="space-y-6 p-4 md:p-6">
        <main class="space-y-6 p-4 pb-24 md:p-6 md:pb-6">
            {% block content %}{% endblock %}
        </main>
    </div>
</div>
<!-- Нижняя навигация: только на мобильных -->
<nav class="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t border-gray-200 bg-white/95 backdrop-blur dark:border-gray-800 dark:bg-gray-900/95 md:hidden">
    {% set nav = [
        ("dash", "/", "Главная"),
        ("chats", "/chats", "Чаты"),
        ("users", "/users", "Люди"),
        ("captcha", "/captcha", "Капчи"),
        ("log", "/log", "Журнал")
    ] %}
    {% for key, href, label in nav %}
    <a href="{{ href }}" class="flex flex-col items-center justify-center py-2.5 text-[11px] leading-tight
        {% if active == key %}text-brand-600 dark:text-brand-400 font-medium{% else %}text-gray-500 dark:text-gray-400{% endif %}">
        {{ label }}
    </a>
    {% endfor %}
</nav>
<script>
    // Переключатель тёмной/светлой темы.
@@ -109,22 +119,6 @@
        root.classList.toggle("dark");
        try { localStorage.setItem("amd-theme", root.classList.contains("dark") ? "dark" : "light"); } catch (e) {}
    });
    // Мобильное меню-«шторка».
    const sidebar = document.getElementById("sidebar");
    const backdrop = document.getElementById("backdrop");
    function openSidebar() {
        sidebar.classList.remove("-translate-x-full");
        backdrop.classList.remove("hidden");
    }
    function closeSidebar() {
        sidebar.classList.add("-translate-x-full");
        backdrop.classList.add("hidden");
    }
    document.getElementById("sidebar-open").addEventListener("click", openSidebar);
    document.getElementById("sidebar-close").addEventListener("click", closeSidebar);
    backdrop.addEventListener("click", closeSidebar);
    document.addEventListener("keydown", function (e) { if (e.key === "Escape") closeSidebar(); });
</script>
</body>
</html>
web/templates/captcha.html
@@ -3,27 +3,20 @@
{% block header %}Активные капчи{% endblock %}
{% block content %}
<div class="overflow-x-auto rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
    <table class="w-full min-w-[420px] text-sm">
        <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400">
            <tr>
                <th class="px-5 py-3 text-left font-medium">Чат</th>
                <th class="px-5 py-3 text-left font-medium">Пользователь</th>
                <th class="px-5 py-3 text-left font-medium">Осталось</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
            {% for r in rows %}
            <tr>
                <td class="px-5 py-3">{{ names.get(r.chat_id, r.chat_id) }}</td>
                <td class="px-5 py-3">{{ r.user_id }}</td>
                <td class="px-5 py-3 text-gray-500">{{ r.left }} с</td>
            </tr>
            {% else %}
            <tr><td colspan="3" class="px-5 py-8 text-center text-gray-500">Сейчас никто не проходит капчу.</td></tr>
            {% endfor %}
        </tbody>
    </table>
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
    {% for r in rows %}
    <div class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
        <div class="flex items-center justify-between gap-2">
            <span class="min-w-0 truncate font-semibold">{{ names.get(r.chat_id, r.chat_id) }}</span>
            <span class="shrink-0 rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300">{{ r.left }} с</span>
        </div>
        <div class="mt-1 text-sm text-gray-500">Пользователь {{ r.user_id }}</div>
    </div>
    {% else %}
    <div class="rounded-xl border border-gray-200 bg-white p-8 text-center text-gray-500 dark:border-gray-800 dark:bg-gray-900 sm:col-span-2 xl:col-span-3">
        Сейчас никто не проходит капчу.
    </div>
    {% endfor %}
</div>
{% endblock %}
web/templates/chat.html
@@ -4,96 +4,91 @@
{% block content %}
<div class="flex items-center gap-3">
    <img src="/avatar/{{ chat.chat_id }}" alt="" class="h-10 w-10 rounded-full bg-gray-200 object-cover dark:bg-gray-700" onerror="this.style.visibility='hidden'">
    <img src="/avatar/{{ chat.chat_id }}" alt=""
         class="h-12 w-12 rounded-full bg-gray-200 object-cover dark:bg-gray-700"
         onerror="this.style.visibility='hidden'">
    <div class="text-sm text-gray-500">id {{ chat.chat_id }} · {{ chat.type }}</div>
</div>
<section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm">
    <h2 class="font-semibold mb-4">Настройки</h2>
    <form method="post" action="/chats/cfg" class="grid md:grid-cols-3 gap-4">
<section class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900 md:p-5">
    <h2 class="mb-4 font-semibold">Настройки</h2>
    <form method="post" action="/chats/cfg" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <input type="hidden" name="chat_id" value="{{ chat.chat_id }}">
        <label class="text-sm">Кнопок капчи
            <input name="btn_count" type="number" min="1" max="9" value="{{ cfg.btn_count }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="btn_count" type="number" min="1" max="9" value="{{ cfg.btn_count }}" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <label class="text-sm">Таймаут, сек
            <input name="timeout" type="number" min="5" max="300" value="{{ cfg.timeout }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="timeout" type="number" min="5" max="300" value="{{ cfg.timeout }}" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <label class="text-sm">Попыток до наказания
            <input name="max_attempts" type="number" min="1" max="10" value="{{ cfg.max_attempts }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="max_attempts" type="number" min="1" max="10" value="{{ cfg.max_attempts }}" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <label class="text-sm">Лимит варнов
            <input name="warn_limit" type="number" min="1" max="10" value="{{ cfg.warn_limit }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="warn_limit" type="number" min="1" max="10" value="{{ cfg.warn_limit }}" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <label class="text-sm">Действие при лимите
            <select name="warn_action" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <select name="warn_action" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
                <option value="mute" {% if cfg.warn_action == "mute" %}selected{% endif %}>мут</option>
                <option value="ban" {% if cfg.warn_action == "ban" %}selected{% endif %}>бан</option>
            </select>
        </label>
        <label class="text-sm">Длительность наказания, сек
            <input name="warn_duration" type="number" min="0" max="2592000" value="{{ cfg.warn_duration }}" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="warn_duration" type="number" min="0" max="2592000" value="{{ cfg.warn_duration }}" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <div class="md:col-span-3">
            <button class="rounded-lg bg-brand-600 hover:bg-brand-700 px-4 py-2 text-sm font-medium text-white">Сохранить</button>
        <div class="sm:col-span-2 lg:col-span-3">
            <button class="w-full rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 sm:w-auto">Сохранить</button>
        </div>
    </form>
</section>
<section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
    <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Права администраторов</div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm whitespace-nowrap">
            <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400">
                <tr>
                    <th class="px-4 py-3 text-left font-medium">Администратор</th>
                    {% for key, label in labels.items() %}
                    <th class="px-4 py-3 text-left font-medium">{{ label }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                {% for a in admins %}
                <tr>
                    <td class="px-4 py-3">
                        <div class="font-medium">{{ a.name }}</div>
                        <div class="text-xs text-gray-500">id {{ a.id }}{% if a.username %} · @{{ a.username }}{% endif %}</div>
                    </td>
                    {% for key, label in labels.items() %}
                    <td class="px-4 py-3">
                        <form method="post" action="/chats/perm" class="inline">
                            <input type="hidden" name="chat_id" value="{{ chat.chat_id }}">
                            <input type="hidden" name="user_id" value="{{ a.id }}">
                            <input type="hidden" name="perm" value="{{ key }}">
                            <input type="hidden" name="allow" value="{{ 0 if a.perms[key] else 1 }}">
                            <button class="rounded-md px-2 py-1 text-xs font-medium border
                                {% if a.perms[key] %}border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300{% else %}border-gray-300 bg-gray-50 text-gray-500 dark:border-gray-700 dark:bg-gray-800{% endif %}">
                                {% if a.perms[key] %}вкл{% else %}выкл{% endif %}
                            </button>
                        </form>
                    </td>
                    {% endfor %}
                </tr>
                {% else %}
                <tr><td class="px-4 py-6 text-gray-500" colspan="9">Не удалось получить список администраторов.</td></tr>
<section class="space-y-3">
    <h2 class="font-semibold">Права администраторов</h2>
    <div class="grid gap-4 lg:grid-cols-2">
        {% for a in admins %}
        <div class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
            <div class="flex items-center gap-3">
                <span class="inline-flex h-9 w-9 items-center justify-center rounded-full bg-gray-200 text-sm font-medium dark:bg-gray-700">{{ a.name[:1] }}</span>
                <div class="min-w-0">
                    <div class="truncate font-medium">{{ a.name }}</div>
                    <div class="truncate text-xs text-gray-500">id {{ a.id }}{% if a.username %} · @{{ a.username }}{% endif %}</div>
                </div>
            </div>
            <div class="mt-3 flex flex-wrap gap-2">
                {% for key, label in labels.items() %}
                <form method="post" action="/chats/perm" class="inline">
                    <input type="hidden" name="chat_id" value="{{ chat.chat_id }}">
                    <input type="hidden" name="user_id" value="{{ a.id }}">
                    <input type="hidden" name="perm" value="{{ key }}">
                    <input type="hidden" name="allow" value="{{ 0 if a.perms[key] else 1 }}">
                    <button class="rounded-full border px-3 py-1.5 text-xs font-medium
                        {% if a.perms[key] %}border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-300{% else %}border-gray-300 bg-gray-50 text-gray-500 dark:border-gray-700 dark:bg-gray-800{% endif %}">
                        {{ label }}: {% if a.perms[key] %}вкл{% else %}выкл{% endif %}
                    </button>
                </form>
                {% endfor %}
            </tbody>
        </table>
            </div>
        </div>
        {% else %}
        <div class="rounded-xl border border-gray-200 bg-white p-6 text-gray-500 shadow-sm dark:border-gray-800 dark:bg-gray-900">
            Не удалось получить список администраторов.
        </div>
        {% endfor %}
    </div>
</section>
<section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-5 shadow-sm">
    <h2 class="font-semibold mb-4">Применить действие</h2>
    <form method="post" action="/action" class="grid md:grid-cols-5 gap-4 items-end">
<section class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900 md:p-5">
    <h2 class="mb-4 font-semibold">Применить действие</h2>
    <form method="post" action="/action" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <input type="hidden" name="chat_id" value="{{ chat.chat_id }}">
        <input type="hidden" name="back" value="/chats/{{ chat.chat_id }}">
        <label class="text-sm">ID пользователя
            <input name="user_id" type="number" required class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="user_id" type="number" required class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <label class="text-sm">Имя (необязательно)
            <input name="name" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="name" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <label class="text-sm">Действие
            <select name="kind" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <select name="kind" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
                <option value="warn">варн</option>
                <option value="mute">мут</option>
                <option value="ban">бан</option>
@@ -103,25 +98,25 @@
            </select>
        </label>
        <label class="text-sm">Время (10m, 1h, -, пусто)
            <input name="dur" placeholder="-" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
            <input name="dur" placeholder="-" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <label class="text-sm">Причина
            <input name="reason" class="mt-1 w-full rounded-lg border border-gray-300 dark:border-gray-700 bg-transparent px-3 py-2">
        <label class="text-sm sm:col-span-2">Причина
            <input name="reason" class="mt-1 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 dark:border-gray-700">
        </label>
        <div class="md:col-span-5">
            <button class="rounded-lg bg-brand-600 hover:bg-brand-700 px-4 py-2 text-sm font-medium text-white">Выполнить</button>
        <div class="sm:col-span-2 lg:col-span-3">
            <button class="w-full rounded-lg bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 sm:w-auto">Выполнить</button>
        </div>
    </form>
</section>
<div class="grid lg:grid-cols-2 gap-6">
    <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
        <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Предупреждения</div>
<div class="grid gap-6 lg:grid-cols-2">
    <section class="rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
        <div class="border-b border-gray-200 px-5 py-3 font-semibold dark:border-gray-800">Предупреждения</div>
        <div class="divide-y divide-gray-100 dark:divide-gray-800">
            {% for w in warns %}
            <div class="px-5 py-3 text-sm flex items-center justify-between">
                <span><a class="text-brand-500 hover:underline" href="/users/{{ chat.chat_id }}/{{ w.user_id }}">{{ w.user_id }}</a> · {{ w.reason or "без причины" }}</span>
                <span class="text-gray-500">{{ fmt_dt(w.created_at) }}</span>
            <div class="flex items-center justify-between px-5 py-3 text-sm">
                <span class="min-w-0 truncate"><a class="text-brand-600 hover:underline dark:text-brand-400" href="/users/{{ chat.chat_id }}/{{ w.user_id }}">{{ w.user_id }}</a> · {{ w.reason or "без причины" }}</span>
                <span class="ml-2 shrink-0 text-gray-500">{{ fmt_dt(w.created_at) }}</span>
            </div>
            {% else %}
            <div class="px-5 py-6 text-sm text-gray-500">Нет предупреждений.</div>
@@ -129,18 +124,18 @@
        </div>
    </section>
    <section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
        <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">История наказаний</div>
    <section class="rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
        <div class="border-b border-gray-200 px-5 py-3 font-semibold dark:border-gray-800">История наказаний</div>
        <div class="divide-y divide-gray-100 dark:divide-gray-800">
            {% for p in punish %}
            <div class="px-5 py-3 text-sm flex items-center justify-between">
                <span>
            <div class="flex items-center justify-between px-5 py-3 text-sm">
                <span class="min-w-0 truncate">
                    {{ "мут" if p.kind == "mute" else "бан" }} ·
                    <a class="text-brand-500 hover:underline" href="/users/{{ chat.chat_id }}/{{ p.user_id }}">{{ p.user_id }}</a>
                    <a class="text-brand-600 hover:underline dark:text-brand-400" href="/users/{{ chat.chat_id }}/{{ p.user_id }}">{{ p.user_id }}</a>
                    · {{ fmt_dur(p.until) if p.until else "бессрочно" }}
                    {% if not p.active %}<span class="text-xs text-gray-400">(снято)</span>{% endif %}
                </span>
                <span class="text-gray-500">{{ fmt_dt(p.created_at) }}</span>
                <span class="ml-2 shrink-0 text-gray-500">{{ fmt_dt(p.created_at) }}</span>
            </div>
            {% else %}
            <div class="px-5 py-6 text-sm text-gray-500">Наказаний нет.</div>
web/templates/chats.html
@@ -3,40 +3,32 @@
{% block header %}Чаты{% endblock %}
{% block content %}
<div class="overflow-x-auto rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
    <table class="w-full min-w-[640px] text-sm">
        <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400">
            <tr>
                <th class="px-5 py-3 text-left font-medium">Чат</th>
                <th class="px-5 py-3 text-left font-medium">Капча</th>
                <th class="px-5 py-3 text-left font-medium">Варны</th>
                <th class="px-5 py-3 text-right font-medium"></th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
            {% for c in chats %}
            {% set cfg = cfgs.get(c.chat_id) %}
            <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                <td class="px-5 py-3">
                    <div class="flex items-center gap-3">
                        <img src="/avatar/{{ c.chat_id }}" alt="" class="h-8 w-8 rounded-full bg-gray-200 object-cover dark:bg-gray-700" onerror="this.style.visibility='hidden'">
                        <div>
                            <div class="font-medium">{{ c.title or c.chat_id }}</div>
                            <div class="text-xs text-gray-500">id {{ c.chat_id }} · {{ c.type }}</div>
                        </div>
                    </div>
                </td>
                <td class="px-5 py-3 text-gray-500">{{ cfg.btn_count }} кнопки · {{ cfg.timeout }} с · {{ cfg.max_attempts }} попытки</td>
                <td class="px-5 py-3 text-gray-500">{{ cfg.warn_limit }} · {{ "бан" if cfg.warn_action == "ban" else "мут" }}</td>
                <td class="px-5 py-3 text-right">
                    <a href="/chats/{{ c.chat_id }}" class="rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 hover:bg-gray-100 dark:hover:bg-gray-800">Открыть</a>
                </td>
            </tr>
            {% else %}
            <tr><td colspan="4" class="px-5 py-8 text-center text-gray-500">Нет доступных чатов.</td></tr>
            {% endfor %}
        </tbody>
    </table>
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
    {% for c in chats %}
    {% set cfg = cfgs.get(c.chat_id) %}
    <a href="/chats/{{ c.chat_id }}"
       class="block rounded-xl border border-gray-200 bg-white p-4 shadow-sm transition hover:border-brand-400 hover:shadow-md dark:border-gray-800 dark:bg-gray-900 dark:hover:border-brand-500">
        <div class="flex items-center gap-3">
            <img src="/avatar/{{ c.chat_id }}" alt=""
                 class="h-11 w-11 shrink-0 rounded-full bg-gray-200 object-cover dark:bg-gray-700"
                 onerror="this.style.visibility='hidden'">
            <div class="min-w-0 flex-1">
                <div class="truncate font-semibold">{{ c.title or c.chat_id }}</div>
                <div class="truncate text-xs text-gray-500">id {{ c.chat_id }} · {{ c.type }}</div>
            </div>
        </div>
        <dl class="mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-xs text-gray-500">
            <div><dt class="text-gray-400">Капча</dt><dd class="text-gray-700 dark:text-gray-300">{{ cfg.btn_count }} кнопки / {{ cfg.timeout }} с</dd></div>
            <div><dt class="text-gray-400">Попыток</dt><dd class="text-gray-700 dark:text-gray-300">{{ cfg.max_attempts }}</dd></div>
            <div><dt class="text-gray-400">Варны</dt><dd class="text-gray-700 dark:text-gray-300">{{ cfg.warn_limit }} · {{ "бан" if cfg.warn_action == "ban" else "мут" }}</dd></div>
            <div><dt class="text-gray-400">Действие</dt><dd class="text-gray-700 dark:text-gray-300">{{ cfg.warn_duration }} с</dd></div>
        </dl>
    </a>
    {% else %}
    <div class="rounded-xl border border-gray-200 bg-white p-8 text-center text-gray-500 dark:border-gray-800 dark:bg-gray-900 sm:col-span-2 xl:col-span-3">
        Нет доступных чатов.
    </div>
    {% endfor %}
</div>
{% endblock %}
web/templates/log.html
@@ -3,33 +3,21 @@
{% block header %}Журнал модерации{% endblock %}
{% block content %}
<div class="overflow-x-auto rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
    <table class="w-full min-w-[720px] text-sm">
        <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400">
            <tr>
                <th class="px-5 py-3 text-left font-medium">Время</th>
                <th class="px-5 py-3 text-left font-medium">Чат</th>
                <th class="px-5 py-3 text-left font-medium">Действие</th>
                <th class="px-5 py-3 text-left font-medium">Админ</th>
                <th class="px-5 py-3 text-left font-medium">Цель</th>
                <th class="px-5 py-3 text-left font-medium">Причина</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
            {% for r in rows %}
            <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                <td class="px-5 py-3 text-gray-500">{{ fmt_dt(r.created_at) }}</td>
                <td class="px-5 py-3">{{ names.get(r.chat_id, r.chat_id) }}</td>
                <td class="px-5 py-3">{{ r.action }}</td>
                <td class="px-5 py-3">{{ r.admin_id }}</td>
                <td class="px-5 py-3">{{ r.target_id }}</td>
                <td class="px-5 py-3">{{ r.reason or "-" }}</td>
            </tr>
            {% else %}
            <tr><td colspan="6" class="px-5 py-8 text-center text-gray-500">Журнал пуст.</td></tr>
            {% endfor %}
        </tbody>
    </table>
</div>
<section class="divide-y divide-gray-100 overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm dark:divide-gray-800 dark:border-gray-800 dark:bg-gray-900">
    {% for r in rows %}
    <div class="p-4 text-sm">
        <div class="flex flex-wrap items-center gap-x-2 gap-y-1">
            <span class="font-medium">{{ r.action }}</span>
            <span class="text-gray-500">{{ names.get(r.chat_id, r.chat_id) }}</span>
            <span class="ml-auto text-xs text-gray-400">{{ fmt_dt(r.created_at) }}</span>
        </div>
        <div class="mt-1 text-gray-500">
            Админ {{ r.admin_id }} → цель {{ r.target_id }}{% if r.reason %} · {{ r.reason }}{% endif %}
        </div>
    </div>
    {% else %}
    <div class="p-8 text-center text-gray-500">Журнал пуст.</div>
    {% endfor %}
</section>
{% endblock %}
web/templates/users.html
@@ -3,64 +3,47 @@
{% block header %}Пользователи{% endblock %}
{% block content %}
<section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
    <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Активные наказания</div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400">
                <tr>
                    <th class="px-5 py-3 text-left font-medium">Пользователь</th>
                    <th class="px-5 py-3 text-left font-medium">Чат</th>
                    <th class="px-5 py-3 text-left font-medium">Тип</th>
                    <th class="px-5 py-3 text-left font-medium">Срок</th>
                    <th class="px-5 py-3 text-left font-medium">Выдан</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                {% for p in rows %}
                <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                    <td class="px-5 py-3">
                        <a class="text-brand-500 hover:underline" href="/users/{{ p.chat_id }}/{{ p.user_id }}">{{ p.user_id }}</a>
                        <div class="text-xs text-gray-500">{{ p.reason or "-" }}</div>
                    </td>
                    <td class="px-5 py-3">{{ names.get(p.chat_id, p.chat_id) }}</td>
                    <td class="px-5 py-3">{{ "мут" if p.kind == "mute" else "бан" }}</td>
                    <td class="px-5 py-3">{{ fmt_dur(p.until) if p.until else "бессрочно" }}</td>
                    <td class="px-5 py-3 text-gray-500">{{ fmt_dt(p.created_at) }}</td>
                </tr>
                {% else %}
                <tr><td colspan="5" class="px-5 py-8 text-center text-gray-500">Активных наказаний нет.</td></tr>
                {% endfor %}
            </tbody>
        </table>
<section class="space-y-3">
    <h2 class="text-sm font-semibold text-gray-500 dark:text-gray-400">Активные наказания</h2>
    <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
        {% for p in rows %}
        <a href="/users/{{ p.chat_id }}/{{ p.user_id }}"
           class="block rounded-xl border border-gray-200 bg-white p-4 shadow-sm transition hover:border-brand-400 dark:border-gray-800 dark:bg-gray-900 dark:hover:border-brand-500">
            <div class="flex items-center justify-between gap-2">
                <span class="font-semibold text-brand-600 dark:text-brand-400">{{ p.user_id }}</span>
                <span class="rounded-full px-2 py-0.5 text-xs
                    {% if p.kind == 'ban' %}bg-red-100 text-red-700 dark:bg-red-950/50 dark:text-red-300{% else %}bg-amber-100 text-amber-700 dark:bg-amber-950/50 dark:text-amber-300{% endif %}">
                    {{ "бан" if p.kind == "ban" else "мут" }}
                </span>
            </div>
            <div class="mt-1 truncate text-xs text-gray-500">{{ names.get(p.chat_id, p.chat_id) }}</div>
            <div class="mt-2 text-sm">Срок: {{ fmt_dur(p.until) if p.until else "бессрочно" }}</div>
            <div class="mt-1 line-clamp-2 text-xs text-gray-500">{{ p.reason or "без причины" }} · {{ fmt_dt(p.created_at) }}</div>
        </a>
        {% else %}
        <div class="rounded-xl border border-gray-200 bg-white p-8 text-center text-gray-500 dark:border-gray-800 dark:bg-gray-900 sm:col-span-2 xl:col-span-3">
            Активных наказаний нет.
        </div>
        {% endfor %}
    </div>
</section>
<section class="rounded-xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm">
    <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-800 font-semibold">Предупреждения</div>
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead class="bg-gray-50 dark:bg-gray-900/60 text-gray-500 dark:text-gray-400">
                <tr>
                    <th class="px-5 py-3 text-left font-medium">Пользователь</th>
                    <th class="px-5 py-3 text-left font-medium">Чат</th>
                    <th class="px-5 py-3 text-left font-medium">Причина</th>
                    <th class="px-5 py-3 text-left font-medium">Добавлен</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                {% for w in warns %}
                <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                    <td class="px-5 py-3"><a class="text-brand-500 hover:underline" href="/users/{{ w.chat_id }}/{{ w.user_id }}">{{ w.user_id }}</a></td>
                    <td class="px-5 py-3">{{ names.get(w.chat_id, w.chat_id) }}</td>
                    <td class="px-5 py-3">{{ w.reason or "-" }}</td>
                    <td class="px-5 py-3 text-gray-500">{{ fmt_dt(w.created_at) }}</td>
                </tr>
                {% else %}
                <tr><td colspan="4" class="px-5 py-8 text-center text-gray-500">Предупреждений нет.</td></tr>
                {% endfor %}
            </tbody>
        </table>
<section class="space-y-3">
    <h2 class="text-sm font-semibold text-gray-500 dark:text-gray-400">Предупреждения</h2>
    <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
        {% for w in warns %}
        <a href="/users/{{ w.chat_id }}/{{ w.user_id }}"
           class="block rounded-xl border border-gray-200 bg-white p-4 shadow-sm transition hover:border-brand-400 dark:border-gray-800 dark:bg-gray-900 dark:hover:border-brand-500">
            <div class="font-semibold text-brand-600 dark:text-brand-400">{{ w.user_id }}</div>
            <div class="mt-1 truncate text-xs text-gray-500">{{ names.get(w.chat_id, w.chat_id) }}</div>
            <div class="mt-2 line-clamp-2 text-sm">{{ w.reason or "без причины" }}</div>
            <div class="mt-1 text-xs text-gray-500">{{ fmt_dt(w.created_at) }}</div>
        </a>
        {% else %}
        <div class="rounded-xl border border-gray-200 bg-white p-8 text-center text-gray-500 dark:border-gray-800 dark:bg-gray-900 sm:col-span-2 xl:col-span-3">
            Предупреждений нет.
        </div>
        {% endfor %}
    </div>
</section>
web/views.py
@@ -5,11 +5,28 @@
import perms as pm
from captcha import CAP_STATE
import cfg
from cfg import bot
from cfg import bot, logger
from perms import P_BAN, P_CFG, P_MUTE, P_PERMS, P_UNBAN, P_UNMUTE, P_UNWARN, P_WARN, PERM_LABELS
from util import fmt_dt, fmt_dur, now_ts, parse_dur
from util import fmt_dt, fmt_dur, mention, now_ts, parse_dur
from web.auth import is_staff
from web.render import render
# Человекочитаемые названия настроек для уведомлений в чат.
CFG_LABELS = {
    "btn_count": "Кнопки капчи",
    "timeout": "Таймаут капчи, сек",
    "max_attempts": "Попыток до наказания",
    "warn_limit": "Лимит варнов",
    "warn_action": "Действие при лимите",
    "warn_duration": "Длительность наказания, сек",
}
async def _notify(chat_id: int, text: str) -> None:
    try:
        await bot.send_message(chat_id, text, parse_mode="HTML")
    except Exception as e:
        logger.warning("notify failed chat=%s: %s", chat_id, e)
# Соответствие действия и требуемого права.
ACTION_PERM = {
@@ -41,7 +58,7 @@
    chats = await allowed_chats(user["user_id"])
    ids = {c["chat_id"] for c in chats}
    names = {c["chat_id"]: c["title"] for c in chats}
    st = await db.stats(now_ts())
    st = await db.stats_scoped(ids, now_ts())
    captchas = [
        {"chat_id": k[0], "user_id": k[1], "left": max(0, v.get("deadline", 0) - now_ts())}
        for k, v in CAP_STATE.items()
@@ -121,8 +138,33 @@
        raise web.HTTPFound(f"/chats/{chat_id}?err=cfg")
    if fields["warn_action"] not in ("mute", "ban"):
        fields["warn_action"] = "mute"
    old = await db.get_chat_cfg(chat_id)
    await db.save_chat_cfg(chat_id, **fields)
    # Сообщаем в чат, что настройки изменены из панели, и что именно поменялось.
    changed = []
    for key, new in fields.items():
        if old.get(key) != new:
            if key == "warn_action":
                prev, nxt = _act_label(old.get(key)), _act_label(new)
            else:
                prev, nxt = old.get(key), new
            changed.append(f"{CFG_LABELS.get(key, key)}: {prev} -> {nxt}")
    if changed:
        actor = user["user_id"]
        name = user.get("first_name") or str(actor)
        await db.add_log(chat_id, actor, 0, "config", "; ".join(changed), now_ts())
        await _notify(
            chat_id,
            "Настройки чата изменены через веб-панель.\n"
            f"Изменил: {mention(actor, name)}\n" + "\n".join(f"- {c}" for c in changed),
        )
    raise web.HTTPFound(f"/chats/{chat_id}")
def _act_label(value) -> str:
    return "бан" if value == "ban" else "мут"
async def chat_perm(request) -> web.Response:
@@ -136,7 +178,17 @@
        raise web.HTTPForbidden()
    if perm not in PERM_LABELS:
        raise web.HTTPFound(f"/chats/{chat_id}")
    await pm.set_perm(chat_id, user["user_id"], target_id, perm, allow)
    ok, _msg = await pm.set_perm(chat_id, user["user_id"], target_id, perm, allow)
    if ok:
        actor = user["user_id"]
        name = user.get("first_name") or str(actor)
        state = "включено" if allow else "выключено"
        await db.add_log(chat_id, actor, target_id, "perm", f"{perm}={allow}", now_ts())
        await _notify(
            chat_id,
            f"Право «{PERM_LABELS[perm]}» для {mention(target_id)} {state} через веб-панель.\n"
            f"Изменил: {mention(actor, name)}",
        )
    raise web.HTTPFound(f"/chats/{chat_id}")