settings.py 19 KB

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