notification.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. """Pydantic schemas for notification providers."""
  2. from datetime import datetime
  3. from enum import Enum
  4. from typing import Any
  5. from pydantic import BaseModel, Field, field_validator
  6. class ProviderType(str, Enum):
  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. class NotificationProviderBase(BaseModel):
  16. """Base schema for notification providers."""
  17. name: str = Field(..., min_length=1, max_length=100, description="User-defined name")
  18. provider_type: ProviderType = Field(..., description="Type of notification provider")
  19. enabled: bool = Field(default=True, description="Whether notifications are enabled")
  20. config: dict[str, Any] = Field(..., description="Provider-specific configuration")
  21. # Event triggers - print lifecycle
  22. on_print_start: bool = Field(default=False, description="Notify on print start")
  23. on_print_complete: bool = Field(default=True, description="Notify on print complete")
  24. on_print_failed: bool = Field(default=True, description="Notify on print failed")
  25. on_print_stopped: bool = Field(default=True, description="Notify when print is stopped/cancelled")
  26. on_print_progress: bool = Field(default=False, description="Notify at 25%, 50%, 75% progress")
  27. # Event triggers - printer status
  28. on_printer_offline: bool = Field(default=False, description="Notify when printer goes offline")
  29. on_printer_error: bool = Field(default=False, description="Notify on printer errors (AMS, etc.)")
  30. on_filament_low: bool = Field(default=False, description="Notify when filament is running low")
  31. on_maintenance_due: bool = Field(default=False, description="Notify when maintenance is due")
  32. # Event triggers - AMS environmental alarms (regular AMS)
  33. on_ams_humidity_high: bool = Field(default=False, description="Notify when AMS humidity exceeds threshold")
  34. on_ams_temperature_high: bool = Field(default=False, description="Notify when AMS temperature exceeds threshold")
  35. # Event triggers - AMS-HT environmental alarms
  36. on_ams_ht_humidity_high: bool = Field(default=False, description="Notify when AMS-HT humidity exceeds threshold")
  37. on_ams_ht_temperature_high: bool = Field(default=False, description="Notify when AMS-HT temperature exceeds threshold")
  38. # Quiet hours
  39. quiet_hours_enabled: bool = Field(default=False, description="Enable quiet hours")
  40. quiet_hours_start: str | None = Field(default=None, description="Start time in HH:MM format")
  41. quiet_hours_end: str | None = Field(default=None, description="End time in HH:MM format")
  42. # Daily digest
  43. daily_digest_enabled: bool = Field(default=False, description="Batch notifications into daily digest")
  44. daily_digest_time: str | None = Field(default=None, description="Time to send digest in HH:MM format")
  45. # Printer filter
  46. printer_id: int | None = Field(default=None, description="Specific printer ID or null for all")
  47. @field_validator("quiet_hours_start", "quiet_hours_end", "daily_digest_time")
  48. @classmethod
  49. def validate_time_format(cls, v: str | None) -> str | None:
  50. if v is None:
  51. return v
  52. try:
  53. parts = v.split(":")
  54. if len(parts) != 2:
  55. raise ValueError("Invalid time format")
  56. hour, minute = int(parts[0]), int(parts[1])
  57. if not (0 <= hour <= 23 and 0 <= minute <= 59):
  58. raise ValueError("Invalid time range")
  59. return f"{hour:02d}:{minute:02d}"
  60. except (ValueError, TypeError):
  61. raise ValueError("Time must be in HH:MM format (e.g., 22:00)")
  62. class NotificationProviderCreate(NotificationProviderBase):
  63. """Schema for creating a notification provider."""
  64. pass
  65. class NotificationProviderUpdate(BaseModel):
  66. """Schema for updating a notification provider (all fields optional)."""
  67. name: str | None = Field(default=None, min_length=1, max_length=100)
  68. provider_type: ProviderType | None = None
  69. enabled: bool | None = None
  70. config: dict[str, Any] | None = None
  71. # Event triggers - print lifecycle
  72. on_print_start: bool | None = None
  73. on_print_complete: bool | None = None
  74. on_print_failed: bool | None = None
  75. on_print_stopped: bool | None = None
  76. on_print_progress: bool | None = None
  77. # Event triggers - printer status
  78. on_printer_offline: bool | None = None
  79. on_printer_error: bool | None = None
  80. on_filament_low: bool | None = None
  81. on_maintenance_due: bool | None = None
  82. # Event triggers - AMS environmental alarms (regular AMS)
  83. on_ams_humidity_high: bool | None = None
  84. on_ams_temperature_high: bool | None = None
  85. # Event triggers - AMS-HT environmental alarms
  86. on_ams_ht_humidity_high: bool | None = None
  87. on_ams_ht_temperature_high: bool | None = None
  88. # Quiet hours
  89. quiet_hours_enabled: bool | None = None
  90. quiet_hours_start: str | None = None
  91. quiet_hours_end: str | None = None
  92. # Daily digest
  93. daily_digest_enabled: bool | None = None
  94. daily_digest_time: str | None = None
  95. # Printer filter
  96. printer_id: int | None = None
  97. class NotificationProviderResponse(NotificationProviderBase):
  98. """Schema for notification provider API responses."""
  99. id: int
  100. last_success: datetime | None = None
  101. last_error: str | None = None
  102. last_error_at: datetime | None = None
  103. created_at: datetime
  104. updated_at: datetime
  105. class Config:
  106. from_attributes = True
  107. class NotificationTestRequest(BaseModel):
  108. """Schema for testing notification configuration."""
  109. provider_type: ProviderType
  110. config: dict[str, Any]
  111. class NotificationTestResponse(BaseModel):
  112. """Schema for test notification response."""
  113. success: bool
  114. message: str
  115. # Provider-specific config schemas for documentation/validation reference
  116. class CallMeBotConfig(BaseModel):
  117. """CallMeBot/WhatsApp configuration."""
  118. phone: str = Field(..., description="Phone number with country code (e.g., +1234567890)")
  119. apikey: str = Field(..., description="API key from CallMeBot")
  120. class NtfyConfig(BaseModel):
  121. """ntfy configuration."""
  122. server: str = Field(default="https://ntfy.sh", description="ntfy server URL")
  123. topic: str = Field(..., description="Topic name to publish to")
  124. auth_token: str | None = Field(default=None, description="Optional authentication token")
  125. class PushoverConfig(BaseModel):
  126. """Pushover configuration."""
  127. user_key: str = Field(..., description="Your Pushover user key")
  128. app_token: str = Field(..., description="Your Pushover application token")
  129. priority: int = Field(default=0, ge=-2, le=2, description="Message priority (-2 to 2)")
  130. class TelegramConfig(BaseModel):
  131. """Telegram bot configuration."""
  132. bot_token: str = Field(..., description="Bot token from @BotFather")
  133. chat_id: str = Field(..., description="Chat ID to send messages to")
  134. class EmailConfig(BaseModel):
  135. """Email/SMTP configuration."""
  136. smtp_server: str = Field(..., description="SMTP server hostname")
  137. smtp_port: int = Field(default=587, description="SMTP port (587 for TLS, 465 for SSL)")
  138. username: str = Field(..., description="SMTP username/email")
  139. password: str = Field(..., description="SMTP password or app password")
  140. from_email: str = Field(..., description="From email address")
  141. to_email: str = Field(..., description="Recipient email address")
  142. use_tls: bool = Field(default=True, description="Use TLS encryption")
  143. # Notification Log schemas
  144. class NotificationLogResponse(BaseModel):
  145. """Schema for notification log API responses."""
  146. id: int
  147. provider_id: int
  148. provider_name: str | None = None
  149. provider_type: str | None = None
  150. event_type: str
  151. title: str
  152. message: str
  153. success: bool
  154. error_message: str | None = None
  155. printer_id: int | None = None
  156. printer_name: str | None = None
  157. created_at: datetime
  158. class Config:
  159. from_attributes = True
  160. class NotificationLogStats(BaseModel):
  161. """Statistics for notification logs."""
  162. total: int
  163. success_count: int
  164. failure_count: int
  165. by_event_type: dict[str, int]
  166. by_provider: dict[str, int]