archives.py 112 KB

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