settings.py 55 KB

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