archives.py 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062
  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. logger.exception(f"Failed to rescan archive {archive.id}: {e}")
  753. errors.append({"id": archive.id, "error": "Failed to parse 3MF file"})
  754. await db.commit()
  755. return {"updated": updated, "errors": errors}
  756. @router.get("/{archive_id}/duplicates")
  757. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  758. """Get duplicates for a specific archive."""
  759. service = ArchiveService(db)
  760. archive = await service.get_archive(archive_id)
  761. if not archive:
  762. raise HTTPException(404, "Archive not found")
  763. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  764. duplicates = await service.find_duplicates(
  765. archive_id=archive.id,
  766. content_hash=archive.content_hash,
  767. print_name=archive.print_name,
  768. makerworld_model_id=makerworld_id,
  769. )
  770. return {"duplicates": duplicates, "count": len(duplicates)}
  771. @router.post("/backfill-hashes")
  772. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  773. """Compute and store content hashes for all archives missing them."""
  774. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  775. archives = list(result.scalars().all())
  776. updated = 0
  777. errors = []
  778. for archive in archives:
  779. try:
  780. file_path = settings.base_dir / archive.file_path
  781. if not file_path.exists():
  782. errors.append({"id": archive.id, "error": "File not found"})
  783. continue
  784. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  785. updated += 1
  786. except Exception as e:
  787. logger.exception(f"Failed to compute hash for archive {archive.id}: {e}")
  788. errors.append({"id": archive.id, "error": "Failed to compute hash"})
  789. await db.commit()
  790. return {"updated": updated, "errors": errors}
  791. @router.delete("/{archive_id}")
  792. async def delete_archive(
  793. archive_id: int,
  794. db: AsyncSession = Depends(get_db),
  795. auth_result: tuple[User | None, bool] = Depends(
  796. require_ownership_permission(
  797. Permission.ARCHIVES_DELETE_ALL,
  798. Permission.ARCHIVES_DELETE_OWN,
  799. )
  800. ),
  801. ):
  802. """Delete an archive."""
  803. user, can_modify_all = auth_result
  804. # Get archive first to check ownership
  805. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  806. archive = result.scalar_one_or_none()
  807. if not archive:
  808. raise HTTPException(404, "Archive not found")
  809. # Ownership check
  810. if not can_modify_all:
  811. if archive.created_by_id != user.id:
  812. raise HTTPException(403, "You can only delete your own archives")
  813. service = ArchiveService(db)
  814. if not await service.delete_archive(archive_id):
  815. raise HTTPException(404, "Archive not found")
  816. return {"status": "deleted"}
  817. @router.get("/{archive_id}/download")
  818. async def download_archive(
  819. archive_id: int,
  820. inline: bool = False,
  821. db: AsyncSession = Depends(get_db),
  822. ):
  823. """Download the 3MF file."""
  824. service = ArchiveService(db)
  825. archive = await service.get_archive(archive_id)
  826. if not archive:
  827. raise HTTPException(404, "Archive not found")
  828. file_path = settings.base_dir / archive.file_path
  829. if not file_path.exists():
  830. raise HTTPException(404, "File not found")
  831. # Use inline disposition to let browser/OS handle file association
  832. content_disposition = "inline" if inline else "attachment"
  833. return FileResponse(
  834. path=file_path,
  835. filename=archive.filename,
  836. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  837. content_disposition_type=content_disposition,
  838. )
  839. @router.get("/{archive_id}/file/{filename}")
  840. async def download_archive_with_filename(
  841. archive_id: int,
  842. filename: str,
  843. db: AsyncSession = Depends(get_db),
  844. ):
  845. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  846. service = ArchiveService(db)
  847. archive = await service.get_archive(archive_id)
  848. if not archive:
  849. raise HTTPException(404, "Archive not found")
  850. file_path = settings.base_dir / archive.file_path
  851. if not file_path.exists():
  852. raise HTTPException(404, "File not found")
  853. return FileResponse(
  854. path=file_path,
  855. filename=archive.filename,
  856. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  857. )
  858. @router.get("/{archive_id}/thumbnail")
  859. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  860. """Get the thumbnail image."""
  861. service = ArchiveService(db)
  862. archive = await service.get_archive(archive_id)
  863. if not archive or not archive.thumbnail_path:
  864. raise HTTPException(404, "Thumbnail not found")
  865. thumb_path = settings.base_dir / archive.thumbnail_path
  866. if not thumb_path.exists():
  867. raise HTTPException(404, "Thumbnail file not found")
  868. # Use file modification time as ETag to bust cache
  869. mtime = int(thumb_path.stat().st_mtime)
  870. return FileResponse(
  871. path=thumb_path,
  872. media_type="image/png",
  873. headers={
  874. "Cache-Control": "no-cache, must-revalidate",
  875. "ETag": f'"{mtime}"',
  876. },
  877. )
  878. @router.get("/{archive_id}/timelapse")
  879. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  880. """Get the timelapse video."""
  881. service = ArchiveService(db)
  882. archive = await service.get_archive(archive_id)
  883. if not archive or not archive.timelapse_path:
  884. raise HTTPException(404, "Timelapse not found")
  885. timelapse_path = settings.base_dir / archive.timelapse_path
  886. if not timelapse_path.exists():
  887. raise HTTPException(404, "Timelapse file not found")
  888. # Use file modification time as ETag to bust cache after processing
  889. mtime = int(timelapse_path.stat().st_mtime)
  890. return FileResponse(
  891. path=timelapse_path,
  892. media_type="video/mp4",
  893. filename=f"{archive.print_name or 'timelapse'}.mp4",
  894. headers={
  895. "Cache-Control": "no-cache, must-revalidate",
  896. "ETag": f'"{mtime}"',
  897. },
  898. )
  899. @router.post("/{archive_id}/timelapse/scan")
  900. async def scan_timelapse(
  901. archive_id: int,
  902. db: AsyncSession = Depends(get_db),
  903. ):
  904. """Scan printer for timelapse matching this archive and attach it."""
  905. from backend.app.models.printer import Printer
  906. from backend.app.services.bambu_ftp import (
  907. download_file_bytes_async,
  908. get_ftp_retry_settings,
  909. list_files_async,
  910. with_ftp_retry,
  911. )
  912. service = ArchiveService(db)
  913. archive = await service.get_archive(archive_id)
  914. if not archive:
  915. raise HTTPException(404, "Archive not found")
  916. if archive.timelapse_path:
  917. return {"status": "exists", "message": "Timelapse already attached"}
  918. if not archive.printer_id:
  919. raise HTTPException(400, "Archive has no associated printer")
  920. # Get printer
  921. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  922. printer = result.scalar_one_or_none()
  923. if not printer:
  924. raise HTTPException(404, "Printer not found")
  925. # Get base name from archive filename (without .3mf extension)
  926. base_name = Path(archive.filename).stem
  927. # Scan timelapse directory on printer
  928. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  929. files = []
  930. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  931. try:
  932. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  933. if files:
  934. break
  935. except Exception:
  936. continue
  937. if not files:
  938. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  939. # Look for matching timelapse
  940. matching_file = None
  941. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  942. # Strategy 1: Match by print name in filename
  943. for f in mp4_files:
  944. fname = f.get("name", "")
  945. if base_name.lower() in fname.lower():
  946. matching_file = f
  947. break
  948. # Strategy 2: Match by timestamp proximity
  949. # Bambu timelapse filename uses the print START time (when recording began)
  950. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  951. import re
  952. from datetime import datetime, timedelta
  953. # Prefer started_at since video filename is the print start time
  954. # Fall back to completed_at or created_at if started_at is not available
  955. archive_start = archive.started_at
  956. archive_end = archive.completed_at or archive.created_at
  957. best_match = None
  958. best_diff = timedelta(hours=24) # Max 24 hour difference
  959. for f in mp4_files:
  960. fname = f.get("name", "")
  961. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  962. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  963. if match:
  964. try:
  965. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  966. # Try multiple timezone offsets since printer timezone can vary
  967. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  968. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  969. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  970. # Check against start time (video filename = print start)
  971. if archive_start:
  972. diff = abs(adjusted_file_time - archive_start)
  973. if diff < best_diff:
  974. best_diff = diff
  975. best_match = f
  976. logger.debug(
  977. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  978. f"diff from start: {diff}"
  979. )
  980. # Also check against end time with a buffer
  981. # (video timestamp should be BEFORE completion time)
  982. if archive_end:
  983. # The video timestamp should be within the print duration before completion
  984. if adjusted_file_time < archive_end:
  985. diff = archive_end - adjusted_file_time
  986. # Reasonable print duration: up to 48 hours
  987. if diff < timedelta(hours=48) and diff < best_diff:
  988. best_diff = diff
  989. best_match = f
  990. logger.debug(
  991. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  992. f"diff: {diff}"
  993. )
  994. except ValueError:
  995. continue
  996. # Accept match within 4 hours (more lenient for timezone issues)
  997. if best_match and best_diff < timedelta(hours=4):
  998. matching_file = best_match
  999. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  1000. # Strategy 3: Use file modification time from FTP listing
  1001. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  1002. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  1003. from datetime import datetime, timedelta
  1004. archive_start = archive.started_at
  1005. archive_end = archive.completed_at or archive.created_at
  1006. best_match = None
  1007. best_diff = timedelta(hours=24)
  1008. for f in mp4_files:
  1009. mtime = f.get("mtime")
  1010. if mtime:
  1011. # Timelapse file should be modified during or shortly after the print
  1012. # The mtime should be close to completion time (video finishes when print ends)
  1013. if archive_end:
  1014. diff = abs(mtime - archive_end)
  1015. if diff < best_diff:
  1016. best_diff = diff
  1017. best_match = f
  1018. logger.debug(
  1019. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  1020. )
  1021. if best_match and best_diff < timedelta(hours=2):
  1022. matching_file = best_match
  1023. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  1024. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  1025. # This handles cases where printer clock is wrong or timezone issues exist
  1026. if not matching_file and len(mp4_files) == 1:
  1027. from datetime import datetime, timedelta
  1028. archive_completed = archive.completed_at or archive.created_at
  1029. if archive_completed:
  1030. time_since_completion = datetime.now() - archive_completed
  1031. # If archive was completed within the last hour, assume the single timelapse is for it
  1032. if time_since_completion < timedelta(hours=1):
  1033. matching_file = mp4_files[0]
  1034. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  1035. # Note: We intentionally don't use a "most recent file" fallback because
  1036. # we can't verify if timelapse was actually enabled for this print.
  1037. # Instead, return the list of available files for manual selection.
  1038. if not matching_file:
  1039. # Return available files for manual selection
  1040. available_files = [
  1041. {
  1042. "name": f.get("name"),
  1043. "path": f.get("path"),
  1044. "size": f.get("size"),
  1045. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  1046. }
  1047. for f in mp4_files
  1048. ]
  1049. # Sort by mtime descending (most recent first)
  1050. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  1051. return {
  1052. "status": "not_found",
  1053. "message": "No matching timelapse found - please select manually",
  1054. "available_files": available_files,
  1055. }
  1056. # Download the timelapse - use the full path from the file listing
  1057. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  1058. # Get FTP retry settings
  1059. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1060. if ftp_retry_enabled:
  1061. timelapse_data = await with_ftp_retry(
  1062. download_file_bytes_async,
  1063. printer.ip_address,
  1064. printer.access_code,
  1065. remote_path,
  1066. socket_timeout=ftp_timeout,
  1067. printer_model=printer.model,
  1068. max_retries=ftp_retry_count,
  1069. retry_delay=ftp_retry_delay,
  1070. operation_name=f"Download timelapse {matching_file['name']}",
  1071. )
  1072. else:
  1073. timelapse_data = await download_file_bytes_async(
  1074. printer.ip_address,
  1075. printer.access_code,
  1076. remote_path,
  1077. socket_timeout=ftp_timeout,
  1078. printer_model=printer.model,
  1079. )
  1080. if not timelapse_data:
  1081. raise HTTPException(500, "Failed to download timelapse")
  1082. # Attach timelapse to archive
  1083. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  1084. if not success:
  1085. raise HTTPException(500, "Failed to attach timelapse")
  1086. return {
  1087. "status": "attached",
  1088. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  1089. "filename": matching_file["name"],
  1090. }
  1091. @router.post("/{archive_id}/timelapse/select")
  1092. async def select_timelapse(
  1093. archive_id: int,
  1094. filename: str = Query(..., description="Timelapse filename to attach"),
  1095. db: AsyncSession = Depends(get_db),
  1096. ):
  1097. """Manually select a timelapse from the printer to attach."""
  1098. from backend.app.models.printer import Printer
  1099. from backend.app.services.bambu_ftp import (
  1100. download_file_bytes_async,
  1101. get_ftp_retry_settings,
  1102. list_files_async,
  1103. with_ftp_retry,
  1104. )
  1105. service = ArchiveService(db)
  1106. archive = await service.get_archive(archive_id)
  1107. if not archive:
  1108. raise HTTPException(404, "Archive not found")
  1109. if not archive.printer_id:
  1110. raise HTTPException(400, "Archive has no associated printer")
  1111. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1112. printer = result.scalar_one_or_none()
  1113. if not printer:
  1114. raise HTTPException(404, "Printer not found")
  1115. # Find the file on the printer
  1116. files = []
  1117. remote_path = None
  1118. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  1119. try:
  1120. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  1121. for f in files:
  1122. if f.get("name") == filename:
  1123. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  1124. break
  1125. if remote_path:
  1126. break
  1127. except Exception:
  1128. continue
  1129. if not remote_path:
  1130. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  1131. # Download and attach
  1132. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1133. if ftp_retry_enabled:
  1134. timelapse_data = await with_ftp_retry(
  1135. download_file_bytes_async,
  1136. printer.ip_address,
  1137. printer.access_code,
  1138. remote_path,
  1139. socket_timeout=ftp_timeout,
  1140. printer_model=printer.model,
  1141. max_retries=ftp_retry_count,
  1142. retry_delay=ftp_retry_delay,
  1143. operation_name=f"Download timelapse {filename}",
  1144. )
  1145. else:
  1146. timelapse_data = await download_file_bytes_async(
  1147. printer.ip_address,
  1148. printer.access_code,
  1149. remote_path,
  1150. socket_timeout=ftp_timeout,
  1151. printer_model=printer.model,
  1152. )
  1153. if not timelapse_data:
  1154. raise HTTPException(500, "Failed to download timelapse")
  1155. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1156. if not success:
  1157. raise HTTPException(500, "Failed to attach timelapse")
  1158. return {
  1159. "status": "attached",
  1160. "message": f"Timelapse '{filename}' attached successfully",
  1161. "filename": filename,
  1162. }
  1163. @router.post("/{archive_id}/timelapse/upload")
  1164. async def upload_timelapse(
  1165. archive_id: int,
  1166. file: UploadFile = File(...),
  1167. db: AsyncSession = Depends(get_db),
  1168. ):
  1169. """Manually upload a timelapse video to an archive."""
  1170. service = ArchiveService(db)
  1171. archive = await service.get_archive(archive_id)
  1172. if not archive:
  1173. raise HTTPException(404, "Archive not found")
  1174. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1175. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1176. content = await file.read()
  1177. success = await service.attach_timelapse(archive_id, content, file.filename)
  1178. if not success:
  1179. raise HTTPException(500, "Failed to attach timelapse")
  1180. return {"status": "attached", "filename": file.filename}
  1181. @router.get("/{archive_id}/timelapse/info")
  1182. async def get_timelapse_info(archive_id: int, db: AsyncSession = Depends(get_db)):
  1183. """Get timelapse video metadata for editor."""
  1184. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1185. from backend.app.services.timelapse_processor import TimelapseProcessor
  1186. service = ArchiveService(db)
  1187. archive = await service.get_archive(archive_id)
  1188. if not archive or not archive.timelapse_path:
  1189. raise HTTPException(404, "Timelapse not found")
  1190. timelapse_path = settings.base_dir / archive.timelapse_path
  1191. if not timelapse_path.exists():
  1192. raise HTTPException(404, "Timelapse file not found")
  1193. try:
  1194. processor = TimelapseProcessor(timelapse_path)
  1195. info = await processor.get_info()
  1196. return TimelapseInfoResponse(**info)
  1197. except Exception as e:
  1198. logger.error(f"Failed to get timelapse info: {e}")
  1199. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1200. @router.get("/{archive_id}/timelapse/thumbnails")
  1201. async def get_timelapse_thumbnails(
  1202. archive_id: int,
  1203. count: int = Query(10, ge=1, le=30),
  1204. width: int = Query(160, ge=80, le=320),
  1205. db: AsyncSession = Depends(get_db),
  1206. ):
  1207. """Generate timeline thumbnail frames for visual scrubbing."""
  1208. import base64
  1209. from backend.app.schemas.timelapse import ThumbnailResponse
  1210. from backend.app.services.timelapse_processor import TimelapseProcessor
  1211. service = ArchiveService(db)
  1212. archive = await service.get_archive(archive_id)
  1213. if not archive or not archive.timelapse_path:
  1214. raise HTTPException(404, "Timelapse not found")
  1215. timelapse_path = settings.base_dir / archive.timelapse_path
  1216. if not timelapse_path.exists():
  1217. raise HTTPException(404, "Timelapse file not found")
  1218. try:
  1219. processor = TimelapseProcessor(timelapse_path)
  1220. thumbnails = await processor.generate_thumbnails(count, width)
  1221. return ThumbnailResponse(
  1222. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1223. timestamps=[ts for ts, _ in thumbnails],
  1224. )
  1225. except Exception as e:
  1226. logger.error(f"Failed to generate thumbnails: {e}")
  1227. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1228. @router.post("/{archive_id}/timelapse/process")
  1229. async def process_timelapse(
  1230. archive_id: int,
  1231. trim_start: float = Form(0),
  1232. trim_end: float = Form(None),
  1233. speed: float = Form(1.0),
  1234. save_mode: str = Form("new"),
  1235. output_filename: str = Form(None),
  1236. audio: UploadFile = File(None),
  1237. db: AsyncSession = Depends(get_db),
  1238. ):
  1239. """Process timelapse with trim, speed, and optional audio overlay."""
  1240. import shutil
  1241. import tempfile
  1242. from backend.app.schemas.timelapse import ProcessResponse
  1243. from backend.app.services.timelapse_processor import TimelapseProcessor
  1244. # Validate speed
  1245. if not 0.25 <= speed <= 4.0:
  1246. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1247. if save_mode not in ("replace", "new"):
  1248. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1249. service = ArchiveService(db)
  1250. archive = await service.get_archive(archive_id)
  1251. if not archive or not archive.timelapse_path:
  1252. raise HTTPException(404, "Timelapse not found")
  1253. timelapse_path = settings.base_dir / archive.timelapse_path
  1254. if not timelapse_path.exists():
  1255. raise HTTPException(404, "Timelapse file not found")
  1256. archive_dir = timelapse_path.parent
  1257. # Handle audio file
  1258. audio_temp_path = None
  1259. if audio and audio.filename:
  1260. # Validate audio file extension
  1261. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1262. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1263. audio_content = await audio.read()
  1264. suffix = Path(audio.filename).suffix
  1265. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1266. audio_temp_path.write_bytes(audio_content)
  1267. try:
  1268. processor = TimelapseProcessor(timelapse_path)
  1269. # Determine output path
  1270. if save_mode == "replace":
  1271. # Process to temp file first, then replace
  1272. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1273. output_path = temp_output
  1274. else:
  1275. # Save as new file alongside original
  1276. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1277. # Sanitize filename
  1278. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1279. if not filename.endswith(".mp4"):
  1280. filename += ".mp4"
  1281. output_path = archive_dir / filename
  1282. success = await processor.process(
  1283. output_path=output_path,
  1284. trim_start=trim_start,
  1285. trim_end=trim_end,
  1286. speed=speed,
  1287. audio_path=audio_temp_path,
  1288. )
  1289. if not success:
  1290. raise HTTPException(500, "Video processing failed")
  1291. # Handle save mode
  1292. if save_mode == "replace":
  1293. # Replace original file
  1294. shutil.move(str(output_path), str(timelapse_path))
  1295. final_path = archive.timelapse_path
  1296. message = "Timelapse replaced successfully"
  1297. else:
  1298. final_path = str(output_path.relative_to(settings.base_dir))
  1299. message = f"Saved as {output_path.name}"
  1300. return ProcessResponse(
  1301. status="completed",
  1302. output_path=final_path,
  1303. message=message,
  1304. )
  1305. except HTTPException:
  1306. raise
  1307. except Exception as e:
  1308. logger.error(f"Timelapse processing failed: {e}")
  1309. raise HTTPException(500, f"Processing failed: {str(e)}")
  1310. finally:
  1311. # Cleanup temp audio file
  1312. if audio_temp_path and audio_temp_path.exists():
  1313. audio_temp_path.unlink()
  1314. # ============================================
  1315. # Photo Endpoints
  1316. # ============================================
  1317. @router.post("/{archive_id}/photos")
  1318. async def upload_photo(
  1319. archive_id: int,
  1320. file: UploadFile = File(...),
  1321. db: AsyncSession = Depends(get_db),
  1322. ):
  1323. """Upload a photo of the printed result."""
  1324. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1325. archive = result.scalar_one_or_none()
  1326. if not archive:
  1327. raise HTTPException(404, "Archive not found")
  1328. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1329. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1330. # Get archive directory
  1331. file_path = settings.base_dir / archive.file_path
  1332. archive_dir = file_path.parent
  1333. photos_dir = archive_dir / "photos"
  1334. photos_dir.mkdir(exist_ok=True)
  1335. # Generate unique filename
  1336. import uuid
  1337. ext = Path(file.filename).suffix.lower()
  1338. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1339. photo_path = photos_dir / photo_filename
  1340. # Save file
  1341. content = await file.read()
  1342. photo_path.write_bytes(content)
  1343. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1344. photos = list(archive.photos or [])
  1345. photos.append(photo_filename)
  1346. archive.photos = photos
  1347. await db.commit()
  1348. await db.refresh(archive)
  1349. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1350. @router.get("/{archive_id}/photos/{filename}")
  1351. async def get_photo(
  1352. archive_id: int,
  1353. filename: str,
  1354. db: AsyncSession = Depends(get_db),
  1355. ):
  1356. """Get a specific photo."""
  1357. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1358. archive = result.scalar_one_or_none()
  1359. if not archive:
  1360. raise HTTPException(404, "Archive not found")
  1361. file_path = settings.base_dir / archive.file_path
  1362. photo_path = file_path.parent / "photos" / filename
  1363. if not photo_path.exists():
  1364. raise HTTPException(404, "Photo not found")
  1365. # Determine media type
  1366. ext = Path(filename).suffix.lower()
  1367. media_types = {
  1368. ".jpg": "image/jpeg",
  1369. ".jpeg": "image/jpeg",
  1370. ".png": "image/png",
  1371. ".webp": "image/webp",
  1372. }
  1373. media_type = media_types.get(ext, "image/jpeg")
  1374. return FileResponse(path=photo_path, media_type=media_type)
  1375. @router.delete("/{archive_id}/photos/{filename}")
  1376. async def delete_photo(
  1377. archive_id: int,
  1378. filename: str,
  1379. db: AsyncSession = Depends(get_db),
  1380. ):
  1381. """Delete a photo."""
  1382. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1383. archive = result.scalar_one_or_none()
  1384. if not archive:
  1385. raise HTTPException(404, "Archive not found")
  1386. if not archive.photos or filename not in archive.photos:
  1387. raise HTTPException(404, "Photo not found")
  1388. # Delete file
  1389. file_path = settings.base_dir / archive.file_path
  1390. photo_path = file_path.parent / "photos" / filename
  1391. if photo_path.exists():
  1392. photo_path.unlink()
  1393. # Update archive photos list
  1394. photos = [p for p in archive.photos if p != filename]
  1395. archive.photos = photos if photos else None
  1396. await db.commit()
  1397. return {"status": "deleted", "photos": archive.photos}
  1398. # ============================================
  1399. # QR Code Endpoint
  1400. # ============================================
  1401. @router.get("/{archive_id}/qrcode")
  1402. async def get_qrcode(
  1403. archive_id: int,
  1404. request: Request,
  1405. size: int = 200,
  1406. db: AsyncSession = Depends(get_db),
  1407. ):
  1408. """Generate a QR code that links to this archive."""
  1409. try:
  1410. import qrcode
  1411. from PIL import Image as PILImage
  1412. except ImportError:
  1413. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1414. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1415. archive = result.scalar_one_or_none()
  1416. if not archive:
  1417. raise HTTPException(404, "Archive not found")
  1418. # Build URL to archive download
  1419. base_url = str(request.base_url).rstrip("/")
  1420. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1421. # Generate QR code
  1422. qr = qrcode.QRCode(
  1423. version=1,
  1424. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1425. box_size=10,
  1426. border=2,
  1427. )
  1428. qr.add_data(archive_url)
  1429. qr.make(fit=True)
  1430. img = qr.make_image(fill_color="black", back_color="white")
  1431. # Convert to PIL Image for resizing
  1432. pil_img = img.get_image()
  1433. # Resize if needed
  1434. if size != 200:
  1435. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1436. # Convert to bytes
  1437. buffer = io.BytesIO()
  1438. pil_img.save(buffer, format="PNG")
  1439. buffer.seek(0)
  1440. return Response(
  1441. content=buffer.getvalue(),
  1442. media_type="image/png",
  1443. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1444. )
  1445. @router.get("/{archive_id}/capabilities")
  1446. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1447. """Check what viewing capabilities are available for this 3MF file."""
  1448. import json
  1449. import xml.etree.ElementTree as ET
  1450. service = ArchiveService(db)
  1451. archive = await service.get_archive(archive_id)
  1452. if not archive:
  1453. raise HTTPException(404, "Archive not found")
  1454. file_path = settings.base_dir / archive.file_path
  1455. if not file_path.exists():
  1456. raise HTTPException(404, "File not found")
  1457. has_model = False
  1458. has_gcode = False
  1459. has_source = False
  1460. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1461. filament_colors: list[str] = []
  1462. # Check if source 3MF exists - this is where actual mesh data typically lives
  1463. source_path = None
  1464. if archive.source_3mf_path:
  1465. source_path = settings.base_dir / archive.source_3mf_path
  1466. if source_path.exists():
  1467. has_source = True
  1468. # Helper function to check for mesh data and extract colors from a 3MF file
  1469. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1470. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1471. found_mesh = False
  1472. colors: list[str] = []
  1473. volume = {"x": 256, "y": 256, "z": 256}
  1474. try:
  1475. with zipfile.ZipFile(zf_path, "r") as zf:
  1476. names = zf.namelist()
  1477. # Check for 3D model - look for actual mesh data
  1478. for name in names:
  1479. if name.endswith(".model"):
  1480. try:
  1481. content = zf.read(name).decode("utf-8")
  1482. if "<vertex" in content or "<mesh" in content:
  1483. found_mesh = True
  1484. break
  1485. except Exception:
  1486. pass
  1487. # Extract filament colors from project_settings.config
  1488. if "Metadata/project_settings.config" in names:
  1489. try:
  1490. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1491. config_data = json.loads(config_content)
  1492. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1493. printable_area = config_data.get("printable_area", [])
  1494. if printable_area and len(printable_area) >= 3:
  1495. max_x = 0
  1496. max_y = 0
  1497. for coord in printable_area:
  1498. if "x" in coord:
  1499. parts = coord.split("x")
  1500. if len(parts) == 2:
  1501. try:
  1502. x, y = int(parts[0]), int(parts[1])
  1503. max_x = max(max_x, x)
  1504. max_y = max(max_y, y)
  1505. except ValueError:
  1506. pass
  1507. if max_x > 0 and max_y > 0:
  1508. volume["x"] = max_x
  1509. volume["y"] = max_y
  1510. # Parse printable_height
  1511. printable_height = config_data.get("printable_height")
  1512. if printable_height:
  1513. try:
  1514. volume["z"] = int(printable_height)
  1515. except (ValueError, TypeError):
  1516. pass
  1517. # Extract filament colors
  1518. raw_colors = config_data.get("filament_colour", [])
  1519. if raw_colors:
  1520. for color in raw_colors:
  1521. if color and isinstance(color, str):
  1522. colors.append(color)
  1523. except Exception:
  1524. pass
  1525. except zipfile.BadZipFile:
  1526. pass
  1527. return found_mesh, colors, volume
  1528. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1529. if has_source and source_path:
  1530. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1531. if source_has_mesh:
  1532. has_model = True
  1533. if source_colors:
  1534. filament_colors = source_colors
  1535. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1536. build_volume = source_volume
  1537. try:
  1538. with zipfile.ZipFile(file_path, "r") as zf:
  1539. names = zf.namelist()
  1540. # Check for G-code in the sliced file
  1541. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1542. # Check for 3D model in sliced file (fallback if no source)
  1543. if not has_model:
  1544. for name in names:
  1545. if name.endswith(".model"):
  1546. try:
  1547. content = zf.read(name).decode("utf-8")
  1548. if "<vertex" in content or "<mesh" in content:
  1549. has_model = True
  1550. break
  1551. except Exception:
  1552. pass
  1553. # Extract filament colors from slice_info.config (for gcode preview)
  1554. # These are the actual filaments used in the print, indexed by tool/extruder
  1555. slice_colors: list[str] = []
  1556. if "Metadata/slice_info.config" in names:
  1557. try:
  1558. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1559. root = ET.fromstring(slice_content)
  1560. filaments = root.findall(".//filament")
  1561. filament_map: dict[int, str] = {}
  1562. for f in filaments:
  1563. fid = f.get("id")
  1564. fcolor = f.get("color")
  1565. used_g = f.get("used_g", "0")
  1566. try:
  1567. used_amount = float(used_g)
  1568. except (ValueError, TypeError):
  1569. used_amount = 0
  1570. if fid is not None and fcolor:
  1571. try:
  1572. tool_id = int(fid) - 1
  1573. if tool_id >= 0 and used_amount > 0:
  1574. filament_map[tool_id] = fcolor
  1575. except ValueError:
  1576. pass
  1577. if filament_map:
  1578. max_tool = max(filament_map.keys())
  1579. for i in range(max_tool + 1):
  1580. slice_colors.append(filament_map.get(i, "#00AE42"))
  1581. except Exception:
  1582. pass
  1583. # Use slice_info colors if we don't have colors from source yet
  1584. if not filament_colors and slice_colors:
  1585. filament_colors = slice_colors
  1586. # Extract build volume from sliced file if not already set from source
  1587. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1588. if "Metadata/project_settings.config" in names:
  1589. try:
  1590. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1591. config_data = json.loads(config_content)
  1592. printable_area = config_data.get("printable_area", [])
  1593. if printable_area and len(printable_area) >= 3:
  1594. max_x = 0
  1595. max_y = 0
  1596. for coord in printable_area:
  1597. if "x" in coord:
  1598. parts = coord.split("x")
  1599. if len(parts) == 2:
  1600. try:
  1601. x, y = int(parts[0]), int(parts[1])
  1602. max_x = max(max_x, x)
  1603. max_y = max(max_y, y)
  1604. except ValueError:
  1605. pass
  1606. if max_x > 0 and max_y > 0:
  1607. build_volume["x"] = max_x
  1608. build_volume["y"] = max_y
  1609. printable_height = config_data.get("printable_height")
  1610. if printable_height:
  1611. try:
  1612. build_volume["z"] = int(printable_height)
  1613. except (ValueError, TypeError):
  1614. pass
  1615. # Fallback colors from project_settings if still empty
  1616. if not filament_colors:
  1617. raw_colors = config_data.get("filament_colour", [])
  1618. if raw_colors:
  1619. for color in raw_colors:
  1620. if color and isinstance(color, str):
  1621. filament_colors.append(color)
  1622. except Exception:
  1623. pass
  1624. except zipfile.BadZipFile:
  1625. raise HTTPException(400, "Invalid 3MF file")
  1626. return {
  1627. "has_model": has_model,
  1628. "has_gcode": has_gcode,
  1629. "has_source": has_source,
  1630. "build_volume": build_volume,
  1631. "filament_colors": filament_colors,
  1632. }
  1633. @router.get("/{archive_id}/gcode")
  1634. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1635. """Extract and return G-code from the 3MF file."""
  1636. service = ArchiveService(db)
  1637. archive = await service.get_archive(archive_id)
  1638. if not archive:
  1639. raise HTTPException(404, "Archive not found")
  1640. file_path = settings.base_dir / archive.file_path
  1641. if not file_path.exists():
  1642. raise HTTPException(404, "File not found")
  1643. try:
  1644. with zipfile.ZipFile(file_path, "r") as zf:
  1645. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1646. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1647. if not gcode_files:
  1648. raise HTTPException(
  1649. 404,
  1650. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1651. )
  1652. # Get the first plate's G-code (usually plate_1.gcode)
  1653. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1654. return Response(content=gcode_content, media_type="text/plain")
  1655. except zipfile.BadZipFile:
  1656. raise HTTPException(400, "Invalid 3MF file")
  1657. except HTTPException:
  1658. raise
  1659. except Exception as e:
  1660. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1661. @router.get("/{archive_id}/plate-preview")
  1662. async def get_plate_preview(archive_id: int, db: AsyncSession = Depends(get_db)):
  1663. """Get the plate preview image from the 3MF file.
  1664. Returns the slicer-generated plate thumbnail which shows the model
  1665. with correct colors and positioning.
  1666. """
  1667. service = ArchiveService(db)
  1668. archive = await service.get_archive(archive_id)
  1669. if not archive:
  1670. raise HTTPException(404, "Archive not found")
  1671. file_path = settings.base_dir / archive.file_path
  1672. if not file_path.exists():
  1673. raise HTTPException(404, "File not found")
  1674. try:
  1675. with zipfile.ZipFile(file_path, "r") as zf:
  1676. names = zf.namelist()
  1677. # Try to find plate preview images in order of preference
  1678. # First look for the specific plate being printed (check slice_info for plate index)
  1679. plate_num = 1
  1680. if "Metadata/slice_info.config" in names:
  1681. try:
  1682. import xml.etree.ElementTree as ET
  1683. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1684. root = ET.fromstring(slice_content)
  1685. plate_elem = root.find(".//plate/metadata[@key='index']")
  1686. if plate_elem is not None:
  1687. plate_num = int(plate_elem.get("value", "1"))
  1688. except Exception:
  1689. pass
  1690. # Try plate-specific image first, then fall back to plate_1
  1691. preview_paths = [
  1692. f"Metadata/plate_{plate_num}.png",
  1693. "Metadata/plate_1.png",
  1694. "Metadata/thumbnail.png",
  1695. ]
  1696. for preview_path in preview_paths:
  1697. if preview_path in names:
  1698. image_data = zf.read(preview_path)
  1699. return Response(content=image_data, media_type="image/png")
  1700. # If no plate image, try any PNG in Metadata
  1701. for name in names:
  1702. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1703. image_data = zf.read(name)
  1704. return Response(content=image_data, media_type="image/png")
  1705. raise HTTPException(404, "No plate preview found in 3MF file")
  1706. except zipfile.BadZipFile:
  1707. raise HTTPException(400, "Invalid 3MF file")
  1708. except HTTPException:
  1709. raise
  1710. except Exception as e:
  1711. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1712. @router.post("/upload")
  1713. async def upload_archive(
  1714. file: UploadFile = File(...),
  1715. printer_id: int | None = None,
  1716. db: AsyncSession = Depends(get_db),
  1717. current_user: User | None = Depends(require_auth_if_enabled),
  1718. ):
  1719. """Manually upload a 3MF file to archive."""
  1720. if not file.filename or not file.filename.endswith(".3mf"):
  1721. raise HTTPException(400, "File must be a .3mf file")
  1722. # Save uploaded file temporarily
  1723. temp_path = settings.archive_dir / "temp" / file.filename
  1724. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1725. try:
  1726. content = await file.read()
  1727. temp_path.write_bytes(content)
  1728. service = ArchiveService(db)
  1729. archive = await service.archive_print(
  1730. printer_id=printer_id,
  1731. source_file=temp_path,
  1732. created_by_id=current_user.id if current_user else None,
  1733. )
  1734. if not archive:
  1735. raise HTTPException(400, "Failed to archive file")
  1736. return ArchiveResponse.model_validate(archive)
  1737. finally:
  1738. if temp_path.exists():
  1739. temp_path.unlink()
  1740. @router.post("/upload-bulk")
  1741. async def upload_archives_bulk(
  1742. files: list[UploadFile] = File(...),
  1743. printer_id: int | None = None,
  1744. db: AsyncSession = Depends(get_db),
  1745. current_user: User | None = Depends(require_auth_if_enabled),
  1746. ):
  1747. """Bulk upload multiple 3MF files to archive."""
  1748. results = []
  1749. errors = []
  1750. for file in files:
  1751. if not file.filename or not file.filename.endswith(".3mf"):
  1752. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1753. continue
  1754. temp_path = settings.archive_dir / "temp" / file.filename
  1755. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1756. try:
  1757. content = await file.read()
  1758. temp_path.write_bytes(content)
  1759. service = ArchiveService(db)
  1760. archive = await service.archive_print(
  1761. printer_id=printer_id,
  1762. source_file=temp_path,
  1763. created_by_id=current_user.id if current_user else None,
  1764. )
  1765. if archive:
  1766. results.append(
  1767. {
  1768. "filename": file.filename,
  1769. "id": archive.id,
  1770. "status": "success",
  1771. }
  1772. )
  1773. else:
  1774. errors.append({"filename": file.filename, "error": "Failed to process"})
  1775. except Exception as e:
  1776. logger.exception(f"Failed to upload archive {file.filename}: {e}")
  1777. errors.append({"filename": file.filename, "error": "Failed to process file"})
  1778. finally:
  1779. if temp_path.exists():
  1780. temp_path.unlink()
  1781. return {
  1782. "uploaded": len(results),
  1783. "failed": len(errors),
  1784. "results": results,
  1785. "errors": errors,
  1786. }
  1787. @router.get("/{archive_id}/plates")
  1788. async def get_archive_plates(
  1789. archive_id: int,
  1790. db: AsyncSession = Depends(get_db),
  1791. ):
  1792. """Get available plates from a multi-plate 3MF archive.
  1793. Returns a list of plates with their index, name, thumbnail availability,
  1794. and filament requirements. For single-plate exports, returns a single plate.
  1795. """
  1796. import xml.etree.ElementTree as ET
  1797. service = ArchiveService(db)
  1798. archive = await service.get_archive(archive_id)
  1799. if not archive:
  1800. raise HTTPException(404, "Archive not found")
  1801. file_path = settings.base_dir / archive.file_path
  1802. if not file_path.exists():
  1803. raise HTTPException(404, "Archive file not found")
  1804. plates = []
  1805. try:
  1806. with zipfile.ZipFile(file_path, "r") as zf:
  1807. namelist = zf.namelist()
  1808. # Find all plate gcode files to determine available plates
  1809. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1810. if not gcode_files:
  1811. # No sliced plates found
  1812. return {"archive_id": archive_id, "filename": archive.filename, "plates": []}
  1813. # Extract plate indices from gcode filenames
  1814. plate_indices = []
  1815. for gf in gcode_files:
  1816. # "Metadata/plate_5.gcode" -> 5
  1817. try:
  1818. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1819. plate_indices.append(int(plate_str))
  1820. except ValueError:
  1821. pass
  1822. plate_indices.sort()
  1823. # Parse model_settings.config for plate names
  1824. # Plate names are stored with plater_id and plater_name keys
  1825. plate_names = {} # plater_id -> name
  1826. if "Metadata/model_settings.config" in namelist:
  1827. try:
  1828. model_content = zf.read("Metadata/model_settings.config").decode()
  1829. model_root = ET.fromstring(model_content)
  1830. for plate_elem in model_root.findall(".//plate"):
  1831. plater_id = None
  1832. plater_name = None
  1833. for meta in plate_elem.findall("metadata"):
  1834. key = meta.get("key")
  1835. value = meta.get("value")
  1836. if key == "plater_id" and value:
  1837. try:
  1838. plater_id = int(value)
  1839. except ValueError:
  1840. pass
  1841. elif key == "plater_name" and value:
  1842. plater_name = value.strip()
  1843. if plater_id is not None and plater_name:
  1844. plate_names[plater_id] = plater_name
  1845. except Exception:
  1846. pass # model_settings.config parsing is optional
  1847. # Parse slice_info.config for plate metadata
  1848. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  1849. if "Metadata/slice_info.config" in namelist:
  1850. content = zf.read("Metadata/slice_info.config").decode()
  1851. root = ET.fromstring(content)
  1852. for plate_elem in root.findall(".//plate"):
  1853. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1854. # Get plate index from metadata
  1855. plate_index = None
  1856. for meta in plate_elem.findall("metadata"):
  1857. key = meta.get("key")
  1858. value = meta.get("value")
  1859. if key == "index" and value:
  1860. try:
  1861. plate_index = int(value)
  1862. except ValueError:
  1863. pass
  1864. elif key == "prediction" and value:
  1865. try:
  1866. plate_info["prediction"] = int(value)
  1867. except ValueError:
  1868. pass
  1869. elif key == "weight" and value:
  1870. try:
  1871. plate_info["weight"] = float(value)
  1872. except ValueError:
  1873. pass
  1874. # Get filaments used in this plate
  1875. for filament_elem in plate_elem.findall("filament"):
  1876. filament_id = filament_elem.get("id")
  1877. filament_type = filament_elem.get("type", "")
  1878. filament_color = filament_elem.get("color", "")
  1879. used_g = filament_elem.get("used_g", "0")
  1880. used_m = filament_elem.get("used_m", "0")
  1881. try:
  1882. used_grams = float(used_g)
  1883. except (ValueError, TypeError):
  1884. used_grams = 0
  1885. if used_grams > 0 and filament_id:
  1886. plate_info["filaments"].append(
  1887. {
  1888. "slot_id": int(filament_id),
  1889. "type": filament_type,
  1890. "color": filament_color,
  1891. "used_grams": round(used_grams, 1),
  1892. "used_meters": float(used_m) if used_m else 0,
  1893. }
  1894. )
  1895. # Sort filaments by slot ID
  1896. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1897. # Collect all object names on this plate
  1898. for obj_elem in plate_elem.findall("object"):
  1899. obj_name = obj_elem.get("name")
  1900. if obj_name and obj_name not in plate_info["objects"]:
  1901. plate_info["objects"].append(obj_name)
  1902. # Set plate name: prefer custom name from model_settings.config,
  1903. # fall back to first object name if no custom name was set
  1904. if plate_index is not None:
  1905. custom_name = plate_names.get(plate_index)
  1906. if custom_name:
  1907. plate_info["name"] = custom_name
  1908. else:
  1909. # Fall back to first object name as hint
  1910. if plate_info["objects"]:
  1911. plate_info["name"] = plate_info["objects"][0]
  1912. plate_metadata[plate_index] = plate_info
  1913. # Build plate list
  1914. for idx in plate_indices:
  1915. meta = plate_metadata.get(idx, {})
  1916. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1917. plates.append(
  1918. {
  1919. "index": idx,
  1920. "name": meta.get("name"),
  1921. "objects": meta.get("objects", []),
  1922. "has_thumbnail": has_thumbnail,
  1923. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  1924. if has_thumbnail
  1925. else None,
  1926. "print_time_seconds": meta.get("prediction"),
  1927. "filament_used_grams": meta.get("weight"),
  1928. "filaments": meta.get("filaments", []),
  1929. }
  1930. )
  1931. except Exception as e:
  1932. logger.warning(f"Failed to parse plates from archive {archive_id}: {e}")
  1933. return {
  1934. "archive_id": archive_id,
  1935. "filename": archive.filename,
  1936. "plates": plates,
  1937. "is_multi_plate": len(plates) > 1,
  1938. }
  1939. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  1940. async def get_plate_thumbnail(
  1941. archive_id: int,
  1942. plate_index: int,
  1943. db: AsyncSession = Depends(get_db),
  1944. ):
  1945. """Get the thumbnail image for a specific plate."""
  1946. service = ArchiveService(db)
  1947. archive = await service.get_archive(archive_id)
  1948. if not archive:
  1949. raise HTTPException(404, "Archive not found")
  1950. file_path = settings.base_dir / archive.file_path
  1951. if not file_path.exists():
  1952. raise HTTPException(404, "Archive file not found")
  1953. try:
  1954. with zipfile.ZipFile(file_path, "r") as zf:
  1955. thumb_path = f"Metadata/plate_{plate_index}.png"
  1956. if thumb_path in zf.namelist():
  1957. data = zf.read(thumb_path)
  1958. return Response(content=data, media_type="image/png")
  1959. except Exception:
  1960. pass
  1961. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  1962. @router.get("/{archive_id}/filament-requirements")
  1963. async def get_filament_requirements(
  1964. archive_id: int,
  1965. plate_id: int | None = None,
  1966. db: AsyncSession = Depends(get_db),
  1967. ):
  1968. """Get filament requirements from the archived 3MF file.
  1969. Returns the filaments used in this print with their slot IDs, types, colors,
  1970. and usage amounts. This can be compared with current AMS state before reprinting.
  1971. Args:
  1972. archive_id: The archive ID
  1973. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  1974. """
  1975. import xml.etree.ElementTree as ET
  1976. service = ArchiveService(db)
  1977. archive = await service.get_archive(archive_id)
  1978. if not archive:
  1979. raise HTTPException(404, "Archive not found")
  1980. file_path = settings.base_dir / archive.file_path
  1981. if not file_path.exists():
  1982. raise HTTPException(404, "Archive file not found")
  1983. filaments = []
  1984. try:
  1985. with zipfile.ZipFile(file_path, "r") as zf:
  1986. # Parse slice_info.config for filament requirements
  1987. if "Metadata/slice_info.config" in zf.namelist():
  1988. content = zf.read("Metadata/slice_info.config").decode()
  1989. root = ET.fromstring(content)
  1990. # If plate_id is specified, find filaments for that specific plate
  1991. if plate_id is not None:
  1992. # Find the plate element with matching index
  1993. for plate_elem in root.findall(".//plate"):
  1994. plate_index = None
  1995. for meta in plate_elem.findall("metadata"):
  1996. if meta.get("key") == "index":
  1997. try:
  1998. plate_index = int(meta.get("value", "0"))
  1999. except ValueError:
  2000. pass
  2001. break
  2002. if plate_index == plate_id:
  2003. # Extract filaments from this plate element
  2004. for filament_elem in plate_elem.findall("filament"):
  2005. filament_id = filament_elem.get("id")
  2006. filament_type = filament_elem.get("type", "")
  2007. filament_color = filament_elem.get("color", "")
  2008. used_g = filament_elem.get("used_g", "0")
  2009. used_m = filament_elem.get("used_m", "0")
  2010. try:
  2011. used_grams = float(used_g)
  2012. except (ValueError, TypeError):
  2013. used_grams = 0
  2014. if used_grams > 0 and filament_id:
  2015. filaments.append(
  2016. {
  2017. "slot_id": int(filament_id),
  2018. "type": filament_type,
  2019. "color": filament_color,
  2020. "used_grams": round(used_grams, 1),
  2021. "used_meters": float(used_m) if used_m else 0,
  2022. }
  2023. )
  2024. break
  2025. else:
  2026. # No plate_id specified - extract all filaments with used_g > 0
  2027. # This is the legacy behavior for single-plate files
  2028. for filament_elem in root.findall(".//filament"):
  2029. filament_id = filament_elem.get("id")
  2030. filament_type = filament_elem.get("type", "")
  2031. filament_color = filament_elem.get("color", "")
  2032. used_g = filament_elem.get("used_g", "0")
  2033. used_m = filament_elem.get("used_m", "0")
  2034. # Only include filaments that are actually used
  2035. try:
  2036. used_grams = float(used_g)
  2037. except (ValueError, TypeError):
  2038. used_grams = 0
  2039. if used_grams > 0 and filament_id:
  2040. filaments.append(
  2041. {
  2042. "slot_id": int(filament_id),
  2043. "type": filament_type,
  2044. "color": filament_color,
  2045. "used_grams": round(used_grams, 1),
  2046. "used_meters": float(used_m) if used_m else 0,
  2047. }
  2048. )
  2049. # Sort by slot ID
  2050. filaments.sort(key=lambda x: x["slot_id"])
  2051. except Exception as e:
  2052. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  2053. return {
  2054. "archive_id": archive_id,
  2055. "filename": archive.filename,
  2056. "plate_id": plate_id,
  2057. "filaments": filaments,
  2058. }
  2059. @router.post("/{archive_id}/reprint")
  2060. async def reprint_archive(
  2061. archive_id: int,
  2062. printer_id: int,
  2063. body: ReprintRequest | None = None,
  2064. db: AsyncSession = Depends(get_db),
  2065. auth_result: tuple[User | None, bool] = Depends(
  2066. require_ownership_permission(
  2067. Permission.ARCHIVES_REPRINT_ALL,
  2068. Permission.ARCHIVES_REPRINT_OWN,
  2069. )
  2070. ),
  2071. ):
  2072. """Send an archived 3MF file to a printer and start printing."""
  2073. from backend.app.main import register_expected_print
  2074. from backend.app.models.printer import Printer
  2075. from backend.app.services.bambu_ftp import (
  2076. get_ftp_retry_settings,
  2077. upload_file_async,
  2078. with_ftp_retry,
  2079. )
  2080. from backend.app.services.printer_manager import printer_manager
  2081. user, can_modify_all = auth_result
  2082. # Use defaults if no body provided
  2083. if body is None:
  2084. body = ReprintRequest()
  2085. # Get archive
  2086. service = ArchiveService(db)
  2087. archive = await service.get_archive(archive_id)
  2088. if not archive:
  2089. raise HTTPException(404, "Archive not found")
  2090. # Ownership check
  2091. if not can_modify_all:
  2092. if archive.created_by_id != user.id:
  2093. raise HTTPException(403, "You can only reprint your own archives")
  2094. # Get printer
  2095. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2096. printer = result.scalar_one_or_none()
  2097. if not printer:
  2098. raise HTTPException(404, "Printer not found")
  2099. # Check printer is connected
  2100. if not printer_manager.is_connected(printer_id):
  2101. raise HTTPException(400, "Printer is not connected")
  2102. # Get the sliced 3MF file path
  2103. file_path = settings.base_dir / archive.file_path
  2104. if not file_path.exists():
  2105. raise HTTPException(404, "Archive file not found")
  2106. # Upload file to printer via FTP
  2107. from backend.app.services.bambu_ftp import delete_file_async
  2108. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  2109. # The printer might reject filenames with unusual extensions
  2110. base_name = archive.filename
  2111. if base_name.endswith(".gcode.3mf"):
  2112. base_name = base_name[:-10] # Remove .gcode.3mf
  2113. elif base_name.endswith(".3mf"):
  2114. base_name = base_name[:-4] # Remove .3mf
  2115. remote_filename = f"{base_name}.3mf"
  2116. remote_path = f"/{remote_filename}"
  2117. # Get FTP retry settings
  2118. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2119. logger.info(
  2120. f"Reprint FTP upload starting: printer={printer.name} ({printer.model}), "
  2121. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  2122. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  2123. )
  2124. # Delete existing file if present (avoids 553 error)
  2125. logger.debug(f"Deleting existing file {remote_path} if present...")
  2126. delete_result = await delete_file_async(
  2127. printer.ip_address,
  2128. printer.access_code,
  2129. remote_path,
  2130. socket_timeout=ftp_timeout,
  2131. printer_model=printer.model,
  2132. )
  2133. logger.debug(f"Delete result: {delete_result}")
  2134. if ftp_retry_enabled:
  2135. uploaded = await with_ftp_retry(
  2136. upload_file_async,
  2137. printer.ip_address,
  2138. printer.access_code,
  2139. file_path,
  2140. remote_path,
  2141. socket_timeout=ftp_timeout,
  2142. printer_model=printer.model,
  2143. max_retries=ftp_retry_count,
  2144. retry_delay=ftp_retry_delay,
  2145. operation_name=f"Upload for reprint to {printer.name}",
  2146. )
  2147. else:
  2148. uploaded = await upload_file_async(
  2149. printer.ip_address,
  2150. printer.access_code,
  2151. file_path,
  2152. remote_path,
  2153. socket_timeout=ftp_timeout,
  2154. printer_model=printer.model,
  2155. )
  2156. if not uploaded:
  2157. logger.error(
  2158. f"FTP upload failed for reprint: printer={printer.name}, model={printer.model}, "
  2159. f"ip={printer.ip_address}, file={remote_filename}. "
  2160. "Check logs above for storage diagnostics and specific error codes."
  2161. )
  2162. raise HTTPException(
  2163. 500,
  2164. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  2165. "See server logs for detailed diagnostics.",
  2166. )
  2167. # Register this as an expected print so we don't create a duplicate archive
  2168. register_expected_print(printer_id, remote_filename, archive_id)
  2169. # Use plate_id from request if provided, otherwise auto-detect from 3MF file
  2170. if body.plate_id is not None:
  2171. plate_id = body.plate_id
  2172. else:
  2173. # Auto-detect plate ID from 3MF file (legacy behavior for single-plate files)
  2174. plate_id = 1
  2175. try:
  2176. with zipfile.ZipFile(file_path, "r") as zf:
  2177. for name in zf.namelist():
  2178. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  2179. # Extract plate number from "Metadata/plate_X.gcode"
  2180. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  2181. plate_id = int(plate_str)
  2182. break
  2183. except Exception:
  2184. pass # Default to plate 1 if detection fails
  2185. logger.info(
  2186. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  2187. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  2188. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  2189. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  2190. )
  2191. # Start the print with options
  2192. started = printer_manager.start_print(
  2193. printer_id,
  2194. remote_filename,
  2195. plate_id,
  2196. ams_mapping=body.ams_mapping,
  2197. timelapse=body.timelapse,
  2198. bed_levelling=body.bed_levelling,
  2199. flow_cali=body.flow_cali,
  2200. vibration_cali=body.vibration_cali,
  2201. layer_inspect=body.layer_inspect,
  2202. use_ams=body.use_ams,
  2203. )
  2204. if not started:
  2205. raise HTTPException(500, "Failed to start print")
  2206. # Track who started this print (Issue #206)
  2207. if user:
  2208. printer_manager.set_current_print_user(printer_id, user.id, user.username)
  2209. logger.info(f"Reprint started by user: {user.username}")
  2210. return {
  2211. "status": "printing",
  2212. "printer_id": printer_id,
  2213. "archive_id": archive_id,
  2214. "filename": archive.filename,
  2215. }
  2216. # =============================================================================
  2217. # Project Page API
  2218. # =============================================================================
  2219. @router.get("/{archive_id}/project-page")
  2220. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  2221. """Get the project page data from the 3MF file."""
  2222. from backend.app.schemas.archive import ProjectPageResponse
  2223. from backend.app.services.archive import ProjectPageParser
  2224. service = ArchiveService(db)
  2225. archive = await service.get_archive(archive_id)
  2226. if not archive:
  2227. raise HTTPException(404, "Archive not found")
  2228. file_path = settings.base_dir / archive.file_path
  2229. if not file_path.exists():
  2230. raise HTTPException(404, "Archive file not found")
  2231. parser = ProjectPageParser(file_path)
  2232. data = parser.parse(archive_id)
  2233. return ProjectPageResponse(**data)
  2234. @router.patch("/{archive_id}/project-page")
  2235. async def update_project_page(
  2236. archive_id: int,
  2237. update_data: dict,
  2238. db: AsyncSession = Depends(get_db),
  2239. ):
  2240. """Update project page metadata in the 3MF file."""
  2241. from backend.app.services.archive import ProjectPageParser
  2242. service = ArchiveService(db)
  2243. archive = await service.get_archive(archive_id)
  2244. if not archive:
  2245. raise HTTPException(404, "Archive not found")
  2246. file_path = settings.base_dir / archive.file_path
  2247. if not file_path.exists():
  2248. raise HTTPException(404, "Archive file not found")
  2249. parser = ProjectPageParser(file_path)
  2250. success = parser.update_metadata(update_data)
  2251. if not success:
  2252. raise HTTPException(500, "Failed to update project page")
  2253. # Return updated data
  2254. data = parser.parse(archive_id)
  2255. return data
  2256. @router.get("/{archive_id}/project-image/{image_path:path}")
  2257. async def get_project_image(
  2258. archive_id: int,
  2259. image_path: str,
  2260. db: AsyncSession = Depends(get_db),
  2261. ):
  2262. """Get an image from the 3MF project page."""
  2263. from backend.app.services.archive import ProjectPageParser
  2264. service = ArchiveService(db)
  2265. archive = await service.get_archive(archive_id)
  2266. if not archive:
  2267. raise HTTPException(404, "Archive not found")
  2268. file_path = settings.base_dir / archive.file_path
  2269. if not file_path.exists():
  2270. raise HTTPException(404, "Archive file not found")
  2271. parser = ProjectPageParser(file_path)
  2272. result = parser.get_image(image_path)
  2273. if not result:
  2274. raise HTTPException(404, "Image not found in 3MF file")
  2275. image_data, content_type = result
  2276. return Response(
  2277. content=image_data,
  2278. media_type=content_type,
  2279. headers={"Cache-Control": "max-age=3600"},
  2280. )
  2281. # =============================================================================
  2282. # Source 3MF API (Original Project Files)
  2283. # =============================================================================
  2284. @router.post("/{archive_id}/source")
  2285. async def upload_source_3mf(
  2286. archive_id: int,
  2287. file: UploadFile = File(...),
  2288. db: AsyncSession = Depends(get_db),
  2289. ):
  2290. """Upload the original source 3MF project file for an archive."""
  2291. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2292. archive = result.scalar_one_or_none()
  2293. if not archive:
  2294. raise HTTPException(404, "Archive not found")
  2295. if not file.filename or not file.filename.endswith(".3mf"):
  2296. raise HTTPException(400, "File must be a .3mf file")
  2297. # Get archive directory and create source subdirectory
  2298. file_path = settings.base_dir / archive.file_path
  2299. archive_dir = file_path.parent
  2300. source_dir = archive_dir / "source"
  2301. source_dir.mkdir(exist_ok=True)
  2302. # Delete old source file if exists
  2303. if archive.source_3mf_path:
  2304. old_source_path = settings.base_dir / archive.source_3mf_path
  2305. if old_source_path.exists():
  2306. old_source_path.unlink()
  2307. # Save the source 3MF file - preserve original filename
  2308. source_filename = file.filename
  2309. source_path = source_dir / source_filename
  2310. content = await file.read()
  2311. source_path.write_bytes(content)
  2312. # Update archive with source path (relative to base_dir)
  2313. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2314. await db.commit()
  2315. await db.refresh(archive)
  2316. return {
  2317. "status": "uploaded",
  2318. "source_3mf_path": archive.source_3mf_path,
  2319. "filename": source_filename,
  2320. }
  2321. @router.get("/{archive_id}/source")
  2322. async def download_source_3mf(
  2323. archive_id: int,
  2324. db: AsyncSession = Depends(get_db),
  2325. ):
  2326. """Download the source 3MF project file."""
  2327. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2328. archive = result.scalar_one_or_none()
  2329. if not archive:
  2330. raise HTTPException(404, "Archive not found")
  2331. if not archive.source_3mf_path:
  2332. raise HTTPException(404, "No source 3MF attached to this archive")
  2333. source_path = settings.base_dir / archive.source_3mf_path
  2334. if not source_path.exists():
  2335. raise HTTPException(404, "Source 3MF file not found on disk")
  2336. # Use the actual filename from the path
  2337. filename = source_path.name
  2338. return FileResponse(
  2339. path=source_path,
  2340. filename=filename,
  2341. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2342. )
  2343. @router.get("/{archive_id}/source/{filename}")
  2344. async def download_source_3mf_for_slicer(
  2345. archive_id: int,
  2346. filename: str,
  2347. db: AsyncSession = Depends(get_db),
  2348. ):
  2349. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  2350. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2351. archive = result.scalar_one_or_none()
  2352. if not archive:
  2353. raise HTTPException(404, "Archive not found")
  2354. if not archive.source_3mf_path:
  2355. raise HTTPException(404, "No source 3MF attached to this archive")
  2356. source_path = settings.base_dir / archive.source_3mf_path
  2357. if not source_path.exists():
  2358. raise HTTPException(404, "Source 3MF file not found on disk")
  2359. return FileResponse(
  2360. path=source_path,
  2361. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  2362. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2363. )
  2364. @router.post("/upload-source")
  2365. async def upload_source_3mf_by_name(
  2366. file: UploadFile = File(...),
  2367. print_name: str = Query(None, description="Match archive by print name"),
  2368. db: AsyncSession = Depends(get_db),
  2369. ):
  2370. """Upload source 3MF and match to archive by print name.
  2371. This endpoint is designed for slicer post-processing scripts.
  2372. It finds the most recent archive matching the print name and attaches the source.
  2373. """
  2374. if not file.filename or not file.filename.endswith(".3mf"):
  2375. raise HTTPException(400, "File must be a .3mf file")
  2376. # Derive print name from filename if not provided
  2377. if not print_name:
  2378. # Remove .3mf extension and common suffixes
  2379. print_name = file.filename.rsplit(".3mf", 1)[0]
  2380. # Remove _source suffix if present
  2381. if print_name.endswith("_source"):
  2382. print_name = print_name[:-7]
  2383. # Find matching archive - try exact match first, then fuzzy
  2384. result = await db.execute(
  2385. select(PrintArchive)
  2386. .where(PrintArchive.print_name == print_name)
  2387. .order_by(PrintArchive.created_at.desc())
  2388. .limit(1)
  2389. )
  2390. archive = result.scalar_one_or_none()
  2391. if not archive:
  2392. # Try matching filename without .gcode.3mf
  2393. result = await db.execute(
  2394. select(PrintArchive)
  2395. .where(PrintArchive.filename.like(f"{print_name}%"))
  2396. .order_by(PrintArchive.created_at.desc())
  2397. .limit(1)
  2398. )
  2399. archive = result.scalar_one_or_none()
  2400. if not archive:
  2401. # Try case-insensitive partial match on print_name
  2402. result = await db.execute(
  2403. select(PrintArchive)
  2404. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  2405. .order_by(PrintArchive.created_at.desc())
  2406. .limit(1)
  2407. )
  2408. archive = result.scalar_one_or_none()
  2409. if not archive:
  2410. raise HTTPException(404, f"No archive found matching '{print_name}'")
  2411. # Get archive directory and create source subdirectory
  2412. file_path = settings.base_dir / archive.file_path
  2413. archive_dir = file_path.parent
  2414. source_dir = archive_dir / "source"
  2415. source_dir.mkdir(exist_ok=True)
  2416. # Delete old source file if exists
  2417. if archive.source_3mf_path:
  2418. old_source_path = settings.base_dir / archive.source_3mf_path
  2419. if old_source_path.exists():
  2420. old_source_path.unlink()
  2421. # Save the source 3MF file - preserve original filename
  2422. source_filename = file.filename
  2423. source_path = source_dir / source_filename
  2424. content = await file.read()
  2425. source_path.write_bytes(content)
  2426. # Update archive with source path
  2427. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2428. await db.commit()
  2429. await db.refresh(archive)
  2430. return {
  2431. "status": "uploaded",
  2432. "archive_id": archive.id,
  2433. "archive_name": archive.print_name or archive.filename,
  2434. "source_3mf_path": archive.source_3mf_path,
  2435. "filename": source_filename,
  2436. }
  2437. @router.delete("/{archive_id}/source")
  2438. async def delete_source_3mf(
  2439. archive_id: int,
  2440. db: AsyncSession = Depends(get_db),
  2441. ):
  2442. """Delete the source 3MF project file from an archive."""
  2443. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2444. archive = result.scalar_one_or_none()
  2445. if not archive:
  2446. raise HTTPException(404, "Archive not found")
  2447. if not archive.source_3mf_path:
  2448. raise HTTPException(404, "No source 3MF attached to this archive")
  2449. # Delete the file
  2450. source_path = settings.base_dir / archive.source_3mf_path
  2451. if source_path.exists():
  2452. source_path.unlink()
  2453. # Clear the path in database
  2454. archive.source_3mf_path = None
  2455. await db.commit()
  2456. return {"status": "deleted"}
  2457. # =============================================================================
  2458. # F3D API (Fusion 360 Design Files)
  2459. # =============================================================================
  2460. @router.post("/{archive_id}/f3d")
  2461. async def upload_f3d(
  2462. archive_id: int,
  2463. file: UploadFile = File(...),
  2464. db: AsyncSession = Depends(get_db),
  2465. ):
  2466. """Upload a Fusion 360 design file for an archive."""
  2467. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2468. archive = result.scalar_one_or_none()
  2469. if not archive:
  2470. raise HTTPException(404, "Archive not found")
  2471. if not file.filename or not file.filename.endswith(".f3d"):
  2472. raise HTTPException(400, "File must be a .f3d file")
  2473. # Get archive directory and create f3d subdirectory
  2474. file_path = settings.base_dir / archive.file_path
  2475. archive_dir = file_path.parent
  2476. f3d_dir = archive_dir / "f3d"
  2477. f3d_dir.mkdir(exist_ok=True)
  2478. # Delete old F3D file if exists
  2479. if archive.f3d_path:
  2480. old_f3d_path = settings.base_dir / archive.f3d_path
  2481. if old_f3d_path.exists():
  2482. old_f3d_path.unlink()
  2483. # Save the F3D file - preserve original filename
  2484. f3d_filename = file.filename
  2485. f3d_path = f3d_dir / f3d_filename
  2486. content = await file.read()
  2487. f3d_path.write_bytes(content)
  2488. # Update archive with F3D path (relative to base_dir)
  2489. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  2490. await db.commit()
  2491. await db.refresh(archive)
  2492. return {
  2493. "status": "uploaded",
  2494. "f3d_path": archive.f3d_path,
  2495. "filename": f3d_filename,
  2496. }
  2497. @router.get("/{archive_id}/f3d")
  2498. async def download_f3d(
  2499. archive_id: int,
  2500. db: AsyncSession = Depends(get_db),
  2501. ):
  2502. """Download the Fusion 360 design file."""
  2503. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2504. archive = result.scalar_one_or_none()
  2505. if not archive:
  2506. raise HTTPException(404, "Archive not found")
  2507. if not archive.f3d_path:
  2508. raise HTTPException(404, "No F3D file attached to this archive")
  2509. f3d_path = settings.base_dir / archive.f3d_path
  2510. if not f3d_path.exists():
  2511. raise HTTPException(404, "F3D file not found on disk")
  2512. # Use the actual filename from the path
  2513. filename = f3d_path.name
  2514. return FileResponse(
  2515. path=f3d_path,
  2516. filename=filename,
  2517. media_type="application/octet-stream",
  2518. )
  2519. @router.delete("/{archive_id}/f3d")
  2520. async def delete_f3d(
  2521. archive_id: int,
  2522. db: AsyncSession = Depends(get_db),
  2523. ):
  2524. """Delete the Fusion 360 design file from an archive."""
  2525. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2526. archive = result.scalar_one_or_none()
  2527. if not archive:
  2528. raise HTTPException(404, "Archive not found")
  2529. if not archive.f3d_path:
  2530. raise HTTPException(404, "No F3D file attached to this archive")
  2531. # Delete the file
  2532. f3d_path = settings.base_dir / archive.f3d_path
  2533. if f3d_path.exists():
  2534. f3d_path.unlink()
  2535. # Clear the path in database
  2536. archive.f3d_path = None
  2537. await db.commit()
  2538. return {"status": "deleted"}