settings.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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. # Include the MFA encryption key as a ZIP top-level entry alongside
  378. # bambuddy.db. Without it, encrypted client_secret / TOTP secret rows
  379. # would be unrecoverable after restore on a host without MFA_ENCRYPTION_KEY set.
  380. from backend.app.core.paths import resolve_data_dir
  381. mfa_key_src = resolve_data_dir() / ".mfa_encryption_key"
  382. if mfa_key_src.exists() and mfa_key_src.is_file():
  383. try:
  384. shutil.copy2(mfa_key_src, temp_path / ".mfa_encryption_key")
  385. except OSError as exc:
  386. logger.error(
  387. "Could not include MFA encryption key in backup (%s). "
  388. "The backup ZIP will not contain the key — restore on a "
  389. "keyless host will fail for encrypted secrets.",
  390. exc,
  391. )
  392. raise
  393. # Create ZIP
  394. if output_path is not None:
  395. zip_file = output_path / filename
  396. else:
  397. fd, tmp = tempfile.mkstemp(suffix=".zip")
  398. os.close(fd)
  399. zip_file = Path(tmp)
  400. with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) as zf:
  401. for file_path in temp_path.rglob("*"):
  402. if file_path.is_file():
  403. arcname = file_path.relative_to(temp_path)
  404. zf.write(file_path, arcname)
  405. return zip_file, filename
  406. @router.get("/backup")
  407. async def create_backup(
  408. db: AsyncSession = Depends(get_db),
  409. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_BACKUP),
  410. ):
  411. """Create a complete backup (database + all files) as a ZIP download."""
  412. from starlette.background import BackgroundTask
  413. try:
  414. zip_file, filename = await create_backup_zip()
  415. return FileResponse(
  416. path=zip_file,
  417. filename=filename,
  418. media_type="application/zip",
  419. background=BackgroundTask(lambda: zip_file.unlink(missing_ok=True)),
  420. )
  421. except Exception as e:
  422. logger.error("Backup failed: %s", e, exc_info=True)
  423. return JSONResponse(
  424. status_code=500,
  425. content={"success": False, "message": "Backup failed. Check server logs for details."},
  426. )
  427. async def _import_sqlite_to_postgres(sqlite_path: Path, postgres_url: str):
  428. """Import data from a SQLite database file into the current PostgreSQL database.
  429. Used for cross-database restore (SQLite backup → PostgreSQL).
  430. Reads all tables from the SQLite file and bulk-inserts into Postgres.
  431. """
  432. import sqlite3
  433. from sqlalchemy import text
  434. from backend.app.core.database import Base, _create_engine
  435. # Create a temporary engine for the import (current engine was disposed)
  436. pg_engine = _create_engine()
  437. try:
  438. # Open SQLite file directly (sync — it's a local file read)
  439. src = sqlite3.connect(str(sqlite_path))
  440. src.row_factory = sqlite3.Row
  441. # Get list of tables from SQLite (skip internal/FTS tables)
  442. cursor = src.execute(
  443. "SELECT name FROM sqlite_master WHERE type='table' "
  444. "AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'archive_fts%'"
  445. )
  446. src_tables = {row["name"] for row in cursor.fetchall()}
  447. # Get Postgres tables from our ORM models
  448. metadata = Base.metadata
  449. pg_tables = set(metadata.tables.keys())
  450. # Only import tables that exist in both source and destination
  451. tables_to_import = src_tables & pg_tables
  452. sorted_tables = [t.name for t in metadata.sorted_tables if t.name in tables_to_import]
  453. # Phase 1: Drop all tables and recreate WITHOUT foreign keys.
  454. # This avoids all FK ordering/orphan issues during import.
  455. saved_fks = {}
  456. for table in metadata.sorted_tables:
  457. fks = list(table.foreign_key_constraints)
  458. if fks:
  459. saved_fks[table.name] = fks
  460. for fk in fks:
  461. table.constraints.discard(fk)
  462. async with pg_engine.begin() as conn:
  463. # Drop every existing table in the public schema with CASCADE
  464. # rather than `metadata.drop_all`. Two reasons:
  465. # 1. The user's live DB may carry orphan tables from removed
  466. # features (e.g. the legacy `spoolman_slot_assignments`,
  467. # `spoolman_k_profile`) that hold FK constraints back to
  468. # ORM tables. `drop_all` doesn't know they exist and emits
  469. # `DROP TABLE printers` without CASCADE — Postgres refuses
  470. # and the whole restore aborts (#XXXX).
  471. # 2. Even within the metadata, `drop_all` is FK-ordered and
  472. # breaks if a future schema rename leaves old constraints
  473. # around. CASCADE is the right tool for a destructive
  474. # restore: the user is intentionally wiping state.
  475. await conn.execute(
  476. text(
  477. "DO $$ DECLARE r RECORD; BEGIN "
  478. "FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP "
  479. "EXECUTE 'DROP TABLE IF EXISTS public.' || quote_ident(r.tablename) || ' CASCADE'; "
  480. "END LOOP; END $$;"
  481. )
  482. )
  483. await conn.run_sync(metadata.create_all)
  484. # Restore FK definitions in metadata (needed for re-adding later)
  485. for table_name, fks in saved_fks.items():
  486. table_obj = metadata.tables[table_name]
  487. for fk in fks:
  488. table_obj.constraints.add(fk)
  489. # Phase 2: Import data (no FKs to worry about)
  490. async with pg_engine.begin() as conn:
  491. # Import each table in dependency order (parents before children)
  492. for table_name in sorted_tables:
  493. rows = src.execute(f"SELECT * FROM {table_name}").fetchall() # noqa: S608 # nosec B608
  494. if not rows:
  495. continue
  496. # Filter to columns that exist in the Postgres table
  497. src_columns = rows[0].keys()
  498. pg_table = metadata.tables.get(table_name)
  499. pg_columns = {c.name for c in pg_table.columns} if pg_table is not None else set()
  500. columns = [c for c in src_columns if c in pg_columns]
  501. if not columns:
  502. continue
  503. col_list = ", ".join(columns)
  504. param_list = ", ".join(f":{c}" for c in columns)
  505. # ON CONFLICT DO NOTHING handles duplicate rows from SQLite (which doesn't enforce unique constraints)
  506. insert_sql = text(f"INSERT INTO {table_name} ({col_list}) VALUES ({param_list}) ON CONFLICT DO NOTHING") # noqa: S608 # nosec B608
  507. # Identify columns that need type conversion (SQLite stores booleans
  508. # as int and datetimes as str — asyncpg requires native Python types)
  509. from datetime import datetime as dt
  510. bool_columns = set()
  511. datetime_columns = set()
  512. not_null_defaults = {} # col_name -> default value for NOT NULL columns
  513. if pg_table is not None:
  514. for col in pg_table.columns:
  515. if col.name not in columns:
  516. continue
  517. col_type = str(col.type)
  518. if col_type == "BOOLEAN":
  519. bool_columns.add(col.name)
  520. elif col_type in ("DATETIME", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE"):
  521. datetime_columns.add(col.name)
  522. # Track NOT NULL columns with defaults — older backups may have NULL
  523. # for columns added after the backup was created
  524. if not col.nullable:
  525. if col.default is not None:
  526. default = col.default.arg
  527. if callable(default):
  528. default = default(None)
  529. not_null_defaults[col.name] = default
  530. elif col.server_default is not None:
  531. # server_default=func.now() → use current timestamp
  532. if col.name in datetime_columns:
  533. not_null_defaults[col.name] = "__now__"
  534. else:
  535. # Try to extract literal server default
  536. sd = str(col.server_default.arg) if hasattr(col.server_default, "arg") else None
  537. if sd is not None:
  538. not_null_defaults[col.name] = sd
  539. now = dt.now()
  540. def _convert_row(
  541. row, cols=columns, bools=bool_columns, dts=datetime_columns, nn_defaults=not_null_defaults, _now=now
  542. ):
  543. result = {}
  544. for c in cols:
  545. val = row[c]
  546. if val is None and c in nn_defaults:
  547. val = _now if nn_defaults[c] == "__now__" else nn_defaults[c]
  548. if val is not None:
  549. if c in bools:
  550. val = bool(val)
  551. elif c in dts and isinstance(val, str):
  552. try:
  553. val = dt.fromisoformat(val)
  554. except ValueError:
  555. pass
  556. result[c] = val
  557. return result
  558. batch = [_convert_row(row) for row in rows]
  559. await conn.execute(insert_sql, batch)
  560. logger.info("Imported %d rows into %s", len(batch), table_name)
  561. # Reset sequences to max(id) + 1 for each table with an id column
  562. for table_name in sorted_tables:
  563. try:
  564. async with conn.begin_nested():
  565. result = await conn.execute(text(f"SELECT MAX(id) FROM {table_name}")) # noqa: S608 # nosec B608
  566. max_id = result.scalar()
  567. if max_id is not None:
  568. seq_name = f"{table_name}_id_seq"
  569. await conn.execute(text(f"SELECT setval('{seq_name}', {max_id})")) # noqa: S608
  570. except Exception:
  571. pass # Table may not have an id column or sequence
  572. src.close()
  573. logger.info("Cross-database import complete: %d tables imported", len(tables_to_import))
  574. # Recreate FK constraints from ORM metadata (not from saved definitions).
  575. # Use individual transactions so orphaned SQLite data doesn't block valid FKs.
  576. from sqlalchemy.schema import AddConstraint
  577. failed_fks = []
  578. for table in metadata.sorted_tables:
  579. for fk in table.foreign_key_constraints:
  580. try:
  581. async with pg_engine.begin() as fk_conn:
  582. await fk_conn.execute(AddConstraint(fk))
  583. except Exception:
  584. failed_fks.append(f"{table.name}.{fk.name}")
  585. if failed_fks:
  586. logger.warning(
  587. "Could not restore %d FK constraints (orphaned data in SQLite): %s",
  588. len(failed_fks),
  589. ", ".join(failed_fks),
  590. )
  591. finally:
  592. await pg_engine.dispose()
  593. @router.post("/restore")
  594. async def restore_backup(
  595. file: UploadFile = File(...),
  596. db: AsyncSession = Depends(get_db),
  597. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_RESTORE),
  598. ):
  599. """Restore from a complete backup ZIP.
  600. Replaces the database and all data directories from the backup ZIP.
  601. Requires a restart after restore.
  602. """
  603. import shutil
  604. import tempfile
  605. from fastapi import HTTPException
  606. from backend.app.core.database import close_all_connections, init_db, reinitialize_database
  607. from backend.app.core.db_dialect import is_sqlite
  608. from backend.app.services.virtual_printer import virtual_printer_manager
  609. base_dir = app_settings.base_dir
  610. with tempfile.TemporaryDirectory() as temp_dir:
  611. temp_path = Path(temp_dir)
  612. # 1. Read and extract ZIP
  613. content = await file.read()
  614. # Check if it's a valid ZIP
  615. if not file.filename or not file.filename.endswith(".zip"):
  616. raise HTTPException(400, "Invalid backup file: must be a .zip file")
  617. try:
  618. with zipfile.ZipFile(io.BytesIO(content), "r") as zf:
  619. for name in zf.namelist():
  620. # Reject path-traversal payloads: any entry whose resolved
  621. # path escapes temp_path would allow writing arbitrary files
  622. # on the host (ZipSlip / CVE-2006-5456).
  623. dest = (temp_path / name).resolve()
  624. # is_relative_to (Python 3.9+) covers both relative
  625. # path-traversal (../etc/passwd) and absolute-path overrides
  626. # (/etc/passwd) — str.startswith was vulnerable to
  627. # prefix-collision attacks (e.g. /tmp/abc_evil/file passing
  628. # a /tmp/abc prefix check).
  629. if not dest.is_relative_to(temp_path.resolve()):
  630. raise HTTPException(400, f"Invalid backup: unsafe path in ZIP: {name!r}")
  631. zf.extractall(temp_path)
  632. except zipfile.BadZipFile:
  633. raise HTTPException(400, "Invalid backup file: not a valid ZIP")
  634. # 2. Validate backup
  635. backup_db = temp_path / "bambuddy.db"
  636. if not backup_db.exists():
  637. raise HTTPException(400, "Invalid backup: missing bambuddy.db")
  638. try:
  639. import asyncio
  640. # 3. Stop virtual printer if running (releases file locks)
  641. try:
  642. if virtual_printer_manager.is_enabled:
  643. logger.info("Stopping virtual printer for restore...")
  644. await virtual_printer_manager.configure(enabled=False)
  645. await asyncio.sleep(1)
  646. except Exception as e:
  647. logger.warning("Failed to stop virtual printer: %s", e)
  648. # 4. Close current database connections
  649. logger.info("Closing database connections...")
  650. await close_all_connections()
  651. # B1: Restore the MFA encryption key file BEFORE the database swap.
  652. # If the key write fails (OSError, RO disk, full disk, EACCES) we
  653. # can still abort while the live DB is intact. Doing this AFTER the
  654. # DB swap would leave the database with rows encrypted under the
  655. # backup's key but the running install holding only the old key —
  656. # every encrypted secret becomes unrecoverable.
  657. from backend.app.core.paths import resolve_data_dir
  658. mfa_key_src = temp_path / ".mfa_encryption_key"
  659. if mfa_key_src.exists() and mfa_key_src.is_file():
  660. dst_key = resolve_data_dir() / ".mfa_encryption_key"
  661. tmp_key = dst_key.parent / ".mfa_encryption_key.restore-tmp"
  662. try:
  663. dst_key.parent.mkdir(parents=True, exist_ok=True)
  664. # S1: atomic write with restrictive mode from creation.
  665. # O_TRUNC because a stale tmp may exist from a prior
  666. # failed restore attempt — we want to overwrite it.
  667. fd = os.open(str(tmp_key), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
  668. try:
  669. os.write(fd, mfa_key_src.read_bytes())
  670. finally:
  671. os.close(fd)
  672. # POSIX rename(2) — atomic when source/dest are on the
  673. # same filesystem (we're staying inside dst_key.parent).
  674. os.replace(str(tmp_key), str(dst_key))
  675. # S9: warn if the FS doesn't enforce 0o600
  676. actual_mode = dst_key.stat().st_mode & 0o777
  677. if actual_mode != 0o600:
  678. logger.warning(
  679. "Restored MFA key file %s: filesystem did not enforce 0o600 "
  680. "(actual: 0o%o). Key may be world-readable on Windows / SMB / FUSE.",
  681. dst_key,
  682. actual_mode,
  683. )
  684. logger.info("Restored .mfa_encryption_key from backup")
  685. except OSError as e:
  686. logger.error(
  687. "Could not write restored MFA key file to %s: %s — "
  688. "aborting BEFORE database swap (DB unchanged).",
  689. dst_key,
  690. e,
  691. exc_info=True,
  692. )
  693. raise HTTPException(
  694. status_code=500,
  695. detail=("Restore aborted: MFA key write failed. Database is unchanged. Check server logs."),
  696. ) from e
  697. # 5. Replace database
  698. logger.info("Restoring database from backup...")
  699. if is_sqlite():
  700. db_path = Path(app_settings.database_url.replace("sqlite+aiosqlite:///", ""))
  701. # Use SQLite's online backup API instead of shutil.copy2.
  702. # The pragma at database.py:19 runs the live DB in WAL mode,
  703. # which means a naive file copy is unsafe: anything written
  704. # to the live DB before this call that hasn't been
  705. # checkpointed yet (seed_default_groups + init_db on first
  706. # start, plus whatever background heartbeats wrote during
  707. # the request window) sits in bambuddy.db-wal with valid
  708. # checksums. The route handler's own `db: Depends(get_db)`
  709. # session also keeps a connection checked out across
  710. # engine.dispose(), holding fds to the WAL inode. With
  711. # `shutil.copy2` SQLite finds the stale WAL on the next
  712. # open and silently re-applies those page-level writes on
  713. # top of the restored DB, partially clobbering it with
  714. # fresh-install state — the user sees a "successful"
  715. # restore where most rows and settings have reverted to
  716. # defaults (#1211 / #668). The page-by-page backup API
  717. # opens both DBs as real SQLite connections, takes the
  718. # right locks, and routes new pages through the live DB's
  719. # own WAL — so concurrent open sessions see their own
  720. # snapshot until they close (transaction isolation) but
  721. # can't corrupt the restored state.
  722. import sqlite3
  723. src_conn = sqlite3.connect(str(backup_db))
  724. try:
  725. dst_conn = sqlite3.connect(str(db_path))
  726. try:
  727. src_conn.backup(dst_conn)
  728. finally:
  729. dst_conn.close()
  730. finally:
  731. src_conn.close()
  732. else:
  733. # Import SQLite backup into PostgreSQL
  734. logger.info("Importing SQLite backup into PostgreSQL...")
  735. await _import_sqlite_to_postgres(backup_db, app_settings.database_url)
  736. # 6. Replace data directories
  737. # For Docker compatibility: clear contents then copy (don't delete mount points)
  738. dirs_to_restore = [
  739. ("archive", base_dir / "archive"),
  740. ("virtual_printer", base_dir / "virtual_printer"),
  741. ("plate_calibration", app_settings.plate_calibration_dir),
  742. ("icons", base_dir / "icons"),
  743. ("projects", base_dir / "projects"),
  744. ]
  745. skipped_dirs = []
  746. for name, dest_dir in dirs_to_restore:
  747. src_dir = temp_path / name
  748. if src_dir.exists():
  749. logger.info("Restoring %s directory...", name)
  750. try:
  751. # Clear destination contents (not the dir itself - may be Docker mount)
  752. if dest_dir.exists():
  753. for item in dest_dir.iterdir():
  754. try:
  755. if item.is_dir():
  756. shutil.rmtree(item)
  757. else:
  758. item.unlink()
  759. except OSError as e:
  760. logger.warning("Could not delete %s: %s", item, e)
  761. else:
  762. dest_dir.mkdir(parents=True, exist_ok=True)
  763. # Copy contents from backup
  764. for item in src_dir.iterdir():
  765. dest_item = dest_dir / item.name
  766. if item.is_dir():
  767. shutil.copytree(item, dest_item)
  768. else:
  769. shutil.copy2(item, dest_item)
  770. except OSError as e:
  771. logger.warning("Could not restore %s directory: %s", name, e)
  772. skipped_dirs.append(name)
  773. # 7. Reset the encryption singleton so the migration that runs
  774. # inside init_db() picks up the restored key file (if a new one
  775. # was written above). Without this reset, _get_fernet would
  776. # return the cached Fernet instance built from the previous key.
  777. import backend.app.core.encryption as _enc_mod
  778. _enc_mod._fernet_instance = None
  779. _enc_mod._key_source = None
  780. _enc_mod._warn_shown = False
  781. # 8. Reinitialize the database engine and apply schema migrations so that
  782. # tables added after the backup was created (e.g. ams_labels) exist
  783. # immediately, without requiring a manual restart.
  784. await reinitialize_database()
  785. await init_db()
  786. logger.info("Restore complete - restart required")
  787. message = "Backup restored successfully. Please restart Bambuddy for changes to take effect."
  788. if skipped_dirs:
  789. message += f" Note: Some directories could not be restored ({', '.join(skipped_dirs)})."
  790. return {
  791. "success": True,
  792. "message": message,
  793. }
  794. except HTTPException:
  795. # Preserve specific HTTP error responses raised inside the restore
  796. # body (e.g. the key-write OSError → 500). The blanket
  797. # except Exception below would otherwise swallow them and replace
  798. # the operator-facing detail with a generic message.
  799. raise
  800. except Exception as e:
  801. logger.error("Restore failed: %s", e, exc_info=True)
  802. return JSONResponse(
  803. status_code=500,
  804. content={"success": False, "message": "Restore failed. Check server logs for details."},
  805. )
  806. @router.get("/network-interfaces")
  807. async def get_network_interfaces(
  808. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  809. ):
  810. """Get available network interfaces with all IPs (primary + aliases)."""
  811. from backend.app.services.network_utils import get_all_interface_ips
  812. interfaces = get_all_interface_ips()
  813. return {"interfaces": interfaces}
  814. @router.get("/virtual-printer/models")
  815. async def get_virtual_printer_models(
  816. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  817. ):
  818. """Get available virtual printer models."""
  819. from backend.app.services.virtual_printer import (
  820. DEFAULT_VIRTUAL_PRINTER_MODEL,
  821. VIRTUAL_PRINTER_MODELS,
  822. )
  823. return {
  824. "models": VIRTUAL_PRINTER_MODELS,
  825. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  826. }
  827. @router.get("/virtual-printer")
  828. async def get_virtual_printer_settings(
  829. db: AsyncSession = Depends(get_db),
  830. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  831. ):
  832. """Get virtual printer settings and status."""
  833. from backend.app.services.virtual_printer import (
  834. DEFAULT_VIRTUAL_PRINTER_MODEL,
  835. virtual_printer_manager,
  836. )
  837. enabled = await get_setting(db, "virtual_printer_enabled")
  838. access_code = await get_setting(db, "virtual_printer_access_code")
  839. mode = await get_setting(db, "virtual_printer_mode")
  840. model = await get_setting(db, "virtual_printer_model")
  841. target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  842. remote_interface_ip = await get_setting(db, "virtual_printer_remote_interface_ip")
  843. tailscale_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  844. archive_name_source = await get_setting(db, "virtual_printer_archive_name_source")
  845. return {
  846. "enabled": enabled == "true" if enabled else False,
  847. "access_code_set": bool(access_code),
  848. "mode": mode or "immediate",
  849. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  850. "target_printer_id": int(target_printer_id) if target_printer_id else None,
  851. "remote_interface_ip": remote_interface_ip or "",
  852. "tailscale_disabled": tailscale_disabled_raw == "true" if tailscale_disabled_raw else True,
  853. "archive_name_source": archive_name_source if archive_name_source in ("metadata", "filename") else "metadata",
  854. "status": virtual_printer_manager.get_status(),
  855. }
  856. @router.put("/virtual-printer")
  857. async def update_virtual_printer_settings(
  858. enabled: bool = None,
  859. access_code: str = None,
  860. mode: str = None,
  861. model: str = None,
  862. target_printer_id: int = None,
  863. remote_interface_ip: str = None,
  864. tailscale_disabled: bool = None,
  865. archive_name_source: str = None,
  866. db: AsyncSession = Depends(get_db),
  867. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  868. ):
  869. """Update virtual printer settings and restart services if needed.
  870. For proxy mode with SSDP proxy (dual-homed setup):
  871. - remote_interface_ip: IP of interface on slicer's network (LAN B)
  872. - Local interface is auto-detected based on target printer IP
  873. """
  874. from sqlalchemy import select
  875. from backend.app.models.printer import Printer
  876. from backend.app.services.virtual_printer import (
  877. DEFAULT_VIRTUAL_PRINTER_MODEL,
  878. VIRTUAL_PRINTER_MODELS,
  879. virtual_printer_manager,
  880. )
  881. # Get current values
  882. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  883. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  884. current_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  885. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  886. current_target_id_str = await get_setting(db, "virtual_printer_target_printer_id")
  887. current_target_id = int(current_target_id_str) if current_target_id_str else None
  888. current_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  889. current_ts_disabled_raw = await get_setting(db, "virtual_printer_tailscale_disabled")
  890. # Default True (opt-in) when the setting has never been saved — matches the model default.
  891. current_ts_disabled = current_ts_disabled_raw == "true" if current_ts_disabled_raw else True
  892. # Apply updates
  893. new_enabled = enabled if enabled is not None else current_enabled
  894. new_access_code = access_code if access_code is not None else current_access_code
  895. new_mode = mode if mode is not None else current_mode
  896. new_model = model if model is not None else current_model
  897. new_target_id = target_printer_id if target_printer_id is not None else current_target_id
  898. new_remote_iface = remote_interface_ip if remote_interface_ip is not None else current_remote_iface
  899. new_ts_disabled = tailscale_disabled if tailscale_disabled is not None else current_ts_disabled
  900. # Validate mode
  901. # "review" is the new name for "queue" (pending review before archiving)
  902. # "print_queue" archives and adds to print queue (unassigned)
  903. # "proxy" is transparent TCP proxy to a real printer
  904. if new_mode not in ("immediate", "queue", "review", "print_queue", "proxy"):
  905. return JSONResponse(
  906. status_code=400,
  907. content={"detail": "Mode must be 'immediate', 'review', 'print_queue', or 'proxy'"},
  908. )
  909. # Validate archive_name_source
  910. if archive_name_source is not None and archive_name_source not in ("metadata", "filename"):
  911. return JSONResponse(
  912. status_code=400,
  913. content={"detail": "archive_name_source must be 'metadata' or 'filename'"},
  914. )
  915. # Normalize legacy "queue" to "review" for storage
  916. if new_mode == "queue":
  917. new_mode = "review"
  918. # Validate model
  919. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  920. return JSONResponse(
  921. status_code=400,
  922. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  923. )
  924. # Mode-specific validation and printer lookup
  925. target_printer_ip = ""
  926. target_printer_serial = ""
  927. if new_mode == "proxy":
  928. # Proxy mode requires target printer when enabling
  929. if new_enabled and not new_target_id:
  930. # If just switching to proxy mode (not explicitly enabling), auto-disable
  931. if enabled is None:
  932. new_enabled = False
  933. else:
  934. return JSONResponse(
  935. status_code=400,
  936. content={"detail": "Target printer is required for proxy mode"},
  937. )
  938. # Look up printer IP and serial if we have a target
  939. if new_target_id:
  940. result = await db.execute(select(Printer).where(Printer.id == new_target_id))
  941. printer = result.scalar_one_or_none()
  942. if not printer:
  943. return JSONResponse(
  944. status_code=400,
  945. content={"detail": f"Printer with ID {new_target_id} not found"},
  946. )
  947. target_printer_ip = printer.ip_address
  948. target_printer_serial = printer.serial_number
  949. # Access code not required for proxy mode
  950. else:
  951. # Non-proxy modes require access code when enabling
  952. if new_enabled and not new_access_code:
  953. # If just switching modes (not explicitly enabling), auto-disable
  954. if enabled is None:
  955. new_enabled = False
  956. else:
  957. return JSONResponse(
  958. status_code=400,
  959. content={"detail": "Access code is required when enabling virtual printer"},
  960. )
  961. # Validate access code length (Bambu Studio requires exactly 8 characters)
  962. if access_code is not None and access_code and len(access_code) != 8:
  963. return JSONResponse(
  964. status_code=400,
  965. content={"detail": "Access code must be exactly 8 characters"},
  966. )
  967. # Save settings
  968. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  969. if access_code is not None:
  970. await set_setting(db, "virtual_printer_access_code", access_code)
  971. await set_setting(db, "virtual_printer_mode", new_mode)
  972. if model is not None:
  973. await set_setting(db, "virtual_printer_model", model)
  974. if target_printer_id is not None:
  975. await set_setting(db, "virtual_printer_target_printer_id", str(target_printer_id))
  976. if remote_interface_ip is not None:
  977. await set_setting(db, "virtual_printer_remote_interface_ip", remote_interface_ip)
  978. if tailscale_disabled is not None:
  979. await set_setting(db, "virtual_printer_tailscale_disabled", "true" if tailscale_disabled else "false")
  980. if archive_name_source is not None:
  981. await set_setting(db, "virtual_printer_archive_name_source", archive_name_source)
  982. # Propagate tailscale_disabled to the first VirtualPrinter row so sync_from_db() picks it up
  983. if tailscale_disabled is not None:
  984. from backend.app.models.virtual_printer import VirtualPrinter as VPModel
  985. vp_result = await db.execute(select(VPModel).order_by(VPModel.position).limit(1))
  986. first_vp = vp_result.scalar_one_or_none()
  987. if first_vp is not None:
  988. first_vp.tailscale_disabled = new_ts_disabled
  989. await db.commit()
  990. db.expire_all()
  991. # Reconfigure virtual printer
  992. try:
  993. await virtual_printer_manager.configure(
  994. enabled=new_enabled,
  995. access_code=new_access_code,
  996. mode=new_mode,
  997. model=new_model,
  998. target_printer_ip=target_printer_ip,
  999. target_printer_serial=target_printer_serial,
  1000. remote_interface_ip=new_remote_iface,
  1001. )
  1002. except ValueError as e:
  1003. logger.warning("Virtual printer configuration validation error: %s", e)
  1004. return JSONResponse(
  1005. status_code=400,
  1006. content={"detail": "Invalid virtual printer configuration. Check the provided values."},
  1007. )
  1008. except Exception as e:
  1009. logger.error("Failed to configure virtual printer: %s", e, exc_info=True)
  1010. return JSONResponse(
  1011. status_code=500,
  1012. content={"detail": "Failed to configure virtual printer. Check server logs for details."},
  1013. )
  1014. return await get_virtual_printer_settings(db)
  1015. # =============================================================================
  1016. # MQTT Relay Settings
  1017. # =============================================================================
  1018. @router.get("/mqtt/status")
  1019. async def get_mqtt_status(
  1020. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  1021. ):
  1022. """Get MQTT relay connection status."""
  1023. from backend.app.services.mqtt_relay import mqtt_relay
  1024. return mqtt_relay.get_status()