archives.py 109 KB

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