archives.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. from pathlib import Path
  2. import zipfile
  3. import io
  4. from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Request
  5. from fastapi.responses import FileResponse, Response
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from sqlalchemy import select, func
  8. from backend.app.core.config import settings
  9. from backend.app.core.database import get_db
  10. from backend.app.models.archive import PrintArchive
  11. from backend.app.schemas.archive import ArchiveResponse, ArchiveUpdate, ArchiveStats
  12. from backend.app.services.archive import ArchiveService
  13. router = APIRouter(prefix="/archives", tags=["archives"])
  14. def compute_time_accuracy(archive: PrintArchive) -> dict:
  15. """Compute actual print time and accuracy for an archive.
  16. Returns dict with actual_time_seconds and time_accuracy.
  17. time_accuracy = (estimated / actual) * 100
  18. - 100% = perfect estimate
  19. - >100% = print was faster than estimated
  20. - <100% = print took longer than estimated
  21. """
  22. result = {"actual_time_seconds": None, "time_accuracy": None}
  23. if archive.started_at and archive.completed_at and archive.status == "completed":
  24. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  25. if actual_seconds > 0:
  26. result["actual_time_seconds"] = actual_seconds
  27. if archive.print_time_seconds and archive.print_time_seconds > 0:
  28. # Calculate accuracy as percentage
  29. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  30. result["time_accuracy"] = round(accuracy, 1)
  31. return result
  32. def archive_to_response(
  33. archive: PrintArchive,
  34. duplicates: list[dict] | None = None,
  35. duplicate_count: int = 0,
  36. ) -> dict:
  37. """Convert archive model to response dict with computed fields."""
  38. data = {
  39. "id": archive.id,
  40. "printer_id": archive.printer_id,
  41. "filename": archive.filename,
  42. "file_path": archive.file_path,
  43. "file_size": archive.file_size,
  44. "content_hash": archive.content_hash,
  45. "thumbnail_path": archive.thumbnail_path,
  46. "timelapse_path": archive.timelapse_path,
  47. "duplicates": duplicates,
  48. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  49. "print_name": archive.print_name,
  50. "print_time_seconds": archive.print_time_seconds,
  51. "filament_used_grams": archive.filament_used_grams,
  52. "filament_type": archive.filament_type,
  53. "filament_color": archive.filament_color,
  54. "layer_height": archive.layer_height,
  55. "nozzle_diameter": archive.nozzle_diameter,
  56. "bed_temperature": archive.bed_temperature,
  57. "nozzle_temperature": archive.nozzle_temperature,
  58. "status": archive.status,
  59. "started_at": archive.started_at,
  60. "completed_at": archive.completed_at,
  61. "extra_data": archive.extra_data,
  62. "makerworld_url": archive.makerworld_url,
  63. "designer": archive.designer,
  64. "is_favorite": archive.is_favorite,
  65. "tags": archive.tags,
  66. "notes": archive.notes,
  67. "cost": archive.cost,
  68. "photos": archive.photos,
  69. "failure_reason": archive.failure_reason,
  70. "created_at": archive.created_at,
  71. }
  72. # Add computed time accuracy fields
  73. accuracy_data = compute_time_accuracy(archive)
  74. data.update(accuracy_data)
  75. return data
  76. @router.get("/", response_model=list[ArchiveResponse])
  77. async def list_archives(
  78. printer_id: int | None = None,
  79. limit: int = 50,
  80. offset: int = 0,
  81. db: AsyncSession = Depends(get_db),
  82. ):
  83. """List archived prints."""
  84. service = ArchiveService(db)
  85. archives = await service.list_archives(
  86. printer_id=printer_id,
  87. limit=limit,
  88. offset=offset,
  89. )
  90. # Get set of hashes that have duplicates (efficient single query)
  91. duplicate_hashes = await service.get_duplicate_hashes()
  92. # Mark archives that have duplicates
  93. result = []
  94. for a in archives:
  95. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  96. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  97. return result
  98. @router.get("/stats", response_model=ArchiveStats)
  99. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  100. """Get statistics across all archives."""
  101. # Total counts
  102. total_result = await db.execute(select(func.count(PrintArchive.id)))
  103. total_prints = total_result.scalar() or 0
  104. successful_result = await db.execute(
  105. select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed")
  106. )
  107. successful_prints = successful_result.scalar() or 0
  108. failed_result = await db.execute(
  109. select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed")
  110. )
  111. failed_prints = failed_result.scalar() or 0
  112. # Totals
  113. time_result = await db.execute(
  114. select(func.sum(PrintArchive.print_time_seconds))
  115. )
  116. total_time = (time_result.scalar() or 0) / 3600 # Convert to hours
  117. filament_result = await db.execute(
  118. select(func.sum(PrintArchive.filament_used_grams))
  119. )
  120. total_filament = filament_result.scalar() or 0
  121. cost_result = await db.execute(
  122. select(func.sum(PrintArchive.cost))
  123. )
  124. total_cost = cost_result.scalar() or 0
  125. # By filament type (split comma-separated values for multi-material prints)
  126. filament_type_result = await db.execute(
  127. select(PrintArchive.filament_type)
  128. .where(PrintArchive.filament_type.isnot(None))
  129. )
  130. prints_by_filament: dict[str, int] = {}
  131. for (filament_types,) in filament_type_result.all():
  132. # Split by comma and count each type
  133. for ftype in filament_types.split(","):
  134. ftype = ftype.strip()
  135. if ftype:
  136. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  137. # By printer
  138. printer_result = await db.execute(
  139. select(PrintArchive.printer_id, func.count(PrintArchive.id))
  140. .group_by(PrintArchive.printer_id)
  141. )
  142. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  143. # Time accuracy statistics
  144. # Get all completed archives with both estimated and actual times
  145. accuracy_result = await db.execute(
  146. select(PrintArchive)
  147. .where(PrintArchive.status == "completed")
  148. .where(PrintArchive.print_time_seconds.isnot(None))
  149. .where(PrintArchive.started_at.isnot(None))
  150. .where(PrintArchive.completed_at.isnot(None))
  151. )
  152. archives_with_times = list(accuracy_result.scalars().all())
  153. average_accuracy = None
  154. accuracy_by_printer: dict[str, float] = {}
  155. if archives_with_times:
  156. accuracies = []
  157. printer_accuracies: dict[str, list[float]] = {}
  158. for archive in archives_with_times:
  159. acc_data = compute_time_accuracy(archive)
  160. if acc_data["time_accuracy"] is not None:
  161. accuracies.append(acc_data["time_accuracy"])
  162. # Group by printer
  163. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  164. if printer_key not in printer_accuracies:
  165. printer_accuracies[printer_key] = []
  166. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  167. if accuracies:
  168. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  169. # Calculate per-printer averages
  170. for printer_key, accs in printer_accuracies.items():
  171. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  172. return ArchiveStats(
  173. total_prints=total_prints,
  174. successful_prints=successful_prints,
  175. failed_prints=failed_prints,
  176. total_print_time_hours=round(total_time, 1),
  177. total_filament_grams=round(total_filament, 1),
  178. total_cost=round(total_cost, 2),
  179. prints_by_filament_type=prints_by_filament,
  180. prints_by_printer=prints_by_printer,
  181. average_time_accuracy=average_accuracy,
  182. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  183. )
  184. @router.get("/{archive_id}", response_model=ArchiveResponse)
  185. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  186. """Get a specific archive."""
  187. service = ArchiveService(db)
  188. archive = await service.get_archive(archive_id)
  189. if not archive:
  190. raise HTTPException(404, "Archive not found")
  191. # Find duplicates
  192. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  193. duplicates = await service.find_duplicates(
  194. archive_id=archive.id,
  195. content_hash=archive.content_hash,
  196. print_name=archive.print_name,
  197. makerworld_model_id=makerworld_id,
  198. )
  199. return archive_to_response(archive, duplicates)
  200. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  201. async def update_archive(
  202. archive_id: int,
  203. update_data: ArchiveUpdate,
  204. db: AsyncSession = Depends(get_db),
  205. ):
  206. """Update archive metadata (tags, notes, cost, is_favorite)."""
  207. result = await db.execute(
  208. select(PrintArchive).where(PrintArchive.id == archive_id)
  209. )
  210. archive = result.scalar_one_or_none()
  211. if not archive:
  212. raise HTTPException(404, "Archive not found")
  213. for field, value in update_data.model_dump(exclude_unset=True).items():
  214. setattr(archive, field, value)
  215. await db.commit()
  216. await db.refresh(archive)
  217. return archive
  218. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  219. async def toggle_favorite(
  220. archive_id: int,
  221. db: AsyncSession = Depends(get_db),
  222. ):
  223. """Toggle favorite status for an archive."""
  224. result = await db.execute(
  225. select(PrintArchive).where(PrintArchive.id == archive_id)
  226. )
  227. archive = result.scalar_one_or_none()
  228. if not archive:
  229. raise HTTPException(404, "Archive not found")
  230. archive.is_favorite = not archive.is_favorite
  231. await db.commit()
  232. await db.refresh(archive)
  233. return archive
  234. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  235. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  236. """Rescan the 3MF file and update metadata."""
  237. from backend.app.services.archive import ThreeMFParser
  238. result = await db.execute(
  239. select(PrintArchive).where(PrintArchive.id == archive_id)
  240. )
  241. archive = result.scalar_one_or_none()
  242. if not archive:
  243. raise HTTPException(404, "Archive not found")
  244. file_path = settings.base_dir / archive.file_path
  245. if not file_path.exists():
  246. raise HTTPException(404, "Archive file not found")
  247. # Parse the 3MF file
  248. parser = ThreeMFParser(file_path)
  249. metadata = parser.parse()
  250. # Update fields from metadata
  251. if metadata.get("filament_type"):
  252. archive.filament_type = metadata["filament_type"]
  253. if metadata.get("filament_color"):
  254. archive.filament_color = metadata["filament_color"]
  255. if metadata.get("print_time_seconds"):
  256. archive.print_time_seconds = metadata["print_time_seconds"]
  257. if metadata.get("filament_used_grams"):
  258. archive.filament_used_grams = metadata["filament_used_grams"]
  259. if metadata.get("layer_height"):
  260. archive.layer_height = metadata["layer_height"]
  261. if metadata.get("nozzle_diameter"):
  262. archive.nozzle_diameter = metadata["nozzle_diameter"]
  263. if metadata.get("bed_temperature"):
  264. archive.bed_temperature = metadata["bed_temperature"]
  265. if metadata.get("nozzle_temperature"):
  266. archive.nozzle_temperature = metadata["nozzle_temperature"]
  267. if metadata.get("makerworld_url"):
  268. archive.makerworld_url = metadata["makerworld_url"]
  269. if metadata.get("designer"):
  270. archive.designer = metadata["designer"]
  271. await db.commit()
  272. await db.refresh(archive)
  273. return archive
  274. @router.post("/rescan-all")
  275. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  276. """Rescan all archives and update their metadata."""
  277. from backend.app.services.archive import ThreeMFParser
  278. result = await db.execute(select(PrintArchive))
  279. archives = list(result.scalars().all())
  280. updated = 0
  281. errors = []
  282. for archive in archives:
  283. try:
  284. file_path = settings.base_dir / archive.file_path
  285. if not file_path.exists():
  286. errors.append({"id": archive.id, "error": "File not found"})
  287. continue
  288. parser = ThreeMFParser(file_path)
  289. metadata = parser.parse()
  290. if metadata.get("filament_type"):
  291. archive.filament_type = metadata["filament_type"]
  292. if metadata.get("filament_color"):
  293. archive.filament_color = metadata["filament_color"]
  294. if metadata.get("print_time_seconds"):
  295. archive.print_time_seconds = metadata["print_time_seconds"]
  296. if metadata.get("filament_used_grams"):
  297. archive.filament_used_grams = metadata["filament_used_grams"]
  298. if metadata.get("layer_height"):
  299. archive.layer_height = metadata["layer_height"]
  300. if metadata.get("nozzle_diameter"):
  301. archive.nozzle_diameter = metadata["nozzle_diameter"]
  302. if metadata.get("makerworld_url"):
  303. archive.makerworld_url = metadata["makerworld_url"]
  304. if metadata.get("designer"):
  305. archive.designer = metadata["designer"]
  306. updated += 1
  307. except Exception as e:
  308. errors.append({"id": archive.id, "error": str(e)})
  309. await db.commit()
  310. return {"updated": updated, "errors": errors}
  311. @router.get("/{archive_id}/duplicates")
  312. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  313. """Get duplicates for a specific archive."""
  314. service = ArchiveService(db)
  315. archive = await service.get_archive(archive_id)
  316. if not archive:
  317. raise HTTPException(404, "Archive not found")
  318. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  319. duplicates = await service.find_duplicates(
  320. archive_id=archive.id,
  321. content_hash=archive.content_hash,
  322. print_name=archive.print_name,
  323. makerworld_model_id=makerworld_id,
  324. )
  325. return {"duplicates": duplicates, "count": len(duplicates)}
  326. @router.post("/backfill-hashes")
  327. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  328. """Compute and store content hashes for all archives missing them."""
  329. result = await db.execute(
  330. select(PrintArchive).where(PrintArchive.content_hash.is_(None))
  331. )
  332. archives = list(result.scalars().all())
  333. updated = 0
  334. errors = []
  335. for archive in archives:
  336. try:
  337. file_path = settings.base_dir / archive.file_path
  338. if not file_path.exists():
  339. errors.append({"id": archive.id, "error": "File not found"})
  340. continue
  341. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  342. updated += 1
  343. except Exception as e:
  344. errors.append({"id": archive.id, "error": str(e)})
  345. await db.commit()
  346. return {"updated": updated, "errors": errors}
  347. @router.delete("/{archive_id}")
  348. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  349. """Delete an archive."""
  350. service = ArchiveService(db)
  351. if not await service.delete_archive(archive_id):
  352. raise HTTPException(404, "Archive not found")
  353. return {"status": "deleted"}
  354. @router.get("/{archive_id}/download")
  355. async def download_archive(
  356. archive_id: int,
  357. inline: bool = False,
  358. db: AsyncSession = Depends(get_db),
  359. ):
  360. """Download the 3MF file."""
  361. service = ArchiveService(db)
  362. archive = await service.get_archive(archive_id)
  363. if not archive:
  364. raise HTTPException(404, "Archive not found")
  365. file_path = settings.base_dir / archive.file_path
  366. if not file_path.exists():
  367. raise HTTPException(404, "File not found")
  368. # Use inline disposition to let browser/OS handle file association
  369. content_disposition = "inline" if inline else "attachment"
  370. return FileResponse(
  371. path=file_path,
  372. filename=archive.filename,
  373. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  374. content_disposition_type=content_disposition,
  375. )
  376. @router.get("/{archive_id}/file/{filename}")
  377. async def download_archive_with_filename(
  378. archive_id: int,
  379. filename: str,
  380. db: AsyncSession = Depends(get_db),
  381. ):
  382. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  383. service = ArchiveService(db)
  384. archive = await service.get_archive(archive_id)
  385. if not archive:
  386. raise HTTPException(404, "Archive not found")
  387. file_path = settings.base_dir / archive.file_path
  388. if not file_path.exists():
  389. raise HTTPException(404, "File not found")
  390. return FileResponse(
  391. path=file_path,
  392. filename=archive.filename,
  393. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  394. )
  395. @router.get("/{archive_id}/thumbnail")
  396. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  397. """Get the thumbnail image."""
  398. service = ArchiveService(db)
  399. archive = await service.get_archive(archive_id)
  400. if not archive or not archive.thumbnail_path:
  401. raise HTTPException(404, "Thumbnail not found")
  402. thumb_path = settings.base_dir / archive.thumbnail_path
  403. if not thumb_path.exists():
  404. raise HTTPException(404, "Thumbnail file not found")
  405. return FileResponse(path=thumb_path, media_type="image/png")
  406. @router.get("/{archive_id}/timelapse")
  407. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  408. """Get the timelapse video."""
  409. service = ArchiveService(db)
  410. archive = await service.get_archive(archive_id)
  411. if not archive or not archive.timelapse_path:
  412. raise HTTPException(404, "Timelapse not found")
  413. timelapse_path = settings.base_dir / archive.timelapse_path
  414. if not timelapse_path.exists():
  415. raise HTTPException(404, "Timelapse file not found")
  416. return FileResponse(
  417. path=timelapse_path,
  418. media_type="video/mp4",
  419. filename=f"{archive.print_name or 'timelapse'}.mp4",
  420. )
  421. @router.post("/{archive_id}/timelapse/scan")
  422. async def scan_timelapse(
  423. archive_id: int,
  424. db: AsyncSession = Depends(get_db),
  425. ):
  426. """Scan printer for timelapse matching this archive and attach it."""
  427. from backend.app.models.printer import Printer
  428. from backend.app.services.bambu_ftp import list_files_async, download_file_bytes_async
  429. service = ArchiveService(db)
  430. archive = await service.get_archive(archive_id)
  431. if not archive:
  432. raise HTTPException(404, "Archive not found")
  433. if archive.timelapse_path:
  434. return {"status": "exists", "message": "Timelapse already attached"}
  435. if not archive.printer_id:
  436. raise HTTPException(400, "Archive has no associated printer")
  437. # Get printer
  438. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  439. printer = result.scalar_one_or_none()
  440. if not printer:
  441. raise HTTPException(404, "Printer not found")
  442. # Get base name from archive filename (without .3mf extension)
  443. base_name = Path(archive.filename).stem
  444. # Scan timelapse directory on printer
  445. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  446. files = []
  447. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  448. try:
  449. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  450. if files:
  451. break
  452. except Exception:
  453. continue
  454. if not files:
  455. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  456. # Look for matching timelapse
  457. matching_file = None
  458. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  459. # Strategy 1: Match by print name in filename
  460. for f in mp4_files:
  461. fname = f.get("name", "")
  462. if base_name.lower() in fname.lower():
  463. matching_file = f
  464. break
  465. # Strategy 2: Match by timestamp proximity
  466. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  467. import re
  468. from datetime import datetime, timedelta
  469. archive_time = archive.started_at or archive.completed_at or archive.created_at
  470. best_match = None
  471. best_diff = timedelta(hours=24) # Max 24 hour difference
  472. for f in mp4_files:
  473. fname = f.get("name", "")
  474. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  475. match = re.search(r'(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})', fname)
  476. if match:
  477. try:
  478. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  479. # Timelapse is usually created at print end, so compare to completed_at or created_at
  480. compare_time = archive.completed_at or archive.created_at
  481. if compare_time:
  482. # Bambu printers use China Standard Time (UTC+8) for filenames
  483. # Try matching with CST offset adjustment
  484. diff_direct = abs(file_time - compare_time)
  485. # Also try with 8-hour offset (CST to UTC-ish local times)
  486. diff_cst_adjusted = abs(file_time - timedelta(hours=8) - compare_time)
  487. diff = min(diff_direct, diff_cst_adjusted)
  488. if diff < best_diff:
  489. best_diff = diff
  490. best_match = f
  491. except ValueError:
  492. continue
  493. if best_match and best_diff < timedelta(hours=2): # Within 2 hours
  494. matching_file = best_match
  495. if not matching_file:
  496. return {"status": "not_found", "message": "No matching timelapse found on printer"}
  497. # Download the timelapse - use the full path from the file listing
  498. remote_path = matching_file.get('path') or f"/timelapse/{matching_file['name']}"
  499. timelapse_data = await download_file_bytes_async(
  500. printer.ip_address, printer.access_code, remote_path
  501. )
  502. if not timelapse_data:
  503. raise HTTPException(500, "Failed to download timelapse")
  504. # Attach timelapse to archive
  505. success = await service.attach_timelapse(
  506. archive_id, timelapse_data, matching_file["name"]
  507. )
  508. if not success:
  509. raise HTTPException(500, "Failed to attach timelapse")
  510. return {
  511. "status": "attached",
  512. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  513. "filename": matching_file["name"],
  514. }
  515. @router.post("/{archive_id}/timelapse/upload")
  516. async def upload_timelapse(
  517. archive_id: int,
  518. file: UploadFile = File(...),
  519. db: AsyncSession = Depends(get_db),
  520. ):
  521. """Manually upload a timelapse video to an archive."""
  522. service = ArchiveService(db)
  523. archive = await service.get_archive(archive_id)
  524. if not archive:
  525. raise HTTPException(404, "Archive not found")
  526. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  527. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  528. content = await file.read()
  529. success = await service.attach_timelapse(archive_id, content, file.filename)
  530. if not success:
  531. raise HTTPException(500, "Failed to attach timelapse")
  532. return {"status": "attached", "filename": file.filename}
  533. # ============================================
  534. # Photo Endpoints
  535. # ============================================
  536. @router.post("/{archive_id}/photos")
  537. async def upload_photo(
  538. archive_id: int,
  539. file: UploadFile = File(...),
  540. db: AsyncSession = Depends(get_db),
  541. ):
  542. """Upload a photo of the printed result."""
  543. result = await db.execute(
  544. select(PrintArchive).where(PrintArchive.id == archive_id)
  545. )
  546. archive = result.scalar_one_or_none()
  547. if not archive:
  548. raise HTTPException(404, "Archive not found")
  549. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  550. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  551. # Get archive directory
  552. file_path = settings.base_dir / archive.file_path
  553. archive_dir = file_path.parent
  554. photos_dir = archive_dir / "photos"
  555. photos_dir.mkdir(exist_ok=True)
  556. # Generate unique filename
  557. import uuid
  558. ext = Path(file.filename).suffix.lower()
  559. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  560. photo_path = photos_dir / photo_filename
  561. # Save file
  562. content = await file.read()
  563. photo_path.write_bytes(content)
  564. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  565. photos = list(archive.photos or [])
  566. photos.append(photo_filename)
  567. archive.photos = photos
  568. await db.commit()
  569. await db.refresh(archive)
  570. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  571. @router.get("/{archive_id}/photos/{filename}")
  572. async def get_photo(
  573. archive_id: int,
  574. filename: str,
  575. db: AsyncSession = Depends(get_db),
  576. ):
  577. """Get a specific photo."""
  578. result = await db.execute(
  579. select(PrintArchive).where(PrintArchive.id == archive_id)
  580. )
  581. archive = result.scalar_one_or_none()
  582. if not archive:
  583. raise HTTPException(404, "Archive not found")
  584. file_path = settings.base_dir / archive.file_path
  585. photo_path = file_path.parent / "photos" / filename
  586. if not photo_path.exists():
  587. raise HTTPException(404, "Photo not found")
  588. # Determine media type
  589. ext = Path(filename).suffix.lower()
  590. media_types = {
  591. ".jpg": "image/jpeg",
  592. ".jpeg": "image/jpeg",
  593. ".png": "image/png",
  594. ".webp": "image/webp",
  595. }
  596. media_type = media_types.get(ext, "image/jpeg")
  597. return FileResponse(path=photo_path, media_type=media_type)
  598. @router.delete("/{archive_id}/photos/{filename}")
  599. async def delete_photo(
  600. archive_id: int,
  601. filename: str,
  602. db: AsyncSession = Depends(get_db),
  603. ):
  604. """Delete a photo."""
  605. result = await db.execute(
  606. select(PrintArchive).where(PrintArchive.id == archive_id)
  607. )
  608. archive = result.scalar_one_or_none()
  609. if not archive:
  610. raise HTTPException(404, "Archive not found")
  611. if not archive.photos or filename not in archive.photos:
  612. raise HTTPException(404, "Photo not found")
  613. # Delete file
  614. file_path = settings.base_dir / archive.file_path
  615. photo_path = file_path.parent / "photos" / filename
  616. if photo_path.exists():
  617. photo_path.unlink()
  618. # Update archive photos list
  619. photos = [p for p in archive.photos if p != filename]
  620. archive.photos = photos if photos else None
  621. await db.commit()
  622. return {"status": "deleted", "photos": archive.photos}
  623. # ============================================
  624. # QR Code Endpoint
  625. # ============================================
  626. @router.get("/{archive_id}/qrcode")
  627. async def get_qrcode(
  628. archive_id: int,
  629. request: Request,
  630. size: int = 200,
  631. db: AsyncSession = Depends(get_db),
  632. ):
  633. """Generate a QR code that links to this archive."""
  634. import qrcode
  635. from qrcode.image.styledpil import StyledPilImage
  636. result = await db.execute(
  637. select(PrintArchive).where(PrintArchive.id == archive_id)
  638. )
  639. archive = result.scalar_one_or_none()
  640. if not archive:
  641. raise HTTPException(404, "Archive not found")
  642. # Build URL to archive detail page
  643. base_url = str(request.base_url).rstrip('/')
  644. archive_url = f"{base_url}/archives?id={archive_id}"
  645. # Generate QR code
  646. qr = qrcode.QRCode(
  647. version=1,
  648. error_correction=qrcode.constants.ERROR_CORRECT_M,
  649. box_size=10,
  650. border=2,
  651. )
  652. qr.add_data(archive_url)
  653. qr.make(fit=True)
  654. img = qr.make_image(fill_color="black", back_color="white")
  655. # Resize if needed
  656. if size != 200:
  657. img = img.resize((size, size))
  658. # Convert to bytes
  659. buffer = io.BytesIO()
  660. img.save(buffer, format="PNG")
  661. buffer.seek(0)
  662. return Response(
  663. content=buffer.getvalue(),
  664. media_type="image/png",
  665. headers={
  666. "Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'
  667. }
  668. )
  669. @router.get("/{archive_id}/capabilities")
  670. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  671. """Check what viewing capabilities are available for this 3MF file."""
  672. import json
  673. import re
  674. service = ArchiveService(db)
  675. archive = await service.get_archive(archive_id)
  676. if not archive:
  677. raise HTTPException(404, "Archive not found")
  678. file_path = settings.base_dir / archive.file_path
  679. if not file_path.exists():
  680. raise HTTPException(404, "File not found")
  681. has_model = False
  682. has_gcode = False
  683. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  684. try:
  685. with zipfile.ZipFile(file_path, 'r') as zf:
  686. names = zf.namelist()
  687. # Check for G-code
  688. has_gcode = any(n.startswith('Metadata/') and n.endswith('.gcode') for n in names)
  689. # Check for 3D model - need to look for actual mesh data
  690. for name in names:
  691. if name.endswith('.model'):
  692. try:
  693. content = zf.read(name).decode('utf-8')
  694. # Check if this model file contains actual mesh vertices
  695. if '<vertex' in content or '<mesh' in content:
  696. has_model = True
  697. break
  698. except Exception:
  699. pass
  700. # Extract build volume from project settings
  701. if 'Metadata/project_settings.config' in names:
  702. try:
  703. config_content = zf.read('Metadata/project_settings.config').decode('utf-8')
  704. config_data = json.loads(config_content)
  705. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  706. printable_area = config_data.get('printable_area', [])
  707. if printable_area and len(printable_area) >= 3:
  708. # Get max X and Y from the corner coordinates
  709. max_x = 0
  710. max_y = 0
  711. for coord in printable_area:
  712. if 'x' in coord:
  713. parts = coord.split('x')
  714. if len(parts) == 2:
  715. try:
  716. x, y = int(parts[0]), int(parts[1])
  717. max_x = max(max_x, x)
  718. max_y = max(max_y, y)
  719. except ValueError:
  720. pass
  721. if max_x > 0 and max_y > 0:
  722. build_volume["x"] = max_x
  723. build_volume["y"] = max_y
  724. # Parse printable_height
  725. printable_height = config_data.get('printable_height')
  726. if printable_height:
  727. try:
  728. build_volume["z"] = int(printable_height)
  729. except (ValueError, TypeError):
  730. pass
  731. except Exception:
  732. pass
  733. except zipfile.BadZipFile:
  734. raise HTTPException(400, "Invalid 3MF file")
  735. return {
  736. "has_model": has_model,
  737. "has_gcode": has_gcode,
  738. "build_volume": build_volume,
  739. }
  740. @router.get("/{archive_id}/gcode")
  741. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  742. """Extract and return G-code from the 3MF file."""
  743. service = ArchiveService(db)
  744. archive = await service.get_archive(archive_id)
  745. if not archive:
  746. raise HTTPException(404, "Archive not found")
  747. file_path = settings.base_dir / archive.file_path
  748. if not file_path.exists():
  749. raise HTTPException(404, "File not found")
  750. try:
  751. with zipfile.ZipFile(file_path, 'r') as zf:
  752. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  753. gcode_files = [n for n in zf.namelist() if n.startswith('Metadata/') and n.endswith('.gcode')]
  754. if not gcode_files:
  755. raise HTTPException(
  756. 404,
  757. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio."
  758. )
  759. # Get the first plate's G-code (usually plate_1.gcode)
  760. gcode_content = zf.read(gcode_files[0]).decode('utf-8')
  761. return Response(content=gcode_content, media_type="text/plain")
  762. except zipfile.BadZipFile:
  763. raise HTTPException(400, "Invalid 3MF file")
  764. except HTTPException:
  765. raise
  766. except Exception as e:
  767. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  768. @router.post("/upload")
  769. async def upload_archive(
  770. file: UploadFile = File(...),
  771. printer_id: int | None = None,
  772. db: AsyncSession = Depends(get_db),
  773. ):
  774. """Manually upload a 3MF file to archive."""
  775. if not file.filename or not file.filename.endswith(".3mf"):
  776. raise HTTPException(400, "File must be a .3mf file")
  777. # Save uploaded file temporarily
  778. temp_path = settings.archive_dir / "temp" / file.filename
  779. temp_path.parent.mkdir(parents=True, exist_ok=True)
  780. try:
  781. content = await file.read()
  782. temp_path.write_bytes(content)
  783. service = ArchiveService(db)
  784. archive = await service.archive_print(
  785. printer_id=printer_id,
  786. source_file=temp_path,
  787. )
  788. if not archive:
  789. raise HTTPException(400, "Failed to archive file")
  790. return ArchiveResponse.model_validate(archive)
  791. finally:
  792. if temp_path.exists():
  793. temp_path.unlink()
  794. @router.post("/upload-bulk")
  795. async def upload_archives_bulk(
  796. files: list[UploadFile] = File(...),
  797. printer_id: int | None = None,
  798. db: AsyncSession = Depends(get_db),
  799. ):
  800. """Bulk upload multiple 3MF files to archive."""
  801. results = []
  802. errors = []
  803. for file in files:
  804. if not file.filename or not file.filename.endswith(".3mf"):
  805. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  806. continue
  807. temp_path = settings.archive_dir / "temp" / file.filename
  808. temp_path.parent.mkdir(parents=True, exist_ok=True)
  809. try:
  810. content = await file.read()
  811. temp_path.write_bytes(content)
  812. service = ArchiveService(db)
  813. archive = await service.archive_print(
  814. printer_id=printer_id,
  815. source_file=temp_path,
  816. )
  817. if archive:
  818. results.append({
  819. "filename": file.filename,
  820. "id": archive.id,
  821. "status": "success",
  822. })
  823. else:
  824. errors.append({"filename": file.filename, "error": "Failed to process"})
  825. except Exception as e:
  826. errors.append({"filename": file.filename, "error": str(e)})
  827. finally:
  828. if temp_path.exists():
  829. temp_path.unlink()
  830. return {
  831. "uploaded": len(results),
  832. "failed": len(errors),
  833. "results": results,
  834. "errors": errors,
  835. }
  836. @router.post("/{archive_id}/reprint")
  837. async def reprint_archive(
  838. archive_id: int,
  839. printer_id: int,
  840. db: AsyncSession = Depends(get_db),
  841. ):
  842. """Send an archived 3MF file to a printer and start printing."""
  843. from backend.app.models.printer import Printer
  844. from backend.app.services.bambu_ftp import upload_file_async
  845. from backend.app.services.printer_manager import printer_manager
  846. # Get archive
  847. service = ArchiveService(db)
  848. archive = await service.get_archive(archive_id)
  849. if not archive:
  850. raise HTTPException(404, "Archive not found")
  851. # Get printer
  852. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  853. printer = result.scalar_one_or_none()
  854. if not printer:
  855. raise HTTPException(404, "Printer not found")
  856. # Check printer is connected
  857. if not printer_manager.is_connected(printer_id):
  858. raise HTTPException(400, "Printer is not connected")
  859. # Get the 3MF file path
  860. file_path = settings.base_dir / archive.file_path
  861. if not file_path.exists():
  862. raise HTTPException(404, "Archive file not found")
  863. # Upload file to printer via FTP
  864. remote_filename = archive.filename
  865. remote_path = f"/cache/{remote_filename}"
  866. uploaded = await upload_file_async(
  867. printer.ip_address,
  868. printer.access_code,
  869. file_path,
  870. remote_path,
  871. )
  872. if not uploaded:
  873. raise HTTPException(500, "Failed to upload file to printer")
  874. # Start the print
  875. started = printer_manager.start_print(printer_id, remote_filename)
  876. if not started:
  877. raise HTTPException(500, "Failed to start print")
  878. return {
  879. "status": "printing",
  880. "printer_id": printer_id,
  881. "archive_id": archive_id,
  882. "filename": archive.filename,
  883. }
  884. # =============================================================================
  885. # Project Page API
  886. # =============================================================================
  887. @router.get("/{archive_id}/project-page")
  888. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  889. """Get the project page data from the 3MF file."""
  890. from backend.app.services.archive import ProjectPageParser
  891. from backend.app.schemas.archive import ProjectPageResponse
  892. service = ArchiveService(db)
  893. archive = await service.get_archive(archive_id)
  894. if not archive:
  895. raise HTTPException(404, "Archive not found")
  896. file_path = settings.base_dir / archive.file_path
  897. if not file_path.exists():
  898. raise HTTPException(404, "Archive file not found")
  899. parser = ProjectPageParser(file_path)
  900. data = parser.parse(archive_id)
  901. return ProjectPageResponse(**data)
  902. @router.patch("/{archive_id}/project-page")
  903. async def update_project_page(
  904. archive_id: int,
  905. update_data: dict,
  906. db: AsyncSession = Depends(get_db),
  907. ):
  908. """Update project page metadata in the 3MF file."""
  909. from backend.app.services.archive import ProjectPageParser
  910. service = ArchiveService(db)
  911. archive = await service.get_archive(archive_id)
  912. if not archive:
  913. raise HTTPException(404, "Archive not found")
  914. file_path = settings.base_dir / archive.file_path
  915. if not file_path.exists():
  916. raise HTTPException(404, "Archive file not found")
  917. parser = ProjectPageParser(file_path)
  918. success = parser.update_metadata(update_data)
  919. if not success:
  920. raise HTTPException(500, "Failed to update project page")
  921. # Return updated data
  922. data = parser.parse(archive_id)
  923. return data
  924. @router.get("/{archive_id}/project-image/{image_path:path}")
  925. async def get_project_image(
  926. archive_id: int,
  927. image_path: str,
  928. db: AsyncSession = Depends(get_db),
  929. ):
  930. """Get an image from the 3MF project page."""
  931. from backend.app.services.archive import ProjectPageParser
  932. service = ArchiveService(db)
  933. archive = await service.get_archive(archive_id)
  934. if not archive:
  935. raise HTTPException(404, "Archive not found")
  936. file_path = settings.base_dir / archive.file_path
  937. if not file_path.exists():
  938. raise HTTPException(404, "Archive file not found")
  939. parser = ProjectPageParser(file_path)
  940. result = parser.get_image(image_path)
  941. if not result:
  942. raise HTTPException(404, "Image not found in 3MF file")
  943. image_data, content_type = result
  944. return Response(
  945. content=image_data,
  946. media_type=content_type,
  947. headers={"Cache-Control": "max-age=3600"},
  948. )