settings.py 37 KB

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