notifications.py 35 KB

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