archives.py 128 KB

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