settings.py 52 KB

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