notification.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. class NotificationProviderBase(BaseModel):
  14. """Base schema for notification providers."""
  15. name: str = Field(..., min_length=1, max_length=100, description="User-defined name")
  16. provider_type: ProviderType = Field(..., description="Type of notification provider")
  17. enabled: bool = Field(default=True, description="Whether notifications are enabled")
  18. config: dict[str, Any] = Field(..., description="Provider-specific configuration")
  19. # Event triggers - print lifecycle
  20. on_print_start: bool = Field(default=False, description="Notify on print start")
  21. on_print_complete: bool = Field(default=True, description="Notify on print complete")
  22. on_print_failed: bool = Field(default=True, description="Notify on print failed")
  23. on_print_stopped: bool = Field(default=True, description="Notify when print is stopped/cancelled")
  24. on_print_progress: bool = Field(default=False, description="Notify at 25%, 50%, 75% progress")
  25. # Event triggers - printer status
  26. on_printer_offline: bool = Field(default=False, description="Notify when printer goes offline")
  27. on_printer_error: bool = Field(default=False, description="Notify on printer errors (AMS, etc.)")
  28. on_filament_low: bool = Field(default=False, description="Notify when filament is running low")
  29. on_maintenance_due: bool = Field(default=False, description="Notify when maintenance is due")
  30. # Quiet hours
  31. quiet_hours_enabled: bool = Field(default=False, description="Enable quiet hours")
  32. quiet_hours_start: str | None = Field(default=None, description="Start time in HH:MM format")
  33. quiet_hours_end: str | None = Field(default=None, description="End time in HH:MM format")
  34. # Printer filter
  35. printer_id: int | None = Field(default=None, description="Specific printer ID or null for all")
  36. @field_validator("quiet_hours_start", "quiet_hours_end")
  37. @classmethod
  38. def validate_time_format(cls, v: str | None) -> str | None:
  39. if v is None:
  40. return v
  41. try:
  42. parts = v.split(":")
  43. if len(parts) != 2:
  44. raise ValueError("Invalid time format")
  45. hour, minute = int(parts[0]), int(parts[1])
  46. if not (0 <= hour <= 23 and 0 <= minute <= 59):
  47. raise ValueError("Invalid time range")
  48. return f"{hour:02d}:{minute:02d}"
  49. except (ValueError, TypeError):
  50. raise ValueError("Time must be in HH:MM format (e.g., 22:00)")
  51. class NotificationProviderCreate(NotificationProviderBase):
  52. """Schema for creating a notification provider."""
  53. pass
  54. class NotificationProviderUpdate(BaseModel):
  55. """Schema for updating a notification provider (all fields optional)."""
  56. name: str | None = Field(default=None, min_length=1, max_length=100)
  57. provider_type: ProviderType | None = None
  58. enabled: bool | None = None
  59. config: dict[str, Any] | None = None
  60. # Event triggers - print lifecycle
  61. on_print_start: bool | None = None
  62. on_print_complete: bool | None = None
  63. on_print_failed: bool | None = None
  64. on_print_stopped: bool | None = None
  65. on_print_progress: bool | None = None
  66. # Event triggers - printer status
  67. on_printer_offline: bool | None = None
  68. on_printer_error: bool | None = None
  69. on_filament_low: bool | None = None
  70. on_maintenance_due: bool | None = None
  71. # Quiet hours
  72. quiet_hours_enabled: bool | None = None
  73. quiet_hours_start: str | None = None
  74. quiet_hours_end: str | None = None
  75. # Printer filter
  76. printer_id: int | None = None
  77. class NotificationProviderResponse(NotificationProviderBase):
  78. """Schema for notification provider API responses."""
  79. id: int
  80. last_success: datetime | None = None
  81. last_error: str | None = None
  82. last_error_at: datetime | None = None
  83. created_at: datetime
  84. updated_at: datetime
  85. class Config:
  86. from_attributes = True
  87. class NotificationTestRequest(BaseModel):
  88. """Schema for testing notification configuration."""
  89. provider_type: ProviderType
  90. config: dict[str, Any]
  91. class NotificationTestResponse(BaseModel):
  92. """Schema for test notification response."""
  93. success: bool
  94. message: str
  95. # Provider-specific config schemas for documentation/validation reference
  96. class CallMeBotConfig(BaseModel):
  97. """CallMeBot/WhatsApp configuration."""
  98. phone: str = Field(..., description="Phone number with country code (e.g., +1234567890)")
  99. apikey: str = Field(..., description="API key from CallMeBot")
  100. class NtfyConfig(BaseModel):
  101. """ntfy configuration."""
  102. server: str = Field(default="https://ntfy.sh", description="ntfy server URL")
  103. topic: str = Field(..., description="Topic name to publish to")
  104. auth_token: str | None = Field(default=None, description="Optional authentication token")
  105. class PushoverConfig(BaseModel):
  106. """Pushover configuration."""
  107. user_key: str = Field(..., description="Your Pushover user key")
  108. app_token: str = Field(..., description="Your Pushover application token")
  109. priority: int = Field(default=0, ge=-2, le=2, description="Message priority (-2 to 2)")
  110. class TelegramConfig(BaseModel):
  111. """Telegram bot configuration."""
  112. bot_token: str = Field(..., description="Bot token from @BotFather")
  113. chat_id: str = Field(..., description="Chat ID to send messages to")
  114. class EmailConfig(BaseModel):
  115. """Email/SMTP configuration."""
  116. smtp_server: str = Field(..., description="SMTP server hostname")
  117. smtp_port: int = Field(default=587, description="SMTP port (587 for TLS, 465 for SSL)")
  118. username: str = Field(..., description="SMTP username/email")
  119. password: str = Field(..., description="SMTP password or app password")
  120. from_email: str = Field(..., description="From email address")
  121. to_email: str = Field(..., description="Recipient email address")
  122. use_tls: bool = Field(default=True, description="Use TLS encryption")