settings.py 51 KB

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