notification.py 17 KB

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