settings.py 40 KB

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