settings.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. import io
  2. import logging
  3. import zipfile
  4. from datetime import datetime
  5. from pathlib import Path
  6. from fastapi import APIRouter, Depends, File, UploadFile
  7. from fastapi.responses import FileResponse, JSONResponse
  8. from sqlalchemy import delete, select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  11. from backend.app.core.config import settings as app_settings
  12. from backend.app.core.database import get_db
  13. from backend.app.core.permissions import Permission
  14. from backend.app.models.settings import Settings
  15. from backend.app.models.user import User
  16. from backend.app.schemas.settings import AppSettings, AppSettingsUpdate
  17. logger = logging.getLogger(__name__)
  18. router = APIRouter(prefix="/settings", tags=["settings"])
  19. # Default settings
  20. DEFAULT_SETTINGS = AppSettings()
  21. async def get_setting(db: AsyncSession, key: str) -> str | None:
  22. """Get a single setting value by key."""
  23. result = await db.execute(select(Settings).where(Settings.key == key))
  24. setting = result.scalar_one_or_none()
  25. return setting.value if setting else None
  26. async def get_external_login_url(db: AsyncSession) -> str:
  27. """Get the external URL for the login page.
  28. Uses external_url from settings if available, otherwise falls back to APP_URL env var.
  29. Args:
  30. db: Database session
  31. Returns:
  32. Full URL to the login page
  33. """
  34. import os
  35. external_url = await get_setting(db, "external_url")
  36. if external_url:
  37. external_url = external_url.rstrip("/")
  38. else:
  39. external_url = os.environ.get("APP_URL", "http://localhost:5173")
  40. return external_url + "/login"
  41. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  42. """Set a single setting value."""
  43. from backend.app.core.db_dialect import upsert_setting
  44. await upsert_setting(db, Settings, key, value)
  45. @router.get("", response_model=AppSettings)
  46. @router.get("/", response_model=AppSettings)
  47. async def get_settings(
  48. db: AsyncSession = Depends(get_db),
  49. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  50. ):
  51. """Get all application settings."""
  52. settings_dict = DEFAULT_SETTINGS.model_dump()
  53. # Load saved settings from database
  54. result = await db.execute(select(Settings))
  55. db_settings = result.scalars().all()
  56. for setting in db_settings:
  57. if setting.key in settings_dict:
  58. # Parse the value based on the expected type
  59. if setting.key in [
  60. "auto_archive",
  61. "save_thumbnails",
  62. "capture_finish_photo",
  63. "spoolman_enabled",
  64. "spoolman_disable_weight_sync",
  65. "spoolman_report_partial_usage",
  66. "disable_filament_warnings",
  67. "prefer_lowest_filament",
  68. "check_updates",
  69. "check_printer_firmware",
  70. "include_beta_updates",
  71. "virtual_printer_enabled",
  72. "ftp_retry_enabled",
  73. "mqtt_enabled",
  74. "mqtt_use_tls",
  75. "ha_enabled",
  76. "per_printer_mapping_expanded",
  77. "prometheus_enabled",
  78. "user_notifications_enabled",
  79. "queue_drying_enabled",
  80. "queue_drying_block",
  81. "ambient_drying_enabled",
  82. "require_plate_clear",
  83. "queue_shortest_first",
  84. "default_bed_levelling",
  85. "default_flow_cali",
  86. "default_vibration_cali",
  87. "default_layer_inspect",
  88. "default_timelapse",
  89. "ldap_enabled",
  90. "ldap_auto_provision",
  91. ]:
  92. settings_dict[setting.key] = setting.value.lower() == "true"
  93. elif setting.key in [
  94. "default_filament_cost",
  95. "energy_cost_per_kwh",
  96. "ams_temp_good",
  97. "ams_temp_fair",
  98. "library_disk_warning_gb",
  99. "low_stock_threshold",
  100. ]:
  101. settings_dict[setting.key] = float(setting.value)
  102. elif setting.key in [
  103. "ams_humidity_good",
  104. "ams_humidity_fair",
  105. "ams_history_retention_days",
  106. "ftp_retry_count",
  107. "ftp_retry_delay",
  108. "ftp_timeout",
  109. "mqtt_port",
  110. "stagger_group_size",
  111. "stagger_interval_minutes",
  112. ]:
  113. settings_dict[setting.key] = int(setting.value)
  114. elif setting.key == "default_printer_id":
  115. # Handle nullable integer
  116. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  117. else:
  118. settings_dict[setting.key] = setting.value
  119. # Get Home Assistant settings (with environment variable overrides)
  120. ha_settings = await get_homeassistant_settings(db)
  121. settings_dict.update(ha_settings)
  122. # Never return LDAP bind password in API responses
  123. settings_dict["ldap_bind_password"] = ""
  124. return AppSettings(**settings_dict)
  125. @router.put("/", response_model=AppSettings)
  126. async def update_settings(
  127. settings_update: AppSettingsUpdate,
  128. db: AsyncSession = Depends(get_db),
  129. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  130. ):
  131. """Update application settings."""
  132. update_data = settings_update.model_dump(exclude_unset=True)
  133. # Check if any MQTT settings are being updated
  134. mqtt_keys = {
  135. "mqtt_enabled",
  136. "mqtt_broker",
  137. "mqtt_port",
  138. "mqtt_username",
  139. "mqtt_password",
  140. "mqtt_topic_prefix",
  141. "mqtt_use_tls",
  142. }
  143. mqtt_updated = bool(mqtt_keys & set(update_data.keys()))
  144. for key, value in update_data.items():
  145. # Convert value to string for storage
  146. if isinstance(value, bool):
  147. str_value = "true" if value else "false"
  148. elif value is None:
  149. str_value = "None"
  150. else:
  151. str_value = str(value)
  152. await set_setting(db, key, str_value)
  153. await db.commit()
  154. # Expire all objects to ensure fresh reads after commit
  155. db.expire_all()
  156. # Reconfigure MQTT relay if any MQTT settings changed
  157. if mqtt_updated:
  158. try:
  159. from backend.app.services.mqtt_relay import mqtt_relay
  160. mqtt_settings = {
  161. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  162. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  163. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  164. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  165. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  166. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  167. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  168. }
  169. await mqtt_relay.configure(mqtt_settings)
  170. except Exception:
  171. pass # Don't fail the settings update if MQTT reconfiguration fails
  172. # Return updated settings
  173. return await get_settings(db)
  174. @router.patch("/", response_model=AppSettings)
  175. @router.patch("", response_model=AppSettings)
  176. async def patch_settings(
  177. settings_update: AppSettingsUpdate,
  178. db: AsyncSession = Depends(get_db),
  179. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  180. ):
  181. """Partially update application settings (same as PUT, for REST compatibility)."""
  182. return await update_settings(settings_update, db, _)
  183. @router.post("/reset", response_model=AppSettings)
  184. async def reset_settings(
  185. db: AsyncSession = Depends(get_db),
  186. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  187. ):
  188. """Reset all settings to defaults."""
  189. # Delete all settings
  190. result = await db.execute(select(Settings))
  191. for setting in result.scalars().all():
  192. await db.delete(setting)
  193. await db.commit()
  194. return DEFAULT_SETTINGS
  195. @router.get("/default-sidebar-order")
  196. async def get_default_sidebar_order(
  197. db: AsyncSession = Depends(get_db),
  198. ):
  199. """Get the admin-set default sidebar order.
  200. Intentionally unauthenticated: non-admin users need to read this value to apply
  201. the default sidebar order, but may lack SETTINGS_READ permission.
  202. The value is non-sensitive (sidebar item IDs only).
  203. """
  204. value = await get_setting(db, "default_sidebar_order")
  205. return {"default_sidebar_order": value or ""}
  206. @router.get("/check-ffmpeg")
  207. async def check_ffmpeg():
  208. """Check if ffmpeg is installed and available."""
  209. from backend.app.services.camera import get_ffmpeg_path
  210. ffmpeg_path = get_ffmpeg_path()
  211. return {
  212. "installed": ffmpeg_path is not None,
  213. "path": ffmpeg_path,
  214. }
  215. @router.get("/spoolman")
  216. async def get_spoolman_settings(
  217. db: AsyncSession = Depends(get_db),
  218. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  219. ):
  220. """Get Spoolman integration settings."""
  221. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  222. spoolman_url = await get_setting(db, "spoolman_url") or ""
  223. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  224. spoolman_disable_weight_sync = await get_setting(db, "spoolman_disable_weight_sync") or "false"
  225. spoolman_report_partial_usage = await get_setting(db, "spoolman_report_partial_usage") or "true"
  226. return {
  227. "spoolman_enabled": spoolman_enabled,
  228. "spoolman_url": spoolman_url,
  229. "spoolman_sync_mode": spoolman_sync_mode,
  230. "spoolman_disable_weight_sync": spoolman_disable_weight_sync,
  231. "spoolman_report_partial_usage": spoolman_report_partial_usage,
  232. }
  233. @router.put("/spoolman")
  234. async def update_spoolman_settings(
  235. settings: dict,
  236. db: AsyncSession = Depends(get_db),
  237. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  238. ):
  239. """Update Spoolman integration settings."""
  240. if "spoolman_enabled" in settings:
  241. old_val = await get_setting(db, "spoolman_enabled") or "false"
  242. new_val = settings["spoolman_enabled"]
  243. await set_setting(db, "spoolman_enabled", new_val)
  244. # Switching to Spoolman: clear built-in inventory slot assignments
  245. if old_val.lower() != "true" and new_val.lower() == "true":
  246. from backend.app.models.spool_assignment import SpoolAssignment
  247. result = await db.execute(delete(SpoolAssignment))
  248. logger.info("Cleared %d spool assignments on switch to Spoolman mode", result.rowcount)
  249. if "spoolman_url" in settings:
  250. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  251. if "spoolman_sync_mode" in settings:
  252. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  253. if "spoolman_disable_weight_sync" in settings:
  254. await set_setting(db, "spoolman_disable_weight_sync", settings["spoolman_disable_weight_sync"])
  255. if "spoolman_report_partial_usage" in settings:
  256. await set_setting(db, "spoolman_report_partial_usage", settings["spoolman_report_partial_usage"])
  257. await db.commit()
  258. db.expire_all()
  259. # Return updated settings
  260. return await get_spoolman_settings(db)
  261. async def get_homeassistant_settings(db: AsyncSession) -> dict:
  262. """
  263. Get Home Assistant integration settings.
  264. Environment variables (HA_URL, HA_TOKEN) take precedence over database settings.
  265. """
  266. import os
  267. # Check environment variables first
  268. ha_url_env = os.environ.get("HA_URL")
  269. ha_token_env = os.environ.get("HA_TOKEN")
  270. # Fall back to database values
  271. ha_url = ha_url_env or await get_setting(db, "ha_url") or ""
  272. ha_token = ha_token_env or await get_setting(db, "ha_token") or ""
  273. ha_enabled_db = await get_setting(db, "ha_enabled") or "false"
  274. # Track which settings come from environment
  275. ha_url_from_env = bool(ha_url_env)
  276. ha_token_from_env = bool(ha_token_env)
  277. ha_env_managed = ha_url_from_env and ha_token_from_env
  278. # Auto-enable when both env vars are set, otherwise use database value
  279. if ha_url_env and ha_token_env:
  280. ha_enabled = True
  281. else:
  282. ha_enabled = ha_enabled_db.lower() == "true"
  283. return {
  284. "ha_enabled": ha_enabled,
  285. "ha_url": ha_url,
  286. "ha_token": ha_token,
  287. "ha_url_from_env": ha_url_from_env,
  288. "ha_token_from_env": ha_token_from_env,
  289. "ha_env_managed": ha_env_managed,
  290. }
  291. async def create_backup_zip(output_path: Path | None = None) -> tuple[Path, str]:
  292. """Create a complete backup ZIP (database + all data directories).
  293. If output_path is given, the ZIP is written there.
  294. Otherwise a temporary file is created (caller must clean up).
  295. Returns (zip_path, filename).
  296. """
  297. import shutil
  298. import tempfile
  299. from backend.app.core.db_dialect import is_sqlite
  300. base_dir = app_settings.base_dir
  301. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  302. with tempfile.TemporaryDirectory() as temp_dir:
  303. temp_path = Path(temp_dir)
  304. if is_sqlite():
  305. from sqlalchemy import text
  306. from backend.app.core.database import engine
  307. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  308. # Checkpoint WAL to ensure all data is in main db file
  309. async with engine.begin() as conn:
  310. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  311. # Copy database file
  312. shutil.copy2(db_path, temp_path / "bambuddy.db")
  313. else:
  314. # PostgreSQL: export to a portable SQLite file via SQLAlchemy.
  315. # This makes backups restorable on both SQLite and Postgres installs.
  316. import json
  317. import sqlite3
  318. from backend.app.core.database import Base, engine
  319. backup_db_path = temp_path / "bambuddy.db"
  320. dst = sqlite3.connect(str(backup_db_path))
  321. metadata = Base.metadata
  322. # Create tables in SQLite backup (simplified — just column names and types)
  323. for table in metadata.sorted_tables:
  324. cols = []
  325. pk_cols = [col.name for col in table.columns if col.primary_key]
  326. for col in table.columns:
  327. col_type = "TEXT" # Default
  328. type_str = str(col.type).upper()
  329. if "INT" in type_str:
  330. col_type = "INTEGER"
  331. elif "FLOAT" in type_str or "REAL" in type_str or "NUMERIC" in type_str:
  332. col_type = "REAL"
  333. elif "BOOL" in type_str:
  334. col_type = "BOOLEAN"
  335. # Only inline PRIMARY KEY for single-column PKs
  336. pk = " PRIMARY KEY" if col.primary_key and len(pk_cols) == 1 else ""
  337. cols.append(f"{col.name} {col_type}{pk}")
  338. # Add composite primary key constraint if needed
  339. if len(pk_cols) > 1:
  340. cols.append(f"PRIMARY KEY ({', '.join(pk_cols)})")
  341. dst.execute(f"CREATE TABLE IF NOT EXISTS {table.name} ({', '.join(cols)})") # noqa: S608
  342. # Export data from Postgres to SQLite
  343. async with engine.connect() as conn:
  344. for table in metadata.sorted_tables:
  345. result = await conn.execute(table.select())
  346. rows = result.fetchall()
  347. if not rows:
  348. continue
  349. columns = list(result.keys())
  350. placeholders = ", ".join(["?"] * len(columns))
  351. col_list = ", ".join(columns)
  352. insert_sql = f"INSERT INTO {table.name} ({col_list}) VALUES ({placeholders})" # noqa: S608 # nosec B608 — table/column names from ORM metadata, not user input
  353. def _serialize_row(row):
  354. return tuple(json.dumps(v) if isinstance(v, (list, dict)) else v for v in row)
  355. dst.executemany(insert_sql, [_serialize_row(row) for row in rows])
  356. dst.commit()
  357. dst.close()
  358. logger.info("PostgreSQL backup exported to portable SQLite format")
  359. # Copy data directories (if they exist)
  360. dirs_to_backup = [
  361. ("archive", base_dir / "archive"),
  362. ("virtual_printer", base_dir / "virtual_printer"),
  363. ("plate_calibration", app_settings.plate_calibration_dir),
  364. ("icons", base_dir / "icons"),
  365. ("projects", base_dir / "projects"),
  366. ]
  367. for name, src_dir in dirs_to_backup:
  368. if src_dir.exists() and any(src_dir.iterdir()):
  369. try:
  370. shutil.copytree(src_dir, temp_path / name)
  371. except shutil.Error as e:
  372. logger.warning("Some files in %s could not be copied: %s", name, e)
  373. except PermissionError as e:
  374. logger.warning("Permission denied copying %s: %s", name, e)
  375. # Create ZIP
  376. if output_path is not None:
  377. zip_file = output_path / filename
  378. else:
  379. zip_file = Path(tempfile.mktemp(suffix=".zip")) # noqa: S306
  380. with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
  381. for file_path in temp_path.rglob("*"):
  382. if file_path.is_file():
  383. arcname = file_path.relative_to(temp_path)
  384. zf.write(file_path, arcname)
  385. return zip_file, filename
  386. @router.get("/backup")
  387. async def create_backup(
  388. db: AsyncSession = Depends(get_db),
  389. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_BACKUP),
  390. ):
  391. """Create a complete backup (database + all files) as a ZIP download."""
  392. from starlette.background import BackgroundTask
  393. try:
  394. zip_file, filename = await create_backup_zip()
  395. return FileResponse(
  396. path=zip_file,
  397. filename=filename,
  398. media_type="application/zip",
  399. background=BackgroundTask(lambda: zip_file.unlink(missing_ok=True)),
  400. )
  401. except Exception as e:
  402. logger.error("Backup failed: %s", e, exc_info=True)
  403. return JSONResponse(
  404. status_code=500,
  405. content={"success": False, "message": "Backup failed. Check server logs for details."},
  406. )
  407. async def _import_sqlite_to_postgres(sqlite_path: Path, postgres_url: str):
  408. """Import data from a SQLite database file into the current PostgreSQL database.
  409. Used for cross-database restore (SQLite backup → PostgreSQL).
  410. Reads all tables from the SQLite file and bulk-inserts into Postgres.
  411. """
  412. import sqlite3
  413. from sqlalchemy import text
  414. from backend.app.core.database import Base, _create_engine
  415. # Create a temporary engine for the import (current engine was disposed)
  416. pg_engine = _create_engine()
  417. try:
  418. # Open SQLite file directly (sync — it's a local file read)
  419. src = sqlite3.connect(str(sqlite_path))
  420. src.row_factory = sqlite3.Row
  421. # Get list of tables from SQLite (skip internal/FTS tables)
  422. cursor = src.execute(
  423. "SELECT name FROM sqlite_master WHERE type='table' "
  424. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  425. )
  426. src_tables = {row["name"] for row in cursor.fetchall()}
  427. # Get Postgres tables from our ORM models
  428. metadata = Base.metadata
  429. pg_tables = set(metadata.tables.keys())
  430. # Only import tables that exist in both source and destination
  431. tables_to_import = src_tables & pg_tables
  432. sorted_tables = [t.name for t in metadata.sorted_tables if t.name in tables_to_import]
  433. # Phase 1: Drop all tables and recreate WITHOUT foreign keys.
  434. # This avoids all FK ordering/orphan issues during import.
  435. saved_fks = {}
  436. for table in metadata.sorted_tables:
  437. fks = list(table.foreign_key_constraints)
  438. if fks:
  439. saved_fks[table.name] = fks
  440. for fk in fks:
  441. table.constraints.discard(fk)
  442. async with pg_engine.begin() as conn:
  443. await conn.run_sync(metadata.drop_all)
  444. await conn.run_sync(metadata.create_all)
  445. # Restore FK definitions in metadata (needed for re-adding later)
  446. for table_name, fks in saved_fks.items():
  447. table_obj = metadata.tables[table_name]
  448. for fk in fks:
  449. table_obj.constraints.add(fk)
  450. # Phase 2: Import data (no FKs to worry about)
  451. async with pg_engine.begin() as conn:
  452. # Import each table in dependency order (parents before children)
  453. for table_name in sorted_tables:
  454. rows = src.execute(f"SELECT * FROM {table_name}").fetchall() # noqa: S608 # nosec B608
  455. if not rows:
  456. continue
  457. # Filter to columns that exist in the Postgres table
  458. src_columns = rows[0].keys()
  459. pg_table = metadata.tables.get(table_name)
  460. pg_columns = {c.name for c in pg_table.columns} if pg_table is not None else set()
  461. columns = [c for c in src_columns if c in pg_columns]
  462. if not columns:
  463. continue
  464. col_list = ", ".join(columns)
  465. param_list = ", ".join(f":{c}" for c in columns)
  466. # ON CONFLICT DO NOTHING handles duplicate rows from SQLite (which doesn't enforce unique constraints)
  467. insert_sql = text(f"INSERT INTO {table_name} ({col_list}) VALUES ({param_list}) ON CONFLICT DO NOTHING") # noqa: S608 # nosec B608
  468. # Identify columns that need type conversion (SQLite stores booleans
  469. # as int and datetimes as str — asyncpg requires native Python types)
  470. from datetime import datetime as dt
  471. bool_columns = set()
  472. datetime_columns = set()
  473. not_null_defaults = {} # col_name -> default value for NOT NULL columns
  474. if pg_table is not None:
  475. for col in pg_table.columns:
  476. if col.name not in columns:
  477. continue
  478. col_type = str(col.type)
  479. if col_type == "BOOLEAN":
  480. bool_columns.add(col.name)
  481. elif col_type in ("DATETIME", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE"):
  482. datetime_columns.add(col.name)
  483. # Track NOT NULL columns with defaults — older backups may have NULL
  484. # for columns added after the backup was created
  485. if not col.nullable:
  486. if col.default is not None:
  487. default = col.default.arg
  488. if callable(default):
  489. default = default(None)
  490. not_null_defaults[col.name] = default
  491. elif col.server_default is not None:
  492. # server_default=func.now() → use current timestamp
  493. if col.name in datetime_columns:
  494. not_null_defaults[col.name] = "__now__"
  495. else:
  496. # Try to extract literal server default
  497. sd = str(col.server_default.arg) if hasattr(col.server_default, "arg") else None
  498. if sd is not None:
  499. not_null_defaults[col.name] = sd
  500. now = dt.now()
  501. def _convert_row(
  502. row, cols=columns, bools=bool_columns, dts=datetime_columns, nn_defaults=not_null_defaults, _now=now
  503. ):
  504. result = {}
  505. for c in cols:
  506. val = row[c]
  507. if val is None and c in nn_defaults:
  508. val = _now if nn_defaults[c] == "__now__" else nn_defaults[c]
  509. if val is not None:
  510. if c in bools:
  511. val = bool(val)
  512. elif c in dts and isinstance(val, str):
  513. try:
  514. val = dt.fromisoformat(val)
  515. except ValueError:
  516. pass
  517. result[c] = val
  518. return result
  519. batch = [_convert_row(row) for row in rows]
  520. await conn.execute(insert_sql, batch)
  521. logger.info("Imported %d rows into %s", len(batch), table_name)
  522. # Reset sequences to max(id) + 1 for each table with an id column
  523. for table_name in sorted_tables:
  524. try:
  525. async with conn.begin_nested():
  526. result = await conn.execute(text(f"SELECT MAX(id) FROM {table_name}")) # noqa: S608 # nosec B608
  527. max_id = result.scalar()
  528. if max_id is not None:
  529. seq_name = f"{table_name}_id_seq"
  530. await conn.execute(text(f"SELECT setval('{seq_name}', {max_id})")) # noqa: S608
  531. except Exception:
  532. pass # Table may not have an id column or sequence
  533. src.close()
  534. logger.info("Cross-database import complete: %d tables imported", len(tables_to_import))
  535. # Recreate FK constraints from ORM metadata (not from saved definitions).
  536. # Use individual transactions so orphaned SQLite data doesn't block valid FKs.
  537. from sqlalchemy.schema import AddConstraint
  538. failed_fks = []
  539. for table in metadata.sorted_tables:
  540. for fk in table.foreign_key_constraints:
  541. try:
  542. async with pg_engine.begin() as fk_conn:
  543. await fk_conn.execute(AddConstraint(fk))
  544. except Exception:
  545. failed_fks.append(f"{table.name}.{fk.name}")
  546. if failed_fks:
  547. logger.warning(
  548. "Could not restore %d FK constraints (orphaned data in SQLite): %s",
  549. len(failed_fks),
  550. ", ".join(failed_fks),
  551. )
  552. finally:
  553. await pg_engine.dispose()
  554. @router.post("/restore")
  555. async def restore_backup(
  556. file: UploadFile = File(...),
  557. db: AsyncSession = Depends(get_db),
  558. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_RESTORE),
  559. ):
  560. """Restore from a complete backup ZIP.
  561. Replaces the database and all data directories from the backup ZIP.
  562. Requires a restart after restore.
  563. """
  564. import shutil
  565. import tempfile
  566. from fastapi import HTTPException
  567. from backend.app.core.database import close_all_connections, init_db, reinitialize_database
  568. from backend.app.core.db_dialect import is_sqlite
  569. from backend.app.services.virtual_printer import virtual_printer_manager
  570. base_dir = app_settings.base_dir
  571. with tempfile.TemporaryDirectory() as temp_dir:
  572. temp_path = Path(temp_dir)
  573. # 1. Read and extract ZIP
  574. content = await file.read()
  575. # Check if it's a valid ZIP
  576. if not file.filename or not file.filename.endswith(".zip"):
  577. raise HTTPException(400, "Invalid backup file: must be a .zip file")
  578. try:
  579. with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
  580. zf.extractall(temp_path)
  581. except zipfile.BadZipFile:
  582. raise HTTPException(400, "Invalid backup file: not a valid ZIP")
  583. # 2. Validate backup
  584. backup_db = temp_path / "bambuddy.db"
  585. if not backup_db.exists():
  586. raise HTTPException(400, "Invalid backup: missing bambuddy.db")
  587. try:
  588. import asyncio
  589. # 3. Stop virtual printer if running (releases file locks)
  590. try:
  591. if virtual_printer_manager.is_enabled:
  592. logger.info("Stopping virtual printer for restore...")
  593. await virtual_printer_manager.configure(enabled=False)
  594. await asyncio.sleep(1)
  595. except Exception as e:
  596. logger.warning("Failed to stop virtual printer: %s", e)
  597. # 4. Close current database connections
  598. logger.info("Closing database connections...")
  599. await close_all_connections()
  600. # 5. Replace database
  601. logger.info("Restoring database from backup...")
  602. if is_sqlite():
  603. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  604. shutil.copy2(backup_db, db_path)
  605. else:
  606. # Import SQLite backup into PostgreSQL
  607. logger.info("Importing SQLite backup into PostgreSQL...")
  608. await _import_sqlite_to_postgres(backup_db, app_settings.database_url)
  609. # 6. Replace data directories
  610. # For Docker compatibility: clear contents then copy (don't delete mount points)
  611. dirs_to_restore = [
  612. ("archive", base_dir / "archive"),
  613. ("virtual_printer", base_dir / "virtual_printer"),
  614. ("plate_calibration", app_settings.plate_calibration_dir),
  615. ("icons", base_dir / "icons"),
  616. ("projects", base_dir / "projects"),
  617. ]
  618. skipped_dirs = []
  619. for name, dest_dir in dirs_to_restore:
  620. src_dir = temp_path / name
  621. if src_dir.exists():
  622. logger.info("Restoring %s directory...", name)
  623. try:
  624. # Clear destination contents (not the dir itself - may be Docker mount)
  625. if dest_dir.exists():
  626. for item in dest_dir.iterdir():
  627. try:
  628. if item.is_dir():
  629. shutil.rmtree(item)
  630. else:
  631. item.unlink()
  632. except OSError as e:
  633. logger.warning("Could not delete %s: %s", item, e)
  634. else:
  635. dest_dir.mkdir(parents=True, exist_ok=True)
  636. # Copy contents from backup
  637. for item in src_dir.iterdir():
  638. dest_item = dest_dir / item.name
  639. if item.is_dir():
  640. shutil.copytree(item, dest_item)
  641. else:
  642. shutil.copy2(item, dest_item)
  643. except OSError as e:
  644. logger.warning("Could not restore %s directory: %s", name, e)
  645. skipped_dirs.append(name)
  646. # 7. Reinitialize the database engine and apply schema migrations so that
  647. # tables added after the backup was created (e.g. ams_labels) exist
  648. # immediately, without requiring a manual restart.
  649. await reinitialize_database()
  650. await init_db()
  651. logger.info("Restore complete - restart required")
  652. message = "Backup restored successfully. Please restart Bambuddy for changes to take effect."
  653. if skipped_dirs:
  654. message += f" Note: Some directories could not be restored ({', '.join(skipped_dirs)})."
  655. return {
  656. "success": True,
  657. "message": message,
  658. }
  659. except Exception as e:
  660. logger.error("Restore failed: %s", e, exc_info=True)
  661. return JSONResponse(
  662. status_code=500,
  663. content={"success": False, "message": "Restore failed. Check server logs for details."},
  664. )
  665. @router.get("/network-interfaces")
  666. async def get_network_interfaces(
  667. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  668. ):
  669. """Get available network interfaces with all IPs (primary + aliases)."""
  670. from backend.app.services.network_utils import get_all_interface_ips
  671. interfaces = get_all_interface_ips()
  672. return {"interfaces": interfaces}
  673. @router.get("/virtual-printer/models")
  674. async def get_virtual_printer_models(
  675. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  676. ):
  677. """Get available virtual printer models."""
  678. from backend.app.services.virtual_printer import (
  679. DEFAULT_VIRTUAL_PRINTER_MODEL,
  680. VIRTUAL_PRINTER_MODELS,
  681. )
  682. return {
  683. "models": VIRTUAL_PRINTER_MODELS,
  684. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  685. }
  686. @router.get("/virtual-printer")
  687. async def get_virtual_printer_settings(
  688. db: AsyncSession = Depends(get_db),
  689. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  690. ):
  691. """Get virtual printer settings and status."""
  692. from backend.app.services.virtual_printer import (
  693. DEFAULT_VIRTUAL_PRINTER_MODEL,
  694. virtual_printer_manager,
  695. )
  696. enabled = await get_setting(db, "virtual_printer_enabled")
  697. access_code = await get_setting(db, "virtual_printer_access_code")
  698. mode = await get_setting(db, "virtual_printer_mode")
  699. model = await get_setting(db, "virtual_printer_model")
  700. target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  701. remote_interface_ip = await get_setting(db, "virtual_printer_remote_interface_ip")
  702. return {
  703. "enabled": enabled == "true" if enabled else False,
  704. "access_code_set": bool(access_code),
  705. "mode": mode or "immediate",
  706. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  707. "target_printer_id": int(target_printer_id) if target_printer_id else None,
  708. "remote_interface_ip": remote_interface_ip or "",
  709. "status": virtual_printer_manager.get_status(),
  710. }
  711. @router.put("/virtual-printer")
  712. async def update_virtual_printer_settings(
  713. enabled: bool = None,
  714. access_code: str = None,
  715. mode: str = None,
  716. model: str = None,
  717. target_printer_id: int = None,
  718. remote_interface_ip: str = None,
  719. db: AsyncSession = Depends(get_db),
  720. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  721. ):
  722. """Update virtual printer settings and restart services if needed.
  723. For proxy mode with SSDP proxy (dual-homed setup):
  724. - remote_interface_ip: IP of interface on slicer's network (LAN B)
  725. - Local interface is auto-detected based on target printer IP
  726. """
  727. from sqlalchemy import select
  728. from backend.app.models.printer import Printer
  729. from backend.app.services.virtual_printer import (
  730. DEFAULT_VIRTUAL_PRINTER_MODEL,
  731. VIRTUAL_PRINTER_MODELS,
  732. virtual_printer_manager,
  733. )
  734. # Get current values
  735. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  736. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  737. current_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  738. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  739. current_target_id_str = await get_setting(db, "virtual_printer_target_printer_id")
  740. current_target_id = int(current_target_id_str) if current_target_id_str else None
  741. current_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  742. # Apply updates
  743. new_enabled = enabled if enabled is not None else current_enabled
  744. new_access_code = access_code if access_code is not None else current_access_code
  745. new_mode = mode if mode is not None else current_mode
  746. new_model = model if model is not None else current_model
  747. new_target_id = target_printer_id if target_printer_id is not None else current_target_id
  748. new_remote_iface = remote_interface_ip if remote_interface_ip is not None else current_remote_iface
  749. # Validate mode
  750. # "review" is the new name for "queue" (pending review before archiving)
  751. # "print_queue" archives and adds to print queue (unassigned)
  752. # "proxy" is transparent TCP proxy to a real printer
  753. if new_mode not in ("immediate", "queue", "review", "print_queue", "proxy"):
  754. return JSONResponse(
  755. status_code=400,
  756. content={"detail": "Mode must be 'immediate', 'review', 'print_queue', or 'proxy'"},
  757. )
  758. # Normalize legacy "queue" to "review" for storage
  759. if new_mode == "queue":
  760. new_mode = "review"
  761. # Validate model
  762. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  763. return JSONResponse(
  764. status_code=400,
  765. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  766. )
  767. # Mode-specific validation and printer lookup
  768. target_printer_ip = ""
  769. target_printer_serial = ""
  770. if new_mode == "proxy":
  771. # Proxy mode requires target printer when enabling
  772. if new_enabled and not new_target_id:
  773. # If just switching to proxy mode (not explicitly enabling), auto-disable
  774. if enabled is None:
  775. new_enabled = False
  776. else:
  777. return JSONResponse(
  778. status_code=400,
  779. content={"detail": "Target printer is required for proxy mode"},
  780. )
  781. # Look up printer IP and serial if we have a target
  782. if new_target_id:
  783. result = await db.execute(select(Printer).where(Printer.id == new_target_id))
  784. printer = result.scalar_one_or_none()
  785. if not printer:
  786. return JSONResponse(
  787. status_code=400,
  788. content={"detail": f"Printer with ID {new_target_id} not found"},
  789. )
  790. target_printer_ip = printer.ip_address
  791. target_printer_serial = printer.serial_number
  792. # Access code not required for proxy mode
  793. else:
  794. # Non-proxy modes require access code when enabling
  795. if new_enabled and not new_access_code:
  796. # If just switching modes (not explicitly enabling), auto-disable
  797. if enabled is None:
  798. new_enabled = False
  799. else:
  800. return JSONResponse(
  801. status_code=400,
  802. content={"detail": "Access code is required when enabling virtual printer"},
  803. )
  804. # Validate access code length (Bambu Studio requires exactly 8 characters)
  805. if access_code is not None and access_code and len(access_code) != 8:
  806. return JSONResponse(
  807. status_code=400,
  808. content={"detail": "Access code must be exactly 8 characters"},
  809. )
  810. # Save settings
  811. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  812. if access_code is not None:
  813. await set_setting(db, "virtual_printer_access_code", access_code)
  814. await set_setting(db, "virtual_printer_mode", new_mode)
  815. if model is not None:
  816. await set_setting(db, "virtual_printer_model", model)
  817. if target_printer_id is not None:
  818. await set_setting(db, "virtual_printer_target_printer_id", str(target_printer_id))
  819. if remote_interface_ip is not None:
  820. await set_setting(db, "virtual_printer_remote_interface_ip", remote_interface_ip)
  821. await db.commit()
  822. db.expire_all()
  823. # Reconfigure virtual printer
  824. try:
  825. await virtual_printer_manager.configure(
  826. enabled=new_enabled,
  827. access_code=new_access_code,
  828. mode=new_mode,
  829. model=new_model,
  830. target_printer_ip=target_printer_ip,
  831. target_printer_serial=target_printer_serial,
  832. remote_interface_ip=new_remote_iface,
  833. )
  834. except ValueError as e:
  835. logger.warning("Virtual printer configuration validation error: %s", e)
  836. return JSONResponse(
  837. status_code=400,
  838. content={"detail": "Invalid virtual printer configuration. Check the provided values."},
  839. )
  840. except Exception as e:
  841. logger.error("Failed to configure virtual printer: %s", e, exc_info=True)
  842. return JSONResponse(
  843. status_code=500,
  844. content={"detail": "Failed to configure virtual printer. Check server logs for details."},
  845. )
  846. return await get_virtual_printer_settings(db)
  847. # =============================================================================
  848. # MQTT Relay Settings
  849. # =============================================================================
  850. @router.get("/mqtt/status")
  851. async def get_mqtt_status(
  852. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  853. ):
  854. """Get MQTT relay connection status."""
  855. from backend.app.services.mqtt_relay import mqtt_relay
  856. return mqtt_relay.get_status()