ForcePilot/backend/package/yuxi/channels/adapters/synologychat/webhook_send.py

79 lines
2.8 KiB
Python
Raw Normal View History

"""Incoming Webhook sender for Synology Chat.
Provides an alternative send path via Synology Chat's Incoming Webhook URL,
as a lighter-weight alternative to the DSM API direct connection.
"""
from __future__ import annotations
import asyncio
from typing import Any
import httpx
from yuxi.channels.adapters.synologychat.send import assert_safe_media_url
from yuxi.channels.models import DeliveryResult
async def send_via_incoming_webhook(
webhook_url: str,
text: str,
file_url: str | None = None,
timeout: float = 30.0,
client: httpx.AsyncClient | None = None,
max_retries: int = 3,
) -> DeliveryResult:
if not webhook_url:
return DeliveryResult(success=False, error="Incoming webhook URL not configured")
try:
await assert_safe_media_url(webhook_url)
except Exception as e:
return DeliveryResult(success=False, error=f"SSRF check failed: {e}")
payload: dict[str, Any] = {"text": text}
if file_url:
payload["file_url"] = file_url
async def _do_send(http_client: httpx.AsyncClient) -> DeliveryResult:
response = await http_client.post(webhook_url, data=payload)
response.raise_for_status()
result = response.json()
if result.get("success"):
return DeliveryResult(success=True, message_id=result.get("data", {}).get("message_id"))
return DeliveryResult(
success=False,
error=f"Webhook send failed: {result.get('error', {})}",
)
last_error = None
for attempt in range(max_retries):
try:
if client:
result = await _do_send(client)
else:
async with httpx.AsyncClient(timeout=httpx.Timeout(timeout)) as new_client:
result = await _do_send(new_client)
if result.success:
return result
last_error = result.error
except httpx.TimeoutException:
last_error = "Incoming webhook request timed out"
except httpx.HTTPStatusError as e:
if e.response.status_code < 500:
return DeliveryResult(success=False, error=f"Incoming webhook HTTP {e.response.status_code}")
last_error = f"Incoming webhook HTTP {e.response.status_code}"
except Exception as e:
last_error = str(e)
if attempt < max_retries - 1:
await asyncio.sleep(1.0 * (2**attempt))
return DeliveryResult(success=False, error=last_error or "Webhook send failed after retries")
def build_webhook_url(dsm_url: str, webhook_token: str) -> str:
"""Build a Synology Chat Incoming Webhook URL from DSM URL and token."""
base = dsm_url.rstrip("/")
return f"{base}/webapi/entry.cgi?api=SYNO.Chat.External&method=incoming&version=1&token={webhook_token}"