settings.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. @router.get("/check-ffmpeg")
  220. async def check_ffmpeg():
  221. """Check if ffmpeg is installed and available."""
  222. from backend.app.services.camera import get_ffmpeg_path
  223. ffmpeg_path = get_ffmpeg_path()
  224. return {
  225. "installed": ffmpeg_path is not None,
  226. "path": ffmpeg_path,
  227. }
  228. @router.get("/spoolman")
  229. async def get_spoolman_settings(
  230. db: AsyncSession = Depends(get_db),
  231. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  232. ):
  233. """Get Spoolman integration settings."""
  234. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  235. spoolman_url = await get_setting(db, "spoolman_url") or ""
  236. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  237. spoolman_disable_weight_sync = await get_setting(db, "spoolman_disable_weight_sync") or "false"
  238. spoolman_report_partial_usage = await get_setting(db, "spoolman_report_partial_usage") or "true"
  239. return {
  240. "spoolman_enabled": spoolman_enabled,
  241. "spoolman_url": spoolman_url,
  242. "spoolman_sync_mode": spoolman_sync_mode,
  243. "spoolman_disable_weight_sync": spoolman_disable_weight_sync,
  244. "spoolman_report_partial_usage": spoolman_report_partial_usage,
  245. }
  246. @router.put("/spoolman")
  247. async def update_spoolman_settings(
  248. settings: dict,
  249. db: AsyncSession = Depends(get_db),
  250. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  251. ):
  252. """Update Spoolman integration settings."""
  253. if "spoolman_enabled" in settings:
  254. old_val = await get_setting(db, "spoolman_enabled") or "false"
  255. new_val = settings["spoolman_enabled"]
  256. await set_setting(db, "spoolman_enabled", new_val)
  257. # Switching to Spoolman: clear built-in inventory slot assignments
  258. if old_val.lower() != "true" and new_val.lower() == "true":
  259. from backend.app.models.spool_assignment import SpoolAssignment
  260. result = await db.execute(delete(SpoolAssignment))
  261. logger.info("Cleared %d spool assignments on switch to Spoolman mode", result.rowcount)
  262. if "spoolman_url" in settings:
  263. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  264. if "spoolman_sync_mode" in settings:
  265. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  266. if "spoolman_disable_weight_sync" in settings:
  267. await set_setting(db, "spoolman_disable_weight_sync", settings["spoolman_disable_weight_sync"])
  268. if "spoolman_report_partial_usage" in settings:
  269. await set_setting(db, "spoolman_report_partial_usage", settings["spoolman_report_partial_usage"])
  270. await db.commit()
  271. db.expire_all()
  272. # Return updated settings
  273. return await get_spoolman_settings(db)
  274. async def get_homeassistant_settings(db: AsyncSession) -> dict:
  275. """
  276. Get Home Assistant integration settings.
  277. Environment variables (HA_URL, HA_TOKEN) take precedence over database settings.
  278. """
  279. import os
  280. # Check environment variables first
  281. ha_url_env = os.environ.get("HA_URL")
  282. ha_token_env = os.environ.get("HA_TOKEN")
  283. # Fall back to database values
  284. ha_url = ha_url_env or await get_setting(db, "ha_url") or ""
  285. ha_token = ha_token_env or await get_setting(db, "ha_token") or ""
  286. ha_enabled_db = await get_setting(db, "ha_enabled") or "false"
  287. # Track which settings come from environment
  288. ha_url_from_env = bool(ha_url_env)
  289. ha_token_from_env = bool(ha_token_env)
  290. ha_env_managed = ha_url_from_env and ha_token_from_env
  291. # Auto-enable when both env vars are set, otherwise use database value
  292. if ha_url_env and ha_token_env:
  293. ha_enabled = True
  294. else:
  295. ha_enabled = ha_enabled_db.lower() == "true"
  296. return {
  297. "ha_enabled": ha_enabled,
  298. "ha_url": ha_url,
  299. "ha_token": ha_token,
  300. "ha_url_from_env": ha_url_from_env,
  301. "ha_token_from_env": ha_token_from_env,
  302. "ha_env_managed": ha_env_managed,
  303. }
  304. async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]:
  305. """Create a complete backup ZIP (database + all data directories).
  306. If output_path is given, the ZIP is written there.
  307. Otherwise a temporary file is created (caller must clean up).
  308. Returns (zip_path, filename).
  309. """
  310. import shutil
  311. import tempfile
  312. from backend.app.core.db_dialect import is_sqlite
  313. base_dir = app_settings.base_dir
  314. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  315. with tempfile.TemporaryDirectory() as temp_dir:
  316. temp_path = Path(temp_dir)
  317. if is_sqlite():
  318. from sqlalchemy import text
  319. from backend.app.core.database import engine
  320. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  321. # Checkpoint WAL to ensure all data is in main db file
  322. async with engine.begin() as conn:
  323. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  324. # Copy database file
  325. shutil.copy2(db_path, temp_path / "bambuddy.db")
  326. else:
  327. # PostgreSQL: export to a portable SQLite file via SQLAlchemy.
  328. # This makes backups restorable on both SQLite and Postgres installs.
  329. import json
  330. import sqlite3
  331. from backend.app.core.database import Base, engine
  332. backup_db_path = temp_path / "bambuddy.db"
  333. dst = sqlite3.connect(str(backup_db_path))
  334. metadata = Base.metadata
  335. # Create tables in SQLite backup (simplified — just column names and types)
  336. for table in metadata.sorted_tables:
  337. cols = []
  338. pk_cols = [col.name for col in table.columns if col.primary_key]
  339. for col in table.columns:
  340. col_type = "TEXT" # Default
  341. type_str = str(col.type).upper()
  342. if "INT" in type_str:
  343. col_type = "INTEGER"
  344. elif "FLOAT" in type_str or "REAL" in type_str or "NUMERIC" in type_str:
  345. col_type = "REAL"
  346. elif "BOOL" in type_str:
  347. col_type = "BOOLEAN"
  348. # Only inline PRIMARY KEY for single-column PKs
  349. pk = " PRIMARY KEY" if col.primary_key and len(pk_cols) == 1 else ""
  350. cols.append(f"{col.name} {col_type}{pk}")
  351. # Add composite primary key constraint if needed
  352. if len(pk_cols) > 1:
  353. cols.append(f"PRIMARY KEY ({', '.join(pk_cols)})")
  354. dst.execute(f"CREATE TABLE IF NOT EXISTS {table.name} ({', '.join(cols)})") # noqa: S608
  355. # Export data from Postgres to SQLite
  356. async with engine.connect() as conn:
  357. for table in metadata.sorted_tables:
  358. result = await conn.execute(table.select())
  359. rows = result.fetchall()
  360. if not rows:
  361. continue
  362. columns = list(result.keys())
  363. placeholders = ", ".join(["?"] * len(columns))
  364. col_list = ", ".join(columns)
  365. insert_sql = f"INSERT INTO {table.name} ({col_list}) VALUES ({placeholders})" # noqa: S608 # nosec B608 — table/column names from ORM metadata, not user input
  366. def _serialize_row(row):
  367. return tuple(json.dumps(v) if isinstance(v, (list, dict)) else v for v in row)
  368. dst.executemany(insert_sql, [_serialize_row(row) for row in rows])
  369. dst.commit()
  370. dst.close()
  371. logger.info("PostgreSQL backup exported to portable SQLite format")
  372. # Copy data directories (if they exist)
  373. dirs_to_backup = [
  374. ("archive", base_dir / "archive"),
  375. ("virtual_printer", base_dir / "virtual_printer"),
  376. ("plate_calibration", app_settings.plate_calibration_dir),
  377. ("icons", base_dir / "icons"),
  378. ("projects", base_dir / "projects"),
  379. ]
  380. for name, src_dir in dirs_to_backup:
  381. if src_dir.exists() and any(src_dir.iterdir()):
  382. try:
  383. shutil.copytree(src_dir, temp_path / name)
  384. except shutil.Error as e:
  385. logger.warning("Some files in %s could not be copied: %s", name, e)
  386. except PermissionError as e:
  387. logger.warning("Permission denied copying %s: %s", name, e)
  388. # Create ZIP
  389. if output_path is not None:
  390. zip_file = output_path / filename
  391. else:
  392. fd, tmp = tempfile.mkstemp(suffix=".zip")
  393. os.close(fd)
  394. zip_file = Path(tmp)
  395. with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
  396. for file_path in temp_path.rglob("*"):
  397. if file_path.is_file():
  398. arcname = file_path.relative_to(temp_path)
  399. zf.write(file_path, arcname)
  400. return zip_file, filename
  401. @router.get("/backup")
  402. async def create_backup(
  403. db: AsyncSession = Depends(get_db),
  404. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_BACKUP),
  405. ):
  406. """Create a complete backup (database + all files) as a ZIP download."""
  407. from starlette.background import BackgroundTask
  408. try:
  409. zip_file, filename = await create_backup_zip()
  410. return FileResponse(
  411. path=zip_file,
  412. filename=filename,
  413. media_type="application/zip",
  414. background=BackgroundTask(lambda: zip_file.unlink(missing_ok=True)),
  415. )
  416. except Exception as e:
  417. logger.error("Backup failed: %s", e, exc_info=True)
  418. return JSONResponse(
  419. status_code=500,
  420. content={"success": False, "message": "Backup failed. Check server logs for details."},
  421. )
  422. async def _import_sqlite_to_postgres(sqlite_path: Path, postgres_url: str):
  423. """Import data from a SQLite database file into the current PostgreSQL database.
  424. Used for cross-database restore (SQLite backup → PostgreSQL).
  425. Reads all tables from the SQLite file and bulk-inserts into Postgres.
  426. """
  427. import sqlite3
  428. from sqlalchemy import text
  429. from backend.app.core.database import Base, _create_engine
  430. # Create a temporary engine for the import (current engine was disposed)
  431. pg_engine = _create_engine()
  432. try:
  433. # Open SQLite file directly (sync — it's a local file read)
  434. src = sqlite3.connect(str(sqlite_path))
  435. src.row_factory = sqlite3.Row
  436. # Get list of tables from SQLite (skip internal/FTS tables)
  437. cursor = src.execute(
  438. "SELECT name FROM sqlite_master WHERE type='table' "
  439. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  440. )
  441. src_tables = {row["name"] for row in cursor.fetchall()}
  442. # Get Postgres tables from our ORM models
  443. metadata = Base.metadata
  444. pg_tables = set(metadata.tables.keys())
  445. # Only import tables that exist in both source and destination
  446. tables_to_import = src_tables & pg_tables
  447. sorted_tables = [t.name for t in metadata.sorted_tables if t.name in tables_to_import]
  448. # Phase 1: Drop all tables and recreate WITHOUT foreign keys.
  449. # This avoids all FK ordering/orphan issues during import.
  450. saved_fks = {}
  451. for table in metadata.sorted_tables:
  452. fks = list(table.foreign_key_constraints)
  453. if fks:
  454. saved_fks[table.name] = fks
  455. for fk in fks:
  456. table.constraints.discard(fk)
  457. async with pg_engine.begin() as conn:
  458. # Drop every existing table in the public schema with CASCADE
  459. # rather than `metadata.drop_all`. Two reasons:
  460. # 1. The user's live DB may carry orphan tables from removed
  461. # features (e.g. the legacy `spoolman_slot_assignments`,
  462. # `spoolman_k_profile`) that hold FK constraints back to
  463. # ORM tables. `drop_all` doesn't know they exist and emits
  464. # `DROP TABLE printers` without CASCADE — Postgres refuses
  465. # and the whole restore aborts (#XXXX).
  466. # 2. Even within the metadata, `drop_all` is FK-ordered and
  467. # breaks if a future schema rename leaves old constraints
  468. # around. CASCADE is the right tool for a destructive
  469. # restore: the user is intentionally wiping state.
  470. await conn.execute(
  471. text(
  472. "DO $$ DECLARE r RECORD; BEGIN "
  473. "FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP "
  474. "EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE'; "
  475. "END LOOP; END $$;"
  476. )
  477. )
  478. await conn.run_sync(metadata.create_all)
  479. # Restore FK definitions in metadata (needed for re-adding later)
  480. for table_name, fks in saved_fks.items():
  481. table_obj = metadata.tables[table_name]
  482. for fk in fks:
  483. table_obj.constraints.add(fk)
  484. # Phase 2: Import data (no FKs to worry about)
  485. async with pg_engine.begin() as conn:
  486. # Import each table in dependency order (parents before children)
  487. for table_name in sorted_tables:
  488. rows = src.execute(f"SELECT * FROM {table_name}").fetchall() # noqa: S608 # nosec B608
  489. if not rows:
  490. continue
  491. # Filter to columns that exist in the Postgres table
  492. src_columns = rows[0].keys()
  493. pg_table = metadata.tables.get(table_name)
  494. pg_columns = {c.name for c in pg_table.columns} if pg_table is not None else set()
  495. columns = [c for c in src_columns if c in pg_columns]
  496. if not columns:
  497. continue
  498. col_list = ", ".join(columns)
  499. param_list = ", ".join(f":{c}" for c in columns)
  500. # ON CONFLICT DO NOTHING handles duplicate rows from SQLite (which doesn't enforce unique constraints)
  501. insert_sql = text(f"INSERT INTO {table_name} ({col_list}) VALUES ({param_list}) ON CONFLICT DO NOTHING") # noqa: S608 # nosec B608
  502. # Identify columns that need type conversion (SQLite stores booleans
  503. # as int and datetimes as str — asyncpg requires native Python types)
  504. from datetime import datetime as dt
  505. bool_columns = set()
  506. datetime_columns = set()
  507. not_null_defaults = {} # col_name -> default value for NOT NULL columns
  508. if pg_table is not None:
  509. for col in pg_table.columns:
  510. if col.name not in columns:
  511. continue
  512. col_type = str(col.type)
  513. if col_type == "BOOLEAN":
  514. bool_columns.add(col.name)
  515. elif col_type in ("DATETIME", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE"):
  516. datetime_columns.add(col.name)
  517. # Track NOT NULL columns with defaults — older backups may have NULL
  518. # for columns added after the backup was created
  519. if not col.nullable:
  520. if col.default is not None:
  521. default = col.default.arg
  522. if callable(default):
  523. default = default(None)
  524. not_null_defaults[col.name] = default
  525. elif col.server_default is not None:
  526. # server_default=func.now() → use current timestamp
  527. if col.name in datetime_columns:
  528. not_null_defaults[col.name] = "__now__"
  529. else:
  530. # Try to extract literal server default
  531. sd = str(col.server_default.arg) if hasattr(col.server_default, "arg") else None
  532. if sd is not None:
  533. not_null_defaults[col.name] = sd
  534. now = dt.now()
  535. def _convert_row(
  536. row, cols=columns, bools=bool_columns, dts=datetime_columns, nn_defaults=not_null_defaults, _now=now
  537. ):
  538. result = {}
  539. for c in cols:
  540. val = row[c]
  541. if val is None and c in nn_defaults:
  542. val = _now if nn_defaults[c] == "__now__" else nn_defaults[c]
  543. if val is not None:
  544. if c in bools:
  545. val = bool(val)
  546. elif c in dts and isinstance(val, str):
  547. try:
  548. val = dt.fromisoformat(val)
  549. except ValueError:
  550. pass
  551. result[c] = val
  552. return result
  553. batch = [_convert_row(row) for row in rows]
  554. await conn.execute(insert_sql, batch)
  555. logger.info("Imported %d rows into %s", len(batch), table_name)
  556. # Reset sequences to max(id) + 1 for each table with an id column
  557. for table_name in sorted_tables:
  558. try:
  559. async with conn.begin_nested():
  560. result = await conn.execute(text(f"SELECT MAX(id) FROM {table_name}")) # noqa: S608 # nosec B608
  561. max_id = result.scalar()
  562. if max_id is not None:
  563. seq_name = f"{table_name}_id_seq"
  564. await conn.execute(text(f"SELECT setval('{seq_name}', {max_id})")) # noqa: S608
  565. except Exception:
  566. pass # Table may not have an id column or sequence
  567. src.close()
  568. logger.info("Cross-database import complete: %d tables imported", len(tables_to_import))
  569. # Recreate FK constraints from ORM metadata (not from saved definitions).
  570. # Use individual transactions so orphaned SQLite data doesn't block valid FKs.
  571. from sqlalchemy.schema import AddConstraint
  572. failed_fks = []
  573. for table in metadata.sorted_tables:
  574. for fk in table.foreign_key_constraints:
  575. try:
  576. async with pg_engine.begin() as fk_conn:
  577. await fk_conn.execute(AddConstraint(fk))
  578. except Exception:
  579. failed_fks.append(f"{table.name}.{fk.name}")
  580. if failed_fks:
  581. logger.warning(
  582. "Could not restore %d FK constraints (orphaned data in SQLite): %s",
  583. len(failed_fks),
  584. ", ".join(failed_fks),
  585. )
  586. finally:
  587. await pg_engine.dispose()
  588. @router.post("/restore")
  589. async def restore_backup(
  590. file: UploadFile = File(...),
  591. db: AsyncSession = Depends(get_db),
  592. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_RESTORE),
  593. ):
  594. """Restore from a complete backup ZIP.
  595. Replaces the database and all data directories from the backup ZIP.
  596. Requires a restart after restore.
  597. """
  598. import shutil
  599. import tempfile
  600. from fastapi import HTTPException
  601. from backend.app.core.database import close_all_connections, init_db, reinitialize_database
  602. from backend.app.core.db_dialect import is_sqlite
  603. from backend.app.services.virtual_printer import virtual_printer_manager
  604. base_dir = app_settings.base_dir
  605. with tempfile.TemporaryDirectory() as temp_dir:
  606. temp_path = Path(temp_dir)
  607. # 1. Read and extract ZIP
  608. content = await file.read()
  609. # Check if it's a valid ZIP
  610. if not file.filename or not file.filename.endswith(".zip"):
  611. raise HTTPException(400, "Invalid backup file: must be a .zip file")
  612. try:
  613. with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
  614. zf.extractall(temp_path)
  615. except zipfile.BadZipFile:
  616. raise HTTPException(400, "Invalid backup file: not a valid ZIP")
  617. # 2. Validate backup
  618. backup_db = temp_path / "bambuddy.db"
  619. if not backup_db.exists():
  620. raise HTTPException(400, "Invalid backup: missing bambuddy.db")
  621. try:
  622. import asyncio
  623. # 3. Stop virtual printer if running (releases file locks)
  624. try:
  625. if virtual_printer_manager.is_enabled:
  626. logger.info("Stopping virtual printer for restore...")
  627. await virtual_printer_manager.configure(enabled=False)
  628. await asyncio.sleep(1)
  629. except Exception as e:
  630. logger.warning("Failed to stop virtual printer: %s", e)
  631. # 4. Close current database connections
  632. logger.info("Closing database connections...")
  633. await close_all_connections()
  634. # 5. Replace database
  635. logger.info("Restoring database from backup...")
  636. if is_sqlite():
  637. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  638. # Use SQLite's online backup API instead of shutil.copy2.
  639. # The pragma at database.py:19 runs the live DB in WAL mode,
  640. # which means a naive file copy is unsafe: anything written
  641. # to the live DB before this call that hasn't been
  642. # checkpointed yet (seed_default_groups + init_db on first
  643. # start, plus whatever background heartbeats wrote during
  644. # the request window) sits in bambuddy.db-wal with valid
  645. # checksums. The route handler's own `db: Depends(get_db)`
  646. # session also keeps a connection checked out across
  647. # engine.dispose(), holding fds to the WAL inode. With
  648. # `shutil.copy2` SQLite finds the stale WAL on the next
  649. # open and silently re-applies those page-level writes on
  650. # top of the restored DB, partially clobbering it with
  651. # fresh-install state — the user sees a "successful"
  652. # restore where most rows and settings have reverted to
  653. # defaults (#1211 / #668). The page-by-page backup API
  654. # opens both DBs as real SQLite connections, takes the
  655. # right locks, and routes new pages through the live DB's
  656. # own WAL — so concurrent open sessions see their own
  657. # snapshot until they close (transaction isolation) but
  658. # can't corrupt the restored state.
  659. import sqlite3
  660. src_conn = sqlite3.connect(str(backup_db))
  661. try:
  662. dst_conn = sqlite3.connect(str(db_path))
  663. try:
  664. src_conn.backup(dst_conn)
  665. finally:
  666. dst_conn.close()
  667. finally:
  668. src_conn.close()
  669. else:
  670. # Import SQLite backup into PostgreSQL
  671. logger.info("Importing SQLite backup into PostgreSQL...")
  672. await _import_sqlite_to_postgres(backup_db, app_settings.database_url)
  673. # 6. Replace data directories
  674. # For Docker compatibility: clear contents then copy (don't delete mount points)
  675. dirs_to_restore = [
  676. ("archive", base_dir / "archive"),
  677. ("virtual_printer", base_dir / "virtual_printer"),
  678. ("plate_calibration", app_settings.plate_calibration_dir),
  679. ("icons", base_dir / "icons"),
  680. ("projects", base_dir / "projects"),
  681. ]
  682. skipped_dirs = []
  683. for name, dest_dir in dirs_to_restore:
  684. src_dir = temp_path / name
  685. if src_dir.exists():
  686. logger.info("Restoring %s directory...", name)
  687. try:
  688. # Clear destination contents (not the dir itself - may be Docker mount)
  689. if dest_dir.exists():
  690. for item in dest_dir.iterdir():
  691. try:
  692. if item.is_dir():
  693. shutil.rmtree(item)
  694. else:
  695. item.unlink()
  696. except OSError as e:
  697. logger.warning("Could not delete %s: %s", item, e)
  698. else:
  699. dest_dir.mkdir(parents=True, exist_ok=True)
  700. # Copy contents from backup
  701. for item in src_dir.iterdir():
  702. dest_item = dest_dir / item.name
  703. if item.is_dir():
  704. shutil.copytree(item, dest_item)
  705. else:
  706. shutil.copy2(item, dest_item)
  707. except OSError as e:
  708. logger.warning("Could not restore %s directory: %s", name, e)
  709. skipped_dirs.append(name)
  710. # 7. Reinitialize the database engine and apply schema migrations so that
  711. # tables added after the backup was created (e.g. ams_labels) exist
  712. # immediately, without requiring a manual restart.
  713. await reinitialize_database()
  714. await init_db()
  715. logger.info("Restore complete - restart required")
  716. message = "Backup restored successfully. Please restart Bambuddy for changes to take effect."
  717. if skipped_dirs:
  718. message += f" Note: Some directories could not be restored ({', '.join(skipped_dirs)})."
  719. return {
  720. "success": True,
  721. "message": message,
  722. }
  723. except Exception as e:
  724. logger.error("Restore failed: %s", e, exc_info=True)
  725. return JSONResponse(
  726. status_code=500,
  727. content={"success": False, "message": "Restore failed. Check server logs for details."},
  728. )
  729. @router.get("/network-interfaces")
  730. async def get_network_interfaces(
  731. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  732. ):
  733. """Get available network interfaces with all IPs (primary + aliases)."""
  734. from backend.app.services.network_utils import get_all_interface_ips
  735. interfaces = get_all_interface_ips()
  736. return {"interfaces": interfaces}
  737. @router.get("/virtual-printer/models")
  738. async def get_virtual_printer_models(
  739. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  740. ):
  741. """Get available virtual printer models."""
  742. from backend.app.services.virtual_printer import (
  743. DEFAULT_VIRTUAL_PRINTER_MODEL,
  744. VIRTUAL_PRINTER_MODELS,
  745. )
  746. return {
  747. "models": VIRTUAL_PRINTER_MODELS,
  748. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  749. }
  750. @router.get("/virtual-printer")
  751. async def get_virtual_printer_settings(
  752. db: AsyncSession = Depends(get_db),
  753. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  754. ):
  755. """Get virtual printer settings and status."""
  756. from backend.app.services.virtual_printer import (
  757. DEFAULT_VIRTUAL_PRINTER_MODEL,
  758. virtual_printer_manager,
  759. )
  760. enabled = await get_setting(db, "virtual_printer_enabled")
  761. access_code = await get_setting(db, "virtual_printer_access_code")
  762. mode = await get_setting(db, "virtual_printer_mode")
  763. model = await get_setting(db, "virtual_printer_model")
  764. target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  765. remote_interface_ip = await get_setting(db, "virtual_printer_remote_interface_ip")
  766. tailscale_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  767. archive_name_source = await get_setting(db, "virtual_printer_archive_name_source")
  768. return {
  769. "enabled": enabled == "true" if enabled else False,
  770. "access_code_set": bool(access_code),
  771. "mode": mode or "immediate",
  772. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  773. "target_printer_id": int(target_printer_id) if target_printer_id else None,
  774. "remote_interface_ip": remote_interface_ip or "",
  775. "tailscale_disabled": tailscale_disabled_raw == "true" if tailscale_disabled_raw else True,
  776. "archive_name_source": archive_name_source if archive_name_source in ("metadata", "filename") else "metadata",
  777. "status": virtual_printer_manager.get_status(),
  778. }
  779. @router.put("/virtual-printer")
  780. async def update_virtual_printer_settings(
  781. enabled: bool = None,
  782. access_code: str = None,
  783. mode: str = None,
  784. model: str = None,
  785. target_printer_id: int = None,
  786. remote_interface_ip: str = None,
  787. tailscale_disabled: bool = None,
  788. archive_name_source: str = None,
  789. db: AsyncSession = Depends(get_db),
  790. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  791. ):
  792. """Update virtual printer settings and restart services if needed.
  793. For proxy mode with SSDP proxy (dual-homed setup):
  794. - remote_interface_ip: IP of interface on slicer's network (LAN B)
  795. - Local interface is auto-detected based on target printer IP
  796. """
  797. from sqlalchemy import select
  798. from backend.app.models.printer import Printer
  799. from backend.app.services.virtual_printer import (
  800. DEFAULT_VIRTUAL_PRINTER_MODEL,
  801. VIRTUAL_PRINTER_MODELS,
  802. virtual_printer_manager,
  803. )
  804. # Get current values
  805. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  806. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  807. current_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  808. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  809. current_target_id_str = await get_setting(db, "virtual_printer_target_printer_id")
  810. current_target_id = int(current_target_id_str) if current_target_id_str else None
  811. current_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  812. current_ts_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  813. # Default True (opt-in) when the setting has never been saved — matches the model default.
  814. current_ts_disabled = current_ts_disabled_raw == "true" if current_ts_disabled_raw else True
  815. # Apply updates
  816. new_enabled = enabled if enabled is not None else current_enabled
  817. new_access_code = access_code if access_code is not None else current_access_code
  818. new_mode = mode if mode is not None else current_mode
  819. new_model = model if model is not None else current_model
  820. new_target_id = target_printer_id if target_printer_id is not None else current_target_id
  821. new_remote_iface = remote_interface_ip if remote_interface_ip is not None else current_remote_iface
  822. new_ts_disabled = tailscale_disabled if tailscale_disabled is not None else current_ts_disabled
  823. # Validate mode
  824. # "review" is the new name for "queue" (pending review before archiving)
  825. # "print_queue" archives and adds to print queue (unassigned)
  826. # "proxy" is transparent TCP proxy to a real printer
  827. if new_mode not in ("immediate", "queue", "review", "print_queue", "proxy"):
  828. return JSONResponse(
  829. status_code=400,
  830. content={"detail": "Mode must be 'immediate', 'review', 'print_queue', or 'proxy'"},
  831. )
  832. # Validate archive_name_source
  833. if archive_name_source is not None and archive_name_source not in ("metadata", "filename"):
  834. return JSONResponse(
  835. status_code=400,
  836. content={"detail": "archive_name_source must be 'metadata' or 'filename'"},
  837. )
  838. # Normalize legacy "queue" to "review" for storage
  839. if new_mode == "queue":
  840. new_mode = "review"
  841. # Validate model
  842. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  843. return JSONResponse(
  844. status_code=400,
  845. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  846. )
  847. # Mode-specific validation and printer lookup
  848. target_printer_ip = ""
  849. target_printer_serial = ""
  850. if new_mode == "proxy":
  851. # Proxy mode requires target printer when enabling
  852. if new_enabled and not new_target_id:
  853. # If just switching to proxy mode (not explicitly enabling), auto-disable
  854. if enabled is None:
  855. new_enabled = False
  856. else:
  857. return JSONResponse(
  858. status_code=400,
  859. content={"detail": "Target printer is required for proxy mode"},
  860. )
  861. # Look up printer IP and serial if we have a target
  862. if new_target_id:
  863. result = await db.execute(select(Printer).where(Printer.id == new_target_id))
  864. printer = result.scalar_one_or_none()
  865. if not printer:
  866. return JSONResponse(
  867. status_code=400,
  868. content={"detail": f"Printer with ID {new_target_id} not found"},
  869. )
  870. target_printer_ip = printer.ip_address
  871. target_printer_serial = printer.serial_number
  872. # Access code not required for proxy mode
  873. else:
  874. # Non-proxy modes require access code when enabling
  875. if new_enabled and not new_access_code:
  876. # If just switching modes (not explicitly enabling), auto-disable
  877. if enabled is None:
  878. new_enabled = False
  879. else:
  880. return JSONResponse(
  881. status_code=400,
  882. content={"detail": "Access code is required when enabling virtual printer"},
  883. )
  884. # Validate access code length (Bambu Studio requires exactly 8 characters)
  885. if access_code is not None and access_code and len(access_code) != 8:
  886. return JSONResponse(
  887. status_code=400,
  888. content={"detail": "Access code must be exactly 8 characters"},
  889. )
  890. # Save settings
  891. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  892. if access_code is not None:
  893. await set_setting(db, "virtual_printer_access_code", access_code)
  894. await set_setting(db, "virtual_printer_mode", new_mode)
  895. if model is not None:
  896. await set_setting(db, "virtual_printer_model", model)
  897. if target_printer_id is not None:
  898. await set_setting(db, "virtual_printer_target_printer_id", str(target_printer_id))
  899. if remote_interface_ip is not None:
  900. await set_setting(db, "virtual_printer_remote_interface_ip", remote_interface_ip)
  901. if tailscale_disabled is not None:
  902. await set_setting(db, "virtual_printer_tailscale_disabled", "true" if tailscale_disabled else "false")
  903. if archive_name_source is not None:
  904. await set_setting(db, "virtual_printer_archive_name_source", archive_name_source)
  905. # Propagate tailscale_disabled to the first VirtualPrinter row so sync_from_db() picks it up
  906. if tailscale_disabled is not None:
  907. from backend.app.models.virtual_printer import VirtualPrinter as VPModel
  908. vp_result = await db.execute(select(VPModel).order_by(VPModel.position).limit(1))
  909. first_vp = vp_result.scalar_one_or_none()
  910. if first_vp is not None:
  911. first_vp.tailscale_disabled = new_ts_disabled
  912. await db.commit()
  913. db.expire_all()
  914. # Reconfigure virtual printer
  915. try:
  916. await virtual_printer_manager.configure(
  917. enabled=new_enabled,
  918. access_code=new_access_code,
  919. mode=new_mode,
  920. model=new_model,
  921. target_printer_ip=target_printer_ip,
  922. target_printer_serial=target_printer_serial,
  923. remote_interface_ip=new_remote_iface,
  924. )
  925. except ValueError as e:
  926. logger.warning("Virtual printer configuration validation error: %s", e)
  927. return JSONResponse(
  928. status_code=400,
  929. content={"detail": "Invalid virtual printer configuration. Check the provided values."},
  930. )
  931. except Exception as e:
  932. logger.error("Failed to configure virtual printer: %s", e, exc_info=True)
  933. return JSONResponse(
  934. status_code=500,
  935. content={"detail": "Failed to configure virtual printer. Check server logs for details."},
  936. )
  937. return await get_virtual_printer_settings(db)
  938. # =============================================================================
  939. # MQTT Relay Settings
  940. # =============================================================================
  941. @router.get("/mqtt/status")
  942. async def get_mqtt_status(
  943. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  944. ):
  945. """Get MQTT relay connection status."""
  946. from backend.app.services.mqtt_relay import mqtt_relay
  947. return mqtt_relay.get_status()