settings.py 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  1. import io
  2. import json
  3. import zipfile
  4. from datetime import datetime
  5. from pathlib import Path
  6. from fastapi import APIRouter, Depends, File, Query, UploadFile
  7. from fastapi.responses import JSONResponse, StreamingResponse
  8. from sqlalchemy import select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from backend.app.core.config import settings as app_settings
  11. from backend.app.core.database import get_db
  12. from backend.app.models.api_key import APIKey
  13. from backend.app.models.archive import PrintArchive
  14. from backend.app.models.external_link import ExternalLink
  15. from backend.app.models.filament import Filament
  16. from backend.app.models.maintenance import MaintenanceHistory, MaintenanceType, PrinterMaintenance
  17. from backend.app.models.notification import NotificationProvider
  18. from backend.app.models.notification_template import NotificationTemplate
  19. from backend.app.models.pending_upload import PendingUpload
  20. from backend.app.models.print_queue import PrintQueueItem
  21. from backend.app.models.printer import Printer
  22. from backend.app.models.project import Project
  23. from backend.app.models.project_bom import ProjectBOMItem
  24. from backend.app.models.settings import Settings
  25. from backend.app.models.smart_plug import SmartPlug
  26. from backend.app.schemas.settings import AppSettings, AppSettingsUpdate
  27. from backend.app.services.printer_manager import printer_manager
  28. from backend.app.services.spoolman import init_spoolman_client
  29. router = APIRouter(prefix="/settings", tags=["settings"])
  30. # Default settings
  31. DEFAULT_SETTINGS = AppSettings()
  32. async def get_setting(db: AsyncSession, key: str) -> str | None:
  33. """Get a single setting value by key."""
  34. result = await db.execute(select(Settings).where(Settings.key == key))
  35. setting = result.scalar_one_or_none()
  36. return setting.value if setting else None
  37. async def set_setting(db: AsyncSession, key: str, value: str) -> None:
  38. """Set a single setting value."""
  39. from sqlalchemy import func
  40. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  41. # Use upsert (INSERT ... ON CONFLICT UPDATE) for reliability
  42. stmt = sqlite_insert(Settings).values(key=key, value=value)
  43. stmt = stmt.on_conflict_do_update(index_elements=["key"], set_={"value": value, "updated_at": func.now()})
  44. await db.execute(stmt)
  45. @router.get("", response_model=AppSettings)
  46. @router.get("/", response_model=AppSettings)
  47. async def get_settings(db: AsyncSession = Depends(get_db)):
  48. """Get all application settings."""
  49. settings_dict = DEFAULT_SETTINGS.model_dump()
  50. # Load saved settings from database
  51. result = await db.execute(select(Settings))
  52. db_settings = result.scalars().all()
  53. for setting in db_settings:
  54. if setting.key in settings_dict:
  55. # Parse the value based on the expected type
  56. if setting.key in [
  57. "auto_archive",
  58. "save_thumbnails",
  59. "capture_finish_photo",
  60. "spoolman_enabled",
  61. "check_updates",
  62. "telemetry_enabled",
  63. "virtual_printer_enabled",
  64. "ftp_retry_enabled",
  65. "mqtt_enabled",
  66. "mqtt_use_tls",
  67. "ha_enabled",
  68. ]:
  69. settings_dict[setting.key] = setting.value.lower() == "true"
  70. elif setting.key in [
  71. "default_filament_cost",
  72. "energy_cost_per_kwh",
  73. "ams_temp_good",
  74. "ams_temp_fair",
  75. "library_disk_warning_gb",
  76. ]:
  77. settings_dict[setting.key] = float(setting.value)
  78. elif setting.key in [
  79. "ams_humidity_good",
  80. "ams_humidity_fair",
  81. "ams_history_retention_days",
  82. "ftp_retry_count",
  83. "ftp_retry_delay",
  84. "mqtt_port",
  85. ]:
  86. settings_dict[setting.key] = int(setting.value)
  87. elif setting.key == "default_printer_id":
  88. # Handle nullable integer
  89. settings_dict[setting.key] = int(setting.value) if setting.value and setting.value != "None" else None
  90. else:
  91. settings_dict[setting.key] = setting.value
  92. return AppSettings(**settings_dict)
  93. @router.put("/", response_model=AppSettings)
  94. async def update_settings(
  95. settings_update: AppSettingsUpdate,
  96. db: AsyncSession = Depends(get_db),
  97. ):
  98. """Update application settings."""
  99. update_data = settings_update.model_dump(exclude_unset=True)
  100. # Check if any MQTT settings are being updated
  101. mqtt_keys = {
  102. "mqtt_enabled",
  103. "mqtt_broker",
  104. "mqtt_port",
  105. "mqtt_username",
  106. "mqtt_password",
  107. "mqtt_topic_prefix",
  108. "mqtt_use_tls",
  109. }
  110. mqtt_updated = bool(mqtt_keys & set(update_data.keys()))
  111. for key, value in update_data.items():
  112. # Convert value to string for storage
  113. if isinstance(value, bool):
  114. str_value = "true" if value else "false"
  115. elif value is None:
  116. str_value = "None"
  117. else:
  118. str_value = str(value)
  119. await set_setting(db, key, str_value)
  120. await db.commit()
  121. # Reconfigure MQTT relay if any MQTT settings changed
  122. if mqtt_updated:
  123. try:
  124. from backend.app.services.mqtt_relay import mqtt_relay
  125. mqtt_settings = {
  126. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  127. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  128. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  129. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  130. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  131. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  132. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  133. }
  134. await mqtt_relay.configure(mqtt_settings)
  135. except Exception:
  136. pass # Don't fail the settings update if MQTT reconfiguration fails
  137. # Return updated settings
  138. return await get_settings(db)
  139. @router.post("/reset", response_model=AppSettings)
  140. async def reset_settings(db: AsyncSession = Depends(get_db)):
  141. """Reset all settings to defaults."""
  142. # Delete all settings
  143. result = await db.execute(select(Settings))
  144. for setting in result.scalars().all():
  145. await db.delete(setting)
  146. await db.commit()
  147. return DEFAULT_SETTINGS
  148. @router.get("/check-ffmpeg")
  149. async def check_ffmpeg():
  150. """Check if ffmpeg is installed and available."""
  151. from backend.app.services.camera import get_ffmpeg_path
  152. ffmpeg_path = get_ffmpeg_path()
  153. return {
  154. "installed": ffmpeg_path is not None,
  155. "path": ffmpeg_path,
  156. }
  157. @router.get("/spoolman")
  158. async def get_spoolman_settings(db: AsyncSession = Depends(get_db)):
  159. """Get Spoolman integration settings."""
  160. spoolman_enabled = await get_setting(db, "spoolman_enabled") or "false"
  161. spoolman_url = await get_setting(db, "spoolman_url") or ""
  162. spoolman_sync_mode = await get_setting(db, "spoolman_sync_mode") or "auto"
  163. return {
  164. "spoolman_enabled": spoolman_enabled,
  165. "spoolman_url": spoolman_url,
  166. "spoolman_sync_mode": spoolman_sync_mode,
  167. }
  168. @router.put("/spoolman")
  169. async def update_spoolman_settings(
  170. settings: dict,
  171. db: AsyncSession = Depends(get_db),
  172. ):
  173. """Update Spoolman integration settings."""
  174. if "spoolman_enabled" in settings:
  175. await set_setting(db, "spoolman_enabled", settings["spoolman_enabled"])
  176. if "spoolman_url" in settings:
  177. await set_setting(db, "spoolman_url", settings["spoolman_url"])
  178. if "spoolman_sync_mode" in settings:
  179. await set_setting(db, "spoolman_sync_mode", settings["spoolman_sync_mode"])
  180. await db.commit()
  181. # Return updated settings
  182. return await get_spoolman_settings(db)
  183. @router.get("/backup")
  184. async def export_backup(
  185. db: AsyncSession = Depends(get_db),
  186. include_settings: bool = Query(True, description="Include app settings"),
  187. include_notifications: bool = Query(True, description="Include notification providers"),
  188. include_templates: bool = Query(True, description="Include notification templates"),
  189. include_smart_plugs: bool = Query(True, description="Include smart plugs"),
  190. include_external_links: bool = Query(True, description="Include external sidebar links"),
  191. include_printers: bool = Query(False, description="Include printers (without access codes)"),
  192. include_filaments: bool = Query(False, description="Include filament inventory"),
  193. include_maintenance: bool = Query(
  194. False, description="Include maintenance types, per-printer settings, and history"
  195. ),
  196. include_print_queue: bool = Query(False, description="Include print queue items"),
  197. include_archives: bool = Query(False, description="Include print archive metadata"),
  198. include_projects: bool = Query(False, description="Include projects with BOM items"),
  199. include_pending_uploads: bool = Query(False, description="Include pending virtual printer uploads"),
  200. include_access_codes: bool = Query(False, description="Include printer access codes (security risk!)"),
  201. include_api_keys: bool = Query(False, description="Include API keys (keys will need to be regenerated on import)"),
  202. ):
  203. """Export selected data as JSON backup."""
  204. backup: dict = {
  205. "version": "2.0",
  206. "exported_at": datetime.utcnow().isoformat(),
  207. "included": [],
  208. }
  209. # Settings
  210. if include_settings:
  211. result = await db.execute(select(Settings))
  212. db_settings = result.scalars().all()
  213. backup["settings"] = {s.key: s.value for s in db_settings}
  214. backup["included"].append("settings")
  215. # Notification providers
  216. if include_notifications:
  217. # Build printer ID to serial lookup for cross-system backup
  218. printer_id_to_serial: dict[int, str] = {}
  219. pr_result = await db.execute(select(Printer))
  220. for pr in pr_result.scalars().all():
  221. printer_id_to_serial[pr.id] = pr.serial_number
  222. result = await db.execute(select(NotificationProvider))
  223. providers = result.scalars().all()
  224. backup["notification_providers"] = []
  225. for p in providers:
  226. # Use printer_serial for cross-system compatibility
  227. provider_printer_id = getattr(p, "printer_id", None)
  228. printer_serial = printer_id_to_serial.get(provider_printer_id) if provider_printer_id else None
  229. backup["notification_providers"].append(
  230. {
  231. "name": p.name,
  232. "provider_type": p.provider_type,
  233. "enabled": p.enabled,
  234. "config": json.loads(p.config) if isinstance(p.config, str) else p.config,
  235. "on_print_start": p.on_print_start,
  236. "on_print_complete": p.on_print_complete,
  237. "on_print_failed": p.on_print_failed,
  238. "on_print_stopped": p.on_print_stopped,
  239. "on_print_progress": p.on_print_progress,
  240. "on_printer_offline": p.on_printer_offline,
  241. "on_printer_error": p.on_printer_error,
  242. "on_filament_low": p.on_filament_low,
  243. "on_maintenance_due": p.on_maintenance_due,
  244. "on_ams_humidity_high": getattr(p, "on_ams_humidity_high", False),
  245. "on_ams_temperature_high": getattr(p, "on_ams_temperature_high", False),
  246. "on_ams_ht_humidity_high": getattr(p, "on_ams_ht_humidity_high", False),
  247. "on_ams_ht_temperature_high": getattr(p, "on_ams_ht_temperature_high", False),
  248. "quiet_hours_enabled": p.quiet_hours_enabled,
  249. "quiet_hours_start": p.quiet_hours_start,
  250. "quiet_hours_end": p.quiet_hours_end,
  251. "daily_digest_enabled": getattr(p, "daily_digest_enabled", False),
  252. "daily_digest_time": getattr(p, "daily_digest_time", None),
  253. "printer_serial": printer_serial,
  254. }
  255. )
  256. backup["included"].append("notification_providers")
  257. # Notification templates
  258. if include_templates:
  259. result = await db.execute(select(NotificationTemplate))
  260. templates = result.scalars().all()
  261. backup["notification_templates"] = []
  262. for t in templates:
  263. backup["notification_templates"].append(
  264. {
  265. "event_type": t.event_type,
  266. "name": t.name,
  267. "title_template": t.title_template,
  268. "body_template": t.body_template,
  269. "is_default": t.is_default,
  270. }
  271. )
  272. backup["included"].append("notification_templates")
  273. # Smart plugs
  274. if include_smart_plugs:
  275. result = await db.execute(select(SmartPlug))
  276. plugs = result.scalars().all()
  277. backup["smart_plugs"] = []
  278. # Build printer ID to serial mapping
  279. printer_id_to_serial: dict[int, str] = {}
  280. pr_result = await db.execute(select(Printer))
  281. for pr in pr_result.scalars().all():
  282. printer_id_to_serial[pr.id] = pr.serial_number
  283. for plug in plugs:
  284. backup["smart_plugs"].append(
  285. {
  286. "name": plug.name,
  287. "plug_type": plug.plug_type,
  288. "ip_address": plug.ip_address,
  289. "ha_entity_id": plug.ha_entity_id,
  290. "printer_serial": printer_id_to_serial.get(plug.printer_id) if plug.printer_id else None,
  291. "enabled": plug.enabled,
  292. "auto_on": plug.auto_on,
  293. "auto_off": plug.auto_off,
  294. "off_delay_mode": plug.off_delay_mode,
  295. "off_delay_minutes": plug.off_delay_minutes,
  296. "off_temp_threshold": plug.off_temp_threshold,
  297. "username": plug.username,
  298. "password": plug.password,
  299. "power_alert_enabled": plug.power_alert_enabled,
  300. "power_alert_high": plug.power_alert_high,
  301. "power_alert_low": plug.power_alert_low,
  302. "schedule_enabled": plug.schedule_enabled,
  303. "schedule_on_time": plug.schedule_on_time,
  304. "schedule_off_time": plug.schedule_off_time,
  305. "show_in_switchbar": plug.show_in_switchbar,
  306. }
  307. )
  308. backup["included"].append("smart_plugs")
  309. # External links
  310. if include_external_links:
  311. result = await db.execute(select(ExternalLink).order_by(ExternalLink.sort_order))
  312. links = result.scalars().all()
  313. backup["external_links"] = []
  314. icons_dir = app_settings.base_dir / "icons"
  315. for link in links:
  316. link_data = {
  317. "name": link.name,
  318. "url": link.url,
  319. "icon": link.icon,
  320. "sort_order": link.sort_order,
  321. }
  322. # Include custom icon file path if exists
  323. if link.custom_icon:
  324. link_data["custom_icon"] = link.custom_icon
  325. icon_path = icons_dir / link.custom_icon
  326. if icon_path.exists():
  327. link_data["custom_icon_path"] = f"icons/{link.custom_icon}"
  328. backup["external_links"].append(link_data)
  329. backup["included"].append("external_links")
  330. # Printers (access codes only included if explicitly requested)
  331. if include_printers:
  332. result = await db.execute(select(Printer))
  333. printers = result.scalars().all()
  334. backup["printers"] = []
  335. for printer in printers:
  336. printer_data = {
  337. "name": printer.name,
  338. "serial_number": printer.serial_number,
  339. "ip_address": printer.ip_address,
  340. "model": printer.model,
  341. "location": printer.location,
  342. "nozzle_count": printer.nozzle_count,
  343. "is_active": printer.is_active,
  344. "auto_archive": printer.auto_archive,
  345. "print_hours_offset": printer.print_hours_offset,
  346. "runtime_seconds": printer.runtime_seconds,
  347. }
  348. if include_access_codes:
  349. printer_data["access_code"] = printer.access_code
  350. backup["printers"].append(printer_data)
  351. backup["included"].append("printers")
  352. if include_access_codes:
  353. backup["included"].append("access_codes")
  354. # Filaments
  355. if include_filaments:
  356. result = await db.execute(select(Filament))
  357. filaments = result.scalars().all()
  358. backup["filaments"] = []
  359. for f in filaments:
  360. backup["filaments"].append(
  361. {
  362. "name": f.name,
  363. "type": f.type,
  364. "brand": f.brand,
  365. "color": f.color,
  366. "color_hex": f.color_hex,
  367. "cost_per_kg": f.cost_per_kg,
  368. "spool_weight_g": f.spool_weight_g,
  369. "currency": f.currency,
  370. "density": f.density,
  371. "print_temp_min": f.print_temp_min,
  372. "print_temp_max": f.print_temp_max,
  373. "bed_temp_min": f.bed_temp_min,
  374. "bed_temp_max": f.bed_temp_max,
  375. }
  376. )
  377. backup["included"].append("filaments")
  378. # Maintenance types and records
  379. if include_maintenance:
  380. # Maintenance types
  381. result = await db.execute(select(MaintenanceType))
  382. types = result.scalars().all()
  383. backup["maintenance_types"] = []
  384. for mt in types:
  385. backup["maintenance_types"].append(
  386. {
  387. "name": mt.name,
  388. "description": mt.description,
  389. "default_interval_hours": mt.default_interval_hours,
  390. "interval_type": mt.interval_type,
  391. "icon": mt.icon,
  392. "is_system": mt.is_system,
  393. }
  394. )
  395. backup["included"].append("maintenance_types")
  396. # Printer maintenance settings (per-printer custom intervals, enabled status, last performed)
  397. result = await db.execute(select(PrinterMaintenance))
  398. printer_maint = result.scalars().all()
  399. backup["printer_maintenance"] = []
  400. # Build lookups for printer serial and maintenance type name
  401. printer_id_to_serial: dict[int, str] = {}
  402. maint_type_id_to_name: dict[int, str] = {}
  403. pr_result = await db.execute(select(Printer))
  404. for pr in pr_result.scalars().all():
  405. printer_id_to_serial[pr.id] = pr.serial_number
  406. for mt in types:
  407. maint_type_id_to_name[mt.id] = mt.name
  408. for pm in printer_maint:
  409. backup["printer_maintenance"].append(
  410. {
  411. "printer_serial": printer_id_to_serial.get(pm.printer_id),
  412. "maintenance_type_name": maint_type_id_to_name.get(pm.maintenance_type_id),
  413. "custom_interval_hours": pm.custom_interval_hours,
  414. "custom_interval_type": pm.custom_interval_type,
  415. "enabled": pm.enabled,
  416. "last_performed_at": pm.last_performed_at.isoformat() if pm.last_performed_at else None,
  417. "last_performed_hours": pm.last_performed_hours,
  418. }
  419. )
  420. backup["included"].append("printer_maintenance")
  421. # Maintenance history
  422. result = await db.execute(select(MaintenanceHistory))
  423. history = result.scalars().all()
  424. backup["maintenance_history"] = []
  425. # Build printer_maintenance ID to (printer_serial, maint_type_name) mapping
  426. pm_id_to_info: dict[int, tuple[str | None, str | None]] = {}
  427. for pm in printer_maint:
  428. pm_id_to_info[pm.id] = (
  429. printer_id_to_serial.get(pm.printer_id),
  430. maint_type_id_to_name.get(pm.maintenance_type_id),
  431. )
  432. for mh in history:
  433. info = pm_id_to_info.get(mh.printer_maintenance_id, (None, None))
  434. backup["maintenance_history"].append(
  435. {
  436. "printer_serial": info[0],
  437. "maintenance_type_name": info[1],
  438. "performed_at": mh.performed_at.isoformat() if mh.performed_at else None,
  439. "hours_at_maintenance": mh.hours_at_maintenance,
  440. "notes": mh.notes,
  441. }
  442. )
  443. backup["included"].append("maintenance_history")
  444. # Print queue
  445. if include_print_queue:
  446. result = await db.execute(select(PrintQueueItem))
  447. queue_items = result.scalars().all()
  448. backup["print_queue"] = []
  449. # Build lookups
  450. printer_id_to_serial: dict[int, str] = {}
  451. archive_id_to_hash: dict[int, str | None] = {}
  452. project_id_to_name: dict[int, str] = {}
  453. pr_result = await db.execute(select(Printer))
  454. for pr in pr_result.scalars().all():
  455. printer_id_to_serial[pr.id] = pr.serial_number
  456. ar_result = await db.execute(select(PrintArchive))
  457. for ar in ar_result.scalars().all():
  458. archive_id_to_hash[ar.id] = ar.content_hash
  459. proj_result = await db.execute(select(Project))
  460. for proj in proj_result.scalars().all():
  461. project_id_to_name[proj.id] = proj.name
  462. for qi in queue_items:
  463. backup["print_queue"].append(
  464. {
  465. "printer_serial": printer_id_to_serial.get(qi.printer_id) if qi.printer_id else None,
  466. "archive_hash": archive_id_to_hash.get(qi.archive_id),
  467. "project_name": project_id_to_name.get(qi.project_id) if qi.project_id else None,
  468. "position": qi.position,
  469. "scheduled_time": qi.scheduled_time.isoformat() if qi.scheduled_time else None,
  470. "require_previous_success": qi.require_previous_success,
  471. "auto_off_after": qi.auto_off_after,
  472. "manual_start": qi.manual_start,
  473. "ams_mapping": qi.ams_mapping,
  474. "plate_id": qi.plate_id,
  475. "bed_levelling": qi.bed_levelling,
  476. "flow_cali": qi.flow_cali,
  477. "vibration_cali": qi.vibration_cali,
  478. "layer_inspect": qi.layer_inspect,
  479. "timelapse": qi.timelapse,
  480. "use_ams": qi.use_ams,
  481. "status": qi.status,
  482. "started_at": qi.started_at.isoformat() if qi.started_at else None,
  483. "completed_at": qi.completed_at.isoformat() if qi.completed_at else None,
  484. "error_message": qi.error_message,
  485. }
  486. )
  487. backup["included"].append("print_queue")
  488. # Collect files for ZIP (icons + archives + project attachments)
  489. backup_files: list[tuple[str, Path]] = [] # (zip_path, local_path)
  490. base_dir = app_settings.base_dir
  491. # Add external link icon files
  492. if include_external_links and "external_links" in backup:
  493. icons_dir = base_dir / "icons"
  494. for link_data in backup["external_links"]:
  495. if "custom_icon_path" in link_data:
  496. icon_path = icons_dir / link_data["custom_icon"]
  497. if icon_path.exists():
  498. backup_files.append((link_data["custom_icon_path"], icon_path))
  499. # Print archives with file paths for ZIP
  500. if include_archives:
  501. result = await db.execute(select(PrintArchive))
  502. archives = result.scalars().all()
  503. backup["archives"] = []
  504. # Build project ID to name mapping for archive export
  505. project_id_to_name: dict[int, str] = {}
  506. if include_projects:
  507. proj_result = await db.execute(select(Project))
  508. for proj in proj_result.scalars().all():
  509. project_id_to_name[proj.id] = proj.name
  510. # Build printer ID to serial mapping for archive export
  511. printer_id_to_serial: dict[int, str] = {}
  512. if include_printers:
  513. printer_result = await db.execute(select(Printer))
  514. for pr in printer_result.scalars().all():
  515. printer_id_to_serial[pr.id] = pr.serial_number
  516. for a in archives:
  517. archive_data = {
  518. "filename": a.filename,
  519. "project_name": project_id_to_name.get(a.project_id) if a.project_id else None,
  520. "printer_serial": printer_id_to_serial.get(a.printer_id) if a.printer_id else None,
  521. "file_size": a.file_size,
  522. "content_hash": a.content_hash,
  523. "print_name": a.print_name,
  524. "print_time_seconds": a.print_time_seconds,
  525. "filament_used_grams": a.filament_used_grams,
  526. "filament_type": a.filament_type,
  527. "filament_color": a.filament_color,
  528. "layer_height": a.layer_height,
  529. "total_layers": a.total_layers,
  530. "nozzle_diameter": a.nozzle_diameter,
  531. "bed_temperature": a.bed_temperature,
  532. "nozzle_temperature": a.nozzle_temperature,
  533. "status": a.status,
  534. "started_at": a.started_at.isoformat() if a.started_at else None,
  535. "completed_at": a.completed_at.isoformat() if a.completed_at else None,
  536. "makerworld_url": a.makerworld_url,
  537. "designer": a.designer,
  538. "is_favorite": a.is_favorite,
  539. "tags": a.tags,
  540. "notes": a.notes,
  541. "cost": a.cost,
  542. "failure_reason": a.failure_reason,
  543. "quantity": a.quantity,
  544. "energy_kwh": a.energy_kwh,
  545. "energy_cost": a.energy_cost,
  546. "extra_data": a.extra_data,
  547. "photos": a.photos,
  548. }
  549. # Collect file paths for ZIP
  550. if a.file_path:
  551. file_path = base_dir / a.file_path
  552. if file_path.exists():
  553. archive_data["file_path"] = a.file_path
  554. backup_files.append((a.file_path, file_path))
  555. if a.thumbnail_path:
  556. thumb_path = base_dir / a.thumbnail_path
  557. if thumb_path.exists():
  558. archive_data["thumbnail_path"] = a.thumbnail_path
  559. backup_files.append((a.thumbnail_path, thumb_path))
  560. if a.timelapse_path:
  561. timelapse_path = base_dir / a.timelapse_path
  562. if timelapse_path.exists():
  563. archive_data["timelapse_path"] = a.timelapse_path
  564. backup_files.append((a.timelapse_path, timelapse_path))
  565. if a.source_3mf_path:
  566. source_path = base_dir / a.source_3mf_path
  567. if source_path.exists():
  568. archive_data["source_3mf_path"] = a.source_3mf_path
  569. backup_files.append((a.source_3mf_path, source_path))
  570. if a.f3d_path:
  571. f3d_path = base_dir / a.f3d_path
  572. if f3d_path.exists():
  573. archive_data["f3d_path"] = a.f3d_path
  574. backup_files.append((a.f3d_path, f3d_path))
  575. # Include photos
  576. if a.photos:
  577. for photo in a.photos:
  578. photo_path = base_dir / "archive" / "photos" / photo
  579. if photo_path.exists():
  580. zip_photo_path = f"archive/photos/{photo}"
  581. backup_files.append((zip_photo_path, photo_path))
  582. backup["archives"].append(archive_data)
  583. backup["included"].append("archives")
  584. # Projects with BOM items
  585. if include_projects:
  586. result = await db.execute(select(Project))
  587. projects = result.scalars().all()
  588. backup["projects"] = []
  589. for p in projects:
  590. # Get BOM items for this project
  591. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == p.id))
  592. bom_items = bom_result.scalars().all()
  593. project_data = {
  594. "name": p.name,
  595. "description": p.description,
  596. "color": p.color,
  597. "status": p.status,
  598. "target_count": p.target_count,
  599. "notes": p.notes,
  600. "tags": p.tags,
  601. "due_date": p.due_date.isoformat() if p.due_date else None,
  602. "priority": p.priority,
  603. "budget": p.budget,
  604. "is_template": p.is_template,
  605. "template_source_id": p.template_source_id,
  606. "parent_id": p.parent_id,
  607. "bom_items": [
  608. {
  609. "name": item.name,
  610. "quantity_needed": item.quantity_needed,
  611. "quantity_acquired": item.quantity_acquired,
  612. "unit_price": item.unit_price,
  613. "sourcing_url": item.sourcing_url,
  614. "stl_filename": item.stl_filename,
  615. "remarks": item.remarks,
  616. "sort_order": item.sort_order,
  617. }
  618. for item in bom_items
  619. ],
  620. }
  621. # Include attachment files for ZIP
  622. if p.attachments:
  623. project_data["attachments"] = p.attachments
  624. attachments_dir = base_dir / "projects" / str(p.id) / "attachments"
  625. for att in p.attachments:
  626. att_path = attachments_dir / att.get("filename", "")
  627. if att_path.exists():
  628. zip_path = f"projects/{p.id}/attachments/{att['filename']}"
  629. backup_files.append((zip_path, att_path))
  630. backup["projects"].append(project_data)
  631. backup["included"].append("projects")
  632. # Pending uploads (virtual printer queue mode)
  633. if include_pending_uploads:
  634. result = await db.execute(select(PendingUpload).where(PendingUpload.status == "pending"))
  635. pending_uploads = result.scalars().all()
  636. backup["pending_uploads"] = []
  637. for p in pending_uploads:
  638. upload_data = {
  639. "filename": p.filename,
  640. "file_size": p.file_size,
  641. "source_ip": p.source_ip,
  642. "status": p.status,
  643. "tags": p.tags,
  644. "notes": p.notes,
  645. "project_id": p.project_id,
  646. "uploaded_at": p.uploaded_at.isoformat() if p.uploaded_at else None,
  647. }
  648. # Include the actual file if it exists
  649. if p.file_path:
  650. file_path = Path(p.file_path)
  651. if file_path.exists():
  652. # Store relative path for ZIP
  653. rel_path = f"pending_uploads/{p.filename}"
  654. upload_data["file_path"] = rel_path
  655. backup_files.append((rel_path, file_path))
  656. backup["pending_uploads"].append(upload_data)
  657. backup["included"].append("pending_uploads")
  658. # API keys (note: key_hash cannot be restored, new keys must be generated)
  659. if include_api_keys:
  660. # Build printer ID to serial mapping for cross-system compatibility
  661. printer_id_to_serial: dict[int, str] = {}
  662. pr_result = await db.execute(select(Printer))
  663. for pr in pr_result.scalars().all():
  664. printer_id_to_serial[pr.id] = pr.serial_number
  665. result = await db.execute(select(APIKey))
  666. api_keys = result.scalars().all()
  667. backup["api_keys"] = []
  668. for key in api_keys:
  669. # Convert printer_ids from list of IDs to list of serials
  670. printer_serials = None
  671. if key.printer_ids:
  672. printer_serials = [
  673. printer_id_to_serial.get(pid) for pid in key.printer_ids if pid in printer_id_to_serial
  674. ]
  675. backup["api_keys"].append(
  676. {
  677. "name": key.name,
  678. "key_prefix": key.key_prefix, # For identification only
  679. "can_queue": key.can_queue,
  680. "can_control_printer": key.can_control_printer,
  681. "can_read_status": key.can_read_status,
  682. "printer_serials": printer_serials, # Use serials instead of IDs
  683. "enabled": key.enabled,
  684. "expires_at": key.expires_at.isoformat() if key.expires_at else None,
  685. }
  686. )
  687. backup["included"].append("api_keys")
  688. # If there are files to include (icons or archives), create ZIP file
  689. if backup_files:
  690. zip_buffer = io.BytesIO()
  691. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  692. # Add backup.json
  693. zf.writestr("backup.json", json.dumps(backup, indent=2))
  694. # Add all backup files (icons, archives, etc.)
  695. added_files = set()
  696. for zip_path, local_path in backup_files:
  697. if zip_path not in added_files and local_path.exists():
  698. try:
  699. zf.write(local_path, zip_path)
  700. added_files.add(zip_path)
  701. except Exception:
  702. pass # Skip files that can't be read
  703. zip_buffer.seek(0)
  704. filename = f"bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip"
  705. return StreamingResponse(
  706. zip_buffer,
  707. media_type="application/zip",
  708. headers={"Content-Disposition": f"attachment; filename={filename}"},
  709. )
  710. # Otherwise return JSON
  711. return JSONResponse(
  712. content=backup,
  713. headers={
  714. "Content-Disposition": f"attachment; filename=bambuddy-backup-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
  715. },
  716. )
  717. @router.post("/restore")
  718. async def import_backup(
  719. file: UploadFile = File(...),
  720. overwrite: bool = Query(False, description="Overwrite existing data instead of skipping duplicates"),
  721. db: AsyncSession = Depends(get_db),
  722. ):
  723. """Restore data from JSON or ZIP backup. By default skips duplicates, set overwrite=true to replace existing."""
  724. try:
  725. content = await file.read()
  726. base_dir = app_settings.base_dir
  727. files_restored = 0
  728. # Check if it's a ZIP file
  729. if file.filename and file.filename.endswith(".zip"):
  730. try:
  731. zip_buffer = io.BytesIO(content)
  732. with zipfile.ZipFile(zip_buffer, "r") as zf:
  733. # Extract backup.json
  734. if "backup.json" not in zf.namelist():
  735. return {"success": False, "message": "Invalid ZIP: missing backup.json"}
  736. backup_content = zf.read("backup.json")
  737. backup = json.loads(backup_content.decode("utf-8"))
  738. # Extract all other files to base_dir
  739. for zip_path in zf.namelist():
  740. if zip_path == "backup.json":
  741. continue
  742. # Ensure path is safe (no path traversal)
  743. if ".." in zip_path or zip_path.startswith("/"):
  744. continue
  745. target_path = base_dir / zip_path
  746. target_path.parent.mkdir(parents=True, exist_ok=True)
  747. with zf.open(zip_path) as src, open(target_path, "wb") as dst:
  748. dst.write(src.read())
  749. files_restored += 1
  750. except zipfile.BadZipFile:
  751. return {"success": False, "message": "Invalid ZIP file"}
  752. else:
  753. backup = json.loads(content.decode("utf-8"))
  754. except json.JSONDecodeError as e:
  755. return {"success": False, "message": f"Invalid JSON: {str(e)}"}
  756. except Exception as e:
  757. return {"success": False, "message": f"Invalid backup file: {str(e)}"}
  758. restored = {
  759. "settings": 0,
  760. "notification_providers": 0,
  761. "notification_templates": 0,
  762. "smart_plugs": 0,
  763. "external_links": 0,
  764. "printers": 0,
  765. "filaments": 0,
  766. "maintenance_types": 0,
  767. "projects": 0,
  768. "pending_uploads": 0,
  769. }
  770. skipped = {
  771. "settings": 0,
  772. "notification_providers": 0,
  773. "notification_templates": 0,
  774. "smart_plugs": 0,
  775. "external_links": 0,
  776. "printers": 0,
  777. "filaments": 0,
  778. "maintenance_types": 0,
  779. "archives": 0,
  780. "projects": 0,
  781. "pending_uploads": 0,
  782. }
  783. skipped_details = {
  784. "notification_providers": [],
  785. "smart_plugs": [],
  786. "external_links": [],
  787. "printers": [],
  788. "filaments": [],
  789. "maintenance_types": [],
  790. "archives": [],
  791. "projects": [],
  792. "pending_uploads": [],
  793. }
  794. # Restore settings (always overwrites)
  795. if "settings" in backup:
  796. for key, value in backup["settings"].items():
  797. # Convert value to proper string format for storage
  798. if isinstance(value, bool):
  799. str_value = "true" if value else "false"
  800. elif value is None:
  801. str_value = "None"
  802. else:
  803. str_value = str(value)
  804. await set_setting(db, key, str_value)
  805. restored["settings"] += 1
  806. # Flush settings to ensure they're persisted before continuing
  807. await db.flush()
  808. # Restore printers FIRST (skip or overwrite duplicates by serial_number)
  809. # Nearly everything in the app references printers, so they must be imported first
  810. if "printers" in backup:
  811. for printer_data in backup["printers"]:
  812. result = await db.execute(select(Printer).where(Printer.serial_number == printer_data["serial_number"]))
  813. existing = result.scalar_one_or_none()
  814. if existing:
  815. if overwrite:
  816. existing.name = printer_data["name"]
  817. existing.ip_address = printer_data["ip_address"]
  818. existing.model = printer_data.get("model")
  819. existing.location = printer_data.get("location")
  820. existing.nozzle_count = printer_data.get("nozzle_count", 1)
  821. existing.auto_archive = printer_data.get("auto_archive", True)
  822. existing.print_hours_offset = printer_data.get("print_hours_offset", 0.0)
  823. existing.runtime_seconds = printer_data.get("runtime_seconds", 0)
  824. # If backup includes access_code, also update access_code and is_active
  825. backup_access_code = printer_data.get("access_code")
  826. if backup_access_code and backup_access_code != "CHANGE_ME":
  827. existing.access_code = backup_access_code
  828. is_active_val = printer_data.get("is_active", False)
  829. if isinstance(is_active_val, str):
  830. is_active_val = is_active_val.lower() == "true"
  831. existing.is_active = is_active_val
  832. restored["printers"] += 1
  833. else:
  834. skipped["printers"] += 1
  835. skipped_details["printers"].append(f"{printer_data['name']} ({printer_data['serial_number']})")
  836. else:
  837. # Use access code from backup if provided, otherwise require manual setup
  838. access_code = printer_data.get("access_code")
  839. has_access_code = access_code and access_code != "CHANGE_ME"
  840. is_active_from_backup = printer_data.get("is_active", False)
  841. # Handle bool or string "true"/"false"
  842. if isinstance(is_active_from_backup, str):
  843. is_active_from_backup = is_active_from_backup.lower() == "true"
  844. printer = Printer(
  845. name=printer_data["name"],
  846. serial_number=printer_data["serial_number"],
  847. ip_address=printer_data["ip_address"],
  848. access_code=access_code if has_access_code else "CHANGE_ME",
  849. model=printer_data.get("model"),
  850. location=printer_data.get("location"),
  851. nozzle_count=printer_data.get("nozzle_count", 1),
  852. is_active=is_active_from_backup if has_access_code else False,
  853. auto_archive=printer_data.get("auto_archive", True),
  854. print_hours_offset=printer_data.get("print_hours_offset", 0.0),
  855. runtime_seconds=printer_data.get("runtime_seconds", 0),
  856. )
  857. db.add(printer)
  858. restored["printers"] += 1
  859. # Flush printers so other sections can look them up
  860. await db.flush()
  861. # Restore notification providers (skip or overwrite duplicates by name)
  862. # Build printer serial to ID lookup (printers were restored first)
  863. if "notification_providers" in backup:
  864. printer_serial_to_id: dict[str, int] = {}
  865. pr_result = await db.execute(select(Printer))
  866. for pr in pr_result.scalars().all():
  867. printer_serial_to_id[pr.serial_number] = pr.id
  868. for provider_data in backup["notification_providers"]:
  869. # Look up printer_id from serial (supports both old printer_id and new printer_serial format)
  870. printer_serial = provider_data.get("printer_serial")
  871. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else provider_data.get("printer_id")
  872. result = await db.execute(
  873. select(NotificationProvider).where(NotificationProvider.name == provider_data["name"])
  874. )
  875. existing = result.scalar_one_or_none()
  876. if existing:
  877. if overwrite:
  878. # Update existing provider
  879. existing.provider_type = provider_data["provider_type"]
  880. existing.enabled = provider_data.get("enabled", True)
  881. existing.config = json.dumps(provider_data.get("config", {}))
  882. existing.on_print_start = provider_data.get("on_print_start", False)
  883. existing.on_print_complete = provider_data.get("on_print_complete", True)
  884. existing.on_print_failed = provider_data.get("on_print_failed", True)
  885. existing.on_print_stopped = provider_data.get("on_print_stopped", True)
  886. existing.on_print_progress = provider_data.get("on_print_progress", False)
  887. existing.on_printer_offline = provider_data.get("on_printer_offline", False)
  888. existing.on_printer_error = provider_data.get("on_printer_error", False)
  889. existing.on_filament_low = provider_data.get("on_filament_low", False)
  890. existing.on_maintenance_due = provider_data.get("on_maintenance_due", False)
  891. existing.on_ams_humidity_high = provider_data.get("on_ams_humidity_high", False)
  892. existing.on_ams_temperature_high = provider_data.get("on_ams_temperature_high", False)
  893. existing.on_ams_ht_humidity_high = provider_data.get("on_ams_ht_humidity_high", False)
  894. existing.on_ams_ht_temperature_high = provider_data.get("on_ams_ht_temperature_high", False)
  895. existing.quiet_hours_enabled = provider_data.get("quiet_hours_enabled", False)
  896. existing.quiet_hours_start = provider_data.get("quiet_hours_start")
  897. existing.quiet_hours_end = provider_data.get("quiet_hours_end")
  898. existing.daily_digest_enabled = provider_data.get("daily_digest_enabled", False)
  899. existing.daily_digest_time = provider_data.get("daily_digest_time")
  900. existing.printer_id = printer_id
  901. restored["notification_providers"] += 1
  902. else:
  903. skipped["notification_providers"] += 1
  904. skipped_details["notification_providers"].append(provider_data["name"])
  905. else:
  906. provider = NotificationProvider(
  907. name=provider_data["name"],
  908. provider_type=provider_data["provider_type"],
  909. enabled=provider_data.get("enabled", True),
  910. config=json.dumps(provider_data.get("config", {})),
  911. on_print_start=provider_data.get("on_print_start", False),
  912. on_print_complete=provider_data.get("on_print_complete", True),
  913. on_print_failed=provider_data.get("on_print_failed", True),
  914. on_print_stopped=provider_data.get("on_print_stopped", True),
  915. on_print_progress=provider_data.get("on_print_progress", False),
  916. on_printer_offline=provider_data.get("on_printer_offline", False),
  917. on_printer_error=provider_data.get("on_printer_error", False),
  918. on_filament_low=provider_data.get("on_filament_low", False),
  919. on_maintenance_due=provider_data.get("on_maintenance_due", False),
  920. on_ams_humidity_high=provider_data.get("on_ams_humidity_high", False),
  921. on_ams_temperature_high=provider_data.get("on_ams_temperature_high", False),
  922. on_ams_ht_humidity_high=provider_data.get("on_ams_ht_humidity_high", False),
  923. on_ams_ht_temperature_high=provider_data.get("on_ams_ht_temperature_high", False),
  924. quiet_hours_enabled=provider_data.get("quiet_hours_enabled", False),
  925. quiet_hours_start=provider_data.get("quiet_hours_start"),
  926. quiet_hours_end=provider_data.get("quiet_hours_end"),
  927. daily_digest_enabled=provider_data.get("daily_digest_enabled", False),
  928. daily_digest_time=provider_data.get("daily_digest_time"),
  929. printer_id=printer_id,
  930. )
  931. db.add(provider)
  932. restored["notification_providers"] += 1
  933. # Restore notification templates (update existing by event_type)
  934. if "notification_templates" in backup:
  935. for template_data in backup["notification_templates"]:
  936. result = await db.execute(
  937. select(NotificationTemplate).where(NotificationTemplate.event_type == template_data["event_type"])
  938. )
  939. existing = result.scalar_one_or_none()
  940. if existing:
  941. # Update existing template
  942. existing.name = template_data.get("name", existing.name)
  943. existing.title_template = template_data.get("title_template", existing.title_template)
  944. existing.body_template = template_data.get("body_template", existing.body_template)
  945. existing.is_default = template_data.get("is_default", False)
  946. else:
  947. template = NotificationTemplate(
  948. event_type=template_data["event_type"],
  949. name=template_data["name"],
  950. title_template=template_data["title_template"],
  951. body_template=template_data["body_template"],
  952. is_default=template_data.get("is_default", False),
  953. )
  954. db.add(template)
  955. restored["notification_templates"] += 1
  956. # Restore smart plugs (skip or overwrite duplicates by IP)
  957. # Note: Smart plugs reference printers, so printers should be restored first
  958. if "smart_plugs" in backup:
  959. # Build printer serial to ID lookup
  960. printer_serial_to_id: dict[str, int] = {}
  961. pr_result = await db.execute(select(Printer))
  962. for pr in pr_result.scalars().all():
  963. printer_serial_to_id[pr.serial_number] = pr.id
  964. for plug_data in backup["smart_plugs"]:
  965. # Look up printer_id from serial (supports both old printer_id and new printer_serial format)
  966. printer_serial = plug_data.get("printer_serial")
  967. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else plug_data.get("printer_id")
  968. # Determine plug type (default to tasmota for backwards compatibility)
  969. plug_type = plug_data.get("plug_type", "tasmota")
  970. # Find existing plug by IP (Tasmota) or entity_id (Home Assistant)
  971. existing = None
  972. if plug_type == "homeassistant" and plug_data.get("ha_entity_id"):
  973. result = await db.execute(select(SmartPlug).where(SmartPlug.ha_entity_id == plug_data["ha_entity_id"]))
  974. existing = result.scalar_one_or_none()
  975. plug_identifier = plug_data["ha_entity_id"]
  976. elif plug_data.get("ip_address"):
  977. result = await db.execute(select(SmartPlug).where(SmartPlug.ip_address == plug_data["ip_address"]))
  978. existing = result.scalar_one_or_none()
  979. plug_identifier = plug_data["ip_address"]
  980. else:
  981. # Skip invalid plug data
  982. continue
  983. if existing:
  984. if overwrite:
  985. existing.name = plug_data["name"]
  986. existing.plug_type = plug_type
  987. existing.ha_entity_id = plug_data.get("ha_entity_id")
  988. existing.printer_id = printer_id
  989. existing.enabled = plug_data.get("enabled", True)
  990. existing.auto_on = plug_data.get("auto_on", True)
  991. existing.auto_off = plug_data.get("auto_off", True)
  992. existing.off_delay_mode = plug_data.get("off_delay_mode", "time")
  993. existing.off_delay_minutes = plug_data.get("off_delay_minutes", 5)
  994. existing.off_temp_threshold = plug_data.get("off_temp_threshold", 70)
  995. existing.username = plug_data.get("username")
  996. existing.password = plug_data.get("password")
  997. existing.power_alert_enabled = plug_data.get("power_alert_enabled", False)
  998. existing.power_alert_high = plug_data.get("power_alert_high")
  999. existing.power_alert_low = plug_data.get("power_alert_low")
  1000. existing.schedule_enabled = plug_data.get("schedule_enabled", False)
  1001. existing.schedule_on_time = plug_data.get("schedule_on_time")
  1002. existing.schedule_off_time = plug_data.get("schedule_off_time")
  1003. existing.show_in_switchbar = plug_data.get("show_in_switchbar", False)
  1004. restored["smart_plugs"] += 1
  1005. else:
  1006. skipped["smart_plugs"] += 1
  1007. skipped_details["smart_plugs"].append(f"{plug_data['name']} ({plug_identifier})")
  1008. else:
  1009. plug = SmartPlug(
  1010. name=plug_data["name"],
  1011. plug_type=plug_type,
  1012. ip_address=plug_data.get("ip_address"),
  1013. ha_entity_id=plug_data.get("ha_entity_id"),
  1014. printer_id=printer_id,
  1015. enabled=plug_data.get("enabled", True),
  1016. auto_on=plug_data.get("auto_on", True),
  1017. auto_off=plug_data.get("auto_off", True),
  1018. off_delay_mode=plug_data.get("off_delay_mode", "time"),
  1019. off_delay_minutes=plug_data.get("off_delay_minutes", 5),
  1020. off_temp_threshold=plug_data.get("off_temp_threshold", 70),
  1021. username=plug_data.get("username"),
  1022. password=plug_data.get("password"),
  1023. power_alert_enabled=plug_data.get("power_alert_enabled", False),
  1024. power_alert_high=plug_data.get("power_alert_high"),
  1025. power_alert_low=plug_data.get("power_alert_low"),
  1026. schedule_enabled=plug_data.get("schedule_enabled", False),
  1027. schedule_on_time=plug_data.get("schedule_on_time"),
  1028. schedule_off_time=plug_data.get("schedule_off_time"),
  1029. show_in_switchbar=plug_data.get("show_in_switchbar", False),
  1030. )
  1031. db.add(plug)
  1032. restored["smart_plugs"] += 1
  1033. # Restore external links (skip or overwrite duplicates by name+url)
  1034. if "external_links" in backup:
  1035. icons_dir = base_dir / "icons"
  1036. icons_dir.mkdir(parents=True, exist_ok=True)
  1037. for link_data in backup["external_links"]:
  1038. result = await db.execute(
  1039. select(ExternalLink).where(ExternalLink.name == link_data["name"], ExternalLink.url == link_data["url"])
  1040. )
  1041. existing = result.scalar_one_or_none()
  1042. if existing:
  1043. if overwrite:
  1044. existing.icon = link_data.get("icon", "link")
  1045. existing.sort_order = link_data.get("sort_order", 0)
  1046. # Handle custom icon
  1047. if link_data.get("custom_icon"):
  1048. existing.custom_icon = link_data["custom_icon"]
  1049. restored["external_links"] += 1
  1050. else:
  1051. skipped["external_links"] += 1
  1052. skipped_details["external_links"].append(link_data["name"])
  1053. else:
  1054. link = ExternalLink(
  1055. name=link_data["name"],
  1056. url=link_data["url"],
  1057. icon=link_data.get("icon", "link"),
  1058. custom_icon=link_data.get("custom_icon"),
  1059. sort_order=link_data.get("sort_order", 0),
  1060. )
  1061. db.add(link)
  1062. restored["external_links"] += 1
  1063. # Restore filaments (skip or overwrite duplicates by name+type+brand)
  1064. if "filaments" in backup:
  1065. for filament_data in backup["filaments"]:
  1066. result = await db.execute(
  1067. select(Filament).where(
  1068. Filament.name == filament_data["name"],
  1069. Filament.type == filament_data["type"],
  1070. Filament.brand == filament_data.get("brand"),
  1071. )
  1072. )
  1073. existing = result.scalar_one_or_none()
  1074. if existing:
  1075. if overwrite:
  1076. existing.color = filament_data.get("color")
  1077. existing.color_hex = filament_data.get("color_hex")
  1078. existing.cost_per_kg = filament_data.get("cost_per_kg", 25.0)
  1079. existing.spool_weight_g = filament_data.get("spool_weight_g", 1000.0)
  1080. existing.currency = filament_data.get("currency", "USD")
  1081. existing.density = filament_data.get("density")
  1082. existing.print_temp_min = filament_data.get("print_temp_min")
  1083. existing.print_temp_max = filament_data.get("print_temp_max")
  1084. existing.bed_temp_min = filament_data.get("bed_temp_min")
  1085. existing.bed_temp_max = filament_data.get("bed_temp_max")
  1086. restored["filaments"] += 1
  1087. else:
  1088. skipped["filaments"] += 1
  1089. skipped_details["filaments"].append(
  1090. f"{filament_data.get('brand', '')} {filament_data['name']} ({filament_data['type']})"
  1091. )
  1092. else:
  1093. filament = Filament(
  1094. name=filament_data["name"],
  1095. type=filament_data["type"],
  1096. brand=filament_data.get("brand"),
  1097. color=filament_data.get("color"),
  1098. color_hex=filament_data.get("color_hex"),
  1099. cost_per_kg=filament_data.get("cost_per_kg", 25.0),
  1100. spool_weight_g=filament_data.get("spool_weight_g", 1000.0),
  1101. currency=filament_data.get("currency", "USD"),
  1102. density=filament_data.get("density"),
  1103. print_temp_min=filament_data.get("print_temp_min"),
  1104. print_temp_max=filament_data.get("print_temp_max"),
  1105. bed_temp_min=filament_data.get("bed_temp_min"),
  1106. bed_temp_max=filament_data.get("bed_temp_max"),
  1107. )
  1108. db.add(filament)
  1109. restored["filaments"] += 1
  1110. # Restore maintenance types (skip or overwrite duplicates by name)
  1111. if "maintenance_types" in backup:
  1112. for mt_data in backup["maintenance_types"]:
  1113. result = await db.execute(select(MaintenanceType).where(MaintenanceType.name == mt_data["name"]))
  1114. existing = result.scalar_one_or_none()
  1115. if existing:
  1116. if overwrite:
  1117. existing.description = mt_data.get("description")
  1118. existing.default_interval_hours = mt_data.get("default_interval_hours", 100.0)
  1119. existing.interval_type = mt_data.get("interval_type", "hours")
  1120. existing.icon = mt_data.get("icon")
  1121. # Don't overwrite is_system
  1122. restored["maintenance_types"] += 1
  1123. else:
  1124. skipped["maintenance_types"] += 1
  1125. skipped_details["maintenance_types"].append(mt_data["name"])
  1126. else:
  1127. mt = MaintenanceType(
  1128. name=mt_data["name"],
  1129. description=mt_data.get("description"),
  1130. default_interval_hours=mt_data.get("default_interval_hours", 100.0),
  1131. interval_type=mt_data.get("interval_type", "hours"),
  1132. icon=mt_data.get("icon"),
  1133. is_system=mt_data.get("is_system", False),
  1134. )
  1135. db.add(mt)
  1136. restored["maintenance_types"] += 1
  1137. # Restore printer maintenance settings (per-printer)
  1138. if "printer_maintenance" in backup:
  1139. # Build lookups
  1140. printer_serial_to_id: dict[str, int] = {}
  1141. maint_type_name_to_id: dict[str, int] = {}
  1142. pr_result = await db.execute(select(Printer))
  1143. for pr in pr_result.scalars().all():
  1144. printer_serial_to_id[pr.serial_number] = pr.id
  1145. mt_result = await db.execute(select(MaintenanceType))
  1146. for mt in mt_result.scalars().all():
  1147. maint_type_name_to_id[mt.name] = mt.id
  1148. restored["printer_maintenance"] = 0
  1149. skipped["printer_maintenance"] = 0
  1150. skipped_details["printer_maintenance"] = []
  1151. for pm_data in backup["printer_maintenance"]:
  1152. printer_serial = pm_data.get("printer_serial")
  1153. maint_type_name = pm_data.get("maintenance_type_name")
  1154. if not printer_serial or not maint_type_name:
  1155. continue
  1156. printer_id = printer_serial_to_id.get(printer_serial)
  1157. maint_type_id = maint_type_name_to_id.get(maint_type_name)
  1158. if not printer_id or not maint_type_id:
  1159. skipped["printer_maintenance"] += 1
  1160. skipped_details["printer_maintenance"].append(f"{printer_serial}/{maint_type_name}")
  1161. continue
  1162. # Check if exists
  1163. result = await db.execute(
  1164. select(PrinterMaintenance).where(
  1165. PrinterMaintenance.printer_id == printer_id,
  1166. PrinterMaintenance.maintenance_type_id == maint_type_id,
  1167. )
  1168. )
  1169. existing = result.scalar_one_or_none()
  1170. if existing:
  1171. if overwrite:
  1172. existing.custom_interval_hours = pm_data.get("custom_interval_hours")
  1173. existing.custom_interval_type = pm_data.get("custom_interval_type")
  1174. existing.enabled = pm_data.get("enabled", True)
  1175. existing.last_performed_hours = pm_data.get("last_performed_hours", 0.0)
  1176. if pm_data.get("last_performed_at"):
  1177. existing.last_performed_at = datetime.fromisoformat(pm_data["last_performed_at"])
  1178. restored["printer_maintenance"] += 1
  1179. else:
  1180. skipped["printer_maintenance"] += 1
  1181. skipped_details["printer_maintenance"].append(f"{printer_serial}/{maint_type_name}")
  1182. else:
  1183. pm = PrinterMaintenance(
  1184. printer_id=printer_id,
  1185. maintenance_type_id=maint_type_id,
  1186. custom_interval_hours=pm_data.get("custom_interval_hours"),
  1187. custom_interval_type=pm_data.get("custom_interval_type"),
  1188. enabled=pm_data.get("enabled", True),
  1189. last_performed_hours=pm_data.get("last_performed_hours", 0.0),
  1190. )
  1191. if pm_data.get("last_performed_at"):
  1192. pm.last_performed_at = datetime.fromisoformat(pm_data["last_performed_at"])
  1193. db.add(pm)
  1194. restored["printer_maintenance"] += 1
  1195. # Restore maintenance history
  1196. if "maintenance_history" in backup:
  1197. # Build lookups
  1198. printer_serial_to_id: dict[str, int] = {}
  1199. maint_type_name_to_id: dict[str, int] = {}
  1200. pr_result = await db.execute(select(Printer))
  1201. for pr in pr_result.scalars().all():
  1202. printer_serial_to_id[pr.serial_number] = pr.id
  1203. mt_result = await db.execute(select(MaintenanceType))
  1204. for mt in mt_result.scalars().all():
  1205. maint_type_name_to_id[mt.name] = mt.id
  1206. restored["maintenance_history"] = 0
  1207. skipped["maintenance_history"] = 0
  1208. skipped_details["maintenance_history"] = []
  1209. for mh_data in backup["maintenance_history"]:
  1210. printer_serial = mh_data.get("printer_serial")
  1211. maint_type_name = mh_data.get("maintenance_type_name")
  1212. if not printer_serial or not maint_type_name:
  1213. continue
  1214. printer_id = printer_serial_to_id.get(printer_serial)
  1215. maint_type_id = maint_type_name_to_id.get(maint_type_name)
  1216. if not printer_id or not maint_type_id:
  1217. skipped["maintenance_history"] += 1
  1218. continue
  1219. # Find the PrinterMaintenance record
  1220. result = await db.execute(
  1221. select(PrinterMaintenance).where(
  1222. PrinterMaintenance.printer_id == printer_id,
  1223. PrinterMaintenance.maintenance_type_id == maint_type_id,
  1224. )
  1225. )
  1226. pm = result.scalar_one_or_none()
  1227. if not pm:
  1228. skipped["maintenance_history"] += 1
  1229. continue
  1230. # Create history entry (no duplicate check - history is append-only)
  1231. mh = MaintenanceHistory(
  1232. printer_maintenance_id=pm.id,
  1233. hours_at_maintenance=mh_data.get("hours_at_maintenance", 0.0),
  1234. notes=mh_data.get("notes"),
  1235. )
  1236. if mh_data.get("performed_at"):
  1237. mh.performed_at = datetime.fromisoformat(mh_data["performed_at"])
  1238. db.add(mh)
  1239. restored["maintenance_history"] += 1
  1240. # Restore archives (skip duplicates by content_hash - overwrite not supported for archives)
  1241. if "archives" in backup:
  1242. # Build printer serial to ID mapping
  1243. printer_serial_to_id: dict[str, int] = {}
  1244. printer_result = await db.execute(select(Printer))
  1245. for pr in printer_result.scalars().all():
  1246. printer_serial_to_id[pr.serial_number] = pr.id
  1247. for archive_data in backup["archives"]:
  1248. # Skip if no content_hash or already exists
  1249. content_hash = archive_data.get("content_hash")
  1250. if content_hash:
  1251. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash == content_hash))
  1252. existing = result.scalar_one_or_none()
  1253. if existing:
  1254. skipped["archives"] += 1
  1255. skipped_details["archives"].append(archive_data.get("filename", "Unknown"))
  1256. continue
  1257. # Only restore if file exists (from ZIP extraction)
  1258. file_path = archive_data.get("file_path")
  1259. if file_path and (base_dir / file_path).exists():
  1260. # Look up printer_id from serial
  1261. printer_serial = archive_data.get("printer_serial")
  1262. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else None
  1263. archive = PrintArchive(
  1264. filename=archive_data["filename"],
  1265. file_path=file_path,
  1266. file_size=archive_data.get("file_size", 0),
  1267. content_hash=content_hash,
  1268. printer_id=printer_id,
  1269. thumbnail_path=archive_data.get("thumbnail_path"),
  1270. timelapse_path=archive_data.get("timelapse_path"),
  1271. source_3mf_path=archive_data.get("source_3mf_path"),
  1272. f3d_path=archive_data.get("f3d_path"),
  1273. print_name=archive_data.get("print_name"),
  1274. print_time_seconds=archive_data.get("print_time_seconds"),
  1275. filament_used_grams=archive_data.get("filament_used_grams"),
  1276. filament_type=archive_data.get("filament_type"),
  1277. filament_color=archive_data.get("filament_color"),
  1278. layer_height=archive_data.get("layer_height"),
  1279. total_layers=archive_data.get("total_layers"),
  1280. nozzle_diameter=archive_data.get("nozzle_diameter"),
  1281. bed_temperature=archive_data.get("bed_temperature"),
  1282. nozzle_temperature=archive_data.get("nozzle_temperature"),
  1283. status=archive_data.get("status", "completed"),
  1284. makerworld_url=archive_data.get("makerworld_url"),
  1285. designer=archive_data.get("designer"),
  1286. is_favorite=archive_data.get("is_favorite", False),
  1287. tags=archive_data.get("tags"),
  1288. notes=archive_data.get("notes"),
  1289. cost=archive_data.get("cost"),
  1290. failure_reason=archive_data.get("failure_reason"),
  1291. quantity=archive_data.get("quantity", 1),
  1292. energy_kwh=archive_data.get("energy_kwh"),
  1293. energy_cost=archive_data.get("energy_cost"),
  1294. extra_data=archive_data.get("extra_data"),
  1295. photos=archive_data.get("photos"),
  1296. )
  1297. db.add(archive)
  1298. restored["archives"] = restored.get("archives", 0) + 1
  1299. # Restore projects (skip or overwrite duplicates by name)
  1300. if "projects" in backup:
  1301. for project_data in backup["projects"]:
  1302. result = await db.execute(select(Project).where(Project.name == project_data["name"]))
  1303. existing = result.scalar_one_or_none()
  1304. if existing:
  1305. if overwrite:
  1306. # Update existing project
  1307. existing.description = project_data.get("description")
  1308. existing.color = project_data.get("color")
  1309. existing.status = project_data.get("status", "active")
  1310. existing.target_count = project_data.get("target_count")
  1311. existing.notes = project_data.get("notes")
  1312. existing.tags = project_data.get("tags")
  1313. existing.priority = project_data.get("priority", "normal")
  1314. existing.budget = project_data.get("budget")
  1315. existing.is_template = project_data.get("is_template", False)
  1316. existing.template_source_id = project_data.get("template_source_id")
  1317. existing.parent_id = project_data.get("parent_id")
  1318. existing.attachments = project_data.get("attachments")
  1319. if project_data.get("due_date"):
  1320. existing.due_date = datetime.fromisoformat(project_data["due_date"])
  1321. # Delete existing BOM items and re-add
  1322. await db.execute(ProjectBOMItem.__table__.delete().where(ProjectBOMItem.project_id == existing.id))
  1323. for bom_data in project_data.get("bom_items", []):
  1324. bom_item = ProjectBOMItem(
  1325. project_id=existing.id,
  1326. name=bom_data["name"],
  1327. quantity_needed=bom_data.get("quantity_needed", 1),
  1328. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1329. unit_price=bom_data.get("unit_price"),
  1330. sourcing_url=bom_data.get("sourcing_url"),
  1331. stl_filename=bom_data.get("stl_filename"),
  1332. remarks=bom_data.get("remarks"),
  1333. sort_order=bom_data.get("sort_order", 0),
  1334. )
  1335. db.add(bom_item)
  1336. restored["projects"] += 1
  1337. else:
  1338. skipped["projects"] += 1
  1339. skipped_details["projects"].append(project_data["name"])
  1340. else:
  1341. # Create new project
  1342. project = Project(
  1343. name=project_data["name"],
  1344. description=project_data.get("description"),
  1345. color=project_data.get("color"),
  1346. status=project_data.get("status", "active"),
  1347. target_count=project_data.get("target_count"),
  1348. notes=project_data.get("notes"),
  1349. tags=project_data.get("tags"),
  1350. priority=project_data.get("priority", "normal"),
  1351. budget=project_data.get("budget"),
  1352. is_template=project_data.get("is_template", False),
  1353. template_source_id=project_data.get("template_source_id"),
  1354. parent_id=project_data.get("parent_id"),
  1355. attachments=project_data.get("attachments"),
  1356. )
  1357. if project_data.get("due_date"):
  1358. project.due_date = datetime.fromisoformat(project_data["due_date"])
  1359. db.add(project)
  1360. await db.flush() # Get the project ID
  1361. # Add BOM items
  1362. for bom_data in project_data.get("bom_items", []):
  1363. bom_item = ProjectBOMItem(
  1364. project_id=project.id,
  1365. name=bom_data["name"],
  1366. quantity_needed=bom_data.get("quantity_needed", 1),
  1367. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1368. unit_price=bom_data.get("unit_price"),
  1369. sourcing_url=bom_data.get("sourcing_url"),
  1370. stl_filename=bom_data.get("stl_filename"),
  1371. remarks=bom_data.get("remarks"),
  1372. sort_order=bom_data.get("sort_order", 0),
  1373. )
  1374. db.add(bom_item)
  1375. restored["projects"] += 1
  1376. # Link archives to projects by name (after both are restored)
  1377. if "archives" in backup and "projects" in backup:
  1378. # Build project name to ID mapping
  1379. proj_result = await db.execute(select(Project))
  1380. project_name_to_id: dict[str, int] = {}
  1381. for proj in proj_result.scalars().all():
  1382. project_name_to_id[proj.name] = proj.id
  1383. # Update archives with project_id
  1384. for archive_data in backup["archives"]:
  1385. project_name = archive_data.get("project_name")
  1386. if project_name and project_name in project_name_to_id:
  1387. content_hash = archive_data.get("content_hash")
  1388. if content_hash:
  1389. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash == content_hash))
  1390. archive = result.scalar_one_or_none()
  1391. if archive:
  1392. archive.project_id = project_name_to_id[project_name]
  1393. # Restore print queue (must be after archives and projects)
  1394. if "print_queue" in backup:
  1395. # Build lookups
  1396. printer_serial_to_id: dict[str, int] = {}
  1397. archive_hash_to_id: dict[str, int] = {}
  1398. project_name_to_id: dict[str, int] = {}
  1399. pr_result = await db.execute(select(Printer))
  1400. for pr in pr_result.scalars().all():
  1401. printer_serial_to_id[pr.serial_number] = pr.id
  1402. ar_result = await db.execute(select(PrintArchive))
  1403. for ar in ar_result.scalars().all():
  1404. if ar.content_hash:
  1405. archive_hash_to_id[ar.content_hash] = ar.id
  1406. proj_result = await db.execute(select(Project))
  1407. for proj in proj_result.scalars().all():
  1408. project_name_to_id[proj.name] = proj.id
  1409. restored["print_queue"] = 0
  1410. skipped["print_queue"] = 0
  1411. skipped_details["print_queue"] = []
  1412. for qi_data in backup["print_queue"]:
  1413. printer_serial = qi_data.get("printer_serial") # Can be None for unassigned items
  1414. archive_hash = qi_data.get("archive_hash")
  1415. # Archive is required, but printer can be None (unassigned)
  1416. if not archive_hash:
  1417. skipped["print_queue"] += 1
  1418. continue
  1419. # Look up printer_id (None if unassigned or printer not found)
  1420. printer_id = printer_serial_to_id.get(printer_serial) if printer_serial else None
  1421. archive_id = archive_hash_to_id.get(archive_hash)
  1422. # Archive must exist, but printer is optional (unassigned items)
  1423. if not archive_id:
  1424. skipped["print_queue"] += 1
  1425. skipped_details["print_queue"].append(
  1426. f"{printer_serial or 'unassigned'}/{archive_hash[:8] if archive_hash else 'N/A'}"
  1427. )
  1428. continue
  1429. # If printer_serial was specified but printer not found, skip
  1430. if printer_serial and not printer_id:
  1431. skipped["print_queue"] += 1
  1432. skipped_details["print_queue"].append(f"{printer_serial}/{archive_hash[:8]}")
  1433. continue
  1434. project_name = qi_data.get("project_name")
  1435. project_id = project_name_to_id.get(project_name) if project_name else None
  1436. qi = PrintQueueItem(
  1437. printer_id=printer_id, # Can be None for unassigned items
  1438. archive_id=archive_id,
  1439. project_id=project_id,
  1440. position=qi_data.get("position", 0),
  1441. require_previous_success=qi_data.get("require_previous_success", False),
  1442. auto_off_after=qi_data.get("auto_off_after", False),
  1443. manual_start=qi_data.get("manual_start", False),
  1444. ams_mapping=qi_data.get("ams_mapping"),
  1445. plate_id=qi_data.get("plate_id"),
  1446. bed_levelling=qi_data.get("bed_levelling", True),
  1447. flow_cali=qi_data.get("flow_cali", False),
  1448. vibration_cali=qi_data.get("vibration_cali", True),
  1449. layer_inspect=qi_data.get("layer_inspect", False),
  1450. timelapse=qi_data.get("timelapse", False),
  1451. use_ams=qi_data.get("use_ams", True),
  1452. status=qi_data.get("status", "pending"),
  1453. error_message=qi_data.get("error_message"),
  1454. )
  1455. if qi_data.get("scheduled_time"):
  1456. qi.scheduled_time = datetime.fromisoformat(qi_data["scheduled_time"])
  1457. if qi_data.get("started_at"):
  1458. qi.started_at = datetime.fromisoformat(qi_data["started_at"])
  1459. if qi_data.get("completed_at"):
  1460. qi.completed_at = datetime.fromisoformat(qi_data["completed_at"])
  1461. db.add(qi)
  1462. restored["print_queue"] += 1
  1463. # Restore pending uploads (skip duplicates by filename)
  1464. if "pending_uploads" in backup:
  1465. # Ensure the pending uploads directory exists
  1466. pending_uploads_dir = base_dir / "virtual_printer" / "uploads"
  1467. pending_uploads_dir.mkdir(parents=True, exist_ok=True)
  1468. for upload_data in backup["pending_uploads"]:
  1469. # Check for existing by filename
  1470. result = await db.execute(
  1471. select(PendingUpload).where(
  1472. PendingUpload.filename == upload_data["filename"],
  1473. PendingUpload.status == "pending",
  1474. )
  1475. )
  1476. existing = result.scalar_one_or_none()
  1477. if existing:
  1478. if overwrite:
  1479. # Update existing
  1480. existing.file_size = upload_data.get("file_size", 0)
  1481. existing.source_ip = upload_data.get("source_ip")
  1482. existing.tags = upload_data.get("tags")
  1483. existing.notes = upload_data.get("notes")
  1484. existing.project_id = upload_data.get("project_id")
  1485. # Update file path if file was restored from ZIP
  1486. if upload_data.get("file_path"):
  1487. restored_file = base_dir / upload_data["file_path"]
  1488. if restored_file.exists():
  1489. # Move to proper location
  1490. target_path = pending_uploads_dir / upload_data["filename"]
  1491. if restored_file != target_path:
  1492. import shutil
  1493. shutil.move(str(restored_file), str(target_path))
  1494. existing.file_path = str(target_path)
  1495. restored["pending_uploads"] += 1
  1496. else:
  1497. skipped["pending_uploads"] += 1
  1498. skipped_details["pending_uploads"].append(upload_data["filename"])
  1499. else:
  1500. # Determine file path
  1501. file_path_str = None
  1502. if upload_data.get("file_path"):
  1503. restored_file = base_dir / upload_data["file_path"]
  1504. if restored_file.exists():
  1505. # Move to proper location
  1506. target_path = pending_uploads_dir / upload_data["filename"]
  1507. if restored_file != target_path:
  1508. import shutil
  1509. shutil.move(str(restored_file), str(target_path))
  1510. file_path_str = str(target_path)
  1511. # Parse uploaded_at
  1512. uploaded_at = None
  1513. if upload_data.get("uploaded_at"):
  1514. try:
  1515. uploaded_at = datetime.fromisoformat(upload_data["uploaded_at"].replace("Z", "+00:00"))
  1516. except (ValueError, AttributeError):
  1517. uploaded_at = datetime.utcnow()
  1518. else:
  1519. uploaded_at = datetime.utcnow()
  1520. pending = PendingUpload(
  1521. filename=upload_data["filename"],
  1522. file_path=file_path_str or "",
  1523. file_size=upload_data.get("file_size", 0),
  1524. source_ip=upload_data.get("source_ip"),
  1525. status="pending",
  1526. tags=upload_data.get("tags"),
  1527. notes=upload_data.get("notes"),
  1528. project_id=upload_data.get("project_id"),
  1529. uploaded_at=uploaded_at,
  1530. )
  1531. db.add(pending)
  1532. restored["pending_uploads"] += 1
  1533. # Restore API keys (generates new keys since we can't restore the hash)
  1534. new_api_keys: list[dict] = [] # Track newly generated keys for response
  1535. if "api_keys" in backup:
  1536. from backend.app.core.auth import generate_api_key
  1537. # Build printer serial to ID mapping
  1538. printer_serial_to_id: dict[str, int] = {}
  1539. pr_result = await db.execute(select(Printer))
  1540. for pr in pr_result.scalars().all():
  1541. printer_serial_to_id[pr.serial_number] = pr.id
  1542. restored["api_keys"] = 0
  1543. skipped["api_keys"] = 0
  1544. skipped_details["api_keys"] = []
  1545. for key_data in backup["api_keys"]:
  1546. # Check if key with same name already exists
  1547. result = await db.execute(select(APIKey).where(APIKey.name == key_data["name"]))
  1548. existing = result.scalar_one_or_none()
  1549. if existing:
  1550. if overwrite:
  1551. # Update permissions but keep the existing key
  1552. existing.can_queue = key_data.get("can_queue", True)
  1553. existing.can_control_printer = key_data.get("can_control_printer", False)
  1554. existing.can_read_status = key_data.get("can_read_status", True)
  1555. existing.enabled = key_data.get("enabled", True)
  1556. if key_data.get("expires_at"):
  1557. existing.expires_at = datetime.fromisoformat(key_data["expires_at"])
  1558. # Convert printer serials to IDs
  1559. if key_data.get("printer_serials"):
  1560. existing.printer_ids = [
  1561. printer_serial_to_id[s] for s in key_data["printer_serials"] if s in printer_serial_to_id
  1562. ]
  1563. restored["api_keys"] += 1
  1564. else:
  1565. skipped["api_keys"] += 1
  1566. skipped_details["api_keys"].append(key_data["name"])
  1567. else:
  1568. # Generate new key
  1569. full_key, key_hash, key_prefix = generate_api_key()
  1570. # Convert printer serials to IDs
  1571. printer_ids = None
  1572. if key_data.get("printer_serials"):
  1573. printer_ids = [
  1574. printer_serial_to_id[s] for s in key_data["printer_serials"] if s in printer_serial_to_id
  1575. ]
  1576. api_key = APIKey(
  1577. name=key_data["name"],
  1578. key_hash=key_hash,
  1579. key_prefix=key_prefix,
  1580. can_queue=key_data.get("can_queue", True),
  1581. can_control_printer=key_data.get("can_control_printer", False),
  1582. can_read_status=key_data.get("can_read_status", True),
  1583. printer_ids=printer_ids,
  1584. enabled=key_data.get("enabled", True),
  1585. )
  1586. if key_data.get("expires_at"):
  1587. api_key.expires_at = datetime.fromisoformat(key_data["expires_at"])
  1588. db.add(api_key)
  1589. restored["api_keys"] += 1
  1590. # Track the new key so user can see it
  1591. new_api_keys.append(
  1592. {
  1593. "name": key_data["name"],
  1594. "key": full_key,
  1595. "key_prefix": key_prefix,
  1596. }
  1597. )
  1598. await db.commit()
  1599. # If printers were in the backup (restored, updated, or skipped), reconnect all active printers
  1600. # This ensures connections are re-established after restore, even if printers were skipped
  1601. if "printers" in backup:
  1602. # Need fresh query after commit to get proper IDs for newly created printers
  1603. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1604. active_printers = result.scalars().all()
  1605. for printer in active_printers:
  1606. # This will disconnect existing connection (if any) and reconnect
  1607. try:
  1608. await printer_manager.connect_printer(printer)
  1609. except Exception:
  1610. pass # Connection failed, but don't fail the restore
  1611. # If settings were restored, check if Spoolman needs to be reconnected
  1612. if "settings" in backup:
  1613. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1614. spoolman_url = await get_setting(db, "spoolman_url")
  1615. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1616. try:
  1617. client = await init_spoolman_client(spoolman_url)
  1618. if await client.health_check():
  1619. pass # Connected successfully
  1620. except Exception:
  1621. pass # Spoolman connection failed, but don't fail the restore
  1622. # Reconfigure virtual printer if settings were restored
  1623. try:
  1624. from backend.app.services.virtual_printer import virtual_printer_manager
  1625. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  1626. vp_access_code = await get_setting(db, "virtual_printer_access_code")
  1627. vp_mode = await get_setting(db, "virtual_printer_mode")
  1628. vp_model = await get_setting(db, "virtual_printer_model")
  1629. enabled = vp_enabled and vp_enabled.lower() == "true"
  1630. access_code = vp_access_code or ""
  1631. mode = vp_mode or "immediate"
  1632. model = vp_model or ""
  1633. if enabled and access_code:
  1634. await virtual_printer_manager.configure(
  1635. enabled=True,
  1636. access_code=access_code,
  1637. mode=mode,
  1638. model=model,
  1639. )
  1640. elif not enabled and virtual_printer_manager.is_enabled:
  1641. await virtual_printer_manager.configure(
  1642. enabled=False,
  1643. access_code=access_code,
  1644. mode=mode,
  1645. model=model,
  1646. )
  1647. except Exception:
  1648. pass # Virtual printer config failed, but don't fail the restore
  1649. # Reconfigure MQTT relay if settings were restored
  1650. try:
  1651. from backend.app.services.mqtt_relay import mqtt_relay
  1652. mqtt_settings = {
  1653. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  1654. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  1655. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  1656. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  1657. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  1658. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  1659. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  1660. }
  1661. await mqtt_relay.configure(mqtt_settings)
  1662. except Exception:
  1663. pass # MQTT relay config failed, but don't fail the restore
  1664. # Build summary message
  1665. restored_parts = []
  1666. for key, count in restored.items():
  1667. if count > 0:
  1668. restored_parts.append(f"{count} {key.replace('_', ' ')}")
  1669. if files_restored > 0:
  1670. restored_parts.append(f"{files_restored} files")
  1671. skipped_parts = []
  1672. total_skipped = sum(skipped.values())
  1673. for key, count in skipped.items():
  1674. if count > 0:
  1675. skipped_parts.append(f"{count} {key.replace('_', ' ')}")
  1676. message_parts = []
  1677. if restored_parts:
  1678. message_parts.append(f"Restored: {', '.join(restored_parts)}")
  1679. if skipped_parts:
  1680. message_parts.append(f"Skipped (already exist): {', '.join(skipped_parts)}")
  1681. response = {
  1682. "success": True,
  1683. "message": ". ".join(message_parts) if message_parts else "Nothing to restore",
  1684. "restored": restored,
  1685. "skipped": skipped,
  1686. "skipped_details": skipped_details,
  1687. "files_restored": files_restored,
  1688. "total_skipped": total_skipped,
  1689. }
  1690. # Include newly generated API keys if any (so user can see them)
  1691. if new_api_keys:
  1692. response["new_api_keys"] = new_api_keys
  1693. return response
  1694. # =============================================================================
  1695. # Virtual Printer Settings
  1696. # =============================================================================
  1697. @router.get("/virtual-printer/models")
  1698. async def get_virtual_printer_models():
  1699. """Get available virtual printer models."""
  1700. from backend.app.services.virtual_printer import (
  1701. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1702. VIRTUAL_PRINTER_MODELS,
  1703. )
  1704. return {
  1705. "models": VIRTUAL_PRINTER_MODELS,
  1706. "default": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1707. }
  1708. @router.get("/virtual-printer")
  1709. async def get_virtual_printer_settings(db: AsyncSession = Depends(get_db)):
  1710. """Get virtual printer settings and status."""
  1711. from backend.app.services.virtual_printer import (
  1712. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1713. virtual_printer_manager,
  1714. )
  1715. enabled = await get_setting(db, "virtual_printer_enabled")
  1716. access_code = await get_setting(db, "virtual_printer_access_code")
  1717. mode = await get_setting(db, "virtual_printer_mode")
  1718. model = await get_setting(db, "virtual_printer_model")
  1719. return {
  1720. "enabled": enabled == "true" if enabled else False,
  1721. "access_code_set": bool(access_code),
  1722. "mode": mode or "immediate",
  1723. "model": model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1724. "status": virtual_printer_manager.get_status(),
  1725. }
  1726. @router.put("/virtual-printer")
  1727. async def update_virtual_printer_settings(
  1728. enabled: bool = None,
  1729. access_code: str = None,
  1730. mode: str = None,
  1731. model: str = None,
  1732. db: AsyncSession = Depends(get_db),
  1733. ):
  1734. """Update virtual printer settings and restart services if needed."""
  1735. from backend.app.services.virtual_printer import (
  1736. DEFAULT_VIRTUAL_PRINTER_MODEL,
  1737. VIRTUAL_PRINTER_MODELS,
  1738. virtual_printer_manager,
  1739. )
  1740. # Get current values
  1741. current_enabled = await get_setting(db, "virtual_printer_enabled") == "true"
  1742. current_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1743. current_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  1744. current_model = await get_setting(db, "virtual_printer_model") or DEFAULT_VIRTUAL_PRINTER_MODEL
  1745. # Apply updates
  1746. new_enabled = enabled if enabled is not None else current_enabled
  1747. new_access_code = access_code if access_code is not None else current_access_code
  1748. new_mode = mode if mode is not None else current_mode
  1749. new_model = model if model is not None else current_model
  1750. # Validate mode
  1751. # "review" is the new name for "queue" (pending review before archiving)
  1752. # "print_queue" archives and adds to print queue (unassigned)
  1753. if new_mode not in ("immediate", "queue", "review", "print_queue"):
  1754. return JSONResponse(
  1755. status_code=400,
  1756. content={"detail": "Mode must be 'immediate', 'review', or 'print_queue'"},
  1757. )
  1758. # Normalize legacy "queue" to "review" for storage
  1759. if new_mode == "queue":
  1760. new_mode = "review"
  1761. # Validate model
  1762. if model is not None and model not in VIRTUAL_PRINTER_MODELS:
  1763. return JSONResponse(
  1764. status_code=400,
  1765. content={"detail": f"Invalid model. Must be one of: {', '.join(VIRTUAL_PRINTER_MODELS.keys())}"},
  1766. )
  1767. # Validate access code when enabling
  1768. if new_enabled and not new_access_code:
  1769. return JSONResponse(
  1770. status_code=400,
  1771. content={"detail": "Access code is required when enabling virtual printer"},
  1772. )
  1773. # Validate access code length (Bambu Studio requires exactly 8 characters)
  1774. if access_code is not None and len(access_code) != 8:
  1775. return JSONResponse(
  1776. status_code=400,
  1777. content={"detail": "Access code must be exactly 8 characters"},
  1778. )
  1779. # Save settings
  1780. await set_setting(db, "virtual_printer_enabled", "true" if new_enabled else "false")
  1781. if access_code is not None:
  1782. await set_setting(db, "virtual_printer_access_code", access_code)
  1783. await set_setting(db, "virtual_printer_mode", new_mode)
  1784. if model is not None:
  1785. await set_setting(db, "virtual_printer_model", model)
  1786. await db.commit()
  1787. # Reconfigure virtual printer
  1788. try:
  1789. await virtual_printer_manager.configure(
  1790. enabled=new_enabled,
  1791. access_code=new_access_code,
  1792. mode=new_mode,
  1793. model=new_model,
  1794. )
  1795. except ValueError as e:
  1796. return JSONResponse(
  1797. status_code=400,
  1798. content={"detail": str(e)},
  1799. )
  1800. except Exception as e:
  1801. return JSONResponse(
  1802. status_code=500,
  1803. content={"detail": f"Failed to configure virtual printer: {e}"},
  1804. )
  1805. return await get_virtual_printer_settings(db)
  1806. # =============================================================================
  1807. # MQTT Relay Settings
  1808. # =============================================================================
  1809. @router.get("/mqtt/status")
  1810. async def get_mqtt_status():
  1811. """Get MQTT relay connection status."""
  1812. from backend.app.services.mqtt_relay import mqtt_relay
  1813. return mqtt_relay.get_status()