archives.py 127 KB

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