settings.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import json
  2. from pydantic import BaseModel, Field, field_validator
  3. class AppSettings(BaseModel):
  4. """Application settings schema."""
  5. auto_archive: bool = Field(default=True, description="Automatically archive prints when completed")
  6. save_thumbnails: bool = Field(default=True, description="Extract and save preview images from 3MF files")
  7. capture_finish_photo: bool = Field(
  8. default=True,
  9. description=(
  10. "Capture photo from printer camera when print completes. Bambuddy records a "
  11. "brief timelapse during the print so the photo can be sourced from the moment "
  12. "before the bed drops; the timelapse file is kept if you enabled timelapse for "
  13. "this print, otherwise it is deleted automatically after the photo is captured."
  14. ),
  15. )
  16. default_filament_cost: float = Field(default=25.0, description="Default filament cost per kg")
  17. currency: str = Field(default="USD", description="Currency for cost tracking")
  18. energy_cost_per_kwh: float = Field(default=0.15, description="Electricity cost per kWh for energy tracking")
  19. energy_tracking_mode: str = Field(
  20. default="total",
  21. description="Energy display mode on stats: 'print' shows sum of per-print energy, 'total' shows lifetime plug consumption",
  22. )
  23. # Spoolman integration
  24. spoolman_enabled: bool = Field(default=False, description="Enable Spoolman integration for filament tracking")
  25. spoolman_url: str = Field(default="", description="Spoolman server URL (e.g., http://localhost:7912)")
  26. spoolman_sync_mode: str = Field(
  27. default="auto", description="Sync mode: 'auto' syncs immediately, 'manual' requires button press"
  28. )
  29. spoolman_disable_weight_sync: bool = Field(
  30. default=False,
  31. description="Disable remaining_weight sync. When enabled, only location is updated for existing spools.",
  32. )
  33. spoolman_report_partial_usage: bool = Field(
  34. default=True,
  35. description="Report Partial Usage for Failed Prints. When a print fails or is cancelled, report the estimated filament used up to that point based on layer progress.",
  36. )
  37. auto_add_unknown_rfid: bool = Field(
  38. default=True,
  39. description="Automatically add spools with unknown RFID tags to inventory. Disable if you pre-create inventory entries manually to avoid duplicates.",
  40. )
  41. disable_filament_warnings: bool = Field(
  42. default=False,
  43. description="Disable insufficient filament warnings when printing or queueing prints",
  44. )
  45. prefer_lowest_filament: bool = Field(
  46. default=False,
  47. description="When multiple AMS spools match, prefer the one with lowest remaining filament",
  48. )
  49. # Updates
  50. check_updates: bool = Field(default=True, description="Automatically check for updates on startup")
  51. check_printer_firmware: bool = Field(default=True, description="Check for printer firmware updates from Bambu Lab")
  52. include_beta_updates: bool = Field(default=False, description="Include beta/prerelease versions in update checks")
  53. # Language
  54. language: str = Field(default="en", description="UI language (en, de, fr, ja, it, pt-BR)")
  55. notification_language: str = Field(default="en", description="Language for push notifications (en, de)")
  56. # Bed cooled notification threshold
  57. bed_cooled_threshold: float = Field(
  58. default=35.0, description="Bed temperature threshold for cooled notification (°C)"
  59. )
  60. # AMS threshold settings for humidity and temperature coloring
  61. ams_humidity_good: int = Field(default=40, description="Humidity threshold for good (green): <= this value")
  62. ams_humidity_fair: int = Field(
  63. default=60, description="Humidity threshold for fair (orange): <= this value, > is red"
  64. )
  65. ams_temp_good: float = Field(default=28.0, description="Temperature threshold for good (blue): <= this value")
  66. ams_temp_fair: float = Field(
  67. default=35.0, description="Temperature threshold for fair (orange): <= this value, > is red"
  68. )
  69. ams_history_retention_days: int = Field(default=30, description="Number of days to keep AMS sensor history data")
  70. printer_sensor_history_retention_days: int = Field(
  71. default=30, description="Number of days to keep printer heater history data (nozzle / bed / chamber)"
  72. )
  73. # Queue auto-drying settings
  74. queue_drying_enabled: bool = Field(
  75. default=False, description="Automatically dry AMS filament between queued prints"
  76. )
  77. queue_drying_block: bool = Field(
  78. default=False,
  79. description="Block queue until drying completes (when disabled, prints take priority over drying)",
  80. )
  81. ambient_drying_enabled: bool = Field(
  82. default=False,
  83. description="Automatically dry AMS filament on idle printers when humidity exceeds threshold, regardless of queue",
  84. )
  85. drying_presets: str = Field(
  86. default="",
  87. description="JSON blob of drying presets per filament type (empty = use built-in defaults)",
  88. )
  89. ams_humidity_thresholds: str = Field(
  90. default="",
  91. description=(
  92. "JSON blob of per-filament-type humidity trigger thresholds for auto-drying and alarms. "
  93. 'Shape: {"default": int, "PLA": int, "ASA": int, ...}. '
  94. "Empty = fall back to ams_humidity_fair for all types."
  95. ),
  96. )
  97. # Auto-print G-code injection (#422)
  98. gcode_snippets: str = Field(
  99. default="",
  100. description="JSON: per-model G-code injection snippets {model: {start_gcode, end_gcode}}",
  101. )
  102. # Scheduled local backup (#884)
  103. local_backup_enabled: bool = Field(default=False, description="Enable scheduled local backups")
  104. local_backup_schedule: str = Field(default="daily", description="Backup frequency: hourly, daily, weekly")
  105. local_backup_time: str = Field(default="03:00", description="Time of day for daily/weekly backups (HH:MM, 24h)")
  106. local_backup_retention: int = Field(default=5, description="Number of backup files to keep (1-100)")
  107. local_backup_path: str = Field(default="", description="Backup output directory (empty = DATA_DIR/backups)")
  108. # Print modal settings
  109. per_printer_mapping_expanded: bool = Field(
  110. default=False, description="Expand custom filament mapping by default in print modal"
  111. )
  112. # Date/time display format
  113. date_format: str = Field(default="system", description="Date format: system, us, eu, iso")
  114. time_format: str = Field(default="system", description="Time format: system, 12h, 24h")
  115. # Default printer for operations
  116. default_printer_id: int | None = Field(default=None, description="Default printer ID for uploads, reprints, etc.")
  117. # Virtual Printer
  118. virtual_printer_enabled: bool = Field(default=False, description="Enable virtual printer for slicer uploads")
  119. virtual_printer_access_code: str = Field(default="", description="Access code for virtual printer authentication")
  120. virtual_printer_mode: str = Field(
  121. default="archive",
  122. description="Mode: 'archive' (archive now), 'review' (pending review), 'queue' (add to print queue), or 'proxy' (relay to real printer)",
  123. )
  124. virtual_printer_archive_name_source: str = Field(
  125. default="metadata",
  126. description="Source for the archive's display name on virtual-printer uploads: 'metadata' uses the 3MF's embedded print_name (default, matches Bambu's behavior), 'filename' uses the filename Bambu Studio sent over FTP (lets users rename via the slicer's 'send to printer' dialog).",
  127. )
  128. # Dark mode theme settings
  129. dark_style: str = Field(default="vibrant", description="Dark mode style: classic, glow, vibrant")
  130. dark_background: str = Field(
  131. default="cool", description="Dark mode background: neutral, warm, cool, oled, slate, forest"
  132. )
  133. dark_accent: str = Field(default="green", description="Dark mode accent: green, teal, blue, orange, purple, red")
  134. # Light mode theme settings
  135. light_style: str = Field(default="classic", description="Light mode style: classic, glow, vibrant")
  136. light_background: str = Field(default="neutral", description="Light mode background: neutral, warm, cool")
  137. light_accent: str = Field(default="green", description="Light mode accent: green, teal, blue, orange, purple, red")
  138. # FTP retry settings for unreliable WiFi connections
  139. ftp_retry_enabled: bool = Field(default=True, description="Enable automatic retry for FTP operations")
  140. ftp_retry_count: int = Field(default=3, description="Number of retry attempts for FTP operations (1-10)")
  141. ftp_retry_delay: int = Field(default=2, description="Seconds to wait between FTP retry attempts (1-30)")
  142. ftp_timeout: int = Field(default=30, description="FTP connection timeout in seconds (10-300)")
  143. # MQTT Relay settings for publishing events to external broker
  144. mqtt_enabled: bool = Field(default=False, description="Enable MQTT event publishing to external broker")
  145. mqtt_broker: str = Field(default="", description="MQTT broker hostname or IP address")
  146. mqtt_port: int = Field(default=1883, description="MQTT broker port (default 1883, TLS typically 8883)")
  147. mqtt_username: str = Field(default="", description="MQTT username for authentication (optional)")
  148. mqtt_password: str = Field(default="", description="MQTT password for authentication (optional)")
  149. mqtt_topic_prefix: str = Field(default="bambuddy", description="Topic prefix for all published messages")
  150. mqtt_use_tls: bool = Field(default=False, description="Use TLS/SSL encryption for MQTT connection")
  151. # External URL for notifications
  152. external_url: str = Field(
  153. default="", description="External URL where Bambuddy is accessible (for notification images)"
  154. )
  155. # Home Assistant integration for smart plug control
  156. ha_enabled: bool = Field(default=False, description="Enable Home Assistant integration for smart plug control")
  157. ha_url: str = Field(default="", description="Home Assistant URL (e.g., http://192.168.1.100:8123)")
  158. ha_token: str = Field(default="", description="Home Assistant Long-Lived Access Token")
  159. ha_url_from_env: bool = Field(default=False, description="Whether HA URL is set via HA_URL environment variable")
  160. ha_token_from_env: bool = Field(
  161. default=False, description="Whether HA token is set via HA_TOKEN environment variable"
  162. )
  163. ha_env_managed: bool = Field(
  164. default=False, description="Whether HA integration is fully managed by environment variables"
  165. )
  166. # File Manager / Library settings
  167. library_archive_mode: str = Field(
  168. default="ask",
  169. description="When printing from File Manager, create archive entry: 'always', 'never', or 'ask'",
  170. )
  171. library_disk_warning_gb: float = Field(
  172. default=5.0,
  173. description="Show warning when free disk space falls below this threshold (GB)",
  174. )
  175. # Camera view settings
  176. camera_view_mode: str = Field(
  177. default="window",
  178. description="Camera view mode: 'window' opens in new browser window, 'embedded' shows overlay on main screen",
  179. )
  180. # Preferred slicer application (server-side / API sidecar slicer)
  181. preferred_slicer: str = Field(
  182. default="bambu_studio",
  183. description="Slicer used for the server-side API / sidecar: 'bambu_studio' or 'orcaslicer'",
  184. )
  185. # "Open in Slicer" desktop URI handler — independent of the API slicer so
  186. # a user can slice via the Bambu Studio sidecar but open files locally in
  187. # OrcaSlicer, or vice versa (#1329). None falls back to ``preferred_slicer``
  188. # so existing installs behave identically until someone changes it.
  189. open_in_slicer: str | None = Field(
  190. default=None,
  191. description=(
  192. "Desktop slicer for the 'Open in Slicer' button: 'bambu_studio' or "
  193. "'orcaslicer'. None inherits from preferred_slicer."
  194. ),
  195. )
  196. # Slicer dispatch mode: when True, "Slice" actions open the in-app
  197. # SliceModal and call the slicer-API sidecar. When False (default), they
  198. # hand off to the user's local desktop slicer via URI scheme — preserving
  199. # the original Bambuddy behavior for users who don't run a sidecar.
  200. use_slicer_api: bool = Field(
  201. default=False,
  202. description="Use the slicer-API sidecar for slicing instead of the desktop slicer URI scheme",
  203. )
  204. # Slicer-API sidecar base URLs. Per-installation, configured via the
  205. # Settings UI (the "Slicer" card). Empty string means "fall back to the
  206. # SLICER_API_URL / BAMBU_STUDIO_API_URL env vars" — which themselves
  207. # default to the docker-compose ports in core/config.py.
  208. orcaslicer_api_url: str = Field(
  209. default="",
  210. description="OrcaSlicer sidecar URL (e.g. http://localhost:3003). Empty falls back to the SLICER_API_URL env var.",
  211. )
  212. bambu_studio_api_url: str = Field(
  213. default="",
  214. description="BambuStudio sidecar URL (e.g. http://localhost:3001). Empty falls back to the BAMBU_STUDIO_API_URL env var.",
  215. )
  216. # Prometheus metrics endpoint
  217. prometheus_enabled: bool = Field(default=False, description="Enable Prometheus metrics endpoint at /metrics")
  218. prometheus_token: str = Field(
  219. default="", description="Bearer token for Prometheus metrics authentication (optional)"
  220. )
  221. # Inventory low stock threshold
  222. low_stock_threshold: float = Field(
  223. default=20.0,
  224. ge=0.1,
  225. le=99.9,
  226. description="Low stock threshold percentage (%) for inventory filtering and display",
  227. )
  228. # Session policy (#1706) — admin-set ceiling for user session lifetime.
  229. # Default 24h preserves the M-2 audit reduction from 7 days. Max 720h
  230. # (30 days) bounds blast radius if an admin chooses a long session.
  231. session_max_hours: int = Field(
  232. default=24,
  233. ge=1,
  234. le=720,
  235. description=(
  236. "Maximum session lifetime in hours for user logins (default 24, max 720). "
  237. "Applies to new logins only; already-issued tokens keep their original expiry. "
  238. "Longer sessions reduce automatic logout protection."
  239. ),
  240. )
  241. # User email notifications (requires Advanced Authentication)
  242. user_notifications_enabled: bool = Field(
  243. default=True,
  244. description="Enable user email notifications for print job events (requires Advanced Authentication)",
  245. )
  246. # Default print options
  247. default_bed_levelling: bool = Field(default=True, description="Default bed levelling option for new prints")
  248. default_flow_cali: bool = Field(default=False, description="Default flow calibration option for new prints")
  249. default_vibration_cali: bool = Field(
  250. default=True, description="Default vibration calibration option for new prints"
  251. )
  252. default_layer_inspect: bool = Field(
  253. default=False, description="Default first layer inspection option for new prints"
  254. )
  255. default_timelapse: bool = Field(default=False, description="Default timelapse option for new prints")
  256. default_nozzle_offset_cali: bool = Field(
  257. default=True,
  258. description="Default nozzle offset calibration option for new prints (dual-nozzle printers only)",
  259. )
  260. # Staggered batch start for multi-printer jobs
  261. stagger_group_size: int = Field(
  262. default=2, ge=1, le=50, description="Number of printers to start simultaneously in staggered mode"
  263. )
  264. stagger_interval_minutes: int = Field(
  265. default=5, ge=1, le=60, description="Minutes between staggered printer groups"
  266. )
  267. # Plate-clear confirmation for queue scheduling
  268. require_plate_clear: bool = Field(
  269. default=False,
  270. description="Require per-printer plate-clear confirmation before starting queued prints on finished printers",
  271. )
  272. queue_shortest_first: bool = Field(
  273. default=False,
  274. description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
  275. )
  276. # User-configurable presets for the printer-card temperature / fan-speed
  277. # popovers. Each is a JSON array of exactly 3 ints (the "Off" button is
  278. # rendered separately and is not configurable). Empty string = use built-in
  279. # defaults. Validators on AppSettingsUpdate enforce the shape on writes.
  280. nozzle_temp_presets: str = Field(
  281. default="",
  282. description="JSON array of 3 nozzle-temperature preset values in C (0-320). Empty = use defaults [120, 220, 260]",
  283. )
  284. bed_temp_presets: str = Field(
  285. default="",
  286. description="JSON array of 3 bed-temperature preset values in C (0-140). Empty = use defaults [55, 75, 90]",
  287. )
  288. chamber_temp_presets: str = Field(
  289. default="",
  290. description="JSON array of 3 chamber-temperature preset values in C (0-60). Empty = use defaults [35, 45, 60]",
  291. )
  292. fan_speed_presets: str = Field(
  293. default="",
  294. description="JSON array of 3 fan-speed preset values in % (0-100). Empty = use defaults [50, 75, 100]",
  295. )
  296. # LDAP authentication (#794)
  297. ldap_enabled: bool = Field(default=False, description="Enable LDAP authentication")
  298. ldap_server_url: str = Field(default="", description="LDAP server URL (e.g., ldap://ldap.example.com:389)")
  299. ldap_bind_dn: str = Field(default="", description="Bind DN for LDAP searches (e.g., cn=admin,dc=example,dc=com)")
  300. ldap_bind_password: str = Field(default="", description="Bind password for LDAP searches")
  301. ldap_search_base: str = Field(default="", description="Search base DN (e.g., ou=users,dc=example,dc=com)")
  302. ldap_user_filter: str = Field(
  303. default="(sAMAccountName={username})",
  304. description="LDAP user search filter. {username} is replaced with the login username",
  305. )
  306. ldap_security: str = Field(default="starttls", description="LDAP security: 'starttls' or 'ldaps'")
  307. ldap_group_mapping: str = Field(
  308. default="",
  309. description="JSON: LDAP group to BamBuddy group mapping {ldap_group_dn: bambuddy_group_name}",
  310. )
  311. ldap_auto_provision: bool = Field(
  312. default=False,
  313. description="Auto-create BamBuddy user on first successful LDAP login",
  314. )
  315. ldap_default_group: str = Field(
  316. default="",
  317. description="Fallback BamBuddy group name assigned when an LDAP user authenticates but has no mapped groups. Empty = no fallback.",
  318. )
  319. # Obico AI failure detection (#172)
  320. obico_enabled: bool = Field(default=False, description="Enable Obico AI print failure detection")
  321. obico_ml_url: str = Field(
  322. default="",
  323. description="Self-hosted Obico ML API base URL (e.g., http://192.168.1.10:3333)",
  324. )
  325. obico_sensitivity: str = Field(
  326. default="medium",
  327. description="Detection sensitivity: 'low', 'medium', or 'high' (adjusts LOW/HIGH thresholds)",
  328. )
  329. obico_action: str = Field(
  330. default="notify",
  331. description="Action on detected failure: 'notify', 'pause', or 'pause_and_off'",
  332. )
  333. obico_poll_interval: int = Field(
  334. default=10,
  335. ge=5,
  336. le=120,
  337. description="Seconds between detection checks while a print is running",
  338. )
  339. obico_enabled_printers: str = Field(
  340. default="",
  341. description="JSON array of printer IDs to monitor (empty = all connected printers)",
  342. )
  343. # Inventory forecasting
  344. forecast_global_lead_time_days: int = Field(
  345. default=0,
  346. ge=0,
  347. description="Global lead time floor (days) used in reorder point calculation for all SKUs",
  348. )
  349. # Default sidebar order (admin-set for all users)
  350. default_sidebar_order: str = Field(
  351. default="",
  352. description="JSON object with 'order' key containing array of sidebar item IDs (empty = no default)",
  353. )
  354. class AppSettingsUpdate(BaseModel):
  355. """Schema for updating settings (all fields optional)."""
  356. auto_archive: bool | None = None
  357. save_thumbnails: bool | None = None
  358. capture_finish_photo: bool | None = None
  359. default_filament_cost: float | None = None
  360. currency: str | None = None
  361. energy_cost_per_kwh: float | None = None
  362. energy_tracking_mode: str | None = None
  363. spoolman_enabled: bool | None = None
  364. spoolman_url: str | None = None
  365. spoolman_sync_mode: str | None = None
  366. spoolman_disable_weight_sync: bool | None = None
  367. spoolman_report_partial_usage: bool | None = None
  368. auto_add_unknown_rfid: bool | None = None
  369. disable_filament_warnings: bool | None = None
  370. prefer_lowest_filament: bool | None = None
  371. check_updates: bool | None = None
  372. check_printer_firmware: bool | None = None
  373. include_beta_updates: bool | None = None
  374. language: str | None = None
  375. notification_language: str | None = None
  376. bed_cooled_threshold: float | None = None
  377. ams_humidity_good: int | None = None
  378. ams_humidity_fair: int | None = None
  379. ams_temp_good: float | None = None
  380. ams_temp_fair: float | None = None
  381. ams_history_retention_days: int | None = None
  382. printer_sensor_history_retention_days: int | None = None
  383. queue_drying_enabled: bool | None = None
  384. queue_drying_block: bool | None = None
  385. ambient_drying_enabled: bool | None = None
  386. drying_presets: str | None = None
  387. ams_humidity_thresholds: str | None = None
  388. per_printer_mapping_expanded: bool | None = None
  389. date_format: str | None = None
  390. time_format: str | None = None
  391. default_printer_id: int | None = None
  392. virtual_printer_enabled: bool | None = None
  393. virtual_printer_access_code: str | None = None
  394. virtual_printer_mode: str | None = None
  395. virtual_printer_archive_name_source: str | None = None
  396. dark_style: str | None = None
  397. dark_background: str | None = None
  398. dark_accent: str | None = None
  399. light_style: str | None = None
  400. light_background: str | None = None
  401. light_accent: str | None = None
  402. ftp_retry_enabled: bool | None = None
  403. ftp_retry_count: int | None = None
  404. ftp_retry_delay: int | None = None
  405. ftp_timeout: int | None = None
  406. mqtt_enabled: bool | None = None
  407. mqtt_broker: str | None = None
  408. mqtt_port: int | None = None
  409. mqtt_username: str | None = None
  410. mqtt_password: str | None = None
  411. mqtt_topic_prefix: str | None = None
  412. mqtt_use_tls: bool | None = None
  413. external_url: str | None = None
  414. ha_enabled: bool | None = None
  415. ha_url: str | None = None
  416. ha_token: str | None = None
  417. library_archive_mode: str | None = None
  418. library_disk_warning_gb: float | None = None
  419. camera_view_mode: str | None = None
  420. preferred_slicer: str | None = None
  421. open_in_slicer: str | None = None
  422. use_slicer_api: bool | None = None
  423. orcaslicer_api_url: str | None = None
  424. bambu_studio_api_url: str | None = None
  425. prometheus_enabled: bool | None = None
  426. prometheus_token: str | None = None
  427. low_stock_threshold: float | None = Field(default=None, ge=0.1, le=99.9)
  428. session_max_hours: int | None = Field(default=None, ge=1, le=720)
  429. user_notifications_enabled: bool | None = None
  430. default_bed_levelling: bool | None = None
  431. default_flow_cali: bool | None = None
  432. default_vibration_cali: bool | None = None
  433. default_layer_inspect: bool | None = None
  434. default_timelapse: bool | None = None
  435. default_nozzle_offset_cali: bool | None = None
  436. stagger_group_size: int | None = Field(default=None, ge=1, le=50)
  437. stagger_interval_minutes: int | None = Field(default=None, ge=1, le=60)
  438. require_plate_clear: bool | None = None
  439. queue_shortest_first: bool | None = None
  440. nozzle_temp_presets: str | None = None
  441. bed_temp_presets: str | None = None
  442. chamber_temp_presets: str | None = None
  443. fan_speed_presets: str | None = None
  444. gcode_snippets: str | None = None
  445. local_backup_enabled: bool | None = None
  446. local_backup_schedule: str | None = None
  447. local_backup_time: str | None = None
  448. local_backup_retention: int | None = None
  449. local_backup_path: str | None = None
  450. ldap_enabled: bool | None = None
  451. ldap_server_url: str | None = None
  452. ldap_bind_dn: str | None = None
  453. ldap_bind_password: str | None = None
  454. ldap_search_base: str | None = None
  455. ldap_user_filter: str | None = None
  456. ldap_security: str | None = None
  457. ldap_group_mapping: str | None = None
  458. ldap_auto_provision: bool | None = None
  459. ldap_default_group: str | None = None
  460. obico_enabled: bool | None = None
  461. obico_ml_url: str | None = None
  462. obico_sensitivity: str | None = None
  463. obico_action: str | None = None
  464. obico_poll_interval: int | None = Field(default=None, ge=5, le=120)
  465. obico_enabled_printers: str | None = None
  466. default_sidebar_order: str | None = None
  467. forecast_global_lead_time_days: int | None = Field(default=None, ge=0)
  468. @field_validator("gcode_snippets")
  469. @classmethod
  470. def validate_gcode_snippets(cls, v: str | None) -> str | None:
  471. if v is None or v == "":
  472. return v
  473. try:
  474. parsed = json.loads(v)
  475. except json.JSONDecodeError:
  476. raise ValueError("gcode_snippets must be valid JSON or empty")
  477. if not isinstance(parsed, dict):
  478. raise ValueError("gcode_snippets must be a JSON object keyed by printer model")
  479. return v
  480. @field_validator("ldap_group_mapping")
  481. @classmethod
  482. def validate_ldap_group_mapping(cls, v: str | None) -> str | None:
  483. if v is None or v == "":
  484. return v
  485. try:
  486. parsed = json.loads(v)
  487. except json.JSONDecodeError:
  488. raise ValueError("ldap_group_mapping must be valid JSON or empty")
  489. if not isinstance(parsed, dict):
  490. raise ValueError("ldap_group_mapping must be a JSON object mapping LDAP group DNs to BamBuddy group names")
  491. return v
  492. @field_validator("obico_enabled_printers")
  493. @classmethod
  494. def validate_obico_enabled_printers(cls, v: str | None) -> str | None:
  495. if v is None or v == "":
  496. return v
  497. try:
  498. parsed = json.loads(v)
  499. except json.JSONDecodeError:
  500. raise ValueError("obico_enabled_printers must be valid JSON or empty")
  501. if not isinstance(parsed, list) or not all(isinstance(item, int) for item in parsed):
  502. raise ValueError("obico_enabled_printers must be a JSON array of printer IDs (integers)")
  503. return v
  504. @staticmethod
  505. def _validate_preset_triple(v: str | None, field_name: str, lo: int, hi: int) -> str | None:
  506. """Validate a JSON array of exactly 3 ints in [lo, hi]. Empty = defaults."""
  507. if v is None or v == "":
  508. return v
  509. try:
  510. parsed = json.loads(v)
  511. except json.JSONDecodeError:
  512. raise ValueError(f"{field_name} must be valid JSON or empty")
  513. if not isinstance(parsed, list) or len(parsed) != 3:
  514. raise ValueError(f"{field_name} must be a JSON array of exactly 3 integers")
  515. if not all(isinstance(item, int) and not isinstance(item, bool) for item in parsed):
  516. raise ValueError(f"{field_name} entries must all be integers")
  517. if not all(lo <= item <= hi for item in parsed):
  518. raise ValueError(f"{field_name} entries must each be in [{lo}, {hi}]")
  519. return v
  520. @field_validator("nozzle_temp_presets")
  521. @classmethod
  522. def validate_nozzle_temp_presets(cls, v: str | None) -> str | None:
  523. return cls._validate_preset_triple(v, "nozzle_temp_presets", 0, 320)
  524. @field_validator("bed_temp_presets")
  525. @classmethod
  526. def validate_bed_temp_presets(cls, v: str | None) -> str | None:
  527. return cls._validate_preset_triple(v, "bed_temp_presets", 0, 140)
  528. @field_validator("chamber_temp_presets")
  529. @classmethod
  530. def validate_chamber_temp_presets(cls, v: str | None) -> str | None:
  531. return cls._validate_preset_triple(v, "chamber_temp_presets", 0, 60)
  532. @field_validator("fan_speed_presets")
  533. @classmethod
  534. def validate_fan_speed_presets(cls, v: str | None) -> str | None:
  535. return cls._validate_preset_triple(v, "fan_speed_presets", 0, 100)
  536. @field_validator("obico_sensitivity")
  537. @classmethod
  538. def validate_obico_sensitivity(cls, v: str | None) -> str | None:
  539. if v is None:
  540. return v
  541. if v not in ("low", "medium", "high"):
  542. raise ValueError("obico_sensitivity must be 'low', 'medium', or 'high'")
  543. return v
  544. @field_validator("obico_action")
  545. @classmethod
  546. def validate_obico_action(cls, v: str | None) -> str | None:
  547. if v is None:
  548. return v
  549. if v not in ("notify", "pause", "pause_and_off"):
  550. raise ValueError("obico_action must be 'notify', 'pause', or 'pause_and_off'")
  551. return v
  552. @field_validator("default_sidebar_order")
  553. @classmethod
  554. def validate_default_sidebar_order(cls, v: str | None) -> str | None:
  555. if v is None or v == "":
  556. return v
  557. try:
  558. parsed = json.loads(v)
  559. except json.JSONDecodeError:
  560. raise ValueError("default_sidebar_order must be valid JSON or empty")
  561. if isinstance(parsed, dict):
  562. order = parsed.get("order")
  563. hidden_system_item_ids = parsed.get("hiddenSystemItemIds", [])
  564. if not isinstance(hidden_system_item_ids, list) or not all(
  565. isinstance(item, str) for item in hidden_system_item_ids
  566. ):
  567. raise ValueError("sidebar hidden system item IDs must be an array of strings")
  568. elif isinstance(parsed, list):
  569. order = parsed
  570. else:
  571. raise ValueError("default_sidebar_order must be a JSON object with 'order' key or a JSON array")
  572. if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
  573. raise ValueError("sidebar order must be an array of strings")
  574. return v