archives.py 123 KB

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