archives.py 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864
  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, ReprintRequest
  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. "f3d_path": archive.f3d_path,
  57. "duplicates": duplicates,
  58. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  59. "print_name": archive.print_name,
  60. "print_time_seconds": archive.print_time_seconds,
  61. "filament_used_grams": archive.filament_used_grams,
  62. "filament_type": archive.filament_type,
  63. "filament_color": archive.filament_color,
  64. "layer_height": archive.layer_height,
  65. "total_layers": archive.total_layers,
  66. "nozzle_diameter": archive.nozzle_diameter,
  67. "bed_temperature": archive.bed_temperature,
  68. "nozzle_temperature": archive.nozzle_temperature,
  69. "status": archive.status,
  70. "started_at": archive.started_at,
  71. "completed_at": archive.completed_at,
  72. "extra_data": archive.extra_data,
  73. "makerworld_url": archive.makerworld_url,
  74. "designer": archive.designer,
  75. "is_favorite": archive.is_favorite,
  76. "tags": archive.tags,
  77. "notes": archive.notes,
  78. "cost": archive.cost,
  79. "photos": archive.photos,
  80. "failure_reason": archive.failure_reason,
  81. "quantity": archive.quantity,
  82. "energy_kwh": archive.energy_kwh,
  83. "energy_cost": archive.energy_cost,
  84. "created_at": archive.created_at,
  85. }
  86. # Add computed time accuracy fields
  87. accuracy_data = compute_time_accuracy(archive)
  88. data.update(accuracy_data)
  89. return data
  90. @router.get("/", response_model=list[ArchiveResponse])
  91. async def list_archives(
  92. printer_id: int | None = None,
  93. project_id: int | None = None,
  94. limit: int = 50,
  95. offset: int = 0,
  96. db: AsyncSession = Depends(get_db),
  97. ):
  98. """List archived prints."""
  99. service = ArchiveService(db)
  100. archives = await service.list_archives(
  101. printer_id=printer_id,
  102. project_id=project_id,
  103. limit=limit,
  104. offset=offset,
  105. )
  106. # Get set of hashes that have duplicates (efficient single query)
  107. duplicate_hashes = await service.get_duplicate_hashes()
  108. # Mark archives that have duplicates
  109. result = []
  110. for a in archives:
  111. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  112. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  113. return result
  114. @router.get("/search", response_model=list[ArchiveResponse])
  115. async def search_archives(
  116. q: str = Query(..., min_length=2, description="Search query"),
  117. printer_id: int | None = None,
  118. project_id: int | None = None,
  119. status: str | None = None,
  120. limit: int = 50,
  121. offset: int = 0,
  122. db: AsyncSession = Depends(get_db),
  123. ):
  124. """Full-text search across archives.
  125. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  126. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  127. """
  128. from sqlalchemy import text
  129. from sqlalchemy.orm import selectinload
  130. # Prepare search query - add wildcard for partial matches
  131. search_term = q.strip()
  132. if not search_term.endswith("*"):
  133. search_term = f"{search_term}*"
  134. # Build the FTS query
  135. # Using MATCH for FTS5 full-text search
  136. fts_query = text("""
  137. SELECT rowid FROM archive_fts
  138. WHERE archive_fts MATCH :search_term
  139. ORDER BY rank
  140. LIMIT :limit OFFSET :offset
  141. """)
  142. try:
  143. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  144. matched_ids = [row[0] for row in result.fetchall()]
  145. except Exception as e:
  146. logger.warning(f"FTS search failed, falling back to LIKE search: {e}")
  147. # Fallback to LIKE search if FTS fails
  148. like_pattern = f"%{q}%"
  149. query = (
  150. select(PrintArchive)
  151. .options(selectinload(PrintArchive.project))
  152. .where(
  153. (PrintArchive.print_name.ilike(like_pattern))
  154. | (PrintArchive.filename.ilike(like_pattern))
  155. | (PrintArchive.tags.ilike(like_pattern))
  156. | (PrintArchive.notes.ilike(like_pattern))
  157. | (PrintArchive.designer.ilike(like_pattern))
  158. | (PrintArchive.filament_type.ilike(like_pattern))
  159. )
  160. .order_by(PrintArchive.created_at.desc())
  161. )
  162. if printer_id:
  163. query = query.where(PrintArchive.printer_id == printer_id)
  164. if project_id:
  165. query = query.where(PrintArchive.project_id == project_id)
  166. if status:
  167. query = query.where(PrintArchive.status == status)
  168. query = query.limit(limit).offset(offset)
  169. result = await db.execute(query)
  170. archives = result.scalars().all()
  171. return [archive_to_response(a) for a in archives]
  172. if not matched_ids:
  173. return []
  174. # Fetch full archive records for matched IDs
  175. query = select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id.in_(matched_ids))
  176. # Apply additional filters
  177. if printer_id:
  178. query = query.where(PrintArchive.printer_id == printer_id)
  179. if project_id:
  180. query = query.where(PrintArchive.project_id == project_id)
  181. if status:
  182. query = query.where(PrintArchive.status == status)
  183. result = await db.execute(query)
  184. archives_dict = {a.id: a for a in result.scalars().all()}
  185. # Preserve FTS ranking order and apply pagination
  186. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  187. paginated = ordered_archives[offset : offset + limit]
  188. return [archive_to_response(a) for a in paginated]
  189. @router.post("/search/rebuild-index")
  190. async def rebuild_search_index(db: AsyncSession = Depends(get_db)):
  191. """Rebuild the full-text search index from existing archives.
  192. Use this if search results seem incomplete or incorrect.
  193. """
  194. from sqlalchemy import text
  195. try:
  196. # Clear and rebuild the FTS index
  197. await db.execute(text("DELETE FROM archive_fts"))
  198. # Repopulate from print_archives
  199. await db.execute(
  200. text("""
  201. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  202. SELECT id, print_name, filename, tags, notes, designer, filament_type
  203. FROM print_archives
  204. """)
  205. )
  206. await db.commit()
  207. # Count entries
  208. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  209. count = result.scalar() or 0
  210. return {"message": f"Search index rebuilt with {count} entries"}
  211. except Exception as e:
  212. logger.error(f"Failed to rebuild search index: {e}")
  213. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  214. @router.get("/analysis/failures")
  215. async def analyze_failures(
  216. days: int = 30,
  217. printer_id: int | None = None,
  218. project_id: int | None = None,
  219. db: AsyncSession = Depends(get_db),
  220. ):
  221. """Analyze failure patterns across prints.
  222. Returns failure statistics including:
  223. - Overall failure rate
  224. - Failures by reason, filament type, printer
  225. - Time of day distribution
  226. - Recent failures
  227. - Weekly trend
  228. """
  229. from backend.app.services.failure_analysis import FailureAnalysisService
  230. service = FailureAnalysisService(db)
  231. return await service.analyze_failures(
  232. days=days,
  233. printer_id=printer_id,
  234. project_id=project_id,
  235. )
  236. @router.get("/compare")
  237. async def compare_archives(
  238. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  239. db: AsyncSession = Depends(get_db),
  240. ):
  241. """Compare multiple archives side by side.
  242. Compares print settings, filament usage, and print times.
  243. Also analyzes correlation between settings and success/failure.
  244. Args:
  245. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  246. """
  247. from backend.app.services.archive_comparison import ArchiveComparisonService
  248. # Parse and validate archive IDs
  249. try:
  250. ids = [int(id.strip()) for id in archive_ids.split(",")]
  251. except ValueError:
  252. raise HTTPException(400, "Invalid archive IDs format")
  253. if len(ids) < 2:
  254. raise HTTPException(400, "At least 2 archives required for comparison")
  255. if len(ids) > 5:
  256. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  257. service = ArchiveComparisonService(db)
  258. try:
  259. return await service.compare_archives(ids)
  260. except ValueError as e:
  261. raise HTTPException(400, str(e))
  262. @router.get("/export")
  263. async def export_archives(
  264. format: str = Query("csv", description="Export format: csv or xlsx"),
  265. fields: str | None = Query(None, description="Comma-separated field names"),
  266. printer_id: int | None = None,
  267. project_id: int | None = None,
  268. status: str | None = None,
  269. date_from: str | None = Query(None, description="Start date (ISO format)"),
  270. date_to: str | None = Query(None, description="End date (ISO format)"),
  271. search: str | None = None,
  272. db: AsyncSession = Depends(get_db),
  273. ):
  274. """Export archives to CSV or Excel format.
  275. Returns a downloadable file with archive data.
  276. """
  277. from datetime import datetime
  278. from fastapi.responses import StreamingResponse
  279. from backend.app.services.export import ExportService
  280. if format not in ("csv", "xlsx"):
  281. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  282. # Parse fields
  283. field_list = None
  284. if fields:
  285. field_list = [f.strip() for f in fields.split(",")]
  286. # Parse dates
  287. date_from_dt = None
  288. date_to_dt = None
  289. if date_from:
  290. try:
  291. date_from_dt = datetime.fromisoformat(date_from)
  292. except ValueError:
  293. raise HTTPException(400, "Invalid date_from format")
  294. if date_to:
  295. try:
  296. date_to_dt = datetime.fromisoformat(date_to)
  297. except ValueError:
  298. raise HTTPException(400, "Invalid date_to format")
  299. service = ExportService(db)
  300. try:
  301. file_bytes, filename, content_type = await service.export_archives(
  302. format=format,
  303. fields=field_list,
  304. printer_id=printer_id,
  305. project_id=project_id,
  306. status=status,
  307. date_from=date_from_dt,
  308. date_to=date_to_dt,
  309. search=search,
  310. )
  311. except ImportError as e:
  312. raise HTTPException(500, str(e))
  313. return StreamingResponse(
  314. io.BytesIO(file_bytes),
  315. media_type=content_type,
  316. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  317. )
  318. @router.get("/stats/export")
  319. async def export_stats(
  320. format: str = Query("csv", description="Export format: csv or xlsx"),
  321. days: int = 30,
  322. printer_id: int | None = None,
  323. project_id: int | None = None,
  324. db: AsyncSession = Depends(get_db),
  325. ):
  326. """Export statistics summary to CSV or Excel format."""
  327. from fastapi.responses import StreamingResponse
  328. from backend.app.services.export import ExportService
  329. if format not in ("csv", "xlsx"):
  330. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  331. service = ExportService(db)
  332. try:
  333. file_bytes, filename, content_type = await service.export_stats(
  334. format=format,
  335. days=days,
  336. printer_id=printer_id,
  337. project_id=project_id,
  338. )
  339. except ImportError as e:
  340. raise HTTPException(500, str(e))
  341. return StreamingResponse(
  342. io.BytesIO(file_bytes),
  343. media_type=content_type,
  344. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  345. )
  346. @router.get("/stats", response_model=ArchiveStats)
  347. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  348. """Get statistics across all archives."""
  349. # Total counts
  350. total_result = await db.execute(select(func.count(PrintArchive.id)))
  351. total_prints = total_result.scalar() or 0
  352. successful_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  353. successful_prints = successful_result.scalar() or 0
  354. failed_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed"))
  355. failed_prints = failed_result.scalar() or 0
  356. # Totals - use actual print time from timestamps (not slicer estimates)
  357. # For archives with both started_at and completed_at, calculate actual duration
  358. # Fall back to print_time_seconds only for archives without timestamps
  359. archives_for_time = await db.execute(
  360. select(PrintArchive.started_at, PrintArchive.completed_at, PrintArchive.print_time_seconds)
  361. )
  362. total_seconds = 0
  363. for started_at, completed_at, print_time_seconds in archives_for_time.all():
  364. if started_at and completed_at:
  365. # Use actual elapsed time
  366. actual_seconds = (completed_at - started_at).total_seconds()
  367. if actual_seconds > 0:
  368. total_seconds += actual_seconds
  369. elif print_time_seconds:
  370. # Fallback to estimate only if no timestamps
  371. total_seconds += print_time_seconds
  372. total_time = total_seconds / 3600 # Convert to hours
  373. filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams)))
  374. total_filament = filament_result.scalar() or 0
  375. cost_result = await db.execute(select(func.sum(PrintArchive.cost)))
  376. total_cost = cost_result.scalar() or 0
  377. # By filament type (split comma-separated values for multi-material prints)
  378. filament_type_result = await db.execute(
  379. select(PrintArchive.filament_type).where(PrintArchive.filament_type.isnot(None))
  380. )
  381. prints_by_filament: dict[str, int] = {}
  382. for (filament_types,) in filament_type_result.all():
  383. # Split by comma and count each type
  384. for ftype in filament_types.split(","):
  385. ftype = ftype.strip()
  386. if ftype:
  387. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  388. # By printer
  389. printer_result = await db.execute(
  390. select(PrintArchive.printer_id, func.count(PrintArchive.id)).group_by(PrintArchive.printer_id)
  391. )
  392. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  393. # Time accuracy statistics
  394. # Get all completed archives with both estimated and actual times
  395. accuracy_result = await db.execute(
  396. select(PrintArchive)
  397. .where(PrintArchive.status == "completed")
  398. .where(PrintArchive.print_time_seconds.isnot(None))
  399. .where(PrintArchive.started_at.isnot(None))
  400. .where(PrintArchive.completed_at.isnot(None))
  401. )
  402. archives_with_times = list(accuracy_result.scalars().all())
  403. average_accuracy = None
  404. accuracy_by_printer: dict[str, float] = {}
  405. if archives_with_times:
  406. accuracies = []
  407. printer_accuracies: dict[str, list[float]] = {}
  408. for archive in archives_with_times:
  409. acc_data = compute_time_accuracy(archive)
  410. if acc_data["time_accuracy"] is not None:
  411. accuracies.append(acc_data["time_accuracy"])
  412. # Group by printer
  413. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  414. if printer_key not in printer_accuracies:
  415. printer_accuracies[printer_key] = []
  416. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  417. if accuracies:
  418. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  419. # Calculate per-printer averages
  420. for printer_key, accs in printer_accuracies.items():
  421. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  422. # Energy totals - check which mode to use
  423. from backend.app.api.routes.settings import get_setting
  424. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  425. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  426. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  427. if energy_tracking_mode == "total":
  428. # Total mode: sum up 'total' counter from all smart plugs (lifetime consumption)
  429. from backend.app.models.smart_plug import SmartPlug
  430. from backend.app.services.tasmota import tasmota_service
  431. plugs_result = await db.execute(select(SmartPlug))
  432. plugs = list(plugs_result.scalars().all())
  433. total_energy_kwh = 0.0
  434. for plug in plugs:
  435. energy = await tasmota_service.get_energy(plug)
  436. if energy and energy.get("total") is not None:
  437. total_energy_kwh += energy["total"]
  438. total_energy_kwh = round(total_energy_kwh, 3)
  439. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 2)
  440. else:
  441. # Print mode: sum up per-print energy from archives
  442. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)))
  443. total_energy_kwh = energy_kwh_result.scalar() or 0
  444. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)))
  445. total_energy_cost = energy_cost_result.scalar() or 0
  446. return ArchiveStats(
  447. total_prints=total_prints,
  448. successful_prints=successful_prints,
  449. failed_prints=failed_prints,
  450. total_print_time_hours=round(total_time, 1),
  451. total_filament_grams=round(total_filament, 1),
  452. total_cost=round(total_cost, 2),
  453. prints_by_filament_type=prints_by_filament,
  454. prints_by_printer=prints_by_printer,
  455. average_time_accuracy=average_accuracy,
  456. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  457. total_energy_kwh=round(total_energy_kwh, 3),
  458. total_energy_cost=round(total_energy_cost, 2),
  459. )
  460. @router.get("/{archive_id}", response_model=ArchiveResponse)
  461. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  462. """Get a specific archive."""
  463. service = ArchiveService(db)
  464. archive = await service.get_archive(archive_id)
  465. if not archive:
  466. raise HTTPException(404, "Archive not found")
  467. # Find duplicates
  468. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  469. duplicates = await service.find_duplicates(
  470. archive_id=archive.id,
  471. content_hash=archive.content_hash,
  472. print_name=archive.print_name,
  473. makerworld_model_id=makerworld_id,
  474. )
  475. return archive_to_response(archive, duplicates)
  476. @router.get("/{archive_id}/similar")
  477. async def find_similar_archives(
  478. archive_id: int,
  479. limit: int = 10,
  480. db: AsyncSession = Depends(get_db),
  481. ):
  482. """Find archives with similar settings for comparison.
  483. Returns archives that match by:
  484. - Same print name (highest priority)
  485. - Same file content hash
  486. - Same filament type
  487. """
  488. from backend.app.services.archive_comparison import ArchiveComparisonService
  489. service = ArchiveComparisonService(db)
  490. try:
  491. return await service.find_similar_archives(archive_id, limit=limit)
  492. except ValueError as e:
  493. raise HTTPException(404, str(e))
  494. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  495. async def update_archive(
  496. archive_id: int,
  497. update_data: ArchiveUpdate,
  498. db: AsyncSession = Depends(get_db),
  499. ):
  500. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  501. from sqlalchemy.orm import selectinload
  502. result = await db.execute(
  503. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  504. )
  505. archive = result.scalar_one_or_none()
  506. if not archive:
  507. raise HTTPException(404, "Archive not found")
  508. for field, value in update_data.model_dump(exclude_unset=True).items():
  509. setattr(archive, field, value)
  510. await db.commit()
  511. # Re-fetch with project relationship loaded after commit
  512. result = await db.execute(
  513. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  514. )
  515. archive = result.scalar_one_or_none()
  516. return archive_to_response(archive)
  517. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  518. async def toggle_favorite(
  519. archive_id: int,
  520. db: AsyncSession = Depends(get_db),
  521. ):
  522. """Toggle favorite status for an archive."""
  523. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  524. archive = result.scalar_one_or_none()
  525. if not archive:
  526. raise HTTPException(404, "Archive not found")
  527. archive.is_favorite = not archive.is_favorite
  528. await db.commit()
  529. await db.refresh(archive)
  530. return archive
  531. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  532. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  533. """Rescan the 3MF file and update metadata."""
  534. from backend.app.api.routes.settings import get_setting
  535. from backend.app.services.archive import ThreeMFParser
  536. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  537. archive = result.scalar_one_or_none()
  538. if not archive:
  539. raise HTTPException(404, "Archive not found")
  540. file_path = settings.base_dir / archive.file_path
  541. if not file_path.exists():
  542. raise HTTPException(404, "Archive file not found")
  543. # Parse the 3MF file
  544. parser = ThreeMFParser(file_path)
  545. metadata = parser.parse()
  546. # Update fields from metadata
  547. if metadata.get("filament_type"):
  548. archive.filament_type = metadata["filament_type"]
  549. if metadata.get("filament_color"):
  550. archive.filament_color = metadata["filament_color"]
  551. if metadata.get("print_time_seconds"):
  552. archive.print_time_seconds = metadata["print_time_seconds"]
  553. if metadata.get("filament_used_grams"):
  554. archive.filament_used_grams = metadata["filament_used_grams"]
  555. if metadata.get("layer_height"):
  556. archive.layer_height = metadata["layer_height"]
  557. if metadata.get("nozzle_diameter"):
  558. archive.nozzle_diameter = metadata["nozzle_diameter"]
  559. if metadata.get("bed_temperature"):
  560. archive.bed_temperature = metadata["bed_temperature"]
  561. if metadata.get("nozzle_temperature"):
  562. archive.nozzle_temperature = metadata["nozzle_temperature"]
  563. if metadata.get("makerworld_url"):
  564. archive.makerworld_url = metadata["makerworld_url"]
  565. if metadata.get("designer"):
  566. archive.designer = metadata["designer"]
  567. # Calculate cost based on filament usage and type
  568. if archive.filament_used_grams and archive.filament_type:
  569. primary_type = archive.filament_type.split(",")[0].strip()
  570. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  571. filament = filament_result.scalar_one_or_none()
  572. if filament:
  573. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  574. else:
  575. # Use default filament cost from settings
  576. default_cost_setting = await get_setting(db, "default_filament_cost")
  577. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  578. archive.cost = round((archive.filament_used_grams / 1000) * default_cost_per_kg, 2)
  579. await db.commit()
  580. await db.refresh(archive)
  581. return archive
  582. @router.post("/recalculate-costs")
  583. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  584. """Recalculate costs for all archives based on filament usage and prices."""
  585. from backend.app.api.routes.settings import get_setting
  586. result = await db.execute(select(PrintArchive))
  587. archives = list(result.scalars().all())
  588. # Load all filaments for lookup
  589. filament_result = await db.execute(select(Filament))
  590. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  591. # Get default filament cost from settings
  592. default_cost_setting = await get_setting(db, "default_filament_cost")
  593. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  594. updated = 0
  595. for archive in archives:
  596. if archive.filament_used_grams and archive.filament_type:
  597. primary_type = archive.filament_type.split(",")[0].strip()
  598. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  599. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  600. if archive.cost != new_cost:
  601. archive.cost = new_cost
  602. updated += 1
  603. await db.commit()
  604. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  605. @router.post("/rescan-all")
  606. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  607. """Rescan all archives and update their metadata."""
  608. from backend.app.services.archive import ThreeMFParser
  609. result = await db.execute(select(PrintArchive))
  610. archives = list(result.scalars().all())
  611. updated = 0
  612. errors = []
  613. for archive in archives:
  614. try:
  615. file_path = settings.base_dir / archive.file_path
  616. if not file_path.exists():
  617. errors.append({"id": archive.id, "error": "File not found"})
  618. continue
  619. parser = ThreeMFParser(file_path)
  620. metadata = parser.parse()
  621. if metadata.get("filament_type"):
  622. archive.filament_type = metadata["filament_type"]
  623. if metadata.get("filament_color"):
  624. archive.filament_color = metadata["filament_color"]
  625. if metadata.get("print_time_seconds"):
  626. archive.print_time_seconds = metadata["print_time_seconds"]
  627. if metadata.get("filament_used_grams"):
  628. archive.filament_used_grams = metadata["filament_used_grams"]
  629. if metadata.get("layer_height"):
  630. archive.layer_height = metadata["layer_height"]
  631. if metadata.get("nozzle_diameter"):
  632. archive.nozzle_diameter = metadata["nozzle_diameter"]
  633. if metadata.get("makerworld_url"):
  634. archive.makerworld_url = metadata["makerworld_url"]
  635. if metadata.get("designer"):
  636. archive.designer = metadata["designer"]
  637. updated += 1
  638. except Exception as e:
  639. errors.append({"id": archive.id, "error": str(e)})
  640. await db.commit()
  641. return {"updated": updated, "errors": errors}
  642. @router.get("/{archive_id}/duplicates")
  643. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  644. """Get duplicates for a specific archive."""
  645. service = ArchiveService(db)
  646. archive = await service.get_archive(archive_id)
  647. if not archive:
  648. raise HTTPException(404, "Archive not found")
  649. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  650. duplicates = await service.find_duplicates(
  651. archive_id=archive.id,
  652. content_hash=archive.content_hash,
  653. print_name=archive.print_name,
  654. makerworld_model_id=makerworld_id,
  655. )
  656. return {"duplicates": duplicates, "count": len(duplicates)}
  657. @router.post("/backfill-hashes")
  658. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  659. """Compute and store content hashes for all archives missing them."""
  660. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  661. archives = list(result.scalars().all())
  662. updated = 0
  663. errors = []
  664. for archive in archives:
  665. try:
  666. file_path = settings.base_dir / archive.file_path
  667. if not file_path.exists():
  668. errors.append({"id": archive.id, "error": "File not found"})
  669. continue
  670. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  671. updated += 1
  672. except Exception as e:
  673. errors.append({"id": archive.id, "error": str(e)})
  674. await db.commit()
  675. return {"updated": updated, "errors": errors}
  676. @router.delete("/{archive_id}")
  677. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  678. """Delete an archive."""
  679. service = ArchiveService(db)
  680. if not await service.delete_archive(archive_id):
  681. raise HTTPException(404, "Archive not found")
  682. return {"status": "deleted"}
  683. @router.get("/{archive_id}/download")
  684. async def download_archive(
  685. archive_id: int,
  686. inline: bool = False,
  687. db: AsyncSession = Depends(get_db),
  688. ):
  689. """Download the 3MF file."""
  690. service = ArchiveService(db)
  691. archive = await service.get_archive(archive_id)
  692. if not archive:
  693. raise HTTPException(404, "Archive not found")
  694. file_path = settings.base_dir / archive.file_path
  695. if not file_path.exists():
  696. raise HTTPException(404, "File not found")
  697. # Use inline disposition to let browser/OS handle file association
  698. content_disposition = "inline" if inline else "attachment"
  699. return FileResponse(
  700. path=file_path,
  701. filename=archive.filename,
  702. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  703. content_disposition_type=content_disposition,
  704. )
  705. @router.get("/{archive_id}/file/{filename}")
  706. async def download_archive_with_filename(
  707. archive_id: int,
  708. filename: str,
  709. db: AsyncSession = Depends(get_db),
  710. ):
  711. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  712. service = ArchiveService(db)
  713. archive = await service.get_archive(archive_id)
  714. if not archive:
  715. raise HTTPException(404, "Archive not found")
  716. file_path = settings.base_dir / archive.file_path
  717. if not file_path.exists():
  718. raise HTTPException(404, "File not found")
  719. return FileResponse(
  720. path=file_path,
  721. filename=archive.filename,
  722. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  723. )
  724. @router.get("/{archive_id}/thumbnail")
  725. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  726. """Get the thumbnail image."""
  727. service = ArchiveService(db)
  728. archive = await service.get_archive(archive_id)
  729. if not archive or not archive.thumbnail_path:
  730. raise HTTPException(404, "Thumbnail not found")
  731. thumb_path = settings.base_dir / archive.thumbnail_path
  732. if not thumb_path.exists():
  733. raise HTTPException(404, "Thumbnail file not found")
  734. # Use file modification time as ETag to bust cache
  735. mtime = int(thumb_path.stat().st_mtime)
  736. return FileResponse(
  737. path=thumb_path,
  738. media_type="image/png",
  739. headers={
  740. "Cache-Control": "no-cache, must-revalidate",
  741. "ETag": f'"{mtime}"',
  742. },
  743. )
  744. @router.get("/{archive_id}/timelapse")
  745. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  746. """Get the timelapse video."""
  747. service = ArchiveService(db)
  748. archive = await service.get_archive(archive_id)
  749. if not archive or not archive.timelapse_path:
  750. raise HTTPException(404, "Timelapse not found")
  751. timelapse_path = settings.base_dir / archive.timelapse_path
  752. if not timelapse_path.exists():
  753. raise HTTPException(404, "Timelapse file not found")
  754. # Use file modification time as ETag to bust cache after processing
  755. mtime = int(timelapse_path.stat().st_mtime)
  756. return FileResponse(
  757. path=timelapse_path,
  758. media_type="video/mp4",
  759. filename=f"{archive.print_name or 'timelapse'}.mp4",
  760. headers={
  761. "Cache-Control": "no-cache, must-revalidate",
  762. "ETag": f'"{mtime}"',
  763. },
  764. )
  765. @router.post("/{archive_id}/timelapse/scan")
  766. async def scan_timelapse(
  767. archive_id: int,
  768. db: AsyncSession = Depends(get_db),
  769. ):
  770. """Scan printer for timelapse matching this archive and attach it."""
  771. from backend.app.models.printer import Printer
  772. from backend.app.services.bambu_ftp import (
  773. download_file_bytes_async,
  774. get_ftp_retry_settings,
  775. list_files_async,
  776. with_ftp_retry,
  777. )
  778. service = ArchiveService(db)
  779. archive = await service.get_archive(archive_id)
  780. if not archive:
  781. raise HTTPException(404, "Archive not found")
  782. if archive.timelapse_path:
  783. return {"status": "exists", "message": "Timelapse already attached"}
  784. if not archive.printer_id:
  785. raise HTTPException(400, "Archive has no associated printer")
  786. # Get printer
  787. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  788. printer = result.scalar_one_or_none()
  789. if not printer:
  790. raise HTTPException(404, "Printer not found")
  791. # Get base name from archive filename (without .3mf extension)
  792. base_name = Path(archive.filename).stem
  793. # Scan timelapse directory on printer
  794. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  795. files = []
  796. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  797. try:
  798. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  799. if files:
  800. break
  801. except Exception:
  802. continue
  803. if not files:
  804. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  805. # Look for matching timelapse
  806. matching_file = None
  807. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  808. # Strategy 1: Match by print name in filename
  809. for f in mp4_files:
  810. fname = f.get("name", "")
  811. if base_name.lower() in fname.lower():
  812. matching_file = f
  813. break
  814. # Strategy 2: Match by timestamp proximity
  815. # Bambu timelapse filename uses the print START time (when recording began)
  816. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  817. import re
  818. from datetime import datetime, timedelta
  819. # Prefer started_at since video filename is the print start time
  820. # Fall back to completed_at or created_at if started_at is not available
  821. archive_start = archive.started_at
  822. archive_end = archive.completed_at or archive.created_at
  823. best_match = None
  824. best_diff = timedelta(hours=24) # Max 24 hour difference
  825. for f in mp4_files:
  826. fname = f.get("name", "")
  827. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  828. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  829. if match:
  830. try:
  831. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  832. # Try multiple timezone offsets since printer timezone can vary
  833. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  834. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  835. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  836. # Check against start time (video filename = print start)
  837. if archive_start:
  838. diff = abs(adjusted_file_time - archive_start)
  839. if diff < best_diff:
  840. best_diff = diff
  841. best_match = f
  842. logger.debug(
  843. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  844. f"diff from start: {diff}"
  845. )
  846. # Also check against end time with a buffer
  847. # (video timestamp should be BEFORE completion time)
  848. if archive_end:
  849. # The video timestamp should be within the print duration before completion
  850. if adjusted_file_time < archive_end:
  851. diff = archive_end - adjusted_file_time
  852. # Reasonable print duration: up to 48 hours
  853. if diff < timedelta(hours=48) and diff < best_diff:
  854. best_diff = diff
  855. best_match = f
  856. logger.debug(
  857. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  858. f"diff: {diff}"
  859. )
  860. except ValueError:
  861. continue
  862. # Accept match within 4 hours (more lenient for timezone issues)
  863. if best_match and best_diff < timedelta(hours=4):
  864. matching_file = best_match
  865. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  866. # Strategy 3: Use file modification time from FTP listing
  867. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  868. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  869. from datetime import datetime, timedelta
  870. archive_start = archive.started_at
  871. archive_end = archive.completed_at or archive.created_at
  872. best_match = None
  873. best_diff = timedelta(hours=24)
  874. for f in mp4_files:
  875. mtime = f.get("mtime")
  876. if mtime:
  877. # Timelapse file should be modified during or shortly after the print
  878. # The mtime should be close to completion time (video finishes when print ends)
  879. if archive_end:
  880. diff = abs(mtime - archive_end)
  881. if diff < best_diff:
  882. best_diff = diff
  883. best_match = f
  884. logger.debug(
  885. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  886. )
  887. if best_match and best_diff < timedelta(hours=2):
  888. matching_file = best_match
  889. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  890. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  891. # This handles cases where printer clock is wrong or timezone issues exist
  892. if not matching_file and len(mp4_files) == 1:
  893. from datetime import datetime, timedelta
  894. archive_completed = archive.completed_at or archive.created_at
  895. if archive_completed:
  896. time_since_completion = datetime.now() - archive_completed
  897. # If archive was completed within the last hour, assume the single timelapse is for it
  898. if time_since_completion < timedelta(hours=1):
  899. matching_file = mp4_files[0]
  900. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  901. # Note: We intentionally don't use a "most recent file" fallback because
  902. # we can't verify if timelapse was actually enabled for this print.
  903. # Instead, return the list of available files for manual selection.
  904. if not matching_file:
  905. # Return available files for manual selection
  906. available_files = [
  907. {
  908. "name": f.get("name"),
  909. "path": f.get("path"),
  910. "size": f.get("size"),
  911. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  912. }
  913. for f in mp4_files
  914. ]
  915. # Sort by mtime descending (most recent first)
  916. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  917. return {
  918. "status": "not_found",
  919. "message": "No matching timelapse found - please select manually",
  920. "available_files": available_files,
  921. }
  922. # Download the timelapse - use the full path from the file listing
  923. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  924. # Get FTP retry settings
  925. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  926. if ftp_retry_enabled:
  927. timelapse_data = await with_ftp_retry(
  928. download_file_bytes_async,
  929. printer.ip_address,
  930. printer.access_code,
  931. remote_path,
  932. socket_timeout=ftp_timeout,
  933. printer_model=printer.model,
  934. max_retries=ftp_retry_count,
  935. retry_delay=ftp_retry_delay,
  936. operation_name=f"Download timelapse {matching_file['name']}",
  937. )
  938. else:
  939. timelapse_data = await download_file_bytes_async(
  940. printer.ip_address,
  941. printer.access_code,
  942. remote_path,
  943. socket_timeout=ftp_timeout,
  944. printer_model=printer.model,
  945. )
  946. if not timelapse_data:
  947. raise HTTPException(500, "Failed to download timelapse")
  948. # Attach timelapse to archive
  949. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  950. if not success:
  951. raise HTTPException(500, "Failed to attach timelapse")
  952. return {
  953. "status": "attached",
  954. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  955. "filename": matching_file["name"],
  956. }
  957. @router.post("/{archive_id}/timelapse/select")
  958. async def select_timelapse(
  959. archive_id: int,
  960. filename: str = Query(..., description="Timelapse filename to attach"),
  961. db: AsyncSession = Depends(get_db),
  962. ):
  963. """Manually select a timelapse from the printer to attach."""
  964. from backend.app.models.printer import Printer
  965. from backend.app.services.bambu_ftp import (
  966. download_file_bytes_async,
  967. get_ftp_retry_settings,
  968. list_files_async,
  969. with_ftp_retry,
  970. )
  971. service = ArchiveService(db)
  972. archive = await service.get_archive(archive_id)
  973. if not archive:
  974. raise HTTPException(404, "Archive not found")
  975. if not archive.printer_id:
  976. raise HTTPException(400, "Archive has no associated printer")
  977. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  978. printer = result.scalar_one_or_none()
  979. if not printer:
  980. raise HTTPException(404, "Printer not found")
  981. # Find the file on the printer
  982. files = []
  983. remote_path = None
  984. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  985. try:
  986. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  987. for f in files:
  988. if f.get("name") == filename:
  989. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  990. break
  991. if remote_path:
  992. break
  993. except Exception:
  994. continue
  995. if not remote_path:
  996. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  997. # Download and attach
  998. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  999. if ftp_retry_enabled:
  1000. timelapse_data = await with_ftp_retry(
  1001. download_file_bytes_async,
  1002. printer.ip_address,
  1003. printer.access_code,
  1004. remote_path,
  1005. socket_timeout=ftp_timeout,
  1006. printer_model=printer.model,
  1007. max_retries=ftp_retry_count,
  1008. retry_delay=ftp_retry_delay,
  1009. operation_name=f"Download timelapse {filename}",
  1010. )
  1011. else:
  1012. timelapse_data = await download_file_bytes_async(
  1013. printer.ip_address,
  1014. printer.access_code,
  1015. remote_path,
  1016. socket_timeout=ftp_timeout,
  1017. printer_model=printer.model,
  1018. )
  1019. if not timelapse_data:
  1020. raise HTTPException(500, "Failed to download timelapse")
  1021. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1022. if not success:
  1023. raise HTTPException(500, "Failed to attach timelapse")
  1024. return {
  1025. "status": "attached",
  1026. "message": f"Timelapse '{filename}' attached successfully",
  1027. "filename": filename,
  1028. }
  1029. @router.post("/{archive_id}/timelapse/upload")
  1030. async def upload_timelapse(
  1031. archive_id: int,
  1032. file: UploadFile = File(...),
  1033. db: AsyncSession = Depends(get_db),
  1034. ):
  1035. """Manually upload a timelapse video to an archive."""
  1036. service = ArchiveService(db)
  1037. archive = await service.get_archive(archive_id)
  1038. if not archive:
  1039. raise HTTPException(404, "Archive not found")
  1040. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1041. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1042. content = await file.read()
  1043. success = await service.attach_timelapse(archive_id, content, file.filename)
  1044. if not success:
  1045. raise HTTPException(500, "Failed to attach timelapse")
  1046. return {"status": "attached", "filename": file.filename}
  1047. @router.get("/{archive_id}/timelapse/info")
  1048. async def get_timelapse_info(archive_id: int, db: AsyncSession = Depends(get_db)):
  1049. """Get timelapse video metadata for editor."""
  1050. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1051. from backend.app.services.timelapse_processor import TimelapseProcessor
  1052. service = ArchiveService(db)
  1053. archive = await service.get_archive(archive_id)
  1054. if not archive or not archive.timelapse_path:
  1055. raise HTTPException(404, "Timelapse not found")
  1056. timelapse_path = settings.base_dir / archive.timelapse_path
  1057. if not timelapse_path.exists():
  1058. raise HTTPException(404, "Timelapse file not found")
  1059. try:
  1060. processor = TimelapseProcessor(timelapse_path)
  1061. info = await processor.get_info()
  1062. return TimelapseInfoResponse(**info)
  1063. except Exception as e:
  1064. logger.error(f"Failed to get timelapse info: {e}")
  1065. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1066. @router.get("/{archive_id}/timelapse/thumbnails")
  1067. async def get_timelapse_thumbnails(
  1068. archive_id: int,
  1069. count: int = Query(10, ge=1, le=30),
  1070. width: int = Query(160, ge=80, le=320),
  1071. db: AsyncSession = Depends(get_db),
  1072. ):
  1073. """Generate timeline thumbnail frames for visual scrubbing."""
  1074. import base64
  1075. from backend.app.schemas.timelapse import ThumbnailResponse
  1076. from backend.app.services.timelapse_processor import TimelapseProcessor
  1077. service = ArchiveService(db)
  1078. archive = await service.get_archive(archive_id)
  1079. if not archive or not archive.timelapse_path:
  1080. raise HTTPException(404, "Timelapse not found")
  1081. timelapse_path = settings.base_dir / archive.timelapse_path
  1082. if not timelapse_path.exists():
  1083. raise HTTPException(404, "Timelapse file not found")
  1084. try:
  1085. processor = TimelapseProcessor(timelapse_path)
  1086. thumbnails = await processor.generate_thumbnails(count, width)
  1087. return ThumbnailResponse(
  1088. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1089. timestamps=[ts for ts, _ in thumbnails],
  1090. )
  1091. except Exception as e:
  1092. logger.error(f"Failed to generate thumbnails: {e}")
  1093. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1094. @router.post("/{archive_id}/timelapse/process")
  1095. async def process_timelapse(
  1096. archive_id: int,
  1097. trim_start: float = Form(0),
  1098. trim_end: float = Form(None),
  1099. speed: float = Form(1.0),
  1100. save_mode: str = Form("new"),
  1101. output_filename: str = Form(None),
  1102. audio: UploadFile = File(None),
  1103. db: AsyncSession = Depends(get_db),
  1104. ):
  1105. """Process timelapse with trim, speed, and optional audio overlay."""
  1106. import shutil
  1107. import tempfile
  1108. from backend.app.schemas.timelapse import ProcessResponse
  1109. from backend.app.services.timelapse_processor import TimelapseProcessor
  1110. # Validate speed
  1111. if not 0.25 <= speed <= 4.0:
  1112. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1113. if save_mode not in ("replace", "new"):
  1114. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1115. service = ArchiveService(db)
  1116. archive = await service.get_archive(archive_id)
  1117. if not archive or not archive.timelapse_path:
  1118. raise HTTPException(404, "Timelapse not found")
  1119. timelapse_path = settings.base_dir / archive.timelapse_path
  1120. if not timelapse_path.exists():
  1121. raise HTTPException(404, "Timelapse file not found")
  1122. archive_dir = timelapse_path.parent
  1123. # Handle audio file
  1124. audio_temp_path = None
  1125. if audio and audio.filename:
  1126. # Validate audio file extension
  1127. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1128. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1129. audio_content = await audio.read()
  1130. suffix = Path(audio.filename).suffix
  1131. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1132. audio_temp_path.write_bytes(audio_content)
  1133. try:
  1134. processor = TimelapseProcessor(timelapse_path)
  1135. # Determine output path
  1136. if save_mode == "replace":
  1137. # Process to temp file first, then replace
  1138. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1139. output_path = temp_output
  1140. else:
  1141. # Save as new file alongside original
  1142. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1143. # Sanitize filename
  1144. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1145. if not filename.endswith(".mp4"):
  1146. filename += ".mp4"
  1147. output_path = archive_dir / filename
  1148. success = await processor.process(
  1149. output_path=output_path,
  1150. trim_start=trim_start,
  1151. trim_end=trim_end,
  1152. speed=speed,
  1153. audio_path=audio_temp_path,
  1154. )
  1155. if not success:
  1156. raise HTTPException(500, "Video processing failed")
  1157. # Handle save mode
  1158. if save_mode == "replace":
  1159. # Replace original file
  1160. shutil.move(str(output_path), str(timelapse_path))
  1161. final_path = archive.timelapse_path
  1162. message = "Timelapse replaced successfully"
  1163. else:
  1164. final_path = str(output_path.relative_to(settings.base_dir))
  1165. message = f"Saved as {output_path.name}"
  1166. return ProcessResponse(
  1167. status="completed",
  1168. output_path=final_path,
  1169. message=message,
  1170. )
  1171. except HTTPException:
  1172. raise
  1173. except Exception as e:
  1174. logger.error(f"Timelapse processing failed: {e}")
  1175. raise HTTPException(500, f"Processing failed: {str(e)}")
  1176. finally:
  1177. # Cleanup temp audio file
  1178. if audio_temp_path and audio_temp_path.exists():
  1179. audio_temp_path.unlink()
  1180. # ============================================
  1181. # Photo Endpoints
  1182. # ============================================
  1183. @router.post("/{archive_id}/photos")
  1184. async def upload_photo(
  1185. archive_id: int,
  1186. file: UploadFile = File(...),
  1187. db: AsyncSession = Depends(get_db),
  1188. ):
  1189. """Upload a photo of the printed result."""
  1190. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1191. archive = result.scalar_one_or_none()
  1192. if not archive:
  1193. raise HTTPException(404, "Archive not found")
  1194. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1195. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1196. # Get archive directory
  1197. file_path = settings.base_dir / archive.file_path
  1198. archive_dir = file_path.parent
  1199. photos_dir = archive_dir / "photos"
  1200. photos_dir.mkdir(exist_ok=True)
  1201. # Generate unique filename
  1202. import uuid
  1203. ext = Path(file.filename).suffix.lower()
  1204. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1205. photo_path = photos_dir / photo_filename
  1206. # Save file
  1207. content = await file.read()
  1208. photo_path.write_bytes(content)
  1209. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1210. photos = list(archive.photos or [])
  1211. photos.append(photo_filename)
  1212. archive.photos = photos
  1213. await db.commit()
  1214. await db.refresh(archive)
  1215. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1216. @router.get("/{archive_id}/photos/{filename}")
  1217. async def get_photo(
  1218. archive_id: int,
  1219. filename: str,
  1220. db: AsyncSession = Depends(get_db),
  1221. ):
  1222. """Get a specific photo."""
  1223. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1224. archive = result.scalar_one_or_none()
  1225. if not archive:
  1226. raise HTTPException(404, "Archive not found")
  1227. file_path = settings.base_dir / archive.file_path
  1228. photo_path = file_path.parent / "photos" / filename
  1229. if not photo_path.exists():
  1230. raise HTTPException(404, "Photo not found")
  1231. # Determine media type
  1232. ext = Path(filename).suffix.lower()
  1233. media_types = {
  1234. ".jpg": "image/jpeg",
  1235. ".jpeg": "image/jpeg",
  1236. ".png": "image/png",
  1237. ".webp": "image/webp",
  1238. }
  1239. media_type = media_types.get(ext, "image/jpeg")
  1240. return FileResponse(path=photo_path, media_type=media_type)
  1241. @router.delete("/{archive_id}/photos/{filename}")
  1242. async def delete_photo(
  1243. archive_id: int,
  1244. filename: str,
  1245. db: AsyncSession = Depends(get_db),
  1246. ):
  1247. """Delete a photo."""
  1248. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1249. archive = result.scalar_one_or_none()
  1250. if not archive:
  1251. raise HTTPException(404, "Archive not found")
  1252. if not archive.photos or filename not in archive.photos:
  1253. raise HTTPException(404, "Photo not found")
  1254. # Delete file
  1255. file_path = settings.base_dir / archive.file_path
  1256. photo_path = file_path.parent / "photos" / filename
  1257. if photo_path.exists():
  1258. photo_path.unlink()
  1259. # Update archive photos list
  1260. photos = [p for p in archive.photos if p != filename]
  1261. archive.photos = photos if photos else None
  1262. await db.commit()
  1263. return {"status": "deleted", "photos": archive.photos}
  1264. # ============================================
  1265. # QR Code Endpoint
  1266. # ============================================
  1267. @router.get("/{archive_id}/qrcode")
  1268. async def get_qrcode(
  1269. archive_id: int,
  1270. request: Request,
  1271. size: int = 200,
  1272. db: AsyncSession = Depends(get_db),
  1273. ):
  1274. """Generate a QR code that links to this archive."""
  1275. try:
  1276. import qrcode
  1277. from PIL import Image as PILImage
  1278. except ImportError:
  1279. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1280. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1281. archive = result.scalar_one_or_none()
  1282. if not archive:
  1283. raise HTTPException(404, "Archive not found")
  1284. # Build URL to archive download
  1285. base_url = str(request.base_url).rstrip("/")
  1286. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1287. # Generate QR code
  1288. qr = qrcode.QRCode(
  1289. version=1,
  1290. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1291. box_size=10,
  1292. border=2,
  1293. )
  1294. qr.add_data(archive_url)
  1295. qr.make(fit=True)
  1296. img = qr.make_image(fill_color="black", back_color="white")
  1297. # Convert to PIL Image for resizing
  1298. pil_img = img.get_image()
  1299. # Resize if needed
  1300. if size != 200:
  1301. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1302. # Convert to bytes
  1303. buffer = io.BytesIO()
  1304. pil_img.save(buffer, format="PNG")
  1305. buffer.seek(0)
  1306. return Response(
  1307. content=buffer.getvalue(),
  1308. media_type="image/png",
  1309. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1310. )
  1311. @router.get("/{archive_id}/capabilities")
  1312. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1313. """Check what viewing capabilities are available for this 3MF file."""
  1314. import json
  1315. import xml.etree.ElementTree as ET
  1316. service = ArchiveService(db)
  1317. archive = await service.get_archive(archive_id)
  1318. if not archive:
  1319. raise HTTPException(404, "Archive not found")
  1320. file_path = settings.base_dir / archive.file_path
  1321. if not file_path.exists():
  1322. raise HTTPException(404, "File not found")
  1323. has_model = False
  1324. has_gcode = False
  1325. has_source = False
  1326. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1327. filament_colors: list[str] = []
  1328. # Check if source 3MF exists - this is where actual mesh data typically lives
  1329. source_path = None
  1330. if archive.source_3mf_path:
  1331. source_path = settings.base_dir / archive.source_3mf_path
  1332. if source_path.exists():
  1333. has_source = True
  1334. # Helper function to check for mesh data and extract colors from a 3MF file
  1335. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1336. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1337. found_mesh = False
  1338. colors: list[str] = []
  1339. volume = {"x": 256, "y": 256, "z": 256}
  1340. try:
  1341. with zipfile.ZipFile(zf_path, "r") as zf:
  1342. names = zf.namelist()
  1343. # Check for 3D model - look for actual mesh data
  1344. for name in names:
  1345. if name.endswith(".model"):
  1346. try:
  1347. content = zf.read(name).decode("utf-8")
  1348. if "<vertex" in content or "<mesh" in content:
  1349. found_mesh = True
  1350. break
  1351. except Exception:
  1352. pass
  1353. # Extract filament colors from project_settings.config
  1354. if "Metadata/project_settings.config" in names:
  1355. try:
  1356. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1357. config_data = json.loads(config_content)
  1358. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1359. printable_area = config_data.get("printable_area", [])
  1360. if printable_area and len(printable_area) >= 3:
  1361. max_x = 0
  1362. max_y = 0
  1363. for coord in printable_area:
  1364. if "x" in coord:
  1365. parts = coord.split("x")
  1366. if len(parts) == 2:
  1367. try:
  1368. x, y = int(parts[0]), int(parts[1])
  1369. max_x = max(max_x, x)
  1370. max_y = max(max_y, y)
  1371. except ValueError:
  1372. pass
  1373. if max_x > 0 and max_y > 0:
  1374. volume["x"] = max_x
  1375. volume["y"] = max_y
  1376. # Parse printable_height
  1377. printable_height = config_data.get("printable_height")
  1378. if printable_height:
  1379. try:
  1380. volume["z"] = int(printable_height)
  1381. except (ValueError, TypeError):
  1382. pass
  1383. # Extract filament colors
  1384. raw_colors = config_data.get("filament_colour", [])
  1385. if raw_colors:
  1386. for color in raw_colors:
  1387. if color and isinstance(color, str):
  1388. colors.append(color)
  1389. except Exception:
  1390. pass
  1391. except zipfile.BadZipFile:
  1392. pass
  1393. return found_mesh, colors, volume
  1394. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1395. if has_source and source_path:
  1396. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1397. if source_has_mesh:
  1398. has_model = True
  1399. if source_colors:
  1400. filament_colors = source_colors
  1401. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1402. build_volume = source_volume
  1403. try:
  1404. with zipfile.ZipFile(file_path, "r") as zf:
  1405. names = zf.namelist()
  1406. # Check for G-code in the sliced file
  1407. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1408. # Check for 3D model in sliced file (fallback if no source)
  1409. if not has_model:
  1410. for name in names:
  1411. if name.endswith(".model"):
  1412. try:
  1413. content = zf.read(name).decode("utf-8")
  1414. if "<vertex" in content or "<mesh" in content:
  1415. has_model = True
  1416. break
  1417. except Exception:
  1418. pass
  1419. # Extract filament colors from slice_info.config (for gcode preview)
  1420. # These are the actual filaments used in the print, indexed by tool/extruder
  1421. slice_colors: list[str] = []
  1422. if "Metadata/slice_info.config" in names:
  1423. try:
  1424. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1425. root = ET.fromstring(slice_content)
  1426. filaments = root.findall(".//filament")
  1427. filament_map: dict[int, str] = {}
  1428. for f in filaments:
  1429. fid = f.get("id")
  1430. fcolor = f.get("color")
  1431. used_g = f.get("used_g", "0")
  1432. try:
  1433. used_amount = float(used_g)
  1434. except (ValueError, TypeError):
  1435. used_amount = 0
  1436. if fid is not None and fcolor:
  1437. try:
  1438. tool_id = int(fid) - 1
  1439. if tool_id >= 0 and used_amount > 0:
  1440. filament_map[tool_id] = fcolor
  1441. except ValueError:
  1442. pass
  1443. if filament_map:
  1444. max_tool = max(filament_map.keys())
  1445. for i in range(max_tool + 1):
  1446. slice_colors.append(filament_map.get(i, "#00AE42"))
  1447. except Exception:
  1448. pass
  1449. # Use slice_info colors if we don't have colors from source yet
  1450. if not filament_colors and slice_colors:
  1451. filament_colors = slice_colors
  1452. # Extract build volume from sliced file if not already set from source
  1453. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1454. if "Metadata/project_settings.config" in names:
  1455. try:
  1456. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1457. config_data = json.loads(config_content)
  1458. printable_area = config_data.get("printable_area", [])
  1459. if printable_area and len(printable_area) >= 3:
  1460. max_x = 0
  1461. max_y = 0
  1462. for coord in printable_area:
  1463. if "x" in coord:
  1464. parts = coord.split("x")
  1465. if len(parts) == 2:
  1466. try:
  1467. x, y = int(parts[0]), int(parts[1])
  1468. max_x = max(max_x, x)
  1469. max_y = max(max_y, y)
  1470. except ValueError:
  1471. pass
  1472. if max_x > 0 and max_y > 0:
  1473. build_volume["x"] = max_x
  1474. build_volume["y"] = max_y
  1475. printable_height = config_data.get("printable_height")
  1476. if printable_height:
  1477. try:
  1478. build_volume["z"] = int(printable_height)
  1479. except (ValueError, TypeError):
  1480. pass
  1481. # Fallback colors from project_settings if still empty
  1482. if not filament_colors:
  1483. raw_colors = config_data.get("filament_colour", [])
  1484. if raw_colors:
  1485. for color in raw_colors:
  1486. if color and isinstance(color, str):
  1487. filament_colors.append(color)
  1488. except Exception:
  1489. pass
  1490. except zipfile.BadZipFile:
  1491. raise HTTPException(400, "Invalid 3MF file")
  1492. return {
  1493. "has_model": has_model,
  1494. "has_gcode": has_gcode,
  1495. "has_source": has_source,
  1496. "build_volume": build_volume,
  1497. "filament_colors": filament_colors,
  1498. }
  1499. @router.get("/{archive_id}/gcode")
  1500. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1501. """Extract and return G-code from the 3MF file."""
  1502. service = ArchiveService(db)
  1503. archive = await service.get_archive(archive_id)
  1504. if not archive:
  1505. raise HTTPException(404, "Archive not found")
  1506. file_path = settings.base_dir / archive.file_path
  1507. if not file_path.exists():
  1508. raise HTTPException(404, "File not found")
  1509. try:
  1510. with zipfile.ZipFile(file_path, "r") as zf:
  1511. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1512. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1513. if not gcode_files:
  1514. raise HTTPException(
  1515. 404,
  1516. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1517. )
  1518. # Get the first plate's G-code (usually plate_1.gcode)
  1519. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1520. return Response(content=gcode_content, media_type="text/plain")
  1521. except zipfile.BadZipFile:
  1522. raise HTTPException(400, "Invalid 3MF file")
  1523. except HTTPException:
  1524. raise
  1525. except Exception as e:
  1526. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1527. @router.get("/{archive_id}/plate-preview")
  1528. async def get_plate_preview(archive_id: int, db: AsyncSession = Depends(get_db)):
  1529. """Get the plate preview image from the 3MF file.
  1530. Returns the slicer-generated plate thumbnail which shows the model
  1531. with correct colors and positioning.
  1532. """
  1533. service = ArchiveService(db)
  1534. archive = await service.get_archive(archive_id)
  1535. if not archive:
  1536. raise HTTPException(404, "Archive not found")
  1537. file_path = settings.base_dir / archive.file_path
  1538. if not file_path.exists():
  1539. raise HTTPException(404, "File not found")
  1540. try:
  1541. with zipfile.ZipFile(file_path, "r") as zf:
  1542. names = zf.namelist()
  1543. # Try to find plate preview images in order of preference
  1544. # First look for the specific plate being printed (check slice_info for plate index)
  1545. plate_num = 1
  1546. if "Metadata/slice_info.config" in names:
  1547. try:
  1548. import xml.etree.ElementTree as ET
  1549. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1550. root = ET.fromstring(slice_content)
  1551. plate_elem = root.find(".//plate/metadata[@key='index']")
  1552. if plate_elem is not None:
  1553. plate_num = int(plate_elem.get("value", "1"))
  1554. except Exception:
  1555. pass
  1556. # Try plate-specific image first, then fall back to plate_1
  1557. preview_paths = [
  1558. f"Metadata/plate_{plate_num}.png",
  1559. "Metadata/plate_1.png",
  1560. "Metadata/thumbnail.png",
  1561. ]
  1562. for preview_path in preview_paths:
  1563. if preview_path in names:
  1564. image_data = zf.read(preview_path)
  1565. return Response(content=image_data, media_type="image/png")
  1566. # If no plate image, try any PNG in Metadata
  1567. for name in names:
  1568. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1569. image_data = zf.read(name)
  1570. return Response(content=image_data, media_type="image/png")
  1571. raise HTTPException(404, "No plate preview found in 3MF file")
  1572. except zipfile.BadZipFile:
  1573. raise HTTPException(400, "Invalid 3MF file")
  1574. except HTTPException:
  1575. raise
  1576. except Exception as e:
  1577. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1578. @router.post("/upload")
  1579. async def upload_archive(
  1580. file: UploadFile = File(...),
  1581. printer_id: int | None = None,
  1582. db: AsyncSession = Depends(get_db),
  1583. ):
  1584. """Manually upload a 3MF file to archive."""
  1585. if not file.filename or not file.filename.endswith(".3mf"):
  1586. raise HTTPException(400, "File must be a .3mf file")
  1587. # Save uploaded file temporarily
  1588. temp_path = settings.archive_dir / "temp" / file.filename
  1589. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1590. try:
  1591. content = await file.read()
  1592. temp_path.write_bytes(content)
  1593. service = ArchiveService(db)
  1594. archive = await service.archive_print(
  1595. printer_id=printer_id,
  1596. source_file=temp_path,
  1597. )
  1598. if not archive:
  1599. raise HTTPException(400, "Failed to archive file")
  1600. return ArchiveResponse.model_validate(archive)
  1601. finally:
  1602. if temp_path.exists():
  1603. temp_path.unlink()
  1604. @router.post("/upload-bulk")
  1605. async def upload_archives_bulk(
  1606. files: list[UploadFile] = File(...),
  1607. printer_id: int | None = None,
  1608. db: AsyncSession = Depends(get_db),
  1609. ):
  1610. """Bulk upload multiple 3MF files to archive."""
  1611. results = []
  1612. errors = []
  1613. for file in files:
  1614. if not file.filename or not file.filename.endswith(".3mf"):
  1615. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1616. continue
  1617. temp_path = settings.archive_dir / "temp" / file.filename
  1618. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1619. try:
  1620. content = await file.read()
  1621. temp_path.write_bytes(content)
  1622. service = ArchiveService(db)
  1623. archive = await service.archive_print(
  1624. printer_id=printer_id,
  1625. source_file=temp_path,
  1626. )
  1627. if archive:
  1628. results.append(
  1629. {
  1630. "filename": file.filename,
  1631. "id": archive.id,
  1632. "status": "success",
  1633. }
  1634. )
  1635. else:
  1636. errors.append({"filename": file.filename, "error": "Failed to process"})
  1637. except Exception as e:
  1638. errors.append({"filename": file.filename, "error": str(e)})
  1639. finally:
  1640. if temp_path.exists():
  1641. temp_path.unlink()
  1642. return {
  1643. "uploaded": len(results),
  1644. "failed": len(errors),
  1645. "results": results,
  1646. "errors": errors,
  1647. }
  1648. @router.get("/{archive_id}/plates")
  1649. async def get_archive_plates(
  1650. archive_id: int,
  1651. db: AsyncSession = Depends(get_db),
  1652. ):
  1653. """Get available plates from a multi-plate 3MF archive.
  1654. Returns a list of plates with their index, name, thumbnail availability,
  1655. and filament requirements. For single-plate exports, returns a single plate.
  1656. """
  1657. import xml.etree.ElementTree as ET
  1658. service = ArchiveService(db)
  1659. archive = await service.get_archive(archive_id)
  1660. if not archive:
  1661. raise HTTPException(404, "Archive not found")
  1662. file_path = settings.base_dir / archive.file_path
  1663. if not file_path.exists():
  1664. raise HTTPException(404, "Archive file not found")
  1665. plates = []
  1666. try:
  1667. with zipfile.ZipFile(file_path, "r") as zf:
  1668. namelist = zf.namelist()
  1669. # Find all plate gcode files to determine available plates
  1670. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1671. if not gcode_files:
  1672. # No sliced plates found
  1673. return {"archive_id": archive_id, "filename": archive.filename, "plates": []}
  1674. # Extract plate indices from gcode filenames
  1675. plate_indices = []
  1676. for gf in gcode_files:
  1677. # "Metadata/plate_5.gcode" -> 5
  1678. try:
  1679. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1680. plate_indices.append(int(plate_str))
  1681. except ValueError:
  1682. pass
  1683. plate_indices.sort()
  1684. # Parse model_settings.config for plate names
  1685. # Plate names are stored with plater_id and plater_name keys
  1686. plate_names = {} # plater_id -> name
  1687. if "Metadata/model_settings.config" in namelist:
  1688. try:
  1689. model_content = zf.read("Metadata/model_settings.config").decode()
  1690. model_root = ET.fromstring(model_content)
  1691. for plate_elem in model_root.findall(".//plate"):
  1692. plater_id = None
  1693. plater_name = None
  1694. for meta in plate_elem.findall("metadata"):
  1695. key = meta.get("key")
  1696. value = meta.get("value")
  1697. if key == "plater_id" and value:
  1698. try:
  1699. plater_id = int(value)
  1700. except ValueError:
  1701. pass
  1702. elif key == "plater_name" and value:
  1703. plater_name = value.strip()
  1704. if plater_id is not None and plater_name:
  1705. plate_names[plater_id] = plater_name
  1706. except Exception:
  1707. pass # model_settings.config parsing is optional
  1708. # Parse slice_info.config for plate metadata
  1709. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  1710. if "Metadata/slice_info.config" in namelist:
  1711. content = zf.read("Metadata/slice_info.config").decode()
  1712. root = ET.fromstring(content)
  1713. for plate_elem in root.findall(".//plate"):
  1714. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1715. # Get plate index from metadata
  1716. plate_index = None
  1717. for meta in plate_elem.findall("metadata"):
  1718. key = meta.get("key")
  1719. value = meta.get("value")
  1720. if key == "index" and value:
  1721. try:
  1722. plate_index = int(value)
  1723. except ValueError:
  1724. pass
  1725. elif key == "prediction" and value:
  1726. try:
  1727. plate_info["prediction"] = int(value)
  1728. except ValueError:
  1729. pass
  1730. elif key == "weight" and value:
  1731. try:
  1732. plate_info["weight"] = float(value)
  1733. except ValueError:
  1734. pass
  1735. # Get filaments used in this plate
  1736. for filament_elem in plate_elem.findall("filament"):
  1737. filament_id = filament_elem.get("id")
  1738. filament_type = filament_elem.get("type", "")
  1739. filament_color = filament_elem.get("color", "")
  1740. used_g = filament_elem.get("used_g", "0")
  1741. used_m = filament_elem.get("used_m", "0")
  1742. try:
  1743. used_grams = float(used_g)
  1744. except (ValueError, TypeError):
  1745. used_grams = 0
  1746. if used_grams > 0 and filament_id:
  1747. plate_info["filaments"].append(
  1748. {
  1749. "slot_id": int(filament_id),
  1750. "type": filament_type,
  1751. "color": filament_color,
  1752. "used_grams": round(used_grams, 1),
  1753. "used_meters": float(used_m) if used_m else 0,
  1754. }
  1755. )
  1756. # Sort filaments by slot ID
  1757. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1758. # Collect all object names on this plate
  1759. for obj_elem in plate_elem.findall("object"):
  1760. obj_name = obj_elem.get("name")
  1761. if obj_name and obj_name not in plate_info["objects"]:
  1762. plate_info["objects"].append(obj_name)
  1763. # Set plate name: prefer custom name from model_settings.config,
  1764. # fall back to first object name if no custom name was set
  1765. if plate_index is not None:
  1766. custom_name = plate_names.get(plate_index)
  1767. if custom_name:
  1768. plate_info["name"] = custom_name
  1769. else:
  1770. # Fall back to first object name as hint
  1771. if plate_info["objects"]:
  1772. plate_info["name"] = plate_info["objects"][0]
  1773. plate_metadata[plate_index] = plate_info
  1774. # Build plate list
  1775. for idx in plate_indices:
  1776. meta = plate_metadata.get(idx, {})
  1777. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1778. plates.append(
  1779. {
  1780. "index": idx,
  1781. "name": meta.get("name"),
  1782. "objects": meta.get("objects", []),
  1783. "has_thumbnail": has_thumbnail,
  1784. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  1785. if has_thumbnail
  1786. else None,
  1787. "print_time_seconds": meta.get("prediction"),
  1788. "filament_used_grams": meta.get("weight"),
  1789. "filaments": meta.get("filaments", []),
  1790. }
  1791. )
  1792. except Exception as e:
  1793. logger.warning(f"Failed to parse plates from archive {archive_id}: {e}")
  1794. return {
  1795. "archive_id": archive_id,
  1796. "filename": archive.filename,
  1797. "plates": plates,
  1798. "is_multi_plate": len(plates) > 1,
  1799. }
  1800. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  1801. async def get_plate_thumbnail(
  1802. archive_id: int,
  1803. plate_index: int,
  1804. db: AsyncSession = Depends(get_db),
  1805. ):
  1806. """Get the thumbnail image for a specific plate."""
  1807. service = ArchiveService(db)
  1808. archive = await service.get_archive(archive_id)
  1809. if not archive:
  1810. raise HTTPException(404, "Archive not found")
  1811. file_path = settings.base_dir / archive.file_path
  1812. if not file_path.exists():
  1813. raise HTTPException(404, "Archive file not found")
  1814. try:
  1815. with zipfile.ZipFile(file_path, "r") as zf:
  1816. thumb_path = f"Metadata/plate_{plate_index}.png"
  1817. if thumb_path in zf.namelist():
  1818. data = zf.read(thumb_path)
  1819. return Response(content=data, media_type="image/png")
  1820. except Exception:
  1821. pass
  1822. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  1823. @router.get("/{archive_id}/filament-requirements")
  1824. async def get_filament_requirements(
  1825. archive_id: int,
  1826. plate_id: int | None = None,
  1827. db: AsyncSession = Depends(get_db),
  1828. ):
  1829. """Get filament requirements from the archived 3MF file.
  1830. Returns the filaments used in this print with their slot IDs, types, colors,
  1831. and usage amounts. This can be compared with current AMS state before reprinting.
  1832. Args:
  1833. archive_id: The archive ID
  1834. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  1835. """
  1836. import xml.etree.ElementTree as ET
  1837. service = ArchiveService(db)
  1838. archive = await service.get_archive(archive_id)
  1839. if not archive:
  1840. raise HTTPException(404, "Archive not found")
  1841. file_path = settings.base_dir / archive.file_path
  1842. if not file_path.exists():
  1843. raise HTTPException(404, "Archive file not found")
  1844. filaments = []
  1845. try:
  1846. with zipfile.ZipFile(file_path, "r") as zf:
  1847. # Parse slice_info.config for filament requirements
  1848. if "Metadata/slice_info.config" in zf.namelist():
  1849. content = zf.read("Metadata/slice_info.config").decode()
  1850. root = ET.fromstring(content)
  1851. # If plate_id is specified, find filaments for that specific plate
  1852. if plate_id is not None:
  1853. # Find the plate element with matching index
  1854. for plate_elem in root.findall(".//plate"):
  1855. plate_index = None
  1856. for meta in plate_elem.findall("metadata"):
  1857. if meta.get("key") == "index":
  1858. try:
  1859. plate_index = int(meta.get("value", "0"))
  1860. except ValueError:
  1861. pass
  1862. break
  1863. if plate_index == plate_id:
  1864. # Extract filaments from this plate element
  1865. for filament_elem in plate_elem.findall("filament"):
  1866. filament_id = filament_elem.get("id")
  1867. filament_type = filament_elem.get("type", "")
  1868. filament_color = filament_elem.get("color", "")
  1869. used_g = filament_elem.get("used_g", "0")
  1870. used_m = filament_elem.get("used_m", "0")
  1871. try:
  1872. used_grams = float(used_g)
  1873. except (ValueError, TypeError):
  1874. used_grams = 0
  1875. if used_grams > 0 and filament_id:
  1876. filaments.append(
  1877. {
  1878. "slot_id": int(filament_id),
  1879. "type": filament_type,
  1880. "color": filament_color,
  1881. "used_grams": round(used_grams, 1),
  1882. "used_meters": float(used_m) if used_m else 0,
  1883. }
  1884. )
  1885. break
  1886. else:
  1887. # No plate_id specified - extract all filaments with used_g > 0
  1888. # This is the legacy behavior for single-plate files
  1889. for filament_elem in root.findall(".//filament"):
  1890. filament_id = filament_elem.get("id")
  1891. filament_type = filament_elem.get("type", "")
  1892. filament_color = filament_elem.get("color", "")
  1893. used_g = filament_elem.get("used_g", "0")
  1894. used_m = filament_elem.get("used_m", "0")
  1895. # Only include filaments that are actually used
  1896. try:
  1897. used_grams = float(used_g)
  1898. except (ValueError, TypeError):
  1899. used_grams = 0
  1900. if used_grams > 0 and filament_id:
  1901. filaments.append(
  1902. {
  1903. "slot_id": int(filament_id),
  1904. "type": filament_type,
  1905. "color": filament_color,
  1906. "used_grams": round(used_grams, 1),
  1907. "used_meters": float(used_m) if used_m else 0,
  1908. }
  1909. )
  1910. # Sort by slot ID
  1911. filaments.sort(key=lambda x: x["slot_id"])
  1912. except Exception as e:
  1913. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  1914. return {
  1915. "archive_id": archive_id,
  1916. "filename": archive.filename,
  1917. "plate_id": plate_id,
  1918. "filaments": filaments,
  1919. }
  1920. @router.post("/{archive_id}/reprint")
  1921. async def reprint_archive(
  1922. archive_id: int,
  1923. printer_id: int,
  1924. body: ReprintRequest | None = None,
  1925. db: AsyncSession = Depends(get_db),
  1926. ):
  1927. """Send an archived 3MF file to a printer and start printing."""
  1928. from backend.app.main import register_expected_print
  1929. from backend.app.models.printer import Printer
  1930. from backend.app.services.bambu_ftp import (
  1931. get_ftp_retry_settings,
  1932. upload_file_async,
  1933. with_ftp_retry,
  1934. )
  1935. from backend.app.services.printer_manager import printer_manager
  1936. # Use defaults if no body provided
  1937. if body is None:
  1938. body = ReprintRequest()
  1939. # Get archive
  1940. service = ArchiveService(db)
  1941. archive = await service.get_archive(archive_id)
  1942. if not archive:
  1943. raise HTTPException(404, "Archive not found")
  1944. # Get printer
  1945. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1946. printer = result.scalar_one_or_none()
  1947. if not printer:
  1948. raise HTTPException(404, "Printer not found")
  1949. # Check printer is connected
  1950. if not printer_manager.is_connected(printer_id):
  1951. raise HTTPException(400, "Printer is not connected")
  1952. # Get the sliced 3MF file path
  1953. file_path = settings.base_dir / archive.file_path
  1954. if not file_path.exists():
  1955. raise HTTPException(404, "Archive file not found")
  1956. # Upload file to printer via FTP
  1957. from backend.app.services.bambu_ftp import delete_file_async
  1958. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1959. # The printer might reject filenames with unusual extensions
  1960. base_name = archive.filename
  1961. if base_name.endswith(".gcode.3mf"):
  1962. base_name = base_name[:-10] # Remove .gcode.3mf
  1963. elif base_name.endswith(".3mf"):
  1964. base_name = base_name[:-4] # Remove .3mf
  1965. remote_filename = f"{base_name}.3mf"
  1966. remote_path = f"/{remote_filename}"
  1967. # Get FTP retry settings
  1968. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1969. # Delete existing file if present (avoids 553 error)
  1970. await delete_file_async(
  1971. printer.ip_address,
  1972. printer.access_code,
  1973. remote_path,
  1974. socket_timeout=ftp_timeout,
  1975. printer_model=printer.model,
  1976. )
  1977. if ftp_retry_enabled:
  1978. uploaded = await with_ftp_retry(
  1979. upload_file_async,
  1980. printer.ip_address,
  1981. printer.access_code,
  1982. file_path,
  1983. remote_path,
  1984. socket_timeout=ftp_timeout,
  1985. printer_model=printer.model,
  1986. max_retries=ftp_retry_count,
  1987. retry_delay=ftp_retry_delay,
  1988. operation_name=f"Upload for reprint to {printer.name}",
  1989. )
  1990. else:
  1991. uploaded = await upload_file_async(
  1992. printer.ip_address,
  1993. printer.access_code,
  1994. file_path,
  1995. remote_path,
  1996. socket_timeout=ftp_timeout,
  1997. printer_model=printer.model,
  1998. )
  1999. if not uploaded:
  2000. raise HTTPException(500, "Failed to upload file to printer")
  2001. # Register this as an expected print so we don't create a duplicate archive
  2002. register_expected_print(printer_id, remote_filename, archive_id)
  2003. # Use plate_id from request if provided, otherwise auto-detect from 3MF file
  2004. if body.plate_id is not None:
  2005. plate_id = body.plate_id
  2006. else:
  2007. # Auto-detect plate ID from 3MF file (legacy behavior for single-plate files)
  2008. plate_id = 1
  2009. try:
  2010. with zipfile.ZipFile(file_path, "r") as zf:
  2011. for name in zf.namelist():
  2012. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  2013. # Extract plate number from "Metadata/plate_X.gcode"
  2014. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  2015. plate_id = int(plate_str)
  2016. break
  2017. except Exception:
  2018. pass # Default to plate 1 if detection fails
  2019. logger.info(
  2020. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  2021. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  2022. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  2023. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  2024. )
  2025. # Start the print with options
  2026. started = printer_manager.start_print(
  2027. printer_id,
  2028. remote_filename,
  2029. plate_id,
  2030. ams_mapping=body.ams_mapping,
  2031. timelapse=body.timelapse,
  2032. bed_levelling=body.bed_levelling,
  2033. flow_cali=body.flow_cali,
  2034. vibration_cali=body.vibration_cali,
  2035. layer_inspect=body.layer_inspect,
  2036. use_ams=body.use_ams,
  2037. )
  2038. if not started:
  2039. raise HTTPException(500, "Failed to start print")
  2040. return {
  2041. "status": "printing",
  2042. "printer_id": printer_id,
  2043. "archive_id": archive_id,
  2044. "filename": archive.filename,
  2045. }
  2046. # =============================================================================
  2047. # Project Page API
  2048. # =============================================================================
  2049. @router.get("/{archive_id}/project-page")
  2050. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  2051. """Get the project page data from the 3MF file."""
  2052. from backend.app.schemas.archive import ProjectPageResponse
  2053. from backend.app.services.archive import ProjectPageParser
  2054. service = ArchiveService(db)
  2055. archive = await service.get_archive(archive_id)
  2056. if not archive:
  2057. raise HTTPException(404, "Archive not found")
  2058. file_path = settings.base_dir / archive.file_path
  2059. if not file_path.exists():
  2060. raise HTTPException(404, "Archive file not found")
  2061. parser = ProjectPageParser(file_path)
  2062. data = parser.parse(archive_id)
  2063. return ProjectPageResponse(**data)
  2064. @router.patch("/{archive_id}/project-page")
  2065. async def update_project_page(
  2066. archive_id: int,
  2067. update_data: dict,
  2068. db: AsyncSession = Depends(get_db),
  2069. ):
  2070. """Update project page metadata in the 3MF file."""
  2071. from backend.app.services.archive import ProjectPageParser
  2072. service = ArchiveService(db)
  2073. archive = await service.get_archive(archive_id)
  2074. if not archive:
  2075. raise HTTPException(404, "Archive not found")
  2076. file_path = settings.base_dir / archive.file_path
  2077. if not file_path.exists():
  2078. raise HTTPException(404, "Archive file not found")
  2079. parser = ProjectPageParser(file_path)
  2080. success = parser.update_metadata(update_data)
  2081. if not success:
  2082. raise HTTPException(500, "Failed to update project page")
  2083. # Return updated data
  2084. data = parser.parse(archive_id)
  2085. return data
  2086. @router.get("/{archive_id}/project-image/{image_path:path}")
  2087. async def get_project_image(
  2088. archive_id: int,
  2089. image_path: str,
  2090. db: AsyncSession = Depends(get_db),
  2091. ):
  2092. """Get an image from the 3MF project page."""
  2093. from backend.app.services.archive import ProjectPageParser
  2094. service = ArchiveService(db)
  2095. archive = await service.get_archive(archive_id)
  2096. if not archive:
  2097. raise HTTPException(404, "Archive not found")
  2098. file_path = settings.base_dir / archive.file_path
  2099. if not file_path.exists():
  2100. raise HTTPException(404, "Archive file not found")
  2101. parser = ProjectPageParser(file_path)
  2102. result = parser.get_image(image_path)
  2103. if not result:
  2104. raise HTTPException(404, "Image not found in 3MF file")
  2105. image_data, content_type = result
  2106. return Response(
  2107. content=image_data,
  2108. media_type=content_type,
  2109. headers={"Cache-Control": "max-age=3600"},
  2110. )
  2111. # =============================================================================
  2112. # Source 3MF API (Original Project Files)
  2113. # =============================================================================
  2114. @router.post("/{archive_id}/source")
  2115. async def upload_source_3mf(
  2116. archive_id: int,
  2117. file: UploadFile = File(...),
  2118. db: AsyncSession = Depends(get_db),
  2119. ):
  2120. """Upload the original source 3MF project file for an archive."""
  2121. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2122. archive = result.scalar_one_or_none()
  2123. if not archive:
  2124. raise HTTPException(404, "Archive not found")
  2125. if not file.filename or not file.filename.endswith(".3mf"):
  2126. raise HTTPException(400, "File must be a .3mf file")
  2127. # Get archive directory and create source subdirectory
  2128. file_path = settings.base_dir / archive.file_path
  2129. archive_dir = file_path.parent
  2130. source_dir = archive_dir / "source"
  2131. source_dir.mkdir(exist_ok=True)
  2132. # Delete old source file if exists
  2133. if archive.source_3mf_path:
  2134. old_source_path = settings.base_dir / archive.source_3mf_path
  2135. if old_source_path.exists():
  2136. old_source_path.unlink()
  2137. # Save the source 3MF file - preserve original filename
  2138. source_filename = file.filename
  2139. source_path = source_dir / source_filename
  2140. content = await file.read()
  2141. source_path.write_bytes(content)
  2142. # Update archive with source path (relative to base_dir)
  2143. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2144. await db.commit()
  2145. await db.refresh(archive)
  2146. return {
  2147. "status": "uploaded",
  2148. "source_3mf_path": archive.source_3mf_path,
  2149. "filename": source_filename,
  2150. }
  2151. @router.get("/{archive_id}/source")
  2152. async def download_source_3mf(
  2153. archive_id: int,
  2154. db: AsyncSession = Depends(get_db),
  2155. ):
  2156. """Download the source 3MF project file."""
  2157. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2158. archive = result.scalar_one_or_none()
  2159. if not archive:
  2160. raise HTTPException(404, "Archive not found")
  2161. if not archive.source_3mf_path:
  2162. raise HTTPException(404, "No source 3MF attached to this archive")
  2163. source_path = settings.base_dir / archive.source_3mf_path
  2164. if not source_path.exists():
  2165. raise HTTPException(404, "Source 3MF file not found on disk")
  2166. # Use the actual filename from the path
  2167. filename = source_path.name
  2168. return FileResponse(
  2169. path=source_path,
  2170. filename=filename,
  2171. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2172. )
  2173. @router.get("/{archive_id}/source/{filename}")
  2174. async def download_source_3mf_for_slicer(
  2175. archive_id: int,
  2176. filename: str,
  2177. db: AsyncSession = Depends(get_db),
  2178. ):
  2179. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  2180. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2181. archive = result.scalar_one_or_none()
  2182. if not archive:
  2183. raise HTTPException(404, "Archive not found")
  2184. if not archive.source_3mf_path:
  2185. raise HTTPException(404, "No source 3MF attached to this archive")
  2186. source_path = settings.base_dir / archive.source_3mf_path
  2187. if not source_path.exists():
  2188. raise HTTPException(404, "Source 3MF file not found on disk")
  2189. return FileResponse(
  2190. path=source_path,
  2191. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  2192. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2193. )
  2194. @router.post("/upload-source")
  2195. async def upload_source_3mf_by_name(
  2196. file: UploadFile = File(...),
  2197. print_name: str = Query(None, description="Match archive by print name"),
  2198. db: AsyncSession = Depends(get_db),
  2199. ):
  2200. """Upload source 3MF and match to archive by print name.
  2201. This endpoint is designed for slicer post-processing scripts.
  2202. It finds the most recent archive matching the print name and attaches the source.
  2203. """
  2204. if not file.filename or not file.filename.endswith(".3mf"):
  2205. raise HTTPException(400, "File must be a .3mf file")
  2206. # Derive print name from filename if not provided
  2207. if not print_name:
  2208. # Remove .3mf extension and common suffixes
  2209. print_name = file.filename.rsplit(".3mf", 1)[0]
  2210. # Remove _source suffix if present
  2211. if print_name.endswith("_source"):
  2212. print_name = print_name[:-7]
  2213. # Find matching archive - try exact match first, then fuzzy
  2214. result = await db.execute(
  2215. select(PrintArchive)
  2216. .where(PrintArchive.print_name == print_name)
  2217. .order_by(PrintArchive.created_at.desc())
  2218. .limit(1)
  2219. )
  2220. archive = result.scalar_one_or_none()
  2221. if not archive:
  2222. # Try matching filename without .gcode.3mf
  2223. result = await db.execute(
  2224. select(PrintArchive)
  2225. .where(PrintArchive.filename.like(f"{print_name}%"))
  2226. .order_by(PrintArchive.created_at.desc())
  2227. .limit(1)
  2228. )
  2229. archive = result.scalar_one_or_none()
  2230. if not archive:
  2231. # Try case-insensitive partial match on print_name
  2232. result = await db.execute(
  2233. select(PrintArchive)
  2234. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  2235. .order_by(PrintArchive.created_at.desc())
  2236. .limit(1)
  2237. )
  2238. archive = result.scalar_one_or_none()
  2239. if not archive:
  2240. raise HTTPException(404, f"No archive found matching '{print_name}'")
  2241. # Get archive directory and create source subdirectory
  2242. file_path = settings.base_dir / archive.file_path
  2243. archive_dir = file_path.parent
  2244. source_dir = archive_dir / "source"
  2245. source_dir.mkdir(exist_ok=True)
  2246. # Delete old source file if exists
  2247. if archive.source_3mf_path:
  2248. old_source_path = settings.base_dir / archive.source_3mf_path
  2249. if old_source_path.exists():
  2250. old_source_path.unlink()
  2251. # Save the source 3MF file - preserve original filename
  2252. source_filename = file.filename
  2253. source_path = source_dir / source_filename
  2254. content = await file.read()
  2255. source_path.write_bytes(content)
  2256. # Update archive with source path
  2257. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2258. await db.commit()
  2259. await db.refresh(archive)
  2260. return {
  2261. "status": "uploaded",
  2262. "archive_id": archive.id,
  2263. "archive_name": archive.print_name or archive.filename,
  2264. "source_3mf_path": archive.source_3mf_path,
  2265. "filename": source_filename,
  2266. }
  2267. @router.delete("/{archive_id}/source")
  2268. async def delete_source_3mf(
  2269. archive_id: int,
  2270. db: AsyncSession = Depends(get_db),
  2271. ):
  2272. """Delete the source 3MF project file from an archive."""
  2273. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2274. archive = result.scalar_one_or_none()
  2275. if not archive:
  2276. raise HTTPException(404, "Archive not found")
  2277. if not archive.source_3mf_path:
  2278. raise HTTPException(404, "No source 3MF attached to this archive")
  2279. # Delete the file
  2280. source_path = settings.base_dir / archive.source_3mf_path
  2281. if source_path.exists():
  2282. source_path.unlink()
  2283. # Clear the path in database
  2284. archive.source_3mf_path = None
  2285. await db.commit()
  2286. return {"status": "deleted"}
  2287. # =============================================================================
  2288. # F3D API (Fusion 360 Design Files)
  2289. # =============================================================================
  2290. @router.post("/{archive_id}/f3d")
  2291. async def upload_f3d(
  2292. archive_id: int,
  2293. file: UploadFile = File(...),
  2294. db: AsyncSession = Depends(get_db),
  2295. ):
  2296. """Upload a Fusion 360 design file for an archive."""
  2297. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2298. archive = result.scalar_one_or_none()
  2299. if not archive:
  2300. raise HTTPException(404, "Archive not found")
  2301. if not file.filename or not file.filename.endswith(".f3d"):
  2302. raise HTTPException(400, "File must be a .f3d file")
  2303. # Get archive directory and create f3d subdirectory
  2304. file_path = settings.base_dir / archive.file_path
  2305. archive_dir = file_path.parent
  2306. f3d_dir = archive_dir / "f3d"
  2307. f3d_dir.mkdir(exist_ok=True)
  2308. # Delete old F3D file if exists
  2309. if archive.f3d_path:
  2310. old_f3d_path = settings.base_dir / archive.f3d_path
  2311. if old_f3d_path.exists():
  2312. old_f3d_path.unlink()
  2313. # Save the F3D file - preserve original filename
  2314. f3d_filename = file.filename
  2315. f3d_path = f3d_dir / f3d_filename
  2316. content = await file.read()
  2317. f3d_path.write_bytes(content)
  2318. # Update archive with F3D path (relative to base_dir)
  2319. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  2320. await db.commit()
  2321. await db.refresh(archive)
  2322. return {
  2323. "status": "uploaded",
  2324. "f3d_path": archive.f3d_path,
  2325. "filename": f3d_filename,
  2326. }
  2327. @router.get("/{archive_id}/f3d")
  2328. async def download_f3d(
  2329. archive_id: int,
  2330. db: AsyncSession = Depends(get_db),
  2331. ):
  2332. """Download the Fusion 360 design file."""
  2333. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2334. archive = result.scalar_one_or_none()
  2335. if not archive:
  2336. raise HTTPException(404, "Archive not found")
  2337. if not archive.f3d_path:
  2338. raise HTTPException(404, "No F3D file attached to this archive")
  2339. f3d_path = settings.base_dir / archive.f3d_path
  2340. if not f3d_path.exists():
  2341. raise HTTPException(404, "F3D file not found on disk")
  2342. # Use the actual filename from the path
  2343. filename = f3d_path.name
  2344. return FileResponse(
  2345. path=f3d_path,
  2346. filename=filename,
  2347. media_type="application/octet-stream",
  2348. )
  2349. @router.delete("/{archive_id}/f3d")
  2350. async def delete_f3d(
  2351. archive_id: int,
  2352. db: AsyncSession = Depends(get_db),
  2353. ):
  2354. """Delete the Fusion 360 design file from an archive."""
  2355. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2356. archive = result.scalar_one_or_none()
  2357. if not archive:
  2358. raise HTTPException(404, "Archive not found")
  2359. if not archive.f3d_path:
  2360. raise HTTPException(404, "No F3D file attached to this archive")
  2361. # Delete the file
  2362. f3d_path = settings.base_dir / archive.f3d_path
  2363. if f3d_path.exists():
  2364. f3d_path.unlink()
  2365. # Clear the path in database
  2366. archive.f3d_path = None
  2367. await db.commit()
  2368. return {"status": "deleted"}