settings.py 59 KB

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