settings.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. import io
  2. import json
  3. import zipfile
  4. from datetime import datetime
  5. from pathlib import Path
  6. from typing import Optional
  7. from fastapi import APIRouter, Depends, UploadFile, File, Query
  8. from fastapi.responses import JSONResponse, StreamingResponse
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from sqlalchemy import select
  11. from backend.app.core.config import settings as app_settings
  12. from backend.app.core.database import get_db
  13. from backend.app.models.settings import Settings
  14. from backend.app.models.notification import NotificationProvider
  15. from backend.app.models.notification_template import NotificationTemplate
  16. from backend.app.models.smart_plug import SmartPlug
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.filament import Filament
  19. from backend.app.models.maintenance import MaintenanceType, PrinterMaintenance, MaintenanceHistory
  20. from backend.app.models.archive import PrintArchive
  21. from backend.app.schemas.settings import AppSettings, AppSettingsUpdate
  22. from backend.app.services.printer_manager import printer_manager
  23. router = APIRouter(prefix="/settings", tags=["settings"])
  24. # Default settings
  25. DEFAULT_SETTINGS = AppSettings()
  26. async def get_setting(db: AsyncSession, key: str) -> str | None:
  27. """Get a single setting value by key."""
  28. result = await db.execute(select(Settings).where(Settings.key == key))
  29. setting = result.scalar_one_or_none()
  30. return setting.value if setting else None
  31. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  32. """Set a single setting value."""
  33. result = await db.execute(select(Settings).where(Settings.key == key))
  34. setting = result.scalar_one_or_none()
  35. if setting:
  36. setting.value = value
  37. else:
  38. setting = Settings(key=key, value=value)
  39. db.add(setting)
  40. @router.get("/", response_model=AppSettings)
  41. async def get_settings(db: AsyncSession = Depends(get_db)):
  42. """Get all application settings."""
  43. settings_dict = DEFAULT_SETTINGS.model_dump()
  44. # Load saved settings from database
  45. result = await db.execute(select(Settings))
  46. db_settings = result.scalars().all()
  47. for setting in db_settings:
  48. if setting.key in settings_dict:
  49. # Parse the value based on the expected type
  50. if setting.key in ["auto_archive", "save_thumbnails", "capture_finish_photo", "spoolman_enabled", "check_updates"]:
  51. settings_dict[setting.key] = setting.value.lower() == "true"
  52. elif setting.key in ["default_filament_cost", "energy_cost_per_kwh", "ams_temp_good", "ams_temp_fair"]:
  53. settings_dict[setting.key] = float(setting.value)
  54. elif setting.key in ["ams_humidity_good", "ams_humidity_fair"]:
  55. settings_dict[setting.key] = int(setting.value)
  56. elif setting.key == "default_printer_id":
  57. # Handle nullable integer
  58. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  59. else:
  60. settings_dict[setting.key] = setting.value
  61. return AppSettings(**settings_dict)
  62. @router.put("/", response_model=AppSettings)
  63. async def update_settings(
  64. settings_update: AppSettingsUpdate,
  65. db: AsyncSession = Depends(get_db),
  66. ):
  67. """Update application settings."""
  68. update_data = settings_update.model_dump(exclude_unset=True)
  69. for key, value in update_data.items():
  70. # Convert value to string for storage
  71. if isinstance(value, bool):
  72. str_value = "true" if value else "false"
  73. elif value is None:
  74. str_value = "None"
  75. else:
  76. str_value = str(value)
  77. await set_setting(db, key, str_value)
  78. await db.commit()
  79. # Return updated settings
  80. return await get_settings(db)
  81. @router.post("/reset", response_model=AppSettings)
  82. async def reset_settings(db: AsyncSession = Depends(get_db)):
  83. """Reset all settings to defaults."""
  84. # Delete all settings
  85. result = await db.execute(select(Settings))
  86. for setting in result.scalars().all():
  87. await db.delete(setting)
  88. await db.commit()
  89. return DEFAULT_SETTINGS
  90. @router.get("/check-ffmpeg")
  91. async def check_ffmpeg():
  92. """Check if ffmpeg is installed and available."""
  93. from backend.app.services.camera import get_ffmpeg_path
  94. ffmpeg_path = get_ffmpeg_path()
  95. return {
  96. "installed": ffmpeg_path is not None,
  97. "path": ffmpeg_path,
  98. }
  99. @router.get("/spoolman")
  100. async def get_spoolman_settings(db: AsyncSession = Depends(get_db)):
  101. """Get Spoolman integration settings."""
  102. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  103. spoolman_url = await get_setting(db, "spoolman_url") or ""
  104. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  105. return {
  106. "spoolman_enabled": spoolman_enabled,
  107. "spoolman_url": spoolman_url,
  108. "spoolman_sync_mode": spoolman_sync_mode,
  109. }
  110. @router.put("/spoolman")
  111. async def update_spoolman_settings(
  112. settings: dict,
  113. db: AsyncSession = Depends(get_db),
  114. ):
  115. """Update Spoolman integration settings."""
  116. if "spoolman_enabled" in settings:
  117. await set_setting(db, "spoolman_enabled", settings["spoolman_enabled"])
  118. if "spoolman_url" in settings:
  119. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  120. if "spoolman_sync_mode" in settings:
  121. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  122. await db.commit()
  123. # Return updated settings
  124. return await get_spoolman_settings(db)
  125. @router.get("/backup")
  126. async def export_backup(
  127. db: AsyncSession = Depends(get_db),
  128. include_settings: bool = Query(True, description="Include app settings"),
  129. include_notifications: bool = Query(True, description="Include notification providers"),
  130. include_templates: bool = Query(True, description="Include notification templates"),
  131. include_smart_plugs: bool = Query(True, description="Include smart plugs"),
  132. include_printers: bool = Query(False, description="Include printers (without access codes)"),
  133. include_filaments: bool = Query(False, description="Include filament inventory"),
  134. include_maintenance: bool = Query(False, description="Include maintenance types and records"),
  135. include_archives: bool = Query(False, description="Include print archive metadata"),
  136. ):
  137. """Export selected data as JSON backup."""
  138. backup: dict = {
  139. "version": "2.0",
  140. "exported_at": datetime.utcnow().isoformat(),
  141. "included": [],
  142. }
  143. # Settings
  144. if include_settings:
  145. result = await db.execute(select(Settings))
  146. db_settings = result.scalars().all()
  147. backup["settings"] = {s.key: s.value for s in db_settings}
  148. backup["included"].append("settings")
  149. # Notification providers
  150. if include_notifications:
  151. result = await db.execute(select(NotificationProvider))
  152. providers = result.scalars().all()
  153. backup["notification_providers"] = []
  154. for p in providers:
  155. backup["notification_providers"].append({
  156. "name": p.name,
  157. "provider_type": p.provider_type,
  158. "enabled": p.enabled,
  159. "config": json.loads(p.config) if isinstance(p.config, str) else p.config,
  160. "on_print_start": p.on_print_start,
  161. "on_print_complete": p.on_print_complete,
  162. "on_print_failed": p.on_print_failed,
  163. "on_print_stopped": p.on_print_stopped,
  164. "on_print_progress": p.on_print_progress,
  165. "on_printer_offline": p.on_printer_offline,
  166. "on_printer_error": p.on_printer_error,
  167. "on_filament_low": p.on_filament_low,
  168. "on_maintenance_due": p.on_maintenance_due,
  169. "quiet_hours_enabled": p.quiet_hours_enabled,
  170. "quiet_hours_start": p.quiet_hours_start,
  171. "quiet_hours_end": p.quiet_hours_end,
  172. "daily_digest_enabled": getattr(p, 'daily_digest_enabled', False),
  173. "daily_digest_time": getattr(p, 'daily_digest_time', None),
  174. "printer_id": getattr(p, 'printer_id', None),
  175. })
  176. backup["included"].append("notification_providers")
  177. # Notification templates
  178. if include_templates:
  179. result = await db.execute(select(NotificationTemplate))
  180. templates = result.scalars().all()
  181. backup["notification_templates"] = []
  182. for t in templates:
  183. backup["notification_templates"].append({
  184. "event_type": t.event_type,
  185. "name": t.name,
  186. "title_template": t.title_template,
  187. "body_template": t.body_template,
  188. "is_default": t.is_default,
  189. })
  190. backup["included"].append("notification_templates")
  191. # Smart plugs
  192. if include_smart_plugs:
  193. result = await db.execute(select(SmartPlug))
  194. plugs = result.scalars().all()
  195. backup["smart_plugs"] = []
  196. for plug in plugs:
  197. backup["smart_plugs"].append({
  198. "name": plug.name,
  199. "ip_address": plug.ip_address,
  200. "printer_id": plug.printer_id,
  201. "enabled": plug.enabled,
  202. "auto_on": plug.auto_on,
  203. "auto_off": plug.auto_off,
  204. "off_delay_mode": plug.off_delay_mode,
  205. "off_delay_minutes": plug.off_delay_minutes,
  206. "off_temp_threshold": plug.off_temp_threshold,
  207. "username": plug.username,
  208. "password": plug.password,
  209. "power_alert_enabled": plug.power_alert_enabled,
  210. "power_alert_high": plug.power_alert_high,
  211. "power_alert_low": plug.power_alert_low,
  212. "schedule_enabled": plug.schedule_enabled,
  213. "schedule_on_time": plug.schedule_on_time,
  214. "schedule_off_time": plug.schedule_off_time,
  215. })
  216. backup["included"].append("smart_plugs")
  217. # Printers (without access codes for security)
  218. if include_printers:
  219. result = await db.execute(select(Printer))
  220. printers = result.scalars().all()
  221. backup["printers"] = []
  222. for printer in printers:
  223. backup["printers"].append({
  224. "name": printer.name,
  225. "serial_number": printer.serial_number,
  226. "ip_address": printer.ip_address,
  227. # access_code intentionally excluded for security
  228. "model": printer.model,
  229. "location": printer.location,
  230. "nozzle_count": printer.nozzle_count,
  231. "is_active": printer.is_active,
  232. "auto_archive": printer.auto_archive,
  233. "print_hours_offset": printer.print_hours_offset,
  234. })
  235. backup["included"].append("printers")
  236. # Filaments
  237. if include_filaments:
  238. result = await db.execute(select(Filament))
  239. filaments = result.scalars().all()
  240. backup["filaments"] = []
  241. for f in filaments:
  242. backup["filaments"].append({
  243. "name": f.name,
  244. "type": f.type,
  245. "brand": f.brand,
  246. "color": f.color,
  247. "color_hex": f.color_hex,
  248. "cost_per_kg": f.cost_per_kg,
  249. "spool_weight_g": f.spool_weight_g,
  250. "currency": f.currency,
  251. "density": f.density,
  252. "print_temp_min": f.print_temp_min,
  253. "print_temp_max": f.print_temp_max,
  254. "bed_temp_min": f.bed_temp_min,
  255. "bed_temp_max": f.bed_temp_max,
  256. })
  257. backup["included"].append("filaments")
  258. # Maintenance types and records
  259. if include_maintenance:
  260. # Maintenance types
  261. result = await db.execute(select(MaintenanceType))
  262. types = result.scalars().all()
  263. backup["maintenance_types"] = []
  264. for mt in types:
  265. backup["maintenance_types"].append({
  266. "name": mt.name,
  267. "description": mt.description,
  268. "default_interval_hours": mt.default_interval_hours,
  269. "interval_type": mt.interval_type,
  270. "icon": mt.icon,
  271. "is_system": mt.is_system,
  272. })
  273. backup["included"].append("maintenance_types")
  274. # Print archives with file paths for ZIP
  275. archive_files: list[tuple[str, Path]] = [] # (zip_path, local_path)
  276. if include_archives:
  277. result = await db.execute(select(PrintArchive))
  278. archives = result.scalars().all()
  279. backup["archives"] = []
  280. base_dir = app_settings.base_dir
  281. for a in archives:
  282. archive_data = {
  283. "filename": a.filename,
  284. "file_size": a.file_size,
  285. "content_hash": a.content_hash,
  286. "print_name": a.print_name,
  287. "print_time_seconds": a.print_time_seconds,
  288. "filament_used_grams": a.filament_used_grams,
  289. "filament_type": a.filament_type,
  290. "filament_color": a.filament_color,
  291. "layer_height": a.layer_height,
  292. "total_layers": a.total_layers,
  293. "nozzle_diameter": a.nozzle_diameter,
  294. "bed_temperature": a.bed_temperature,
  295. "nozzle_temperature": a.nozzle_temperature,
  296. "status": a.status,
  297. "started_at": a.started_at.isoformat() if a.started_at else None,
  298. "completed_at": a.completed_at.isoformat() if a.completed_at else None,
  299. "makerworld_url": a.makerworld_url,
  300. "designer": a.designer,
  301. "is_favorite": a.is_favorite,
  302. "tags": a.tags,
  303. "notes": a.notes,
  304. "cost": a.cost,
  305. "failure_reason": a.failure_reason,
  306. "energy_kwh": a.energy_kwh,
  307. "energy_cost": a.energy_cost,
  308. "extra_data": a.extra_data,
  309. "photos": a.photos,
  310. }
  311. # Collect file paths for ZIP
  312. if a.file_path:
  313. file_path = base_dir / a.file_path
  314. if file_path.exists():
  315. archive_data["file_path"] = a.file_path
  316. archive_files.append((a.file_path, file_path))
  317. if a.thumbnail_path:
  318. thumb_path = base_dir / a.thumbnail_path
  319. if thumb_path.exists():
  320. archive_data["thumbnail_path"] = a.thumbnail_path
  321. archive_files.append((a.thumbnail_path, thumb_path))
  322. if a.timelapse_path:
  323. timelapse_path = base_dir / a.timelapse_path
  324. if timelapse_path.exists():
  325. archive_data["timelapse_path"] = a.timelapse_path
  326. archive_files.append((a.timelapse_path, timelapse_path))
  327. if a.source_3mf_path:
  328. source_path = base_dir / a.source_3mf_path
  329. if source_path.exists():
  330. archive_data["source_3mf_path"] = a.source_3mf_path
  331. archive_files.append((a.source_3mf_path, source_path))
  332. # Include photos
  333. if a.photos:
  334. for photo in a.photos:
  335. photo_path = base_dir / "archive" / "photos" / photo
  336. if photo_path.exists():
  337. zip_photo_path = f"archive/photos/{photo}"
  338. archive_files.append((zip_photo_path, photo_path))
  339. backup["archives"].append(archive_data)
  340. backup["included"].append("archives")
  341. # If archives included, create ZIP file with all files
  342. if include_archives and archive_files:
  343. zip_buffer = io.BytesIO()
  344. with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
  345. # Add backup.json
  346. zf.writestr("backup.json", json.dumps(backup, indent=2))
  347. # Add all archive files
  348. added_files = set()
  349. for zip_path, local_path in archive_files:
  350. if zip_path not in added_files and local_path.exists():
  351. try:
  352. zf.write(local_path, zip_path)
  353. added_files.add(zip_path)
  354. except Exception:
  355. pass # Skip files that can't be read
  356. zip_buffer.seek(0)
  357. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  358. return StreamingResponse(
  359. zip_buffer,
  360. media_type="application/zip",
  361. headers={"Content-Disposition": f"attachment; filename={filename}"}
  362. )
  363. # Otherwise return JSON
  364. return JSONResponse(
  365. content=backup,
  366. headers={
  367. "Content-Disposition": f"attachment; filename=bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
  368. }
  369. )
  370. @router.post("/restore")
  371. async def import_backup(
  372. file: UploadFile = File(...),
  373. overwrite: bool = Query(False, description="Overwrite existing data instead of skipping duplicates"),
  374. db: AsyncSession = Depends(get_db),
  375. ):
  376. """Restore data from JSON or ZIP backup. By default skips duplicates, set overwrite=true to replace existing."""
  377. try:
  378. content = await file.read()
  379. base_dir = app_settings.base_dir
  380. files_restored = 0
  381. # Check if it's a ZIP file
  382. if file.filename and file.filename.endswith('.zip'):
  383. try:
  384. zip_buffer = io.BytesIO(content)
  385. with zipfile.ZipFile(zip_buffer, 'r') as zf:
  386. # Extract backup.json
  387. if 'backup.json' not in zf.namelist():
  388. return {"success": False, "message": "Invalid ZIP: missing backup.json"}
  389. backup_content = zf.read('backup.json')
  390. backup = json.loads(backup_content.decode("utf-8"))
  391. # Extract all other files to base_dir
  392. for zip_path in zf.namelist():
  393. if zip_path == 'backup.json':
  394. continue
  395. # Ensure path is safe (no path traversal)
  396. if '..' in zip_path or zip_path.startswith('/'):
  397. continue
  398. target_path = base_dir / zip_path
  399. target_path.parent.mkdir(parents=True, exist_ok=True)
  400. with zf.open(zip_path) as src, open(target_path, 'wb') as dst:
  401. dst.write(src.read())
  402. files_restored += 1
  403. except zipfile.BadZipFile:
  404. return {"success": False, "message": "Invalid ZIP file"}
  405. else:
  406. backup = json.loads(content.decode("utf-8"))
  407. except json.JSONDecodeError as e:
  408. return {"success": False, "message": f"Invalid JSON: {str(e)}"}
  409. except Exception as e:
  410. return {"success": False, "message": f"Invalid backup file: {str(e)}"}
  411. restored = {
  412. "settings": 0,
  413. "notification_providers": 0,
  414. "notification_templates": 0,
  415. "smart_plugs": 0,
  416. "printers": 0,
  417. "filaments": 0,
  418. "maintenance_types": 0,
  419. }
  420. skipped = {
  421. "settings": 0,
  422. "notification_providers": 0,
  423. "notification_templates": 0,
  424. "smart_plugs": 0,
  425. "printers": 0,
  426. "filaments": 0,
  427. "maintenance_types": 0,
  428. "archives": 0,
  429. }
  430. skipped_details = {
  431. "notification_providers": [],
  432. "smart_plugs": [],
  433. "printers": [],
  434. "filaments": [],
  435. "maintenance_types": [],
  436. "archives": [],
  437. }
  438. # Restore settings (always overwrites)
  439. if "settings" in backup:
  440. for key, value in backup["settings"].items():
  441. await set_setting(db, key, value)
  442. restored["settings"] += 1
  443. # Restore notification providers (skip or overwrite duplicates by name)
  444. if "notification_providers" in backup:
  445. for provider_data in backup["notification_providers"]:
  446. result = await db.execute(
  447. select(NotificationProvider).where(NotificationProvider.name == provider_data["name"])
  448. )
  449. existing = result.scalar_one_or_none()
  450. if existing:
  451. if overwrite:
  452. # Update existing provider
  453. existing.provider_type = provider_data["provider_type"]
  454. existing.enabled = provider_data.get("enabled", True)
  455. existing.config = json.dumps(provider_data.get("config", {}))
  456. existing.on_print_start = provider_data.get("on_print_start", False)
  457. existing.on_print_complete = provider_data.get("on_print_complete", True)
  458. existing.on_print_failed = provider_data.get("on_print_failed", True)
  459. existing.on_print_stopped = provider_data.get("on_print_stopped", True)
  460. existing.on_print_progress = provider_data.get("on_print_progress", False)
  461. existing.on_printer_offline = provider_data.get("on_printer_offline", False)
  462. existing.on_printer_error = provider_data.get("on_printer_error", False)
  463. existing.on_filament_low = provider_data.get("on_filament_low", False)
  464. existing.on_maintenance_due = provider_data.get("on_maintenance_due", False)
  465. existing.quiet_hours_enabled = provider_data.get("quiet_hours_enabled", False)
  466. existing.quiet_hours_start = provider_data.get("quiet_hours_start")
  467. existing.quiet_hours_end = provider_data.get("quiet_hours_end")
  468. existing.daily_digest_enabled = provider_data.get("daily_digest_enabled", False)
  469. existing.daily_digest_time = provider_data.get("daily_digest_time")
  470. existing.printer_id = provider_data.get("printer_id")
  471. restored["notification_providers"] += 1
  472. else:
  473. skipped["notification_providers"] += 1
  474. skipped_details["notification_providers"].append(provider_data["name"])
  475. else:
  476. provider = NotificationProvider(
  477. name=provider_data["name"],
  478. provider_type=provider_data["provider_type"],
  479. enabled=provider_data.get("enabled", True),
  480. config=json.dumps(provider_data.get("config", {})),
  481. on_print_start=provider_data.get("on_print_start", False),
  482. on_print_complete=provider_data.get("on_print_complete", True),
  483. on_print_failed=provider_data.get("on_print_failed", True),
  484. on_print_stopped=provider_data.get("on_print_stopped", True),
  485. on_print_progress=provider_data.get("on_print_progress", False),
  486. on_printer_offline=provider_data.get("on_printer_offline", False),
  487. on_printer_error=provider_data.get("on_printer_error", False),
  488. on_filament_low=provider_data.get("on_filament_low", False),
  489. on_maintenance_due=provider_data.get("on_maintenance_due", False),
  490. quiet_hours_enabled=provider_data.get("quiet_hours_enabled", False),
  491. quiet_hours_start=provider_data.get("quiet_hours_start"),
  492. quiet_hours_end=provider_data.get("quiet_hours_end"),
  493. daily_digest_enabled=provider_data.get("daily_digest_enabled", False),
  494. daily_digest_time=provider_data.get("daily_digest_time"),
  495. printer_id=provider_data.get("printer_id"),
  496. )
  497. db.add(provider)
  498. restored["notification_providers"] += 1
  499. # Restore notification templates (update existing by event_type)
  500. if "notification_templates" in backup:
  501. for template_data in backup["notification_templates"]:
  502. result = await db.execute(
  503. select(NotificationTemplate).where(
  504. NotificationTemplate.event_type == template_data["event_type"]
  505. )
  506. )
  507. existing = result.scalar_one_or_none()
  508. if existing:
  509. # Update existing template
  510. existing.name = template_data.get("name", existing.name)
  511. existing.title_template = template_data.get("title_template", existing.title_template)
  512. existing.body_template = template_data.get("body_template", existing.body_template)
  513. existing.is_default = template_data.get("is_default", False)
  514. else:
  515. template = NotificationTemplate(
  516. event_type=template_data["event_type"],
  517. name=template_data["name"],
  518. title_template=template_data["title_template"],
  519. body_template=template_data["body_template"],
  520. is_default=template_data.get("is_default", False),
  521. )
  522. db.add(template)
  523. restored["notification_templates"] += 1
  524. # Restore smart plugs (skip or overwrite duplicates by IP)
  525. if "smart_plugs" in backup:
  526. for plug_data in backup["smart_plugs"]:
  527. result = await db.execute(
  528. select(SmartPlug).where(SmartPlug.ip_address == plug_data["ip_address"])
  529. )
  530. existing = result.scalar_one_or_none()
  531. if existing:
  532. if overwrite:
  533. existing.name = plug_data["name"]
  534. existing.printer_id = plug_data.get("printer_id")
  535. existing.enabled = plug_data.get("enabled", True)
  536. existing.auto_on = plug_data.get("auto_on", True)
  537. existing.auto_off = plug_data.get("auto_off", True)
  538. existing.off_delay_mode = plug_data.get("off_delay_mode", "time")
  539. existing.off_delay_minutes = plug_data.get("off_delay_minutes", 5)
  540. existing.off_temp_threshold = plug_data.get("off_temp_threshold", 70)
  541. existing.username = plug_data.get("username")
  542. existing.password = plug_data.get("password")
  543. existing.power_alert_enabled = plug_data.get("power_alert_enabled", False)
  544. existing.power_alert_high = plug_data.get("power_alert_high")
  545. existing.power_alert_low = plug_data.get("power_alert_low")
  546. existing.schedule_enabled = plug_data.get("schedule_enabled", False)
  547. existing.schedule_on_time = plug_data.get("schedule_on_time")
  548. existing.schedule_off_time = plug_data.get("schedule_off_time")
  549. restored["smart_plugs"] += 1
  550. else:
  551. skipped["smart_plugs"] += 1
  552. skipped_details["smart_plugs"].append(f"{plug_data['name']} ({plug_data['ip_address']})")
  553. else:
  554. plug = SmartPlug(
  555. name=plug_data["name"],
  556. ip_address=plug_data["ip_address"],
  557. printer_id=plug_data.get("printer_id"),
  558. enabled=plug_data.get("enabled", True),
  559. auto_on=plug_data.get("auto_on", True),
  560. auto_off=plug_data.get("auto_off", True),
  561. off_delay_mode=plug_data.get("off_delay_mode", "time"),
  562. off_delay_minutes=plug_data.get("off_delay_minutes", 5),
  563. off_temp_threshold=plug_data.get("off_temp_threshold", 70),
  564. username=plug_data.get("username"),
  565. password=plug_data.get("password"),
  566. power_alert_enabled=plug_data.get("power_alert_enabled", False),
  567. power_alert_high=plug_data.get("power_alert_high"),
  568. power_alert_low=plug_data.get("power_alert_low"),
  569. schedule_enabled=plug_data.get("schedule_enabled", False),
  570. schedule_on_time=plug_data.get("schedule_on_time"),
  571. schedule_off_time=plug_data.get("schedule_off_time"),
  572. )
  573. db.add(plug)
  574. restored["smart_plugs"] += 1
  575. # Restore printers (skip or overwrite duplicates by serial_number)
  576. # Note: access_code is never restored for security - must be set manually
  577. if "printers" in backup:
  578. for printer_data in backup["printers"]:
  579. result = await db.execute(
  580. select(Printer).where(Printer.serial_number == printer_data["serial_number"])
  581. )
  582. existing = result.scalar_one_or_none()
  583. if existing:
  584. if overwrite:
  585. existing.name = printer_data["name"]
  586. existing.ip_address = printer_data["ip_address"]
  587. existing.model = printer_data.get("model")
  588. existing.location = printer_data.get("location")
  589. existing.nozzle_count = printer_data.get("nozzle_count", 1)
  590. existing.auto_archive = printer_data.get("auto_archive", True)
  591. existing.print_hours_offset = printer_data.get("print_hours_offset", 0.0)
  592. # Don't overwrite access_code or is_active to preserve working connection
  593. restored["printers"] += 1
  594. else:
  595. skipped["printers"] += 1
  596. skipped_details["printers"].append(f"{printer_data['name']} ({printer_data['serial_number']})")
  597. else:
  598. printer = Printer(
  599. name=printer_data["name"],
  600. serial_number=printer_data["serial_number"],
  601. ip_address=printer_data["ip_address"],
  602. access_code="CHANGE_ME", # Must be set manually for security
  603. model=printer_data.get("model"),
  604. location=printer_data.get("location"),
  605. nozzle_count=printer_data.get("nozzle_count", 1),
  606. is_active=False, # Disabled until access_code is set
  607. auto_archive=printer_data.get("auto_archive", True),
  608. print_hours_offset=printer_data.get("print_hours_offset", 0.0),
  609. )
  610. db.add(printer)
  611. restored["printers"] += 1
  612. # Restore filaments (skip or overwrite duplicates by name+type+brand)
  613. if "filaments" in backup:
  614. for filament_data in backup["filaments"]:
  615. result = await db.execute(
  616. select(Filament).where(
  617. Filament.name == filament_data["name"],
  618. Filament.type == filament_data["type"],
  619. Filament.brand == filament_data.get("brand"),
  620. )
  621. )
  622. existing = result.scalar_one_or_none()
  623. if existing:
  624. if overwrite:
  625. existing.color = filament_data.get("color")
  626. existing.color_hex = filament_data.get("color_hex")
  627. existing.cost_per_kg = filament_data.get("cost_per_kg", 25.0)
  628. existing.spool_weight_g = filament_data.get("spool_weight_g", 1000.0)
  629. existing.currency = filament_data.get("currency", "USD")
  630. existing.density = filament_data.get("density")
  631. existing.print_temp_min = filament_data.get("print_temp_min")
  632. existing.print_temp_max = filament_data.get("print_temp_max")
  633. existing.bed_temp_min = filament_data.get("bed_temp_min")
  634. existing.bed_temp_max = filament_data.get("bed_temp_max")
  635. restored["filaments"] += 1
  636. else:
  637. skipped["filaments"] += 1
  638. skipped_details["filaments"].append(f"{filament_data.get('brand', '')} {filament_data['name']} ({filament_data['type']})")
  639. else:
  640. filament = Filament(
  641. name=filament_data["name"],
  642. type=filament_data["type"],
  643. brand=filament_data.get("brand"),
  644. color=filament_data.get("color"),
  645. color_hex=filament_data.get("color_hex"),
  646. cost_per_kg=filament_data.get("cost_per_kg", 25.0),
  647. spool_weight_g=filament_data.get("spool_weight_g", 1000.0),
  648. currency=filament_data.get("currency", "USD"),
  649. density=filament_data.get("density"),
  650. print_temp_min=filament_data.get("print_temp_min"),
  651. print_temp_max=filament_data.get("print_temp_max"),
  652. bed_temp_min=filament_data.get("bed_temp_min"),
  653. bed_temp_max=filament_data.get("bed_temp_max"),
  654. )
  655. db.add(filament)
  656. restored["filaments"] += 1
  657. # Restore maintenance types (skip or overwrite duplicates by name)
  658. if "maintenance_types" in backup:
  659. for mt_data in backup["maintenance_types"]:
  660. result = await db.execute(
  661. select(MaintenanceType).where(MaintenanceType.name == mt_data["name"])
  662. )
  663. existing = result.scalar_one_or_none()
  664. if existing:
  665. if overwrite:
  666. existing.description = mt_data.get("description")
  667. existing.default_interval_hours = mt_data.get("default_interval_hours", 100.0)
  668. existing.interval_type = mt_data.get("interval_type", "hours")
  669. existing.icon = mt_data.get("icon")
  670. # Don't overwrite is_system
  671. restored["maintenance_types"] += 1
  672. else:
  673. skipped["maintenance_types"] += 1
  674. skipped_details["maintenance_types"].append(mt_data["name"])
  675. else:
  676. mt = MaintenanceType(
  677. name=mt_data["name"],
  678. description=mt_data.get("description"),
  679. default_interval_hours=mt_data.get("default_interval_hours", 100.0),
  680. interval_type=mt_data.get("interval_type", "hours"),
  681. icon=mt_data.get("icon"),
  682. is_system=mt_data.get("is_system", False),
  683. )
  684. db.add(mt)
  685. restored["maintenance_types"] += 1
  686. # Restore archives (skip duplicates by content_hash - overwrite not supported for archives)
  687. if "archives" in backup:
  688. for archive_data in backup["archives"]:
  689. # Skip if no content_hash or already exists
  690. content_hash = archive_data.get("content_hash")
  691. if content_hash:
  692. result = await db.execute(
  693. select(PrintArchive).where(PrintArchive.content_hash == content_hash)
  694. )
  695. existing = result.scalar_one_or_none()
  696. if existing:
  697. skipped["archives"] += 1
  698. skipped_details["archives"].append(archive_data.get("filename", "Unknown"))
  699. continue
  700. # Only restore if file exists (from ZIP extraction)
  701. file_path = archive_data.get("file_path")
  702. if file_path and (base_dir / file_path).exists():
  703. archive = PrintArchive(
  704. filename=archive_data["filename"],
  705. file_path=file_path,
  706. file_size=archive_data.get("file_size", 0),
  707. content_hash=content_hash,
  708. thumbnail_path=archive_data.get("thumbnail_path"),
  709. timelapse_path=archive_data.get("timelapse_path"),
  710. source_3mf_path=archive_data.get("source_3mf_path"),
  711. print_name=archive_data.get("print_name"),
  712. print_time_seconds=archive_data.get("print_time_seconds"),
  713. filament_used_grams=archive_data.get("filament_used_grams"),
  714. filament_type=archive_data.get("filament_type"),
  715. filament_color=archive_data.get("filament_color"),
  716. layer_height=archive_data.get("layer_height"),
  717. total_layers=archive_data.get("total_layers"),
  718. nozzle_diameter=archive_data.get("nozzle_diameter"),
  719. bed_temperature=archive_data.get("bed_temperature"),
  720. nozzle_temperature=archive_data.get("nozzle_temperature"),
  721. status=archive_data.get("status", "completed"),
  722. makerworld_url=archive_data.get("makerworld_url"),
  723. designer=archive_data.get("designer"),
  724. is_favorite=archive_data.get("is_favorite", False),
  725. tags=archive_data.get("tags"),
  726. notes=archive_data.get("notes"),
  727. cost=archive_data.get("cost"),
  728. failure_reason=archive_data.get("failure_reason"),
  729. energy_kwh=archive_data.get("energy_kwh"),
  730. energy_cost=archive_data.get("energy_cost"),
  731. extra_data=archive_data.get("extra_data"),
  732. photos=archive_data.get("photos"),
  733. )
  734. db.add(archive)
  735. restored["archives"] = restored.get("archives", 0) + 1
  736. await db.commit()
  737. # If printers were in the backup (restored, updated, or skipped), reconnect all active printers
  738. # This ensures connections are re-established after restore, even if printers were skipped
  739. if "printers" in backup:
  740. # Fetch all active printers and connect them
  741. result = await db.execute(
  742. select(Printer).where(Printer.is_active == True)
  743. )
  744. active_printers = result.scalars().all()
  745. for printer in active_printers:
  746. # This will disconnect existing connection (if any) and reconnect
  747. await printer_manager.connect_printer(printer)
  748. # Build summary message
  749. restored_parts = []
  750. for key, count in restored.items():
  751. if count > 0:
  752. restored_parts.append(f"{count} {key.replace('_', ' ')}")
  753. if files_restored > 0:
  754. restored_parts.append(f"{files_restored} files")
  755. skipped_parts = []
  756. total_skipped = sum(skipped.values())
  757. for key, count in skipped.items():
  758. if count > 0:
  759. skipped_parts.append(f"{count} {key.replace('_', ' ')}")
  760. message_parts = []
  761. if restored_parts:
  762. message_parts.append(f"Restored: {', '.join(restored_parts)}")
  763. if skipped_parts:
  764. message_parts.append(f"Skipped (already exist): {', '.join(skipped_parts)}")
  765. return {
  766. "success": True,
  767. "message": ". ".join(message_parts) if message_parts else "Nothing to restore",
  768. "restored": restored,
  769. "skipped": skipped,
  770. "skipped_details": skipped_details,
  771. "files_restored": files_restored,
  772. "total_skipped": total_skipped,
  773. }