settings.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. import json
  2. import re
  3. from pydantic import BaseModel, Field, ValidationInfo, field_validator
  4. from backend.app.schemas.print_queue import TriState
  5. from backend.app.utils.printer_models import MAX_CHAMBER_TEMP_C
  6. # Outbound service URLs validated on save, so a bad value is rejected at
  7. # configuration time with a clear message rather than failing opaquely at
  8. # request time. Every one of these services is commonly self-hosted on the same
  9. # host or LAN as Bambuddy, so the LAN-service policy applies: loopback and
  10. # RFC-1918 stay permitted, while cloud-metadata endpoints, numeric-encoded IPs,
  11. # IPv4-mapped IPv6 and non-HTTP schemes are rejected. See
  12. # ``_url_safety.assert_safe_lan_service_url``.
  13. #
  14. # Module-level rather than a class attribute so the CI backstop in
  15. # tests/unit/test_outbound_url_ssrf_guards.py can import the real list and
  16. # cannot drift from it. Any new outbound-URL setting belongs here (or, if it
  17. # must be reachable on the public internet, on the stricter OIDC guard).
  18. LAN_SERVICE_URL_SETTINGS = ("ha_url", "obico_ml_url", "orcaslicer_api_url", "bambu_studio_api_url")
  19. # ``docker_compose_dir`` is unusual among the string settings: it is not
  20. # consumed by Bambuddy at all, it is interpolated into a shell command that
  21. # the Settings page invites the user to copy and paste into a root-capable
  22. # terminal (#2664). A value like ``/opt/bambuddy; rm -rf /`` would render as a
  23. # perfectly plausible-looking update command, so anyone with settings:update
  24. # could hand every admin a destructive one-liner to run. Restricting the field
  25. # to characters that occur in real paths removes that entirely; the frontend
  26. # double-quotes the value when it contains a space, which is safe precisely
  27. # because quotes, ``$`` and backticks cannot survive this pattern.
  28. _COMPOSE_DIR_ALLOWED = re.compile(r"^[\w \-./\\:~]+$", re.UNICODE)
  29. _COMPOSE_DIR_MAX_LEN = 512
  30. class AppSettings(BaseModel):
  31. """Application settings schema."""
  32. auto_archive: bool = Field(default=True, description="Automatically archive prints when completed")
  33. save_thumbnails: bool = Field(default=True, description="Extract and save preview images from 3MF files")
  34. capture_finish_photo: bool = Field(
  35. default=True,
  36. description=(
  37. "Capture photo from printer camera when print completes. Bambuddy records a "
  38. "brief timelapse during the print so the photo can be sourced from the moment "
  39. "before the bed drops; the timelapse file is kept if you enabled timelapse for "
  40. "this print, otherwise it is deleted automatically after the photo is captured."
  41. ),
  42. )
  43. finish_photo_restore_plate: bool = Field(
  44. default=True,
  45. description=(
  46. "Raise the build plate back into camera framing before taking the finish photo. "
  47. "Bambu's end G-code drops the plate ~100mm as the last thing it does, leaving the "
  48. "finished print far below the camera's natural framing. Bambuddy moves it back to "
  49. "just above the last printed layer, takes the photo, then lowers it again. Skipped "
  50. "when the print height is unknown or another job is queued for the printer."
  51. ),
  52. )
  53. default_filament_cost: float = Field(default=25.0, description="Default filament cost per kg")
  54. currency: str = Field(default="USD", description="Currency for cost tracking")
  55. energy_cost_per_kwh: float = Field(default=0.15, description="Electricity cost per kWh for energy tracking")
  56. energy_tracking_mode: str = Field(
  57. default="total",
  58. description="Energy display mode on stats: 'print' shows sum of per-print energy, 'total' shows lifetime plug consumption",
  59. )
  60. # Spoolman integration
  61. spoolman_enabled: bool = Field(default=False, description="Enable Spoolman integration for filament tracking")
  62. spoolman_url: str = Field(default="", description="Spoolman server URL (e.g., http://localhost:7912)")
  63. spoolman_sync_mode: str = Field(
  64. default="auto", description="Sync mode: 'auto' syncs immediately, 'manual' requires button press"
  65. )
  66. spoolman_disable_weight_sync: bool = Field(
  67. default=False,
  68. description="Disable remaining_weight sync. When enabled, only location is updated for existing spools.",
  69. )
  70. spoolman_report_partial_usage: bool = Field(
  71. default=True,
  72. 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.",
  73. )
  74. auto_add_unknown_rfid: bool = Field(
  75. default=True,
  76. description="Automatically add spools with unknown RFID tags to inventory. Disable if you pre-create inventory entries manually to avoid duplicates.",
  77. )
  78. disable_filament_warnings: bool = Field(
  79. default=False,
  80. description="Disable insufficient filament warnings when printing or queueing prints",
  81. )
  82. prefer_lowest_filament: bool = Field(
  83. default=False,
  84. description="When multiple AMS spools match, prefer the one with lowest remaining filament",
  85. )
  86. # Updates
  87. check_updates: bool = Field(default=True, description="Automatically check for updates on startup")
  88. check_printer_firmware: bool = Field(default=True, description="Check for printer firmware updates from Bambu Lab")
  89. include_beta_updates: bool = Field(default=False, description="Include beta/prerelease versions in update checks")
  90. # Language
  91. language: str = Field(default="en", description="UI language (en, de, fr, ja, it, pt-BR)")
  92. notification_language: str = Field(default="en", description="Language for push notifications (en, de)")
  93. # Bed cooled notification threshold
  94. bed_cooled_threshold: float = Field(
  95. default=35.0, description="Bed temperature threshold for cooled notification (°C)"
  96. )
  97. # AMS threshold settings for humidity and temperature coloring
  98. ams_humidity_good: int = Field(default=40, description="Humidity threshold for good (green): <= this value")
  99. ams_humidity_fair: int = Field(
  100. default=60, description="Humidity threshold for fair (orange): <= this value, > is red"
  101. )
  102. ams_temp_good: float = Field(default=28.0, description="Temperature threshold for good (blue): <= this value")
  103. ams_temp_fair: float = Field(
  104. default=35.0, description="Temperature threshold for fair (orange): <= this value, > is red"
  105. )
  106. # Separate from ams_temp_fair on purpose (#2905). The fair threshold decides
  107. # when the AMS card turns amber; this decides when a notification is sent.
  108. # 35 C is a sensible place to change a colour and not a sensible place to
  109. # page someone -- a room above 35 C makes the alarm fire once an hour for as
  110. # long as the weather lasts, and the only way to silence it was to raise the
  111. # display band and lose the colour that says the unit is warm. None means
  112. # "not set", which resolves to ams_temp_fair so every existing install keeps
  113. # behaving exactly as it does now.
  114. ams_temp_alarm: float | None = Field(
  115. default=None,
  116. description="Temperature threshold (°C) for sending an alarm. Unset falls back to ams_temp_fair.",
  117. )
  118. ams_history_retention_days: int = Field(default=30, description="Number of days to keep AMS sensor history data")
  119. printer_sensor_history_retention_days: int = Field(
  120. default=30, description="Number of days to keep printer heater history data (nozzle / bed / chamber)"
  121. )
  122. # Queue auto-drying settings
  123. queue_drying_enabled: bool = Field(
  124. default=False, description="Automatically dry AMS filament between queued prints"
  125. )
  126. queue_drying_block: bool = Field(
  127. default=False,
  128. description="Block queue until drying completes (when disabled, prints take priority over drying)",
  129. )
  130. ambient_drying_enabled: bool = Field(
  131. default=False,
  132. description="Automatically dry AMS filament on idle printers when humidity exceeds threshold, regardless of queue",
  133. )
  134. print_drying_enabled: bool = Field(
  135. default=False,
  136. description=(
  137. "Allow auto-drying to also fire on a printer that is currently printing, "
  138. "when its model+firmware supports concurrent drying (H2D 01.03.00.00+, "
  139. "H2C/H2S/P2S/H2D Pro 01.02.00.00+, X2D/A2L 01.01.00.00+, X1C 01.11.02.00+). "
  140. "Drying temperature is automatically capped 5 degC below the idle preset "
  141. "(floor 40 degC) to protect spools during print."
  142. ),
  143. )
  144. drying_presets: str = Field(
  145. default="",
  146. description="JSON blob of drying presets per filament type (empty = use built-in defaults)",
  147. )
  148. ams_humidity_thresholds: str = Field(
  149. default="",
  150. description=(
  151. "JSON blob of per-filament-type humidity trigger thresholds for auto-drying and alarms. "
  152. 'Shape: {"default": int, "PLA": int, "ASA": int, ...}. '
  153. "Empty = fall back to ams_humidity_fair for all types."
  154. ),
  155. )
  156. # Auto-print G-code injection (#422)
  157. gcode_snippets: str = Field(
  158. default="",
  159. description="JSON: per-model G-code injection snippets {model: {start_gcode, end_gcode}}",
  160. )
  161. # Scheduled local backup (#884)
  162. local_backup_enabled: bool = Field(default=False, description="Enable scheduled local backups")
  163. local_backup_schedule: str = Field(default="daily", description="Backup frequency: hourly, daily, weekly")
  164. local_backup_time: str = Field(default="03:00", description="Time of day for daily/weekly backups (HH:MM, 24h)")
  165. local_backup_retention: int = Field(default=5, description="Number of backup files to keep (1-100)")
  166. local_backup_path: str = Field(default="", description="Backup output directory (empty = DATA_DIR/backups)")
  167. # Print modal settings
  168. per_printer_mapping_expanded: bool = Field(
  169. default=False, description="Expand custom filament mapping by default in print modal"
  170. )
  171. # Date/time display format
  172. date_format: str = Field(default="system", description="Date format: system, us, eu, iso")
  173. time_format: str = Field(default="system", description="Time format: system, 12h, 24h")
  174. # Default printer for operations
  175. default_printer_id: int | None = Field(default=None, description="Default printer ID for uploads, reprints, etc.")
  176. # Slicer Pipelines (#1425 PR C). Cap on the ``copies`` field in the
  177. # Run-with-pipeline modal — keeps a misclick from queueing 5000 prints.
  178. pipeline_max_copies: int = Field(
  179. default=50,
  180. ge=1,
  181. le=1000,
  182. 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.",
  183. )
  184. # Virtual Printer
  185. virtual_printer_enabled: bool = Field(default=False, description="Enable virtual printer for slicer uploads")
  186. virtual_printer_access_code: str = Field(default="", description="Access code for virtual printer authentication")
  187. virtual_printer_mode: str = Field(
  188. default="archive",
  189. description="Mode: 'archive' (archive now), 'review' (pending review), 'queue' (add to print queue), or 'proxy' (relay to real printer)",
  190. )
  191. virtual_printer_archive_name_source: str = Field(
  192. default="metadata",
  193. 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).",
  194. )
  195. # Dark mode theme settings
  196. dark_style: str = Field(default="vibrant", description="Dark mode style: classic, glow, vibrant")
  197. dark_background: str = Field(
  198. default="cool", description="Dark mode background: neutral, warm, cool, oled, slate, forest"
  199. )
  200. dark_accent: str = Field(default="green", description="Dark mode accent: green, teal, blue, orange, purple, red")
  201. # Light mode theme settings
  202. light_style: str = Field(default="classic", description="Light mode style: classic, glow, vibrant")
  203. light_background: str = Field(default="neutral", description="Light mode background: neutral, warm, cool")
  204. light_accent: str = Field(default="green", description="Light mode accent: green, teal, blue, orange, purple, red")
  205. # FTP retry settings for unreliable WiFi connections
  206. ftp_retry_enabled: bool = Field(default=True, description="Enable automatic retry for FTP operations")
  207. ftp_retry_count: int = Field(default=3, description="Number of retry attempts for FTP operations (1-10)")
  208. ftp_retry_delay: int = Field(default=2, description="Seconds to wait between FTP retry attempts (1-30)")
  209. ftp_timeout: int = Field(default=30, description="FTP connection timeout in seconds (10-300)")
  210. # MQTT Relay settings for publishing events to external broker
  211. mqtt_enabled: bool = Field(default=False, description="Enable MQTT event publishing to external broker")
  212. mqtt_broker: str = Field(default="", description="MQTT broker hostname or IP address")
  213. mqtt_port: int = Field(default=1883, description="MQTT broker port (default 1883, TLS typically 8883)")
  214. mqtt_username: str = Field(default="", description="MQTT username for authentication (optional)")
  215. mqtt_password: str = Field(default="", description="MQTT password for authentication (optional)")
  216. mqtt_topic_prefix: str = Field(default="bambuddy", description="Topic prefix for all published messages")
  217. mqtt_use_tls: bool = Field(default=False, description="Use TLS/SSL encryption for MQTT connection")
  218. # External URL for notifications
  219. external_url: str = Field(
  220. default="", description="External URL where Bambuddy is accessible (for notification images)"
  221. )
  222. # Directory holding the user's docker-compose.yml, shown in the update
  223. # instructions so the printed command can be pasted from anywhere (#2664).
  224. # Empty means "omit the cd" — which is also the correct rendering when
  225. # nothing could be detected, rather than guessing a path that fails.
  226. docker_compose_dir: str = Field(
  227. default="", description="Host directory containing docker-compose.yml, used in the update instructions"
  228. )
  229. # Home Assistant integration for smart plug control
  230. ha_enabled: bool = Field(default=False, description="Enable Home Assistant integration for smart plug control")
  231. ha_url: str = Field(default="", description="Home Assistant URL (e.g., http://192.168.1.100:8123)")
  232. ha_token: str = Field(default="", description="Home Assistant Long-Lived Access Token")
  233. ha_url_from_env: bool = Field(default=False, description="Whether HA URL is set via HA_URL environment variable")
  234. ha_token_from_env: bool = Field(
  235. default=False, description="Whether HA token is set via HA_TOKEN environment variable"
  236. )
  237. ha_env_managed: bool = Field(
  238. default=False, description="Whether HA integration is fully managed by environment variables"
  239. )
  240. # File Manager / Library settings
  241. library_archive_mode: str = Field(
  242. default="ask",
  243. description="When printing from File Manager, create archive entry: 'always', 'never', or 'ask'",
  244. )
  245. library_disk_warning_gb: float = Field(
  246. default=5.0,
  247. description="Show warning when free disk space falls below this threshold (GB)",
  248. )
  249. # Camera view settings
  250. camera_view_mode: str = Field(
  251. default="window",
  252. description="Camera view mode: 'window' opens in new browser window, 'embedded' shows overlay on main screen",
  253. )
  254. # Preferred slicer application (server-side / API sidecar slicer)
  255. preferred_slicer: str = Field(
  256. default="bambu_studio",
  257. description="Slicer used for the server-side API / sidecar: 'bambu_studio' or 'orcaslicer'",
  258. )
  259. # "Open in Slicer" desktop URI handler — independent of the API slicer so
  260. # a user can slice via the Bambu Studio sidecar but open files locally in
  261. # OrcaSlicer, or vice versa (#1329). None falls back to ``preferred_slicer``
  262. # so existing installs behave identically until someone changes it.
  263. open_in_slicer: str | None = Field(
  264. default=None,
  265. description=(
  266. "Desktop slicer for the 'Open in Slicer' button: 'bambu_studio' or "
  267. "'orcaslicer'. None inherits from preferred_slicer."
  268. ),
  269. )
  270. # Where slicing runs. Orthogonal to ``preferred_slicer``, which only says
  271. # *which slicer binary* the sidecar drives: a browser engine is a different
  272. # execution site, not a different binary choice. Kept as its own key so the
  273. # two never have to encode impossible combinations.
  274. #
  275. # Only "sidecar" is implemented today; the slice modal offers a per-job
  276. # choice when more than one engine is available, and hides the control
  277. # entirely while there is only one.
  278. slice_engine: str = Field(
  279. default="sidecar",
  280. description="Default execution site for slicing: 'sidecar' (server-side API) or 'browser'",
  281. )
  282. # Slicer dispatch mode: when True, "Slice" actions open the in-app
  283. # SliceModal and call the slicer-API sidecar. When False (default), they
  284. # hand off to the user's local desktop slicer via URI scheme — preserving
  285. # the original Bambuddy behavior for users who don't run a sidecar.
  286. use_slicer_api: bool = Field(
  287. default=False,
  288. description="Use the slicer-API sidecar for slicing instead of the desktop slicer URI scheme",
  289. )
  290. # Slicer-API sidecar base URLs. Per-installation, configured via the
  291. # Settings UI (the "Slicer" card). Empty string means "fall back to the
  292. # SLICER_API_URL / BAMBU_STUDIO_API_URL env vars" — which themselves
  293. # default to the docker-compose ports in core/config.py.
  294. orcaslicer_api_url: str = Field(
  295. default="",
  296. description="OrcaSlicer sidecar URL (e.g. http://localhost:3003). Empty falls back to the SLICER_API_URL env var.",
  297. )
  298. bambu_studio_api_url: str = Field(
  299. default="",
  300. description="BambuStudio sidecar URL (e.g. http://localhost:3001). Empty falls back to the BAMBU_STUDIO_API_URL env var.",
  301. )
  302. # How long to keep waiting on a slice that isn't finishing. Measured against
  303. # the sidecar's progress channel, not total elapsed time — a heavy model can
  304. # legitimately slice for half an hour, and a wall-clock ceiling cannot tell
  305. # that apart from a stalled one (#2730). Sidecars too old to report progress
  306. # fall back to using this as a total-elapsed ceiling, which is the pre-#2730
  307. # behaviour with a configurable number.
  308. slicer_stall_timeout_minutes: int = Field(
  309. default=15,
  310. ge=1,
  311. le=240,
  312. description=(
  313. "Give up on a slice after this many minutes with no progress from the sidecar. "
  314. "On sidecars that do not report progress, applies to total slicing time instead."
  315. ),
  316. )
  317. # Prometheus metrics endpoint
  318. prometheus_enabled: bool = Field(default=False, description="Enable Prometheus metrics endpoint at /metrics")
  319. prometheus_token: str = Field(
  320. default="", description="Bearer token for Prometheus metrics authentication (optional)"
  321. )
  322. # Inventory low stock threshold
  323. low_stock_threshold: float = Field(
  324. default=20.0,
  325. ge=0.1,
  326. le=99.9,
  327. description="Low stock threshold percentage (%) for inventory filtering and display",
  328. )
  329. # Session policy (#1706) — admin-set ceiling for user session lifetime.
  330. # Default 24h preserves the M-2 audit reduction from 7 days. Max 720h
  331. # (30 days) bounds blast radius if an admin chooses a long session.
  332. session_max_hours: int = Field(
  333. default=24,
  334. ge=1,
  335. le=720,
  336. description=(
  337. "Maximum session lifetime in hours for user logins (default 24, max 720). "
  338. "Applies to new logins only; already-issued tokens keep their original expiry. "
  339. "Longer sessions reduce automatic logout protection."
  340. ),
  341. )
  342. # User email notifications (requires Advanced Authentication)
  343. user_notifications_enabled: bool = Field(
  344. default=True,
  345. description="Enable user email notifications for print job events (requires Advanced Authentication)",
  346. )
  347. # Default print options. bed_levelling / flow_cali / nozzle_offset_cali are
  348. # tri-state (off/on/auto), defaulting to "auto" per BambuStudio.
  349. default_bed_levelling: TriState = Field(default="auto", description="Default bed levelling option for new prints")
  350. default_flow_cali: TriState = Field(default="auto", description="Default flow calibration option for new prints")
  351. default_vibration_cali: bool = Field(
  352. default=True, description="Default vibration calibration option for new prints"
  353. )
  354. default_layer_inspect: bool = Field(
  355. default=False, description="Default first layer inspection option for new prints"
  356. )
  357. default_timelapse: bool = Field(default=False, description="Default timelapse option for new prints")
  358. default_nozzle_offset_cali: TriState = Field(
  359. default="auto",
  360. description="Default nozzle offset calibration option for new prints (dual-nozzle printers only)",
  361. )
  362. default_confirm_outcome: bool = Field(
  363. default=False,
  364. description="Default for asking for a post-print outcome verdict on new prints (#1898)",
  365. )
  366. confirm_outcome_external_prints: bool = Field(
  367. default=False,
  368. description=(
  369. "Also ask for the outcome of prints Bambuddy archived but did not dispatch — started at "
  370. "the printer, in Bambu Studio or in the Handy app (#1898)"
  371. ),
  372. )
  373. confirm_default_good_on_plate_clear: bool = Field(
  374. default=False,
  375. description=(
  376. "When the build plate is released (manual acknowledgment or next dispatch) with the "
  377. "outcome prompt still unanswered, record the print as a good part (#1898)"
  378. ),
  379. )
  380. # Staggered batch start for multi-printer jobs
  381. stagger_group_size: int = Field(
  382. default=2, ge=1, le=50, description="Number of printers to start simultaneously in staggered mode"
  383. )
  384. stagger_interval_minutes: int = Field(
  385. default=5, ge=1, le=60, description="Minutes between staggered printer groups"
  386. )
  387. # Finance budget window settings
  388. billing_enabled: bool = Field(
  389. default=False,
  390. description="Enable cost-center billing enforcement for print and queue operations",
  391. )
  392. printer_kill_switch_enabled: bool = Field(
  393. default=False,
  394. description="Immediately stop printer jobs that start without Bambuddy authorization",
  395. )
  396. finance_budget_reset_day: int = Field(
  397. default=1,
  398. ge=1,
  399. le=31,
  400. description="Day of month when monthly finance budget window resets (1-31, clamped for short months)",
  401. )
  402. finance_budget_reset_timezone: str = Field(
  403. default="UTC",
  404. description="IANA timezone for finance monthly budget reset calculation (e.g., Europe/Berlin)",
  405. )
  406. # Plate-clear confirmation for queue scheduling
  407. require_plate_clear: bool = Field(
  408. default=False,
  409. description="Require per-printer plate-clear confirmation before starting queued prints on finished printers",
  410. )
  411. queue_shortest_first: bool = Field(
  412. default=False,
  413. description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
  414. )
  415. queue_max_concurrent_uploads: int = Field(
  416. default=4,
  417. ge=1,
  418. le=16,
  419. description=(
  420. "How many printers the queue may upload to at the same time. Printers are independent "
  421. "machines, so raising this starts a multi-printer batch proportionally sooner; each "
  422. "concurrent upload costs one connection and one thread on the Bambuddy host."
  423. ),
  424. )
  425. # Preheat / heat-soak before queued prints (#1468). The scheduler stage runs
  426. # BEFORE FTP upload. Three hardware tiers behave differently:
  427. # - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E): M141 → wait for chamber
  428. # sensor to reach target → soak
  429. # - Chamber sensor only (X1C/P2S): M140 only → wait for radiant chamber
  430. # warm-up to reach target OR max-wait timeout → soak
  431. # - No chamber sensor (P1S/P1P/A1/A1 Mini): M140 only → fixed soak timer
  432. # (no way to verify chamber temp; relies entirely on max_wait + soak)
  433. # Chamber target derives per-print from the loaded AMS filament types via
  434. # preheat_filament_targets (max across loaded slots). A target of 0 skips
  435. # the chamber phase but keeps the bed phase + soak. Per-queue-item
  436. # `preheat_chamber_target_override` (nullable) bypasses the derivation.
  437. preheat_enabled: bool = Field(
  438. default=False,
  439. description="Master toggle / default for new queue items. Per-item preheat_override can flip the decision per print.",
  440. )
  441. preheat_filament_targets: str = Field(
  442. default="",
  443. description=(
  444. "JSON map of normalized filament type → chamber target °C. Empty = bundled defaults "
  445. "(PLA/PETG/TPU/PVA: 0, PETG-CF: 40, ABS/ASA: 45, PA/PC/PC-FR: 50, PA-CF: 55, default: 0). "
  446. "Scheduler picks max across loaded AMS slots; 0 disables chamber phase for that print."
  447. ),
  448. )
  449. preheat_max_wait_seconds: int = Field(
  450. default=900,
  451. ge=60,
  452. le=3600,
  453. 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).",
  454. )
  455. preheat_soak_seconds: int = Field(
  456. default=300,
  457. ge=0,
  458. le=1800,
  459. description="Additional hold time at temperature after the chamber reaches the target (or after max_wait_seconds elapses). 0 = no soak.",
  460. )
  461. queue_keep_bed_warm: bool = Field(
  462. default=False,
  463. description=(
  464. "While a printer is in FINISH state awaiting plate-clear and the next queued item requires "
  465. "chamber heating, hold the bed hot so the chamber stays warm during the bed-clearing "
  466. "window. The bed is the chamber's heating element here: the hold target is "
  467. "queue_keep_warm_bed_temp, or the item's own bed_temperature when the slicer metadata "
  468. "reports a higher one. Only fires for filaments with a non-zero chamber target "
  469. "(ASA, ABS, PA, PC etc.); PLA/PETG prints are skipped automatically."
  470. ),
  471. )
  472. queue_keep_warm_bed_temp: int = Field(
  473. default=90,
  474. ge=40,
  475. le=110,
  476. description=(
  477. "Bed temperature (°C) used when the bed's job is to heat the chamber. 90 sustains "
  478. "chamber warmth on enclosed printers and satisfies bed-threshold-linked aftermarket "
  479. "chamber heaters (which typically activate at bed ≥ 80). Applies in two places: the "
  480. "keep-warm hold between chamber-heated prints, and preheat when a chamber-heated "
  481. "item's slicer metadata carries no bed temperature at all. A parsed bed temperature "
  482. "higher than this always wins, so the bed is never driven cooler than the print needs."
  483. ),
  484. )
  485. queue_keep_warm_max_minutes: int = Field(
  486. default=120,
  487. ge=5,
  488. le=480,
  489. description=(
  490. "How long keep-warm may hold the bed on a printer waiting for its plate to be cleared. "
  491. "When this elapses the bed is switched off, and the hold does not re-arm until the "
  492. "printer next becomes a keep-warm candidate — so a plate nobody clears cannot leave the "
  493. "bed hot indefinitely. Set it to how long you realistically take to reach the printer; "
  494. "the only cost of it being too short is that the next print re-soaks from cold."
  495. ),
  496. )
  497. # User-configurable presets for the printer-card temperature / fan-speed
  498. # popovers. Each is a JSON array of exactly 3 ints (the "Off" button is
  499. # rendered separately and is not configurable). Empty string = use built-in
  500. # defaults. Validators on AppSettingsUpdate enforce the shape on writes.
  501. nozzle_temp_presets: str = Field(
  502. default="",
  503. description="JSON array of 3 nozzle-temperature preset values in C (0-320). Empty = use defaults [120, 220, 260]",
  504. )
  505. bed_temp_presets: str = Field(
  506. default="",
  507. description="JSON array of 3 bed-temperature preset values in C (0-140). Empty = use defaults [55, 75, 90]",
  508. )
  509. chamber_temp_presets: str = Field(
  510. default="",
  511. description="JSON array of 3 chamber-temperature preset values in C (0-65). Empty = use defaults [35, 45, 60]",
  512. )
  513. fan_speed_presets: str = Field(
  514. default="",
  515. description="JSON array of 3 fan-speed preset values in % (0-100). Empty = use defaults [50, 75, 100]",
  516. )
  517. # Local login (#1589) — when False, /auth/login rejects username+password
  518. # credentials with HTTP 403 and the login page hides the credentials form,
  519. # leaving only the OIDC SSO provider buttons. LDAP is governed by its own
  520. # `ldap_enabled` toggle and is not affected. The env-var
  521. # ``BAMBUDDY_LOCAL_LOGIN=true`` bypasses this gate at the route level so a
  522. # server admin can recover an install whose SSO provider is unreachable
  523. # without editing the DB.
  524. local_login_enabled: bool = Field(
  525. default=True,
  526. description=(
  527. "Allow username + password login on /auth/login. Disable when only SSO should be usable. "
  528. "BAMBUDDY_LOCAL_LOGIN=true on the server overrides this to keep a recovery path open."
  529. ),
  530. )
  531. # LDAP authentication (#794)
  532. ldap_enabled: bool = Field(default=False, description="Enable LDAP authentication")
  533. ldap_server_url: str = Field(default="", description="LDAP server URL (e.g., ldap://ldap.example.com:389)")
  534. ldap_bind_dn: str = Field(default="", description="Bind DN for LDAP searches (e.g., cn=admin,dc=example,dc=com)")
  535. ldap_bind_password: str = Field(default="", description="Bind password for LDAP searches")
  536. ldap_search_base: str = Field(default="", description="Search base DN (e.g., ou=users,dc=example,dc=com)")
  537. ldap_user_filter: str = Field(
  538. default="(sAMAccountName={username})",
  539. description="LDAP user search filter. {username} is replaced with the login username",
  540. )
  541. ldap_security: str = Field(default="starttls", description="LDAP security: 'starttls' or 'ldaps'")
  542. ldap_group_mapping: str = Field(
  543. default="",
  544. description="JSON: LDAP group to BamBuddy group mapping {ldap_group_dn: bambuddy_group_name}",
  545. )
  546. ldap_auto_provision: bool = Field(
  547. default=False,
  548. description="Auto-create BamBuddy user on first successful LDAP login",
  549. )
  550. ldap_default_group: str = Field(
  551. default="",
  552. description="Fallback BamBuddy group name assigned when an LDAP user authenticates but has no mapped groups. Empty = no fallback.",
  553. )
  554. # Obico AI failure detection (#172)
  555. obico_enabled: bool = Field(default=False, description="Enable Obico AI print failure detection")
  556. obico_ml_url: str = Field(
  557. default="",
  558. description="Self-hosted Obico ML API base URL (e.g., http://192.168.1.10:3333)",
  559. )
  560. obico_ml_token: str = Field(
  561. default="",
  562. description=(
  563. "Bearer token for the Obico ML API, matching the server's ML_API_TOKEN "
  564. "environment variable. Empty when the server runs without one."
  565. ),
  566. )
  567. obico_sensitivity: str = Field(
  568. default="medium",
  569. description="Detection sensitivity: 'low', 'medium', or 'high' (adjusts LOW/HIGH thresholds)",
  570. )
  571. obico_action: str = Field(
  572. default="notify",
  573. description="Action on detected failure: 'notify', 'pause', or 'pause_and_off'",
  574. )
  575. obico_poll_interval: int = Field(
  576. default=10,
  577. ge=5,
  578. le=120,
  579. description="Seconds between detection checks while a print is running",
  580. )
  581. obico_enabled_printers: str = Field(
  582. default="",
  583. description="JSON array of printer IDs to monitor (empty = all connected printers)",
  584. )
  585. # Inventory forecasting
  586. forecast_global_lead_time_days: int = Field(
  587. default=0,
  588. ge=0,
  589. description="Global lead time floor (days) used in reorder point calculation for all SKUs",
  590. )
  591. location_sensor_poll_interval: int = Field(
  592. default=120,
  593. ge=60,
  594. le=3600,
  595. description="Seconds between Home Assistant polls/UI refreshes for storage-location sensors",
  596. )
  597. # Server-backed rather than per-browser: these seed the alert rule written
  598. # onto each sensor row when one is bound, so two admins binding sensors
  599. # from different browsers must not seed different rules — and a restore
  600. # has to bring them back. The "show on card" default stays local, because
  601. # show_on_card is decided per sensor and this is only its form
  602. # pre-selection. Same JSON-in-a-string shape as preheat_filament_targets.
  603. location_sensor_alert_defaults: str = Field(
  604. default="",
  605. description=(
  606. "JSON map of sensor category (temperature/humidity/battery) → "
  607. '{"alertAbove": str, "alertBelow": str, "notifyOnAlert": bool}, seeding new '
  608. "storage-location sensor bindings. Empty = built-in defaults."
  609. ),
  610. )
  611. # Default sidebar order (admin-set for all users)
  612. default_sidebar_order: str = Field(
  613. default="",
  614. description="JSON object with 'order' key containing array of sidebar item IDs (empty = no default)",
  615. )
  616. class AppSettingsUpdate(BaseModel):
  617. """Schema for updating settings (all fields optional)."""
  618. auto_archive: bool | None = None
  619. save_thumbnails: bool | None = None
  620. capture_finish_photo: bool | None = None
  621. finish_photo_restore_plate: bool | None = None
  622. default_filament_cost: float | None = None
  623. currency: str | None = None
  624. energy_cost_per_kwh: float | None = None
  625. energy_tracking_mode: str | None = None
  626. spoolman_enabled: bool | None = None
  627. spoolman_url: str | None = None
  628. spoolman_sync_mode: str | None = None
  629. spoolman_disable_weight_sync: bool | None = None
  630. spoolman_report_partial_usage: bool | None = None
  631. auto_add_unknown_rfid: bool | None = None
  632. disable_filament_warnings: bool | None = None
  633. prefer_lowest_filament: bool | None = None
  634. check_updates: bool | None = None
  635. check_printer_firmware: bool | None = None
  636. include_beta_updates: bool | None = None
  637. local_login_enabled: bool | None = None
  638. language: str | None = None
  639. notification_language: str | None = None
  640. bed_cooled_threshold: float | None = None
  641. ams_humidity_good: int | None = None
  642. ams_humidity_fair: int | None = None
  643. ams_temp_good: float | None = None
  644. ams_temp_fair: float | None = None
  645. ams_temp_alarm: float | None = None
  646. ams_history_retention_days: int | None = None
  647. printer_sensor_history_retention_days: int | None = None
  648. queue_drying_enabled: bool | None = None
  649. queue_drying_block: bool | None = None
  650. ambient_drying_enabled: bool | None = None
  651. print_drying_enabled: bool | None = None
  652. drying_presets: str | None = None
  653. ams_humidity_thresholds: str | None = None
  654. per_printer_mapping_expanded: bool | None = None
  655. date_format: str | None = None
  656. time_format: str | None = None
  657. default_printer_id: int | None = None
  658. pipeline_max_copies: int | None = None
  659. virtual_printer_enabled: bool | None = None
  660. virtual_printer_access_code: str | None = None
  661. virtual_printer_mode: str | None = None
  662. virtual_printer_archive_name_source: str | None = None
  663. dark_style: str | None = None
  664. dark_background: str | None = None
  665. dark_accent: str | None = None
  666. light_style: str | None = None
  667. light_background: str | None = None
  668. light_accent: str | None = None
  669. ftp_retry_enabled: bool | None = None
  670. ftp_retry_count: int | None = None
  671. ftp_retry_delay: int | None = None
  672. ftp_timeout: int | None = None
  673. mqtt_enabled: bool | None = None
  674. mqtt_broker: str | None = None
  675. mqtt_port: int | None = None
  676. mqtt_username: str | None = None
  677. mqtt_password: str | None = None
  678. mqtt_topic_prefix: str | None = None
  679. mqtt_use_tls: bool | None = None
  680. external_url: str | None = None
  681. docker_compose_dir: str | None = None
  682. ha_enabled: bool | None = None
  683. ha_url: str | None = None
  684. ha_token: str | None = None
  685. library_archive_mode: str | None = None
  686. library_disk_warning_gb: float | None = None
  687. camera_view_mode: str | None = None
  688. preferred_slicer: str | None = None
  689. open_in_slicer: str | None = None
  690. slice_engine: str | None = None
  691. use_slicer_api: bool | None = None
  692. orcaslicer_api_url: str | None = None
  693. bambu_studio_api_url: str | None = None
  694. slicer_stall_timeout_minutes: int | None = Field(default=None, ge=1, le=240)
  695. prometheus_enabled: bool | None = None
  696. prometheus_token: str | None = None
  697. low_stock_threshold: float | None = Field(default=None, ge=0.1, le=99.9)
  698. session_max_hours: int | None = Field(default=None, ge=1, le=720)
  699. user_notifications_enabled: bool | None = None
  700. default_bed_levelling: TriState | None = None
  701. default_flow_cali: TriState | None = None
  702. default_vibration_cali: bool | None = None
  703. default_layer_inspect: bool | None = None
  704. default_timelapse: bool | None = None
  705. default_nozzle_offset_cali: TriState | None = None
  706. default_confirm_outcome: bool | None = None
  707. confirm_outcome_external_prints: bool | None = None
  708. confirm_default_good_on_plate_clear: bool | None = None
  709. stagger_group_size: int | None = Field(default=None, ge=1, le=50)
  710. stagger_interval_minutes: int | None = Field(default=None, ge=1, le=60)
  711. billing_enabled: bool | None = None
  712. printer_kill_switch_enabled: bool | None = None
  713. finance_budget_reset_day: int | None = Field(default=None, ge=1, le=31)
  714. finance_budget_reset_timezone: str | None = None
  715. require_plate_clear: bool | None = None
  716. queue_shortest_first: bool | None = None
  717. queue_max_concurrent_uploads: int | None = Field(default=None, ge=1, le=16)
  718. preheat_enabled: bool | None = None
  719. preheat_filament_targets: str | None = None
  720. preheat_max_wait_seconds: int | None = Field(default=None, ge=60, le=3600)
  721. preheat_soak_seconds: int | None = Field(default=None, ge=0, le=1800)
  722. queue_keep_bed_warm: bool | None = None
  723. queue_keep_warm_bed_temp: int | None = Field(default=None, ge=40, le=110)
  724. queue_keep_warm_max_minutes: int | None = Field(default=None, ge=5, le=480)
  725. nozzle_temp_presets: str | None = None
  726. bed_temp_presets: str | None = None
  727. chamber_temp_presets: str | None = None
  728. fan_speed_presets: str | None = None
  729. gcode_snippets: str | None = None
  730. local_backup_enabled: bool | None = None
  731. local_backup_schedule: str | None = None
  732. local_backup_time: str | None = None
  733. local_backup_retention: int | None = None
  734. local_backup_path: str | None = None
  735. ldap_enabled: bool | None = None
  736. ldap_server_url: str | None = None
  737. ldap_bind_dn: str | None = None
  738. ldap_bind_password: str | None = None
  739. ldap_search_base: str | None = None
  740. ldap_user_filter: str | None = None
  741. ldap_security: str | None = None
  742. ldap_group_mapping: str | None = None
  743. ldap_auto_provision: bool | None = None
  744. ldap_default_group: str | None = None
  745. obico_enabled: bool | None = None
  746. obico_ml_url: str | None = None
  747. obico_ml_token: str | None = None
  748. obico_sensitivity: str | None = None
  749. obico_action: str | None = None
  750. obico_poll_interval: int | None = Field(default=None, ge=5, le=120)
  751. obico_enabled_printers: str | None = None
  752. default_sidebar_order: str | None = None
  753. forecast_global_lead_time_days: int | None = Field(default=None, ge=0)
  754. location_sensor_poll_interval: int | None = Field(default=None, ge=60, le=3600)
  755. # Three categories × three short fields is well under 300 characters of
  756. # JSON, so 2000 is pure headroom — the cap only stops a stray client from
  757. # parking megabytes in the settings table. Write path only: the AppSettings
  758. # read model must keep accepting whatever an older install already stored.
  759. location_sensor_alert_defaults: str | None = Field(default=None, max_length=2000)
  760. @field_validator(*LAN_SERVICE_URL_SETTINGS)
  761. @classmethod
  762. def validate_lan_service_url(cls, v: str | None, info: ValidationInfo) -> str | None:
  763. """Reject SSRF-unsafe outbound service URLs on save.
  764. Empty (and whitespace-only) is the documented "not configured / fall
  765. back to the env var" value for all four fields and must keep passing.
  766. Values that are not absolute URLs at all ("192.168.1.10:3333",
  767. "localhost:3333") are left alone rather than rejected. Two reasons:
  768. - They are inert. Every consumer of these four settings goes through
  769. httpx, which raises UnsupportedProtocol for a URL with no scheme, so
  770. no request is ever issued and there is nothing to guard against.
  771. - They were storable before this validator existed, and the settings
  772. UI is a plain text input with no scheme enforcement. Newly rejecting
  773. them would break saves that have nothing to do with the URL: the
  774. Obico panel, for one, sends obico_ml_url with every change and
  775. auto-saves, so one legacy value would block toggling detection on or
  776. off. A pre-existing misconfiguration should keep failing where it
  777. already failed (at request time), not spread to unrelated fields.
  778. ``urlparse`` is no help in telling the two apart — it reads
  779. "localhost:3333" as scheme "localhost" — so the test is the literal
  780. "://" that makes a string an absolute URL.
  781. """
  782. if v is None or not v.strip():
  783. return v
  784. candidate = v.strip()
  785. if "://" not in candidate:
  786. return v
  787. # Lazy-imported: schemas avoid top-level imports from api/routes,
  788. # matching the existing pattern in auth.py's _validate_icon_url.
  789. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  790. try:
  791. assert_safe_lan_service_url(candidate, label=info.field_name or "URL")
  792. except ValueError as exc:
  793. raise ValueError(str(exc)) from exc
  794. return v
  795. @field_validator("docker_compose_dir")
  796. @classmethod
  797. def validate_docker_compose_dir(cls, v: str | None) -> str | None:
  798. """Keep the copy-and-paste update command free of shell injection (#2664).
  799. Validated on the write path only. Doing it on ``AppSettings`` as well
  800. would mean a single bad row — however it got there — 500s the entire
  801. settings GET and takes the app down with it, which is a worse outcome
  802. than rendering a string that has to be pasted into a shell by hand to
  803. do anything at all.
  804. """
  805. if v is None or not v.strip():
  806. return v
  807. candidate = v.strip()
  808. if len(candidate) > _COMPOSE_DIR_MAX_LEN:
  809. raise ValueError(f"Compose directory must be at most {_COMPOSE_DIR_MAX_LEN} characters")
  810. if not _COMPOSE_DIR_ALLOWED.match(candidate):
  811. raise ValueError(
  812. "Compose directory may only contain path characters (letters, digits, space, and - _ . / \\ : ~)"
  813. )
  814. # A trailing backslash is the one survivor that would still break the
  815. # frontend's double-quoting: `cd "/opt/bam buddy\"` escapes the closing
  816. # quote and swallows the rest of the line. Harmless (the shell just
  817. # waits for a terminator rather than running anything) but the user
  818. # would be left staring at a continuation prompt, so refuse it here
  819. # instead of shipping a command that cannot work.
  820. if candidate.endswith("\\"):
  821. raise ValueError("Compose directory must not end with a backslash")
  822. return candidate
  823. @field_validator("gcode_snippets")
  824. @classmethod
  825. def validate_gcode_snippets(cls, v: str | None) -> str | None:
  826. if v is None or v == "":
  827. return v
  828. try:
  829. parsed = json.loads(v)
  830. except json.JSONDecodeError:
  831. raise ValueError("gcode_snippets must be valid JSON or empty")
  832. if not isinstance(parsed, dict):
  833. raise ValueError("gcode_snippets must be a JSON object keyed by printer model")
  834. return v
  835. @field_validator("ldap_group_mapping")
  836. @classmethod
  837. def validate_ldap_group_mapping(cls, v: str | None) -> str | None:
  838. if v is None or v == "":
  839. return v
  840. try:
  841. parsed = json.loads(v)
  842. except json.JSONDecodeError:
  843. raise ValueError("ldap_group_mapping must be valid JSON or empty")
  844. if not isinstance(parsed, dict):
  845. raise ValueError("ldap_group_mapping must be a JSON object mapping LDAP group DNs to BamBuddy group names")
  846. return v
  847. @field_validator("obico_enabled_printers")
  848. @classmethod
  849. def validate_obico_enabled_printers(cls, v: str | None) -> str | None:
  850. if v is None or v == "":
  851. return v
  852. try:
  853. parsed = json.loads(v)
  854. except json.JSONDecodeError:
  855. raise ValueError("obico_enabled_printers must be valid JSON or empty")
  856. if not isinstance(parsed, list) or not all(isinstance(item, int) for item in parsed):
  857. raise ValueError("obico_enabled_printers must be a JSON array of printer IDs (integers)")
  858. return v
  859. @staticmethod
  860. def _validate_preset_triple(v: str | None, field_name: str, lo: int, hi: int) -> str | None:
  861. """Validate a JSON array of exactly 3 ints in [lo, hi]. Empty = defaults."""
  862. if v is None or v == "":
  863. return v
  864. try:
  865. parsed = json.loads(v)
  866. except json.JSONDecodeError:
  867. raise ValueError(f"{field_name} must be valid JSON or empty")
  868. if not isinstance(parsed, list) or len(parsed) != 3:
  869. raise ValueError(f"{field_name} must be a JSON array of exactly 3 integers")
  870. if not all(isinstance(item, int) and not isinstance(item, bool) for item in parsed):
  871. raise ValueError(f"{field_name} entries must all be integers")
  872. if not all(lo <= item <= hi for item in parsed):
  873. raise ValueError(f"{field_name} entries must each be in [{lo}, {hi}]")
  874. return v
  875. @field_validator("nozzle_temp_presets")
  876. @classmethod
  877. def validate_nozzle_temp_presets(cls, v: str | None) -> str | None:
  878. return cls._validate_preset_triple(v, "nozzle_temp_presets", 0, 320)
  879. @field_validator("bed_temp_presets")
  880. @classmethod
  881. def validate_bed_temp_presets(cls, v: str | None) -> str | None:
  882. return cls._validate_preset_triple(v, "bed_temp_presets", 0, 140)
  883. @field_validator("chamber_temp_presets")
  884. @classmethod
  885. def validate_chamber_temp_presets(cls, v: str | None) -> str | None:
  886. return cls._validate_preset_triple(v, "chamber_temp_presets", 0, MAX_CHAMBER_TEMP_C)
  887. @field_validator("fan_speed_presets")
  888. @classmethod
  889. def validate_fan_speed_presets(cls, v: str | None) -> str | None:
  890. return cls._validate_preset_triple(v, "fan_speed_presets", 0, 100)
  891. @field_validator("obico_sensitivity")
  892. @classmethod
  893. def validate_obico_sensitivity(cls, v: str | None) -> str | None:
  894. if v is None:
  895. return v
  896. if v not in ("low", "medium", "high"):
  897. raise ValueError("obico_sensitivity must be 'low', 'medium', or 'high'")
  898. return v
  899. @field_validator("obico_action")
  900. @classmethod
  901. def validate_obico_action(cls, v: str | None) -> str | None:
  902. if v is None:
  903. return v
  904. if v not in ("notify", "pause", "pause_and_off"):
  905. raise ValueError("obico_action must be 'notify', 'pause', or 'pause_and_off'")
  906. return v
  907. @field_validator("default_sidebar_order")
  908. @classmethod
  909. def validate_default_sidebar_order(cls, v: str | None) -> str | None:
  910. if v is None or v == "":
  911. return v
  912. try:
  913. parsed = json.loads(v)
  914. except json.JSONDecodeError:
  915. raise ValueError("default_sidebar_order must be valid JSON or empty")
  916. if isinstance(parsed, dict):
  917. order = parsed.get("order")
  918. hidden_system_item_ids = parsed.get("hiddenSystemItemIds", [])
  919. if not isinstance(hidden_system_item_ids, list) or not all(
  920. isinstance(item, str) for item in hidden_system_item_ids
  921. ):
  922. raise ValueError("sidebar hidden system item IDs must be an array of strings")
  923. elif isinstance(parsed, list):
  924. order = parsed
  925. else:
  926. raise ValueError("default_sidebar_order must be a JSON object with 'order' key or a JSON array")
  927. if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
  928. raise ValueError("sidebar order must be an array of strings")
  929. return v