settings.py 80 KB

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