settings.py 49 KB

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