archives.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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:
  446. files = await list_files_async(printer.ip_address, printer.access_code, "/timelapse/video")
  447. except Exception:
  448. raise HTTPException(500, "Failed to connect to printer")
  449. # Look for matching timelapse
  450. matching_file = None
  451. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  452. # Strategy 1: Match by print name in filename
  453. for f in mp4_files:
  454. fname = f.get("name", "")
  455. if base_name.lower() in fname.lower():
  456. matching_file = f
  457. break
  458. # Strategy 2: Match by timestamp proximity
  459. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  460. import re
  461. from datetime import datetime, timedelta
  462. archive_time = archive.started_at or archive.completed_at or archive.created_at
  463. best_match = None
  464. best_diff = timedelta(hours=24) # Max 24 hour difference
  465. for f in mp4_files:
  466. fname = f.get("name", "")
  467. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  468. match = re.search(r'(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})', fname)
  469. if match:
  470. try:
  471. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  472. # Timelapse is usually created at print end, so compare to completed_at or created_at
  473. compare_time = archive.completed_at or archive.created_at
  474. if compare_time:
  475. diff = abs(file_time - compare_time)
  476. if diff < best_diff:
  477. best_diff = diff
  478. best_match = f
  479. except ValueError:
  480. continue
  481. if best_match and best_diff < timedelta(hours=2): # Within 2 hours
  482. matching_file = best_match
  483. if not matching_file:
  484. return {"status": "not_found", "message": "No matching timelapse found on printer"}
  485. # Download the timelapse
  486. remote_path = f"/timelapse/video/{matching_file['name']}"
  487. timelapse_data = await download_file_bytes_async(
  488. printer.ip_address, printer.access_code, remote_path
  489. )
  490. if not timelapse_data:
  491. raise HTTPException(500, "Failed to download timelapse")
  492. # Attach timelapse to archive
  493. success = await service.attach_timelapse(
  494. archive_id, timelapse_data, matching_file["name"]
  495. )
  496. if not success:
  497. raise HTTPException(500, "Failed to attach timelapse")
  498. return {
  499. "status": "attached",
  500. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  501. "filename": matching_file["name"],
  502. }
  503. @router.post("/{archive_id}/timelapse/upload")
  504. async def upload_timelapse(
  505. archive_id: int,
  506. file: UploadFile = File(...),
  507. db: AsyncSession = Depends(get_db),
  508. ):
  509. """Manually upload a timelapse video to an archive."""
  510. service = ArchiveService(db)
  511. archive = await service.get_archive(archive_id)
  512. if not archive:
  513. raise HTTPException(404, "Archive not found")
  514. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  515. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  516. content = await file.read()
  517. success = await service.attach_timelapse(archive_id, content, file.filename)
  518. if not success:
  519. raise HTTPException(500, "Failed to attach timelapse")
  520. return {"status": "attached", "filename": file.filename}
  521. # ============================================
  522. # Photo Endpoints
  523. # ============================================
  524. @router.post("/{archive_id}/photos")
  525. async def upload_photo(
  526. archive_id: int,
  527. file: UploadFile = File(...),
  528. db: AsyncSession = Depends(get_db),
  529. ):
  530. """Upload a photo of the printed result."""
  531. result = await db.execute(
  532. select(PrintArchive).where(PrintArchive.id == archive_id)
  533. )
  534. archive = result.scalar_one_or_none()
  535. if not archive:
  536. raise HTTPException(404, "Archive not found")
  537. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  538. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  539. # Get archive directory
  540. file_path = settings.base_dir / archive.file_path
  541. archive_dir = file_path.parent
  542. photos_dir = archive_dir / "photos"
  543. photos_dir.mkdir(exist_ok=True)
  544. # Generate unique filename
  545. import uuid
  546. ext = Path(file.filename).suffix.lower()
  547. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  548. photo_path = photos_dir / photo_filename
  549. # Save file
  550. content = await file.read()
  551. photo_path.write_bytes(content)
  552. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  553. photos = list(archive.photos or [])
  554. photos.append(photo_filename)
  555. archive.photos = photos
  556. await db.commit()
  557. await db.refresh(archive)
  558. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  559. @router.get("/{archive_id}/photos/{filename}")
  560. async def get_photo(
  561. archive_id: int,
  562. filename: str,
  563. db: AsyncSession = Depends(get_db),
  564. ):
  565. """Get a specific photo."""
  566. result = await db.execute(
  567. select(PrintArchive).where(PrintArchive.id == archive_id)
  568. )
  569. archive = result.scalar_one_or_none()
  570. if not archive:
  571. raise HTTPException(404, "Archive not found")
  572. file_path = settings.base_dir / archive.file_path
  573. photo_path = file_path.parent / "photos" / filename
  574. if not photo_path.exists():
  575. raise HTTPException(404, "Photo not found")
  576. # Determine media type
  577. ext = Path(filename).suffix.lower()
  578. media_types = {
  579. ".jpg": "image/jpeg",
  580. ".jpeg": "image/jpeg",
  581. ".png": "image/png",
  582. ".webp": "image/webp",
  583. }
  584. media_type = media_types.get(ext, "image/jpeg")
  585. return FileResponse(path=photo_path, media_type=media_type)
  586. @router.delete("/{archive_id}/photos/{filename}")
  587. async def delete_photo(
  588. archive_id: int,
  589. filename: str,
  590. db: AsyncSession = Depends(get_db),
  591. ):
  592. """Delete a photo."""
  593. result = await db.execute(
  594. select(PrintArchive).where(PrintArchive.id == archive_id)
  595. )
  596. archive = result.scalar_one_or_none()
  597. if not archive:
  598. raise HTTPException(404, "Archive not found")
  599. if not archive.photos or filename not in archive.photos:
  600. raise HTTPException(404, "Photo not found")
  601. # Delete file
  602. file_path = settings.base_dir / archive.file_path
  603. photo_path = file_path.parent / "photos" / filename
  604. if photo_path.exists():
  605. photo_path.unlink()
  606. # Update archive photos list
  607. photos = [p for p in archive.photos if p != filename]
  608. archive.photos = photos if photos else None
  609. await db.commit()
  610. return {"status": "deleted", "photos": archive.photos}
  611. # ============================================
  612. # QR Code Endpoint
  613. # ============================================
  614. @router.get("/{archive_id}/qrcode")
  615. async def get_qrcode(
  616. archive_id: int,
  617. request: Request,
  618. size: int = 200,
  619. db: AsyncSession = Depends(get_db),
  620. ):
  621. """Generate a QR code that links to this archive."""
  622. import qrcode
  623. from qrcode.image.styledpil import StyledPilImage
  624. result = await db.execute(
  625. select(PrintArchive).where(PrintArchive.id == archive_id)
  626. )
  627. archive = result.scalar_one_or_none()
  628. if not archive:
  629. raise HTTPException(404, "Archive not found")
  630. # Build URL to archive detail page
  631. base_url = str(request.base_url).rstrip('/')
  632. archive_url = f"{base_url}/archives?id={archive_id}"
  633. # Generate QR code
  634. qr = qrcode.QRCode(
  635. version=1,
  636. error_correction=qrcode.constants.ERROR_CORRECT_M,
  637. box_size=10,
  638. border=2,
  639. )
  640. qr.add_data(archive_url)
  641. qr.make(fit=True)
  642. img = qr.make_image(fill_color="black", back_color="white")
  643. # Resize if needed
  644. if size != 200:
  645. img = img.resize((size, size))
  646. # Convert to bytes
  647. buffer = io.BytesIO()
  648. img.save(buffer, format="PNG")
  649. buffer.seek(0)
  650. return Response(
  651. content=buffer.getvalue(),
  652. media_type="image/png",
  653. headers={
  654. "Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'
  655. }
  656. )
  657. @router.get("/{archive_id}/capabilities")
  658. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  659. """Check what viewing capabilities are available for this 3MF file."""
  660. import json
  661. import re
  662. service = ArchiveService(db)
  663. archive = await service.get_archive(archive_id)
  664. if not archive:
  665. raise HTTPException(404, "Archive not found")
  666. file_path = settings.base_dir / archive.file_path
  667. if not file_path.exists():
  668. raise HTTPException(404, "File not found")
  669. has_model = False
  670. has_gcode = False
  671. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  672. try:
  673. with zipfile.ZipFile(file_path, 'r') as zf:
  674. names = zf.namelist()
  675. # Check for G-code
  676. has_gcode = any(n.startswith('Metadata/') and n.endswith('.gcode') for n in names)
  677. # Check for 3D model - need to look for actual mesh data
  678. for name in names:
  679. if name.endswith('.model'):
  680. try:
  681. content = zf.read(name).decode('utf-8')
  682. # Check if this model file contains actual mesh vertices
  683. if '<vertex' in content or '<mesh' in content:
  684. has_model = True
  685. break
  686. except Exception:
  687. pass
  688. # Extract build volume from project settings
  689. if 'Metadata/project_settings.config' in names:
  690. try:
  691. config_content = zf.read('Metadata/project_settings.config').decode('utf-8')
  692. config_data = json.loads(config_content)
  693. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  694. printable_area = config_data.get('printable_area', [])
  695. if printable_area and len(printable_area) >= 3:
  696. # Get max X and Y from the corner coordinates
  697. max_x = 0
  698. max_y = 0
  699. for coord in printable_area:
  700. if 'x' in coord:
  701. parts = coord.split('x')
  702. if len(parts) == 2:
  703. try:
  704. x, y = int(parts[0]), int(parts[1])
  705. max_x = max(max_x, x)
  706. max_y = max(max_y, y)
  707. except ValueError:
  708. pass
  709. if max_x > 0 and max_y > 0:
  710. build_volume["x"] = max_x
  711. build_volume["y"] = max_y
  712. # Parse printable_height
  713. printable_height = config_data.get('printable_height')
  714. if printable_height:
  715. try:
  716. build_volume["z"] = int(printable_height)
  717. except (ValueError, TypeError):
  718. pass
  719. except Exception:
  720. pass
  721. except zipfile.BadZipFile:
  722. raise HTTPException(400, "Invalid 3MF file")
  723. return {
  724. "has_model": has_model,
  725. "has_gcode": has_gcode,
  726. "build_volume": build_volume,
  727. }
  728. @router.get("/{archive_id}/gcode")
  729. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  730. """Extract and return G-code from the 3MF file."""
  731. service = ArchiveService(db)
  732. archive = await service.get_archive(archive_id)
  733. if not archive:
  734. raise HTTPException(404, "Archive not found")
  735. file_path = settings.base_dir / archive.file_path
  736. if not file_path.exists():
  737. raise HTTPException(404, "File not found")
  738. try:
  739. with zipfile.ZipFile(file_path, 'r') as zf:
  740. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  741. gcode_files = [n for n in zf.namelist() if n.startswith('Metadata/') and n.endswith('.gcode')]
  742. if not gcode_files:
  743. raise HTTPException(
  744. 404,
  745. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio."
  746. )
  747. # Get the first plate's G-code (usually plate_1.gcode)
  748. gcode_content = zf.read(gcode_files[0]).decode('utf-8')
  749. return Response(content=gcode_content, media_type="text/plain")
  750. except zipfile.BadZipFile:
  751. raise HTTPException(400, "Invalid 3MF file")
  752. except HTTPException:
  753. raise
  754. except Exception as e:
  755. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  756. @router.post("/upload")
  757. async def upload_archive(
  758. file: UploadFile = File(...),
  759. printer_id: int | None = None,
  760. db: AsyncSession = Depends(get_db),
  761. ):
  762. """Manually upload a 3MF file to archive."""
  763. if not file.filename or not file.filename.endswith(".3mf"):
  764. raise HTTPException(400, "File must be a .3mf file")
  765. # Save uploaded file temporarily
  766. temp_path = settings.archive_dir / "temp" / file.filename
  767. temp_path.parent.mkdir(parents=True, exist_ok=True)
  768. try:
  769. content = await file.read()
  770. temp_path.write_bytes(content)
  771. service = ArchiveService(db)
  772. archive = await service.archive_print(
  773. printer_id=printer_id,
  774. source_file=temp_path,
  775. )
  776. if not archive:
  777. raise HTTPException(400, "Failed to archive file")
  778. return ArchiveResponse.model_validate(archive)
  779. finally:
  780. if temp_path.exists():
  781. temp_path.unlink()
  782. @router.post("/upload-bulk")
  783. async def upload_archives_bulk(
  784. files: list[UploadFile] = File(...),
  785. printer_id: int | None = None,
  786. db: AsyncSession = Depends(get_db),
  787. ):
  788. """Bulk upload multiple 3MF files to archive."""
  789. results = []
  790. errors = []
  791. for file in files:
  792. if not file.filename or not file.filename.endswith(".3mf"):
  793. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  794. continue
  795. temp_path = settings.archive_dir / "temp" / file.filename
  796. temp_path.parent.mkdir(parents=True, exist_ok=True)
  797. try:
  798. content = await file.read()
  799. temp_path.write_bytes(content)
  800. service = ArchiveService(db)
  801. archive = await service.archive_print(
  802. printer_id=printer_id,
  803. source_file=temp_path,
  804. )
  805. if archive:
  806. results.append({
  807. "filename": file.filename,
  808. "id": archive.id,
  809. "status": "success",
  810. })
  811. else:
  812. errors.append({"filename": file.filename, "error": "Failed to process"})
  813. except Exception as e:
  814. errors.append({"filename": file.filename, "error": str(e)})
  815. finally:
  816. if temp_path.exists():
  817. temp_path.unlink()
  818. return {
  819. "uploaded": len(results),
  820. "failed": len(errors),
  821. "results": results,
  822. "errors": errors,
  823. }
  824. @router.post("/{archive_id}/reprint")
  825. async def reprint_archive(
  826. archive_id: int,
  827. printer_id: int,
  828. db: AsyncSession = Depends(get_db),
  829. ):
  830. """Send an archived 3MF file to a printer and start printing."""
  831. from backend.app.models.printer import Printer
  832. from backend.app.services.bambu_ftp import upload_file_async
  833. from backend.app.services.printer_manager import printer_manager
  834. # Get archive
  835. service = ArchiveService(db)
  836. archive = await service.get_archive(archive_id)
  837. if not archive:
  838. raise HTTPException(404, "Archive not found")
  839. # Get printer
  840. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  841. printer = result.scalar_one_or_none()
  842. if not printer:
  843. raise HTTPException(404, "Printer not found")
  844. # Check printer is connected
  845. if not printer_manager.is_connected(printer_id):
  846. raise HTTPException(400, "Printer is not connected")
  847. # Get the 3MF file path
  848. file_path = settings.base_dir / archive.file_path
  849. if not file_path.exists():
  850. raise HTTPException(404, "Archive file not found")
  851. # Upload file to printer via FTP
  852. remote_filename = archive.filename
  853. remote_path = f"/cache/{remote_filename}"
  854. uploaded = await upload_file_async(
  855. printer.ip_address,
  856. printer.access_code,
  857. file_path,
  858. remote_path,
  859. )
  860. if not uploaded:
  861. raise HTTPException(500, "Failed to upload file to printer")
  862. # Start the print
  863. started = printer_manager.start_print(printer_id, remote_filename)
  864. if not started:
  865. raise HTTPException(500, "Failed to start print")
  866. return {
  867. "status": "printing",
  868. "printer_id": printer_id,
  869. "archive_id": archive_id,
  870. "filename": archive.filename,
  871. }
  872. # =============================================================================
  873. # Project Page API
  874. # =============================================================================
  875. @router.get("/{archive_id}/project-page")
  876. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  877. """Get the project page data from the 3MF file."""
  878. from backend.app.services.archive import ProjectPageParser
  879. from backend.app.schemas.archive import ProjectPageResponse
  880. service = ArchiveService(db)
  881. archive = await service.get_archive(archive_id)
  882. if not archive:
  883. raise HTTPException(404, "Archive not found")
  884. file_path = settings.base_dir / archive.file_path
  885. if not file_path.exists():
  886. raise HTTPException(404, "Archive file not found")
  887. parser = ProjectPageParser(file_path)
  888. data = parser.parse(archive_id)
  889. return ProjectPageResponse(**data)
  890. @router.patch("/{archive_id}/project-page")
  891. async def update_project_page(
  892. archive_id: int,
  893. update_data: dict,
  894. db: AsyncSession = Depends(get_db),
  895. ):
  896. """Update project page metadata in the 3MF file."""
  897. from backend.app.services.archive import ProjectPageParser
  898. service = ArchiveService(db)
  899. archive = await service.get_archive(archive_id)
  900. if not archive:
  901. raise HTTPException(404, "Archive not found")
  902. file_path = settings.base_dir / archive.file_path
  903. if not file_path.exists():
  904. raise HTTPException(404, "Archive file not found")
  905. parser = ProjectPageParser(file_path)
  906. success = parser.update_metadata(update_data)
  907. if not success:
  908. raise HTTPException(500, "Failed to update project page")
  909. # Return updated data
  910. data = parser.parse(archive_id)
  911. return data
  912. @router.get("/{archive_id}/project-image/{image_path:path}")
  913. async def get_project_image(
  914. archive_id: int,
  915. image_path: str,
  916. db: AsyncSession = Depends(get_db),
  917. ):
  918. """Get an image from the 3MF project page."""
  919. from backend.app.services.archive import ProjectPageParser
  920. service = ArchiveService(db)
  921. archive = await service.get_archive(archive_id)
  922. if not archive:
  923. raise HTTPException(404, "Archive not found")
  924. file_path = settings.base_dir / archive.file_path
  925. if not file_path.exists():
  926. raise HTTPException(404, "Archive file not found")
  927. parser = ProjectPageParser(file_path)
  928. result = parser.get_image(image_path)
  929. if not result:
  930. raise HTTPException(404, "Image not found in 3MF file")
  931. image_data, content_type = result
  932. return Response(
  933. content=image_data,
  934. media_type=content_type,
  935. headers={"Cache-Control": "max-age=3600"},
  936. )