settings.py 49 KB

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