settings.py 55 KB

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