Бот для капчи в чатах
Roman Sergienko
8 hours ago c80fb18220a339f2b1a218fd1b5886e0a41725f6
web/views.py
@@ -63,7 +63,11 @@
async def dashboard(request) -> web.Response:
    user = await _user(request)
    user = request["user"]
    if user is None:
        if request.headers.get("X-Telegram-Web-App-Platform"):
            raise web.HTTPFound("/miniapp")
        raise web.HTTPFound("/login")
    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}
@@ -88,7 +92,11 @@
async def chats_page(request) -> web.Response:
    user = await _user(request)
    user = request["user"]
    if user is None:
        if request.headers.get("X-Telegram-Web-App-Platform"):
            raise web.HTTPFound("/miniapp")
        raise web.HTTPFound("/login")
    chats = await allowed_chats(user["user_id"])
    cfgs = {c["chat_id"]: await db.get_chat_cfg(c["chat_id"]) for c in chats}
    alarms = {r["chat_id"]: r for r in await db.list_alarm_chats()}
@@ -96,40 +104,31 @@
async def miniapp_page(request) -> web.Response:
    """Выбирает стартовый экран Mini App по проверенному initData Telegram."""
    user = await _user(request)
    chats = await allowed_chats(user["user_id"])
    available_ids = {c["chat_id"] for c in chats}
    init_data = request.query.get("tgWebAppData", "")
    context = None
    if init_data:
        from web.auth import verify_webapp_init_data
    """Выбирает стартовый экран Mini App по chat_id из Telegram launch URL."""
    if request["user"] is None:
        raise web.HTTPFound("/miniapp/login")
        verified = verify_webapp_init_data(init_data)
        if verified:
            try:
                tg_user = json.loads(verified["user"])
                if int(tg_user["id"]) == user["user_id"]:
                    chat = json.loads(verified.get("chat", "{}"))
                    candidate = int(chat.get("id", 0)) if chat else 0
                    if not candidate and verified.get("chat_instance"):
                        instance = verified["chat_instance"]
                        candidate = int(instance) if instance.lstrip("-").isdigit() else 0
                    if candidate in available_ids:
                        context = candidate
            except (KeyError, TypeError, ValueError):
                pass
    if context is None:
        context = request.query.get("chat_id", "")
        try:
            context = int(context)
        except (TypeError, ValueError):
            context = 0
        if context not in available_ids:
            context = 0
    user_id = request["user"]["user_id"]
    chats = await allowed_chats(user_id)
    available_ids = {c["chat_id"] for c in chats}
    try:
        context = int(request.query.get("chat_id", "") or 0)
    except (TypeError, ValueError):
        context = 0
    if context not in available_ids:
        context = 0
    if context:
        raise web.HTTPFound(f"/chats/{context}")
    raise web.HTTPFound("/chats")
async def miniapp_login_page(request) -> web.Response:
    """Стартовая HTML-страница: получает initData через Telegram WebApp JS API."""
    if request["user"] is not None:
        raise web.HTTPFound("/miniapp")
    response = render(request, "miniapp_login.html")
    response.headers["X-Amadeus-MiniApp-Version"] = "5387fa6"
    return response
async def chat_page(request) -> web.Response:
@@ -608,3 +607,113 @@
    ids = set(names)
    rows = [r for r in await db.list_log(limit=500) if r["chat_id"] in ids][:200]
    return render(request, "log.html", active="log", rows=rows, names=names, fmt_dt=fmt_dt)
async def rp_page(request) -> web.Response:
    user = await _user(request)
    chat_id = int(request.match_info["chat_id"])
    if chat_id not in await _allowed_ids(user["user_id"]):
        raise web.HTTPForbidden()
    chat = await db.get_chat(chat_id) or {"chat_id": chat_id, "title": str(chat_id)}
    actions = await db.list_rp_actions(chat_id)
    return render(request, "rp.html", active="chats", chat=chat, actions=actions)
async def api_rp_add(request) -> web.Response:
    try:
        user = await _user(request)
        if user is None:
            return web.json_response({"ok": False, "msg": "Не авторизован."}, status=401)
        data = await request.post()
        try:
            chat_id = int(data["chat_id"])
            trigger = (data.get("trigger") or "").strip()
            response_text = (data.get("response_text") or "").strip()
        except (KeyError, ValueError) as e:
            return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
        if chat_id not in await _allowed_ids(user["user_id"]):
            return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
        if not trigger or not response_text:
            return web.json_response({"ok": False, "msg": "Триггер и текст обязательны."}, status=400)
        # Обработка загруженной гифки
        gif_file_id = None
        if "gif" in data:
            file = data["gif"]
            if file.filename and file.file:
                try:
                    import pathlib
                    # Создаём директорию для гифок если не существует
                    gif_dir = pathlib.Path("data/rp_gifs")
                    gif_dir.mkdir(parents=True, exist_ok=True)
                    # Генерируем имя файла (timestamp + uuid)
                    import uuid
                    file_name = f"{now_ts()}_{uuid.uuid4().hex[:8]}.gif"
                    file_path = gif_dir / file_name
                    # Сохраняем файл
                    content = file.file.read()
                    with open(file_path, "wb") as f:
                        f.write(content)
                    gif_file_id = str(file_path)
                except Exception as e:
                    logger.warning("Failed to save GIF: %s", e)
        # Добавляем действие
        action_id = await db.add_rp_action(chat_id, trigger, response_text, gif_file_id, now_ts())
        if not action_id:
            return web.json_response({"ok": False, "msg": "Триггер уже существует."}, status=400)
        await db.add_log(chat_id, user["user_id"], 0, "rp_add", f"{trigger} -> {response_text[:50]}", now_ts())
        return web.json_response({"ok": True})
    except Exception as e:
        logger.exception("api_rp_add error: %s", e)
        return web.json_response({"ok": False, "msg": "Внутренняя ошибка сервера."}, status=500)
async def api_rp_delete(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    try:
        action_id = int(data["action_id"])
        chat_id = int(data["chat_id"])
    except (KeyError, ValueError):
        return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
    if chat_id not in await _allowed_ids(user["user_id"]):
        return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
    action = await db.get_rp_action(action_id)
    if not action or action["chat_id"] != chat_id:
        return web.json_response({"ok": False, "msg": "Действие не найдено."}, status=404)
    await db.delete_rp_action(action_id)
    await db.add_log(chat_id, user["user_id"], 0, "rp_delete", action["trigger"], now_ts())
    return web.json_response({"ok": True})
async def api_rp_toggle(request) -> web.Response:
    user = await _user(request)
    data = await request.post()
    try:
        action_id = int(data["action_id"])
        chat_id = int(data["chat_id"])
        enabled = data.get("enabled") == "1"
    except (KeyError, ValueError):
        return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
    if chat_id not in await _allowed_ids(user["user_id"]):
        return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403)
    action = await db.get_rp_action(action_id)
    if not action or action["chat_id"] != chat_id:
        return web.json_response({"ok": False, "msg": "Действие не найдено."}, status=404)
    await db.set_rp_action_enabled(action_id, enabled)
    await db.add_log(chat_id, user["user_id"], 0, "rp_enable" if enabled else "rp_disable", action["trigger"], now_ts())
    return web.json_response({"ok": True})