settings.py 45 KB

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