archives.py 43 KB

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