settings.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import json
  2. from pydantic import BaseModel, Field, field_validator
  3. class AppSettings(BaseModel):
  4. """Application settings schema."""
  5. auto_archive: bool = Field(default=True, description="Automatically archive prints when completed")
  6. save_thumbnails: bool = Field(default=True, description="Extract and save preview images from 3MF files")
  7. capture_finish_photo: bool = Field(
  8. default=True,
  9. description=(
  10. "Capture photo from printer camera when print completes. Bambuddy records a "
  11. "brief timelapse during the print so the photo can be sourced from the moment "
  12. "before the bed drops; the timelapse file is kept if you enabled timelapse for "
  13. "this print, otherwise it is deleted automatically after the photo is captured."
  14. ),
  15. )
  16. default_filament_cost: float = Field(default=25.0, description="Default filament cost per kg")
  17. currency: str = Field(default="USD", description="Currency for cost tracking")
  18. energy_cost_per_kwh: float = Field(default=0.15, description="Electricity cost per kWh for energy tracking")
  19. energy_tracking_mode: str = Field(
  20. default="total",
  21. description="Energy display mode on stats: 'print' shows sum of per-print energy, 'total' shows lifetime plug consumption",
  22. )
  23. # Spoolman integration
  24. spoolman_enabled: bool = Field(default=False, description="Enable Spoolman integration for filament tracking")
  25. spoolman_url: str = Field(default="", description="Spoolman server URL (e.g., http://localhost:7912)")
  26. spoolman_sync_mode: str = Field(
  27. default="auto", description="Sync mode: 'auto' syncs immediately, 'manual' requires button press"
  28. )
  29. spoolman_disable_weight_sync: bool = Field(
  30. default=False,
  31. description="Disable remaining_weight sync. When enabled, only location is updated for existing spools.",
  32. )
  33. spoolman_report_partial_usage: bool = Field(
  34. default=True,
  35. 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.",
  36. )
  37. disable_filament_warnings: bool = Field(
  38. default=False,
  39. description="Disable insufficient filament warnings when printing or queueing prints",
  40. )
  41. prefer_lowest_filament: bool = Field(
  42. default=False,
  43. description="When multiple AMS spools match, prefer the one with lowest remaining filament",
  44. )
  45. # Updates
  46. check_updates: bool = Field(default=True, description="Automatically check for updates on startup")
  47. check_printer_firmware: bool = Field(default=True, description="Check for printer firmware updates from Bambu Lab")
  48. include_beta_updates: bool = Field(default=False, description="Include beta/prerelease versions in update checks")
  49. # Language
  50. language: str = Field(default="en", description="UI language (en, de, fr, ja, it, pt-BR)")
  51. notification_language: str = Field(default="en", description="Language for push notifications (en, de)")
  52. # Bed cooled notification threshold
  53. bed_cooled_threshold: float = Field(
  54. default=35.0, description="Bed temperature threshold for cooled notification (°C)"
  55. )
  56. # AMS threshold settings for humidity and temperature coloring
  57. ams_humidity_good: int = Field(default=40, description="Humidity threshold for good (green): <= this value")
  58. ams_humidity_fair: int = Field(
  59. default=60, description="Humidity threshold for fair (orange): <= this value, > is red"
  60. )
  61. ams_temp_good: float = Field(default=28.0, description="Temperature threshold for good (blue): <= this value")
  62. ams_temp_fair: float = Field(
  63. default=35.0, description="Temperature threshold for fair (orange): <= this value, > is red"
  64. )
  65. ams_history_retention_days: int = Field(default=30, description="Number of days to keep AMS sensor history data")
  66. # Queue auto-drying settings
  67. queue_drying_enabled: bool = Field(
  68. default=False, description="Automatically dry AMS filament between queued prints"
  69. )
  70. queue_drying_block: bool = Field(
  71. default=False,
  72. description="Block queue until drying completes (when disabled, prints take priority over drying)",
  73. )
  74. ambient_drying_enabled: bool = Field(
  75. default=False,
  76. description="Automatically dry AMS filament on idle printers when humidity exceeds threshold, regardless of queue",
  77. )
  78. drying_presets: str = Field(
  79. default="",
  80. description="JSON blob of drying presets per filament type (empty = use built-in defaults)",
  81. )
  82. # Auto-print G-code injection (#422)
  83. gcode_snippets: str = Field(
  84. default="",
  85. description="JSON: per-model G-code injection snippets {model: {start_gcode, end_gcode}}",
  86. )
  87. # Scheduled local backup (#884)
  88. local_backup_enabled: bool = Field(default=False, description="Enable scheduled local backups")
  89. local_backup_schedule: str = Field(default="daily", description="Backup frequency: hourly, daily, weekly")
  90. local_backup_time: str = Field(default="03:00", description="Time of day for daily/weekly backups (HH:MM, 24h)")
  91. local_backup_retention: int = Field(default=5, description="Number of backup files to keep (1-100)")
  92. local_backup_path: str = Field(default="", description="Backup output directory (empty = DATA_DIR/backups)")
  93. # Print modal settings
  94. per_printer_mapping_expanded: bool = Field(
  95. default=False, description="Expand custom filament mapping by default in print modal"
  96. )
  97. # Date/time display format
  98. date_format: str = Field(default="system", description="Date format: system, us, eu, iso")
  99. time_format: str = Field(default="system", description="Time format: system, 12h, 24h")
  100. # Default printer for operations
  101. default_printer_id: int | None = Field(default=None, description="Default printer ID for uploads, reprints, etc.")
  102. # Virtual Printer
  103. virtual_printer_enabled: bool = Field(default=False, description="Enable virtual printer for slicer uploads")
  104. virtual_printer_access_code: str = Field(default="", description="Access code for virtual printer authentication")
  105. virtual_printer_mode: str = Field(
  106. default="archive",
  107. description="Mode: 'archive' (archive now), 'review' (pending review), 'queue' (add to print queue), or 'proxy' (relay to real printer)",
  108. )
  109. virtual_printer_archive_name_source: str = Field(
  110. default="metadata",
  111. 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).",
  112. )
  113. # Dark mode theme settings
  114. dark_style: str = Field(default="vibrant", description="Dark mode style: classic, glow, vibrant")
  115. dark_background: str = Field(
  116. default="cool", description="Dark mode background: neutral, warm, cool, oled, slate, forest"
  117. )
  118. dark_accent: str = Field(default="green", description="Dark mode accent: green, teal, blue, orange, purple, red")
  119. # Light mode theme settings
  120. light_style: str = Field(default="classic", description="Light mode style: classic, glow, vibrant")
  121. light_background: str = Field(default="neutral", description="Light mode background: neutral, warm, cool")
  122. light_accent: str = Field(default="green", description="Light mode accent: green, teal, blue, orange, purple, red")
  123. # FTP retry settings for unreliable WiFi connections
  124. ftp_retry_enabled: bool = Field(default=True, description="Enable automatic retry for FTP operations")
  125. ftp_retry_count: int = Field(default=3, description="Number of retry attempts for FTP operations (1-10)")
  126. ftp_retry_delay: int = Field(default=2, description="Seconds to wait between FTP retry attempts (1-30)")
  127. ftp_timeout: int = Field(default=30, description="FTP connection timeout in seconds (10-300)")
  128. # MQTT Relay settings for publishing events to external broker
  129. mqtt_enabled: bool = Field(default=False, description="Enable MQTT event publishing to external broker")
  130. mqtt_broker: str = Field(default="", description="MQTT broker hostname or IP address")
  131. mqtt_port: int = Field(default=1883, description="MQTT broker port (default 1883, TLS typically 8883)")
  132. mqtt_username: str = Field(default="", description="MQTT username for authentication (optional)")
  133. mqtt_password: str = Field(default="", description="MQTT password for authentication (optional)")
  134. mqtt_topic_prefix: str = Field(default="bambuddy", description="Topic prefix for all published messages")
  135. mqtt_use_tls: bool = Field(default=False, description="Use TLS/SSL encryption for MQTT connection")
  136. # External URL for notifications
  137. external_url: str = Field(
  138. default="", description="External URL where Bambuddy is accessible (for notification images)"
  139. )
  140. # Home Assistant integration for smart plug control
  141. ha_enabled: bool = Field(default=False, description="Enable Home Assistant integration for smart plug control")
  142. ha_url: str = Field(default="", description="Home Assistant URL (e.g., http://192.168.1.100:8123)")
  143. ha_token: str = Field(default="", description="Home Assistant Long-Lived Access Token")
  144. ha_url_from_env: bool = Field(default=False, description="Whether HA URL is set via HA_URL environment variable")
  145. ha_token_from_env: bool = Field(
  146. default=False, description="Whether HA token is set via HA_TOKEN environment variable"
  147. )
  148. ha_env_managed: bool = Field(
  149. default=False, description="Whether HA integration is fully managed by environment variables"
  150. )
  151. # File Manager / Library settings
  152. library_archive_mode: str = Field(
  153. default="ask",
  154. description="When printing from File Manager, create archive entry: 'always', 'never', or 'ask'",
  155. )
  156. library_disk_warning_gb: float = Field(
  157. default=5.0,
  158. description="Show warning when free disk space falls below this threshold (GB)",
  159. )
  160. # Camera view settings
  161. camera_view_mode: str = Field(
  162. default="window",
  163. description="Camera view mode: 'window' opens in new browser window, 'embedded' shows overlay on main screen",
  164. )
  165. # Preferred slicer application
  166. preferred_slicer: str = Field(
  167. default="bambu_studio",
  168. description="Preferred slicer: 'bambu_studio' or 'orcaslicer'",
  169. )
  170. # Slicer dispatch mode: when True, "Slice" actions open the in-app
  171. # SliceModal and call the slicer-API sidecar. When False (default), they
  172. # hand off to the user's local desktop slicer via URI scheme — preserving
  173. # the original Bambuddy behavior for users who don't run a sidecar.
  174. use_slicer_api: bool = Field(
  175. default=False,
  176. description="Use the slicer-API sidecar for slicing instead of the desktop slicer URI scheme",
  177. )
  178. # Slicer-API sidecar base URLs. Per-installation, configured via the
  179. # Settings UI (the "Slicer" card). Empty string means "fall back to the
  180. # SLICER_API_URL / BAMBU_STUDIO_API_URL env vars" — which themselves
  181. # default to the docker-compose ports in core/config.py.
  182. orcaslicer_api_url: str = Field(
  183. default="",
  184. description="OrcaSlicer sidecar URL (e.g. http://localhost:3003). Empty falls back to the SLICER_API_URL env var.",
  185. )
  186. bambu_studio_api_url: str = Field(
  187. default="",
  188. description="BambuStudio sidecar URL (e.g. http://localhost:3001). Empty falls back to the BAMBU_STUDIO_API_URL env var.",
  189. )
  190. # Prometheus metrics endpoint
  191. prometheus_enabled: bool = Field(default=False, description="Enable Prometheus metrics endpoint at /metrics")
  192. prometheus_token: str = Field(
  193. default="", description="Bearer token for Prometheus metrics authentication (optional)"
  194. )
  195. # Inventory low stock threshold
  196. low_stock_threshold: float = Field(
  197. default=20.0,
  198. ge=0.1,
  199. le=99.9,
  200. description="Low stock threshold percentage (%) for inventory filtering and display",
  201. )
  202. # User email notifications (requires Advanced Authentication)
  203. user_notifications_enabled: bool = Field(
  204. default=True,
  205. description="Enable user email notifications for print job events (requires Advanced Authentication)",
  206. )
  207. # Default print options
  208. default_bed_levelling: bool = Field(default=True, description="Default bed levelling option for new prints")
  209. default_flow_cali: bool = Field(default=False, description="Default flow calibration option for new prints")
  210. default_vibration_cali: bool = Field(
  211. default=True, description="Default vibration calibration option for new prints"
  212. )
  213. default_layer_inspect: bool = Field(
  214. default=False, description="Default first layer inspection option for new prints"
  215. )
  216. default_timelapse: bool = Field(default=False, description="Default timelapse option for new prints")
  217. # Staggered batch start for multi-printer jobs
  218. stagger_group_size: int = Field(
  219. default=2, ge=1, le=50, description="Number of printers to start simultaneously in staggered mode"
  220. )
  221. stagger_interval_minutes: int = Field(
  222. default=5, ge=1, le=60, description="Minutes between staggered printer groups"
  223. )
  224. # Plate-clear confirmation for queue scheduling
  225. require_plate_clear: bool = Field(
  226. default=False,
  227. description="Require per-printer plate-clear confirmation before starting queued prints on finished printers",
  228. )
  229. queue_shortest_first: bool = Field(
  230. default=False,
  231. description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
  232. )
  233. # LDAP authentication (#794)
  234. ldap_enabled: bool = Field(default=False, description="Enable LDAP authentication")
  235. ldap_server_url: str = Field(default="", description="LDAP server URL (e.g., ldap://ldap.example.com:389)")
  236. ldap_bind_dn: str = Field(default="", description="Bind DN for LDAP searches (e.g., cn=admin,dc=example,dc=com)")
  237. ldap_bind_password: str = Field(default="", description="Bind password for LDAP searches")
  238. ldap_search_base: str = Field(default="", description="Search base DN (e.g., ou=users,dc=example,dc=com)")
  239. ldap_user_filter: str = Field(
  240. default="(sAMAccountName={username})",
  241. description="LDAP user search filter. {username} is replaced with the login username",
  242. )
  243. ldap_security: str = Field(default="starttls", description="LDAP security: 'starttls' or 'ldaps'")
  244. ldap_group_mapping: str = Field(
  245. default="",
  246. description="JSON: LDAP group to BamBuddy group mapping {ldap_group_dn: bambuddy_group_name}",
  247. )
  248. ldap_auto_provision: bool = Field(
  249. default=False,
  250. description="Auto-create BamBuddy user on first successful LDAP login",
  251. )
  252. ldap_default_group: str = Field(
  253. default="",
  254. description="Fallback BamBuddy group name assigned when an LDAP user authenticates but has no mapped groups. Empty = no fallback.",
  255. )
  256. # Obico AI failure detection (#172)
  257. obico_enabled: bool = Field(default=False, description="Enable Obico AI print failure detection")
  258. obico_ml_url: str = Field(
  259. default="",
  260. description="Self-hosted Obico ML API base URL (e.g., http://192.168.1.10:3333)",
  261. )
  262. obico_sensitivity: str = Field(
  263. default="medium",
  264. description="Detection sensitivity: 'low', 'medium', or 'high' (adjusts LOW/HIGH thresholds)",
  265. )
  266. obico_action: str = Field(
  267. default="notify",
  268. description="Action on detected failure: 'notify', 'pause', or 'pause_and_off'",
  269. )
  270. obico_poll_interval: int = Field(
  271. default=10,
  272. ge=5,
  273. le=120,
  274. description="Seconds between detection checks while a print is running",
  275. )
  276. obico_enabled_printers: str = Field(
  277. default="",
  278. description="JSON array of printer IDs to monitor (empty = all connected printers)",
  279. )
  280. # Inventory forecasting
  281. forecast_global_lead_time_days: int = Field(
  282. default=0,
  283. ge=0,
  284. description="Global lead time floor (days) used in reorder point calculation for all SKUs",
  285. )
  286. # Default sidebar order (admin-set for all users)
  287. default_sidebar_order: str = Field(
  288. default="",
  289. description="JSON object with 'order' key containing array of sidebar item IDs (empty = no default)",
  290. )
  291. class AppSettingsUpdate(BaseModel):
  292. """Schema for updating settings (all fields optional)."""
  293. auto_archive: bool | None = None
  294. save_thumbnails: bool | None = None
  295. capture_finish_photo: bool | None = None
  296. default_filament_cost: float | None = None
  297. currency: str | None = None
  298. energy_cost_per_kwh: float | None = None
  299. energy_tracking_mode: str | None = None
  300. spoolman_enabled: bool | None = None
  301. spoolman_url: str | None = None
  302. spoolman_sync_mode: str | None = None
  303. spoolman_disable_weight_sync: bool | None = None
  304. spoolman_report_partial_usage: bool | None = None
  305. disable_filament_warnings: bool | None = None
  306. prefer_lowest_filament: bool | None = None
  307. check_updates: bool | None = None
  308. check_printer_firmware: bool | None = None
  309. include_beta_updates: bool | None = None
  310. language: str | None = None
  311. notification_language: str | None = None
  312. bed_cooled_threshold: float | None = None
  313. ams_humidity_good: int | None = None
  314. ams_humidity_fair: int | None = None
  315. ams_temp_good: float | None = None
  316. ams_temp_fair: float | None = None
  317. ams_history_retention_days: int | None = None
  318. queue_drying_enabled: bool | None = None
  319. queue_drying_block: bool | None = None
  320. ambient_drying_enabled: bool | None = None
  321. drying_presets: str | None = None
  322. per_printer_mapping_expanded: bool | None = None
  323. date_format: str | None = None
  324. time_format: str | None = None
  325. default_printer_id: int | None = None
  326. virtual_printer_enabled: bool | None = None
  327. virtual_printer_access_code: str | None = None
  328. virtual_printer_mode: str | None = None
  329. virtual_printer_archive_name_source: str | None = None
  330. dark_style: str | None = None
  331. dark_background: str | None = None
  332. dark_accent: str | None = None
  333. light_style: str | None = None
  334. light_background: str | None = None
  335. light_accent: str | None = None
  336. ftp_retry_enabled: bool | None = None
  337. ftp_retry_count: int | None = None
  338. ftp_retry_delay: int | None = None
  339. ftp_timeout: int | None = None
  340. mqtt_enabled: bool | None = None
  341. mqtt_broker: str | None = None
  342. mqtt_port: int | None = None
  343. mqtt_username: str | None = None
  344. mqtt_password: str | None = None
  345. mqtt_topic_prefix: str | None = None
  346. mqtt_use_tls: bool | None = None
  347. external_url: str | None = None
  348. ha_enabled: bool | None = None
  349. ha_url: str | None = None
  350. ha_token: str | None = None
  351. library_archive_mode: str | None = None
  352. library_disk_warning_gb: float | None = None
  353. camera_view_mode: str | None = None
  354. preferred_slicer: str | None = None
  355. use_slicer_api: bool | None = None
  356. orcaslicer_api_url: str | None = None
  357. bambu_studio_api_url: str | None = None
  358. prometheus_enabled: bool | None = None
  359. prometheus_token: str | None = None
  360. low_stock_threshold: float | None = Field(default=None, ge=0.1, le=99.9)
  361. user_notifications_enabled: bool | None = None
  362. default_bed_levelling: bool | None = None
  363. default_flow_cali: bool | None = None
  364. default_vibration_cali: bool | None = None
  365. default_layer_inspect: bool | None = None
  366. default_timelapse: bool | None = None
  367. stagger_group_size: int | None = Field(default=None, ge=1, le=50)
  368. stagger_interval_minutes: int | None = Field(default=None, ge=1, le=60)
  369. require_plate_clear: bool | None = None
  370. queue_shortest_first: bool | None = None
  371. gcode_snippets: str | None = None
  372. local_backup_enabled: bool | None = None
  373. local_backup_schedule: str | None = None
  374. local_backup_time: str | None = None
  375. local_backup_retention: int | None = None
  376. local_backup_path: str | None = None
  377. ldap_enabled: bool | None = None
  378. ldap_server_url: str | None = None
  379. ldap_bind_dn: str | None = None
  380. ldap_bind_password: str | None = None
  381. ldap_search_base: str | None = None
  382. ldap_user_filter: str | None = None
  383. ldap_security: str | None = None
  384. ldap_group_mapping: str | None = None
  385. ldap_auto_provision: bool | None = None
  386. ldap_default_group: str | None = None
  387. obico_enabled: bool | None = None
  388. obico_ml_url: str | None = None
  389. obico_sensitivity: str | None = None
  390. obico_action: str | None = None
  391. obico_poll_interval: int | None = Field(default=None, ge=5, le=120)
  392. obico_enabled_printers: str | None = None
  393. default_sidebar_order: str | None = None
  394. forecast_global_lead_time_days: int | None = Field(default=None, ge=0)
  395. @field_validator("gcode_snippets")
  396. @classmethod
  397. def validate_gcode_snippets(cls, v: str | None) -> str | None:
  398. if v is None or v == "":
  399. return v
  400. try:
  401. parsed = json.loads(v)
  402. except json.JSONDecodeError:
  403. raise ValueError("gcode_snippets must be valid JSON or empty")
  404. if not isinstance(parsed, dict):
  405. raise ValueError("gcode_snippets must be a JSON object keyed by printer model")
  406. return v
  407. @field_validator("ldap_group_mapping")
  408. @classmethod
  409. def validate_ldap_group_mapping(cls, v: str | None) -> str | None:
  410. if v is None or v == "":
  411. return v
  412. try:
  413. parsed = json.loads(v)
  414. except json.JSONDecodeError:
  415. raise ValueError("ldap_group_mapping must be valid JSON or empty")
  416. if not isinstance(parsed, dict):
  417. raise ValueError("ldap_group_mapping must be a JSON object mapping LDAP group DNs to BamBuddy group names")
  418. return v
  419. @field_validator("obico_enabled_printers")
  420. @classmethod
  421. def validate_obico_enabled_printers(cls, v: str | None) -> str | None:
  422. if v is None or v == "":
  423. return v
  424. try:
  425. parsed = json.loads(v)
  426. except json.JSONDecodeError:
  427. raise ValueError("obico_enabled_printers must be valid JSON or empty")
  428. if not isinstance(parsed, list) or not all(isinstance(item, int) for item in parsed):
  429. raise ValueError("obico_enabled_printers must be a JSON array of printer IDs (integers)")
  430. return v
  431. @field_validator("obico_sensitivity")
  432. @classmethod
  433. def validate_obico_sensitivity(cls, v: str | None) -> str | None:
  434. if v is None:
  435. return v
  436. if v not in ("low", "medium", "high"):
  437. raise ValueError("obico_sensitivity must be 'low', 'medium', or 'high'")
  438. return v
  439. @field_validator("obico_action")
  440. @classmethod
  441. def validate_obico_action(cls, v: str | None) -> str | None:
  442. if v is None:
  443. return v
  444. if v not in ("notify", "pause", "pause_and_off"):
  445. raise ValueError("obico_action must be 'notify', 'pause', or 'pause_and_off'")
  446. return v
  447. @field_validator("default_sidebar_order")
  448. @classmethod
  449. def validate_default_sidebar_order(cls, v: str | None) -> str | None:
  450. if v is None or v == "":
  451. return v
  452. try:
  453. parsed = json.loads(v)
  454. except json.JSONDecodeError:
  455. raise ValueError("default_sidebar_order must be valid JSON or empty")
  456. if isinstance(parsed, dict):
  457. order = parsed.get("order")
  458. elif isinstance(parsed, list):
  459. order = parsed
  460. else:
  461. raise ValueError("default_sidebar_order must be a JSON object with 'order' key or a JSON array")
  462. if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
  463. raise ValueError("sidebar order must be an array of strings")
  464. return v