notifications.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. """API routes for notification providers."""
  2. import json
  3. import logging
  4. import time
  5. from collections import defaultdict, deque
  6. from datetime import datetime, timedelta, timezone
  7. from fastapi import APIRouter, Depends, HTTPException, Query
  8. from fastapi.responses import FileResponse
  9. from sqlalchemy import delete, desc, func, select, update
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.auth import RequirePermissionIfAuthEnabled, ScopedCaller, require_notification_send
  12. from backend.app.core.database import get_db
  13. from backend.app.core.permissions import Permission
  14. from backend.app.core.printer_scope import ensure_printers_exist
  15. from backend.app.models.notification import NotificationLog, NotificationProvider
  16. from backend.app.models.notification_lock_screen_widget import NotificationLockScreenWidget
  17. from backend.app.models.user import User
  18. from backend.app.schemas.notification import (
  19. AppMessage,
  20. AppMessageChannel,
  21. AppMessageResult,
  22. NotificationLogResponse,
  23. NotificationLogStats,
  24. NotificationProviderCreate,
  25. NotificationProviderResponse,
  26. NotificationProviderUpdate,
  27. NotificationTestRequest,
  28. NotificationTestResponse,
  29. )
  30. from backend.app.services.notification_service import notification_service
  31. from backend.app.services.notify_client import NotifyError, notify_credentials
  32. from backend.app.services.notify_live_activities import notify_live_activities
  33. from backend.app.services.notify_widgets import notify_widgets
  34. from backend.app.services.telegram_reactions import telegram_reaction_poller
  35. from backend.app.utils.notification_photos import find_notification_photo
  36. logger = logging.getLogger(__name__)
  37. router = APIRouter(prefix="/notifications", tags=["notifications"])
  38. def _notify_providers_changed() -> None:
  39. """Wake optional workers after a provider edit, without waiting for their HTTP work."""
  40. for worker in (notify_live_activities, notify_widgets):
  41. try:
  42. worker.providers_changed()
  43. except Exception:
  44. logger.exception("Could not refresh Notify worker configuration")
  45. async def _resync_reaction_poller():
  46. """Start/stop Telegram reaction polls after a provider changed (#3046).
  47. Never fails the request: the provider row is already saved, and the
  48. poller catches up on the next restart at worst.
  49. """
  50. try:
  51. await telegram_reaction_poller.sync()
  52. except Exception as e:
  53. logger.warning("Telegram reaction poller resync failed: %s", e)
  54. async def delete_provider(db: AsyncSession, provider: NotificationProvider) -> bool:
  55. """Delete a provider (the caller commits, then calls after_providers_deleted).
  56. A Bambuddy Notify provider is first retired and its live activities and
  57. widgets queued for remote cleanup, while the rows that name them still
  58. exist. Returns whether it was one.
  59. """
  60. notify = provider.provider_type == "notify"
  61. if notify:
  62. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  63. # Retire this provider and capture owned IDs before FK cascade removes
  64. # them. Queue remote cleanup; HTTP must never delay this request.
  65. provider.enabled = False
  66. await db.commit()
  67. await notify_live_activities.schedule_cleanup(provider.id, config)
  68. await notify_widgets.schedule_cleanup(provider.id, config)
  69. await db.delete(provider)
  70. return notify
  71. async def after_providers_deleted(*, notify: bool) -> None:
  72. """What deleted providers leave to do once the delete is committed."""
  73. if notify:
  74. _notify_providers_changed()
  75. await _resync_reaction_poller()
  76. def _provider_to_dict(provider: NotificationProvider) -> dict:
  77. """Convert a NotificationProvider model to a response dictionary."""
  78. return {
  79. "id": provider.id,
  80. "name": provider.name,
  81. "provider_type": provider.provider_type,
  82. "enabled": provider.enabled,
  83. "config": json.loads(provider.config) if isinstance(provider.config, str) else provider.config,
  84. "attach_photo": provider.attach_photo,
  85. # Print lifecycle events
  86. "on_print_start": provider.on_print_start,
  87. "on_print_complete": provider.on_print_complete,
  88. "on_print_failed": provider.on_print_failed,
  89. "on_print_stopped": provider.on_print_stopped,
  90. "on_print_progress": provider.on_print_progress,
  91. "on_print_missing_spool_assignment": provider.on_print_missing_spool_assignment,
  92. "on_billing_charge_failed": provider.on_billing_charge_failed,
  93. # Printer status events
  94. "on_printer_offline": provider.on_printer_offline,
  95. "on_printer_error": provider.on_printer_error,
  96. "on_ai_failure_detection": provider.on_ai_failure_detection,
  97. "on_filament_low": provider.on_filament_low,
  98. "on_maintenance_due": provider.on_maintenance_due,
  99. # Home Assistant sensor alerts (#1148, #2824). Both directions of this
  100. # file are hand-maintained field maps, so a column missing here reads
  101. # back as the schema default (False) no matter what the row holds.
  102. "on_ha_sensor_alert": provider.on_ha_sensor_alert,
  103. "on_location_ha_sensor_alert": provider.on_location_ha_sensor_alert,
  104. # AMS environmental alarms (regular AMS)
  105. "on_ams_humidity_high": provider.on_ams_humidity_high,
  106. "on_ams_temperature_high": provider.on_ams_temperature_high,
  107. "on_ams_drying_suspended": provider.on_ams_drying_suspended,
  108. # AMS-HT environmental alarms
  109. "on_ams_ht_humidity_high": provider.on_ams_ht_humidity_high,
  110. "on_ams_ht_temperature_high": provider.on_ams_ht_temperature_high,
  111. # Build plate detection
  112. "on_plate_not_empty": provider.on_plate_not_empty,
  113. "on_plate_clear_required": provider.on_plate_clear_required,
  114. # Post-print outcome confirmation (#1898)
  115. "on_print_confirm_request": provider.on_print_confirm_request,
  116. # Rows from before #3046 hold NULL here; "buttons" is what they did.
  117. "telegram_verdict_mode": provider.telegram_verdict_mode or "buttons",
  118. # Bed cooled
  119. "on_bed_cooled": provider.on_bed_cooled,
  120. # First layer complete
  121. "on_first_layer_complete": provider.on_first_layer_complete,
  122. # Messages from connected apps
  123. "on_app_message": bool(provider.on_app_message),
  124. # Inventory stock alerts. Absent here, the toggles above always read
  125. # back off no matter what the row holds — the same hand-maintained
  126. # field map the Home Assistant comment warns about.
  127. "on_stock_reorder_alert": provider.on_stock_reorder_alert,
  128. "on_stock_break_alert": provider.on_stock_break_alert,
  129. # Print queue events
  130. "on_queue_job_added": provider.on_queue_job_added,
  131. "on_queue_job_assigned": provider.on_queue_job_assigned,
  132. "on_queue_job_started": provider.on_queue_job_started,
  133. "on_queue_job_waiting": provider.on_queue_job_waiting,
  134. "on_queue_job_skipped": provider.on_queue_job_skipped,
  135. "on_queue_job_failed": provider.on_queue_job_failed,
  136. "on_queue_completed": provider.on_queue_completed,
  137. # Quiet hours
  138. "quiet_hours_enabled": provider.quiet_hours_enabled,
  139. "quiet_hours_start": provider.quiet_hours_start,
  140. "quiet_hours_end": provider.quiet_hours_end,
  141. # Daily digest
  142. "daily_digest_enabled": provider.daily_digest_enabled,
  143. "daily_digest_time": provider.daily_digest_time,
  144. # Printer filter
  145. "printer_id": provider.printer_id,
  146. # Status tracking
  147. "last_success": provider.last_success,
  148. "last_error": provider.last_error,
  149. "last_error_at": provider.last_error_at,
  150. # Timestamps
  151. "created_at": provider.created_at,
  152. "updated_at": provider.updated_at,
  153. }
  154. # ============================================================================
  155. # Provider List/Create Routes (no path parameters)
  156. # ============================================================================
  157. @router.get("/", response_model=list[NotificationProviderResponse])
  158. async def list_notification_providers(
  159. db: AsyncSession = Depends(get_db),
  160. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  161. ):
  162. """List all notification providers."""
  163. result = await db.execute(select(NotificationProvider).order_by(NotificationProvider.created_at.desc()))
  164. providers = result.scalars().all()
  165. return [_provider_to_dict(provider) for provider in providers]
  166. @router.post("/", response_model=NotificationProviderResponse)
  167. async def create_notification_provider(
  168. provider_data: NotificationProviderCreate,
  169. db: AsyncSession = Depends(get_db),
  170. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_CREATE),
  171. ):
  172. """Create a new notification provider."""
  173. await ensure_printers_exist(db, [provider_data.printer_id])
  174. if provider_data.provider_type.value == "notify":
  175. try:
  176. notify_credentials(provider_data.config)
  177. except NotifyError as exc:
  178. raise HTTPException(status_code=422, detail=str(exc)) from None
  179. provider = NotificationProvider(
  180. name=provider_data.name,
  181. provider_type=provider_data.provider_type.value,
  182. enabled=provider_data.enabled,
  183. config=json.dumps(provider_data.config),
  184. attach_photo=provider_data.attach_photo,
  185. # Print lifecycle events
  186. on_print_start=provider_data.on_print_start,
  187. on_print_complete=provider_data.on_print_complete,
  188. on_print_failed=provider_data.on_print_failed,
  189. on_print_stopped=provider_data.on_print_stopped,
  190. on_print_progress=provider_data.on_print_progress,
  191. on_print_missing_spool_assignment=provider_data.on_print_missing_spool_assignment,
  192. on_billing_charge_failed=provider_data.on_billing_charge_failed,
  193. # Printer status events
  194. on_printer_offline=provider_data.on_printer_offline,
  195. on_printer_error=provider_data.on_printer_error,
  196. on_ai_failure_detection=provider_data.on_ai_failure_detection,
  197. on_filament_low=provider_data.on_filament_low,
  198. on_maintenance_due=provider_data.on_maintenance_due,
  199. # Home Assistant sensor alerts (#1148, #2824)
  200. on_ha_sensor_alert=provider_data.on_ha_sensor_alert,
  201. on_location_ha_sensor_alert=provider_data.on_location_ha_sensor_alert,
  202. # AMS environmental alarms (regular AMS)
  203. on_ams_humidity_high=provider_data.on_ams_humidity_high,
  204. on_ams_temperature_high=provider_data.on_ams_temperature_high,
  205. on_ams_drying_suspended=provider_data.on_ams_drying_suspended,
  206. # AMS-HT environmental alarms
  207. on_ams_ht_humidity_high=provider_data.on_ams_ht_humidity_high,
  208. on_ams_ht_temperature_high=provider_data.on_ams_ht_temperature_high,
  209. # Build plate detection
  210. on_plate_not_empty=provider_data.on_plate_not_empty,
  211. on_plate_clear_required=provider_data.on_plate_clear_required,
  212. # Post-print outcome confirmation (#1898)
  213. on_print_confirm_request=provider_data.on_print_confirm_request,
  214. telegram_verdict_mode=provider_data.telegram_verdict_mode,
  215. # Bed cooled
  216. on_bed_cooled=provider_data.on_bed_cooled,
  217. # First layer complete
  218. on_first_layer_complete=provider_data.on_first_layer_complete,
  219. on_app_message=provider_data.on_app_message,
  220. # Inventory stock alerts
  221. on_stock_reorder_alert=provider_data.on_stock_reorder_alert,
  222. on_stock_break_alert=provider_data.on_stock_break_alert,
  223. # Print queue events
  224. on_queue_job_added=provider_data.on_queue_job_added,
  225. on_queue_job_assigned=provider_data.on_queue_job_assigned,
  226. on_queue_job_started=provider_data.on_queue_job_started,
  227. on_queue_job_waiting=provider_data.on_queue_job_waiting,
  228. on_queue_job_skipped=provider_data.on_queue_job_skipped,
  229. on_queue_job_failed=provider_data.on_queue_job_failed,
  230. on_queue_completed=provider_data.on_queue_completed,
  231. # Quiet hours
  232. quiet_hours_enabled=provider_data.quiet_hours_enabled,
  233. quiet_hours_start=provider_data.quiet_hours_start,
  234. quiet_hours_end=provider_data.quiet_hours_end,
  235. # Daily digest
  236. daily_digest_enabled=provider_data.daily_digest_enabled,
  237. daily_digest_time=provider_data.daily_digest_time,
  238. # Printer filter
  239. printer_id=provider_data.printer_id,
  240. )
  241. db.add(provider)
  242. await db.commit()
  243. await db.refresh(provider)
  244. logger.info("Created notification provider: %s (%s)", provider.name, provider.provider_type)
  245. if provider.provider_type == "notify":
  246. _notify_providers_changed()
  247. await _resync_reaction_poller()
  248. return _provider_to_dict(provider)
  249. # ============================================================================
  250. # Static Path Routes (must come BEFORE parameterized routes)
  251. # ============================================================================
  252. @router.post("/test-config", response_model=NotificationTestResponse)
  253. async def test_notification_config(
  254. test_request: NotificationTestRequest,
  255. db: AsyncSession = Depends(get_db),
  256. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_CREATE),
  257. ):
  258. """Test notification configuration before saving."""
  259. success, message = await notification_service.send_test_notification(
  260. test_request.provider_type.value, test_request.config, db, attach_photo=test_request.attach_photo
  261. )
  262. return NotificationTestResponse(success=success, message=message)
  263. @router.post("/test-all")
  264. async def test_all_notification_providers(
  265. db: AsyncSession = Depends(get_db),
  266. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  267. ):
  268. """Send a test notification to all enabled providers."""
  269. result = await db.execute(select(NotificationProvider).where(NotificationProvider.enabled.is_(True)))
  270. providers = result.scalars().all()
  271. if not providers:
  272. return {"tested": 0, "success": 0, "failed": 0, "results": []}
  273. results = []
  274. success_count = 0
  275. failed_count = 0
  276. for provider in providers:
  277. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  278. success, message = await notification_service.send_test_notification(
  279. provider.provider_type, config, db, attach_photo=provider.attach_photo
  280. )
  281. # Update provider status
  282. if success:
  283. provider.last_success = datetime.now(timezone.utc)
  284. success_count += 1
  285. else:
  286. provider.last_error = message
  287. provider.last_error_at = datetime.now(timezone.utc)
  288. failed_count += 1
  289. results.append(
  290. {
  291. "provider_id": provider.id,
  292. "provider_name": provider.name,
  293. "provider_type": provider.provider_type,
  294. "success": success,
  295. "message": message,
  296. }
  297. )
  298. await db.commit()
  299. return {
  300. "tested": len(providers),
  301. "success": success_count,
  302. "failed": failed_count,
  303. "results": results,
  304. }
  305. # ============================================================================
  306. # Notification Log Routes (must come BEFORE /{provider_id} routes)
  307. # ============================================================================
  308. @router.get("/logs", response_model=list[NotificationLogResponse])
  309. async def get_notification_logs(
  310. limit: int = Query(default=100, ge=1, le=500),
  311. offset: int = Query(default=0, ge=0),
  312. provider_id: int | None = Query(default=None),
  313. event_type: str | None = Query(default=None),
  314. success: bool | None = Query(default=None),
  315. days: int | None = Query(default=7, ge=1, le=90, description="Filter logs from the last N days"),
  316. db: AsyncSession = Depends(get_db),
  317. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  318. ):
  319. """Get notification logs with optional filters."""
  320. query = select(NotificationLog).order_by(desc(NotificationLog.created_at))
  321. # Apply filters
  322. if provider_id is not None:
  323. query = query.where(NotificationLog.provider_id == provider_id)
  324. if event_type is not None:
  325. query = query.where(NotificationLog.event_type == event_type)
  326. if success is not None:
  327. query = query.where(NotificationLog.success == success)
  328. if days is not None:
  329. cutoff = datetime.now(timezone.utc) - timedelta(days=days)
  330. query = query.where(NotificationLog.created_at >= cutoff)
  331. query = query.offset(offset).limit(limit)
  332. result = await db.execute(query)
  333. logs = result.scalars().all()
  334. # Get provider info for each log
  335. response = []
  336. providers_cache: dict[int, NotificationProvider | None] = {}
  337. for log in logs:
  338. if log.provider_id not in providers_cache:
  339. provider_result = await db.execute(
  340. select(NotificationProvider).where(NotificationProvider.id == log.provider_id)
  341. )
  342. providers_cache[log.provider_id] = provider_result.scalar_one_or_none()
  343. provider = providers_cache[log.provider_id]
  344. response.append(
  345. NotificationLogResponse(
  346. id=log.id,
  347. provider_id=log.provider_id,
  348. provider_name=provider.name if provider else None,
  349. provider_type=provider.provider_type if provider else None,
  350. event_type=log.event_type,
  351. title=log.title,
  352. message=log.message,
  353. success=log.success,
  354. error_message=log.error_message,
  355. printer_id=log.printer_id,
  356. printer_name=log.printer_name,
  357. created_at=log.created_at,
  358. )
  359. )
  360. return response
  361. @router.get("/logs/stats", response_model=NotificationLogStats)
  362. async def get_notification_log_stats(
  363. days: int = Query(default=7, ge=1, le=90, description="Statistics for the last N days"),
  364. db: AsyncSession = Depends(get_db),
  365. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  366. ):
  367. """Get notification log statistics."""
  368. cutoff = datetime.now(timezone.utc) - timedelta(days=days)
  369. # Total counts
  370. total_result = await db.execute(select(func.count(NotificationLog.id)).where(NotificationLog.created_at >= cutoff))
  371. total = total_result.scalar() or 0
  372. success_result = await db.execute(
  373. select(func.count(NotificationLog.id)).where(
  374. NotificationLog.created_at >= cutoff, NotificationLog.success.is_(True)
  375. )
  376. )
  377. success_count = success_result.scalar() or 0
  378. # By event type
  379. event_result = await db.execute(
  380. select(NotificationLog.event_type, func.count(NotificationLog.id))
  381. .where(NotificationLog.created_at >= cutoff)
  382. .group_by(NotificationLog.event_type)
  383. )
  384. by_event_type = {row[0]: row[1] for row in event_result.fetchall()}
  385. # By provider (need to join to get name)
  386. provider_result = await db.execute(
  387. select(NotificationProvider.name, func.count(NotificationLog.id))
  388. .join(NotificationProvider, NotificationLog.provider_id == NotificationProvider.id)
  389. .where(NotificationLog.created_at >= cutoff)
  390. .group_by(NotificationProvider.name)
  391. )
  392. by_provider = {row[0]: row[1] for row in provider_result.fetchall()}
  393. return NotificationLogStats(
  394. total=total,
  395. success_count=success_count,
  396. failure_count=total - success_count,
  397. by_event_type=by_event_type,
  398. by_provider=by_provider,
  399. )
  400. @router.delete("/logs")
  401. async def clear_notification_logs(
  402. older_than_days: int = Query(default=30, ge=1, description="Delete logs older than N days"),
  403. db: AsyncSession = Depends(get_db),
  404. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_DELETE),
  405. ):
  406. """Clear old notification logs."""
  407. cutoff = datetime.now(timezone.utc) - timedelta(days=older_than_days)
  408. result = await db.execute(delete(NotificationLog).where(NotificationLog.created_at < cutoff))
  409. await db.commit()
  410. deleted_count = result.rowcount
  411. logger.info("Deleted %s notification logs older than %s days", deleted_count, older_than_days)
  412. return {"deleted": deleted_count, "message": f"Deleted {deleted_count} logs older than {older_than_days} days"}
  413. @router.get("/photos/{filename}")
  414. async def get_notification_photo(filename: str):
  415. """Serve an ad-hoc notification snapshot to HA, Bark or Slack.
  416. They fetch this URL themselves with no session, so the unguessable
  417. filename is the credential and opens this one photo only -- see
  418. backend/app/utils/notification_photos.py. Anything that isn't a live
  419. photo of exactly that shape is a 404.
  420. """
  421. photo_path = find_notification_photo(filename)
  422. if photo_path is None:
  423. raise HTTPException(404, "Photo not found")
  424. return FileResponse(path=photo_path, media_type="image/jpeg", headers={"Cache-Control": "private, no-store"})
  425. # ============================================================================
  426. # Provider Instance Routes (parameterized - must come LAST)
  427. # ============================================================================
  428. # Messages from other applications -------------------------------------------
  429. # Per caller, in memory: enough for any real app (Bambuddy Orders sends a few a
  430. # day), and a buggy or hostile one can't flood the channels.
  431. APP_MESSAGE_LIMIT = 20
  432. APP_MESSAGE_WINDOW_SECONDS = 60
  433. _app_message_times: dict[str, deque[float]] = defaultdict(deque)
  434. def _app_sender(caller: ScopedCaller) -> tuple[str, str]:
  435. """(rate-limit key, name shown in the log) for whoever sends the message."""
  436. if caller.api_key is not None:
  437. return f"key:{caller.api_key.id}", caller.api_key.name
  438. if caller.user is not None:
  439. return f"user:{caller.user.id}", caller.user.username
  440. return "anonymous", "app"
  441. def forget_app_senders(api_key_ids=(), user_ids=()) -> None:
  442. """Drop deleted keys' and users' message counts: SQLite gives an id to the
  443. next key or user created, which would start out throttled."""
  444. for key_id in api_key_ids:
  445. _app_message_times.pop(f"key:{key_id}", None)
  446. for user_id in user_ids:
  447. _app_message_times.pop(f"user:{user_id}", None)
  448. def _check_app_message_rate(key: str) -> None:
  449. times = _app_message_times[key]
  450. cutoff = time.monotonic() - APP_MESSAGE_WINDOW_SECONDS
  451. while times and times[0] < cutoff:
  452. times.popleft()
  453. if len(times) >= APP_MESSAGE_LIMIT:
  454. raise HTTPException(status_code=429, detail="Too many messages; try again in a minute")
  455. times.append(time.monotonic())
  456. @router.post("/app-message", response_model=AppMessageResult)
  457. async def send_app_message(
  458. data: AppMessage,
  459. db: AsyncSession = Depends(get_db),
  460. caller: ScopedCaller = Depends(require_notification_send()),
  461. ):
  462. """Send a message through every enabled channel that has "Messages from
  463. connected apps" on. For other applications, e.g. Bambuddy Orders; an API
  464. key needs the "Send notifications" permission."""
  465. key, sender = _app_sender(caller)
  466. _check_app_message_rate(key)
  467. channels = await notification_service.on_app_message(
  468. db, sender=sender, title=data.title, message=data.message, url=data.url
  469. )
  470. return AppMessageResult(channels=channels)
  471. @router.get("/app-message/channels", response_model=list[AppMessageChannel])
  472. async def app_message_channels(
  473. db: AsyncSession = Depends(get_db),
  474. _: ScopedCaller = Depends(require_notification_send()),
  475. ):
  476. """The enabled channels that deliver app messages: names and types only,
  477. so an app can tell its user where its messages will arrive."""
  478. rows = await db.execute(
  479. select(NotificationProvider)
  480. .where(NotificationProvider.enabled.is_(True), NotificationProvider.on_app_message.is_(True))
  481. .order_by(NotificationProvider.name)
  482. )
  483. return [AppMessageChannel(name=p.name, provider_type=p.provider_type) for p in rows.scalars()]
  484. @router.get("/{provider_id}", response_model=NotificationProviderResponse)
  485. async def get_notification_provider(
  486. provider_id: int,
  487. db: AsyncSession = Depends(get_db),
  488. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_READ),
  489. ):
  490. """Get a specific notification provider."""
  491. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  492. provider = result.scalar_one_or_none()
  493. if not provider:
  494. raise HTTPException(status_code=404, detail="Notification provider not found")
  495. return _provider_to_dict(provider)
  496. @router.patch("/{provider_id}", response_model=NotificationProviderResponse)
  497. async def update_notification_provider(
  498. provider_id: int,
  499. update_data: NotificationProviderUpdate,
  500. db: AsyncSession = Depends(get_db),
  501. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  502. ):
  503. """Update a notification provider."""
  504. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  505. provider = result.scalar_one_or_none()
  506. if not provider:
  507. raise HTTPException(status_code=404, detail="Notification provider not found")
  508. old_config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  509. old_type = provider.provider_type
  510. # Update only provided fields
  511. update_dict = update_data.model_dump(exclude_unset=True)
  512. await ensure_printers_exist(db, [update_dict.get("printer_id")])
  513. effective_type = update_dict.get("provider_type") or provider.provider_type
  514. effective_type = getattr(effective_type, "value", effective_type)
  515. if effective_type == "notify":
  516. try:
  517. effective_config = update_dict.get("config", old_config)
  518. if not isinstance(effective_config, dict):
  519. raise NotifyError("Notify! configuration must be an object")
  520. notify_credentials(effective_config)
  521. except NotifyError as exc:
  522. raise HTTPException(status_code=422, detail=str(exc)) from None
  523. for key, value in update_dict.items():
  524. if key == "config" and value is not None:
  525. setattr(provider, key, json.dumps(value))
  526. elif key == "provider_type" and value is not None:
  527. setattr(provider, key, value.value)
  528. else:
  529. setattr(provider, key, value)
  530. if old_type == "notify":
  531. effective_config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  532. remove_widgets = (
  533. provider.provider_type != "notify"
  534. or not provider.enabled
  535. or effective_config.get("lock_screen_widgets") is not True
  536. )
  537. if remove_widgets or provider.printer_id is not None:
  538. condition = NotificationLockScreenWidget.provider_id == provider_id
  539. if not remove_widgets:
  540. condition = condition & (NotificationLockScreenWidget.printer_id != provider.printer_id)
  541. # Persist opt-out before returning, even if the user immediately
  542. # opts back in. The worker finishes cleanup before creating anew.
  543. await db.execute(
  544. update(NotificationLockScreenWidget)
  545. .where(condition)
  546. .values(
  547. state="deleting",
  548. failures=0,
  549. next_attempt_at=None,
  550. )
  551. )
  552. await db.commit()
  553. await db.refresh(provider)
  554. response = _provider_to_dict(provider)
  555. new_config = response["config"]
  556. changed = old_type != provider.provider_type or any(
  557. old_config.get(key) != new_config.get(key) for key in ("device_id", "token")
  558. )
  559. # Refresh opened a new read transaction; close it before remote cleanup.
  560. await db.commit()
  561. if old_type == "notify" and changed:
  562. await notify_live_activities.schedule_cleanup(provider_id, old_config)
  563. await notify_widgets.schedule_cleanup(provider_id, old_config)
  564. if old_type == "notify" or provider.provider_type == "notify":
  565. _notify_providers_changed()
  566. logger.info("Updated notification provider: %s", provider.name)
  567. await _resync_reaction_poller()
  568. return response
  569. @router.delete("/{provider_id}")
  570. async def delete_notification_provider(
  571. provider_id: int,
  572. db: AsyncSession = Depends(get_db),
  573. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_DELETE),
  574. ):
  575. """Delete a notification provider."""
  576. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  577. provider = result.scalar_one_or_none()
  578. if not provider:
  579. raise HTTPException(status_code=404, detail="Notification provider not found")
  580. name = provider.name
  581. notify = await delete_provider(db, provider)
  582. await db.commit()
  583. await after_providers_deleted(notify=notify)
  584. logger.info("Deleted notification provider: %s", name)
  585. return {"message": f"Notification provider '{name}' deleted"}
  586. @router.post("/{provider_id}/test", response_model=NotificationTestResponse)
  587. async def test_notification_provider(
  588. provider_id: int,
  589. db: AsyncSession = Depends(get_db),
  590. _: User | None = RequirePermissionIfAuthEnabled(Permission.NOTIFICATIONS_UPDATE),
  591. ):
  592. """Send a test notification using an existing provider."""
  593. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  594. provider = result.scalar_one_or_none()
  595. if not provider:
  596. raise HTTPException(status_code=404, detail="Notification provider not found")
  597. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  598. success, message = await notification_service.send_test_notification(
  599. provider.provider_type, config, db, attach_photo=provider.attach_photo
  600. )
  601. # Update provider status
  602. if success:
  603. provider.last_success = datetime.now(timezone.utc)
  604. else:
  605. provider.last_error = message
  606. provider.last_error_at = datetime.now(timezone.utc)
  607. await db.commit()
  608. return NotificationTestResponse(success=success, message=message)