settings.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. import io
  2. import logging
  3. import os
  4. import zipfile
  5. from datetime import datetime
  6. from pathlib import Path
  7. from fastapi import APIRouter, Depends, File, UploadFile
  8. from fastapi.responses import FileResponse, JSONResponse
  9. from sqlalchemy import delete, select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.auth import RequirePermissionIfAuthEnabled, caller_is_api_key
  12. from backend.app.core.config import settings as app_settings
  13. from backend.app.core.database import get_db
  14. from backend.app.core.permissions import Permission
  15. from backend.app.models.settings import Settings
  16. from backend.app.models.user import User
  17. from backend.app.schemas.settings import AppSettings, AppSettingsUpdate
  18. logger = logging.getLogger(__name__)
  19. router = APIRouter(prefix="/settings", tags=["settings"])
  20. DEFAULT_SETTINGS = AppSettings()
  21. # Sensitive credential fields blanked for API-key callers
  22. _SENSITIVE_FIELDS_FOR_API_KEY = (
  23. "mqtt_password",
  24. "ha_token",
  25. "prometheus_token",
  26. "virtual_printer_access_code",
  27. "ldap_bind_password",
  28. )
  29. async def get_setting(db: AsyncSession, key: str) -> str | None:
  30. """Get a single setting value by key."""
  31. result = await db.execute(select(Settings).where(Settings.key == key))
  32. setting = result.scalar_one_or_none()
  33. return setting.value if setting else None
  34. async def get_external_login_url(db: AsyncSession) -> str:
  35. """Get the external URL for the login page.
  36. Uses external_url from settings if available, otherwise falls back to APP_URL env var.
  37. Args:
  38. db: Database session
  39. Returns:
  40. Full URL to the login page
  41. """
  42. import os
  43. external_url = await get_setting(db, "external_url")
  44. if external_url:
  45. external_url = external_url.rstrip("/")
  46. else:
  47. external_url = os.environ.get("APP_URL", "http://localhost:5173")
  48. return external_url + "/login"
  49. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  50. """Set a single setting value."""
  51. from backend.app.core.db_dialect import upsert_setting
  52. await upsert_setting(db, Settings, key, value)
  53. async def _build_settings_response(db: AsyncSession, is_api_key: bool = False) -> AppSettings:
  54. """Build the full settings response, scrubbing secrets for API-key callers."""
  55. settings_dict = DEFAULT_SETTINGS.model_dump()
  56. result = await db.execute(select(Settings))
  57. for setting in result.scalars().all():
  58. if setting.key not in settings_dict:
  59. continue
  60. if setting.key in [
  61. "auto_archive",
  62. "save_thumbnails",
  63. "capture_finish_photo",
  64. "spoolman_enabled",
  65. "spoolman_disable_weight_sync",
  66. "spoolman_report_partial_usage",
  67. "disable_filament_warnings",
  68. "prefer_lowest_filament",
  69. "check_updates",
  70. "check_printer_firmware",
  71. "include_beta_updates",
  72. "virtual_printer_enabled",
  73. "ftp_retry_enabled",
  74. "mqtt_enabled",
  75. "mqtt_use_tls",
  76. "ha_enabled",
  77. "per_printer_mapping_expanded",
  78. "prometheus_enabled",
  79. "user_notifications_enabled",
  80. "queue_drying_enabled",
  81. "queue_drying_block",
  82. "ambient_drying_enabled",
  83. "require_plate_clear",
  84. "queue_shortest_first",
  85. "default_bed_levelling",
  86. "default_flow_cali",
  87. "default_vibration_cali",
  88. "default_layer_inspect",
  89. "default_timelapse",
  90. "ldap_enabled",
  91. "ldap_auto_provision",
  92. ]:
  93. settings_dict[setting.key] = setting.value.lower() == "true"
  94. elif setting.key in [
  95. "default_filament_cost",
  96. "energy_cost_per_kwh",
  97. "ams_temp_good",
  98. "ams_temp_fair",
  99. "library_disk_warning_gb",
  100. "low_stock_threshold",
  101. ]:
  102. settings_dict[setting.key] = float(setting.value)
  103. elif setting.key in [
  104. "ams_humidity_good",
  105. "ams_humidity_fair",
  106. "ams_history_retention_days",
  107. "ftp_retry_count",
  108. "ftp_retry_delay",
  109. "ftp_timeout",
  110. "mqtt_port",
  111. "stagger_group_size",
  112. "stagger_interval_minutes",
  113. "forecast_global_lead_time_days",
  114. ]:
  115. settings_dict[setting.key] = int(setting.value)
  116. elif setting.key == "default_printer_id":
  117. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  118. else:
  119. settings_dict[setting.key] = setting.value
  120. ha_settings = await get_homeassistant_settings(db)
  121. settings_dict.update(ha_settings)
  122. # ldap_bind_password is never returned to any caller
  123. settings_dict["ldap_bind_password"] = ""
  124. if is_api_key:
  125. for field in _SENSITIVE_FIELDS_FOR_API_KEY:
  126. if field in settings_dict:
  127. settings_dict[field] = ""
  128. return AppSettings(**settings_dict)
  129. @router.get("", response_model=AppSettings)
  130. @router.get("/", response_model=AppSettings)
  131. async def get_settings(
  132. db: AsyncSession = Depends(get_db),
  133. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  134. _is_api_key: bool = Depends(caller_is_api_key),
  135. ):
  136. """Get all application settings."""
  137. return await _build_settings_response(db, is_api_key=_is_api_key)
  138. @router.put("/", response_model=AppSettings)
  139. async def update_settings(
  140. settings_update: AppSettingsUpdate,
  141. db: AsyncSession = Depends(get_db),
  142. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  143. ):
  144. """Update application settings."""
  145. update_data = settings_update.model_dump(exclude_unset=True)
  146. # Check if any MQTT settings are being updated
  147. mqtt_keys = {
  148. "mqtt_enabled",
  149. "mqtt_broker",
  150. "mqtt_port",
  151. "mqtt_username",
  152. "mqtt_password",
  153. "mqtt_topic_prefix",
  154. "mqtt_use_tls",
  155. }
  156. mqtt_updated = bool(mqtt_keys & set(update_data.keys()))
  157. for key, value in update_data.items():
  158. # Convert value to string for storage
  159. if isinstance(value, bool):
  160. str_value = "true" if value else "false"
  161. elif value is None:
  162. str_value = "None"
  163. else:
  164. str_value = str(value)
  165. await set_setting(db, key, str_value)
  166. await db.commit()
  167. # Expire all objects to ensure fresh reads after commit
  168. db.expire_all()
  169. # Reconfigure MQTT relay if any MQTT settings changed
  170. if mqtt_updated:
  171. try:
  172. from backend.app.services.mqtt_relay import mqtt_relay
  173. mqtt_settings = {
  174. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  175. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  176. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  177. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  178. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  179. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  180. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  181. }
  182. await mqtt_relay.configure(mqtt_settings)
  183. except Exception:
  184. pass # Don't fail the settings update if MQTT reconfiguration fails
  185. # Return updated settings (never scrub secrets on PUT — caller has SETTINGS_UPDATE permission)
  186. return await _build_settings_response(db, is_api_key=False)
  187. @router.patch("/", response_model=AppSettings)
  188. @router.patch("", response_model=AppSettings)
  189. async def patch_settings(
  190. settings_update: AppSettingsUpdate,
  191. db: AsyncSession = Depends(get_db),
  192. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  193. ):
  194. """Partially update application settings (same as PUT, for REST compatibility)."""
  195. return await update_settings(settings_update, db, _)
  196. @router.post("/reset", response_model=AppSettings)
  197. async def reset_settings(
  198. db: AsyncSession = Depends(get_db),
  199. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  200. ):
  201. """Reset all settings to defaults."""
  202. # Delete all settings
  203. result = await db.execute(select(Settings))
  204. for setting in result.scalars().all():
  205. await db.delete(setting)
  206. await db.commit()
  207. return DEFAULT_SETTINGS
  208. @router.get("/default-sidebar-order")
  209. async def get_default_sidebar_order(
  210. db: AsyncSession = Depends(get_db),
  211. ):
  212. """Get the admin-set default sidebar order.
  213. Intentionally unauthenticated: non-admin users need to read this value to apply
  214. the default sidebar order, but may lack SETTINGS_READ permission.
  215. The value is non-sensitive (sidebar item IDs only).
  216. """
  217. value = await get_setting(db, "default_sidebar_order")
  218. return {"default_sidebar_order": value or ""}
  219. # Fields exposed via /ui-preferences without SETTINGS_READ. Each entry MUST be
  220. # non-sensitive (no credentials, no PII, no secret tokens) — granting SETTINGS_READ
  221. # also grants visibility of SMTP/LDAP/MQTT passwords and similar, so the goal of
  222. # this endpoint is exactly to NOT require that permission for UI rendering hints.
  223. # When adding a field here, confirm it doesn't carry anything sensitive.
  224. _UI_PREFERENCE_FIELDS: tuple[str, ...] = (
  225. "require_plate_clear",
  226. "check_printer_firmware",
  227. "camera_view_mode",
  228. "time_format",
  229. "date_format",
  230. "drying_presets",
  231. "ams_humidity_good",
  232. "ams_humidity_fair",
  233. "ams_temp_good",
  234. "ams_temp_fair",
  235. "bed_cooled_threshold",
  236. )
  237. @router.get("/ui-preferences")
  238. async def get_ui_preferences(db: AsyncSession = Depends(get_db)):
  239. """Get the curated subset of settings that any page needs to render correctly.
  240. Intentionally not gated on SETTINGS_READ — every authenticated user (and
  241. every page that loads for them) needs these fields, but granting SETTINGS_READ
  242. would also grant visibility of secrets (SMTP/LDAP/MQTT credentials, etc.).
  243. Same pattern as /default-sidebar-order (#1293).
  244. Reuses _build_settings_response so the typed values match what /settings
  245. returns for fields with the same name — bool/int/float/str types stay in
  246. sync without a separate type-coercion path.
  247. """
  248. full = await _build_settings_response(db, is_api_key=False)
  249. dumped = full.model_dump()
  250. return {key: dumped[key] for key in _UI_PREFERENCE_FIELDS if key in dumped}
  251. @router.get("/check-ffmpeg")
  252. async def check_ffmpeg():
  253. """Check if ffmpeg is installed and available."""
  254. from backend.app.services.camera import get_ffmpeg_path
  255. ffmpeg_path = get_ffmpeg_path()
  256. return {
  257. "installed": ffmpeg_path is not None,
  258. "path": ffmpeg_path,
  259. }
  260. @router.get("/spoolman")
  261. async def get_spoolman_settings(
  262. db: AsyncSession = Depends(get_db),
  263. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  264. ):
  265. """Get Spoolman integration settings."""
  266. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  267. spoolman_url = await get_setting(db, "spoolman_url") or ""
  268. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  269. spoolman_disable_weight_sync = await get_setting(db, "spoolman_disable_weight_sync") or "false"
  270. spoolman_report_partial_usage = await get_setting(db, "spoolman_report_partial_usage") or "true"
  271. return {
  272. "spoolman_enabled": spoolman_enabled,
  273. "spoolman_url": spoolman_url,
  274. "spoolman_sync_mode": spoolman_sync_mode,
  275. "spoolman_disable_weight_sync": spoolman_disable_weight_sync,
  276. "spoolman_report_partial_usage": spoolman_report_partial_usage,
  277. }
  278. @router.put("/spoolman")
  279. async def update_spoolman_settings(
  280. settings: dict,
  281. db: AsyncSession = Depends(get_db),
  282. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  283. ):
  284. """Update Spoolman integration settings."""
  285. if "spoolman_enabled" in settings:
  286. old_val = await get_setting(db, "spoolman_enabled") or "false"
  287. new_val = settings["spoolman_enabled"]
  288. await set_setting(db, "spoolman_enabled", new_val)
  289. # Switching to Spoolman: clear built-in inventory slot assignments
  290. if old_val.lower() != "true" and new_val.lower() == "true":
  291. from backend.app.models.spool_assignment import SpoolAssignment
  292. result = await db.execute(delete(SpoolAssignment))
  293. logger.info("Cleared %d spool assignments on switch to Spoolman mode", result.rowcount)
  294. if "spoolman_url" in settings:
  295. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  296. if "spoolman_sync_mode" in settings:
  297. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  298. if "spoolman_disable_weight_sync" in settings:
  299. await set_setting(db, "spoolman_disable_weight_sync", settings["spoolman_disable_weight_sync"])
  300. if "spoolman_report_partial_usage" in settings:
  301. await set_setting(db, "spoolman_report_partial_usage", settings["spoolman_report_partial_usage"])
  302. await db.commit()
  303. db.expire_all()
  304. # Return updated settings
  305. return await get_spoolman_settings(db)
  306. async def get_homeassistant_settings(db: AsyncSession) -> dict:
  307. """
  308. Get Home Assistant integration settings.
  309. Environment variables (HA_URL, HA_TOKEN) take precedence over database settings.
  310. """
  311. import os
  312. # Check environment variables first
  313. ha_url_env = os.environ.get("HA_URL")
  314. ha_token_env = os.environ.get("HA_TOKEN")
  315. # Fall back to database values
  316. ha_url = ha_url_env or await get_setting(db, "ha_url") or ""
  317. ha_token = ha_token_env or await get_setting(db, "ha_token") or ""
  318. ha_enabled_db = await get_setting(db, "ha_enabled") or "false"
  319. # Track which settings come from environment
  320. ha_url_from_env = bool(ha_url_env)
  321. ha_token_from_env = bool(ha_token_env)
  322. ha_env_managed = ha_url_from_env and ha_token_from_env
  323. # Auto-enable when both env vars are set, otherwise use database value
  324. if ha_url_env and ha_token_env:
  325. ha_enabled = True
  326. else:
  327. ha_enabled = ha_enabled_db.lower() == "true"
  328. return {
  329. "ha_enabled": ha_enabled,
  330. "ha_url": ha_url,
  331. "ha_token": ha_token,
  332. "ha_url_from_env": ha_url_from_env,
  333. "ha_token_from_env": ha_token_from_env,
  334. "ha_env_managed": ha_env_managed,
  335. }
  336. async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]:
  337. """Create a complete backup ZIP (database + all data directories).
  338. If output_path is given, the ZIP is written there.
  339. Otherwise a temporary file is created (caller must clean up).
  340. Returns (zip_path, filename).
  341. """
  342. import shutil
  343. import tempfile
  344. from backend.app.core.db_dialect import is_sqlite
  345. base_dir = app_settings.base_dir
  346. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  347. with tempfile.TemporaryDirectory() as temp_dir:
  348. temp_path = Path(temp_dir)
  349. if is_sqlite():
  350. from sqlalchemy import text
  351. from backend.app.core.database import engine
  352. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  353. # Checkpoint WAL to ensure all data is in main db file
  354. async with engine.begin() as conn:
  355. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  356. # Copy database file
  357. shutil.copy2(db_path, temp_path / "bambuddy.db")
  358. else:
  359. # PostgreSQL: export to a portable SQLite file via SQLAlchemy.
  360. # This makes backups restorable on both SQLite and Postgres installs.
  361. import json
  362. import sqlite3
  363. from backend.app.core.database import Base, engine
  364. backup_db_path = temp_path / "bambuddy.db"
  365. dst = sqlite3.connect(str(backup_db_path))
  366. metadata = Base.metadata
  367. # Create tables in SQLite backup (simplified — just column names and types)
  368. for table in metadata.sorted_tables:
  369. cols = []
  370. pk_cols = [col.name for col in table.columns if col.primary_key]
  371. for col in table.columns:
  372. col_type = "TEXT" # Default
  373. type_str = str(col.type).upper()
  374. if "INT" in type_str:
  375. col_type = "INTEGER"
  376. elif "FLOAT" in type_str or "REAL" in type_str or "NUMERIC" in type_str:
  377. col_type = "REAL"
  378. elif "BOOL" in type_str:
  379. col_type = "BOOLEAN"
  380. # Only inline PRIMARY KEY for single-column PKs
  381. pk = " PRIMARY KEY" if col.primary_key and len(pk_cols) == 1 else ""
  382. cols.append(f"{col.name} {col_type}{pk}")
  383. # Add composite primary key constraint if needed
  384. if len(pk_cols) > 1:
  385. cols.append(f"PRIMARY KEY ({', '.join(pk_cols)})")
  386. dst.execute(f"CREATE TABLE IF NOT EXISTS {table.name} ({', '.join(cols)})") # noqa: S608
  387. # Export data from Postgres to SQLite
  388. async with engine.connect() as conn:
  389. for table in metadata.sorted_tables:
  390. result = await conn.execute(table.select())
  391. rows = result.fetchall()
  392. if not rows:
  393. continue
  394. columns = list(result.keys())
  395. placeholders = ", ".join(["?"] * len(columns))
  396. col_list = ", ".join(columns)
  397. insert_sql = f"INSERT INTO {table.name} ({col_list}) VALUES ({placeholders})" # noqa: S608 # nosec B608 — table/column names from ORM metadata, not user input
  398. def _serialize_row(row):
  399. return tuple(json.dumps(v) if isinstance(v, (list, dict)) else v for v in row)
  400. dst.executemany(insert_sql, [_serialize_row(row) for row in rows])
  401. dst.commit()
  402. dst.close()
  403. logger.info("PostgreSQL backup exported to portable SQLite format")
  404. # Copy data directories (if they exist)
  405. dirs_to_backup = [
  406. ("archive", base_dir / "archive"),
  407. ("virtual_printer", base_dir / "virtual_printer"),
  408. ("plate_calibration", app_settings.plate_calibration_dir),
  409. ("icons", base_dir / "icons"),
  410. ("projects", base_dir / "projects"),
  411. ]
  412. for name, src_dir in dirs_to_backup:
  413. if src_dir.exists() and any(src_dir.iterdir()):
  414. try:
  415. shutil.copytree(src_dir, temp_path / name)
  416. except shutil.Error as e:
  417. logger.warning("Some files in %s could not be copied: %s", name, e)
  418. except PermissionError as e:
  419. logger.warning("Permission denied copying %s: %s", name, e)
  420. # Include the MFA encryption key as a ZIP top-level entry alongside
  421. # bambuddy.db. Without it, encrypted client_secret / TOTP secret rows
  422. # would be unrecoverable after restore on a host without MFA_ENCRYPTION_KEY set.
  423. from backend.app.core.paths import resolve_data_dir
  424. mfa_key_src = resolve_data_dir() / ".mfa_encryption_key"
  425. if mfa_key_src.exists() and mfa_key_src.is_file():
  426. try:
  427. shutil.copy2(mfa_key_src, temp_path / ".mfa_encryption_key")
  428. except OSError as exc:
  429. logger.error(
  430. "Could not include MFA encryption key in backup (%s). "
  431. "The backup ZIP will not contain the key — restore on a "
  432. "keyless host will fail for encrypted secrets.",
  433. exc,
  434. )
  435. raise
  436. # Create ZIP
  437. if output_path is not None:
  438. zip_file = output_path / filename
  439. else:
  440. fd, tmp = tempfile.mkstemp(suffix=".zip")
  441. os.close(fd)
  442. zip_file = Path(tmp)
  443. with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
  444. for file_path in temp_path.rglob("*"):
  445. if file_path.is_file():
  446. arcname = file_path.relative_to(temp_path)
  447. zf.write(file_path, arcname)
  448. return zip_file, filename
  449. @router.get("/backup")
  450. async def create_backup(
  451. db: AsyncSession = Depends(get_db),
  452. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_BACKUP),
  453. ):
  454. """Create a complete backup (database + all files) as a ZIP download."""
  455. from starlette.background import BackgroundTask
  456. try:
  457. zip_file, filename = await create_backup_zip()
  458. return FileResponse(
  459. path=zip_file,
  460. filename=filename,
  461. media_type="application/zip",
  462. background=BackgroundTask(lambda: zip_file.unlink(missing_ok=True)),
  463. )
  464. except Exception as e:
  465. logger.error("Backup failed: %s", e, exc_info=True)
  466. return JSONResponse(
  467. status_code=500,
  468. content={"success": False, "message": "Backup failed. Check server logs for details."},
  469. )
  470. async def _import_sqlite_to_postgres(sqlite_path: Path, postgres_url: str):
  471. """Import data from a SQLite database file into the current PostgreSQL database.
  472. Used for cross-database restore (SQLite backup → PostgreSQL).
  473. Reads all tables from the SQLite file and bulk-inserts into Postgres.
  474. """
  475. import sqlite3
  476. from sqlalchemy import text
  477. from backend.app.core.database import Base, _create_engine
  478. # Create a temporary engine for the import (current engine was disposed)
  479. pg_engine = _create_engine()
  480. try:
  481. # Open SQLite file directly (sync — it's a local file read)
  482. src = sqlite3.connect(str(sqlite_path))
  483. src.row_factory = sqlite3.Row
  484. # Get list of tables from SQLite (skip internal/FTS tables)
  485. cursor = src.execute(
  486. "SELECT name FROM sqlite_master WHERE type='table' "
  487. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  488. )
  489. src_tables = {row["name"] for row in cursor.fetchall()}
  490. # Get Postgres tables from our ORM models
  491. metadata = Base.metadata
  492. pg_tables = set(metadata.tables.keys())
  493. # Only import tables that exist in both source and destination
  494. tables_to_import = src_tables & pg_tables
  495. sorted_tables = [t.name for t in metadata.sorted_tables if t.name in tables_to_import]
  496. # Phase 1: Drop all tables and recreate WITHOUT foreign keys.
  497. # This avoids all FK ordering/orphan issues during import.
  498. saved_fks = {}
  499. for table in metadata.sorted_tables:
  500. fks = list(table.foreign_key_constraints)
  501. if fks:
  502. saved_fks[table.name] = fks
  503. for fk in fks:
  504. table.constraints.discard(fk)
  505. async with pg_engine.begin() as conn:
  506. # Drop every existing table in the public schema with CASCADE
  507. # rather than `metadata.drop_all`. Two reasons:
  508. # 1. The user's live DB may carry orphan tables from removed
  509. # features (e.g. the legacy `spoolman_slot_assignments`,
  510. # `spoolman_k_profile`) that hold FK constraints back to
  511. # ORM tables. `drop_all` doesn't know they exist and emits
  512. # `DROP TABLE printers` without CASCADE — Postgres refuses
  513. # and the whole restore aborts (#XXXX).
  514. # 2. Even within the metadata, `drop_all` is FK-ordered and
  515. # breaks if a future schema rename leaves old constraints
  516. # around. CASCADE is the right tool for a destructive
  517. # restore: the user is intentionally wiping state.
  518. await conn.execute(
  519. text(
  520. "DO $$ DECLARE r RECORD; BEGIN "
  521. "FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP "
  522. "EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE'; "
  523. "END LOOP; END $$;"
  524. )
  525. )
  526. await conn.run_sync(metadata.create_all)
  527. # Restore FK definitions in metadata (needed for re-adding later)
  528. for table_name, fks in saved_fks.items():
  529. table_obj = metadata.tables[table_name]
  530. for fk in fks:
  531. table_obj.constraints.add(fk)
  532. # Phase 2: Import data (no FKs to worry about)
  533. async with pg_engine.begin() as conn:
  534. # Import each table in dependency order (parents before children)
  535. for table_name in sorted_tables:
  536. rows = src.execute(f"SELECT * FROM {table_name}").fetchall() # noqa: S608 # nosec B608
  537. if not rows:
  538. continue
  539. # Filter to columns that exist in the Postgres table
  540. src_columns = rows[0].keys()
  541. pg_table = metadata.tables.get(table_name)
  542. pg_columns = {c.name for c in pg_table.columns} if pg_table is not None else set()
  543. columns = [c for c in src_columns if c in pg_columns]
  544. if not columns:
  545. continue
  546. col_list = ", ".join(columns)
  547. param_list = ", ".join(f":{c}" for c in columns)
  548. # ON CONFLICT DO NOTHING handles duplicate rows from SQLite (which doesn't enforce unique constraints)
  549. insert_sql = text(f"INSERT INTO {table_name} ({col_list}) VALUES ({param_list}) ON CONFLICT DO NOTHING") # noqa: S608 # nosec B608
  550. # Identify columns that need type conversion (SQLite stores booleans
  551. # as int and datetimes as str — asyncpg requires native Python types)
  552. from datetime import datetime as dt
  553. bool_columns = set()
  554. datetime_columns = set()
  555. not_null_defaults = {} # col_name -> default value for NOT NULL columns
  556. if pg_table is not None:
  557. for col in pg_table.columns:
  558. if col.name not in columns:
  559. continue
  560. col_type = str(col.type)
  561. if col_type == "BOOLEAN":
  562. bool_columns.add(col.name)
  563. elif col_type in ("DATETIME", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE"):
  564. datetime_columns.add(col.name)
  565. # Track NOT NULL columns with defaults — older backups may have NULL
  566. # for columns added after the backup was created
  567. if not col.nullable:
  568. if col.default is not None:
  569. default = col.default.arg
  570. if callable(default):
  571. default = default(None)
  572. not_null_defaults[col.name] = default
  573. elif col.server_default is not None:
  574. # server_default=func.now() → use current timestamp
  575. if col.name in datetime_columns:
  576. not_null_defaults[col.name] = "__now__"
  577. else:
  578. # Try to extract literal server default
  579. sd = str(col.server_default.arg) if hasattr(col.server_default, "arg") else None
  580. if sd is not None:
  581. not_null_defaults[col.name] = sd
  582. now = dt.now()
  583. def _convert_row(
  584. row, cols=columns, bools=bool_columns, dts=datetime_columns, nn_defaults=not_null_defaults, _now=now
  585. ):
  586. result = {}
  587. for c in cols:
  588. val = row[c]
  589. if val is None and c in nn_defaults:
  590. val = _now if nn_defaults[c] == "__now__" else nn_defaults[c]
  591. if val is not None:
  592. if c in bools:
  593. val = bool(val)
  594. elif c in dts and isinstance(val, str):
  595. try:
  596. val = dt.fromisoformat(val)
  597. except ValueError:
  598. pass
  599. result[c] = val
  600. return result
  601. batch = [_convert_row(row) for row in rows]
  602. await conn.execute(insert_sql, batch)
  603. logger.info("Imported %d rows into %s", len(batch), table_name)
  604. # Reset sequences to max(id) + 1 for each table with an id column
  605. for table_name in sorted_tables:
  606. try:
  607. async with conn.begin_nested():
  608. result = await conn.execute(text(f"SELECT MAX(id) FROM {table_name}")) # noqa: S608 # nosec B608
  609. max_id = result.scalar()
  610. if max_id is not None:
  611. seq_name = f"{table_name}_id_seq"
  612. await conn.execute(text(f"SELECT setval('{seq_name}', {max_id})")) # noqa: S608
  613. except Exception:
  614. pass # Table may not have an id column or sequence
  615. src.close()
  616. logger.info("Cross-database import complete: %d tables imported", len(tables_to_import))
  617. # Recreate FK constraints from ORM metadata (not from saved definitions).
  618. # Use individual transactions so orphaned SQLite data doesn't block valid FKs.
  619. from sqlalchemy.schema import AddConstraint
  620. failed_fks = []
  621. for table in metadata.sorted_tables:
  622. for fk in table.foreign_key_constraints:
  623. try:
  624. async with pg_engine.begin() as fk_conn:
  625. await fk_conn.execute(AddConstraint(fk))
  626. except Exception:
  627. failed_fks.append(f"{table.name}.{fk.name}")
  628. if failed_fks:
  629. logger.warning(
  630. "Could not restore %d FK constraints (orphaned data in SQLite): %s",
  631. len(failed_fks),
  632. ", ".join(failed_fks),
  633. )
  634. finally:
  635. await pg_engine.dispose()
  636. @router.post("/restore")
  637. async def restore_backup(
  638. file: UploadFile = File(...),
  639. db: AsyncSession = Depends(get_db),
  640. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_RESTORE),
  641. ):
  642. """Restore from a complete backup ZIP.
  643. Replaces the database and all data directories from the backup ZIP.
  644. Requires a restart after restore.
  645. """
  646. import shutil
  647. import tempfile
  648. from fastapi import HTTPException
  649. from backend.app.core.database import close_all_connections, init_db, reinitialize_database
  650. from backend.app.core.db_dialect import is_sqlite
  651. from backend.app.services.virtual_printer import virtual_printer_manager
  652. base_dir = app_settings.base_dir
  653. with tempfile.TemporaryDirectory() as temp_dir:
  654. temp_path = Path(temp_dir)
  655. # 1. Read and extract ZIP
  656. content = await file.read()
  657. # Check if it's a valid ZIP
  658. if not file.filename or not file.filename.endswith(".zip"):
  659. raise HTTPException(400, "Invalid backup file: must be a .zip file")
  660. try:
  661. with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
  662. for name in zf.namelist():
  663. # Reject path-traversal payloads: any entry whose resolved
  664. # path escapes temp_path would allow writing arbitrary files
  665. # on the host (ZipSlip / CVE-2006-5456).
  666. dest = (temp_path / name).resolve()
  667. # is_relative_to (Python 3.9+) covers both relative
  668. # path-traversal (../etc/passwd) and absolute-path overrides
  669. # (/etc/passwd) — str.startswith was vulnerable to
  670. # prefix-collision attacks (e.g. /tmp/abc_evil/file passing
  671. # a /tmp/abc prefix check).
  672. if not dest.is_relative_to(temp_path.resolve()):
  673. raise HTTPException(400, f"Invalid backup: unsafe path in ZIP: {name!r}")
  674. zf.extractall(temp_path)
  675. except zipfile.BadZipFile:
  676. raise HTTPException(400, "Invalid backup file: not a valid ZIP")
  677. # 2. Validate backup
  678. backup_db = temp_path / "bambuddy.db"
  679. if not backup_db.exists():
  680. raise HTTPException(400, "Invalid backup: missing bambuddy.db")
  681. try:
  682. import asyncio
  683. # 3. Stop virtual printer if running (releases file locks)
  684. try:
  685. if virtual_printer_manager.is_enabled:
  686. logger.info("Stopping virtual printer for restore...")
  687. await virtual_printer_manager.configure(enabled=False)
  688. await asyncio.sleep(1)
  689. except Exception as e:
  690. logger.warning("Failed to stop virtual printer: %s", e)
  691. # 4. Close current database connections
  692. logger.info("Closing database connections...")
  693. await close_all_connections()
  694. # B1: Restore the MFA encryption key file BEFORE the database swap.
  695. # If the key write fails (OSError, RO disk, full disk, EACCES) we
  696. # can still abort while the live DB is intact. Doing this AFTER the
  697. # DB swap would leave the database with rows encrypted under the
  698. # backup's key but the running install holding only the old key —
  699. # every encrypted secret becomes unrecoverable.
  700. from backend.app.core.paths import resolve_data_dir
  701. mfa_key_src = temp_path / ".mfa_encryption_key"
  702. if mfa_key_src.exists() and mfa_key_src.is_file():
  703. dst_key = resolve_data_dir() / ".mfa_encryption_key"
  704. tmp_key = dst_key.parent / ".mfa_encryption_key.restore-tmp"
  705. try:
  706. dst_key.parent.mkdir(parents=True, exist_ok=True)
  707. # S1: atomic write with restrictive mode from creation.
  708. # O_TRUNC because a stale tmp may exist from a prior
  709. # failed restore attempt — we want to overwrite it.
  710. fd = os.open(str(tmp_key), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
  711. try:
  712. os.write(fd, mfa_key_src.read_bytes())
  713. finally:
  714. os.close(fd)
  715. # POSIX rename(2) — atomic when source/dest are on the
  716. # same filesystem (we're staying inside dst_key.parent).
  717. os.replace(str(tmp_key), str(dst_key))
  718. # S9: warn if the FS doesn't enforce 0o600
  719. actual_mode = dst_key.stat().st_mode & 0o777
  720. if actual_mode != 0o600:
  721. logger.warning(
  722. "Restored MFA key file %s: filesystem did not enforce 0o600 "
  723. "(actual: 0o%o). Key may be world-readable on Windows / SMB / FUSE.",
  724. dst_key,
  725. actual_mode,
  726. )
  727. logger.info("Restored .mfa_encryption_key from backup")
  728. except OSError as e:
  729. logger.error(
  730. "Could not write restored MFA key file to %s: %s — "
  731. "aborting BEFORE database swap (DB unchanged).",
  732. dst_key,
  733. e,
  734. exc_info=True,
  735. )
  736. raise HTTPException(
  737. status_code=500,
  738. detail=("Restore aborted: MFA key write failed. Database is unchanged. Check server logs."),
  739. ) from e
  740. # 5. Replace database
  741. logger.info("Restoring database from backup...")
  742. if is_sqlite():
  743. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  744. # Use SQLite's online backup API instead of shutil.copy2.
  745. # The pragma at database.py:19 runs the live DB in WAL mode,
  746. # which means a naive file copy is unsafe: anything written
  747. # to the live DB before this call that hasn't been
  748. # checkpointed yet (seed_default_groups + init_db on first
  749. # start, plus whatever background heartbeats wrote during
  750. # the request window) sits in bambuddy.db-wal with valid
  751. # checksums. The route handler's own `db: Depends(get_db)`
  752. # session also keeps a connection checked out across
  753. # engine.dispose(), holding fds to the WAL inode. With
  754. # `shutil.copy2` SQLite finds the stale WAL on the next
  755. # open and silently re-applies those page-level writes on
  756. # top of the restored DB, partially clobbering it with
  757. # fresh-install state — the user sees a "successful"
  758. # restore where most rows and settings have reverted to
  759. # defaults (#1211 / #668). The page-by-page backup API
  760. # opens both DBs as real SQLite connections, takes the
  761. # right locks, and routes new pages through the live DB's
  762. # own WAL — so concurrent open sessions see their own
  763. # snapshot until they close (transaction isolation) but
  764. # can't corrupt the restored state.
  765. import sqlite3
  766. src_conn = sqlite3.connect(str(backup_db))
  767. try:
  768. dst_conn = sqlite3.connect(str(db_path))
  769. try:
  770. src_conn.backup(dst_conn)
  771. finally:
  772. dst_conn.close()
  773. finally:
  774. src_conn.close()
  775. else:
  776. # Import SQLite backup into PostgreSQL
  777. logger.info("Importing SQLite backup into PostgreSQL...")
  778. await _import_sqlite_to_postgres(backup_db, app_settings.database_url)
  779. # 6. Replace data directories
  780. # For Docker compatibility: clear contents then copy (don't delete mount points)
  781. dirs_to_restore = [
  782. ("archive", base_dir / "archive"),
  783. ("virtual_printer", base_dir / "virtual_printer"),
  784. ("plate_calibration", app_settings.plate_calibration_dir),
  785. ("icons", base_dir / "icons"),
  786. ("projects", base_dir / "projects"),
  787. ]
  788. skipped_dirs = []
  789. for name, dest_dir in dirs_to_restore:
  790. src_dir = temp_path / name
  791. if src_dir.exists():
  792. logger.info("Restoring %s directory...", name)
  793. try:
  794. # Clear destination contents (not the dir itself - may be Docker mount)
  795. if dest_dir.exists():
  796. for item in dest_dir.iterdir():
  797. try:
  798. if item.is_dir():
  799. shutil.rmtree(item)
  800. else:
  801. item.unlink()
  802. except OSError as e:
  803. logger.warning("Could not delete %s: %s", item, e)
  804. else:
  805. dest_dir.mkdir(parents=True, exist_ok=True)
  806. # Copy contents from backup
  807. for item in src_dir.iterdir():
  808. dest_item = dest_dir / item.name
  809. if item.is_dir():
  810. shutil.copytree(item, dest_item)
  811. else:
  812. shutil.copy2(item, dest_item)
  813. except OSError as e:
  814. logger.warning("Could not restore %s directory: %s", name, e)
  815. skipped_dirs.append(name)
  816. # 7. Reset the encryption singleton so the migration that runs
  817. # inside init_db() picks up the restored key file (if a new one
  818. # was written above). Without this reset, _get_fernet would
  819. # return the cached Fernet instance built from the previous key.
  820. import backend.app.core.encryption as _enc_mod
  821. _enc_mod._fernet_instance = None
  822. _enc_mod._key_source = None
  823. _enc_mod._warn_shown = False
  824. # 8. Reinitialize the database engine and apply schema migrations so that
  825. # tables added after the backup was created (e.g. ams_labels) exist
  826. # immediately, without requiring a manual restart.
  827. await reinitialize_database()
  828. await init_db()
  829. logger.info("Restore complete - restart required")
  830. message = "Backup restored successfully. Please restart Bambuddy for changes to take effect."
  831. if skipped_dirs:
  832. message += f" Note: Some directories could not be restored ({', '.join(skipped_dirs)})."
  833. return {
  834. "success": True,
  835. "message": message,
  836. }
  837. except HTTPException:
  838. # Preserve specific HTTP error responses raised inside the restore
  839. # body (e.g. the key-write OSError → 500). The blanket
  840. # except Exception below would otherwise swallow them and replace
  841. # the operator-facing detail with a generic message.
  842. raise
  843. except Exception as e:
  844. logger.error("Restore failed: %s", e, exc_info=True)
  845. return JSONResponse(
  846. status_code=500,
  847. content={"success": False, "message": "Restore failed. Check server logs for details."},
  848. )
  849. @router.get("/network-interfaces")
  850. async def get_network_interfaces(
  851. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  852. ):
  853. """Get available network interfaces with all IPs (primary + aliases)."""
  854. from backend.app.services.network_utils import get_all_interface_ips
  855. interfaces = get_all_interface_ips()
  856. return {"interfaces": interfaces}
  857. @router.get("/virtual-printer/models")
  858. async def get_virtual_printer_models(
  859. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  860. ):
  861. """Get available virtual printer models."""
  862. from backend.app.services.virtual_printer import (
  863. DEFAULT_VIRTUAL_PRINTER_MODEL,
  864. VIRTUAL_PRINTER_MODELS,
  865. )
  866. return {
  867. "models": VIRTUAL_PRINTER_MODELS,
  868. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  869. }
  870. @router.get("/virtual-printer")
  871. async def get_virtual_printer_settings(
  872. db: AsyncSession = Depends(get_db),
  873. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  874. ):
  875. """Get virtual printer settings and status."""
  876. from backend.app.services.virtual_printer import (
  877. DEFAULT_VIRTUAL_PRINTER_MODEL,
  878. virtual_printer_manager,
  879. )
  880. enabled = await get_setting(db, "virtual_printer_enabled")
  881. access_code = await get_setting(db, "virtual_printer_access_code")
  882. mode = await get_setting(db, "virtual_printer_mode")
  883. model = await get_setting(db, "virtual_printer_model")
  884. target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  885. remote_interface_ip = await get_setting(db, "virtual_printer_remote_interface_ip")
  886. tailscale_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  887. archive_name_source = await get_setting(db, "virtual_printer_archive_name_source")
  888. return {
  889. "enabled": enabled == "true" if enabled else False,
  890. "access_code_set": bool(access_code),
  891. "mode": mode or "immediate",
  892. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  893. "target_printer_id": int(target_printer_id) if target_printer_id else None,
  894. "remote_interface_ip": remote_interface_ip or "",
  895. "tailscale_disabled": tailscale_disabled_raw == "true" if tailscale_disabled_raw else True,
  896. "archive_name_source": archive_name_source if archive_name_source in ("metadata", "filename") else "metadata",
  897. "status": virtual_printer_manager.get_status(),
  898. }
  899. @router.put("/virtual-printer")
  900. async def update_virtual_printer_settings(
  901. enabled: bool = None,
  902. access_code: str = None,
  903. mode: str = None,
  904. model: str = None,
  905. target_printer_id: int = None,
  906. remote_interface_ip: str = None,
  907. tailscale_disabled: bool = None,
  908. archive_name_source: str = None,
  909. db: AsyncSession = Depends(get_db),
  910. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  911. ):
  912. """Update virtual printer settings and restart services if needed.
  913. For proxy mode with SSDP proxy (dual-homed setup):
  914. - remote_interface_ip: IP of interface on slicer's network (LAN B)
  915. - Local interface is auto-detected based on target printer IP
  916. """
  917. from sqlalchemy import select
  918. from backend.app.models.printer import Printer
  919. from backend.app.services.virtual_printer import (
  920. DEFAULT_VIRTUAL_PRINTER_MODEL,
  921. VIRTUAL_PRINTER_MODELS,
  922. virtual_printer_manager,
  923. )
  924. # Get current values
  925. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  926. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  927. current_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  928. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  929. current_target_id_str = await get_setting(db, "virtual_printer_target_printer_id")
  930. current_target_id = int(current_target_id_str) if current_target_id_str else None
  931. current_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  932. current_ts_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  933. # Default True (opt-in) when the setting has never been saved — matches the model default.
  934. current_ts_disabled = current_ts_disabled_raw == "true" if current_ts_disabled_raw else True
  935. # Apply updates
  936. new_enabled = enabled if enabled is not None else current_enabled
  937. new_access_code = access_code if access_code is not None else current_access_code
  938. new_mode = mode if mode is not None else current_mode
  939. new_model = model if model is not None else current_model
  940. new_target_id = target_printer_id if target_printer_id is not None else current_target_id
  941. new_remote_iface = remote_interface_ip if remote_interface_ip is not None else current_remote_iface
  942. new_ts_disabled = tailscale_disabled if tailscale_disabled is not None else current_ts_disabled
  943. # Validate mode
  944. # "review" is the new name for "queue" (pending review before archiving)
  945. # "print_queue" archives and adds to print queue (unassigned)
  946. # "proxy" is transparent TCP proxy to a real printer
  947. if new_mode not in ("immediate", "queue", "review", "print_queue", "proxy"):
  948. return JSONResponse(
  949. status_code=400,
  950. content={"detail": "Mode must be 'immediate', 'review', 'print_queue', or 'proxy'"},
  951. )
  952. # Validate archive_name_source
  953. if archive_name_source is not None and archive_name_source not in ("metadata", "filename"):
  954. return JSONResponse(
  955. status_code=400,
  956. content={"detail": "archive_name_source must be 'metadata' or 'filename'"},
  957. )
  958. # Normalize legacy "queue" to "review" for storage
  959. if new_mode == "queue":
  960. new_mode = "review"
  961. # Validate model
  962. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  963. return JSONResponse(
  964. status_code=400,
  965. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  966. )
  967. # Mode-specific validation and printer lookup
  968. target_printer_ip = ""
  969. target_printer_serial = ""
  970. if new_mode == "proxy":
  971. # Proxy mode requires target printer when enabling
  972. if new_enabled and not new_target_id:
  973. # If just switching to proxy mode (not explicitly enabling), auto-disable
  974. if enabled is None:
  975. new_enabled = False
  976. else:
  977. return JSONResponse(
  978. status_code=400,
  979. content={"detail": "Target printer is required for proxy mode"},
  980. )
  981. # Look up printer IP and serial if we have a target
  982. if new_target_id:
  983. result = await db.execute(select(Printer).where(Printer.id == new_target_id))
  984. printer = result.scalar_one_or_none()
  985. if not printer:
  986. return JSONResponse(
  987. status_code=400,
  988. content={"detail": f"Printer with ID {new_target_id} not found"},
  989. )
  990. target_printer_ip = printer.ip_address
  991. target_printer_serial = printer.serial_number
  992. # Access code not required for proxy mode
  993. else:
  994. # Non-proxy modes require access code when enabling
  995. if new_enabled and not new_access_code:
  996. # If just switching modes (not explicitly enabling), auto-disable
  997. if enabled is None:
  998. new_enabled = False
  999. else:
  1000. return JSONResponse(
  1001. status_code=400,
  1002. content={"detail": "Access code is required when enabling virtual printer"},
  1003. )
  1004. # Validate access code length (Bambu Studio requires exactly 8 characters)
  1005. if access_code is not None and access_code and len(access_code) != 8:
  1006. return JSONResponse(
  1007. status_code=400,
  1008. content={"detail": "Access code must be exactly 8 characters"},
  1009. )
  1010. # Save settings
  1011. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  1012. if access_code is not None:
  1013. await set_setting(db, "virtual_printer_access_code", access_code)
  1014. await set_setting(db, "virtual_printer_mode", new_mode)
  1015. if model is not None:
  1016. await set_setting(db, "virtual_printer_model", model)
  1017. if target_printer_id is not None:
  1018. await set_setting(db, "virtual_printer_target_printer_id", str(target_printer_id))
  1019. if remote_interface_ip is not None:
  1020. await set_setting(db, "virtual_printer_remote_interface_ip", remote_interface_ip)
  1021. if tailscale_disabled is not None:
  1022. await set_setting(db, "virtual_printer_tailscale_disabled", "true" if tailscale_disabled else "false")
  1023. if archive_name_source is not None:
  1024. await set_setting(db, "virtual_printer_archive_name_source", archive_name_source)
  1025. # Propagate tailscale_disabled to the first VirtualPrinter row so sync_from_db() picks it up
  1026. if tailscale_disabled is not None:
  1027. from backend.app.models.virtual_printer import VirtualPrinter as VPModel
  1028. vp_result = await db.execute(select(VPModel).order_by(VPModel.position).limit(1))
  1029. first_vp = vp_result.scalar_one_or_none()
  1030. if first_vp is not None:
  1031. first_vp.tailscale_disabled = new_ts_disabled
  1032. await db.commit()
  1033. db.expire_all()
  1034. # Reconfigure virtual printer
  1035. try:
  1036. await virtual_printer_manager.configure(
  1037. enabled=new_enabled,
  1038. access_code=new_access_code,
  1039. mode=new_mode,
  1040. model=new_model,
  1041. target_printer_ip=target_printer_ip,
  1042. target_printer_serial=target_printer_serial,
  1043. remote_interface_ip=new_remote_iface,
  1044. )
  1045. except ValueError as e:
  1046. logger.warning("Virtual printer configuration validation error: %s", e)
  1047. return JSONResponse(
  1048. status_code=400,
  1049. content={"detail": "Invalid virtual printer configuration. Check the provided values."},
  1050. )
  1051. except Exception as e:
  1052. logger.error("Failed to configure virtual printer: %s", e, exc_info=True)
  1053. return JSONResponse(
  1054. status_code=500,
  1055. content={"detail": "Failed to configure virtual printer. Check server logs for details."},
  1056. )
  1057. return await get_virtual_printer_settings(db)
  1058. # =============================================================================
  1059. # MQTT Relay Settings
  1060. # =============================================================================
  1061. @router.get("/mqtt/status")
  1062. async def get_mqtt_status(
  1063. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1064. ):
  1065. """Get MQTT relay connection status."""
  1066. from backend.app.services.mqtt_relay import mqtt_relay
  1067. return mqtt_relay.get_status()