feat web: реалтайм-обновление сообщений (polling), реплаи, отправка по Enter (Ctrl+Enter — новая строка), мобильная раскладка
| | |
| | | "user_id INTEGER, " |
| | | "name TEXT, " |
| | | "text TEXT, " |
| | | "created_at INTEGER)", |
| | | "created_at INTEGER, " |
| | | "tg_msg_id INTEGER DEFAULT 0)", |
| | | ) |
| | | |
| | | |
| | |
| | | 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") and not await col_exists(db, "messages", "tg_msg_id"): |
| | | await db.execute("ALTER TABLE messages ADD COLUMN tg_msg_id INTEGER DEFAULT 0") |
| | | |
| | | |
| | | async def init_db() -> None: |
| | |
| | | |
| | | # --- Последние сообщения чата --- |
| | | |
| | | async def add_msg(chat_id: int, user_id: int, name: str, text: str, ts: int, keep: int = 200) -> None: |
| | | async def add_msg(chat_id: int, user_id: int, name: str, text: str, ts: int, tg_msg_id: int = 0, keep: int = 200) -> int: |
| | | # Храним последние keep сообщений на чат. |
| | | async with db_conn() as db: |
| | | await db.execute( |
| | | "INSERT INTO messages (chat_id, user_id, name, text, created_at) VALUES (?, ?, ?, ?, ?)", |
| | | (chat_id, user_id, name, text, ts), |
| | | cur = await db.execute( |
| | | "INSERT INTO messages (chat_id, user_id, name, text, created_at, tg_msg_id) " |
| | | "VALUES (?, ?, ?, ?, ?, ?)", |
| | | (chat_id, user_id, name, text, ts, tg_msg_id), |
| | | ) |
| | | await db.execute( |
| | | "DELETE FROM messages WHERE chat_id=? AND id NOT IN " |
| | |
| | | (chat_id, chat_id, keep), |
| | | ) |
| | | await db.commit() |
| | | return cur.lastrowid |
| | | |
| | | |
| | | async def list_msgs(chat_id: int, limit: int = 100) -> List[dict]: |
| | |
| | | ) 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()] |
| | |
| | | content = event.text or event.caption or "" |
| | | if content: |
| | | try: |
| | | await db.add_msg(chat.id, u.id, u.full_name, content[:1000], ts) |
| | | await db.add_msg(chat.id, u.id, u.full_name, content[:1000], ts, event.message_id) |
| | | except Exception as e: |
| | | logger.warning("add_msg failed chat=%s: %s", chat.id, e) |
| | | return await handler(event, data) |
| | |
| | | app.router.add_post("/reports/clear", views.report_clear) |
| | | app.router.add_post("/reports/accept", views.report_accept) |
| | | app.router.add_post("/chats/say", views.say) |
| | | app.router.add_get("/api/messages", views.api_messages) |
| | | app.router.add_post("/api/say", views.api_say) |
| | | app.router.add_post("/api/perm", views.api_perm) |
| | | app.router.add_get("/users", views.users_page) |
| | | app.router.add_get("/users/{chat_id}/{user_id}", views.user_page) |
| | |
| | | {% block header %}Сообщения{% endblock %} |
| | | {% block content %} |
| | | |
| | | <a href="/chats/{{ chat.chat_id }}" class="inline-flex items-center gap-1 text-sm text-brand-600 hover:underline dark:text-brand-400"> |
| | | ← Назад к чату |
| | | </a> |
| | | |
| | | <div class="text-sm text-gray-500">{{ chat.title or chat.chat_id }} (id {{ chat.chat_id }})</div> |
| | | <div class="flex items-center justify-between gap-3"> |
| | | <a href="/chats/{{ chat.chat_id }}" class="inline-flex items-center gap-1 text-sm text-brand-600 hover:underline dark:text-brand-400"> |
| | | ← Назад к чату |
| | | </a> |
| | | <span class="truncate text-xs text-gray-500">{{ chat.title or chat.chat_id }} · id {{ chat.chat_id }}</span> |
| | | </div> |
| | | |
| | | <section class="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900"> |
| | | <div class="max-h-[60vh] divide-y divide-gray-100 overflow-y-auto dark:divide-gray-800"> |
| | | <div id="msg-list" class="flex max-h-[55vh] flex-col gap-1 overflow-y-auto p-2 md:max-h-[60vh]"> |
| | | {% for m in msgs %} |
| | | <div class="px-4 py-2 text-sm"> |
| | | <div class="msg rounded-lg px-3 py-2 text-sm" data-id="{{ m.id }}" data-tg="{{ m.tg_msg_id or 0 }}" data-name="{{ m.name }}"> |
| | | <div class="flex flex-wrap items-center justify-between gap-2"> |
| | | <span class="font-medium {% if m.name and m.name.startswith('Amadeus') %}text-brand-600 dark:text-brand-400{% endif %}">{{ m.name }}</span> |
| | | <span class="text-xs text-gray-400">{{ fmt_dt(m.created_at) }}</span> |
| | | <span class="flex items-center gap-2"> |
| | | <span class="text-xs text-gray-400">{{ fmt_dt(m.created_at) }}</span> |
| | | <button type="button" class="reply-btn text-xs text-gray-400 hover:text-brand-500">ответить</button> |
| | | </span> |
| | | </div> |
| | | <div class="mt-0.5 whitespace-pre-wrap break-words">{{ m.text }}</div> |
| | | </div> |
| | | {% else %} |
| | | <div class="px-4 py-8 text-center text-gray-500">Сообщений пока нет.</div> |
| | | <div id="empty" class="px-4 py-8 text-center text-gray-500">Сообщений пока нет.</div> |
| | | {% endfor %} |
| | | </div> |
| | | </section> |
| | | |
| | | <section class="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"> |
| | | <form method="post" action="/chats/say" class="space-y-3"> |
| | | <section class="rounded-xl border border-gray-200 bg-white p-3 shadow-sm dark:border-gray-800 dark:bg-gray-900 md:p-4"> |
| | | <div id="reply-bar" class="mb-2 hidden items-center justify-between rounded-lg bg-gray-100 px-3 py-2 text-xs dark:bg-gray-800"> |
| | | <span class="truncate">Ответ: <span id="reply-to-name" class="font-medium"></span></span> |
| | | <button type="button" id="reply-cancel" class="shrink-0 text-gray-500 hover:text-red-500">отмена</button> |
| | | </div> |
| | | <form id="say-form"> |
| | | <input type="hidden" name="chat_id" value="{{ chat.chat_id }}"> |
| | | <textarea name="text" rows="3" required placeholder="Написать в чат от имени Амадеуса..." |
| | | class="w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700"></textarea> |
| | | <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> |
| | | <input type="hidden" name="reply_to" id="reply-to" value="0"> |
| | | <textarea id="say-text" rows="2" placeholder="Сообщение от имени Амадеуса..." |
| | | class="w-full resize-none rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm dark:border-gray-700"></textarea> |
| | | <div class="mt-2 flex items-center justify-between gap-2"> |
| | | <span id="say-status" class="text-xs text-gray-500"></span> |
| | | <button class="rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700">Отправить</button> |
| | | </div> |
| | | <p class="mt-1 text-[11px] text-gray-400">Enter — отправить, Ctrl+Enter (или Shift+Enter) — новая строка. Сообщение уйдёт с пометкой «От <ваше имя>».</p> |
| | | </form> |
| | | <p class="mt-2 text-xs text-gray-500">Амадеус отправит сообщение с пометкой «От <ваше имя>».</p> |
| | | </section> |
| | | |
| | | <script> |
| | | (function () { |
| | | const chatId = "{{ chat.chat_id }}"; |
| | | const list = document.getElementById("msg-list"); |
| | | const statusEl = document.getElementById("say-status"); |
| | | const replyBar = document.getElementById("reply-bar"); |
| | | const replyTo = document.getElementById("reply-to"); |
| | | const replyName = document.getElementById("reply-to-name"); |
| | | const text = document.getElementById("say-text"); |
| | | const form = document.getElementById("say-form"); |
| | | let lastId = {{ msgs[-1].id if msgs else 0 }}; |
| | | |
| | | function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : s; return d.innerHTML; } |
| | | function atBottom() { return list.scrollTop + list.clientHeight >= list.scrollHeight - 40; } |
| | | function toBottom() { list.scrollTop = list.scrollHeight; } |
| | | |
| | | function bindReply(el) { |
| | | const btn = el.querySelector(".reply-btn"); |
| | | if (!btn) return; |
| | | btn.addEventListener("click", function () { |
| | | replyTo.value = el.dataset.tg || 0; |
| | | replyName.textContent = el.dataset.name || ""; |
| | | replyBar.classList.remove("hidden"); |
| | | replyBar.classList.add("flex"); |
| | | text.focus(); |
| | | }); |
| | | } |
| | | document.querySelectorAll(".msg").forEach(bindReply); |
| | | |
| | | document.getElementById("reply-cancel").addEventListener("click", function () { |
| | | replyTo.value = 0; |
| | | replyBar.classList.add("hidden"); |
| | | replyBar.classList.remove("flex"); |
| | | }); |
| | | |
| | | function addMsg(m, scroll) { |
| | | const empty = document.getElementById("empty"); |
| | | if (empty) empty.remove(); |
| | | const el = document.createElement("div"); |
| | | el.className = "msg rounded-lg px-3 py-2 text-sm"; |
| | | el.dataset.id = m.id; |
| | | el.dataset.tg = m.tg_msg_id || 0; |
| | | el.dataset.name = m.name || ""; |
| | | const isBot = (m.name || "").startsWith("Amadeus"); |
| | | el.innerHTML = |
| | | '<div class="flex flex-wrap items-center justify-between gap-2">' + |
| | | '<span class="font-medium ' + (isBot ? "text-brand-600 dark:text-brand-400" : "") + '">' + esc(m.name) + "</span>" + |
| | | '<span class="flex items-center gap-2"><span class="text-xs text-gray-400">' + esc(m.time || "") + "</span>" + |
| | | '<button type="button" class="reply-btn text-xs text-gray-400 hover:text-brand-500">ответить</button></span></div>' + |
| | | '<div class="mt-0.5 whitespace-pre-wrap break-words">' + esc(m.text) + "</div>"; |
| | | list.appendChild(el); |
| | | bindReply(el); |
| | | if (scroll) toBottom(); |
| | | } |
| | | |
| | | // Enter — отправить; Ctrl/Shift/Alt+Enter — новая строка. |
| | | text.addEventListener("keydown", function (e) { |
| | | if (e.key === "Enter" && !e.ctrlKey && !e.shiftKey && !e.metaKey && !e.altKey) { |
| | | e.preventDefault(); |
| | | form.requestSubmit(); |
| | | } |
| | | }); |
| | | |
| | | form.addEventListener("submit", async function (e) { |
| | | e.preventDefault(); |
| | | const val = text.value.trim(); |
| | | if (!val) return; |
| | | const body = new URLSearchParams({ chat_id: chatId, text: val, reply_to: replyTo.value }); |
| | | text.disabled = true; |
| | | statusEl.textContent = "Отправка..."; |
| | | try { |
| | | const r = await fetch("/api/say", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: body }); |
| | | const j = await r.json(); |
| | | if (j.ok) { |
| | | text.value = ""; |
| | | replyTo.value = 0; |
| | | replyBar.classList.add("hidden"); |
| | | replyBar.classList.remove("flex"); |
| | | statusEl.textContent = ""; |
| | | addMsg(j.message, true); |
| | | lastId = j.message.id; |
| | | } else { |
| | | statusEl.textContent = j.msg || "Ошибка отправки."; |
| | | } |
| | | } catch (err) { |
| | | statusEl.textContent = "Ошибка сети."; |
| | | } finally { |
| | | text.disabled = false; |
| | | text.focus(); |
| | | } |
| | | }); |
| | | |
| | | // Реалтайм: подтягиваем новые сообщения. |
| | | async function poll() { |
| | | try { |
| | | const r = await fetch("/api/messages?chat_id=" + encodeURIComponent(chatId) + "&after=" + lastId); |
| | | const j = await r.json(); |
| | | if (j.messages && j.messages.length) { |
| | | const stick = atBottom(); |
| | | j.messages.forEach(function (m) { if (m.id > lastId) { addMsg(m, false); lastId = m.id; } }); |
| | | if (stick) toBottom(); |
| | | } |
| | | } catch (err) { /* тихо игнорируем */ } |
| | | } |
| | | |
| | | toBottom(); |
| | | setInterval(poll, 3000); |
| | | text.focus(); |
| | | })(); |
| | | </script> |
| | | |
| | | {% endblock %} |
| | |
| | | ) |
| | | |
| | | |
| | | async def _deliver(chat_id: int, name: str, text: str, reply_id: int) -> int: |
| | | # Возвращает tg message_id или -1 при ошибке. |
| | | prefix = f"От {name}:\n{text}" |
| | | try: |
| | | msg = await bot.send_message(chat_id, prefix, reply_to_message_id=reply_id or None) |
| | | return getattr(msg, "message_id", 0) |
| | | except Exception as e: |
| | | logger.warning("say failed chat=%s: %s", chat_id, e) |
| | | if reply_id: |
| | | try: |
| | | msg = await bot.send_message(chat_id, prefix) |
| | | return getattr(msg, "message_id", 0) |
| | | except Exception as e2: |
| | | logger.warning("say retry failed chat=%s: %s", chat_id, e2) |
| | | return -1 |
| | | |
| | | |
| | | async def say(request) -> web.Response: |
| | | # Отправка сообщения в чат от имени Амадеуса с указанием автора. |
| | | user = await _user(request) |
| | | data = await request.post() |
| | | chat_id = int(data["chat_id"]) |
| | | text = (data.get("text") or "").strip() |
| | | reply_id = int(data.get("reply_to") or 0) |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | raise web.HTTPForbidden() |
| | | if not text: |
| | | raise web.HTTPFound(f"/chats/{chat_id}/messages") |
| | | name = user.get("first_name") or str(user["user_id"]) |
| | | try: |
| | | await bot.send_message(chat_id, f"От {name}:\n{text}") |
| | | await db.add_msg(chat_id, user["user_id"], f"Amadeus / {name}", text, now_ts()) |
| | | tg_id = await _deliver(chat_id, name, text, reply_id) |
| | | if tg_id >= 0: |
| | | await db.add_msg(chat_id, user["user_id"], f"Amadeus / {name}", text, now_ts(), tg_id) |
| | | await db.add_log(chat_id, user["user_id"], 0, "say", text[:200], now_ts()) |
| | | except Exception as e: |
| | | logger.warning("say failed chat=%s: %s", chat_id, e) |
| | | raise web.HTTPFound(f"/chats/{chat_id}/messages") |
| | | |
| | | |
| | | async def api_messages(request) -> web.Response: |
| | | user = await _user(request) |
| | | try: |
| | | chat_id = int(request.query["chat_id"]) |
| | | after = int(request.query.get("after", "0") or 0) |
| | | except (KeyError, ValueError): |
| | | return web.json_response({"ok": False}, status=400) |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | return web.json_response({"ok": False}, status=403) |
| | | rows = await db.list_msgs_after(chat_id, after, 200) |
| | | for row in rows: |
| | | row["time"] = fmt_dt(row["created_at"]) |
| | | return web.json_response({"messages": rows}) |
| | | |
| | | |
| | | async def api_say(request) -> web.Response: |
| | | user = await _user(request) |
| | | data = await request.post() |
| | | try: |
| | | chat_id = int(data["chat_id"]) |
| | | except (KeyError, ValueError): |
| | | return web.json_response({"ok": False, "msg": "Некорректные данные."}, status=400) |
| | | text = (data.get("text") or "").strip() |
| | | reply_id = int(data.get("reply_to") or 0) |
| | | if chat_id not in await _allowed_ids(user["user_id"]): |
| | | return web.json_response({"ok": False, "msg": "Нет доступа."}, status=403) |
| | | if not text: |
| | | return web.json_response({"ok": False, "msg": "Пустое сообщение."}, status=400) |
| | | name = user.get("first_name") or str(user["user_id"]) |
| | | ts = now_ts() |
| | | tg_id = await _deliver(chat_id, name, text, reply_id) |
| | | if tg_id < 0: |
| | | return web.json_response({"ok": False, "msg": "Не удалось отправить. Проверьте права бота."}, status=502) |
| | | mid = await db.add_msg(chat_id, user["user_id"], f"Amadeus / {name}", text, ts, tg_id) |
| | | await db.add_log(chat_id, user["user_id"], 0, "say", text[:200], ts) |
| | | return web.json_response({ |
| | | "ok": True, |
| | | "message": { |
| | | "id": mid, "chat_id": chat_id, "user_id": user["user_id"], |
| | | "name": f"Amadeus / {name}", "text": text, "created_at": ts, |
| | | "tg_msg_id": tg_id, "time": fmt_dt(ts), |
| | | }, |
| | | }) |
| | | |
| | | |
| | | async def alarm_toggle(request) -> web.Response: |
| | | user = await _user(request) |
| | | data = await request.post() |