settings.py 40 KB

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