archives.py 123 KB

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