settings.py 29 KB

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