archives.py 108 KB

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