notification.py 12 KB

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