notification.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. """Pydantic schemas for notification providers."""
  2. from datetime import datetime
  3. from typing import Any
  4. from pydantic import BaseModel, Field, field_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. class NotificationProviderBase(BaseModel):
  18. """Base schema for notification providers."""
  19. name: str = Field(..., min_length=1, max_length=100, description="User-defined name")
  20. provider_type: ProviderType = Field(..., description="Type of notification provider")
  21. enabled: bool = Field(default=True, description="Whether notifications are enabled")
  22. config: dict[str, Any] = Field(..., description="Provider-specific configuration")
  23. # Event triggers - print lifecycle
  24. on_print_start: bool = Field(default=False, description="Notify on print start")
  25. on_print_complete: bool = Field(default=True, description="Notify on print complete")
  26. on_print_failed: bool = Field(default=True, description="Notify on print failed")
  27. on_print_stopped: bool = Field(default=True, description="Notify when print is stopped/cancelled")
  28. on_print_progress: bool = Field(default=False, description="Notify at 25%, 50%, 75% progress")
  29. on_print_missing_spool_assignment: bool = Field(
  30. default=False,
  31. description="Notify when a print starts with required trays missing spool assignments",
  32. )
  33. on_billing_charge_failed: bool = Field(default=True, description="Notify when a print charge cannot be recorded")
  34. # Event triggers - printer status
  35. on_printer_offline: bool = Field(default=False, description="Notify when printer goes offline")
  36. on_printer_error: bool = Field(default=False, description="Notify on printer errors (AMS, etc.)")
  37. on_ai_failure_detection: bool = Field(
  38. default=False,
  39. description="Notify when Obico AI detects a possible print failure (spaghetti)",
  40. )
  41. on_filament_low: bool = Field(default=False, description="Notify when filament is running low")
  42. on_maintenance_due: bool = Field(default=False, description="Notify when maintenance is due")
  43. # Event triggers - AMS environmental alarms (regular AMS)
  44. on_ams_humidity_high: bool = Field(default=False, description="Notify when AMS humidity exceeds threshold")
  45. on_ams_temperature_high: bool = Field(default=False, description="Notify when AMS temperature exceeds threshold")
  46. # Event triggers - AMS-HT environmental alarms
  47. on_ams_ht_humidity_high: bool = Field(default=False, description="Notify when AMS-HT humidity exceeds threshold")
  48. on_ams_ht_temperature_high: bool = Field(
  49. default=False, description="Notify when AMS-HT temperature exceeds threshold"
  50. )
  51. # Event triggers - Home Assistant sensors (#1148)
  52. on_ha_sensor_alert: bool = Field(
  53. default=False, description="Notify when a bound Home Assistant sensor enters its alert state"
  54. )
  55. # Event triggers - Build plate detection
  56. on_plate_not_empty: bool = Field(default=True, description="Notify when objects detected on plate before print")
  57. on_plate_clear_required: bool = Field(
  58. default=False, description="Notify when a finished print is waiting for plate-clear confirmation"
  59. )
  60. # Event triggers - Bed cooled
  61. on_bed_cooled: bool = Field(default=False, description="Notify when bed cools after print")
  62. # Event triggers - First layer complete
  63. on_first_layer_complete: bool = Field(default=False, description="Notify when first layer completes")
  64. # Event triggers - Print queue
  65. on_queue_job_added: bool = Field(default=False, description="Notify when job is added to queue")
  66. on_queue_job_assigned: bool = Field(default=False, description="Notify when model-based job is assigned to printer")
  67. on_queue_job_started: bool = Field(default=False, description="Notify when queue job starts printing")
  68. on_queue_job_waiting: bool = Field(default=True, description="Notify when job is waiting for filament or printer")
  69. on_queue_job_skipped: bool = Field(default=True, description="Notify when job is skipped")
  70. on_queue_job_failed: bool = Field(default=True, description="Notify when job fails to start")
  71. on_queue_completed: bool = Field(default=False, description="Notify when all queue jobs finish")
  72. # Quiet hours
  73. quiet_hours_enabled: bool = Field(default=False, description="Enable quiet hours")
  74. quiet_hours_start: str | None = Field(default=None, description="Start time in HH:MM format")
  75. quiet_hours_end: str | None = Field(default=None, description="End time in HH:MM format")
  76. # Daily digest
  77. daily_digest_enabled: bool = Field(default=False, description="Batch notifications into daily digest")
  78. daily_digest_time: str | None = Field(default=None, description="Time to send digest in HH:MM format")
  79. # Printer filter
  80. printer_id: int | None = Field(default=None, description="Specific printer ID or null for all")
  81. @field_validator("quiet_hours_start", "quiet_hours_end", "daily_digest_time")
  82. @classmethod
  83. def validate_time_format(cls, v: str | None) -> str | None:
  84. if v is None:
  85. return v
  86. try:
  87. parts = v.split(":")
  88. if len(parts) != 2:
  89. raise ValueError("Invalid time format")
  90. hour, minute = int(parts[0]), int(parts[1])
  91. if not (0 <= hour <= 23 and 0 <= minute <= 59):
  92. raise ValueError("Invalid time range")
  93. return f"{hour:02d}:{minute:02d}"
  94. except (ValueError, TypeError):
  95. raise ValueError("Time must be in HH:MM format (e.g., 22:00)")
  96. class NotificationProviderCreate(NotificationProviderBase):
  97. """Schema for creating a notification provider."""
  98. pass
  99. class NotificationProviderUpdate(BaseModel):
  100. """Schema for updating a notification provider (all fields optional)."""
  101. name: str | None = Field(default=None, min_length=1, max_length=100)
  102. provider_type: ProviderType | None = None
  103. enabled: bool | None = None
  104. config: dict[str, Any] | None = None
  105. # Event triggers - print lifecycle
  106. on_print_start: bool | None = None
  107. on_print_complete: bool | None = None
  108. on_print_failed: bool | None = None
  109. on_print_stopped: bool | None = None
  110. on_print_progress: bool | None = None
  111. on_print_missing_spool_assignment: bool | None = None
  112. on_billing_charge_failed: bool | None = None
  113. # Event triggers - printer status
  114. on_printer_offline: bool | None = None
  115. on_printer_error: bool | None = None
  116. on_ai_failure_detection: bool | None = None
  117. on_filament_low: bool | None = None
  118. on_maintenance_due: bool | None = None
  119. # Event triggers - AMS environmental alarms (regular AMS)
  120. on_ams_humidity_high: bool | None = None
  121. on_ams_temperature_high: bool | None = None
  122. # Event triggers - AMS-HT environmental alarms
  123. on_ams_ht_humidity_high: bool | None = None
  124. on_ams_ht_temperature_high: bool | None = None
  125. # Event triggers - Home Assistant sensors (#1148)
  126. on_ha_sensor_alert: bool | None = None
  127. # Event triggers - Build plate detection
  128. on_plate_not_empty: bool | None = None
  129. on_plate_clear_required: bool | None = None
  130. # Event triggers - Bed cooled
  131. on_bed_cooled: bool | None = None
  132. # Event triggers - First layer complete
  133. on_first_layer_complete: bool | None = None
  134. # Event triggers - Print queue
  135. on_queue_job_added: bool | None = None
  136. on_queue_job_assigned: bool | None = None
  137. on_queue_job_started: bool | None = None
  138. on_queue_job_waiting: bool | None = None
  139. on_queue_job_skipped: bool | None = None
  140. on_queue_job_failed: bool | None = None
  141. on_queue_completed: bool | None = None
  142. # Quiet hours
  143. quiet_hours_enabled: bool | None = None
  144. quiet_hours_start: str | None = None
  145. quiet_hours_end: str | None = None
  146. # Daily digest
  147. daily_digest_enabled: bool | None = None
  148. daily_digest_time: str | None = None
  149. # Printer filter
  150. printer_id: int | None = None
  151. class NotificationProviderResponse(NotificationProviderBase):
  152. """Schema for notification provider API responses."""
  153. id: int
  154. last_success: datetime | None = None
  155. last_error: str | None = None
  156. last_error_at: datetime | None = None
  157. created_at: datetime
  158. updated_at: datetime
  159. class Config:
  160. from_attributes = True
  161. class NotificationTestRequest(BaseModel):
  162. """Schema for testing notification configuration."""
  163. provider_type: ProviderType
  164. config: dict[str, Any]
  165. class NotificationTestResponse(BaseModel):
  166. """Schema for test notification response."""
  167. success: bool
  168. message: str
  169. # Provider-specific config schemas for documentation/validation reference
  170. class CallMeBotConfig(BaseModel):
  171. """CallMeBot/WhatsApp configuration."""
  172. phone: str = Field(..., description="Phone number with country code (e.g., +1234567890)")
  173. apikey: str = Field(..., description="API key from CallMeBot")
  174. class NtfyConfig(BaseModel):
  175. """ntfy configuration."""
  176. server: str = Field(default="https://ntfy.sh", description="ntfy server URL")
  177. topic: str = Field(..., description="Topic name to publish to")
  178. auth_token: str | None = Field(default=None, description="Optional authentication token")
  179. event_priorities: dict[str, int] | None = Field(
  180. default=None,
  181. description=(
  182. "Per-event priority override. Keys are event names (e.g. 'on_print_failed'); "
  183. "values are ntfy priorities 1-5 (1=min, 2=low, 3=default, 4=high, 5=urgent). "
  184. "Events without an entry use ntfy's server-side default."
  185. ),
  186. )
  187. class PushoverConfig(BaseModel):
  188. """Pushover configuration."""
  189. user_key: str = Field(..., description="Your Pushover user key")
  190. app_token: str = Field(..., description="Your Pushover application token")
  191. priority: int = Field(default=0, ge=-2, le=2, description="Message priority (-2 to 2)")
  192. # Emergency priority (2) only: how often to re-alert and when to stop.
  193. # Pushover requires retry >= 30s and expire <= 10800s (3h).
  194. retry: int = Field(default=60, ge=30, le=10800, description="Emergency re-alert interval in seconds (priority 2)")
  195. expire: int = Field(default=3600, ge=30, le=10800, description="Emergency alert expiry in seconds (priority 2)")
  196. class TelegramConfig(BaseModel):
  197. """Telegram bot configuration."""
  198. bot_token: str = Field(..., description="Bot token from @BotFather")
  199. chat_id: str = Field(..., description="Chat ID to send messages to")
  200. class EmailConfig(BaseModel):
  201. """Email/SMTP configuration."""
  202. smtp_server: str = Field(..., description="SMTP server hostname")
  203. smtp_port: int = Field(default=587, description="SMTP port (587 for TLS, 465 for SSL)")
  204. username: str = Field(..., description="SMTP username/email")
  205. password: str = Field(..., description="SMTP password or app password")
  206. from_email: str = Field(..., description="From email address")
  207. to_email: str = Field(..., description="Recipient email address")
  208. use_tls: bool = Field(default=True, description="Use TLS encryption")
  209. # Notification Log schemas
  210. class NotificationLogResponse(BaseModel):
  211. """Schema for notification log API responses."""
  212. id: int
  213. provider_id: int
  214. provider_name: str | None = None
  215. provider_type: str | None = None
  216. event_type: str
  217. title: str
  218. message: str
  219. success: bool
  220. error_message: str | None = None
  221. printer_id: int | None = None
  222. printer_name: str | None = None
  223. created_at: datetime
  224. class Config:
  225. from_attributes = True
  226. class NotificationLogStats(BaseModel):
  227. """Statistics for notification logs."""
  228. total: int
  229. success_count: int
  230. failure_count: int
  231. by_event_type: dict[str, int]
  232. by_provider: dict[str, int]