b803d004e1
Security: - Fix NUT protocol command injection (validate names against safe regex) - Enable Jinja2 autoescape=True to prevent HTML injection via external data - Add WebhookProviderConfig validation model Performance: - Shared aiohttp.ClientSession singleton (replaces 40+ per-request sessions) - Fix 4 N+1 queries with batch IN loads (poller, scheduler, memory, broadcast) - asyncio.gather for Gitea commands and notification dispatcher - Add DB indexes on NotificationTrackerState.tracker_id, CommandTrackerListener - LRU cache for compiled Jinja2 templates - Daily EventLog cleanup job (90-day retention) - 30s HTTP timeout on all external calls - GROUP BY for target type counts (replaces 7 sequential queries) Code quality: - Extract get_owned_entity() helper (replaces 11 duplicate functions) - Extract slot_helpers.py (load_slots, save_slots, render_template_preview) - Extract command_utils.py (tracker lookup, last event, collection IDs) - Extract http_session.py (shared session lifecycle) - Provider connection validation dedup (3x → 1 helper) - Command dispatch tables replacing if/elif chains - Album+links fetch helper (fetch_albums_with_links) - Provider dispatch polymorphism (list_provider_collections) - Immutable _enrich_assets (no longer mutates in-place) - Fix _format_assets return type + handler unpacking Frontend: - Fix 18+ hardcoded English strings → t() with new i18n keys (en + ru) - Mobile "More" nav panel with provider filter and search - Shared Button.svelte component (4 variants, 2 sizes) - Shared ErrorBanner.svelte component (8 pages updated) - SvelteKit goto() replacing window.location.href - Dashboard grid fixed for 4 cards, paginator opacity consistency Functionality: - max_instances=1 on scheduler jobs (prevents duplicate events) - Webhook provider in watcher (prevents error spam) - Fix stale SQLModel reference in poller - Gitea get_repo() direct API call
118 lines
4.3 KiB
Python
118 lines
4.3 KiB
Python
"""Telegram webhook handler for bot commands."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hmac
|
|
import logging
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
|
from sqlmodel import select
|
|
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
|
|
from notify_bridge_core.notifications.telegram.client import TelegramClient
|
|
|
|
from ..database.engine import get_session
|
|
from ..database.models import TelegramBot, TelegramChat
|
|
from ..services.telegram import save_chat_from_webhook
|
|
from .base import CommandResponse
|
|
from .handler import handle_command, send_media_group, send_reply
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
router = APIRouter(prefix="/api/telegram", tags=["telegram-webhook"])
|
|
|
|
# Webhook secret — set via NOTIFY_BRIDGE_TELEGRAM_WEBHOOK_SECRET env var
|
|
_webhook_secret: str | None = None
|
|
|
|
|
|
def set_webhook_secret(secret: str | None) -> None:
|
|
global _webhook_secret
|
|
_webhook_secret = secret
|
|
|
|
|
|
@router.post("/webhook/{webhook_id}")
|
|
async def telegram_webhook(
|
|
webhook_id: str,
|
|
request: Request,
|
|
x_telegram_bot_api_secret_token: str | None = Header(default=None),
|
|
session: AsyncSession = Depends(get_session),
|
|
):
|
|
"""Handle incoming Telegram messages — route commands to handlers."""
|
|
# Validate webhook secret if configured
|
|
if _webhook_secret:
|
|
if not hmac.compare_digest(x_telegram_bot_api_secret_token or "", _webhook_secret):
|
|
raise HTTPException(status_code=403, detail="Invalid webhook secret")
|
|
|
|
# Find bot by opaque webhook path ID (not by token — token must not appear in URLs)
|
|
bot_result = await session.exec(
|
|
select(TelegramBot).where(TelegramBot.webhook_path_id == webhook_id)
|
|
)
|
|
bot = bot_result.first()
|
|
if not bot:
|
|
raise HTTPException(status_code=403, detail="Unknown webhook")
|
|
|
|
try:
|
|
update = await request.json()
|
|
except Exception:
|
|
return {"ok": True, "error": "invalid_json"}
|
|
|
|
message = update.get("message")
|
|
if not message:
|
|
return {"ok": True, "skipped": "no_message"}
|
|
|
|
chat_info = message.get("chat", {})
|
|
chat_id = str(chat_info.get("id", ""))
|
|
text = message.get("text", "")
|
|
|
|
if not chat_id or not text:
|
|
return {"ok": True, "skipped": "empty"}
|
|
|
|
# Auto-persist chat from incoming message
|
|
from_user = message.get("from", {})
|
|
msg_language = from_user.get("language_code", "")
|
|
try:
|
|
await save_chat_from_webhook(session, bot.id, chat_info, language_code=msg_language)
|
|
await session.commit()
|
|
except Exception:
|
|
_LOGGER.warning("Failed to auto-save chat %s", chat_id, exc_info=True)
|
|
|
|
# Handle commands (only if chat has commands enabled)
|
|
if text.startswith("/"):
|
|
chat_row = (await session.exec(
|
|
select(TelegramChat).where(
|
|
TelegramChat.bot_id == bot.id,
|
|
TelegramChat.chat_id == chat_id,
|
|
)
|
|
)).first()
|
|
if not chat_row or not chat_row.commands_enabled:
|
|
return {"ok": True, "skipped": "commands_disabled"}
|
|
effective_lang = chat_row.language_override or msg_language
|
|
message_id = message.get("message_id")
|
|
responses = await handle_command(bot, chat_id, text, language_code=effective_lang)
|
|
if responses:
|
|
for resp in responses:
|
|
if resp.text:
|
|
await send_reply(bot.token, chat_id, resp.text, reply_to_message_id=message_id)
|
|
if resp.media:
|
|
await send_media_group(bot.token, chat_id, resp.media, reply_to_message_id=message_id)
|
|
return {"ok": True}
|
|
|
|
return {"ok": True, "skipped": "not_a_command"}
|
|
|
|
|
|
async def register_webhook(bot_token: str, webhook_url: str, secret: str | None = None) -> dict:
|
|
"""Register webhook URL with Telegram Bot API via TelegramClient."""
|
|
from ..services.http_session import get_http_session
|
|
http = await get_http_session()
|
|
client = TelegramClient(http, bot_token)
|
|
return await client.set_webhook(webhook_url, secret=secret)
|
|
|
|
|
|
async def unregister_webhook(bot_token: str) -> dict:
|
|
"""Remove webhook from Telegram Bot API via TelegramClient."""
|
|
from ..services.http_session import get_http_session
|
|
http = await get_http_session()
|
|
client = TelegramClient(http, bot_token)
|
|
return await client.delete_webhook()
|