archives.py 121 KB

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