import base64 import logging from typing import Optional import httpx from cryptography.fernet import InvalidToken from sqlalchemy import select from app.database import AsyncSessionLocal from app.utils.crypto import decrypt logger = logging.getLogger("bourbonacci.notify") def _header_value(value: str) -> str: # HTTP header values must be ASCII; ntfy decodes RFC 2047 encoded-words, # so send non-ASCII titles/tags that way and leave plain ASCII untouched. if value.isascii(): return value return "=?UTF-8?B?" + base64.b64encode(value.encode("utf-8")).decode("ascii") + "?=" def _normalize_server_url(server_url: str) -> str: server_url = server_url.strip() if not server_url.startswith(("http://", "https://")): server_url = "https://" + server_url return server_url async def notify( title: str, message: str, priority: str = "default", tags: Optional[list[str]] = None, ) -> bool: """Send an admin push notification using the ntfy settings saved in the admin panel (Notifications tab). Returns False if not configured or the send failed; never raises.""" from app.models.admin_settings import AdminSettings async with AsyncSessionLocal() as db: row = (await db.execute(select(AdminSettings).where(AdminSettings.id == 1))).scalar_one_or_none() if not row or not row.ntfy_server_url or not row.ntfy_topic: return False try: token = decrypt(row.ntfy_token) if row.ntfy_token else None except InvalidToken: logger.error("Could not decrypt stored admin ntfy token") return False server_url = _normalize_server_url(row.ntfy_server_url) url = server_url.rstrip("/") + "/" + row.ntfy_topic.strip("/") headers = {"Title": _header_value(f"Bourbonacci Admin - {title}"), "Priority": priority} if tags: headers["Tags"] = _header_value(",".join(tags)) if token: headers["Authorization"] = f"Bearer {token}" try: async with httpx.AsyncClient(timeout=10) as client: resp = await client.post(url, content=message.encode("utf-8"), headers=headers) if resp.status_code >= 300: logger.warning("Ntfy send to %s failed with status %s", server_url, resp.status_code) return False return True except httpx.HTTPError as exc: logger.warning("Ntfy send to %s failed: %s", server_url, exc) return False