settings.py 34 KB

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