settings.py 39 KB

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