From 40d1e4fb89e332ff34c0996f56eee012ec0ddb15 Mon Sep 17 00:00:00 2001
From: Roman Sergienko <romasergienko@outlook.com>
Date: Fri, 04 Dec 2026 11:29:08 +0000
Subject: [PATCH] Show and manage disabled RP actions; improve mobile layout

---
 web/views.py |  111 +++++++++++++++++++++++++++++++++++--------------------
 1 files changed, 70 insertions(+), 41 deletions(-)

diff --git a/web/views.py b/web/views.py
index 5b921ae..0f55ae7 100644
--- a/web/views.py
+++ b/web/views.py
@@ -620,53 +620,60 @@
 
 
 async def api_rp_add(request) -> web.Response:
-    user = await _user(request)
-    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):
-        return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400)
+        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 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)
+        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 + trigger)
-                import uuid
-                file_name = f"{now_ts()}_{uuid.uuid4().hex[:8]}.gif"
-                file_path = gif_dir / file_name
-                
-                # Сохраняем файл
-                content = await 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)
+        # Обработка загруженной гифки
+        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)
+        # Добавляем действие
+        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})
+        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:
@@ -688,3 +695,25 @@
     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})

--
Gitblit v1.9.3