archives.py 122 KB

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