archives.py 112 KB

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