settings.py 41 KB

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