archives.py 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283
  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(
  994. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  995. )
  996. if files:
  997. break
  998. except Exception:
  999. continue
  1000. if not files:
  1001. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  1002. # Look for matching timelapse
  1003. matching_file = None
  1004. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  1005. # Strategy 1: Match by print name in filename
  1006. for f in mp4_files:
  1007. fname = f.get("name", "")
  1008. if base_name.lower() in fname.lower():
  1009. matching_file = f
  1010. break
  1011. # Strategy 2: Match by timestamp proximity
  1012. # Bambu timelapse filename uses the print START time (when recording began)
  1013. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  1014. import re
  1015. from datetime import datetime, timedelta
  1016. # Prefer started_at since video filename is the print start time
  1017. # Fall back to completed_at or created_at if started_at is not available
  1018. archive_start = archive.started_at
  1019. archive_end = archive.completed_at or archive.created_at
  1020. best_match = None
  1021. best_diff = timedelta(hours=24) # Max 24 hour difference
  1022. for f in mp4_files:
  1023. fname = f.get("name", "")
  1024. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  1025. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  1026. if match:
  1027. try:
  1028. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  1029. # Try multiple timezone offsets since printer timezone can vary
  1030. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  1031. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  1032. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  1033. # Check against start time (video filename = print start)
  1034. if archive_start:
  1035. diff = abs(adjusted_file_time - archive_start)
  1036. if diff < best_diff:
  1037. best_diff = diff
  1038. best_match = f
  1039. logger.debug(
  1040. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  1041. f"diff from start: {diff}"
  1042. )
  1043. # Also check against end time with a buffer
  1044. # (video timestamp should be BEFORE completion time)
  1045. if archive_end:
  1046. # The video timestamp should be within the print duration before completion
  1047. if adjusted_file_time < archive_end:
  1048. diff = archive_end - adjusted_file_time
  1049. # Reasonable print duration: up to 48 hours
  1050. if diff < timedelta(hours=48) and diff < best_diff:
  1051. best_diff = diff
  1052. best_match = f
  1053. logger.debug(
  1054. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  1055. f"diff: {diff}"
  1056. )
  1057. except ValueError:
  1058. continue
  1059. # Accept match within 4 hours (more lenient for timezone issues)
  1060. if best_match and best_diff < timedelta(hours=4):
  1061. matching_file = best_match
  1062. logger.info("Matched timelapse by timestamp: %s (diff: %s)", best_match.get("name"), best_diff)
  1063. # Strategy 3: Use file modification time from FTP listing
  1064. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  1065. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  1066. from datetime import datetime, timedelta
  1067. _archive_start = archive.started_at
  1068. archive_end = archive.completed_at or archive.created_at
  1069. best_match = None
  1070. best_diff = timedelta(hours=24)
  1071. for f in mp4_files:
  1072. mtime = f.get("mtime")
  1073. if mtime:
  1074. # Timelapse file should be modified during or shortly after the print
  1075. # The mtime should be close to completion time (video finishes when print ends)
  1076. if archive_end:
  1077. diff = abs(mtime - archive_end)
  1078. if diff < best_diff:
  1079. best_diff = diff
  1080. best_match = f
  1081. logger.debug(
  1082. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  1083. )
  1084. if best_match and best_diff < timedelta(hours=2):
  1085. matching_file = best_match
  1086. logger.info("Matched timelapse by file mtime: %s (diff: %s)", best_match.get("name"), best_diff)
  1087. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  1088. # This handles cases where printer clock is wrong or timezone issues exist
  1089. if not matching_file and len(mp4_files) == 1:
  1090. from datetime import datetime, timedelta
  1091. archive_completed = archive.completed_at or archive.created_at
  1092. if archive_completed:
  1093. time_since_completion = datetime.now() - archive_completed
  1094. # If archive was completed within the last hour, assume the single timelapse is for it
  1095. if time_since_completion < timedelta(hours=1):
  1096. matching_file = mp4_files[0]
  1097. logger.info("Using single timelapse file as fallback: %s", mp4_files[0].get("name"))
  1098. # Note: We intentionally don't use a "most recent file" fallback because
  1099. # we can't verify if timelapse was actually enabled for this print.
  1100. # Instead, return the list of available files for manual selection.
  1101. if not matching_file:
  1102. # Return available files for manual selection
  1103. available_files = [
  1104. {
  1105. "name": f.get("name"),
  1106. "path": f.get("path"),
  1107. "size": f.get("size"),
  1108. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  1109. }
  1110. for f in mp4_files
  1111. ]
  1112. # Sort by mtime descending (most recent first)
  1113. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  1114. return {
  1115. "status": "not_found",
  1116. "message": "No matching timelapse found - please select manually",
  1117. "available_files": available_files,
  1118. }
  1119. # Download the timelapse - use the full path from the file listing
  1120. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  1121. # Get FTP retry settings
  1122. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1123. if ftp_retry_enabled:
  1124. timelapse_data = await with_ftp_retry(
  1125. download_file_bytes_async,
  1126. printer.ip_address,
  1127. printer.access_code,
  1128. remote_path,
  1129. socket_timeout=ftp_timeout,
  1130. printer_model=printer.model,
  1131. max_retries=ftp_retry_count,
  1132. retry_delay=ftp_retry_delay,
  1133. operation_name=f"Download timelapse {matching_file['name']}",
  1134. )
  1135. else:
  1136. timelapse_data = await download_file_bytes_async(
  1137. printer.ip_address,
  1138. printer.access_code,
  1139. remote_path,
  1140. socket_timeout=ftp_timeout,
  1141. printer_model=printer.model,
  1142. )
  1143. if not timelapse_data:
  1144. raise HTTPException(500, "Failed to download timelapse")
  1145. # Attach timelapse to archive
  1146. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  1147. if not success:
  1148. raise HTTPException(500, "Failed to attach timelapse")
  1149. return {
  1150. "status": "attached",
  1151. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  1152. "filename": matching_file["name"],
  1153. }
  1154. @router.post("/{archive_id}/timelapse/select")
  1155. async def select_timelapse(
  1156. archive_id: int,
  1157. filename: str = Query(..., description="Timelapse filename to attach"),
  1158. db: AsyncSession = Depends(get_db),
  1159. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1160. ):
  1161. """Manually select a timelapse from the printer to attach."""
  1162. from backend.app.models.printer import Printer
  1163. from backend.app.services.bambu_ftp import (
  1164. download_file_bytes_async,
  1165. get_ftp_retry_settings,
  1166. list_files_async,
  1167. with_ftp_retry,
  1168. )
  1169. service = ArchiveService(db)
  1170. archive = await service.get_archive(archive_id)
  1171. if not archive:
  1172. raise HTTPException(404, "Archive not found")
  1173. if not archive.printer_id:
  1174. raise HTTPException(400, "Archive has no associated printer")
  1175. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1176. printer = result.scalar_one_or_none()
  1177. if not printer:
  1178. raise HTTPException(404, "Printer not found")
  1179. # Find the file on the printer
  1180. files = []
  1181. remote_path = None
  1182. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  1183. try:
  1184. files = await list_files_async(
  1185. printer.ip_address, printer.access_code, timelapse_dir, printer_model=printer.model
  1186. )
  1187. for f in files:
  1188. if f.get("name") == filename:
  1189. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  1190. break
  1191. if remote_path:
  1192. break
  1193. except Exception:
  1194. continue
  1195. if not remote_path:
  1196. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  1197. # Download and attach
  1198. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1199. if ftp_retry_enabled:
  1200. timelapse_data = await with_ftp_retry(
  1201. download_file_bytes_async,
  1202. printer.ip_address,
  1203. printer.access_code,
  1204. remote_path,
  1205. socket_timeout=ftp_timeout,
  1206. printer_model=printer.model,
  1207. max_retries=ftp_retry_count,
  1208. retry_delay=ftp_retry_delay,
  1209. operation_name=f"Download timelapse {filename}",
  1210. )
  1211. else:
  1212. timelapse_data = await download_file_bytes_async(
  1213. printer.ip_address,
  1214. printer.access_code,
  1215. remote_path,
  1216. socket_timeout=ftp_timeout,
  1217. printer_model=printer.model,
  1218. )
  1219. if not timelapse_data:
  1220. raise HTTPException(500, "Failed to download timelapse")
  1221. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1222. if not success:
  1223. raise HTTPException(500, "Failed to attach timelapse")
  1224. return {
  1225. "status": "attached",
  1226. "message": f"Timelapse '{filename}' attached successfully",
  1227. "filename": filename,
  1228. }
  1229. @router.post("/{archive_id}/timelapse/upload")
  1230. async def upload_timelapse(
  1231. archive_id: int,
  1232. file: UploadFile = File(...),
  1233. db: AsyncSession = Depends(get_db),
  1234. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1235. ):
  1236. """Manually upload a timelapse video to an archive."""
  1237. service = ArchiveService(db)
  1238. archive = await service.get_archive(archive_id)
  1239. if not archive:
  1240. raise HTTPException(404, "Archive not found")
  1241. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1242. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1243. content = await file.read()
  1244. success = await service.attach_timelapse(archive_id, content, file.filename)
  1245. if not success:
  1246. raise HTTPException(500, "Failed to attach timelapse")
  1247. return {"status": "attached", "filename": file.filename}
  1248. @router.get("/{archive_id}/timelapse/info")
  1249. async def get_timelapse_info(
  1250. archive_id: int,
  1251. db: AsyncSession = Depends(get_db),
  1252. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1253. ):
  1254. """Get timelapse video metadata for editor."""
  1255. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1256. from backend.app.services.timelapse_processor import TimelapseProcessor
  1257. service = ArchiveService(db)
  1258. archive = await service.get_archive(archive_id)
  1259. if not archive or not archive.timelapse_path:
  1260. raise HTTPException(404, "Timelapse not found")
  1261. timelapse_path = settings.base_dir / archive.timelapse_path
  1262. if not timelapse_path.exists():
  1263. raise HTTPException(404, "Timelapse file not found")
  1264. try:
  1265. processor = TimelapseProcessor(timelapse_path)
  1266. info = await processor.get_info()
  1267. return TimelapseInfoResponse(**info)
  1268. except Exception as e:
  1269. logger.error("Failed to get timelapse info: %s", e)
  1270. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1271. @router.get("/{archive_id}/timelapse/thumbnails")
  1272. async def get_timelapse_thumbnails(
  1273. archive_id: int,
  1274. count: int = Query(10, ge=1, le=30),
  1275. width: int = Query(160, ge=80, le=320),
  1276. db: AsyncSession = Depends(get_db),
  1277. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1278. ):
  1279. """Generate timeline thumbnail frames for visual scrubbing."""
  1280. import base64
  1281. from backend.app.schemas.timelapse import ThumbnailResponse
  1282. from backend.app.services.timelapse_processor import TimelapseProcessor
  1283. service = ArchiveService(db)
  1284. archive = await service.get_archive(archive_id)
  1285. if not archive or not archive.timelapse_path:
  1286. raise HTTPException(404, "Timelapse not found")
  1287. timelapse_path = settings.base_dir / archive.timelapse_path
  1288. if not timelapse_path.exists():
  1289. raise HTTPException(404, "Timelapse file not found")
  1290. try:
  1291. processor = TimelapseProcessor(timelapse_path)
  1292. thumbnails = await processor.generate_thumbnails(count, width)
  1293. return ThumbnailResponse(
  1294. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1295. timestamps=[ts for ts, _ in thumbnails],
  1296. )
  1297. except Exception as e:
  1298. logger.error("Failed to generate thumbnails: %s", e)
  1299. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1300. @router.post("/{archive_id}/timelapse/process")
  1301. async def process_timelapse(
  1302. archive_id: int,
  1303. trim_start: float = Form(0),
  1304. trim_end: float = Form(None),
  1305. speed: float = Form(1.0),
  1306. save_mode: str = Form("new"),
  1307. output_filename: str = Form(None),
  1308. audio: UploadFile = File(None),
  1309. db: AsyncSession = Depends(get_db),
  1310. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1311. ):
  1312. """Process timelapse with trim, speed, and optional audio overlay."""
  1313. import shutil
  1314. import tempfile
  1315. from backend.app.schemas.timelapse import ProcessResponse
  1316. from backend.app.services.timelapse_processor import TimelapseProcessor
  1317. # Validate speed
  1318. if not 0.25 <= speed <= 4.0:
  1319. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1320. if save_mode not in ("replace", "new"):
  1321. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1322. service = ArchiveService(db)
  1323. archive = await service.get_archive(archive_id)
  1324. if not archive or not archive.timelapse_path:
  1325. raise HTTPException(404, "Timelapse not found")
  1326. timelapse_path = settings.base_dir / archive.timelapse_path
  1327. if not timelapse_path.exists():
  1328. raise HTTPException(404, "Timelapse file not found")
  1329. archive_dir = timelapse_path.parent
  1330. # Handle audio file
  1331. audio_temp_path = None
  1332. if audio and audio.filename:
  1333. # Validate audio file extension
  1334. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1335. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1336. audio_content = await audio.read()
  1337. # Extract and validate suffix to prevent path injection
  1338. suffix = Path(audio.filename).suffix.lower()
  1339. if suffix not in (".mp3", ".wav", ".m4a", ".aac", ".ogg"):
  1340. raise HTTPException(400, "Invalid audio file extension")
  1341. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1342. audio_temp_path.write_bytes(audio_content)
  1343. try:
  1344. processor = TimelapseProcessor(timelapse_path)
  1345. # Determine output path
  1346. if save_mode == "replace":
  1347. # Process to temp file first, then replace
  1348. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1349. output_path = temp_output
  1350. else:
  1351. # Save as new file alongside original
  1352. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1353. # Sanitize filename - remove path separators and traversal sequences
  1354. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1355. # Prevent path traversal
  1356. if ".." in filename or not filename or filename.startswith("."):
  1357. filename = f"timelapse_{archive_id}_edited"
  1358. if not filename.endswith(".mp4"):
  1359. filename += ".mp4"
  1360. output_path = archive_dir / filename
  1361. success = await processor.process(
  1362. output_path=output_path,
  1363. trim_start=trim_start,
  1364. trim_end=trim_end,
  1365. speed=speed,
  1366. audio_path=audio_temp_path,
  1367. )
  1368. if not success:
  1369. raise HTTPException(500, "Video processing failed")
  1370. # Handle save mode
  1371. if save_mode == "replace":
  1372. # Replace original file
  1373. shutil.move(str(output_path), str(timelapse_path))
  1374. final_path = archive.timelapse_path
  1375. message = "Timelapse replaced successfully"
  1376. else:
  1377. final_path = str(output_path.relative_to(settings.base_dir))
  1378. message = f"Saved as {output_path.name}"
  1379. return ProcessResponse(
  1380. status="completed",
  1381. output_path=final_path,
  1382. message=message,
  1383. )
  1384. except HTTPException:
  1385. raise
  1386. except Exception as e:
  1387. logger.error("Timelapse processing failed: %s", e)
  1388. raise HTTPException(500, f"Processing failed: {str(e)}")
  1389. finally:
  1390. # Cleanup temp audio file
  1391. if audio_temp_path and audio_temp_path.exists():
  1392. audio_temp_path.unlink()
  1393. # ============================================
  1394. # Photo Endpoints
  1395. # ============================================
  1396. @router.post("/{archive_id}/photos")
  1397. async def upload_photo(
  1398. archive_id: int,
  1399. file: UploadFile = File(...),
  1400. db: AsyncSession = Depends(get_db),
  1401. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  1402. ):
  1403. """Upload a photo of the printed result."""
  1404. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1405. archive = result.scalar_one_or_none()
  1406. if not archive:
  1407. raise HTTPException(404, "Archive not found")
  1408. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1409. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1410. # Get archive directory
  1411. file_path = settings.base_dir / archive.file_path
  1412. archive_dir = file_path.parent
  1413. photos_dir = archive_dir / "photos"
  1414. photos_dir.mkdir(exist_ok=True)
  1415. # Generate unique filename
  1416. import uuid
  1417. ext = Path(file.filename).suffix.lower()
  1418. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1419. photo_path = photos_dir / photo_filename
  1420. # Save file
  1421. content = await file.read()
  1422. photo_path.write_bytes(content)
  1423. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1424. photos = list(archive.photos or [])
  1425. photos.append(photo_filename)
  1426. archive.photos = photos
  1427. await db.commit()
  1428. await db.refresh(archive)
  1429. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1430. @router.get("/{archive_id}/photos/{filename}")
  1431. async def get_photo(
  1432. archive_id: int,
  1433. filename: str,
  1434. db: AsyncSession = Depends(get_db),
  1435. ):
  1436. """Get a specific photo.
  1437. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  1438. """
  1439. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1440. archive = result.scalar_one_or_none()
  1441. if not archive:
  1442. raise HTTPException(404, "Archive not found")
  1443. file_path = settings.base_dir / archive.file_path
  1444. photo_path = file_path.parent / "photos" / filename
  1445. if not photo_path.exists():
  1446. raise HTTPException(404, "Photo not found")
  1447. # Determine media type
  1448. ext = Path(filename).suffix.lower()
  1449. media_types = {
  1450. ".jpg": "image/jpeg",
  1451. ".jpeg": "image/jpeg",
  1452. ".png": "image/png",
  1453. ".webp": "image/webp",
  1454. }
  1455. media_type = media_types.get(ext, "image/jpeg")
  1456. return FileResponse(path=photo_path, media_type=media_type)
  1457. @router.delete("/{archive_id}/photos/{filename}")
  1458. async def delete_photo(
  1459. archive_id: int,
  1460. filename: str,
  1461. db: AsyncSession = Depends(get_db),
  1462. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  1463. ):
  1464. """Delete a photo."""
  1465. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1466. archive = result.scalar_one_or_none()
  1467. if not archive:
  1468. raise HTTPException(404, "Archive not found")
  1469. if not archive.photos or filename not in archive.photos:
  1470. raise HTTPException(404, "Photo not found")
  1471. # Delete file
  1472. file_path = settings.base_dir / archive.file_path
  1473. photo_path = file_path.parent / "photos" / filename
  1474. if photo_path.exists():
  1475. photo_path.unlink()
  1476. # Update archive photos list
  1477. photos = [p for p in archive.photos if p != filename]
  1478. archive.photos = photos if photos else None
  1479. await db.commit()
  1480. return {"status": "deleted", "photos": archive.photos}
  1481. # ============================================
  1482. # QR Code Endpoint
  1483. # ============================================
  1484. @router.get("/{archive_id}/qrcode")
  1485. async def get_qrcode(
  1486. archive_id: int,
  1487. request: Request,
  1488. size: int = 200,
  1489. db: AsyncSession = Depends(get_db),
  1490. ):
  1491. """Generate a QR code that links to this archive.
  1492. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  1493. """
  1494. try:
  1495. import qrcode
  1496. from PIL import Image as PILImage
  1497. except ImportError:
  1498. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1499. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1500. archive = result.scalar_one_or_none()
  1501. if not archive:
  1502. raise HTTPException(404, "Archive not found")
  1503. # Build URL to archive download
  1504. base_url = str(request.base_url).rstrip("/")
  1505. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1506. # Generate QR code
  1507. qr = qrcode.QRCode(
  1508. version=1,
  1509. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1510. box_size=10,
  1511. border=2,
  1512. )
  1513. qr.add_data(archive_url)
  1514. qr.make(fit=True)
  1515. img = qr.make_image(fill_color="black", back_color="white")
  1516. # Convert to PIL Image for resizing
  1517. pil_img = img.get_image()
  1518. # Resize if needed
  1519. if size != 200:
  1520. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1521. # Convert to bytes
  1522. buffer = io.BytesIO()
  1523. pil_img.save(buffer, format="PNG")
  1524. buffer.seek(0)
  1525. return Response(
  1526. content=buffer.getvalue(),
  1527. media_type="image/png",
  1528. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1529. )
  1530. @router.get("/{archive_id}/capabilities")
  1531. async def get_archive_capabilities(
  1532. archive_id: int,
  1533. db: AsyncSession = Depends(get_db),
  1534. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1535. ):
  1536. """Check what viewing capabilities are available for this 3MF file."""
  1537. import defusedxml.ElementTree as ET
  1538. service = ArchiveService(db)
  1539. archive = await service.get_archive(archive_id)
  1540. if not archive:
  1541. raise HTTPException(404, "Archive not found")
  1542. file_path = settings.base_dir / archive.file_path
  1543. if not file_path.exists():
  1544. raise HTTPException(404, "File not found")
  1545. has_model = False
  1546. has_gcode = False
  1547. has_source = False
  1548. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1549. filament_colors: list[str] = []
  1550. # Check if source 3MF exists - this is where actual mesh data typically lives
  1551. source_path = None
  1552. if archive.source_3mf_path:
  1553. source_path = settings.base_dir / archive.source_3mf_path
  1554. if source_path.exists():
  1555. has_source = True
  1556. # Helper function to check for mesh data and extract colors from a 3MF file
  1557. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1558. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1559. found_mesh = False
  1560. colors: list[str] = []
  1561. volume = {"x": 256, "y": 256, "z": 256}
  1562. try:
  1563. with zipfile.ZipFile(zf_path, "r") as zf:
  1564. names = zf.namelist()
  1565. # Check for 3D model - look for actual mesh data
  1566. for name in names:
  1567. if name.endswith(".model"):
  1568. try:
  1569. content = zf.read(name).decode("utf-8")
  1570. if "<vertex" in content or "<mesh" in content:
  1571. found_mesh = True
  1572. break
  1573. except (KeyError, UnicodeDecodeError):
  1574. pass # Skip unreadable .model entries in archive
  1575. # Extract filament colors from project_settings.config
  1576. if "Metadata/project_settings.config" in names:
  1577. try:
  1578. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1579. config_data = json.loads(config_content)
  1580. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1581. printable_area = config_data.get("printable_area", [])
  1582. if printable_area and len(printable_area) >= 3:
  1583. max_x = 0
  1584. max_y = 0
  1585. for coord in printable_area:
  1586. if "x" in coord:
  1587. parts = coord.split("x")
  1588. if len(parts) == 2:
  1589. try:
  1590. x, y = int(parts[0]), int(parts[1])
  1591. max_x = max(max_x, x)
  1592. max_y = max(max_y, y)
  1593. except ValueError:
  1594. pass # Skip non-numeric printable_area coordinate
  1595. if max_x > 0 and max_y > 0:
  1596. volume["x"] = max_x
  1597. volume["y"] = max_y
  1598. # Parse printable_height
  1599. printable_height = config_data.get("printable_height")
  1600. if printable_height:
  1601. try:
  1602. volume["z"] = int(printable_height)
  1603. except (ValueError, TypeError):
  1604. pass # Skip unparseable printable_height value
  1605. # Extract filament colors
  1606. raw_colors = config_data.get("filament_colour", [])
  1607. if raw_colors:
  1608. for color in raw_colors:
  1609. if color and isinstance(color, str):
  1610. colors.append(color)
  1611. except (json.JSONDecodeError, KeyError, ValueError, TypeError):
  1612. pass # Skip malformed project_settings.config
  1613. except zipfile.BadZipFile:
  1614. pass # File is not a valid zip/3MF archive
  1615. return found_mesh, colors, volume
  1616. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1617. if has_source and source_path:
  1618. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1619. if source_has_mesh:
  1620. has_model = True
  1621. if source_colors:
  1622. filament_colors = source_colors
  1623. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1624. build_volume = source_volume
  1625. try:
  1626. with zipfile.ZipFile(file_path, "r") as zf:
  1627. names = zf.namelist()
  1628. # Check for G-code in the sliced file
  1629. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1630. # Check for 3D model in sliced file (fallback if no source)
  1631. if not has_model:
  1632. for name in names:
  1633. if name.endswith(".model"):
  1634. try:
  1635. content = zf.read(name).decode("utf-8")
  1636. if "<vertex" in content or "<mesh" in content:
  1637. has_model = True
  1638. break
  1639. except (KeyError, UnicodeDecodeError):
  1640. pass # Skip unreadable .model entries in archive
  1641. # Extract filament colors from slice_info.config (for gcode preview)
  1642. # These are the actual filaments used in the print, indexed by tool/extruder
  1643. slice_colors: list[str] = []
  1644. if "Metadata/slice_info.config" in names:
  1645. try:
  1646. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1647. root = ET.fromstring(slice_content)
  1648. filaments = root.findall(".//filament")
  1649. filament_map: dict[int, str] = {}
  1650. for f in filaments:
  1651. fid = f.get("id")
  1652. fcolor = f.get("color")
  1653. used_g = f.get("used_g", "0")
  1654. try:
  1655. used_amount = float(used_g)
  1656. except (ValueError, TypeError):
  1657. used_amount = 0
  1658. if fid is not None and fcolor:
  1659. try:
  1660. tool_id = int(fid) - 1
  1661. if tool_id >= 0 and used_amount > 0:
  1662. filament_map[tool_id] = fcolor
  1663. except ValueError:
  1664. pass # Skip filament entry with non-numeric ID
  1665. if filament_map:
  1666. max_tool = max(filament_map.keys())
  1667. for i in range(max_tool + 1):
  1668. slice_colors.append(filament_map.get(i, "#00AE42"))
  1669. except (KeyError, ValueError, ET.ParseError, UnicodeDecodeError):
  1670. pass # Skip malformed slice_info.config XML
  1671. # Use slice_info colors if we don't have colors from source yet
  1672. if not filament_colors and slice_colors:
  1673. filament_colors = slice_colors
  1674. # Extract build volume from sliced file if not already set from source
  1675. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1676. if "Metadata/project_settings.config" in names:
  1677. try:
  1678. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1679. config_data = json.loads(config_content)
  1680. printable_area = config_data.get("printable_area", [])
  1681. if printable_area and len(printable_area) >= 3:
  1682. max_x = 0
  1683. max_y = 0
  1684. for coord in printable_area:
  1685. if "x" in coord:
  1686. parts = coord.split("x")
  1687. if len(parts) == 2:
  1688. try:
  1689. x, y = int(parts[0]), int(parts[1])
  1690. max_x = max(max_x, x)
  1691. max_y = max(max_y, y)
  1692. except ValueError:
  1693. pass # Skip non-numeric printable_area coordinate
  1694. if max_x > 0 and max_y > 0:
  1695. build_volume["x"] = max_x
  1696. build_volume["y"] = max_y
  1697. printable_height = config_data.get("printable_height")
  1698. if printable_height:
  1699. try:
  1700. build_volume["z"] = int(printable_height)
  1701. except (ValueError, TypeError):
  1702. pass # Skip unparseable printable_height value
  1703. # Fallback colors from project_settings if still empty
  1704. if not filament_colors:
  1705. raw_colors = config_data.get("filament_colour", [])
  1706. if raw_colors:
  1707. for color in raw_colors:
  1708. if color and isinstance(color, str):
  1709. filament_colors.append(color)
  1710. except (json.JSONDecodeError, KeyError, ValueError, TypeError):
  1711. pass # Skip malformed project_settings.config
  1712. except zipfile.BadZipFile:
  1713. raise HTTPException(400, "Invalid 3MF file")
  1714. return {
  1715. "has_model": has_model,
  1716. "has_gcode": has_gcode,
  1717. "has_source": has_source,
  1718. "build_volume": build_volume,
  1719. "filament_colors": filament_colors,
  1720. }
  1721. @router.get("/{archive_id}/gcode")
  1722. async def get_gcode(
  1723. archive_id: int,
  1724. db: AsyncSession = Depends(get_db),
  1725. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1726. ):
  1727. """Extract and return G-code from the 3MF file."""
  1728. service = ArchiveService(db)
  1729. archive = await service.get_archive(archive_id)
  1730. if not archive:
  1731. raise HTTPException(404, "Archive not found")
  1732. file_path = settings.base_dir / archive.file_path
  1733. if not file_path.exists():
  1734. raise HTTPException(404, "File not found")
  1735. try:
  1736. with zipfile.ZipFile(file_path, "r") as zf:
  1737. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1738. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1739. if not gcode_files:
  1740. raise HTTPException(
  1741. 404,
  1742. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1743. )
  1744. # Get the first plate's G-code (usually plate_1.gcode)
  1745. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1746. return Response(content=gcode_content, media_type="text/plain")
  1747. except zipfile.BadZipFile:
  1748. raise HTTPException(400, "Invalid 3MF file")
  1749. except HTTPException:
  1750. raise
  1751. except Exception as e:
  1752. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1753. @router.get("/{archive_id}/plate-preview")
  1754. async def get_plate_preview(
  1755. archive_id: int,
  1756. db: AsyncSession = Depends(get_db),
  1757. ):
  1758. """Get the plate preview image from the 3MF file.
  1759. Returns the slicer-generated plate thumbnail which shows the model
  1760. with correct colors and positioning.
  1761. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  1762. """
  1763. service = ArchiveService(db)
  1764. archive = await service.get_archive(archive_id)
  1765. if not archive:
  1766. raise HTTPException(404, "Archive not found")
  1767. file_path = settings.base_dir / archive.file_path
  1768. if not file_path.exists():
  1769. raise HTTPException(404, "File not found")
  1770. try:
  1771. with zipfile.ZipFile(file_path, "r") as zf:
  1772. names = zf.namelist()
  1773. # Try to find plate preview images in order of preference
  1774. # First look for the specific plate being printed (check slice_info for plate index)
  1775. plate_num = 1
  1776. if "Metadata/slice_info.config" in names:
  1777. try:
  1778. import defusedxml.ElementTree as ET
  1779. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1780. root = ET.fromstring(slice_content)
  1781. plate_elem = root.find(".//plate/metadata[@key='index']")
  1782. if plate_elem is not None:
  1783. plate_num = int(plate_elem.get("value", "1"))
  1784. except (KeyError, ValueError, ET.ParseError, UnicodeDecodeError):
  1785. pass # Default plate_num=1 if slice_info is missing or malformed
  1786. # Try plate-specific image first, then fall back to plate_1
  1787. preview_paths = [
  1788. f"Metadata/plate_{plate_num}.png",
  1789. "Metadata/plate_1.png",
  1790. "Metadata/thumbnail.png",
  1791. ]
  1792. for preview_path in preview_paths:
  1793. if preview_path in names:
  1794. image_data = zf.read(preview_path)
  1795. return Response(content=image_data, media_type="image/png")
  1796. # If no plate image, try any PNG in Metadata
  1797. for name in names:
  1798. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1799. image_data = zf.read(name)
  1800. return Response(content=image_data, media_type="image/png")
  1801. raise HTTPException(404, "No plate preview found in 3MF file")
  1802. except zipfile.BadZipFile:
  1803. raise HTTPException(400, "Invalid 3MF file")
  1804. except HTTPException:
  1805. raise
  1806. except Exception as e:
  1807. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1808. @router.post("/upload")
  1809. async def upload_archive(
  1810. file: UploadFile = File(...),
  1811. printer_id: int | None = None,
  1812. db: AsyncSession = Depends(get_db),
  1813. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  1814. ):
  1815. """Manually upload a 3MF file to archive."""
  1816. if not file.filename or not file.filename.endswith(".3mf"):
  1817. raise HTTPException(400, "File must be a .3mf file")
  1818. # Save uploaded file temporarily
  1819. temp_path = settings.archive_dir / "temp" / file.filename
  1820. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1821. try:
  1822. content = await file.read()
  1823. temp_path.write_bytes(content)
  1824. service = ArchiveService(db)
  1825. archive = await service.archive_print(
  1826. printer_id=printer_id,
  1827. source_file=temp_path,
  1828. created_by_id=current_user.id if current_user else None,
  1829. )
  1830. if not archive:
  1831. raise HTTPException(400, "Failed to archive file")
  1832. return ArchiveResponse.model_validate(archive)
  1833. finally:
  1834. if temp_path.exists():
  1835. temp_path.unlink()
  1836. @router.post("/upload-bulk")
  1837. async def upload_archives_bulk(
  1838. files: list[UploadFile] = File(...),
  1839. printer_id: int | None = None,
  1840. db: AsyncSession = Depends(get_db),
  1841. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  1842. ):
  1843. """Bulk upload multiple 3MF files to archive."""
  1844. results = []
  1845. errors = []
  1846. for file in files:
  1847. if not file.filename or not file.filename.endswith(".3mf"):
  1848. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1849. continue
  1850. temp_path = settings.archive_dir / "temp" / file.filename
  1851. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1852. try:
  1853. content = await file.read()
  1854. temp_path.write_bytes(content)
  1855. service = ArchiveService(db)
  1856. archive = await service.archive_print(
  1857. printer_id=printer_id,
  1858. source_file=temp_path,
  1859. created_by_id=current_user.id if current_user else None,
  1860. )
  1861. if archive:
  1862. results.append(
  1863. {
  1864. "filename": file.filename,
  1865. "id": archive.id,
  1866. "status": "success",
  1867. }
  1868. )
  1869. else:
  1870. errors.append({"filename": file.filename, "error": "Failed to process"})
  1871. except Exception as e:
  1872. logger.exception("Failed to upload archive %s: %s", file.filename, e)
  1873. errors.append({"filename": file.filename, "error": "Failed to process file"})
  1874. finally:
  1875. if temp_path.exists():
  1876. temp_path.unlink()
  1877. return {
  1878. "uploaded": len(results),
  1879. "failed": len(errors),
  1880. "results": results,
  1881. "errors": errors,
  1882. }
  1883. @router.get("/{archive_id}/plates")
  1884. async def get_archive_plates(
  1885. archive_id: int,
  1886. db: AsyncSession = Depends(get_db),
  1887. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1888. ):
  1889. """Get available plates from a multi-plate 3MF archive.
  1890. Returns a list of plates with their index, name, thumbnail availability,
  1891. and filament requirements. For single-plate exports, returns a single plate.
  1892. """
  1893. import re
  1894. import defusedxml.ElementTree as ET
  1895. service = ArchiveService(db)
  1896. archive = await service.get_archive(archive_id)
  1897. if not archive:
  1898. raise HTTPException(404, "Archive not found")
  1899. file_path = settings.base_dir / archive.file_path
  1900. if not file_path.exists():
  1901. raise HTTPException(404, "Archive file not found")
  1902. plates = []
  1903. try:
  1904. with zipfile.ZipFile(file_path, "r") as zf:
  1905. namelist = zf.namelist()
  1906. # Find all plate gcode files to determine available plates
  1907. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1908. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  1909. plate_indices: list[int] = []
  1910. if gcode_files:
  1911. # Extract plate indices from gcode filenames
  1912. for gf in gcode_files:
  1913. # "Metadata/plate_5.gcode" -> 5
  1914. try:
  1915. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1916. plate_indices.append(int(plate_str))
  1917. except ValueError:
  1918. pass # Skip gcode file with non-numeric plate index
  1919. else:
  1920. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  1921. plate_png_files = [
  1922. n
  1923. for n in namelist
  1924. if n.startswith("Metadata/plate_")
  1925. and n.endswith(".png")
  1926. and "_small" not in n
  1927. and "no_light" not in n
  1928. ]
  1929. plate_name_candidates = plate_json_files + plate_png_files
  1930. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  1931. seen_indices: set[int] = set()
  1932. for name in plate_name_candidates:
  1933. match = plate_re.match(name)
  1934. if match:
  1935. try:
  1936. index = int(match.group(1))
  1937. except ValueError:
  1938. continue
  1939. if index in seen_indices:
  1940. continue
  1941. seen_indices.add(index)
  1942. plate_indices.append(index)
  1943. if not plate_indices:
  1944. # No plate metadata found
  1945. return {
  1946. "archive_id": archive_id,
  1947. "filename": archive.filename,
  1948. "plates": [],
  1949. "is_multi_plate": False,
  1950. }
  1951. plate_indices.sort()
  1952. # Parse model_settings.config for plate names + object assignments
  1953. # Plate names are stored with plater_id and plater_name keys
  1954. plate_names = {} # plater_id -> name
  1955. plate_object_ids: dict[int, list[str]] = {}
  1956. object_names_by_id: dict[str, str] = {}
  1957. if "Metadata/model_settings.config" in namelist:
  1958. try:
  1959. model_content = zf.read("Metadata/model_settings.config").decode()
  1960. model_root = ET.fromstring(model_content)
  1961. # Build object ID -> name map
  1962. for obj_elem in model_root.findall(".//object"):
  1963. obj_id = obj_elem.get("id")
  1964. if not obj_id:
  1965. continue
  1966. name_meta = obj_elem.find("metadata[@key='name']")
  1967. obj_name = name_meta.get("value") if name_meta is not None else None
  1968. if obj_name:
  1969. object_names_by_id[obj_id] = obj_name
  1970. for plate_elem in model_root.findall(".//plate"):
  1971. plater_id = None
  1972. plater_name = None
  1973. for meta in plate_elem.findall("metadata"):
  1974. key = meta.get("key")
  1975. value = meta.get("value")
  1976. if key == "plater_id" and value:
  1977. try:
  1978. plater_id = int(value)
  1979. except ValueError:
  1980. pass # Skip plate with non-numeric plater_id
  1981. elif key == "plater_name" and value:
  1982. plater_name = value.strip()
  1983. if plater_id is not None and plater_name:
  1984. plate_names[plater_id] = plater_name
  1985. if plater_id is not None:
  1986. for instance_elem in plate_elem.findall("model_instance"):
  1987. for inst_meta in instance_elem.findall("metadata"):
  1988. if inst_meta.get("key") == "object_id":
  1989. obj_id = inst_meta.get("value")
  1990. if not obj_id:
  1991. continue
  1992. plate_object_ids.setdefault(plater_id, [])
  1993. if obj_id not in plate_object_ids[plater_id]:
  1994. plate_object_ids[plater_id].append(obj_id)
  1995. except (KeyError, ValueError, ET.ParseError, UnicodeDecodeError):
  1996. pass # model_settings.config parsing is optional
  1997. # Parse slice_info.config for plate metadata
  1998. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  1999. if "Metadata/slice_info.config" in namelist:
  2000. content = zf.read("Metadata/slice_info.config").decode()
  2001. root = ET.fromstring(content)
  2002. for plate_elem in root.findall(".//plate"):
  2003. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  2004. # Get plate index from metadata
  2005. plate_index = None
  2006. for meta in plate_elem.findall("metadata"):
  2007. key = meta.get("key")
  2008. value = meta.get("value")
  2009. if key == "index" and value:
  2010. try:
  2011. plate_index = int(value)
  2012. except ValueError:
  2013. pass # Skip plate with non-numeric index
  2014. elif key == "prediction" and value:
  2015. try:
  2016. plate_info["prediction"] = int(value)
  2017. except ValueError:
  2018. pass # Skip non-numeric print time prediction
  2019. elif key == "weight" and value:
  2020. try:
  2021. plate_info["weight"] = float(value)
  2022. except ValueError:
  2023. pass # Skip non-numeric filament weight
  2024. # Get filaments used in this plate
  2025. for filament_elem in plate_elem.findall("filament"):
  2026. filament_id = filament_elem.get("id")
  2027. filament_type = filament_elem.get("type", "")
  2028. filament_color = filament_elem.get("color", "")
  2029. used_g = filament_elem.get("used_g", "0")
  2030. used_m = filament_elem.get("used_m", "0")
  2031. try:
  2032. used_grams = float(used_g)
  2033. except (ValueError, TypeError):
  2034. used_grams = 0
  2035. if used_grams > 0 and filament_id:
  2036. plate_info["filaments"].append(
  2037. {
  2038. "slot_id": int(filament_id),
  2039. "type": filament_type,
  2040. "color": filament_color,
  2041. "used_grams": round(used_grams, 1),
  2042. "used_meters": float(used_m) if used_m else 0,
  2043. }
  2044. )
  2045. # Sort filaments by slot ID
  2046. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  2047. # Collect all object names on this plate
  2048. for obj_elem in plate_elem.findall("object"):
  2049. obj_name = obj_elem.get("name")
  2050. if obj_name and obj_name not in plate_info["objects"]:
  2051. plate_info["objects"].append(obj_name)
  2052. # Set plate name: prefer custom name from model_settings.config,
  2053. # fall back to first object name if no custom name was set
  2054. if plate_index is not None:
  2055. custom_name = plate_names.get(plate_index)
  2056. if custom_name:
  2057. plate_info["name"] = custom_name
  2058. else:
  2059. # Fall back to first object name as hint
  2060. if plate_info["objects"]:
  2061. plate_info["name"] = plate_info["objects"][0]
  2062. plate_metadata[plate_index] = plate_info
  2063. # Parse plate_*.json for object lists when slice_info is missing
  2064. plate_json_objects: dict[int, list[str]] = {}
  2065. for name in namelist:
  2066. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  2067. if not match:
  2068. continue
  2069. try:
  2070. plate_index = int(match.group(1))
  2071. except ValueError:
  2072. continue
  2073. try:
  2074. payload = json.loads(zf.read(name).decode())
  2075. bbox_objects = payload.get("bbox_objects", [])
  2076. names = []
  2077. for obj in bbox_objects:
  2078. obj_name = obj.get("name") if isinstance(obj, dict) else None
  2079. if obj_name and obj_name not in names:
  2080. names.append(obj_name)
  2081. if names:
  2082. plate_json_objects[plate_index] = names
  2083. except (json.JSONDecodeError, KeyError, ValueError, UnicodeDecodeError):
  2084. continue
  2085. # Build plate list
  2086. for idx in plate_indices:
  2087. meta = plate_metadata.get(idx, {})
  2088. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  2089. objects = meta.get("objects", [])
  2090. if not objects:
  2091. objects = plate_json_objects.get(idx, [])
  2092. if not objects and plate_object_ids.get(idx):
  2093. objects = [
  2094. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  2095. ]
  2096. plate_name = meta.get("name")
  2097. if not plate_name:
  2098. plate_name = plate_names.get(idx)
  2099. if not plate_name and objects:
  2100. plate_name = objects[0]
  2101. plates.append(
  2102. {
  2103. "index": idx,
  2104. "name": plate_name,
  2105. "objects": objects,
  2106. "object_count": len(objects),
  2107. "has_thumbnail": has_thumbnail,
  2108. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  2109. if has_thumbnail
  2110. else None,
  2111. "print_time_seconds": meta.get("prediction"),
  2112. "filament_used_grams": meta.get("weight"),
  2113. "filaments": meta.get("filaments", []),
  2114. }
  2115. )
  2116. except (KeyError, ValueError, zipfile.BadZipFile, ET.ParseError, UnicodeDecodeError) as e:
  2117. logger.warning("Failed to parse plates from archive %s: %s", archive_id, e)
  2118. return {
  2119. "archive_id": archive_id,
  2120. "filename": archive.filename,
  2121. "plates": plates,
  2122. "is_multi_plate": len(plates) > 1,
  2123. }
  2124. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  2125. async def get_plate_thumbnail(
  2126. archive_id: int,
  2127. plate_index: int,
  2128. db: AsyncSession = Depends(get_db),
  2129. ):
  2130. """Get the thumbnail image for a specific plate.
  2131. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  2132. """
  2133. service = ArchiveService(db)
  2134. archive = await service.get_archive(archive_id)
  2135. if not archive:
  2136. raise HTTPException(404, "Archive not found")
  2137. file_path = settings.base_dir / archive.file_path
  2138. if not file_path.exists():
  2139. raise HTTPException(404, "Archive file not found")
  2140. try:
  2141. with zipfile.ZipFile(file_path, "r") as zf:
  2142. thumb_path = f"Metadata/plate_{plate_index}.png"
  2143. if thumb_path in zf.namelist():
  2144. data = zf.read(thumb_path)
  2145. return Response(content=data, media_type="image/png")
  2146. except (zipfile.BadZipFile, KeyError, OSError):
  2147. pass # Fall through to 404 if archive is unreadable or thumbnail missing
  2148. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  2149. @router.get("/{archive_id}/filament-requirements")
  2150. async def get_filament_requirements(
  2151. archive_id: int,
  2152. plate_id: int | None = None,
  2153. db: AsyncSession = Depends(get_db),
  2154. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2155. ):
  2156. """Get filament requirements from the archived 3MF file.
  2157. Returns the filaments used in this print with their slot IDs, types, colors,
  2158. and usage amounts. This can be compared with current AMS state before reprinting.
  2159. Args:
  2160. archive_id: The archive ID
  2161. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  2162. """
  2163. import defusedxml.ElementTree as ET
  2164. service = ArchiveService(db)
  2165. archive = await service.get_archive(archive_id)
  2166. if not archive:
  2167. raise HTTPException(404, "Archive not found")
  2168. file_path = settings.base_dir / archive.file_path
  2169. if not file_path.exists():
  2170. raise HTTPException(404, "Archive file not found")
  2171. filaments = []
  2172. try:
  2173. with zipfile.ZipFile(file_path, "r") as zf:
  2174. # Parse slice_info.config for filament requirements
  2175. if "Metadata/slice_info.config" in zf.namelist():
  2176. content = zf.read("Metadata/slice_info.config").decode()
  2177. root = ET.fromstring(content)
  2178. # If plate_id is specified, find filaments for that specific plate
  2179. if plate_id is not None:
  2180. # Find the plate element with matching index
  2181. for plate_elem in root.findall(".//plate"):
  2182. plate_index = None
  2183. for meta in plate_elem.findall("metadata"):
  2184. if meta.get("key") == "index":
  2185. try:
  2186. plate_index = int(meta.get("value", "0"))
  2187. except ValueError:
  2188. pass # Skip plate with non-numeric index metadata
  2189. break
  2190. if plate_index == plate_id:
  2191. # Extract filaments from this plate element
  2192. for filament_elem in plate_elem.findall("filament"):
  2193. filament_id = filament_elem.get("id")
  2194. filament_type = filament_elem.get("type", "")
  2195. filament_color = filament_elem.get("color", "")
  2196. used_g = filament_elem.get("used_g", "0")
  2197. used_m = filament_elem.get("used_m", "0")
  2198. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2199. try:
  2200. used_grams = float(used_g)
  2201. except (ValueError, TypeError):
  2202. used_grams = 0
  2203. if used_grams > 0 and filament_id:
  2204. filaments.append(
  2205. {
  2206. "slot_id": int(filament_id),
  2207. "type": filament_type,
  2208. "color": filament_color,
  2209. "used_grams": round(used_grams, 1),
  2210. "used_meters": float(used_m) if used_m else 0,
  2211. "tray_info_idx": tray_info_idx,
  2212. }
  2213. )
  2214. break
  2215. else:
  2216. # No plate_id specified - extract all filaments with used_g > 0
  2217. # This is the legacy behavior for single-plate files
  2218. for filament_elem in root.findall(".//filament"):
  2219. filament_id = filament_elem.get("id")
  2220. filament_type = filament_elem.get("type", "")
  2221. filament_color = filament_elem.get("color", "")
  2222. used_g = filament_elem.get("used_g", "0")
  2223. used_m = filament_elem.get("used_m", "0")
  2224. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2225. # Only include filaments that are actually used
  2226. try:
  2227. used_grams = float(used_g)
  2228. except (ValueError, TypeError):
  2229. used_grams = 0
  2230. if used_grams > 0 and filament_id:
  2231. filaments.append(
  2232. {
  2233. "slot_id": int(filament_id),
  2234. "type": filament_type,
  2235. "color": filament_color,
  2236. "used_grams": round(used_grams, 1),
  2237. "used_meters": float(used_m) if used_m else 0,
  2238. "tray_info_idx": tray_info_idx,
  2239. }
  2240. )
  2241. # Sort by slot ID
  2242. filaments.sort(key=lambda x: x["slot_id"])
  2243. except (KeyError, ValueError, zipfile.BadZipFile, ET.ParseError, UnicodeDecodeError) as e:
  2244. logger.warning("Failed to parse filament requirements from archive %s: %s", archive_id, e)
  2245. return {
  2246. "archive_id": archive_id,
  2247. "filename": archive.filename,
  2248. "plate_id": plate_id,
  2249. "filaments": filaments,
  2250. }
  2251. @router.post("/{archive_id}/reprint")
  2252. async def reprint_archive(
  2253. archive_id: int,
  2254. printer_id: int,
  2255. body: ReprintRequest | None = None,
  2256. db: AsyncSession = Depends(get_db),
  2257. auth_result: tuple[User | None, bool] = Depends(
  2258. require_ownership_permission(
  2259. Permission.ARCHIVES_REPRINT_ALL,
  2260. Permission.ARCHIVES_REPRINT_OWN,
  2261. )
  2262. ),
  2263. ):
  2264. """Send an archived 3MF file to a printer and start printing."""
  2265. from backend.app.main import register_expected_print
  2266. from backend.app.models.printer import Printer
  2267. from backend.app.services.bambu_ftp import (
  2268. get_ftp_retry_settings,
  2269. upload_file_async,
  2270. with_ftp_retry,
  2271. )
  2272. from backend.app.services.printer_manager import printer_manager
  2273. user, can_modify_all = auth_result
  2274. # Use defaults if no body provided
  2275. if body is None:
  2276. body = ReprintRequest()
  2277. # Get archive
  2278. service = ArchiveService(db)
  2279. archive = await service.get_archive(archive_id)
  2280. if not archive:
  2281. raise HTTPException(404, "Archive not found")
  2282. # Ownership check
  2283. if not can_modify_all:
  2284. if archive.created_by_id != user.id:
  2285. raise HTTPException(403, "You can only reprint your own archives")
  2286. # Get printer
  2287. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2288. printer = result.scalar_one_or_none()
  2289. if not printer:
  2290. raise HTTPException(404, "Printer not found")
  2291. # Check printer is connected
  2292. if not printer_manager.is_connected(printer_id):
  2293. raise HTTPException(400, "Printer is not connected")
  2294. # Get the sliced 3MF file path
  2295. file_path = settings.base_dir / archive.file_path
  2296. if not file_path.exists():
  2297. raise HTTPException(404, "Archive file not found")
  2298. # Upload file to printer via FTP
  2299. from backend.app.services.bambu_ftp import delete_file_async
  2300. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  2301. # The printer might reject filenames with unusual extensions
  2302. base_name = archive.filename
  2303. if base_name.endswith(".gcode.3mf"):
  2304. base_name = base_name[:-10] # Remove .gcode.3mf
  2305. elif base_name.endswith(".3mf"):
  2306. base_name = base_name[:-4] # Remove .3mf
  2307. remote_filename = f"{base_name}.3mf"
  2308. remote_path = f"/{remote_filename}"
  2309. # Get FTP retry settings
  2310. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2311. logger.info(
  2312. f"Reprint FTP upload starting: printer={printer.name} ({printer.model}), "
  2313. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  2314. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  2315. )
  2316. # Delete existing file if present (avoids 553 error)
  2317. logger.debug("Deleting existing file %s if present...", remote_path)
  2318. delete_result = await delete_file_async(
  2319. printer.ip_address,
  2320. printer.access_code,
  2321. remote_path,
  2322. socket_timeout=ftp_timeout,
  2323. printer_model=printer.model,
  2324. )
  2325. logger.debug("Delete result: %s", delete_result)
  2326. if ftp_retry_enabled:
  2327. uploaded = await with_ftp_retry(
  2328. upload_file_async,
  2329. printer.ip_address,
  2330. printer.access_code,
  2331. file_path,
  2332. remote_path,
  2333. socket_timeout=ftp_timeout,
  2334. printer_model=printer.model,
  2335. max_retries=ftp_retry_count,
  2336. retry_delay=ftp_retry_delay,
  2337. operation_name=f"Upload for reprint to {printer.name}",
  2338. )
  2339. else:
  2340. uploaded = await upload_file_async(
  2341. printer.ip_address,
  2342. printer.access_code,
  2343. file_path,
  2344. remote_path,
  2345. socket_timeout=ftp_timeout,
  2346. printer_model=printer.model,
  2347. )
  2348. if not uploaded:
  2349. logger.error(
  2350. f"FTP upload failed for reprint: printer={printer.name}, model={printer.model}, "
  2351. f"ip={printer.ip_address}, file={remote_filename}. "
  2352. "Check logs above for storage diagnostics and specific error codes."
  2353. )
  2354. raise HTTPException(
  2355. 500,
  2356. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  2357. "See server logs for detailed diagnostics.",
  2358. )
  2359. # Register this as an expected print so we don't create a duplicate archive
  2360. register_expected_print(printer_id, remote_filename, archive_id)
  2361. # Use plate_id from request if provided, otherwise auto-detect from 3MF file
  2362. if body.plate_id is not None:
  2363. plate_id = body.plate_id
  2364. else:
  2365. # Auto-detect plate ID from 3MF file (legacy behavior for single-plate files)
  2366. plate_id = 1
  2367. try:
  2368. with zipfile.ZipFile(file_path, "r") as zf:
  2369. for name in zf.namelist():
  2370. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  2371. # Extract plate number from "Metadata/plate_X.gcode"
  2372. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  2373. plate_id = int(plate_str)
  2374. break
  2375. except (ValueError, zipfile.BadZipFile, OSError):
  2376. pass # Default to plate 1 if detection fails
  2377. logger.info(
  2378. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  2379. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  2380. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  2381. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  2382. )
  2383. # Start the print with options
  2384. started = printer_manager.start_print(
  2385. printer_id,
  2386. remote_filename,
  2387. plate_id,
  2388. ams_mapping=body.ams_mapping,
  2389. timelapse=body.timelapse,
  2390. bed_levelling=body.bed_levelling,
  2391. flow_cali=body.flow_cali,
  2392. vibration_cali=body.vibration_cali,
  2393. layer_inspect=body.layer_inspect,
  2394. use_ams=body.use_ams,
  2395. )
  2396. if not started:
  2397. raise HTTPException(500, "Failed to start print")
  2398. # Track who started this print (Issue #206)
  2399. if user:
  2400. printer_manager.set_current_print_user(printer_id, user.id, user.username)
  2401. logger.info("Reprint started by user: %s", user.username)
  2402. return {
  2403. "status": "printing",
  2404. "printer_id": printer_id,
  2405. "archive_id": archive_id,
  2406. "filename": archive.filename,
  2407. }
  2408. # =============================================================================
  2409. # Project Page API
  2410. # =============================================================================
  2411. @router.get("/{archive_id}/project-page")
  2412. async def get_project_page(
  2413. archive_id: int,
  2414. db: AsyncSession = Depends(get_db),
  2415. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2416. ):
  2417. """Get the project page data from the 3MF file."""
  2418. from backend.app.schemas.archive import ProjectPageResponse
  2419. from backend.app.services.archive import ProjectPageParser
  2420. service = ArchiveService(db)
  2421. archive = await service.get_archive(archive_id)
  2422. if not archive:
  2423. raise HTTPException(404, "Archive not found")
  2424. file_path = settings.base_dir / archive.file_path
  2425. if not file_path.exists():
  2426. raise HTTPException(404, "Archive file not found")
  2427. parser = ProjectPageParser(file_path)
  2428. data = parser.parse(archive_id)
  2429. return ProjectPageResponse(**data)
  2430. @router.patch("/{archive_id}/project-page")
  2431. async def update_project_page(
  2432. archive_id: int,
  2433. update_data: dict,
  2434. db: AsyncSession = Depends(get_db),
  2435. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2436. ):
  2437. """Update project page metadata in the 3MF file."""
  2438. from backend.app.services.archive import ProjectPageParser
  2439. service = ArchiveService(db)
  2440. archive = await service.get_archive(archive_id)
  2441. if not archive:
  2442. raise HTTPException(404, "Archive not found")
  2443. file_path = settings.base_dir / archive.file_path
  2444. if not file_path.exists():
  2445. raise HTTPException(404, "Archive file not found")
  2446. parser = ProjectPageParser(file_path)
  2447. success = parser.update_metadata(update_data)
  2448. if not success:
  2449. raise HTTPException(500, "Failed to update project page")
  2450. # Return updated data
  2451. data = parser.parse(archive_id)
  2452. return data
  2453. @router.get("/{archive_id}/project-image/{image_path:path}")
  2454. async def get_project_image(
  2455. archive_id: int,
  2456. image_path: str,
  2457. db: AsyncSession = Depends(get_db),
  2458. ):
  2459. """Get an image from the 3MF project page.
  2460. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  2461. """
  2462. from backend.app.services.archive import ProjectPageParser
  2463. service = ArchiveService(db)
  2464. archive = await service.get_archive(archive_id)
  2465. if not archive:
  2466. raise HTTPException(404, "Archive not found")
  2467. file_path = settings.base_dir / archive.file_path
  2468. if not file_path.exists():
  2469. raise HTTPException(404, "Archive file not found")
  2470. parser = ProjectPageParser(file_path)
  2471. result = parser.get_image(image_path)
  2472. if not result:
  2473. raise HTTPException(404, "Image not found in 3MF file")
  2474. image_data, content_type = result
  2475. return Response(
  2476. content=image_data,
  2477. media_type=content_type,
  2478. headers={"Cache-Control": "max-age=3600"},
  2479. )
  2480. # =============================================================================
  2481. # Source 3MF API (Original Project Files)
  2482. # =============================================================================
  2483. @router.post("/{archive_id}/source")
  2484. async def upload_source_3mf(
  2485. archive_id: int,
  2486. file: UploadFile = File(...),
  2487. db: AsyncSession = Depends(get_db),
  2488. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2489. ):
  2490. """Upload the original source 3MF project file for an archive."""
  2491. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2492. archive = result.scalar_one_or_none()
  2493. if not archive:
  2494. raise HTTPException(404, "Archive not found")
  2495. if not file.filename or not file.filename.endswith(".3mf"):
  2496. raise HTTPException(400, "File must be a .3mf file")
  2497. # Get archive directory and create source subdirectory
  2498. file_path = settings.base_dir / archive.file_path
  2499. archive_dir = file_path.parent
  2500. source_dir = archive_dir / "source"
  2501. source_dir.mkdir(exist_ok=True)
  2502. # Delete old source file if exists
  2503. if archive.source_3mf_path:
  2504. old_source_path = settings.base_dir / archive.source_3mf_path
  2505. if old_source_path.exists():
  2506. old_source_path.unlink()
  2507. # Save the source 3MF file - preserve original filename
  2508. source_filename = file.filename
  2509. source_path = source_dir / source_filename
  2510. content = await file.read()
  2511. source_path.write_bytes(content)
  2512. # Update archive with source path (relative to base_dir)
  2513. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2514. await db.commit()
  2515. await db.refresh(archive)
  2516. return {
  2517. "status": "uploaded",
  2518. "source_3mf_path": archive.source_3mf_path,
  2519. "filename": source_filename,
  2520. }
  2521. @router.get("/{archive_id}/source")
  2522. async def download_source_3mf(
  2523. archive_id: int,
  2524. db: AsyncSession = Depends(get_db),
  2525. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2526. ):
  2527. """Download the source 3MF project file."""
  2528. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2529. archive = result.scalar_one_or_none()
  2530. if not archive:
  2531. raise HTTPException(404, "Archive not found")
  2532. if not archive.source_3mf_path:
  2533. raise HTTPException(404, "No source 3MF attached to this archive")
  2534. source_path = settings.base_dir / archive.source_3mf_path
  2535. if not source_path.exists():
  2536. raise HTTPException(404, "Source 3MF file not found on disk")
  2537. # Use the actual filename from the path
  2538. filename = source_path.name
  2539. return FileResponse(
  2540. path=source_path,
  2541. filename=filename,
  2542. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2543. )
  2544. @router.get("/{archive_id}/source/{filename}")
  2545. async def download_source_3mf_for_slicer(
  2546. archive_id: int,
  2547. filename: str,
  2548. db: AsyncSession = Depends(get_db),
  2549. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2550. ):
  2551. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  2552. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2553. archive = result.scalar_one_or_none()
  2554. if not archive:
  2555. raise HTTPException(404, "Archive not found")
  2556. if not archive.source_3mf_path:
  2557. raise HTTPException(404, "No source 3MF attached to this archive")
  2558. source_path = settings.base_dir / archive.source_3mf_path
  2559. if not source_path.exists():
  2560. raise HTTPException(404, "Source 3MF file not found on disk")
  2561. return FileResponse(
  2562. path=source_path,
  2563. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  2564. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2565. )
  2566. @router.post("/upload-source")
  2567. async def upload_source_3mf_by_name(
  2568. file: UploadFile = File(...),
  2569. print_name: str = Query(None, description="Match archive by print name"),
  2570. db: AsyncSession = Depends(get_db),
  2571. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2572. ):
  2573. """Upload source 3MF and match to archive by print name.
  2574. This endpoint is designed for slicer post-processing scripts.
  2575. It finds the most recent archive matching the print name and attaches the source.
  2576. """
  2577. if not file.filename or not file.filename.endswith(".3mf"):
  2578. raise HTTPException(400, "File must be a .3mf file")
  2579. # Derive print name from filename if not provided
  2580. if not print_name:
  2581. # Remove .3mf extension and common suffixes
  2582. print_name = file.filename.rsplit(".3mf", 1)[0]
  2583. # Remove _source suffix if present
  2584. if print_name.endswith("_source"):
  2585. print_name = print_name[:-7]
  2586. # Find matching archive - try exact match first, then fuzzy
  2587. result = await db.execute(
  2588. select(PrintArchive)
  2589. .where(PrintArchive.print_name == print_name)
  2590. .order_by(PrintArchive.created_at.desc())
  2591. .limit(1)
  2592. )
  2593. archive = result.scalar_one_or_none()
  2594. if not archive:
  2595. # Try matching filename without .gcode.3mf
  2596. result = await db.execute(
  2597. select(PrintArchive)
  2598. .where(PrintArchive.filename.like(f"{print_name}%"))
  2599. .order_by(PrintArchive.created_at.desc())
  2600. .limit(1)
  2601. )
  2602. archive = result.scalar_one_or_none()
  2603. if not archive:
  2604. # Try case-insensitive partial match on print_name
  2605. result = await db.execute(
  2606. select(PrintArchive)
  2607. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  2608. .order_by(PrintArchive.created_at.desc())
  2609. .limit(1)
  2610. )
  2611. archive = result.scalar_one_or_none()
  2612. if not archive:
  2613. raise HTTPException(404, f"No archive found matching '{print_name}'")
  2614. # Get archive directory and create source subdirectory
  2615. file_path = settings.base_dir / archive.file_path
  2616. archive_dir = file_path.parent
  2617. source_dir = archive_dir / "source"
  2618. source_dir.mkdir(exist_ok=True)
  2619. # Delete old source file if exists
  2620. if archive.source_3mf_path:
  2621. old_source_path = settings.base_dir / archive.source_3mf_path
  2622. if old_source_path.exists():
  2623. old_source_path.unlink()
  2624. # Save the source 3MF file - preserve original filename
  2625. source_filename = file.filename
  2626. source_path = source_dir / source_filename
  2627. content = await file.read()
  2628. source_path.write_bytes(content)
  2629. # Update archive with source path
  2630. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2631. await db.commit()
  2632. await db.refresh(archive)
  2633. return {
  2634. "status": "uploaded",
  2635. "archive_id": archive.id,
  2636. "archive_name": archive.print_name or archive.filename,
  2637. "source_3mf_path": archive.source_3mf_path,
  2638. "filename": source_filename,
  2639. }
  2640. @router.delete("/{archive_id}/source")
  2641. async def delete_source_3mf(
  2642. archive_id: int,
  2643. db: AsyncSession = Depends(get_db),
  2644. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  2645. ):
  2646. """Delete the source 3MF project file from an archive."""
  2647. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2648. archive = result.scalar_one_or_none()
  2649. if not archive:
  2650. raise HTTPException(404, "Archive not found")
  2651. if not archive.source_3mf_path:
  2652. raise HTTPException(404, "No source 3MF attached to this archive")
  2653. # Delete the file
  2654. source_path = settings.base_dir / archive.source_3mf_path
  2655. if source_path.exists():
  2656. source_path.unlink()
  2657. # Clear the path in database
  2658. archive.source_3mf_path = None
  2659. await db.commit()
  2660. return {"status": "deleted"}
  2661. # =============================================================================
  2662. # F3D API (Fusion 360 Design Files)
  2663. # =============================================================================
  2664. @router.post("/{archive_id}/f3d")
  2665. async def upload_f3d(
  2666. archive_id: int,
  2667. file: UploadFile = File(...),
  2668. db: AsyncSession = Depends(get_db),
  2669. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2670. ):
  2671. """Upload a Fusion 360 design file for an archive."""
  2672. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2673. archive = result.scalar_one_or_none()
  2674. if not archive:
  2675. raise HTTPException(404, "Archive not found")
  2676. if not file.filename or not file.filename.endswith(".f3d"):
  2677. raise HTTPException(400, "File must be a .f3d file")
  2678. # Get archive directory and create f3d subdirectory
  2679. file_path = settings.base_dir / archive.file_path
  2680. archive_dir = file_path.parent
  2681. f3d_dir = archive_dir / "f3d"
  2682. f3d_dir.mkdir(exist_ok=True)
  2683. # Delete old F3D file if exists
  2684. if archive.f3d_path:
  2685. old_f3d_path = settings.base_dir / archive.f3d_path
  2686. if old_f3d_path.exists():
  2687. old_f3d_path.unlink()
  2688. # Save the F3D file - preserve original filename
  2689. f3d_filename = file.filename
  2690. f3d_path = f3d_dir / f3d_filename
  2691. content = await file.read()
  2692. f3d_path.write_bytes(content)
  2693. # Update archive with F3D path (relative to base_dir)
  2694. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  2695. await db.commit()
  2696. await db.refresh(archive)
  2697. return {
  2698. "status": "uploaded",
  2699. "f3d_path": archive.f3d_path,
  2700. "filename": f3d_filename,
  2701. }
  2702. @router.get("/{archive_id}/f3d")
  2703. async def download_f3d(
  2704. archive_id: int,
  2705. db: AsyncSession = Depends(get_db),
  2706. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2707. ):
  2708. """Download the Fusion 360 design file."""
  2709. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2710. archive = result.scalar_one_or_none()
  2711. if not archive:
  2712. raise HTTPException(404, "Archive not found")
  2713. if not archive.f3d_path:
  2714. raise HTTPException(404, "No F3D file attached to this archive")
  2715. f3d_path = settings.base_dir / archive.f3d_path
  2716. if not f3d_path.exists():
  2717. raise HTTPException(404, "F3D file not found on disk")
  2718. # Use the actual filename from the path
  2719. filename = f3d_path.name
  2720. return FileResponse(
  2721. path=f3d_path,
  2722. filename=filename,
  2723. media_type="application/octet-stream",
  2724. )
  2725. @router.delete("/{archive_id}/f3d")
  2726. async def delete_f3d(
  2727. archive_id: int,
  2728. db: AsyncSession = Depends(get_db),
  2729. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  2730. ):
  2731. """Delete the Fusion 360 design file from an archive."""
  2732. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2733. archive = result.scalar_one_or_none()
  2734. if not archive:
  2735. raise HTTPException(404, "Archive not found")
  2736. if not archive.f3d_path:
  2737. raise HTTPException(404, "No F3D file attached to this archive")
  2738. # Delete the file
  2739. f3d_path = settings.base_dir / archive.f3d_path
  2740. if f3d_path.exists():
  2741. f3d_path.unlink()
  2742. # Clear the path in database
  2743. archive.f3d_path = None
  2744. await db.commit()
  2745. return {"status": "deleted"}