archives.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  6. from fastapi.responses import FileResponse, Response
  7. from sqlalchemy import func, select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.config import settings
  10. from backend.app.core.database import get_db
  11. from backend.app.models.archive import PrintArchive
  12. from backend.app.models.filament import Filament
  13. from backend.app.schemas.archive import ArchiveResponse, ArchiveStats, ArchiveUpdate
  14. from backend.app.services.archive import ArchiveService
  15. logger = logging.getLogger(__name__)
  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. # Sanity check: skip unreasonable values (e.g., manually changed status)
  34. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  35. if 5 <= accuracy <= 500:
  36. result["time_accuracy"] = round(accuracy, 1)
  37. return result
  38. def archive_to_response(
  39. archive: PrintArchive,
  40. duplicates: list[dict] | None = None,
  41. duplicate_count: int = 0,
  42. ) -> dict:
  43. """Convert archive model to response dict with computed fields."""
  44. data = {
  45. "id": archive.id,
  46. "printer_id": archive.printer_id,
  47. "project_id": archive.project_id,
  48. "project_name": archive.project.name if archive.project else None,
  49. "filename": archive.filename,
  50. "file_path": archive.file_path,
  51. "file_size": archive.file_size,
  52. "content_hash": archive.content_hash,
  53. "thumbnail_path": archive.thumbnail_path,
  54. "timelapse_path": archive.timelapse_path,
  55. "source_3mf_path": archive.source_3mf_path,
  56. "duplicates": duplicates,
  57. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  58. "print_name": archive.print_name,
  59. "print_time_seconds": archive.print_time_seconds,
  60. "filament_used_grams": archive.filament_used_grams,
  61. "filament_type": archive.filament_type,
  62. "filament_color": archive.filament_color,
  63. "layer_height": archive.layer_height,
  64. "total_layers": archive.total_layers,
  65. "nozzle_diameter": archive.nozzle_diameter,
  66. "bed_temperature": archive.bed_temperature,
  67. "nozzle_temperature": archive.nozzle_temperature,
  68. "status": archive.status,
  69. "started_at": archive.started_at,
  70. "completed_at": archive.completed_at,
  71. "extra_data": archive.extra_data,
  72. "makerworld_url": archive.makerworld_url,
  73. "designer": archive.designer,
  74. "is_favorite": archive.is_favorite,
  75. "tags": archive.tags,
  76. "notes": archive.notes,
  77. "cost": archive.cost,
  78. "photos": archive.photos,
  79. "failure_reason": archive.failure_reason,
  80. "created_at": archive.created_at,
  81. }
  82. # Add computed time accuracy fields
  83. accuracy_data = compute_time_accuracy(archive)
  84. data.update(accuracy_data)
  85. return data
  86. @router.get("/", response_model=list[ArchiveResponse])
  87. async def list_archives(
  88. printer_id: int | None = None,
  89. project_id: int | None = None,
  90. limit: int = 50,
  91. offset: int = 0,
  92. db: AsyncSession = Depends(get_db),
  93. ):
  94. """List archived prints."""
  95. service = ArchiveService(db)
  96. archives = await service.list_archives(
  97. printer_id=printer_id,
  98. project_id=project_id,
  99. limit=limit,
  100. offset=offset,
  101. )
  102. # Get set of hashes that have duplicates (efficient single query)
  103. duplicate_hashes = await service.get_duplicate_hashes()
  104. # Mark archives that have duplicates
  105. result = []
  106. for a in archives:
  107. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  108. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  109. return result
  110. @router.get("/search", response_model=list[ArchiveResponse])
  111. async def search_archives(
  112. q: str = Query(..., min_length=2, description="Search query"),
  113. printer_id: int | None = None,
  114. project_id: int | None = None,
  115. status: str | None = None,
  116. limit: int = 50,
  117. offset: int = 0,
  118. db: AsyncSession = Depends(get_db),
  119. ):
  120. """Full-text search across archives.
  121. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  122. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  123. """
  124. from sqlalchemy import text
  125. from sqlalchemy.orm import selectinload
  126. # Prepare search query - add wildcard for partial matches
  127. search_term = q.strip()
  128. if not search_term.endswith("*"):
  129. search_term = f"{search_term}*"
  130. # Build the FTS query
  131. # Using MATCH for FTS5 full-text search
  132. fts_query = text("""
  133. SELECT rowid FROM archive_fts
  134. WHERE archive_fts MATCH :search_term
  135. ORDER BY rank
  136. LIMIT :limit OFFSET :offset
  137. """)
  138. try:
  139. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  140. matched_ids = [row[0] for row in result.fetchall()]
  141. except Exception as e:
  142. logger.warning(f"FTS search failed, falling back to LIKE search: {e}")
  143. # Fallback to LIKE search if FTS fails
  144. like_pattern = f"%{q}%"
  145. query = (
  146. select(PrintArchive)
  147. .options(selectinload(PrintArchive.project))
  148. .where(
  149. (PrintArchive.print_name.ilike(like_pattern))
  150. | (PrintArchive.filename.ilike(like_pattern))
  151. | (PrintArchive.tags.ilike(like_pattern))
  152. | (PrintArchive.notes.ilike(like_pattern))
  153. | (PrintArchive.designer.ilike(like_pattern))
  154. | (PrintArchive.filament_type.ilike(like_pattern))
  155. )
  156. .order_by(PrintArchive.created_at.desc())
  157. )
  158. if printer_id:
  159. query = query.where(PrintArchive.printer_id == printer_id)
  160. if project_id:
  161. query = query.where(PrintArchive.project_id == project_id)
  162. if status:
  163. query = query.where(PrintArchive.status == status)
  164. query = query.limit(limit).offset(offset)
  165. result = await db.execute(query)
  166. archives = result.scalars().all()
  167. return [archive_to_response(a) for a in archives]
  168. if not matched_ids:
  169. return []
  170. # Fetch full archive records for matched IDs
  171. query = select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id.in_(matched_ids))
  172. # Apply additional filters
  173. if printer_id:
  174. query = query.where(PrintArchive.printer_id == printer_id)
  175. if project_id:
  176. query = query.where(PrintArchive.project_id == project_id)
  177. if status:
  178. query = query.where(PrintArchive.status == status)
  179. result = await db.execute(query)
  180. archives_dict = {a.id: a for a in result.scalars().all()}
  181. # Preserve FTS ranking order and apply pagination
  182. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  183. paginated = ordered_archives[offset : offset + limit]
  184. return [archive_to_response(a) for a in paginated]
  185. @router.post("/search/rebuild-index")
  186. async def rebuild_search_index(db: AsyncSession = Depends(get_db)):
  187. """Rebuild the full-text search index from existing archives.
  188. Use this if search results seem incomplete or incorrect.
  189. """
  190. from sqlalchemy import text
  191. try:
  192. # Clear and rebuild the FTS index
  193. await db.execute(text("DELETE FROM archive_fts"))
  194. # Repopulate from print_archives
  195. await db.execute(
  196. text("""
  197. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  198. SELECT id, print_name, filename, tags, notes, designer, filament_type
  199. FROM print_archives
  200. """)
  201. )
  202. await db.commit()
  203. # Count entries
  204. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  205. count = result.scalar() or 0
  206. return {"message": f"Search index rebuilt with {count} entries"}
  207. except Exception as e:
  208. logger.error(f"Failed to rebuild search index: {e}")
  209. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  210. @router.get("/analysis/failures")
  211. async def analyze_failures(
  212. days: int = 30,
  213. printer_id: int | None = None,
  214. project_id: int | None = None,
  215. db: AsyncSession = Depends(get_db),
  216. ):
  217. """Analyze failure patterns across prints.
  218. Returns failure statistics including:
  219. - Overall failure rate
  220. - Failures by reason, filament type, printer
  221. - Time of day distribution
  222. - Recent failures
  223. - Weekly trend
  224. """
  225. from backend.app.services.failure_analysis import FailureAnalysisService
  226. service = FailureAnalysisService(db)
  227. return await service.analyze_failures(
  228. days=days,
  229. printer_id=printer_id,
  230. project_id=project_id,
  231. )
  232. @router.get("/compare")
  233. async def compare_archives(
  234. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  235. db: AsyncSession = Depends(get_db),
  236. ):
  237. """Compare multiple archives side by side.
  238. Compares print settings, filament usage, and print times.
  239. Also analyzes correlation between settings and success/failure.
  240. Args:
  241. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  242. """
  243. from backend.app.services.archive_comparison import ArchiveComparisonService
  244. # Parse and validate archive IDs
  245. try:
  246. ids = [int(id.strip()) for id in archive_ids.split(",")]
  247. except ValueError:
  248. raise HTTPException(400, "Invalid archive IDs format")
  249. if len(ids) < 2:
  250. raise HTTPException(400, "At least 2 archives required for comparison")
  251. if len(ids) > 5:
  252. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  253. service = ArchiveComparisonService(db)
  254. try:
  255. return await service.compare_archives(ids)
  256. except ValueError as e:
  257. raise HTTPException(400, str(e))
  258. @router.get("/export")
  259. async def export_archives(
  260. format: str = Query("csv", description="Export format: csv or xlsx"),
  261. fields: str | None = Query(None, description="Comma-separated field names"),
  262. printer_id: int | None = None,
  263. project_id: int | None = None,
  264. status: str | None = None,
  265. date_from: str | None = Query(None, description="Start date (ISO format)"),
  266. date_to: str | None = Query(None, description="End date (ISO format)"),
  267. search: str | None = None,
  268. db: AsyncSession = Depends(get_db),
  269. ):
  270. """Export archives to CSV or Excel format.
  271. Returns a downloadable file with archive data.
  272. """
  273. from datetime import datetime
  274. from fastapi.responses import StreamingResponse
  275. from backend.app.services.export import ExportService
  276. if format not in ("csv", "xlsx"):
  277. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  278. # Parse fields
  279. field_list = None
  280. if fields:
  281. field_list = [f.strip() for f in fields.split(",")]
  282. # Parse dates
  283. date_from_dt = None
  284. date_to_dt = None
  285. if date_from:
  286. try:
  287. date_from_dt = datetime.fromisoformat(date_from)
  288. except ValueError:
  289. raise HTTPException(400, "Invalid date_from format")
  290. if date_to:
  291. try:
  292. date_to_dt = datetime.fromisoformat(date_to)
  293. except ValueError:
  294. raise HTTPException(400, "Invalid date_to format")
  295. service = ExportService(db)
  296. try:
  297. file_bytes, filename, content_type = await service.export_archives(
  298. format=format,
  299. fields=field_list,
  300. printer_id=printer_id,
  301. project_id=project_id,
  302. status=status,
  303. date_from=date_from_dt,
  304. date_to=date_to_dt,
  305. search=search,
  306. )
  307. except ImportError as e:
  308. raise HTTPException(500, str(e))
  309. return StreamingResponse(
  310. io.BytesIO(file_bytes),
  311. media_type=content_type,
  312. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  313. )
  314. @router.get("/stats/export")
  315. async def export_stats(
  316. format: str = Query("csv", description="Export format: csv or xlsx"),
  317. days: int = 30,
  318. printer_id: int | None = None,
  319. project_id: int | None = None,
  320. db: AsyncSession = Depends(get_db),
  321. ):
  322. """Export statistics summary to CSV or Excel format."""
  323. from fastapi.responses import StreamingResponse
  324. from backend.app.services.export import ExportService
  325. if format not in ("csv", "xlsx"):
  326. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  327. service = ExportService(db)
  328. try:
  329. file_bytes, filename, content_type = await service.export_stats(
  330. format=format,
  331. days=days,
  332. printer_id=printer_id,
  333. project_id=project_id,
  334. )
  335. except ImportError as e:
  336. raise HTTPException(500, str(e))
  337. return StreamingResponse(
  338. io.BytesIO(file_bytes),
  339. media_type=content_type,
  340. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  341. )
  342. @router.get("/stats", response_model=ArchiveStats)
  343. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  344. """Get statistics across all archives."""
  345. # Total counts
  346. total_result = await db.execute(select(func.count(PrintArchive.id)))
  347. total_prints = total_result.scalar() or 0
  348. successful_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  349. successful_prints = successful_result.scalar() or 0
  350. failed_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed"))
  351. failed_prints = failed_result.scalar() or 0
  352. # Totals
  353. time_result = await db.execute(select(func.sum(PrintArchive.print_time_seconds)))
  354. total_time = (time_result.scalar() or 0) / 3600 # Convert to hours
  355. filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams)))
  356. total_filament = filament_result.scalar() or 0
  357. cost_result = await db.execute(select(func.sum(PrintArchive.cost)))
  358. total_cost = cost_result.scalar() or 0
  359. # By filament type (split comma-separated values for multi-material prints)
  360. filament_type_result = await db.execute(
  361. select(PrintArchive.filament_type).where(PrintArchive.filament_type.isnot(None))
  362. )
  363. prints_by_filament: dict[str, int] = {}
  364. for (filament_types,) in filament_type_result.all():
  365. # Split by comma and count each type
  366. for ftype in filament_types.split(","):
  367. ftype = ftype.strip()
  368. if ftype:
  369. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  370. # By printer
  371. printer_result = await db.execute(
  372. select(PrintArchive.printer_id, func.count(PrintArchive.id)).group_by(PrintArchive.printer_id)
  373. )
  374. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  375. # Time accuracy statistics
  376. # Get all completed archives with both estimated and actual times
  377. accuracy_result = await db.execute(
  378. select(PrintArchive)
  379. .where(PrintArchive.status == "completed")
  380. .where(PrintArchive.print_time_seconds.isnot(None))
  381. .where(PrintArchive.started_at.isnot(None))
  382. .where(PrintArchive.completed_at.isnot(None))
  383. )
  384. archives_with_times = list(accuracy_result.scalars().all())
  385. average_accuracy = None
  386. accuracy_by_printer: dict[str, float] = {}
  387. if archives_with_times:
  388. accuracies = []
  389. printer_accuracies: dict[str, list[float]] = {}
  390. for archive in archives_with_times:
  391. acc_data = compute_time_accuracy(archive)
  392. if acc_data["time_accuracy"] is not None:
  393. accuracies.append(acc_data["time_accuracy"])
  394. # Group by printer
  395. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  396. if printer_key not in printer_accuracies:
  397. printer_accuracies[printer_key] = []
  398. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  399. if accuracies:
  400. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  401. # Calculate per-printer averages
  402. for printer_key, accs in printer_accuracies.items():
  403. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  404. # Energy totals - check which mode to use
  405. from backend.app.api.routes.settings import get_setting
  406. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  407. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  408. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  409. if energy_tracking_mode == "total":
  410. # Total mode: sum up 'total' counter from all smart plugs (lifetime consumption)
  411. from backend.app.models.smart_plug import SmartPlug
  412. from backend.app.services.tasmota import tasmota_service
  413. plugs_result = await db.execute(select(SmartPlug))
  414. plugs = list(plugs_result.scalars().all())
  415. total_energy_kwh = 0.0
  416. for plug in plugs:
  417. energy = await tasmota_service.get_energy(plug)
  418. if energy and energy.get("total") is not None:
  419. total_energy_kwh += energy["total"]
  420. total_energy_kwh = round(total_energy_kwh, 3)
  421. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 2)
  422. else:
  423. # Print mode: sum up per-print energy from archives
  424. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)))
  425. total_energy_kwh = energy_kwh_result.scalar() or 0
  426. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)))
  427. total_energy_cost = energy_cost_result.scalar() or 0
  428. return ArchiveStats(
  429. total_prints=total_prints,
  430. successful_prints=successful_prints,
  431. failed_prints=failed_prints,
  432. total_print_time_hours=round(total_time, 1),
  433. total_filament_grams=round(total_filament, 1),
  434. total_cost=round(total_cost, 2),
  435. prints_by_filament_type=prints_by_filament,
  436. prints_by_printer=prints_by_printer,
  437. average_time_accuracy=average_accuracy,
  438. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  439. total_energy_kwh=round(total_energy_kwh, 3),
  440. total_energy_cost=round(total_energy_cost, 2),
  441. )
  442. @router.get("/{archive_id}", response_model=ArchiveResponse)
  443. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  444. """Get a specific archive."""
  445. service = ArchiveService(db)
  446. archive = await service.get_archive(archive_id)
  447. if not archive:
  448. raise HTTPException(404, "Archive not found")
  449. # Find duplicates
  450. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  451. duplicates = await service.find_duplicates(
  452. archive_id=archive.id,
  453. content_hash=archive.content_hash,
  454. print_name=archive.print_name,
  455. makerworld_model_id=makerworld_id,
  456. )
  457. return archive_to_response(archive, duplicates)
  458. @router.get("/{archive_id}/similar")
  459. async def find_similar_archives(
  460. archive_id: int,
  461. limit: int = 10,
  462. db: AsyncSession = Depends(get_db),
  463. ):
  464. """Find archives with similar settings for comparison.
  465. Returns archives that match by:
  466. - Same print name (highest priority)
  467. - Same file content hash
  468. - Same filament type
  469. """
  470. from backend.app.services.archive_comparison import ArchiveComparisonService
  471. service = ArchiveComparisonService(db)
  472. try:
  473. return await service.find_similar_archives(archive_id, limit=limit)
  474. except ValueError as e:
  475. raise HTTPException(404, str(e))
  476. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  477. async def update_archive(
  478. archive_id: int,
  479. update_data: ArchiveUpdate,
  480. db: AsyncSession = Depends(get_db),
  481. ):
  482. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  483. from sqlalchemy.orm import selectinload
  484. result = await db.execute(
  485. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  486. )
  487. archive = result.scalar_one_or_none()
  488. if not archive:
  489. raise HTTPException(404, "Archive not found")
  490. for field, value in update_data.model_dump(exclude_unset=True).items():
  491. setattr(archive, field, value)
  492. await db.commit()
  493. # Re-fetch with project relationship loaded after commit
  494. result = await db.execute(
  495. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  496. )
  497. archive = result.scalar_one_or_none()
  498. return archive_to_response(archive)
  499. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  500. async def toggle_favorite(
  501. archive_id: int,
  502. db: AsyncSession = Depends(get_db),
  503. ):
  504. """Toggle favorite status for an archive."""
  505. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  506. archive = result.scalar_one_or_none()
  507. if not archive:
  508. raise HTTPException(404, "Archive not found")
  509. archive.is_favorite = not archive.is_favorite
  510. await db.commit()
  511. await db.refresh(archive)
  512. return archive
  513. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  514. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  515. """Rescan the 3MF file and update metadata."""
  516. from backend.app.services.archive import ThreeMFParser
  517. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  518. archive = result.scalar_one_or_none()
  519. if not archive:
  520. raise HTTPException(404, "Archive not found")
  521. file_path = settings.base_dir / archive.file_path
  522. if not file_path.exists():
  523. raise HTTPException(404, "Archive file not found")
  524. # Parse the 3MF file
  525. parser = ThreeMFParser(file_path)
  526. metadata = parser.parse()
  527. # Update fields from metadata
  528. if metadata.get("filament_type"):
  529. archive.filament_type = metadata["filament_type"]
  530. if metadata.get("filament_color"):
  531. archive.filament_color = metadata["filament_color"]
  532. if metadata.get("print_time_seconds"):
  533. archive.print_time_seconds = metadata["print_time_seconds"]
  534. if metadata.get("filament_used_grams"):
  535. archive.filament_used_grams = metadata["filament_used_grams"]
  536. if metadata.get("layer_height"):
  537. archive.layer_height = metadata["layer_height"]
  538. if metadata.get("nozzle_diameter"):
  539. archive.nozzle_diameter = metadata["nozzle_diameter"]
  540. if metadata.get("bed_temperature"):
  541. archive.bed_temperature = metadata["bed_temperature"]
  542. if metadata.get("nozzle_temperature"):
  543. archive.nozzle_temperature = metadata["nozzle_temperature"]
  544. if metadata.get("makerworld_url"):
  545. archive.makerworld_url = metadata["makerworld_url"]
  546. if metadata.get("designer"):
  547. archive.designer = metadata["designer"]
  548. # Calculate cost based on filament usage and type
  549. if archive.filament_used_grams and archive.filament_type:
  550. primary_type = archive.filament_type.split(",")[0].strip()
  551. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  552. filament = filament_result.scalar_one_or_none()
  553. if filament:
  554. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  555. else:
  556. archive.cost = round((archive.filament_used_grams / 1000) * 25.0, 2)
  557. await db.commit()
  558. await db.refresh(archive)
  559. return archive
  560. @router.post("/recalculate-costs")
  561. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  562. """Recalculate costs for all archives based on filament usage and prices."""
  563. result = await db.execute(select(PrintArchive))
  564. archives = list(result.scalars().all())
  565. # Load all filaments for lookup
  566. filament_result = await db.execute(select(Filament))
  567. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  568. default_cost_per_kg = 25.0
  569. updated = 0
  570. for archive in archives:
  571. if archive.filament_used_grams and archive.filament_type:
  572. primary_type = archive.filament_type.split(",")[0].strip()
  573. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  574. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  575. if archive.cost != new_cost:
  576. archive.cost = new_cost
  577. updated += 1
  578. await db.commit()
  579. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  580. @router.post("/rescan-all")
  581. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  582. """Rescan all archives and update their metadata."""
  583. from backend.app.services.archive import ThreeMFParser
  584. result = await db.execute(select(PrintArchive))
  585. archives = list(result.scalars().all())
  586. updated = 0
  587. errors = []
  588. for archive in archives:
  589. try:
  590. file_path = settings.base_dir / archive.file_path
  591. if not file_path.exists():
  592. errors.append({"id": archive.id, "error": "File not found"})
  593. continue
  594. parser = ThreeMFParser(file_path)
  595. metadata = parser.parse()
  596. if metadata.get("filament_type"):
  597. archive.filament_type = metadata["filament_type"]
  598. if metadata.get("filament_color"):
  599. archive.filament_color = metadata["filament_color"]
  600. if metadata.get("print_time_seconds"):
  601. archive.print_time_seconds = metadata["print_time_seconds"]
  602. if metadata.get("filament_used_grams"):
  603. archive.filament_used_grams = metadata["filament_used_grams"]
  604. if metadata.get("layer_height"):
  605. archive.layer_height = metadata["layer_height"]
  606. if metadata.get("nozzle_diameter"):
  607. archive.nozzle_diameter = metadata["nozzle_diameter"]
  608. if metadata.get("makerworld_url"):
  609. archive.makerworld_url = metadata["makerworld_url"]
  610. if metadata.get("designer"):
  611. archive.designer = metadata["designer"]
  612. updated += 1
  613. except Exception as e:
  614. errors.append({"id": archive.id, "error": str(e)})
  615. await db.commit()
  616. return {"updated": updated, "errors": errors}
  617. @router.get("/{archive_id}/duplicates")
  618. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  619. """Get duplicates for a specific archive."""
  620. service = ArchiveService(db)
  621. archive = await service.get_archive(archive_id)
  622. if not archive:
  623. raise HTTPException(404, "Archive not found")
  624. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  625. duplicates = await service.find_duplicates(
  626. archive_id=archive.id,
  627. content_hash=archive.content_hash,
  628. print_name=archive.print_name,
  629. makerworld_model_id=makerworld_id,
  630. )
  631. return {"duplicates": duplicates, "count": len(duplicates)}
  632. @router.post("/backfill-hashes")
  633. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  634. """Compute and store content hashes for all archives missing them."""
  635. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  636. archives = list(result.scalars().all())
  637. updated = 0
  638. errors = []
  639. for archive in archives:
  640. try:
  641. file_path = settings.base_dir / archive.file_path
  642. if not file_path.exists():
  643. errors.append({"id": archive.id, "error": "File not found"})
  644. continue
  645. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  646. updated += 1
  647. except Exception as e:
  648. errors.append({"id": archive.id, "error": str(e)})
  649. await db.commit()
  650. return {"updated": updated, "errors": errors}
  651. @router.delete("/{archive_id}")
  652. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  653. """Delete an archive."""
  654. service = ArchiveService(db)
  655. if not await service.delete_archive(archive_id):
  656. raise HTTPException(404, "Archive not found")
  657. return {"status": "deleted"}
  658. @router.get("/{archive_id}/download")
  659. async def download_archive(
  660. archive_id: int,
  661. inline: bool = False,
  662. db: AsyncSession = Depends(get_db),
  663. ):
  664. """Download the 3MF file."""
  665. service = ArchiveService(db)
  666. archive = await service.get_archive(archive_id)
  667. if not archive:
  668. raise HTTPException(404, "Archive not found")
  669. file_path = settings.base_dir / archive.file_path
  670. if not file_path.exists():
  671. raise HTTPException(404, "File not found")
  672. # Use inline disposition to let browser/OS handle file association
  673. content_disposition = "inline" if inline else "attachment"
  674. return FileResponse(
  675. path=file_path,
  676. filename=archive.filename,
  677. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  678. content_disposition_type=content_disposition,
  679. )
  680. @router.get("/{archive_id}/file/{filename}")
  681. async def download_archive_with_filename(
  682. archive_id: int,
  683. filename: str,
  684. db: AsyncSession = Depends(get_db),
  685. ):
  686. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  687. service = ArchiveService(db)
  688. archive = await service.get_archive(archive_id)
  689. if not archive:
  690. raise HTTPException(404, "Archive not found")
  691. file_path = settings.base_dir / archive.file_path
  692. if not file_path.exists():
  693. raise HTTPException(404, "File not found")
  694. return FileResponse(
  695. path=file_path,
  696. filename=archive.filename,
  697. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  698. )
  699. @router.get("/{archive_id}/thumbnail")
  700. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  701. """Get the thumbnail image."""
  702. service = ArchiveService(db)
  703. archive = await service.get_archive(archive_id)
  704. if not archive or not archive.thumbnail_path:
  705. raise HTTPException(404, "Thumbnail not found")
  706. thumb_path = settings.base_dir / archive.thumbnail_path
  707. if not thumb_path.exists():
  708. raise HTTPException(404, "Thumbnail file not found")
  709. # Use file modification time as ETag to bust cache
  710. mtime = int(thumb_path.stat().st_mtime)
  711. return FileResponse(
  712. path=thumb_path,
  713. media_type="image/png",
  714. headers={
  715. "Cache-Control": "no-cache, must-revalidate",
  716. "ETag": f'"{mtime}"',
  717. },
  718. )
  719. @router.get("/{archive_id}/timelapse")
  720. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  721. """Get the timelapse video."""
  722. service = ArchiveService(db)
  723. archive = await service.get_archive(archive_id)
  724. if not archive or not archive.timelapse_path:
  725. raise HTTPException(404, "Timelapse not found")
  726. timelapse_path = settings.base_dir / archive.timelapse_path
  727. if not timelapse_path.exists():
  728. raise HTTPException(404, "Timelapse file not found")
  729. # Use file modification time as ETag to bust cache after processing
  730. mtime = int(timelapse_path.stat().st_mtime)
  731. return FileResponse(
  732. path=timelapse_path,
  733. media_type="video/mp4",
  734. filename=f"{archive.print_name or 'timelapse'}.mp4",
  735. headers={
  736. "Cache-Control": "no-cache, must-revalidate",
  737. "ETag": f'"{mtime}"',
  738. },
  739. )
  740. @router.post("/{archive_id}/timelapse/scan")
  741. async def scan_timelapse(
  742. archive_id: int,
  743. db: AsyncSession = Depends(get_db),
  744. ):
  745. """Scan printer for timelapse matching this archive and attach it."""
  746. from backend.app.models.printer import Printer
  747. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  748. service = ArchiveService(db)
  749. archive = await service.get_archive(archive_id)
  750. if not archive:
  751. raise HTTPException(404, "Archive not found")
  752. if archive.timelapse_path:
  753. return {"status": "exists", "message": "Timelapse already attached"}
  754. if not archive.printer_id:
  755. raise HTTPException(400, "Archive has no associated printer")
  756. # Get printer
  757. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  758. printer = result.scalar_one_or_none()
  759. if not printer:
  760. raise HTTPException(404, "Printer not found")
  761. # Get base name from archive filename (without .3mf extension)
  762. base_name = Path(archive.filename).stem
  763. # Scan timelapse directory on printer
  764. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  765. files = []
  766. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  767. try:
  768. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  769. if files:
  770. break
  771. except Exception:
  772. continue
  773. if not files:
  774. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  775. # Look for matching timelapse
  776. matching_file = None
  777. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  778. # Strategy 1: Match by print name in filename
  779. for f in mp4_files:
  780. fname = f.get("name", "")
  781. if base_name.lower() in fname.lower():
  782. matching_file = f
  783. break
  784. # Strategy 2: Match by timestamp proximity
  785. # Bambu timelapse filename uses the print START time (when recording began)
  786. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  787. import re
  788. from datetime import datetime, timedelta
  789. # Prefer started_at since video filename is the print start time
  790. # Fall back to completed_at or created_at if started_at is not available
  791. archive_start = archive.started_at
  792. archive_end = archive.completed_at or archive.created_at
  793. best_match = None
  794. best_diff = timedelta(hours=24) # Max 24 hour difference
  795. for f in mp4_files:
  796. fname = f.get("name", "")
  797. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  798. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  799. if match:
  800. try:
  801. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  802. # Try multiple timezone offsets since printer timezone can vary
  803. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  804. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  805. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  806. # Check against start time (video filename = print start)
  807. if archive_start:
  808. diff = abs(adjusted_file_time - archive_start)
  809. if diff < best_diff:
  810. best_diff = diff
  811. best_match = f
  812. logger.debug(
  813. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  814. f"diff from start: {diff}"
  815. )
  816. # Also check against end time with a buffer
  817. # (video timestamp should be BEFORE completion time)
  818. if archive_end:
  819. # The video timestamp should be within the print duration before completion
  820. if adjusted_file_time < archive_end:
  821. diff = archive_end - adjusted_file_time
  822. # Reasonable print duration: up to 48 hours
  823. if diff < timedelta(hours=48) and diff < best_diff:
  824. best_diff = diff
  825. best_match = f
  826. logger.debug(
  827. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  828. f"diff: {diff}"
  829. )
  830. except ValueError:
  831. continue
  832. # Accept match within 4 hours (more lenient for timezone issues)
  833. if best_match and best_diff < timedelta(hours=4):
  834. matching_file = best_match
  835. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  836. # Strategy 3: Use file modification time from FTP listing
  837. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  838. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  839. from datetime import datetime, timedelta
  840. archive_start = archive.started_at
  841. archive_end = archive.completed_at or archive.created_at
  842. best_match = None
  843. best_diff = timedelta(hours=24)
  844. for f in mp4_files:
  845. mtime = f.get("mtime")
  846. if mtime:
  847. # Timelapse file should be modified during or shortly after the print
  848. # The mtime should be close to completion time (video finishes when print ends)
  849. if archive_end:
  850. diff = abs(mtime - archive_end)
  851. if diff < best_diff:
  852. best_diff = diff
  853. best_match = f
  854. logger.debug(
  855. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  856. )
  857. if best_match and best_diff < timedelta(hours=2):
  858. matching_file = best_match
  859. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  860. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  861. # This handles cases where printer clock is wrong or timezone issues exist
  862. if not matching_file and len(mp4_files) == 1:
  863. from datetime import datetime, timedelta
  864. archive_completed = archive.completed_at or archive.created_at
  865. if archive_completed:
  866. time_since_completion = datetime.now() - archive_completed
  867. # If archive was completed within the last hour, assume the single timelapse is for it
  868. if time_since_completion < timedelta(hours=1):
  869. matching_file = mp4_files[0]
  870. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  871. # Note: We intentionally don't use a "most recent file" fallback because
  872. # we can't verify if timelapse was actually enabled for this print.
  873. # Instead, return the list of available files for manual selection.
  874. if not matching_file:
  875. # Return available files for manual selection
  876. available_files = [
  877. {
  878. "name": f.get("name"),
  879. "path": f.get("path"),
  880. "size": f.get("size"),
  881. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  882. }
  883. for f in mp4_files
  884. ]
  885. # Sort by mtime descending (most recent first)
  886. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  887. return {
  888. "status": "not_found",
  889. "message": "No matching timelapse found - please select manually",
  890. "available_files": available_files,
  891. }
  892. # Download the timelapse - use the full path from the file listing
  893. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  894. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  895. if not timelapse_data:
  896. raise HTTPException(500, "Failed to download timelapse")
  897. # Attach timelapse to archive
  898. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  899. if not success:
  900. raise HTTPException(500, "Failed to attach timelapse")
  901. return {
  902. "status": "attached",
  903. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  904. "filename": matching_file["name"],
  905. }
  906. @router.post("/{archive_id}/timelapse/select")
  907. async def select_timelapse(
  908. archive_id: int,
  909. filename: str = Query(..., description="Timelapse filename to attach"),
  910. db: AsyncSession = Depends(get_db),
  911. ):
  912. """Manually select a timelapse from the printer to attach."""
  913. from backend.app.models.printer import Printer
  914. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  915. service = ArchiveService(db)
  916. archive = await service.get_archive(archive_id)
  917. if not archive:
  918. raise HTTPException(404, "Archive not found")
  919. if not archive.printer_id:
  920. raise HTTPException(400, "Archive has no associated printer")
  921. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  922. printer = result.scalar_one_or_none()
  923. if not printer:
  924. raise HTTPException(404, "Printer not found")
  925. # Find the file on the printer
  926. files = []
  927. remote_path = None
  928. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  929. try:
  930. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  931. for f in files:
  932. if f.get("name") == filename:
  933. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  934. break
  935. if remote_path:
  936. break
  937. except Exception:
  938. continue
  939. if not remote_path:
  940. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  941. # Download and attach
  942. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  943. if not timelapse_data:
  944. raise HTTPException(500, "Failed to download timelapse")
  945. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  946. if not success:
  947. raise HTTPException(500, "Failed to attach timelapse")
  948. return {
  949. "status": "attached",
  950. "message": f"Timelapse '{filename}' attached successfully",
  951. "filename": filename,
  952. }
  953. @router.post("/{archive_id}/timelapse/upload")
  954. async def upload_timelapse(
  955. archive_id: int,
  956. file: UploadFile = File(...),
  957. db: AsyncSession = Depends(get_db),
  958. ):
  959. """Manually upload a timelapse video to an archive."""
  960. service = ArchiveService(db)
  961. archive = await service.get_archive(archive_id)
  962. if not archive:
  963. raise HTTPException(404, "Archive not found")
  964. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  965. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  966. content = await file.read()
  967. success = await service.attach_timelapse(archive_id, content, file.filename)
  968. if not success:
  969. raise HTTPException(500, "Failed to attach timelapse")
  970. return {"status": "attached", "filename": file.filename}
  971. @router.get("/{archive_id}/timelapse/info")
  972. async def get_timelapse_info(archive_id: int, db: AsyncSession = Depends(get_db)):
  973. """Get timelapse video metadata for editor."""
  974. from backend.app.schemas.timelapse import TimelapseInfoResponse
  975. from backend.app.services.timelapse_processor import TimelapseProcessor
  976. service = ArchiveService(db)
  977. archive = await service.get_archive(archive_id)
  978. if not archive or not archive.timelapse_path:
  979. raise HTTPException(404, "Timelapse not found")
  980. timelapse_path = settings.base_dir / archive.timelapse_path
  981. if not timelapse_path.exists():
  982. raise HTTPException(404, "Timelapse file not found")
  983. try:
  984. processor = TimelapseProcessor(timelapse_path)
  985. info = await processor.get_info()
  986. return TimelapseInfoResponse(**info)
  987. except Exception as e:
  988. logger.error(f"Failed to get timelapse info: {e}")
  989. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  990. @router.get("/{archive_id}/timelapse/thumbnails")
  991. async def get_timelapse_thumbnails(
  992. archive_id: int,
  993. count: int = Query(10, ge=1, le=30),
  994. width: int = Query(160, ge=80, le=320),
  995. db: AsyncSession = Depends(get_db),
  996. ):
  997. """Generate timeline thumbnail frames for visual scrubbing."""
  998. import base64
  999. from backend.app.schemas.timelapse import ThumbnailResponse
  1000. from backend.app.services.timelapse_processor import TimelapseProcessor
  1001. service = ArchiveService(db)
  1002. archive = await service.get_archive(archive_id)
  1003. if not archive or not archive.timelapse_path:
  1004. raise HTTPException(404, "Timelapse not found")
  1005. timelapse_path = settings.base_dir / archive.timelapse_path
  1006. if not timelapse_path.exists():
  1007. raise HTTPException(404, "Timelapse file not found")
  1008. try:
  1009. processor = TimelapseProcessor(timelapse_path)
  1010. thumbnails = await processor.generate_thumbnails(count, width)
  1011. return ThumbnailResponse(
  1012. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1013. timestamps=[ts for ts, _ in thumbnails],
  1014. )
  1015. except Exception as e:
  1016. logger.error(f"Failed to generate thumbnails: {e}")
  1017. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1018. @router.post("/{archive_id}/timelapse/process")
  1019. async def process_timelapse(
  1020. archive_id: int,
  1021. trim_start: float = Form(0),
  1022. trim_end: float = Form(None),
  1023. speed: float = Form(1.0),
  1024. save_mode: str = Form("new"),
  1025. output_filename: str = Form(None),
  1026. audio: UploadFile = File(None),
  1027. db: AsyncSession = Depends(get_db),
  1028. ):
  1029. """Process timelapse with trim, speed, and optional audio overlay."""
  1030. import shutil
  1031. import tempfile
  1032. from backend.app.schemas.timelapse import ProcessResponse
  1033. from backend.app.services.timelapse_processor import TimelapseProcessor
  1034. # Validate speed
  1035. if not 0.25 <= speed <= 4.0:
  1036. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1037. if save_mode not in ("replace", "new"):
  1038. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1039. service = ArchiveService(db)
  1040. archive = await service.get_archive(archive_id)
  1041. if not archive or not archive.timelapse_path:
  1042. raise HTTPException(404, "Timelapse not found")
  1043. timelapse_path = settings.base_dir / archive.timelapse_path
  1044. if not timelapse_path.exists():
  1045. raise HTTPException(404, "Timelapse file not found")
  1046. archive_dir = timelapse_path.parent
  1047. # Handle audio file
  1048. audio_temp_path = None
  1049. if audio and audio.filename:
  1050. # Validate audio file extension
  1051. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1052. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1053. audio_content = await audio.read()
  1054. suffix = Path(audio.filename).suffix
  1055. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1056. audio_temp_path.write_bytes(audio_content)
  1057. try:
  1058. processor = TimelapseProcessor(timelapse_path)
  1059. # Determine output path
  1060. if save_mode == "replace":
  1061. # Process to temp file first, then replace
  1062. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1063. output_path = temp_output
  1064. else:
  1065. # Save as new file alongside original
  1066. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1067. # Sanitize filename
  1068. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1069. if not filename.endswith(".mp4"):
  1070. filename += ".mp4"
  1071. output_path = archive_dir / filename
  1072. success = await processor.process(
  1073. output_path=output_path,
  1074. trim_start=trim_start,
  1075. trim_end=trim_end,
  1076. speed=speed,
  1077. audio_path=audio_temp_path,
  1078. )
  1079. if not success:
  1080. raise HTTPException(500, "Video processing failed")
  1081. # Handle save mode
  1082. if save_mode == "replace":
  1083. # Replace original file
  1084. shutil.move(str(output_path), str(timelapse_path))
  1085. final_path = archive.timelapse_path
  1086. message = "Timelapse replaced successfully"
  1087. else:
  1088. final_path = str(output_path.relative_to(settings.base_dir))
  1089. message = f"Saved as {output_path.name}"
  1090. return ProcessResponse(
  1091. status="completed",
  1092. output_path=final_path,
  1093. message=message,
  1094. )
  1095. except HTTPException:
  1096. raise
  1097. except Exception as e:
  1098. logger.error(f"Timelapse processing failed: {e}")
  1099. raise HTTPException(500, f"Processing failed: {str(e)}")
  1100. finally:
  1101. # Cleanup temp audio file
  1102. if audio_temp_path and audio_temp_path.exists():
  1103. audio_temp_path.unlink()
  1104. # ============================================
  1105. # Photo Endpoints
  1106. # ============================================
  1107. @router.post("/{archive_id}/photos")
  1108. async def upload_photo(
  1109. archive_id: int,
  1110. file: UploadFile = File(...),
  1111. db: AsyncSession = Depends(get_db),
  1112. ):
  1113. """Upload a photo of the printed result."""
  1114. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1115. archive = result.scalar_one_or_none()
  1116. if not archive:
  1117. raise HTTPException(404, "Archive not found")
  1118. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1119. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1120. # Get archive directory
  1121. file_path = settings.base_dir / archive.file_path
  1122. archive_dir = file_path.parent
  1123. photos_dir = archive_dir / "photos"
  1124. photos_dir.mkdir(exist_ok=True)
  1125. # Generate unique filename
  1126. import uuid
  1127. ext = Path(file.filename).suffix.lower()
  1128. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1129. photo_path = photos_dir / photo_filename
  1130. # Save file
  1131. content = await file.read()
  1132. photo_path.write_bytes(content)
  1133. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1134. photos = list(archive.photos or [])
  1135. photos.append(photo_filename)
  1136. archive.photos = photos
  1137. await db.commit()
  1138. await db.refresh(archive)
  1139. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1140. @router.get("/{archive_id}/photos/{filename}")
  1141. async def get_photo(
  1142. archive_id: int,
  1143. filename: str,
  1144. db: AsyncSession = Depends(get_db),
  1145. ):
  1146. """Get a specific photo."""
  1147. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1148. archive = result.scalar_one_or_none()
  1149. if not archive:
  1150. raise HTTPException(404, "Archive not found")
  1151. file_path = settings.base_dir / archive.file_path
  1152. photo_path = file_path.parent / "photos" / filename
  1153. if not photo_path.exists():
  1154. raise HTTPException(404, "Photo not found")
  1155. # Determine media type
  1156. ext = Path(filename).suffix.lower()
  1157. media_types = {
  1158. ".jpg": "image/jpeg",
  1159. ".jpeg": "image/jpeg",
  1160. ".png": "image/png",
  1161. ".webp": "image/webp",
  1162. }
  1163. media_type = media_types.get(ext, "image/jpeg")
  1164. return FileResponse(path=photo_path, media_type=media_type)
  1165. @router.delete("/{archive_id}/photos/{filename}")
  1166. async def delete_photo(
  1167. archive_id: int,
  1168. filename: str,
  1169. db: AsyncSession = Depends(get_db),
  1170. ):
  1171. """Delete a photo."""
  1172. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1173. archive = result.scalar_one_or_none()
  1174. if not archive:
  1175. raise HTTPException(404, "Archive not found")
  1176. if not archive.photos or filename not in archive.photos:
  1177. raise HTTPException(404, "Photo not found")
  1178. # Delete file
  1179. file_path = settings.base_dir / archive.file_path
  1180. photo_path = file_path.parent / "photos" / filename
  1181. if photo_path.exists():
  1182. photo_path.unlink()
  1183. # Update archive photos list
  1184. photos = [p for p in archive.photos if p != filename]
  1185. archive.photos = photos if photos else None
  1186. await db.commit()
  1187. return {"status": "deleted", "photos": archive.photos}
  1188. # ============================================
  1189. # QR Code Endpoint
  1190. # ============================================
  1191. @router.get("/{archive_id}/qrcode")
  1192. async def get_qrcode(
  1193. archive_id: int,
  1194. request: Request,
  1195. size: int = 200,
  1196. db: AsyncSession = Depends(get_db),
  1197. ):
  1198. """Generate a QR code that links to this archive."""
  1199. import qrcode
  1200. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1201. archive = result.scalar_one_or_none()
  1202. if not archive:
  1203. raise HTTPException(404, "Archive not found")
  1204. # Build URL to archive detail page
  1205. base_url = str(request.base_url).rstrip("/")
  1206. archive_url = f"{base_url}/archives?id={archive_id}"
  1207. # Generate QR code
  1208. qr = qrcode.QRCode(
  1209. version=1,
  1210. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1211. box_size=10,
  1212. border=2,
  1213. )
  1214. qr.add_data(archive_url)
  1215. qr.make(fit=True)
  1216. img = qr.make_image(fill_color="black", back_color="white")
  1217. # Resize if needed
  1218. if size != 200:
  1219. img = img.resize((size, size))
  1220. # Convert to bytes
  1221. buffer = io.BytesIO()
  1222. img.save(buffer, format="PNG")
  1223. buffer.seek(0)
  1224. return Response(
  1225. content=buffer.getvalue(),
  1226. media_type="image/png",
  1227. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1228. )
  1229. @router.get("/{archive_id}/capabilities")
  1230. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1231. """Check what viewing capabilities are available for this 3MF file."""
  1232. import json
  1233. import xml.etree.ElementTree as ET
  1234. service = ArchiveService(db)
  1235. archive = await service.get_archive(archive_id)
  1236. if not archive:
  1237. raise HTTPException(404, "Archive not found")
  1238. file_path = settings.base_dir / archive.file_path
  1239. if not file_path.exists():
  1240. raise HTTPException(404, "File not found")
  1241. has_model = False
  1242. has_gcode = False
  1243. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1244. filament_colors: list[str] = []
  1245. try:
  1246. with zipfile.ZipFile(file_path, "r") as zf:
  1247. names = zf.namelist()
  1248. # Check for G-code
  1249. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1250. # Check for 3D model - need to look for actual mesh data
  1251. for name in names:
  1252. if name.endswith(".model"):
  1253. try:
  1254. content = zf.read(name).decode("utf-8")
  1255. # Check if this model file contains actual mesh vertices
  1256. if "<vertex" in content or "<mesh" in content:
  1257. has_model = True
  1258. break
  1259. except Exception:
  1260. pass
  1261. # Extract filament colors from slice_info.config
  1262. # These are the actual filaments used in the print, indexed by tool/extruder
  1263. if "Metadata/slice_info.config" in names:
  1264. try:
  1265. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1266. root = ET.fromstring(slice_content)
  1267. # Get all filaments with their IDs and colors
  1268. # <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  1269. # ID corresponds to the tool number in G-code (T0, T1, etc.)
  1270. filaments = root.findall(".//filament")
  1271. filament_map: dict[int, str] = {}
  1272. for f in filaments:
  1273. fid = f.get("id")
  1274. fcolor = f.get("color")
  1275. used_g = f.get("used_g", "0")
  1276. try:
  1277. used_amount = float(used_g)
  1278. except (ValueError, TypeError):
  1279. used_amount = 0
  1280. # Include all filaments, but mark unused ones
  1281. if fid is not None and fcolor:
  1282. try:
  1283. # IDs are 1-based in slice_info, tools are 0-based
  1284. tool_id = int(fid) - 1
  1285. if tool_id >= 0 and used_amount > 0:
  1286. filament_map[tool_id] = fcolor
  1287. except ValueError:
  1288. pass
  1289. # Convert to ordered list (tool 0, tool 1, etc.)
  1290. if filament_map:
  1291. max_tool = max(filament_map.keys())
  1292. for i in range(max_tool + 1):
  1293. filament_colors.append(filament_map.get(i, "#00AE42"))
  1294. except Exception:
  1295. pass
  1296. # Extract build volume from project settings
  1297. if "Metadata/project_settings.config" in names:
  1298. try:
  1299. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1300. config_data = json.loads(config_content)
  1301. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1302. printable_area = config_data.get("printable_area", [])
  1303. if printable_area and len(printable_area) >= 3:
  1304. # Get max X and Y from the corner coordinates
  1305. max_x = 0
  1306. max_y = 0
  1307. for coord in printable_area:
  1308. if "x" in coord:
  1309. parts = coord.split("x")
  1310. if len(parts) == 2:
  1311. try:
  1312. x, y = int(parts[0]), int(parts[1])
  1313. max_x = max(max_x, x)
  1314. max_y = max(max_y, y)
  1315. except ValueError:
  1316. pass
  1317. if max_x > 0 and max_y > 0:
  1318. build_volume["x"] = max_x
  1319. build_volume["y"] = max_y
  1320. # Parse printable_height
  1321. printable_height = config_data.get("printable_height")
  1322. if printable_height:
  1323. try:
  1324. build_volume["z"] = int(printable_height)
  1325. except (ValueError, TypeError):
  1326. pass
  1327. except Exception:
  1328. pass
  1329. except zipfile.BadZipFile:
  1330. raise HTTPException(400, "Invalid 3MF file")
  1331. return {
  1332. "has_model": has_model,
  1333. "has_gcode": has_gcode,
  1334. "build_volume": build_volume,
  1335. "filament_colors": filament_colors,
  1336. }
  1337. @router.get("/{archive_id}/gcode")
  1338. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1339. """Extract and return G-code from the 3MF file."""
  1340. service = ArchiveService(db)
  1341. archive = await service.get_archive(archive_id)
  1342. if not archive:
  1343. raise HTTPException(404, "Archive not found")
  1344. file_path = settings.base_dir / archive.file_path
  1345. if not file_path.exists():
  1346. raise HTTPException(404, "File not found")
  1347. try:
  1348. with zipfile.ZipFile(file_path, "r") as zf:
  1349. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1350. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1351. if not gcode_files:
  1352. raise HTTPException(
  1353. 404,
  1354. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1355. )
  1356. # Get the first plate's G-code (usually plate_1.gcode)
  1357. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1358. return Response(content=gcode_content, media_type="text/plain")
  1359. except zipfile.BadZipFile:
  1360. raise HTTPException(400, "Invalid 3MF file")
  1361. except HTTPException:
  1362. raise
  1363. except Exception as e:
  1364. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1365. @router.post("/upload")
  1366. async def upload_archive(
  1367. file: UploadFile = File(...),
  1368. printer_id: int | None = None,
  1369. db: AsyncSession = Depends(get_db),
  1370. ):
  1371. """Manually upload a 3MF file to archive."""
  1372. if not file.filename or not file.filename.endswith(".3mf"):
  1373. raise HTTPException(400, "File must be a .3mf file")
  1374. # Save uploaded file temporarily
  1375. temp_path = settings.archive_dir / "temp" / file.filename
  1376. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1377. try:
  1378. content = await file.read()
  1379. temp_path.write_bytes(content)
  1380. service = ArchiveService(db)
  1381. archive = await service.archive_print(
  1382. printer_id=printer_id,
  1383. source_file=temp_path,
  1384. )
  1385. if not archive:
  1386. raise HTTPException(400, "Failed to archive file")
  1387. return ArchiveResponse.model_validate(archive)
  1388. finally:
  1389. if temp_path.exists():
  1390. temp_path.unlink()
  1391. @router.post("/upload-bulk")
  1392. async def upload_archives_bulk(
  1393. files: list[UploadFile] = File(...),
  1394. printer_id: int | None = None,
  1395. db: AsyncSession = Depends(get_db),
  1396. ):
  1397. """Bulk upload multiple 3MF files to archive."""
  1398. results = []
  1399. errors = []
  1400. for file in files:
  1401. if not file.filename or not file.filename.endswith(".3mf"):
  1402. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1403. continue
  1404. temp_path = settings.archive_dir / "temp" / file.filename
  1405. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1406. try:
  1407. content = await file.read()
  1408. temp_path.write_bytes(content)
  1409. service = ArchiveService(db)
  1410. archive = await service.archive_print(
  1411. printer_id=printer_id,
  1412. source_file=temp_path,
  1413. )
  1414. if archive:
  1415. results.append(
  1416. {
  1417. "filename": file.filename,
  1418. "id": archive.id,
  1419. "status": "success",
  1420. }
  1421. )
  1422. else:
  1423. errors.append({"filename": file.filename, "error": "Failed to process"})
  1424. except Exception as e:
  1425. errors.append({"filename": file.filename, "error": str(e)})
  1426. finally:
  1427. if temp_path.exists():
  1428. temp_path.unlink()
  1429. return {
  1430. "uploaded": len(results),
  1431. "failed": len(errors),
  1432. "results": results,
  1433. "errors": errors,
  1434. }
  1435. @router.get("/{archive_id}/filament-requirements")
  1436. async def get_filament_requirements(
  1437. archive_id: int,
  1438. db: AsyncSession = Depends(get_db),
  1439. ):
  1440. """Get filament requirements from the archived 3MF file.
  1441. Returns the filaments used in this print with their slot IDs, types, colors,
  1442. and usage amounts. This can be compared with current AMS state before reprinting.
  1443. """
  1444. import xml.etree.ElementTree as ET
  1445. service = ArchiveService(db)
  1446. archive = await service.get_archive(archive_id)
  1447. if not archive:
  1448. raise HTTPException(404, "Archive not found")
  1449. file_path = settings.base_dir / archive.file_path
  1450. if not file_path.exists():
  1451. raise HTTPException(404, "Archive file not found")
  1452. filaments = []
  1453. try:
  1454. with zipfile.ZipFile(file_path, "r") as zf:
  1455. # Parse slice_info.config for filament requirements
  1456. if "Metadata/slice_info.config" in zf.namelist():
  1457. content = zf.read("Metadata/slice_info.config").decode()
  1458. root = ET.fromstring(content)
  1459. # Extract filament elements
  1460. # Format: <filament id="1" type="PLA" color="#FFFFFF" used_g="100" used_m="10" />
  1461. for filament_elem in root.findall(".//filament"):
  1462. filament_id = filament_elem.get("id")
  1463. filament_type = filament_elem.get("type", "")
  1464. filament_color = filament_elem.get("color", "")
  1465. used_g = filament_elem.get("used_g", "0")
  1466. used_m = filament_elem.get("used_m", "0")
  1467. # Only include filaments that are actually used
  1468. try:
  1469. used_grams = float(used_g)
  1470. except (ValueError, TypeError):
  1471. used_grams = 0
  1472. if used_grams > 0 and filament_id:
  1473. filaments.append(
  1474. {
  1475. "slot_id": int(filament_id),
  1476. "type": filament_type,
  1477. "color": filament_color,
  1478. "used_grams": round(used_grams, 1),
  1479. "used_meters": float(used_m) if used_m else 0,
  1480. }
  1481. )
  1482. # Sort by slot ID
  1483. filaments.sort(key=lambda x: x["slot_id"])
  1484. except Exception as e:
  1485. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  1486. return {
  1487. "archive_id": archive_id,
  1488. "filename": archive.filename,
  1489. "filaments": filaments,
  1490. }
  1491. @router.post("/{archive_id}/reprint")
  1492. async def reprint_archive(
  1493. archive_id: int,
  1494. printer_id: int,
  1495. db: AsyncSession = Depends(get_db),
  1496. ):
  1497. """Send an archived 3MF file to a printer and start printing."""
  1498. from backend.app.main import register_expected_print
  1499. from backend.app.models.printer import Printer
  1500. from backend.app.services.bambu_ftp import upload_file_async
  1501. from backend.app.services.printer_manager import printer_manager
  1502. # Get archive
  1503. service = ArchiveService(db)
  1504. archive = await service.get_archive(archive_id)
  1505. if not archive:
  1506. raise HTTPException(404, "Archive not found")
  1507. # Get printer
  1508. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1509. printer = result.scalar_one_or_none()
  1510. if not printer:
  1511. raise HTTPException(404, "Printer not found")
  1512. # Check printer is connected
  1513. if not printer_manager.is_connected(printer_id):
  1514. raise HTTPException(400, "Printer is not connected")
  1515. # Get the sliced 3MF file path
  1516. file_path = settings.base_dir / archive.file_path
  1517. if not file_path.exists():
  1518. raise HTTPException(404, "Archive file not found")
  1519. # Upload file to printer via FTP
  1520. from backend.app.services.bambu_ftp import delete_file_async
  1521. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1522. # The printer might reject filenames with unusual extensions
  1523. base_name = archive.filename
  1524. if base_name.endswith(".gcode.3mf"):
  1525. base_name = base_name[:-10] # Remove .gcode.3mf
  1526. elif base_name.endswith(".3mf"):
  1527. base_name = base_name[:-4] # Remove .3mf
  1528. remote_filename = f"{base_name}.3mf"
  1529. remote_path = f"/{remote_filename}"
  1530. # Delete existing file if present (avoids 553 error)
  1531. await delete_file_async(
  1532. printer.ip_address,
  1533. printer.access_code,
  1534. remote_path,
  1535. )
  1536. uploaded = await upload_file_async(
  1537. printer.ip_address,
  1538. printer.access_code,
  1539. file_path,
  1540. remote_path,
  1541. )
  1542. if not uploaded:
  1543. raise HTTPException(500, "Failed to upload file to printer")
  1544. # Register this as an expected print so we don't create a duplicate archive
  1545. register_expected_print(printer_id, remote_filename, archive_id)
  1546. # Detect plate ID from 3MF file
  1547. plate_id = 1
  1548. try:
  1549. with zipfile.ZipFile(file_path, "r") as zf:
  1550. for name in zf.namelist():
  1551. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1552. # Extract plate number from "Metadata/plate_X.gcode"
  1553. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1554. plate_id = int(plate_str)
  1555. break
  1556. except Exception:
  1557. pass # Default to plate 1 if detection fails
  1558. logger.info(f"Reprint archive {archive_id}: using plate_id={plate_id}")
  1559. # Start the print
  1560. started = printer_manager.start_print(printer_id, remote_filename, plate_id)
  1561. if not started:
  1562. raise HTTPException(500, "Failed to start print")
  1563. return {
  1564. "status": "printing",
  1565. "printer_id": printer_id,
  1566. "archive_id": archive_id,
  1567. "filename": archive.filename,
  1568. }
  1569. # =============================================================================
  1570. # Project Page API
  1571. # =============================================================================
  1572. @router.get("/{archive_id}/project-page")
  1573. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  1574. """Get the project page data from the 3MF file."""
  1575. from backend.app.schemas.archive import ProjectPageResponse
  1576. from backend.app.services.archive import ProjectPageParser
  1577. service = ArchiveService(db)
  1578. archive = await service.get_archive(archive_id)
  1579. if not archive:
  1580. raise HTTPException(404, "Archive not found")
  1581. file_path = settings.base_dir / archive.file_path
  1582. if not file_path.exists():
  1583. raise HTTPException(404, "Archive file not found")
  1584. parser = ProjectPageParser(file_path)
  1585. data = parser.parse(archive_id)
  1586. return ProjectPageResponse(**data)
  1587. @router.patch("/{archive_id}/project-page")
  1588. async def update_project_page(
  1589. archive_id: int,
  1590. update_data: dict,
  1591. db: AsyncSession = Depends(get_db),
  1592. ):
  1593. """Update project page metadata in the 3MF file."""
  1594. from backend.app.services.archive import ProjectPageParser
  1595. service = ArchiveService(db)
  1596. archive = await service.get_archive(archive_id)
  1597. if not archive:
  1598. raise HTTPException(404, "Archive not found")
  1599. file_path = settings.base_dir / archive.file_path
  1600. if not file_path.exists():
  1601. raise HTTPException(404, "Archive file not found")
  1602. parser = ProjectPageParser(file_path)
  1603. success = parser.update_metadata(update_data)
  1604. if not success:
  1605. raise HTTPException(500, "Failed to update project page")
  1606. # Return updated data
  1607. data = parser.parse(archive_id)
  1608. return data
  1609. @router.get("/{archive_id}/project-image/{image_path:path}")
  1610. async def get_project_image(
  1611. archive_id: int,
  1612. image_path: str,
  1613. db: AsyncSession = Depends(get_db),
  1614. ):
  1615. """Get an image from the 3MF project page."""
  1616. from backend.app.services.archive import ProjectPageParser
  1617. service = ArchiveService(db)
  1618. archive = await service.get_archive(archive_id)
  1619. if not archive:
  1620. raise HTTPException(404, "Archive not found")
  1621. file_path = settings.base_dir / archive.file_path
  1622. if not file_path.exists():
  1623. raise HTTPException(404, "Archive file not found")
  1624. parser = ProjectPageParser(file_path)
  1625. result = parser.get_image(image_path)
  1626. if not result:
  1627. raise HTTPException(404, "Image not found in 3MF file")
  1628. image_data, content_type = result
  1629. return Response(
  1630. content=image_data,
  1631. media_type=content_type,
  1632. headers={"Cache-Control": "max-age=3600"},
  1633. )
  1634. # =============================================================================
  1635. # Source 3MF API (Original Project Files)
  1636. # =============================================================================
  1637. @router.post("/{archive_id}/source")
  1638. async def upload_source_3mf(
  1639. archive_id: int,
  1640. file: UploadFile = File(...),
  1641. db: AsyncSession = Depends(get_db),
  1642. ):
  1643. """Upload the original source 3MF project file for an archive."""
  1644. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1645. archive = result.scalar_one_or_none()
  1646. if not archive:
  1647. raise HTTPException(404, "Archive not found")
  1648. if not file.filename or not file.filename.endswith(".3mf"):
  1649. raise HTTPException(400, "File must be a .3mf file")
  1650. # Get archive directory and create source subdirectory
  1651. file_path = settings.base_dir / archive.file_path
  1652. archive_dir = file_path.parent
  1653. source_dir = archive_dir / "source"
  1654. source_dir.mkdir(exist_ok=True)
  1655. # Delete old source file if exists
  1656. if archive.source_3mf_path:
  1657. old_source_path = settings.base_dir / archive.source_3mf_path
  1658. if old_source_path.exists():
  1659. old_source_path.unlink()
  1660. # Save the source 3MF file - preserve original filename
  1661. source_filename = file.filename
  1662. source_path = source_dir / source_filename
  1663. content = await file.read()
  1664. source_path.write_bytes(content)
  1665. # Update archive with source path (relative to base_dir)
  1666. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1667. await db.commit()
  1668. await db.refresh(archive)
  1669. return {
  1670. "status": "uploaded",
  1671. "source_3mf_path": archive.source_3mf_path,
  1672. "filename": source_filename,
  1673. }
  1674. @router.get("/{archive_id}/source")
  1675. async def download_source_3mf(
  1676. archive_id: int,
  1677. db: AsyncSession = Depends(get_db),
  1678. ):
  1679. """Download the source 3MF project file."""
  1680. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1681. archive = result.scalar_one_or_none()
  1682. if not archive:
  1683. raise HTTPException(404, "Archive not found")
  1684. if not archive.source_3mf_path:
  1685. raise HTTPException(404, "No source 3MF attached to this archive")
  1686. source_path = settings.base_dir / archive.source_3mf_path
  1687. if not source_path.exists():
  1688. raise HTTPException(404, "Source 3MF file not found on disk")
  1689. # Use the actual filename from the path
  1690. filename = source_path.name
  1691. return FileResponse(
  1692. path=source_path,
  1693. filename=filename,
  1694. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1695. )
  1696. @router.get("/{archive_id}/source/{filename}")
  1697. async def download_source_3mf_for_slicer(
  1698. archive_id: int,
  1699. filename: str,
  1700. db: AsyncSession = Depends(get_db),
  1701. ):
  1702. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  1703. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1704. archive = result.scalar_one_or_none()
  1705. if not archive:
  1706. raise HTTPException(404, "Archive not found")
  1707. if not archive.source_3mf_path:
  1708. raise HTTPException(404, "No source 3MF attached to this archive")
  1709. source_path = settings.base_dir / archive.source_3mf_path
  1710. if not source_path.exists():
  1711. raise HTTPException(404, "Source 3MF file not found on disk")
  1712. return FileResponse(
  1713. path=source_path,
  1714. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  1715. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1716. )
  1717. @router.post("/upload-source")
  1718. async def upload_source_3mf_by_name(
  1719. file: UploadFile = File(...),
  1720. print_name: str = Query(None, description="Match archive by print name"),
  1721. db: AsyncSession = Depends(get_db),
  1722. ):
  1723. """Upload source 3MF and match to archive by print name.
  1724. This endpoint is designed for slicer post-processing scripts.
  1725. It finds the most recent archive matching the print name and attaches the source.
  1726. """
  1727. if not file.filename or not file.filename.endswith(".3mf"):
  1728. raise HTTPException(400, "File must be a .3mf file")
  1729. # Derive print name from filename if not provided
  1730. if not print_name:
  1731. # Remove .3mf extension and common suffixes
  1732. print_name = file.filename.rsplit(".3mf", 1)[0]
  1733. # Remove _source suffix if present
  1734. if print_name.endswith("_source"):
  1735. print_name = print_name[:-7]
  1736. # Find matching archive - try exact match first, then fuzzy
  1737. result = await db.execute(
  1738. select(PrintArchive)
  1739. .where(PrintArchive.print_name == print_name)
  1740. .order_by(PrintArchive.created_at.desc())
  1741. .limit(1)
  1742. )
  1743. archive = result.scalar_one_or_none()
  1744. if not archive:
  1745. # Try matching filename without .gcode.3mf
  1746. result = await db.execute(
  1747. select(PrintArchive)
  1748. .where(PrintArchive.filename.like(f"{print_name}%"))
  1749. .order_by(PrintArchive.created_at.desc())
  1750. .limit(1)
  1751. )
  1752. archive = result.scalar_one_or_none()
  1753. if not archive:
  1754. # Try case-insensitive partial match on print_name
  1755. result = await db.execute(
  1756. select(PrintArchive)
  1757. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  1758. .order_by(PrintArchive.created_at.desc())
  1759. .limit(1)
  1760. )
  1761. archive = result.scalar_one_or_none()
  1762. if not archive:
  1763. raise HTTPException(404, f"No archive found matching '{print_name}'")
  1764. # Get archive directory and create source subdirectory
  1765. file_path = settings.base_dir / archive.file_path
  1766. archive_dir = file_path.parent
  1767. source_dir = archive_dir / "source"
  1768. source_dir.mkdir(exist_ok=True)
  1769. # Delete old source file if exists
  1770. if archive.source_3mf_path:
  1771. old_source_path = settings.base_dir / archive.source_3mf_path
  1772. if old_source_path.exists():
  1773. old_source_path.unlink()
  1774. # Save the source 3MF file - preserve original filename
  1775. source_filename = file.filename
  1776. source_path = source_dir / source_filename
  1777. content = await file.read()
  1778. source_path.write_bytes(content)
  1779. # Update archive with source path
  1780. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1781. await db.commit()
  1782. await db.refresh(archive)
  1783. return {
  1784. "status": "uploaded",
  1785. "archive_id": archive.id,
  1786. "archive_name": archive.print_name or archive.filename,
  1787. "source_3mf_path": archive.source_3mf_path,
  1788. "filename": source_filename,
  1789. }
  1790. @router.delete("/{archive_id}/source")
  1791. async def delete_source_3mf(
  1792. archive_id: int,
  1793. db: AsyncSession = Depends(get_db),
  1794. ):
  1795. """Delete the source 3MF project file from an archive."""
  1796. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1797. archive = result.scalar_one_or_none()
  1798. if not archive:
  1799. raise HTTPException(404, "Archive not found")
  1800. if not archive.source_3mf_path:
  1801. raise HTTPException(404, "No source 3MF attached to this archive")
  1802. # Delete the file
  1803. source_path = settings.base_dir / archive.source_3mf_path
  1804. if source_path.exists():
  1805. source_path.unlink()
  1806. # Clear the path in database
  1807. archive.source_3mf_path = None
  1808. await db.commit()
  1809. return {"status": "deleted"}