notifications.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """API routes for notification providers."""
  2. import json
  3. import logging
  4. from fastapi import APIRouter, Depends, HTTPException
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.database import get_db
  8. from backend.app.models.notification import NotificationProvider
  9. from backend.app.schemas.notification import (
  10. NotificationProviderCreate,
  11. NotificationProviderResponse,
  12. NotificationProviderUpdate,
  13. NotificationTestRequest,
  14. NotificationTestResponse,
  15. )
  16. from backend.app.services.notification_service import notification_service
  17. logger = logging.getLogger(__name__)
  18. router = APIRouter(prefix="/notifications", tags=["notifications"])
  19. def _provider_to_dict(provider: NotificationProvider) -> dict:
  20. """Convert a NotificationProvider model to a response dictionary."""
  21. return {
  22. "id": provider.id,
  23. "name": provider.name,
  24. "provider_type": provider.provider_type,
  25. "enabled": provider.enabled,
  26. "config": json.loads(provider.config) if isinstance(provider.config, str) else provider.config,
  27. # Print lifecycle events
  28. "on_print_start": provider.on_print_start,
  29. "on_print_complete": provider.on_print_complete,
  30. "on_print_failed": provider.on_print_failed,
  31. "on_print_progress": provider.on_print_progress,
  32. # Printer status events
  33. "on_printer_offline": provider.on_printer_offline,
  34. "on_printer_error": provider.on_printer_error,
  35. "on_filament_low": provider.on_filament_low,
  36. # Quiet hours
  37. "quiet_hours_enabled": provider.quiet_hours_enabled,
  38. "quiet_hours_start": provider.quiet_hours_start,
  39. "quiet_hours_end": provider.quiet_hours_end,
  40. # Printer filter
  41. "printer_id": provider.printer_id,
  42. # Status tracking
  43. "last_success": provider.last_success,
  44. "last_error": provider.last_error,
  45. "last_error_at": provider.last_error_at,
  46. # Timestamps
  47. "created_at": provider.created_at,
  48. "updated_at": provider.updated_at,
  49. }
  50. @router.get("/", response_model=list[NotificationProviderResponse])
  51. async def list_notification_providers(db: AsyncSession = Depends(get_db)):
  52. """List all notification providers."""
  53. result = await db.execute(
  54. select(NotificationProvider).order_by(NotificationProvider.created_at.desc())
  55. )
  56. providers = result.scalars().all()
  57. return [_provider_to_dict(provider) for provider in providers]
  58. @router.post("/", response_model=NotificationProviderResponse)
  59. async def create_notification_provider(
  60. provider_data: NotificationProviderCreate,
  61. db: AsyncSession = Depends(get_db),
  62. ):
  63. """Create a new notification provider."""
  64. provider = NotificationProvider(
  65. name=provider_data.name,
  66. provider_type=provider_data.provider_type.value,
  67. enabled=provider_data.enabled,
  68. config=json.dumps(provider_data.config),
  69. # Print lifecycle events
  70. on_print_start=provider_data.on_print_start,
  71. on_print_complete=provider_data.on_print_complete,
  72. on_print_failed=provider_data.on_print_failed,
  73. on_print_progress=provider_data.on_print_progress,
  74. # Printer status events
  75. on_printer_offline=provider_data.on_printer_offline,
  76. on_printer_error=provider_data.on_printer_error,
  77. on_filament_low=provider_data.on_filament_low,
  78. # Quiet hours
  79. quiet_hours_enabled=provider_data.quiet_hours_enabled,
  80. quiet_hours_start=provider_data.quiet_hours_start,
  81. quiet_hours_end=provider_data.quiet_hours_end,
  82. # Printer filter
  83. printer_id=provider_data.printer_id,
  84. )
  85. db.add(provider)
  86. await db.commit()
  87. await db.refresh(provider)
  88. logger.info(f"Created notification provider: {provider.name} ({provider.provider_type})")
  89. return _provider_to_dict(provider)
  90. @router.get("/{provider_id}", response_model=NotificationProviderResponse)
  91. async def get_notification_provider(
  92. provider_id: int,
  93. db: AsyncSession = Depends(get_db),
  94. ):
  95. """Get a specific notification provider."""
  96. result = await db.execute(
  97. select(NotificationProvider).where(NotificationProvider.id == provider_id)
  98. )
  99. provider = result.scalar_one_or_none()
  100. if not provider:
  101. raise HTTPException(status_code=404, detail="Notification provider not found")
  102. return _provider_to_dict(provider)
  103. @router.patch("/{provider_id}", response_model=NotificationProviderResponse)
  104. async def update_notification_provider(
  105. provider_id: int,
  106. update_data: NotificationProviderUpdate,
  107. db: AsyncSession = Depends(get_db),
  108. ):
  109. """Update a notification provider."""
  110. result = await db.execute(
  111. select(NotificationProvider).where(NotificationProvider.id == provider_id)
  112. )
  113. provider = result.scalar_one_or_none()
  114. if not provider:
  115. raise HTTPException(status_code=404, detail="Notification provider not found")
  116. # Update only provided fields
  117. update_dict = update_data.model_dump(exclude_unset=True)
  118. for key, value in update_dict.items():
  119. if key == "config" and value is not None:
  120. setattr(provider, key, json.dumps(value))
  121. elif key == "provider_type" and value is not None:
  122. setattr(provider, key, value.value)
  123. else:
  124. setattr(provider, key, value)
  125. await db.commit()
  126. await db.refresh(provider)
  127. logger.info(f"Updated notification provider: {provider.name}")
  128. return _provider_to_dict(provider)
  129. @router.delete("/{provider_id}")
  130. async def delete_notification_provider(
  131. provider_id: int,
  132. db: AsyncSession = Depends(get_db),
  133. ):
  134. """Delete a notification provider."""
  135. result = await db.execute(
  136. select(NotificationProvider).where(NotificationProvider.id == provider_id)
  137. )
  138. provider = result.scalar_one_or_none()
  139. if not provider:
  140. raise HTTPException(status_code=404, detail="Notification provider not found")
  141. name = provider.name
  142. await db.delete(provider)
  143. await db.commit()
  144. logger.info(f"Deleted notification provider: {name}")
  145. return {"message": f"Notification provider '{name}' deleted"}
  146. @router.post("/{provider_id}/test", response_model=NotificationTestResponse)
  147. async def test_notification_provider(
  148. provider_id: int,
  149. db: AsyncSession = Depends(get_db),
  150. ):
  151. """Send a test notification using an existing provider."""
  152. result = await db.execute(
  153. select(NotificationProvider).where(NotificationProvider.id == provider_id)
  154. )
  155. provider = result.scalar_one_or_none()
  156. if not provider:
  157. raise HTTPException(status_code=404, detail="Notification provider not found")
  158. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  159. success, message = await notification_service.send_test_notification(
  160. provider.provider_type, config
  161. )
  162. # Update provider status
  163. if success:
  164. from datetime import datetime
  165. provider.last_success = datetime.utcnow()
  166. else:
  167. from datetime import datetime
  168. provider.last_error = message
  169. provider.last_error_at = datetime.utcnow()
  170. await db.commit()
  171. return NotificationTestResponse(success=success, message=message)
  172. @router.post("/test-config", response_model=NotificationTestResponse)
  173. async def test_notification_config(
  174. test_request: NotificationTestRequest,
  175. ):
  176. """Test notification configuration before saving."""
  177. success, message = await notification_service.send_test_notification(
  178. test_request.provider_type.value, test_request.config
  179. )
  180. return NotificationTestResponse(success=success, message=message)