archives.py 123 KB

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