notification.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. """Pydantic schemas for notification providers."""
  2. from datetime import datetime
  3. from typing import Any, Literal
  4. from pydantic import BaseModel, Field, field_validator, model_validator
  5. from backend.app.core.compat import StrEnum
  6. class ProviderType(StrEnum):
  7. """Supported notification provider types."""
  8. CALLMEBOT = "callmebot"
  9. NTFY = "ntfy"
  10. PUSHOVER = "pushover"
  11. TELEGRAM = "telegram"
  12. EMAIL = "email"
  13. DISCORD = "discord"
  14. WEBHOOK = "webhook"
  15. HOMEASSISTANT = "homeassistant"
  16. BARK = "bark"
  17. GOTIFY = "gotify"
  18. class NotificationProviderBase(BaseModel):
  19. """Base schema for notification providers."""
  20. name: str = Field(..., min_length=1, max_length=100, description="User-defined name")
  21. provider_type: ProviderType = Field(..., description="Type of notification provider")
  22. enabled: bool = Field(default=True, description="Whether notifications are enabled")
  23. config: dict[str, Any] = Field(..., description="Provider-specific configuration")
  24. attach_photo: bool = Field(
  25. default=True, description="Attach a camera snapshot to this provider's notifications when one is available"
  26. )
  27. # Event triggers - print lifecycle
  28. on_print_start: bool = Field(default=False, description="Notify on print start")
  29. on_print_complete: bool = Field(default=True, description="Notify on print complete")
  30. on_print_failed: bool = Field(default=True, description="Notify on print failed")
  31. on_print_stopped: bool = Field(default=True, description="Notify when print is stopped/cancelled")
  32. on_print_progress: bool = Field(default=False, description="Notify at 25%, 50%, 75% progress")
  33. on_print_missing_spool_assignment: bool = Field(
  34. default=False,
  35. description="Notify when a print starts with required trays missing spool assignments",
  36. )
  37. on_billing_charge_failed: bool = Field(default=True, description="Notify when a print charge cannot be recorded")
  38. # Event triggers - printer status
  39. on_printer_offline: bool = Field(default=False, description="Notify when printer goes offline")
  40. on_printer_error: bool = Field(default=False, description="Notify on printer errors (AMS, etc.)")
  41. on_ai_failure_detection: bool = Field(
  42. default=False,
  43. description="Notify when Obico AI detects a possible print failure (spaghetti)",
  44. )
  45. on_filament_low: bool = Field(default=False, description="Notify when filament is running low")
  46. on_maintenance_due: bool = Field(default=False, description="Notify when maintenance is due")
  47. # Event triggers - AMS environmental alarms (regular AMS)
  48. on_ams_humidity_high: bool = Field(default=False, description="Notify when AMS humidity exceeds threshold")
  49. on_ams_temperature_high: bool = Field(default=False, description="Notify when AMS temperature exceeds threshold")
  50. on_ams_drying_suspended: bool = Field(
  51. default=True, description="Notify when automatic drying gives up on an AMS unit"
  52. )
  53. # Event triggers - AMS-HT environmental alarms
  54. on_ams_ht_humidity_high: bool = Field(default=False, description="Notify when AMS-HT humidity exceeds threshold")
  55. on_ams_ht_temperature_high: bool = Field(
  56. default=False, description="Notify when AMS-HT temperature exceeds threshold"
  57. )
  58. # Event triggers - Home Assistant sensors bound to a printer (#1148)
  59. on_ha_sensor_alert: bool = Field(
  60. default=False, description="Notify when a bound Home Assistant sensor enters its alert state"
  61. )
  62. # Event triggers - Home Assistant sensors bound to a storage location (#2824)
  63. on_location_ha_sensor_alert: bool = Field(
  64. default=False,
  65. description="Notify when a Home Assistant sensor bound to a storage location enters its alert state",
  66. )
  67. # Event triggers - Build plate detection
  68. on_plate_not_empty: bool = Field(default=True, description="Notify when objects detected on plate before print")
  69. on_plate_clear_required: bool = Field(
  70. default=False, description="Notify when a finished print is waiting for plate-clear confirmation"
  71. )
  72. # Event triggers - Post-print outcome confirmation (#1898)
  73. on_print_confirm_request: bool = Field(
  74. default=True,
  75. description="Notify with one-tap verdict links when a print that opted in asks for its outcome",
  76. )
  77. # How a Telegram provider collects the verdict (#3046). Ignored elsewhere.
  78. telegram_verdict_mode: Literal["buttons", "reactions", "both"] = Field(
  79. default="buttons",
  80. description="Telegram only: answer the outcome prompt via inline buttons, a thumbs reaction, or both",
  81. )
  82. # Event triggers - Bed cooled
  83. on_bed_cooled: bool = Field(default=False, description="Notify when bed cools after print")
  84. # Event triggers - First layer complete
  85. on_first_layer_complete: bool = Field(default=False, description="Notify when first layer completes")
  86. # Messages from connected apps (POST /notifications/app-message)
  87. on_app_message: bool = Field(default=False, description="Deliver messages other applications send")
  88. # Event triggers - Inventory stock alerts
  89. # Missing from this schema until now, so every payload naming them was
  90. # dropped silently: the UI's toggles round-tripped as 200 OK and the row
  91. # never changed, and _provider_to_dict never returned them either, so they
  92. # always read back off. The columns and the sending code have existed since
  93. # the inventory forecast landed.
  94. on_stock_reorder_alert: bool = Field(
  95. default=False, description="Notify when an inventory SKU hits its reorder point"
  96. )
  97. on_stock_break_alert: bool = Field(
  98. default=False, description="Notify when stock will run out before replenishment arrives"
  99. )
  100. # Event triggers - Print queue
  101. on_queue_job_added: bool = Field(default=False, description="Notify when job is added to queue")
  102. on_queue_job_assigned: bool = Field(default=False, description="Notify when model-based job is assigned to printer")
  103. on_queue_job_started: bool = Field(default=False, description="Notify when queue job starts printing")
  104. on_queue_job_waiting: bool = Field(default=True, description="Notify when job is waiting for filament or printer")
  105. on_queue_job_skipped: bool = Field(default=True, description="Notify when job is skipped")
  106. on_queue_job_failed: bool = Field(default=True, description="Notify when job fails to start")
  107. on_queue_completed: bool = Field(default=False, description="Notify when all queue jobs finish")
  108. # Quiet hours
  109. quiet_hours_enabled: bool = Field(default=False, description="Enable quiet hours")
  110. quiet_hours_start: str | None = Field(default=None, description="Start time in HH:MM format")
  111. quiet_hours_end: str | None = Field(default=None, description="End time in HH:MM format")
  112. # Daily digest
  113. daily_digest_enabled: bool = Field(default=False, description="Batch notifications into daily digest")
  114. daily_digest_time: str | None = Field(default=None, description="Time to send digest in HH:MM format")
  115. # Printer filter
  116. printer_id: int | None = Field(default=None, description="Specific printer ID or null for all")
  117. @field_validator("quiet_hours_start", "quiet_hours_end", "daily_digest_time")
  118. @classmethod
  119. def validate_time_format(cls, v: str | None) -> str | None:
  120. if v is None:
  121. return v
  122. try:
  123. parts = v.split(":")
  124. if len(parts) != 2:
  125. raise ValueError("Invalid time format")
  126. hour, minute = int(parts[0]), int(parts[1])
  127. if not (0 <= hour <= 23 and 0 <= minute <= 59):
  128. raise ValueError("Invalid time range")
  129. return f"{hour:02d}:{minute:02d}"
  130. except (ValueError, TypeError):
  131. raise ValueError("Time must be in HH:MM format (e.g., 22:00)")
  132. class NotificationProviderCreate(NotificationProviderBase):
  133. """Schema for creating a notification provider."""
  134. pass
  135. class NotificationProviderUpdate(BaseModel):
  136. """Schema for updating a notification provider (all fields optional)."""
  137. name: str | None = Field(default=None, min_length=1, max_length=100)
  138. provider_type: ProviderType | None = None
  139. enabled: bool | None = None
  140. config: dict[str, Any] | None = None
  141. attach_photo: bool | None = None
  142. # Event triggers - print lifecycle
  143. on_print_start: bool | None = None
  144. on_print_complete: bool | None = None
  145. on_print_failed: bool | None = None
  146. on_print_stopped: bool | None = None
  147. on_print_progress: bool | None = None
  148. on_print_missing_spool_assignment: bool | None = None
  149. on_billing_charge_failed: bool | None = None
  150. # Event triggers - printer status
  151. on_printer_offline: bool | None = None
  152. on_printer_error: bool | None = None
  153. on_ai_failure_detection: bool | None = None
  154. on_filament_low: bool | None = None
  155. on_maintenance_due: bool | None = None
  156. # Event triggers - AMS environmental alarms (regular AMS)
  157. on_ams_humidity_high: bool | None = None
  158. on_ams_temperature_high: bool | None = None
  159. on_ams_drying_suspended: bool | None = None
  160. # Event triggers - AMS-HT environmental alarms
  161. on_ams_ht_humidity_high: bool | None = None
  162. on_ams_ht_temperature_high: bool | None = None
  163. # Event triggers - Home Assistant sensors bound to a printer (#1148)
  164. on_ha_sensor_alert: bool | None = None
  165. # Event triggers - Home Assistant sensors bound to a storage location (#2824)
  166. on_location_ha_sensor_alert: bool | None = None
  167. # Event triggers - Build plate detection
  168. on_plate_not_empty: bool | None = None
  169. on_plate_clear_required: bool | None = None
  170. # Event triggers - Post-print outcome confirmation (#1898)
  171. on_print_confirm_request: bool | None = None
  172. telegram_verdict_mode: Literal["buttons", "reactions", "both"] | None = None
  173. # Event triggers - Bed cooled
  174. on_bed_cooled: bool | None = None
  175. # Event triggers - First layer complete
  176. on_first_layer_complete: bool | None = None
  177. # Messages from connected apps
  178. on_app_message: bool | None = None
  179. # Event triggers - Inventory stock alerts
  180. on_stock_reorder_alert: bool | None = None
  181. on_stock_break_alert: bool | None = None
  182. # Event triggers - Print queue
  183. on_queue_job_added: bool | None = None
  184. on_queue_job_assigned: bool | None = None
  185. on_queue_job_started: bool | None = None
  186. on_queue_job_waiting: bool | None = None
  187. on_queue_job_skipped: bool | None = None
  188. on_queue_job_failed: bool | None = None
  189. on_queue_completed: bool | None = None
  190. # Quiet hours
  191. quiet_hours_enabled: bool | None = None
  192. quiet_hours_start: str | None = None
  193. quiet_hours_end: str | None = None
  194. # Daily digest
  195. daily_digest_enabled: bool | None = None
  196. daily_digest_time: str | None = None
  197. # Printer filter
  198. printer_id: int | None = None
  199. class NotificationProviderResponse(NotificationProviderBase):
  200. """Schema for notification provider API responses."""
  201. @model_validator(mode="before")
  202. @classmethod
  203. def _null_event_flags_read_as_off(cls, data: Any) -> Any:
  204. """Read a NULL event flag as off instead of failing the whole response.
  205. Every on_* column on notification_providers is nullable with no server
  206. default -- the values come from the ORM at INSERT time. A row created
  207. before a flag's column existed keeps NULL there forever unless a
  208. migration backfills it, and one that did not (the column was created by
  209. Base.metadata before run_migrations, so the ALTER ... DEFAULT false was
  210. swallowed as a duplicate) leaves NULLs behind on a live install.
  211. Those NULLs are harmless until the flag is declared on this schema: the
  212. Response inherits the write model, so `bool` is then required on the way
  213. out, pydantic rejects None, and every provider row fails at once -- the
  214. list route 500s and the UI renders an empty list, which reads to the user
  215. as "my providers are gone". That is exactly what shipped in #2827.
  216. Off is not a guess: _get_providers_for_event selects on `.is_(True)`, so
  217. the sender already skips a NULL flag. This makes the read agree with the
  218. behaviour the row already has, rather than with the field's declared
  219. default -- some of which are True, and none of which should switch a
  220. notification on as a side effect of repairing a legacy row.
  221. Writes are untouched: Create and Update inherit from the base, not here,
  222. so a payload sending null for a flag is still a 422.
  223. """
  224. # Every route returns _provider_to_dict(); anything else (an ORM object
  225. # via from_attributes) is passed through for pydantic to handle.
  226. if not isinstance(data, dict):
  227. return data
  228. flags = [name for name, f in cls.model_fields.items() if f.annotation is bool]
  229. if any(data.get(name, False) is None for name in flags):
  230. data = {**data, **{name: False for name in flags if data.get(name, False) is None}}
  231. return data
  232. id: int
  233. last_success: datetime | None = None
  234. last_error: str | None = None
  235. last_error_at: datetime | None = None
  236. created_at: datetime
  237. updated_at: datetime
  238. class Config:
  239. from_attributes = True
  240. class AppMessage(BaseModel):
  241. """A message another application sends through Bambuddy's notification channels."""
  242. title: str = Field(min_length=1, max_length=120)
  243. message: str = Field(min_length=1, max_length=2000)
  244. url: str | None = Field(default=None, max_length=500, description="A link the message points to (http or https)")
  245. @field_validator("title", "message")
  246. @classmethod
  247. def _plain_text(cls, value: str) -> str:
  248. # Plain text: no control characters beyond line breaks and tabs.
  249. cleaned = "".join(ch for ch in value if ch in "\n\t" or ch.isprintable()).strip()
  250. if not cleaned:
  251. raise ValueError("must not be empty")
  252. return cleaned
  253. @field_validator("url")
  254. @classmethod
  255. def _http_url(cls, value: str | None) -> str | None:
  256. if value is None or value.strip() == "":
  257. return None
  258. value = value.strip()
  259. if not value.lower().startswith(("http://", "https://")) or any(c.isspace() for c in value):
  260. raise ValueError("must be an http or https address")
  261. return value
  262. class AppMessageResult(BaseModel):
  263. channels: int = Field(description="How many channels the message was handed to")
  264. class AppMessageChannel(BaseModel):
  265. name: str
  266. provider_type: str
  267. class NotificationTestRequest(BaseModel):
  268. """Schema for testing notification configuration."""
  269. provider_type: ProviderType
  270. config: dict[str, Any]
  271. attach_photo: bool = Field(
  272. default=True, description="Include a sample photo in the test, mirroring the provider's own toggle"
  273. )
  274. class NotificationTestResponse(BaseModel):
  275. """Schema for test notification response."""
  276. success: bool
  277. message: str
  278. # Provider-specific config schemas for documentation/validation reference
  279. class CallMeBotConfig(BaseModel):
  280. """CallMeBot/WhatsApp configuration."""
  281. phone: str = Field(..., description="Phone number with country code (e.g., +1234567890)")
  282. apikey: str = Field(..., description="API key from CallMeBot")
  283. class NtfyConfig(BaseModel):
  284. """ntfy configuration."""
  285. server: str = Field(default="https://ntfy.sh", description="ntfy server URL")
  286. topic: str = Field(..., description="Topic name to publish to")
  287. auth_token: str | None = Field(default=None, description="Optional authentication token")
  288. event_priorities: dict[str, int] | None = Field(
  289. default=None,
  290. description=(
  291. "Per-event priority override. Keys are event names, either the provider's "
  292. "toggle column ('on_print_failed', what the UI writes) or the bare event "
  293. "name ('print_failed'); both are accepted. Values are ntfy priorities 1-5 "
  294. "(1=min, 2=low, 3=default, 4=high, 5=urgent). Events without an entry use "
  295. "ntfy's server-side default."
  296. ),
  297. )
  298. class GotifyConfig(BaseModel):
  299. """Gotify configuration (#2743)."""
  300. server: str = Field(..., description="Gotify server URL")
  301. app_token: str = Field(..., description="Token of the Gotify application to post as")
  302. event_priorities: dict[str, int] | None = Field(
  303. default=None,
  304. description=(
  305. "Per-event priority override, keyed like NtfyConfig.event_priorities. Values are "
  306. "levels 1-5 (min, low, default, high, urgent), sent to Gotify as 0, 2, 5, 8 and 10. "
  307. "Events without an entry are sent at 5."
  308. ),
  309. )
  310. class PushoverConfig(BaseModel):
  311. """Pushover configuration."""
  312. user_key: str = Field(..., description="Your Pushover user key")
  313. app_token: str = Field(..., description="Your Pushover application token")
  314. priority: int = Field(default=0, ge=-2, le=2, description="Message priority (-2 to 2)")
  315. # Emergency priority (2) only: how often to re-alert and when to stop.
  316. # Pushover requires retry >= 30s and expire <= 10800s (3h).
  317. retry: int = Field(default=60, ge=30, le=10800, description="Emergency re-alert interval in seconds (priority 2)")
  318. expire: int = Field(default=3600, ge=30, le=10800, description="Emergency alert expiry in seconds (priority 2)")
  319. class TelegramConfig(BaseModel):
  320. """Telegram bot configuration."""
  321. bot_token: str = Field(..., description="Bot token from @BotFather")
  322. chat_id: str = Field(..., description="Chat ID to send messages to")
  323. class EmailConfig(BaseModel):
  324. """Email/SMTP configuration."""
  325. smtp_server: str = Field(..., description="SMTP server hostname")
  326. smtp_port: int = Field(default=587, description="SMTP port (587 for TLS, 465 for SSL)")
  327. username: str = Field(..., description="SMTP username/email")
  328. password: str = Field(..., description="SMTP password or app password")
  329. from_email: str = Field(..., description="From email address")
  330. to_email: str = Field(..., description="Recipient email address")
  331. use_tls: bool = Field(default=True, description="Use TLS encryption")
  332. # Notification Log schemas
  333. class NotificationLogResponse(BaseModel):
  334. """Schema for notification log API responses."""
  335. id: int
  336. provider_id: int
  337. provider_name: str | None = None
  338. provider_type: str | None = None
  339. event_type: str
  340. title: str
  341. message: str
  342. success: bool
  343. error_message: str | None = None
  344. printer_id: int | None = None
  345. printer_name: str | None = None
  346. created_at: datetime
  347. class Config:
  348. from_attributes = True
  349. class NotificationLogStats(BaseModel):
  350. """Statistics for notification logs."""
  351. total: int
  352. success_count: int
  353. failure_count: int
  354. by_event_type: dict[str, int]
  355. by_provider: dict[str, int]