archives.py 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642
  1. import io
  2. import json
  3. import logging
  4. import re as _re
  5. import zipfile
  6. from collections import defaultdict
  7. from datetime import date, datetime, time, timedelta, timezone
  8. from decimal import ROUND_HALF_UP, Decimal
  9. from pathlib import Path
  10. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  11. from fastapi.responses import FileResponse, Response
  12. from sqlalchemy import and_, case, func, or_, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.auth import (
  15. RequireCameraStreamTokenIfAuthEnabled,
  16. RequirePermissionIfAuthEnabled,
  17. require_ownership_permission,
  18. )
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import get_db
  21. from backend.app.core.permissions import Permission
  22. from backend.app.models.archive import PrintArchive
  23. from backend.app.models.filament import Filament
  24. from backend.app.models.spool_usage_history import SpoolUsageHistory
  25. from backend.app.models.user import User
  26. from backend.app.schemas.archive import ArchiveResponse, ArchiveSlim, ArchiveStats, ArchiveUpdate
  27. from backend.app.schemas.print_log import PrintLogResponse
  28. from backend.app.schemas.slicer import SliceRequest
  29. from backend.app.services.archive import ArchiveService
  30. from backend.app.utils.http import build_content_disposition
  31. from backend.app.utils.safe_path import safe_join_under
  32. from backend.app.utils.threemf_tools import (
  33. extract_embedded_presets_from_3mf,
  34. extract_nozzle_mapping_from_3mf,
  35. extract_project_filaments_from_3mf,
  36. )
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/archives", tags=["archives"])
  39. def _safe_filename(filename: str) -> str:
  40. """Extract basename from a client-supplied filename, preventing path traversal.
  41. Normalizes backslashes (Windows paths) before extracting so that
  42. '..\\\\..\\\\evil.3mf' is correctly stripped to 'evil.3mf' on Linux.
  43. """
  44. return Path(filename.replace("\\", "/")).name
  45. _TIMELAPSE_FILENAME_TS_RE = _re.compile(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})")
  46. _DEFAULT_TIMELAPSE_OFFSETS_HOURS: tuple[int, ...] = (0, 8, -8, 7, -7, 1, -1)
  47. _DEFAULT_TIMELAPSE_TOLERANCE = timedelta(hours=4)
  48. _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN = timedelta(minutes=15)
  49. def _match_timelapse_by_timestamp(
  50. video_files: list[dict],
  51. archive_start: datetime | None,
  52. *,
  53. tolerance: timedelta = _DEFAULT_TIMELAPSE_TOLERANCE,
  54. ambiguity_margin: timedelta = _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN,
  55. offsets_hours: tuple[int, ...] = _DEFAULT_TIMELAPSE_OFFSETS_HOURS,
  56. ) -> tuple[dict | None, timedelta | None]:
  57. """Pick the timelapse whose filename timestamp best matches the print start time.
  58. Bambu timelapse filenames embed the printer-local START time (e.g.
  59. "video_2026-05-08_09-41-29.mp4"). The printer's clock may be offset from the
  60. server's — especially in LAN-Only mode where NTP is unreachable — so we try a
  61. small set of common UTC offsets and keep the (video, offset) pair with the
  62. smallest absolute distance from archive_start. We deliberately do NOT consider
  63. archive_end here: the filename is start time, not end time, so comparing it to
  64. completion is not a real signal (Strategy 3 handles end via file mtime).
  65. Because the offset list densely covers a wide span, an unrelated video's
  66. filename can coincidentally land near a later print's start at some offset.
  67. To avoid that false positive, we require the best (video, offset) pair to
  68. beat the next-best pair *from a different video* by at least `ambiguity_margin`.
  69. When the top two candidates from different videos are too close to call,
  70. we return None and let the caller fall back to manual selection.
  71. """
  72. if archive_start is None:
  73. return None, None
  74. # (diff, video) for every (video, offset) pair within tolerance.
  75. candidates: list[tuple[timedelta, dict]] = []
  76. for f in video_files:
  77. fname = f.get("name", "")
  78. m = _TIMELAPSE_FILENAME_TS_RE.search(fname)
  79. if not m:
  80. continue
  81. try:
  82. file_time = datetime.strptime(m.group(1), "%Y-%m-%d_%H-%M-%S")
  83. except ValueError:
  84. continue
  85. for hour_offset in offsets_hours:
  86. adjusted = file_time - timedelta(hours=hour_offset)
  87. diff = abs(adjusted - archive_start)
  88. if diff <= tolerance:
  89. candidates.append((diff, f))
  90. if not candidates:
  91. return None, None
  92. candidates.sort(key=lambda c: c[0])
  93. best_diff, best_video = candidates[0]
  94. best_name = best_video.get("name")
  95. for diff, video in candidates[1:]:
  96. if video.get("name") != best_name and (diff - best_diff) < ambiguity_margin:
  97. # Another video matches almost as well — refuse to auto-pick.
  98. return None, None
  99. return best_video, best_diff
  100. def _ensure_archive_visible(
  101. archive: PrintArchive | None,
  102. user: User | None,
  103. can_read_all: bool,
  104. ) -> PrintArchive:
  105. """Per-archive visibility gate for ownership-scoped reads (#1726-adjacent).
  106. Returns ``archive`` if the caller is allowed to see it; raises 404 otherwise.
  107. Single enforcement point used by every detail / download / sub-resource
  108. route so we can't accidentally leak a row through a less-guarded sibling.
  109. Rules:
  110. - Missing archive or soft-deleted (``deleted_at != None``) → 404.
  111. - Caller with ARCHIVES_READ_ALL or auth disabled (``can_read_all=True``,
  112. ``user`` may be None) → archive returned.
  113. - Caller without ARCHIVES_READ_ALL and ``archive.created_by_id != user.id``
  114. → 404, deliberately NOT 403. 403 leaks "this id exists but you can't
  115. see it" — enumeration-friendly. 404 is indistinguishable from a
  116. nonexistent id. Pre-GHSA fix the caller saw 200 here (the PoC vector).
  117. - Ownerless rows (``created_by_id is None``) require ALL — fail-closed
  118. per ``feedback_no_fail_open_in_auth``.
  119. """
  120. if not archive or archive.deleted_at is not None:
  121. raise HTTPException(404, "Archive not found")
  122. if can_read_all:
  123. return archive
  124. # Auth enabled, caller has _OWN only.
  125. if user is None:
  126. # Defensive: should be unreachable (RequirePermissionIfAuthEnabled
  127. # would have 401'd already), but never trust user identity to be
  128. # non-None when can_read_all is False.
  129. raise HTTPException(404, "Archive not found")
  130. if archive.created_by_id is None or archive.created_by_id != user.id:
  131. raise HTTPException(404, "Archive not found")
  132. return archive
  133. def _validate_user_filter_permission(current_user: User | None, created_by_id: int | None):
  134. """Raise 403 if created_by_id filter is used without stats:filter_by_user permission."""
  135. if created_by_id is None or current_user is None:
  136. return
  137. if current_user.is_admin:
  138. return
  139. if not current_user.has_permission(Permission.STATS_FILTER_BY_USER.value):
  140. raise HTTPException(status_code=403, detail="Permission stats:filter_by_user required")
  141. def _apply_user_filter(conditions: list, created_by_id: int | None):
  142. """Append created_by_id filter to conditions list if specified."""
  143. if created_by_id is not None:
  144. if created_by_id == -1:
  145. conditions.append(PrintArchive.created_by_id.is_(None))
  146. else:
  147. conditions.append(PrintArchive.created_by_id == created_by_id)
  148. def _apply_run_user_filter(conditions: list, created_by_id: int | None):
  149. """Append created_by_id filter scoped to PrintLogEntry rows."""
  150. from backend.app.models.print_log import PrintLogEntry
  151. if created_by_id is not None:
  152. if created_by_id == -1:
  153. conditions.append(PrintLogEntry.created_by_id.is_(None))
  154. else:
  155. conditions.append(PrintLogEntry.created_by_id == created_by_id)
  156. def compute_time_accuracy(archive: PrintArchive, run_aggregate: dict | None = None) -> dict:
  157. """Compute actual print time and accuracy for an archive.
  158. Returns dict with actual_time_seconds and time_accuracy.
  159. time_accuracy = (estimated / actual) * 100
  160. - 100% = perfect estimate
  161. - >100% = print was faster than estimated
  162. - <100% = print took longer than estimated
  163. When ``run_aggregate`` indicates the archive has more than one logged
  164. run (multi-plate file printed plate-by-plate, or reprints), both
  165. fields are suppressed: ``archive.started_at / completed_at`` reflect
  166. the LATEST run only, while ``archive.print_time_seconds`` is the
  167. whole-file estimate (post-#1593 the parser sums across plates), so
  168. comparing the two describes different scopes. The card-rendering
  169. frontend falls through to ``archive.print_time_seconds`` for the
  170. time display and hides the badge when ``time_accuracy`` is null —
  171. that's the desired "show estimate, no badge" presentation for
  172. multi-run archives (#1608). Single-run archives keep the original
  173. badge behaviour verbatim.
  174. """
  175. result: dict[str, int | float | None] = {"actual_time_seconds": None, "time_accuracy": None}
  176. # Multi-run archives: the per-run actual (started_at..completed_at on
  177. # the archive row) is incommensurable with the whole-file estimate.
  178. # Both fields are cleared so the card shows estimate + no badge.
  179. if run_aggregate and (run_aggregate.get("run_count") or 0) > 1:
  180. return result
  181. if archive.started_at and archive.completed_at and archive.status == "completed":
  182. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  183. if actual_seconds > 0:
  184. result["actual_time_seconds"] = actual_seconds
  185. if archive.print_time_seconds and archive.print_time_seconds > 0:
  186. # Calculate accuracy as percentage
  187. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  188. # Sanity check: skip unreasonable values (e.g., manually changed status)
  189. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  190. if 5 <= accuracy <= 500:
  191. result["time_accuracy"] = round(accuracy, 1)
  192. return result
  193. async def _load_run_aggregates(db: AsyncSession, archive_ids: list[int]) -> dict[int, dict]:
  194. """Batch-load per-archive run aggregates from PrintLogEntry.
  195. Returns ``{archive_id: {run_count, last_run_at, total_filament_actual_grams,
  196. successful_run_count, failed_run_count}}``. Archives with no logged runs are
  197. absent from the map; callers should treat that as zero/none.
  198. """
  199. from backend.app.models.print_log import PrintLogEntry
  200. if not archive_ids:
  201. return {}
  202. rows = await db.execute(
  203. select(
  204. PrintLogEntry.archive_id,
  205. func.count(PrintLogEntry.id).label("run_count"),
  206. func.max(PrintLogEntry.started_at).label("last_run_at"),
  207. func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0).label("total_filament"),
  208. func.sum(case((PrintLogEntry.status == "completed", 1), else_=0)).label("successful"),
  209. func.sum(case((PrintLogEntry.status == "failed", 1), else_=0)).label("failed"),
  210. )
  211. .where(PrintLogEntry.archive_id.in_(archive_ids))
  212. .group_by(PrintLogEntry.archive_id)
  213. )
  214. aggregates: dict[int, dict] = {}
  215. for archive_id, run_count, last_run_at, total_filament, successful, failed in rows.all():
  216. aggregates[archive_id] = {
  217. "run_count": int(run_count or 0),
  218. "last_run_at": last_run_at,
  219. "total_filament_actual_grams": float(total_filament) if total_filament else None,
  220. "successful_run_count": int(successful or 0),
  221. "failed_run_count": int(failed or 0),
  222. }
  223. return aggregates
  224. def archive_to_response(
  225. archive: PrintArchive,
  226. duplicates: list[dict] | None = None,
  227. duplicate_count: int = 0,
  228. duplicate_sequence: int = 0,
  229. original_archive_id: int | None = None,
  230. run_aggregate: dict | None = None,
  231. ) -> dict:
  232. """Convert archive model to response dict with computed fields."""
  233. data = {
  234. "id": archive.id,
  235. "printer_id": archive.printer_id,
  236. "project_id": archive.project_id,
  237. "project_name": archive.project.name if archive.project else None,
  238. "filename": archive.filename,
  239. "file_path": archive.file_path,
  240. "file_size": archive.file_size,
  241. "content_hash": archive.content_hash,
  242. "thumbnail_path": archive.thumbnail_path,
  243. "timelapse_path": archive.timelapse_path,
  244. "source_3mf_path": archive.source_3mf_path,
  245. "f3d_path": archive.f3d_path,
  246. "duplicates": duplicates,
  247. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  248. "duplicate_sequence": duplicate_sequence,
  249. "original_archive_id": original_archive_id,
  250. "print_name": archive.print_name,
  251. "print_time_seconds": archive.print_time_seconds,
  252. "filament_used_grams": archive.filament_used_grams,
  253. "filament_type": archive.filament_type,
  254. "filament_color": archive.filament_color,
  255. "layer_height": archive.layer_height,
  256. "total_layers": archive.total_layers,
  257. "nozzle_diameter": archive.nozzle_diameter,
  258. "bed_temperature": archive.bed_temperature,
  259. "bed_type": archive.bed_type,
  260. "nozzle_temperature": archive.nozzle_temperature,
  261. "sliced_for_model": archive.sliced_for_model,
  262. "status": archive.status,
  263. "started_at": archive.started_at,
  264. "completed_at": archive.completed_at,
  265. "extra_data": archive.extra_data,
  266. "makerworld_url": archive.makerworld_url,
  267. "designer": archive.designer,
  268. "external_url": archive.external_url,
  269. "is_favorite": archive.is_favorite,
  270. "tags": archive.tags,
  271. "notes": archive.notes,
  272. "cost": archive.cost,
  273. "photos": archive.photos,
  274. "failure_reason": archive.failure_reason,
  275. "quantity": archive.quantity,
  276. "energy_kwh": archive.energy_kwh,
  277. "energy_cost": archive.energy_cost,
  278. "created_at": archive.created_at,
  279. # User tracking (Issue #206)
  280. "created_by_id": archive.created_by_id,
  281. "created_by_username": archive.created_by.username if archive.created_by else None,
  282. }
  283. # Add computed time accuracy fields. ``run_aggregate`` lets
  284. # ``compute_time_accuracy`` suppress the badge for multi-run archives
  285. # where the per-run actual / whole-file estimate scopes don't match
  286. # (#1608).
  287. accuracy_data = compute_time_accuracy(archive, run_aggregate)
  288. data.update(accuracy_data)
  289. if run_aggregate:
  290. data["run_count"] = run_aggregate.get("run_count", 0)
  291. data["last_run_at"] = run_aggregate.get("last_run_at")
  292. data["total_filament_actual_grams"] = run_aggregate.get("total_filament_actual_grams")
  293. data["successful_run_count"] = run_aggregate.get("successful_run_count", 0)
  294. data["failed_run_count"] = run_aggregate.get("failed_run_count", 0)
  295. return data
  296. @router.get("/", response_model=list[ArchiveResponse])
  297. async def list_archives(
  298. printer_id: int | None = None,
  299. project_id: int | None = None,
  300. date_from: date | None = Query(None),
  301. date_to: date | None = Query(None),
  302. limit: int = 50,
  303. offset: int = 0,
  304. db: AsyncSession = Depends(get_db),
  305. auth_result: tuple[User | None, bool] = Depends(
  306. require_ownership_permission(
  307. Permission.ARCHIVES_READ_ALL,
  308. Permission.ARCHIVES_READ_OWN,
  309. )
  310. ),
  311. ):
  312. """List archived prints."""
  313. user, can_read_all = auth_result
  314. visible_to_user_id = user.id if (user is not None and not can_read_all) else None
  315. service = ArchiveService(db)
  316. archives = await service.list_archives(
  317. printer_id=printer_id,
  318. project_id=project_id,
  319. date_from=date_from,
  320. date_to=date_to,
  321. limit=limit,
  322. offset=offset,
  323. visible_to_user_id=visible_to_user_id,
  324. )
  325. # Get sets of duplicate hashes and duplicate (name, hash) pairs (efficient single queries)
  326. duplicate_hashes, duplicate_name_hash_pairs = await service.get_duplicate_hashes_and_names()
  327. # Batch-load duplicate groups once for the current page keys.
  328. duplicate_hashes_in_page = {
  329. a.content_hash for a in archives if a.content_hash and a.content_hash in duplicate_hashes
  330. }
  331. duplicate_name_hash_keys_in_page = {
  332. (a.print_name.lower(), a.content_hash)
  333. for a in archives
  334. if a.print_name and a.content_hash and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  335. }
  336. duplicate_meta_by_archive_id: dict[int, tuple[int, int, int]] = {}
  337. if duplicate_hashes_in_page or duplicate_name_hash_keys_in_page:
  338. duplicate_group_conditions = []
  339. if duplicate_hashes_in_page:
  340. duplicate_group_conditions.append(PrintArchive.content_hash.in_(duplicate_hashes_in_page))
  341. if duplicate_name_hash_keys_in_page:
  342. name_hash_conditions = [
  343. and_(func.lower(PrintArchive.print_name) == name, PrintArchive.content_hash == hash_)
  344. for name, hash_ in duplicate_name_hash_keys_in_page
  345. ]
  346. duplicate_group_conditions.extend(name_hash_conditions)
  347. duplicate_group_rows = await db.execute(
  348. select(
  349. PrintArchive.id,
  350. PrintArchive.created_at,
  351. PrintArchive.content_hash,
  352. func.lower(PrintArchive.print_name).label("print_name_lower"),
  353. ).where(or_(*duplicate_group_conditions), PrintArchive.deleted_at.is_(None))
  354. )
  355. duplicate_groups_by_hash: dict[str, list[tuple[int, datetime]]] = defaultdict(list)
  356. duplicate_groups_by_name_hash: dict[tuple[str, str], list[tuple[int, datetime]]] = defaultdict(list)
  357. for archive_id, created_at, content_hash, print_name_lower in duplicate_group_rows.all():
  358. if content_hash and content_hash in duplicate_hashes_in_page:
  359. duplicate_groups_by_hash[content_hash].append((archive_id, created_at))
  360. if (
  361. print_name_lower
  362. and content_hash
  363. and (print_name_lower, content_hash) in duplicate_name_hash_keys_in_page
  364. ):
  365. duplicate_groups_by_name_hash[(print_name_lower, content_hash)].append((archive_id, created_at))
  366. for group in duplicate_groups_by_hash.values():
  367. if len(group) < 2:
  368. continue
  369. group.sort(key=lambda x: x[1])
  370. original_id = group[0][0]
  371. duplicate_count = len(group) - 1
  372. for sequence, (archive_id, _) in enumerate(group):
  373. duplicate_meta_by_archive_id[archive_id] = (sequence, original_id, duplicate_count)
  374. # Keep hash-based grouping precedence; name/hash groups only fill missing items.
  375. for group in duplicate_groups_by_name_hash.values():
  376. if len(group) < 2:
  377. continue
  378. group.sort(key=lambda x: x[1])
  379. original_id = group[0][0]
  380. duplicate_count = len(group) - 1
  381. for sequence, (archive_id, _) in enumerate(group):
  382. duplicate_meta_by_archive_id.setdefault(archive_id, (sequence, original_id, duplicate_count))
  383. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives])
  384. # Build response with duplicate sequence and original archive ID pre-computed
  385. result = []
  386. for a in archives:
  387. has_hash_dup = a.content_hash in duplicate_hashes if a.content_hash else False
  388. has_name_dup = (
  389. bool(a.print_name and a.content_hash)
  390. and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  391. )
  392. has_duplicate = has_hash_dup or has_name_dup
  393. # Pre-compute duplicate sequence and original archive ID
  394. duplicate_sequence = 0
  395. original_archive_id: int | None = None
  396. duplicate_count = 1 if has_duplicate else 0
  397. if has_duplicate and a.id in duplicate_meta_by_archive_id:
  398. duplicate_sequence, original_archive_id, duplicate_count = duplicate_meta_by_archive_id[a.id]
  399. result.append(
  400. archive_to_response(
  401. a,
  402. duplicate_count=duplicate_count,
  403. duplicate_sequence=duplicate_sequence,
  404. original_archive_id=original_archive_id,
  405. run_aggregate=run_aggregates.get(a.id),
  406. )
  407. )
  408. return result
  409. @router.get("/no-3mf-warning")
  410. async def no_3mf_warning(
  411. db: AsyncSession = Depends(get_db),
  412. auth_result: tuple[User | None, bool] = Depends(
  413. require_ownership_permission(
  414. Permission.ARCHIVES_READ_ALL,
  415. Permission.ARCHIVES_READ_OWN,
  416. )
  417. ),
  418. ):
  419. """Whether to nudge the user about install step 4 ("Store sent files on
  420. external storage"). True iff any archive in the last 30 days was created
  421. via the no-3MF fallback path — that's the deterministic symptom of the
  422. slicer-side variant of the setting being off.
  423. Complements the connection-diagnostic ``external_storage`` check, which
  424. only catches the printer-side variant of the setting. On older slicers
  425. where the toggle lives only in BambuStudio, the printer never reports it
  426. and the diagnostic passes — this endpoint surfaces the symptom instead.
  427. Dismissal is handled client-side via localStorage (one-shot): once the
  428. user has been told, no further nudge until they clear browser storage.
  429. The backend stays stateless.
  430. """
  431. user, can_read_all = auth_result
  432. cutoff = datetime.now(timezone.utc) - timedelta(days=30)
  433. conditions = [
  434. PrintArchive.created_at >= cutoff,
  435. PrintArchive.deleted_at.is_(None),
  436. PrintArchive.extra_data.isnot(None),
  437. ]
  438. if user is not None and not can_read_all:
  439. conditions.append(PrintArchive.created_by_id == user.id)
  440. result = await db.execute(select(PrintArchive.extra_data).where(*conditions))
  441. for (extra_data,) in result.all():
  442. if extra_data and extra_data.get("no_3mf_available"):
  443. return {"has_fallback": True}
  444. return {"has_fallback": False}
  445. @router.get("/slim", response_model=list[ArchiveSlim])
  446. async def list_archives_slim(
  447. date_from: date | None = Query(None),
  448. date_to: date | None = Query(None),
  449. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  450. limit: int = Query(default=10000, le=50000),
  451. offset: int = 0,
  452. db: AsyncSession = Depends(get_db),
  453. auth_result: tuple[User | None, bool] = Depends(
  454. require_ownership_permission(
  455. Permission.ARCHIVES_READ_ALL,
  456. Permission.ARCHIVES_READ_OWN,
  457. )
  458. ),
  459. ):
  460. """Per-event listing for stats/dashboard widgets.
  461. Reads from print_log_entries so reprints contribute each run and
  462. orphaned events (archive deleted, log row survived via ON DELETE
  463. SET NULL) still aggregate consistently with Quick Stats. The sliced
  464. print_time_seconds is joined from the archive when available; for
  465. orphan events it is null and downstream widgets fall back to the
  466. measured duration_seconds.
  467. """
  468. from backend.app.models.print_log import PrintLogEntry
  469. current_user, can_read_all = auth_result
  470. _validate_user_filter_permission(current_user, created_by_id)
  471. # Callers without ARCHIVES_READ_ALL can only see their own runs — pin
  472. # the filter unconditionally so a caller-supplied ?created_by_id=
  473. # can't widen the listing past their own scope. The existing
  474. # _validate_user_filter_permission rejects ?created_by_id= without
  475. # STATS_FILTER_BY_USER, so the only way to reach this is owner-self
  476. # filtering anyway, but pinning here is the fail-closed default.
  477. if current_user is not None and not can_read_all:
  478. created_by_id = current_user.id
  479. filters = []
  480. if date_from:
  481. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  482. filters.append(PrintLogEntry.created_at >= dt_from)
  483. if date_to:
  484. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  485. filters.append(PrintLogEntry.created_at <= dt_to)
  486. _apply_run_user_filter(filters, created_by_id)
  487. query = (
  488. select(
  489. PrintLogEntry.printer_id,
  490. PrintLogEntry.print_name,
  491. PrintArchive.print_time_seconds,
  492. PrintLogEntry.started_at,
  493. PrintLogEntry.completed_at,
  494. PrintLogEntry.duration_seconds,
  495. PrintLogEntry.filament_used_grams,
  496. PrintLogEntry.filament_type,
  497. PrintLogEntry.filament_color,
  498. PrintLogEntry.status,
  499. PrintLogEntry.cost,
  500. PrintLogEntry.created_at,
  501. )
  502. .outerjoin(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  503. .where(*filters)
  504. .order_by(PrintLogEntry.created_at.desc())
  505. .limit(limit)
  506. .offset(offset)
  507. )
  508. result = await db.execute(query)
  509. rows = result.all()
  510. return [
  511. {
  512. "printer_id": r.printer_id,
  513. "print_name": r.print_name,
  514. "print_time_seconds": r.print_time_seconds,
  515. "actual_time_seconds": (
  516. # Measured elapsed time for every status (#1390): failed /
  517. # cancelled prints still ran for some duration, and Quick
  518. # Stats already counts that. Widgets that fall back to
  519. # print_time_seconds (slicer estimate) for non-completed
  520. # events would diverge from Quick Stats — so expose the
  521. # measured value here unconditionally.
  522. r.duration_seconds
  523. if r.duration_seconds and r.duration_seconds > 0
  524. else (
  525. int((r.completed_at - r.started_at).total_seconds())
  526. if r.started_at and r.completed_at and (r.completed_at - r.started_at).total_seconds() > 0
  527. else None
  528. )
  529. ),
  530. "filament_used_grams": r.filament_used_grams,
  531. "filament_type": r.filament_type,
  532. "filament_color": r.filament_color,
  533. "status": r.status,
  534. "started_at": r.started_at,
  535. "completed_at": r.completed_at,
  536. "cost": r.cost,
  537. "quantity": 1,
  538. "created_at": r.created_at,
  539. }
  540. for r in rows
  541. ]
  542. @router.get("/search", response_model=list[ArchiveResponse])
  543. async def search_archives(
  544. q: str = Query(..., min_length=2, description="Search query"),
  545. printer_id: int | None = None,
  546. project_id: int | None = None,
  547. status: str | None = None,
  548. limit: int = 50,
  549. offset: int = 0,
  550. db: AsyncSession = Depends(get_db),
  551. auth_result: tuple[User | None, bool] = Depends(
  552. require_ownership_permission(
  553. Permission.ARCHIVES_READ_ALL,
  554. Permission.ARCHIVES_READ_OWN,
  555. )
  556. ),
  557. ):
  558. """Full-text search across archives.
  559. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  560. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  561. """
  562. from sqlalchemy import text
  563. from sqlalchemy.orm import selectinload
  564. from backend.app.core.db_dialect import is_sqlite
  565. user, can_read_all = auth_result
  566. own_only = user is not None and not can_read_all
  567. search_term = q.strip()
  568. # Build dialect-specific full-text search query
  569. if is_sqlite():
  570. # SQLite FTS5: wildcard suffix for partial matches
  571. if not search_term.endswith("*"):
  572. search_term = f"{search_term}*"
  573. fts_query = text("""
  574. SELECT rowid FROM archive_fts
  575. WHERE archive_fts MATCH :search_term
  576. ORDER BY rank
  577. LIMIT :limit OFFSET :offset
  578. """)
  579. else:
  580. # PostgreSQL: tsvector + plainto_tsquery with prefix matching
  581. fts_query = text("""
  582. SELECT id FROM print_archives
  583. WHERE to_tsvector('simple',
  584. COALESCE(print_name, '') || ' ' ||
  585. COALESCE(filename, '') || ' ' ||
  586. COALESCE(tags, '') || ' ' ||
  587. COALESCE(notes, '') || ' ' ||
  588. COALESCE(designer, '') || ' ' ||
  589. COALESCE(filament_type, '')
  590. ) @@ to_tsquery('simple', :search_term)
  591. LIMIT :limit OFFSET :offset
  592. """)
  593. # Convert "benchy" to "benchy:*" for prefix matching in tsquery
  594. search_term = " & ".join(f"{word}:*" for word in search_term.split() if word)
  595. try:
  596. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  597. matched_ids = [row[0] for row in result.fetchall()]
  598. except Exception as e:
  599. logger.warning("FTS search failed, falling back to LIKE search: %s", e)
  600. # Fallback to LIKE search if FTS fails
  601. like_pattern = f"%{q}%"
  602. query = (
  603. select(PrintArchive)
  604. .options(selectinload(PrintArchive.project))
  605. .where(
  606. (
  607. (PrintArchive.print_name.ilike(like_pattern))
  608. | (PrintArchive.filename.ilike(like_pattern))
  609. | (PrintArchive.tags.ilike(like_pattern))
  610. | (PrintArchive.notes.ilike(like_pattern))
  611. | (PrintArchive.designer.ilike(like_pattern))
  612. | (PrintArchive.filament_type.ilike(like_pattern))
  613. ),
  614. PrintArchive.deleted_at.is_(None),
  615. )
  616. .order_by(PrintArchive.created_at.desc())
  617. )
  618. if printer_id:
  619. query = query.where(PrintArchive.printer_id == printer_id)
  620. if project_id:
  621. query = query.where(PrintArchive.project_id == project_id)
  622. if status:
  623. query = query.where(PrintArchive.status == status)
  624. if own_only:
  625. query = query.where(PrintArchive.created_by_id == user.id)
  626. query = query.limit(limit).offset(offset)
  627. result = await db.execute(query)
  628. archives = result.scalars().all()
  629. # Load run aggregates so multi-run archives' time/accuracy badge is
  630. # suppressed consistently with the main list endpoint (#1608).
  631. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives])
  632. return [archive_to_response(a, run_aggregate=run_aggregates.get(a.id)) for a in archives]
  633. if not matched_ids:
  634. return []
  635. # Fetch full archive records for matched IDs (excluding soft-deleted, #1343)
  636. query = (
  637. select(PrintArchive)
  638. .options(selectinload(PrintArchive.project))
  639. .where(PrintArchive.id.in_(matched_ids), PrintArchive.deleted_at.is_(None))
  640. )
  641. if own_only:
  642. query = query.where(PrintArchive.created_by_id == user.id)
  643. # Apply additional filters
  644. if printer_id:
  645. query = query.where(PrintArchive.printer_id == printer_id)
  646. if project_id:
  647. query = query.where(PrintArchive.project_id == project_id)
  648. if status:
  649. query = query.where(PrintArchive.status == status)
  650. result = await db.execute(query)
  651. archives_dict = {a.id: a for a in result.scalars().all()}
  652. # Preserve FTS ranking order and apply pagination
  653. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  654. paginated = ordered_archives[offset : offset + limit]
  655. # Load run aggregates so multi-run archives' time/accuracy badge is
  656. # suppressed consistently with the main list endpoint (#1608).
  657. run_aggregates = await _load_run_aggregates(db, [a.id for a in paginated])
  658. return [archive_to_response(a, run_aggregate=run_aggregates.get(a.id)) for a in paginated]
  659. @router.post("/search/rebuild-index")
  660. async def rebuild_search_index(
  661. db: AsyncSession = Depends(get_db),
  662. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  663. ):
  664. """Rebuild the full-text search index from existing archives.
  665. Use this if search results seem incomplete or incorrect.
  666. """
  667. from sqlalchemy import text
  668. from backend.app.core.db_dialect import is_sqlite
  669. try:
  670. if is_sqlite():
  671. # SQLite: rebuild FTS5 virtual table
  672. await db.execute(text("DELETE FROM archive_fts"))
  673. await db.execute(
  674. text("""
  675. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  676. SELECT id, print_name, filename, tags, notes, designer, filament_type
  677. FROM print_archives
  678. """)
  679. )
  680. await db.commit()
  681. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  682. count = result.scalar() or 0
  683. else:
  684. # PostgreSQL: GIN index is auto-maintained, just reindex
  685. await db.execute(text("REINDEX INDEX idx_archives_fulltext"))
  686. await db.commit()
  687. result = await db.execute(text("SELECT COUNT(*) FROM print_archives"))
  688. count = result.scalar() or 0
  689. return {"message": f"Search index rebuilt with {count} entries"}
  690. except Exception as e:
  691. logger.error("Failed to rebuild search index: %s", e)
  692. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  693. @router.get("/analysis/failures")
  694. async def analyze_failures(
  695. days: int | None = None,
  696. date_from: date | None = Query(None),
  697. date_to: date | None = Query(None),
  698. printer_id: int | None = None,
  699. project_id: int | None = None,
  700. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  701. db: AsyncSession = Depends(get_db),
  702. auth_result: tuple[User | None, bool] = Depends(
  703. require_ownership_permission(
  704. Permission.ARCHIVES_READ_ALL,
  705. Permission.ARCHIVES_READ_OWN,
  706. )
  707. ),
  708. ):
  709. """Analyze failure patterns across prints.
  710. Returns failure statistics including:
  711. - Overall failure rate
  712. - Failures by reason, filament type, printer
  713. - Time of day distribution
  714. - Recent failures
  715. - Weekly trend
  716. """
  717. current_user, can_read_all = auth_result
  718. _validate_user_filter_permission(current_user, created_by_id)
  719. # Callers without ARCHIVES_READ_ALL are scoped to their own runs (#2).
  720. if current_user is not None and not can_read_all:
  721. created_by_id = current_user.id
  722. from backend.app.services.failure_analysis import FailureAnalysisService
  723. service = FailureAnalysisService(db)
  724. return await service.analyze_failures(
  725. days=days,
  726. date_from=date_from,
  727. date_to=date_to,
  728. printer_id=printer_id,
  729. project_id=project_id,
  730. created_by_id=created_by_id,
  731. )
  732. @router.get("/compare")
  733. async def compare_archives(
  734. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  735. db: AsyncSession = Depends(get_db),
  736. auth_result: tuple[User | None, bool] = Depends(
  737. require_ownership_permission(
  738. Permission.ARCHIVES_READ_ALL,
  739. Permission.ARCHIVES_READ_OWN,
  740. )
  741. ),
  742. ):
  743. """Compare multiple archives side by side.
  744. Compares print settings, filament usage, and print times.
  745. Also analyzes correlation between settings and success/failure.
  746. Args:
  747. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  748. """
  749. from backend.app.services.archive_comparison import ArchiveComparisonService
  750. user, can_read_all = auth_result
  751. # Parse and validate archive IDs
  752. try:
  753. ids = [int(id.strip()) for id in archive_ids.split(",")]
  754. except ValueError:
  755. raise HTTPException(400, "Invalid archive IDs format")
  756. if len(ids) < 2:
  757. raise HTTPException(400, "At least 2 archives required for comparison")
  758. if len(ids) > 5:
  759. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  760. # Verify the caller is allowed to see every archive in the comparison —
  761. # one not-owned id in the list would otherwise leak its full detail block.
  762. # _ensure_archive_visible raises 404 on the first miss (same 404 the
  763. # single-archive endpoint would return).
  764. if user is not None and not can_read_all:
  765. existing = await db.execute(
  766. select(PrintArchive.id, PrintArchive.created_by_id, PrintArchive.deleted_at).where(PrintArchive.id.in_(ids))
  767. )
  768. owners_by_id = {row.id: row for row in existing.all()}
  769. for archive_id in ids:
  770. row = owners_by_id.get(archive_id)
  771. if row is None or row.deleted_at is not None or row.created_by_id != user.id:
  772. raise HTTPException(404, "Archive not found")
  773. service = ArchiveComparisonService(db)
  774. try:
  775. return await service.compare_archives(ids)
  776. except ValueError as e:
  777. raise HTTPException(400, str(e))
  778. @router.get("/export")
  779. async def export_archives(
  780. format: str = Query("csv", description="Export format: csv or xlsx"),
  781. fields: str | None = Query(None, description="Comma-separated field names"),
  782. printer_id: int | None = None,
  783. project_id: int | None = None,
  784. status: str | None = None,
  785. date_from: str | None = Query(None, description="Start date (ISO format)"),
  786. date_to: str | None = Query(None, description="End date (ISO format)"),
  787. search: str | None = None,
  788. db: AsyncSession = Depends(get_db),
  789. auth_result: tuple[User | None, bool] = Depends(
  790. require_ownership_permission(
  791. Permission.ARCHIVES_READ_ALL,
  792. Permission.ARCHIVES_READ_OWN,
  793. )
  794. ),
  795. ):
  796. """Export archives to CSV or Excel format.
  797. Returns a downloadable file with archive data.
  798. """
  799. from datetime import datetime
  800. from fastapi.responses import StreamingResponse
  801. from backend.app.services.export import ExportService
  802. user, can_read_all = auth_result
  803. visible_to_user_id = user.id if (user is not None and not can_read_all) else None
  804. if format not in ("csv", "xlsx"):
  805. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  806. # Parse fields
  807. field_list = None
  808. if fields:
  809. field_list = [f.strip() for f in fields.split(",")]
  810. # Parse dates
  811. date_from_dt = None
  812. date_to_dt = None
  813. if date_from:
  814. try:
  815. date_from_dt = datetime.fromisoformat(date_from)
  816. except ValueError:
  817. raise HTTPException(400, "Invalid date_from format")
  818. if date_to:
  819. try:
  820. date_to_dt = datetime.fromisoformat(date_to)
  821. except ValueError:
  822. raise HTTPException(400, "Invalid date_to format")
  823. service = ExportService(db)
  824. try:
  825. file_bytes, filename, content_type = await service.export_archives(
  826. format=format,
  827. fields=field_list,
  828. printer_id=printer_id,
  829. project_id=project_id,
  830. status=status,
  831. date_from=date_from_dt,
  832. date_to=date_to_dt,
  833. search=search,
  834. visible_to_user_id=visible_to_user_id,
  835. )
  836. except ImportError as e:
  837. raise HTTPException(500, str(e))
  838. return StreamingResponse(
  839. io.BytesIO(file_bytes),
  840. media_type=content_type,
  841. headers={"Content-Disposition": build_content_disposition(filename)},
  842. )
  843. @router.get("/stats/export")
  844. async def export_stats(
  845. format: str = Query("csv", description="Export format: csv or xlsx"),
  846. days: int = 30,
  847. printer_id: int | None = None,
  848. project_id: int | None = None,
  849. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  850. db: AsyncSession = Depends(get_db),
  851. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  852. ):
  853. """Export statistics summary to CSV or Excel format."""
  854. _validate_user_filter_permission(current_user, created_by_id)
  855. from fastapi.responses import StreamingResponse
  856. from backend.app.services.export import ExportService
  857. if format not in ("csv", "xlsx"):
  858. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  859. service = ExportService(db)
  860. try:
  861. file_bytes, filename, content_type = await service.export_stats(
  862. format=format,
  863. days=days,
  864. printer_id=printer_id,
  865. project_id=project_id,
  866. created_by_id=created_by_id,
  867. )
  868. except ImportError as e:
  869. raise HTTPException(500, str(e))
  870. return StreamingResponse(
  871. io.BytesIO(file_bytes),
  872. media_type=content_type,
  873. headers={"Content-Disposition": build_content_disposition(filename)},
  874. )
  875. @router.get("/stats", response_model=ArchiveStats)
  876. async def get_archive_stats(
  877. date_from: date | None = Query(None, description="Start date (inclusive), YYYY-MM-DD"),
  878. date_to: date | None = Query(None, description="End date (inclusive), YYYY-MM-DD"),
  879. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  880. db: AsyncSession = Depends(get_db),
  881. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  882. ):
  883. """Get statistics across all archives.
  884. Stats aggregate over PrintLogEntry (one row per print event), not over
  885. PrintArchive (one row per file). A reprint contributes a new PrintLogEntry
  886. so its filament/cost/time/energy add to the totals instead of overwriting
  887. the source archive's first-run values (#1378).
  888. """
  889. from backend.app.models.print_log import PrintLogEntry
  890. _validate_user_filter_permission(current_user, created_by_id)
  891. # Build date filter conditions scoped to PrintLogEntry (event-time).
  892. base_conditions = []
  893. if date_from:
  894. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  895. base_conditions.append(PrintLogEntry.created_at >= dt_from)
  896. if date_to:
  897. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  898. base_conditions.append(PrintLogEntry.created_at <= dt_to)
  899. _apply_run_user_filter(base_conditions, created_by_id)
  900. # Total counts (one row per print event).
  901. total_result = await db.execute(select(func.count(PrintLogEntry.id)).where(*base_conditions))
  902. total_prints = total_result.scalar() or 0
  903. successful_result = await db.execute(
  904. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status == "completed", *base_conditions)
  905. )
  906. successful_prints = successful_result.scalar() or 0
  907. failed_result = await db.execute(
  908. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status.in_(("failed", "aborted")), *base_conditions)
  909. )
  910. failed_prints = failed_result.scalar() or 0
  911. # User/system-stopped prints — stopped/cancelled/skipped are distinct from
  912. # quality failures: the user (or the queue) interrupted them, the printer
  913. # didn't detect a fault. Bucketed separately so the Success Rate gauge
  914. # divides by completed + failed only (a cancelled print shouldn't drag
  915. # the gauge down), while still being visible in the breakdown so they
  916. # don't silently vanish from Total Prints (#1390).
  917. cancelled_result = await db.execute(
  918. select(func.count(PrintLogEntry.id)).where(
  919. PrintLogEntry.status.in_(("stopped", "cancelled", "skipped")), *base_conditions
  920. )
  921. )
  922. cancelled_prints = cancelled_result.scalar() or 0
  923. # Total elapsed time — PrintLogEntry stores duration_seconds directly so we
  924. # can sum it server-side. Rows missing duration fall back to the slicer
  925. # estimate from the archive (joined for that case only).
  926. time_rows = await db.execute(
  927. select(
  928. PrintLogEntry.duration_seconds,
  929. PrintLogEntry.started_at,
  930. PrintLogEntry.completed_at,
  931. ).where(*base_conditions)
  932. )
  933. total_seconds = 0
  934. for duration_seconds, started_at, completed_at in time_rows.all():
  935. if duration_seconds:
  936. total_seconds += duration_seconds
  937. elif started_at and completed_at:
  938. elapsed = (completed_at - started_at).total_seconds()
  939. if elapsed > 0:
  940. total_seconds += int(elapsed)
  941. total_time = total_seconds / 3600 # Convert to hours
  942. filament_result = await db.execute(
  943. select(func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0)).where(*base_conditions)
  944. )
  945. total_filament = filament_result.scalar() or 0
  946. cost_result = await db.execute(select(func.sum(PrintLogEntry.cost)).where(*base_conditions))
  947. total_cost = cost_result.scalar() or 0
  948. # By filament type (split comma-separated values for multi-material prints)
  949. filament_type_result = await db.execute(
  950. select(PrintLogEntry.filament_type).where(PrintLogEntry.filament_type.isnot(None), *base_conditions)
  951. )
  952. prints_by_filament: dict[str, int] = {}
  953. for (filament_types,) in filament_type_result.all():
  954. for ftype in filament_types.split(","):
  955. ftype = ftype.strip()
  956. if ftype:
  957. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  958. # By printer
  959. printer_result = await db.execute(
  960. select(PrintLogEntry.printer_id, func.count(PrintLogEntry.id))
  961. .where(*base_conditions)
  962. .group_by(PrintLogEntry.printer_id)
  963. )
  964. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  965. # Time accuracy — compare each completed run's actual duration to the
  966. # slicer's estimate on the linked archive. Runs without a linked archive
  967. # (NULL archive_id) or without an estimate are excluded.
  968. accuracy_rows = await db.execute(
  969. select(
  970. PrintLogEntry.duration_seconds,
  971. PrintLogEntry.started_at,
  972. PrintLogEntry.completed_at,
  973. PrintLogEntry.printer_id,
  974. PrintArchive.print_time_seconds,
  975. )
  976. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  977. .where(
  978. PrintLogEntry.status == "completed",
  979. PrintArchive.print_time_seconds.isnot(None),
  980. *base_conditions,
  981. )
  982. )
  983. # Accuracy is meaningful only when the estimate roughly describes the
  984. # work the run actually performed. Two shapes produce wildly-off ratios
  985. # that are pure noise:
  986. # - multi-plate ``.gcode.3mf`` printed plate-by-plate: each run's
  987. # actual is one plate, the archive's estimate is the sum across
  988. # plates (post-#1593 parser fix), so the ratio is roughly N×100%
  989. # for an N-plate file. Pre-fix this shape was also broken, just
  990. # less dramatically — the estimate was plate-1-only so the ratio
  991. # was meaningless rather than N×.
  992. # - manual interventions / purge waste blowing the actual far past
  993. # the estimate.
  994. # Clamp to the [50%, 200%] band so the printer-level average reflects
  995. # real slicer-vs-reality drift, not multi-plate accounting or one-off
  996. # outliers. Single-plate archives — the case the metric is actually
  997. # designed for — stay fully included.
  998. _ACCURACY_BAND_LO = 50.0
  999. _ACCURACY_BAND_HI = 200.0
  1000. average_accuracy = None
  1001. accuracy_by_printer: dict[str, float] = {}
  1002. accuracies: list[float] = []
  1003. printer_accuracies: dict[str, list[float]] = {}
  1004. for duration_seconds, started_at, completed_at, run_printer_id, estimate_seconds in accuracy_rows.all():
  1005. actual_seconds = duration_seconds
  1006. if not actual_seconds and started_at and completed_at:
  1007. elapsed = (completed_at - started_at).total_seconds()
  1008. actual_seconds = int(elapsed) if elapsed > 0 else None
  1009. if not actual_seconds or not estimate_seconds:
  1010. continue
  1011. accuracy = (estimate_seconds / actual_seconds) * 100
  1012. if accuracy < _ACCURACY_BAND_LO or accuracy > _ACCURACY_BAND_HI:
  1013. continue
  1014. accuracies.append(accuracy)
  1015. printer_key = str(run_printer_id) if run_printer_id else "unknown"
  1016. printer_accuracies.setdefault(printer_key, []).append(accuracy)
  1017. if accuracies:
  1018. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  1019. for printer_key, accs in printer_accuracies.items():
  1020. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  1021. # Energy totals - check which mode to use
  1022. from backend.app.api.routes.settings import get_setting
  1023. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  1024. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  1025. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  1026. total_energy_kwh: float = 0.0
  1027. total_energy_cost: float = 0.0
  1028. energy_data_warming_up = False
  1029. if energy_tracking_mode == "total" and not date_from and not date_to:
  1030. # All-time total consumption — read live lifetime counters.
  1031. total_energy_kwh = await _sum_live_plug_totals(db)
  1032. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  1033. elif energy_tracking_mode == "total":
  1034. # Total consumption mode with a date filter (#941): use hourly snapshots
  1035. # to compute per-plug (endpoint - baseline) deltas.
  1036. total_energy_kwh, energy_data_warming_up = await _sum_snapshot_deltas(
  1037. db,
  1038. dt_from=(datetime.combine(date_from, time.min, tzinfo=timezone.utc) if date_from else None),
  1039. dt_to=(datetime.combine(date_to, time.max, tzinfo=timezone.utc) if date_to else None),
  1040. )
  1041. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  1042. else:
  1043. # Per-print mode: sum the per-run energy column from PrintLogEntry.
  1044. energy_kwh_result = await db.execute(select(func.sum(PrintLogEntry.energy_kwh)).where(*base_conditions))
  1045. total_energy_kwh = energy_kwh_result.scalar() or 0
  1046. energy_cost_result = await db.execute(select(func.sum(PrintLogEntry.energy_cost)).where(*base_conditions))
  1047. total_energy_cost = energy_cost_result.scalar() or 0
  1048. return ArchiveStats(
  1049. total_prints=total_prints,
  1050. successful_prints=successful_prints,
  1051. failed_prints=failed_prints,
  1052. cancelled_prints=cancelled_prints,
  1053. total_print_time_hours=round(total_time, 1),
  1054. total_filament_grams=round(total_filament, 1),
  1055. total_cost=round(total_cost, 2),
  1056. prints_by_filament_type=prints_by_filament,
  1057. prints_by_printer=prints_by_printer,
  1058. average_time_accuracy=average_accuracy,
  1059. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  1060. total_energy_kwh=round(total_energy_kwh, 3),
  1061. total_energy_cost=round(total_energy_cost, 3),
  1062. energy_data_warming_up=energy_data_warming_up,
  1063. )
  1064. async def _sum_live_plug_totals(db: AsyncSession) -> float:
  1065. """Sum the live lifetime counter from every smart plug.
  1066. Used for all-time "total consumption" mode. Only the current value is
  1067. available so this can't be date-filtered — use `_sum_snapshot_deltas` for
  1068. that case.
  1069. """
  1070. from backend.app.api.routes.settings import get_setting
  1071. from backend.app.models.smart_plug import SmartPlug
  1072. from backend.app.services.homeassistant import homeassistant_service
  1073. from backend.app.services.mqtt_relay import mqtt_relay
  1074. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  1075. from backend.app.services.tasmota import tasmota_service
  1076. plugs_result = await db.execute(select(SmartPlug))
  1077. plugs = list(plugs_result.scalars().all())
  1078. ha_url = await get_setting(db, "ha_url") or ""
  1079. ha_token = await get_setting(db, "ha_token") or ""
  1080. homeassistant_service.configure(ha_url, ha_token)
  1081. total = 0.0
  1082. for plug in plugs:
  1083. if plug.plug_type == "tasmota":
  1084. energy = await tasmota_service.get_energy(plug)
  1085. if energy and energy.get("total") is not None:
  1086. total += energy["total"]
  1087. elif plug.plug_type == "homeassistant":
  1088. energy = await homeassistant_service.get_energy(plug)
  1089. if energy and energy.get("total") is not None:
  1090. total += energy["total"]
  1091. elif plug.plug_type == "mqtt":
  1092. # MQTT plugs only expose today's counter, not lifetime.
  1093. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  1094. if mqtt_data and mqtt_data.energy is not None:
  1095. total += mqtt_data.energy
  1096. elif plug.plug_type == "rest":
  1097. energy = await rest_smart_plug_service.get_energy(plug)
  1098. if energy and energy.get("today") is not None:
  1099. total += energy["today"]
  1100. return total
  1101. async def _sum_snapshot_deltas(
  1102. db: AsyncSession,
  1103. *,
  1104. dt_from: datetime | None,
  1105. dt_to: datetime | None,
  1106. ) -> tuple[float, bool]:
  1107. """Sum per-plug energy consumption over a date range using hourly snapshots.
  1108. For each plug:
  1109. * baseline = last snapshot at or before `dt_from` (ideal)
  1110. — if missing, fall back to the earliest snapshot ever
  1111. recorded for the plug and flag the result as warming up.
  1112. * endpoint = last snapshot at or before `dt_to` (or most recent overall)
  1113. * delta = max(0, endpoint - baseline) — clamp counter resets to 0.
  1114. Returns (total_kwh, warming_up). `warming_up = True` means at least one plug
  1115. had no baseline before `dt_from` (fresh install or fresh upgrade), so the
  1116. result undercounts the beginning of the range.
  1117. """
  1118. from backend.app.models.smart_plug import SmartPlug
  1119. from backend.app.models.smart_plug_energy_snapshot import SmartPlugEnergySnapshot
  1120. from backend.app.utils.local_time import to_naive_utc
  1121. # ``recorded_at`` is a naive column holding UTC. Binding an aware datetime
  1122. # against it raises DataError on asyncpg (SQLite silently drops the offset),
  1123. # which took the whole date-filtered energy figure down on Postgres.
  1124. dt_from = to_naive_utc(dt_from)
  1125. dt_to = to_naive_utc(dt_to)
  1126. plug_ids_result = await db.execute(select(SmartPlug.id))
  1127. plug_ids = [row[0] for row in plug_ids_result.all()]
  1128. if not plug_ids:
  1129. return 0.0, False
  1130. total = 0.0
  1131. warming_up = False
  1132. for plug_id in plug_ids:
  1133. baseline: float | None = None
  1134. if dt_from is not None:
  1135. baseline_q = await db.execute(
  1136. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1137. .where(
  1138. SmartPlugEnergySnapshot.plug_id == plug_id,
  1139. SmartPlugEnergySnapshot.recorded_at <= dt_from,
  1140. )
  1141. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  1142. .limit(1)
  1143. )
  1144. baseline = baseline_q.scalar()
  1145. if baseline is None:
  1146. # No snapshot before range start — fall back to the earliest
  1147. # snapshot ever recorded. Result undercounts the pre-first-snapshot
  1148. # portion of the range; signal that to the frontend.
  1149. earliest_q = await db.execute(
  1150. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1151. .where(SmartPlugEnergySnapshot.plug_id == plug_id)
  1152. .order_by(SmartPlugEnergySnapshot.recorded_at.asc())
  1153. .limit(1)
  1154. )
  1155. baseline = earliest_q.scalar()
  1156. if baseline is None:
  1157. # No snapshots at all for this plug yet.
  1158. warming_up = True
  1159. continue
  1160. warming_up = True
  1161. endpoint_conditions = [SmartPlugEnergySnapshot.plug_id == plug_id]
  1162. if dt_to is not None:
  1163. endpoint_conditions.append(SmartPlugEnergySnapshot.recorded_at <= dt_to)
  1164. endpoint_q = await db.execute(
  1165. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1166. .where(*endpoint_conditions)
  1167. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  1168. .limit(1)
  1169. )
  1170. endpoint = endpoint_q.scalar()
  1171. if endpoint is None:
  1172. continue
  1173. total += max(0.0, endpoint - baseline)
  1174. return total, warming_up
  1175. @router.get("/tags")
  1176. async def get_all_tags(
  1177. db: AsyncSession = Depends(get_db),
  1178. auth_result: tuple[User | None, bool] = Depends(
  1179. require_ownership_permission(
  1180. Permission.ARCHIVES_READ_ALL,
  1181. Permission.ARCHIVES_READ_OWN,
  1182. )
  1183. ),
  1184. ):
  1185. """List all unique tags with usage counts.
  1186. Returns a list of tags sorted by count (descending), then by name.
  1187. """
  1188. user, can_read_all = auth_result
  1189. # Query all archives with non-null tags
  1190. tag_conditions = [PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None)]
  1191. if user is not None and not can_read_all:
  1192. tag_conditions.append(PrintArchive.created_by_id == user.id)
  1193. result = await db.execute(select(PrintArchive.tags).where(*tag_conditions))
  1194. all_tags_rows = result.all()
  1195. # Count occurrences of each tag
  1196. tag_counts: dict[str, int] = {}
  1197. for (tags_str,) in all_tags_rows:
  1198. if tags_str:
  1199. for tag in tags_str.split(","):
  1200. tag = tag.strip()
  1201. if tag:
  1202. tag_counts[tag] = tag_counts.get(tag, 0) + 1
  1203. # Convert to list and sort by count (desc), then name (asc)
  1204. tags_list = [{"name": name, "count": count} for name, count in tag_counts.items()]
  1205. tags_list.sort(key=lambda x: (-x["count"], x["name"].lower()))
  1206. return tags_list
  1207. @router.put("/tags/{tag_name}")
  1208. async def rename_tag(
  1209. tag_name: str,
  1210. request: Request,
  1211. db: AsyncSession = Depends(get_db),
  1212. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1213. ):
  1214. """Rename a tag across all archives.
  1215. Request body should contain {"new_name": "new tag name"}.
  1216. Returns the count of affected archives.
  1217. """
  1218. body = await request.json()
  1219. new_name = body.get("new_name", "").strip()
  1220. if not new_name:
  1221. raise HTTPException(400, "new_name is required")
  1222. if new_name == tag_name:
  1223. return {"affected": 0}
  1224. # Find all archives containing the old tag
  1225. result = await db.execute(
  1226. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1227. )
  1228. archives = list(result.scalars().all())
  1229. affected = 0
  1230. for archive in archives:
  1231. if not archive.tags:
  1232. continue
  1233. tags = [t.strip() for t in archive.tags.split(",")]
  1234. if tag_name in tags:
  1235. # Replace old tag with new tag
  1236. new_tags = [new_name if t == tag_name else t for t in tags]
  1237. # Remove duplicates while preserving order
  1238. seen = set()
  1239. unique_tags = []
  1240. for t in new_tags:
  1241. if t not in seen:
  1242. seen.add(t)
  1243. unique_tags.append(t)
  1244. archive.tags = ", ".join(unique_tags)
  1245. affected += 1
  1246. await db.commit()
  1247. return {"affected": affected}
  1248. @router.delete("/tags/{tag_name}")
  1249. async def delete_tag(
  1250. tag_name: str,
  1251. db: AsyncSession = Depends(get_db),
  1252. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1253. ):
  1254. """Delete a tag from all archives.
  1255. Returns the count of affected archives.
  1256. """
  1257. # Find all archives containing the tag
  1258. result = await db.execute(
  1259. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1260. )
  1261. archives = list(result.scalars().all())
  1262. affected = 0
  1263. for archive in archives:
  1264. if not archive.tags:
  1265. continue
  1266. tags = [t.strip() for t in archive.tags.split(",")]
  1267. if tag_name in tags:
  1268. # Remove the tag
  1269. new_tags = [t for t in tags if t != tag_name]
  1270. archive.tags = ", ".join(new_tags) if new_tags else None
  1271. affected += 1
  1272. await db.commit()
  1273. return {"affected": affected}
  1274. @router.get("/{archive_id}", response_model=ArchiveResponse)
  1275. async def get_archive(
  1276. archive_id: int,
  1277. db: AsyncSession = Depends(get_db),
  1278. auth_result: tuple[User | None, bool] = Depends(
  1279. require_ownership_permission(
  1280. Permission.ARCHIVES_READ_ALL,
  1281. Permission.ARCHIVES_READ_OWN,
  1282. )
  1283. ),
  1284. ):
  1285. """Get a specific archive."""
  1286. user, can_read_all = auth_result
  1287. service = ArchiveService(db)
  1288. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1289. # Find duplicates
  1290. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1291. duplicates = await service.find_duplicates(
  1292. archive_id=archive.id,
  1293. content_hash=archive.content_hash,
  1294. print_name=archive.print_name,
  1295. makerworld_model_id=makerworld_id,
  1296. )
  1297. run_aggregates = await _load_run_aggregates(db, [archive.id])
  1298. return archive_to_response(archive, duplicates, run_aggregate=run_aggregates.get(archive.id))
  1299. @router.get("/{archive_id}/delete-impact")
  1300. async def get_archive_delete_impact(
  1301. archive_id: int,
  1302. db: AsyncSession = Depends(get_db),
  1303. auth_result: tuple[User | None, bool] = Depends(
  1304. require_ownership_permission(
  1305. Permission.ARCHIVES_READ_ALL,
  1306. Permission.ARCHIVES_READ_OWN,
  1307. )
  1308. ),
  1309. ):
  1310. """Pre-flight for the delete-confirm modal (#1734).
  1311. Returns the number of related queue items the user is about to remove
  1312. AND whether any of them are currently printing (which would block the
  1313. delete with a 409 — surfaced to the modal so it can disable the
  1314. confirm button instead of failing on submit). Cheap, single endpoint —
  1315. not folded into the archive GET response so the much larger list
  1316. endpoint isn't forced to run the same query per row.
  1317. """
  1318. user, can_read_all = auth_result
  1319. service = ArchiveService(db)
  1320. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1321. from backend.app.services.archive import _count_related_queue_items
  1322. total, printing = await _count_related_queue_items(db, archive.id)
  1323. return {"related_queue_items": total, "currently_printing": printing}
  1324. @router.get("/{archive_id}/runs", response_model=PrintLogResponse)
  1325. async def list_archive_runs(
  1326. archive_id: int,
  1327. db: AsyncSession = Depends(get_db),
  1328. auth_result: tuple[User | None, bool] = Depends(
  1329. require_ownership_permission(
  1330. Permission.ARCHIVES_READ_ALL,
  1331. Permission.ARCHIVES_READ_OWN,
  1332. )
  1333. ),
  1334. ):
  1335. """List PrintLogEntry rows for this archive — one per print event.
  1336. Newest first. Drives the per-archive "Print Log" view (#1378).
  1337. """
  1338. from backend.app.models.print_log import PrintLogEntry
  1339. from backend.app.schemas.print_log import PrintLogEntrySchema
  1340. user, can_read_all = auth_result
  1341. _ensure_archive_visible(await db.get(PrintArchive, archive_id), user, can_read_all)
  1342. rows = await db.execute(
  1343. select(PrintLogEntry)
  1344. .where(PrintLogEntry.archive_id == archive_id)
  1345. .order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc())
  1346. )
  1347. entries = list(rows.scalars().all())
  1348. items = [PrintLogEntrySchema.model_validate(e, from_attributes=True) for e in entries]
  1349. return PrintLogResponse(items=items, total=len(items))
  1350. @router.get("/{archive_id}/similar")
  1351. async def find_similar_archives(
  1352. archive_id: int,
  1353. limit: int = 10,
  1354. db: AsyncSession = Depends(get_db),
  1355. auth_result: tuple[User | None, bool] = Depends(
  1356. require_ownership_permission(
  1357. Permission.ARCHIVES_READ_ALL,
  1358. Permission.ARCHIVES_READ_OWN,
  1359. )
  1360. ),
  1361. ):
  1362. """Find archives with similar settings for comparison.
  1363. Returns archives that match by:
  1364. - Same print name (highest priority)
  1365. - Same file content hash
  1366. - Same filament type
  1367. """
  1368. from backend.app.services.archive_comparison import ArchiveComparisonService
  1369. user, can_read_all = auth_result
  1370. _ensure_archive_visible(await db.get(PrintArchive, archive_id), user, can_read_all)
  1371. service = ArchiveComparisonService(db)
  1372. try:
  1373. return await service.find_similar_archives(archive_id, limit=limit)
  1374. except ValueError as e:
  1375. raise HTTPException(404, str(e))
  1376. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  1377. async def update_archive(
  1378. archive_id: int,
  1379. update_data: ArchiveUpdate,
  1380. db: AsyncSession = Depends(get_db),
  1381. auth_result: tuple[User | None, bool] = Depends(
  1382. require_ownership_permission(
  1383. Permission.ARCHIVES_UPDATE_ALL,
  1384. Permission.ARCHIVES_UPDATE_OWN,
  1385. )
  1386. ),
  1387. ):
  1388. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  1389. from sqlalchemy.orm import selectinload
  1390. user, can_modify_all = auth_result
  1391. result = await db.execute(
  1392. select(PrintArchive)
  1393. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1394. .where(PrintArchive.id == archive_id)
  1395. )
  1396. archive = result.scalar_one_or_none()
  1397. if not archive:
  1398. raise HTTPException(404, "Archive not found")
  1399. # Ownership check
  1400. if not can_modify_all:
  1401. if archive.created_by_id != user.id:
  1402. raise HTTPException(403, "You can only update your own archives")
  1403. update_payload = update_data.model_dump(exclude_unset=True)
  1404. for field, value in update_payload.items():
  1405. setattr(archive, field, value)
  1406. # #1444: Mirror per-run classification fields to the most recent
  1407. # PrintLogEntry for this archive. PrintLogEntry.failure_reason is captured
  1408. # once at print-completion time from archive.failure_reason — which is
  1409. # NULL until the user classifies the failure via the Edit Archive modal.
  1410. # Without this mirror the Failure Analysis widget (which groups by
  1411. # print_log_entries.failure_reason) keeps showing "Unknown" forever.
  1412. # Same desync hits status: flipping it in the modal wouldn't update the
  1413. # entry either. Only the latest entry is touched because that's the run
  1414. # the modal is implicitly showing (archive.failure_reason / status are
  1415. # overwritten on each reprint to reflect the latest run's outcome).
  1416. mirror_fields = {"failure_reason", "status"}
  1417. to_mirror = {k: v for k, v in update_payload.items() if k in mirror_fields}
  1418. if to_mirror:
  1419. from backend.app.models.print_log import PrintLogEntry
  1420. latest_entry = await db.scalar(
  1421. select(PrintLogEntry)
  1422. .where(PrintLogEntry.archive_id == archive_id)
  1423. .order_by(PrintLogEntry.id.desc())
  1424. .limit(1)
  1425. )
  1426. if latest_entry is not None:
  1427. for field, value in to_mirror.items():
  1428. setattr(latest_entry, field, value)
  1429. await db.commit()
  1430. # Re-fetch with relationships loaded after commit
  1431. result = await db.execute(
  1432. select(PrintArchive)
  1433. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1434. .where(PrintArchive.id == archive_id)
  1435. )
  1436. archive = result.scalar_one_or_none()
  1437. # Load run aggregate so the time/accuracy badge stays consistent with
  1438. # the list / detail endpoints when the frontend re-renders the card
  1439. # after a PATCH (#1608).
  1440. run_aggregates = await _load_run_aggregates(db, [archive.id]) if archive else {}
  1441. return archive_to_response(archive, run_aggregate=run_aggregates.get(archive.id) if archive else None)
  1442. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  1443. async def toggle_favorite(
  1444. archive_id: int,
  1445. db: AsyncSession = Depends(get_db),
  1446. auth_result: tuple[User | None, bool] = Depends(
  1447. require_ownership_permission(
  1448. Permission.ARCHIVES_UPDATE_ALL,
  1449. Permission.ARCHIVES_UPDATE_OWN,
  1450. )
  1451. ),
  1452. ):
  1453. """Toggle favorite status for an archive."""
  1454. user, can_modify_all = auth_result
  1455. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1456. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  1457. archive.is_favorite = not archive.is_favorite
  1458. await db.commit()
  1459. await db.refresh(archive)
  1460. return archive
  1461. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  1462. async def rescan_archive(
  1463. archive_id: int,
  1464. db: AsyncSession = Depends(get_db),
  1465. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1466. ):
  1467. """Rescan the 3MF file and update metadata."""
  1468. from backend.app.api.routes.settings import get_setting
  1469. from backend.app.services.archive import ThreeMFParser
  1470. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1471. archive = result.scalar_one_or_none()
  1472. if not archive:
  1473. raise HTTPException(404, "Archive not found")
  1474. file_path = settings.base_dir / archive.file_path
  1475. if not file_path.is_file():
  1476. raise HTTPException(404, "Archive file not found")
  1477. # Parse the 3MF file
  1478. parser = ThreeMFParser(file_path)
  1479. metadata = parser.parse()
  1480. # Update fields from metadata
  1481. if metadata.get("filament_type"):
  1482. archive.filament_type = metadata["filament_type"]
  1483. if metadata.get("filament_color"):
  1484. archive.filament_color = metadata["filament_color"]
  1485. if metadata.get("print_time_seconds"):
  1486. archive.print_time_seconds = metadata["print_time_seconds"]
  1487. if metadata.get("filament_used_grams"):
  1488. archive.filament_used_grams = metadata["filament_used_grams"]
  1489. if metadata.get("layer_height"):
  1490. archive.layer_height = metadata["layer_height"]
  1491. if metadata.get("nozzle_diameter"):
  1492. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1493. if metadata.get("bed_temperature"):
  1494. archive.bed_temperature = metadata["bed_temperature"]
  1495. if metadata.get("bed_type"):
  1496. archive.bed_type = metadata["bed_type"]
  1497. if metadata.get("nozzle_temperature"):
  1498. archive.nozzle_temperature = metadata["nozzle_temperature"]
  1499. if metadata.get("makerworld_url"):
  1500. archive.makerworld_url = metadata["makerworld_url"]
  1501. if metadata.get("designer"):
  1502. archive.designer = metadata["designer"]
  1503. # Calculate cost: prefer spool-based cost if available, else catalog-based.
  1504. # When spool-based costs exist but don't cover every filament gram used
  1505. # (#1344), fall back to the global default rate for the untracked weight
  1506. # so the displayed cost still reflects the whole print.
  1507. if archive.filament_used_grams and archive.filament_type:
  1508. default_cost_setting = await get_setting(db, "default_filament_cost")
  1509. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1510. usage_result = await db.execute(
  1511. select(
  1512. func.sum(SpoolUsageHistory.cost),
  1513. func.sum(SpoolUsageHistory.weight_used),
  1514. ).where(SpoolUsageHistory.archive_id == archive.id)
  1515. )
  1516. usage_cost_row = usage_result.one()
  1517. usage_cost = usage_cost_row[0]
  1518. tracked_grams = float(usage_cost_row[1] or 0)
  1519. if usage_cost is not None and usage_cost > 0:
  1520. total_cost = float(usage_cost)
  1521. untracked_grams = max(0.0, archive.filament_used_grams - tracked_grams)
  1522. if untracked_grams > 0 and default_cost_per_kg > 0:
  1523. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1524. archive.cost = float(Decimal(str(total_cost)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
  1525. else:
  1526. primary_type = archive.filament_type.split(",")[0].strip()
  1527. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1528. filament = filament_result.scalar_one_or_none()
  1529. if filament:
  1530. archive.cost = float(
  1531. Decimal(str((archive.filament_used_grams / 1000) * filament.cost_per_kg)).quantize(
  1532. Decimal("0.01"), rounding=ROUND_HALF_UP
  1533. )
  1534. )
  1535. else:
  1536. archive.cost = float(
  1537. Decimal(str((archive.filament_used_grams / 1000) * default_cost_per_kg)).quantize(
  1538. Decimal("0.01"), rounding=ROUND_HALF_UP
  1539. )
  1540. )
  1541. await db.commit()
  1542. await db.refresh(archive)
  1543. return archive
  1544. @router.post("/recalculate-costs")
  1545. async def recalculate_all_costs(
  1546. db: AsyncSession = Depends(get_db),
  1547. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1548. ):
  1549. """Recalculate costs for all archives based on filament usage and prices."""
  1550. from backend.app.api.routes.settings import get_setting
  1551. result = await db.execute(select(PrintArchive))
  1552. archives = list(result.scalars().all())
  1553. # Load all filaments for lookup
  1554. filament_result = await db.execute(select(Filament))
  1555. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  1556. # Get default filament cost from settings
  1557. default_cost_setting = await get_setting(db, "default_filament_cost")
  1558. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1559. # Pre-fetch all usage costs and tracked weight by archive_id.
  1560. # Tracked weight is used to top-up the cost at the default rate for any
  1561. # filament grams not covered by an inventory spool (#1344).
  1562. usage_costs_result = await db.execute(
  1563. select(
  1564. SpoolUsageHistory.archive_id,
  1565. func.sum(SpoolUsageHistory.cost),
  1566. func.sum(SpoolUsageHistory.weight_used),
  1567. ).group_by(SpoolUsageHistory.archive_id)
  1568. )
  1569. usage_costs = usage_costs_result.fetchall()
  1570. cost_map = {
  1571. row[0]: (row[1], float(row[2] or 0))
  1572. for row in usage_costs
  1573. if row[0] is not None and row[1] is not None and row[1] > 0
  1574. }
  1575. updated = 0
  1576. for archive in archives:
  1577. usage = cost_map.get(archive.id)
  1578. if usage is not None:
  1579. usage_cost, tracked_grams = usage
  1580. total_cost = float(usage_cost)
  1581. archive_grams = float(archive.filament_used_grams or 0)
  1582. untracked_grams = max(0.0, archive_grams - tracked_grams)
  1583. if untracked_grams > 0 and default_cost_per_kg > 0:
  1584. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1585. new_cost = round(total_cost, 2)
  1586. else:
  1587. # Fallback: sum costs for old records by print_name
  1588. usage_result = await db.execute(
  1589. select(func.sum(SpoolUsageHistory.cost)).where(
  1590. SpoolUsageHistory.print_name == archive.print_name,
  1591. SpoolUsageHistory.archive_id.is_(None),
  1592. )
  1593. )
  1594. fallback_cost = usage_result.scalar()
  1595. if fallback_cost is not None and fallback_cost > 0:
  1596. new_cost = round(fallback_cost, 2)
  1597. elif archive.filament_used_grams and archive.filament_type:
  1598. primary_type = archive.filament_type.split(",")[0].strip()
  1599. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  1600. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  1601. else:
  1602. new_cost = None
  1603. if new_cost is not None and archive.cost != new_cost:
  1604. archive.cost = new_cost
  1605. updated += 1
  1606. await db.commit()
  1607. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  1608. @router.post("/rescan-all")
  1609. async def rescan_all_archives(
  1610. db: AsyncSession = Depends(get_db),
  1611. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1612. ):
  1613. """Rescan all archives and update their metadata."""
  1614. from backend.app.services.archive import ThreeMFParser
  1615. result = await db.execute(select(PrintArchive))
  1616. archives = list(result.scalars().all())
  1617. updated = 0
  1618. errors = []
  1619. for archive in archives:
  1620. try:
  1621. file_path = settings.base_dir / archive.file_path
  1622. if not file_path.is_file():
  1623. errors.append({"id": archive.id, "error": "File not found"})
  1624. continue
  1625. parser = ThreeMFParser(file_path)
  1626. metadata = parser.parse()
  1627. if metadata.get("filament_type"):
  1628. archive.filament_type = metadata["filament_type"]
  1629. if metadata.get("filament_color"):
  1630. archive.filament_color = metadata["filament_color"]
  1631. if metadata.get("print_time_seconds"):
  1632. archive.print_time_seconds = metadata["print_time_seconds"]
  1633. if metadata.get("filament_used_grams"):
  1634. archive.filament_used_grams = metadata["filament_used_grams"]
  1635. if metadata.get("layer_height"):
  1636. archive.layer_height = metadata["layer_height"]
  1637. if metadata.get("nozzle_diameter"):
  1638. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1639. if metadata.get("makerworld_url"):
  1640. archive.makerworld_url = metadata["makerworld_url"]
  1641. if metadata.get("designer"):
  1642. archive.designer = metadata["designer"]
  1643. updated += 1
  1644. except Exception as e:
  1645. logger.exception("Failed to rescan archive %s: %s", archive.id, e)
  1646. errors.append({"id": archive.id, "error": "Failed to parse 3MF file"})
  1647. await db.commit()
  1648. return {"updated": updated, "errors": errors}
  1649. @router.get("/{archive_id}/duplicates")
  1650. async def get_archive_duplicates(
  1651. archive_id: int,
  1652. db: AsyncSession = Depends(get_db),
  1653. auth_result: tuple[User | None, bool] = Depends(
  1654. require_ownership_permission(
  1655. Permission.ARCHIVES_READ_ALL,
  1656. Permission.ARCHIVES_READ_OWN,
  1657. )
  1658. ),
  1659. ):
  1660. """Get duplicates for a specific archive."""
  1661. user, can_read_all = auth_result
  1662. service = ArchiveService(db)
  1663. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1664. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1665. duplicates = await service.find_duplicates(
  1666. archive_id=archive.id,
  1667. content_hash=archive.content_hash,
  1668. print_name=archive.print_name,
  1669. makerworld_model_id=makerworld_id,
  1670. )
  1671. return {"duplicates": duplicates, "count": len(duplicates)}
  1672. @router.post("/backfill-hashes")
  1673. async def backfill_content_hashes(
  1674. db: AsyncSession = Depends(get_db),
  1675. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1676. ):
  1677. """Compute and store content hashes for all archives missing them."""
  1678. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  1679. archives = list(result.scalars().all())
  1680. updated = 0
  1681. errors = []
  1682. for archive in archives:
  1683. try:
  1684. file_path = settings.base_dir / archive.file_path
  1685. if not file_path.is_file():
  1686. errors.append({"id": archive.id, "error": "File not found"})
  1687. continue
  1688. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  1689. updated += 1
  1690. except Exception as e:
  1691. logger.exception("Failed to compute hash for archive %s: %s", archive.id, e)
  1692. errors.append({"id": archive.id, "error": "Failed to compute hash"})
  1693. await db.commit()
  1694. return {"updated": updated, "errors": errors}
  1695. @router.delete("/{archive_id}")
  1696. async def delete_archive(
  1697. archive_id: int,
  1698. purge_stats: bool = Query(
  1699. False,
  1700. description=(
  1701. "When false (default) the archive is soft-deleted — files removed "
  1702. "from disk, row hidden from listings, but its filament / energy / "
  1703. "time / cost contribution stays in Quick Stats. Set true to also "
  1704. "drop the row from statistics (#1343)."
  1705. ),
  1706. ),
  1707. db: AsyncSession = Depends(get_db),
  1708. auth_result: tuple[User | None, bool] = Depends(
  1709. require_ownership_permission(
  1710. Permission.ARCHIVES_DELETE_ALL,
  1711. Permission.ARCHIVES_DELETE_OWN,
  1712. )
  1713. ),
  1714. ):
  1715. """Delete an archive (soft by default; ``?purge_stats=true`` to hard-delete).
  1716. Both delete paths now cascade to related ``print_queue`` rows (#1734) —
  1717. hard delete via the ``ON DELETE CASCADE`` FK, soft delete via the
  1718. ``_delete_related_queue_items`` helper. A 409 guard blocks the delete
  1719. when any related queue item is currently mid-print so the dispatcher
  1720. doesn't lose its metadata trail under the running print.
  1721. """
  1722. user, can_modify_all = auth_result
  1723. # Get archive first to check ownership
  1724. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1725. archive = result.scalar_one_or_none()
  1726. if not archive:
  1727. raise HTTPException(404, "Archive not found")
  1728. # Ownership check
  1729. if not can_modify_all:
  1730. if archive.created_by_id != user.id:
  1731. raise HTTPException(403, "You can only delete your own archives")
  1732. # #1734: block delete when any related queue item is currently printing.
  1733. # Both soft and hard delete are gated — an in-flight print needs its
  1734. # backing archive to stay around for the metadata trail (filament,
  1735. # plate, ams_mapping). The user can stop the print first, then retry.
  1736. from backend.app.services.archive import _count_related_queue_items
  1737. _related_total, related_printing = await _count_related_queue_items(db, archive_id)
  1738. if related_printing > 0:
  1739. raise HTTPException(
  1740. 409,
  1741. f"Cannot delete archive — {related_printing} related queue item(s) are "
  1742. f"currently printing. Stop the print first, then retry.",
  1743. )
  1744. service = ArchiveService(db)
  1745. if purge_stats:
  1746. # Hard-delete the linked PrintLogEntry rows first so their filament /
  1747. # cost / count contributions disappear from /archives/stats. The FK is
  1748. # ON DELETE SET NULL, so without this delete the runs would survive
  1749. # the archive row and keep showing up in totals (#1343 / #1378).
  1750. from sqlalchemy import delete as sa_delete
  1751. from backend.app.models.print_log import PrintLogEntry
  1752. await db.execute(sa_delete(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id))
  1753. await db.commit()
  1754. if not await service.delete_archive(archive_id):
  1755. raise HTTPException(404, "Archive not found")
  1756. return {"status": "deleted", "purged_from_stats": True}
  1757. if not await service.soft_delete_archive(archive_id):
  1758. raise HTTPException(404, "Archive not found")
  1759. return {"status": "deleted", "purged_from_stats": False}
  1760. @router.get("/{archive_id}/download")
  1761. async def download_archive(
  1762. archive_id: int,
  1763. inline: bool = False,
  1764. db: AsyncSession = Depends(get_db),
  1765. auth_result: tuple[User | None, bool] = Depends(
  1766. require_ownership_permission(
  1767. Permission.ARCHIVES_READ_ALL,
  1768. Permission.ARCHIVES_READ_OWN,
  1769. )
  1770. ),
  1771. ):
  1772. """Download the 3MF file."""
  1773. user, can_read_all = auth_result
  1774. service = ArchiveService(db)
  1775. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1776. file_path = settings.base_dir / archive.file_path
  1777. if not file_path.is_file():
  1778. raise HTTPException(404, "File not found")
  1779. # Use inline disposition to let browser/OS handle file association
  1780. content_disposition = "inline" if inline else "attachment"
  1781. return FileResponse(
  1782. path=file_path,
  1783. filename=archive.filename,
  1784. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1785. content_disposition_type=content_disposition,
  1786. )
  1787. @router.get("/{archive_id}/file/{filename}")
  1788. async def download_archive_with_filename(
  1789. archive_id: int,
  1790. filename: str,
  1791. db: AsyncSession = Depends(get_db),
  1792. auth_result: tuple[User | None, bool] = Depends(
  1793. require_ownership_permission(
  1794. Permission.ARCHIVES_READ_ALL,
  1795. Permission.ARCHIVES_READ_OWN,
  1796. )
  1797. ),
  1798. ):
  1799. """Download the 3MF file with filename in URL."""
  1800. user, can_read_all = auth_result
  1801. service = ArchiveService(db)
  1802. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1803. file_path = settings.base_dir / archive.file_path
  1804. if not file_path.is_file():
  1805. raise HTTPException(404, "File not found")
  1806. return FileResponse(
  1807. path=file_path,
  1808. filename=archive.filename,
  1809. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1810. )
  1811. @router.post("/{archive_id}/slicer-token")
  1812. async def create_archive_slicer_token(
  1813. archive_id: int,
  1814. db: AsyncSession = Depends(get_db),
  1815. auth_result: tuple[User | None, bool] = Depends(
  1816. require_ownership_permission(
  1817. Permission.ARCHIVES_READ_ALL,
  1818. Permission.ARCHIVES_READ_OWN,
  1819. )
  1820. ),
  1821. ):
  1822. """Create a short-lived download token for opening files in slicer applications.
  1823. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  1824. auth headers, so they use this token in the URL path instead.
  1825. """
  1826. from backend.app.core.auth import create_slicer_download_token
  1827. user, can_read_all = auth_result
  1828. service = ArchiveService(db)
  1829. _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1830. token = await create_slicer_download_token("archive", archive_id)
  1831. return {"token": token}
  1832. @router.get("/{archive_id}/dl/{token}/{filename}")
  1833. async def download_archive_for_slicer(
  1834. archive_id: int,
  1835. token: str,
  1836. filename: str,
  1837. db: AsyncSession = Depends(get_db),
  1838. ):
  1839. """Download 3MF file using a slicer download token.
  1840. Token-authenticated (no auth headers needed). The token is short-lived
  1841. and single-use, created by POST /{archive_id}/slicer-token.
  1842. Filename is at the end of the URL so slicers can detect the file format.
  1843. """
  1844. from backend.app.core.auth import verify_slicer_download_token
  1845. if not await verify_slicer_download_token(token, "archive", archive_id):
  1846. raise HTTPException(403, "Invalid or expired download token")
  1847. service = ArchiveService(db)
  1848. archive = await service.get_archive(archive_id)
  1849. if not archive:
  1850. raise HTTPException(404, "Archive not found")
  1851. file_path = settings.base_dir / archive.file_path
  1852. if not file_path.is_file():
  1853. raise HTTPException(404, "File not found")
  1854. return FileResponse(
  1855. path=file_path,
  1856. filename=archive.filename,
  1857. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1858. )
  1859. @router.get("/{archive_id}/thumbnail")
  1860. async def get_thumbnail(
  1861. archive_id: int,
  1862. db: AsyncSession = Depends(get_db),
  1863. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1864. ):
  1865. """Get the thumbnail image.
  1866. Requires a stream token query param (?token=xxx) when auth is enabled.
  1867. """
  1868. service = ArchiveService(db)
  1869. archive = await service.get_archive(archive_id)
  1870. if not archive or not archive.thumbnail_path:
  1871. raise HTTPException(404, "Thumbnail not found")
  1872. thumb_path = settings.base_dir / archive.thumbnail_path
  1873. if not thumb_path.exists():
  1874. raise HTTPException(404, "Thumbnail file not found")
  1875. # Use file modification time as ETag to bust cache
  1876. mtime = int(thumb_path.stat().st_mtime)
  1877. return FileResponse(
  1878. path=thumb_path,
  1879. media_type="image/png",
  1880. headers={
  1881. "Cache-Control": "no-cache, must-revalidate",
  1882. "ETag": f'"{mtime}"',
  1883. },
  1884. )
  1885. @router.get("/{archive_id}/timelapse")
  1886. async def get_timelapse(
  1887. archive_id: int,
  1888. db: AsyncSession = Depends(get_db),
  1889. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1890. ):
  1891. """Get the timelapse video.
  1892. Requires a stream token query param (?token=xxx) when auth is enabled.
  1893. """
  1894. service = ArchiveService(db)
  1895. archive = await service.get_archive(archive_id)
  1896. if not archive or not archive.timelapse_path:
  1897. raise HTTPException(404, "Timelapse not found")
  1898. timelapse_path = settings.base_dir / archive.timelapse_path
  1899. if not timelapse_path.exists():
  1900. raise HTTPException(404, "Timelapse file not found")
  1901. # Use file modification time as ETag to bust cache after processing
  1902. mtime = int(timelapse_path.stat().st_mtime)
  1903. # Detect media type from file extension (AVI from P1S before background conversion)
  1904. suffix = timelapse_path.suffix.lower()
  1905. media_type = {".mp4": "video/mp4", ".avi": "video/x-msvideo", ".mkv": "video/x-matroska"}.get(suffix, "video/mp4")
  1906. ext = suffix if suffix in (".mp4", ".avi", ".mkv") else ".mp4"
  1907. return FileResponse(
  1908. path=timelapse_path,
  1909. media_type=media_type,
  1910. filename=f"{archive.print_name or 'timelapse'}{ext}",
  1911. headers={
  1912. "Cache-Control": "no-cache, must-revalidate",
  1913. "ETag": f'"{mtime}"',
  1914. },
  1915. )
  1916. @router.delete("/{archive_id}/timelapse")
  1917. async def delete_timelapse(
  1918. archive_id: int,
  1919. db: AsyncSession = Depends(get_db),
  1920. auth_result: tuple[User | None, bool] = Depends(
  1921. require_ownership_permission(
  1922. Permission.ARCHIVES_DELETE_ALL,
  1923. Permission.ARCHIVES_DELETE_OWN,
  1924. )
  1925. ),
  1926. ):
  1927. """Remove the timelapse video from an archive."""
  1928. user, can_modify_all = auth_result
  1929. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1930. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  1931. if not archive.timelapse_path:
  1932. raise HTTPException(404, "No timelapse attached to this archive")
  1933. # Delete the file
  1934. timelapse_path = settings.base_dir / archive.timelapse_path
  1935. if timelapse_path.exists():
  1936. timelapse_path.unlink()
  1937. # Clear the path in database
  1938. archive.timelapse_path = None
  1939. await db.commit()
  1940. return {"status": "deleted"}
  1941. @router.post("/{archive_id}/timelapse/scan")
  1942. async def scan_timelapse(
  1943. archive_id: int,
  1944. db: AsyncSession = Depends(get_db),
  1945. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1946. ):
  1947. """Scan printer for timelapse matching this archive and attach it."""
  1948. from backend.app.models.printer import Printer
  1949. from backend.app.services.bambu_ftp import (
  1950. download_file_bytes_async,
  1951. get_ftp_retry_settings,
  1952. list_files_async,
  1953. with_ftp_retry,
  1954. )
  1955. service = ArchiveService(db)
  1956. archive = await service.get_archive(archive_id)
  1957. if not archive:
  1958. raise HTTPException(404, "Archive not found")
  1959. if archive.timelapse_path:
  1960. return {"status": "exists", "message": "Timelapse already attached"}
  1961. if not archive.printer_id:
  1962. raise HTTPException(400, "Archive has no associated printer")
  1963. # Get printer
  1964. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1965. printer = result.scalar_one_or_none()
  1966. if not printer:
  1967. raise HTTPException(404, "Printer not found")
  1968. # Get base name from archive filename (without .3mf extension)
  1969. base_name = Path(archive.filename).stem
  1970. # Scan timelapse directory on printer
  1971. # Different printer models use different paths
  1972. files = []
  1973. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1974. try:
  1975. files = await list_files_async(
  1976. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1977. )
  1978. if files:
  1979. break
  1980. except Exception:
  1981. continue
  1982. if not files:
  1983. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  1984. # Look for matching timelapse
  1985. matching_file = None
  1986. video_files = [
  1987. f for f in files if not f.get("is_directory") and f.get("name", "").lower().endswith((".mp4", ".avi"))
  1988. ]
  1989. # Strategy 1: Match by print name in filename
  1990. for f in video_files:
  1991. fname = f.get("name", "")
  1992. if base_name.lower() in fname.lower():
  1993. matching_file = f
  1994. break
  1995. # Strategy 2: Match by timestamp proximity against print START time.
  1996. # Bambu timelapse filename embeds the print start time in printer-local clock.
  1997. # See _match_timelapse_by_timestamp for the offset-search rationale and why we
  1998. # intentionally don't try to match filename against end time here.
  1999. if not matching_file and archive.started_at:
  2000. candidate, diff = _match_timelapse_by_timestamp(video_files, archive.started_at)
  2001. if candidate is not None:
  2002. matching_file = candidate
  2003. logger.info("Matched timelapse by timestamp: %s (diff: %s)", candidate.get("name"), diff)
  2004. # Strategy 3: Use file modification time from FTP listing
  2005. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  2006. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  2007. from datetime import datetime, timedelta
  2008. _archive_start = archive.started_at
  2009. archive_end = archive.completed_at or archive.created_at
  2010. best_match = None
  2011. best_diff = timedelta(hours=24)
  2012. for f in video_files:
  2013. mtime = f.get("mtime")
  2014. if mtime:
  2015. # Timelapse file should be modified during or shortly after the print
  2016. # The mtime should be close to completion time (video finishes when print ends)
  2017. if archive_end:
  2018. diff = abs(mtime - archive_end)
  2019. if diff < best_diff:
  2020. best_diff = diff
  2021. best_match = f
  2022. logger.debug(
  2023. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  2024. )
  2025. if best_match and best_diff < timedelta(hours=2):
  2026. matching_file = best_match
  2027. logger.info("Matched timelapse by file mtime: %s (diff: %s)", best_match.get("name"), best_diff)
  2028. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  2029. # This handles cases where printer clock is wrong or timezone issues exist
  2030. if not matching_file and len(video_files) == 1:
  2031. from datetime import datetime, timedelta, timezone
  2032. archive_completed = archive.completed_at or archive.created_at
  2033. if archive_completed:
  2034. if archive_completed.tzinfo is None:
  2035. archive_completed = archive_completed.replace(tzinfo=timezone.utc)
  2036. time_since_completion = datetime.now(timezone.utc) - archive_completed
  2037. # If archive was completed within the last hour, assume the single timelapse is for it
  2038. if time_since_completion < timedelta(hours=1):
  2039. matching_file = video_files[0]
  2040. logger.info("Using single timelapse file as fallback: %s", video_files[0].get("name"))
  2041. # Note: We intentionally don't use a "most recent file" fallback because
  2042. # we can't verify if timelapse was actually enabled for this print.
  2043. # Instead, return the list of available files for manual selection.
  2044. if not matching_file:
  2045. # Return available files for manual selection
  2046. available_files = [
  2047. {
  2048. "name": f.get("name"),
  2049. "path": f.get("path"),
  2050. "size": f.get("size"),
  2051. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  2052. }
  2053. for f in video_files
  2054. ]
  2055. # Sort by mtime descending (most recent first)
  2056. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  2057. return {
  2058. "status": "not_found",
  2059. "message": "No matching timelapse found - please select manually",
  2060. "available_files": available_files,
  2061. }
  2062. # Download the timelapse - use the full path from the file listing
  2063. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  2064. # Get FTP retry settings
  2065. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2066. if ftp_retry_enabled:
  2067. timelapse_data = await with_ftp_retry(
  2068. download_file_bytes_async,
  2069. printer.ip_address,
  2070. printer.access_code,
  2071. remote_path,
  2072. socket_timeout=ftp_timeout,
  2073. printer_model=printer.model,
  2074. max_retries=ftp_retry_count,
  2075. retry_delay=ftp_retry_delay,
  2076. operation_name=f"Download timelapse {matching_file['name']}",
  2077. )
  2078. else:
  2079. timelapse_data = await download_file_bytes_async(
  2080. printer.ip_address,
  2081. printer.access_code,
  2082. remote_path,
  2083. socket_timeout=ftp_timeout,
  2084. printer_model=printer.model,
  2085. )
  2086. if not timelapse_data:
  2087. raise HTTPException(500, "Failed to download timelapse")
  2088. # Attach timelapse to archive
  2089. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  2090. if not success:
  2091. raise HTTPException(500, "Failed to attach timelapse")
  2092. return {
  2093. "status": "attached",
  2094. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  2095. "filename": matching_file["name"],
  2096. }
  2097. @router.post("/{archive_id}/timelapse/select")
  2098. async def select_timelapse(
  2099. archive_id: int,
  2100. filename: str = Query(..., description="Timelapse filename to attach"),
  2101. db: AsyncSession = Depends(get_db),
  2102. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2103. ):
  2104. """Manually select a timelapse from the printer to attach."""
  2105. from backend.app.models.printer import Printer
  2106. from backend.app.services.bambu_ftp import (
  2107. download_file_bytes_async,
  2108. get_ftp_retry_settings,
  2109. list_files_async,
  2110. with_ftp_retry,
  2111. )
  2112. service = ArchiveService(db)
  2113. archive = await service.get_archive(archive_id)
  2114. if not archive:
  2115. raise HTTPException(404, "Archive not found")
  2116. if not archive.printer_id:
  2117. raise HTTPException(400, "Archive has no associated printer")
  2118. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2119. printer = result.scalar_one_or_none()
  2120. if not printer:
  2121. raise HTTPException(404, "Printer not found")
  2122. # Find the file on the printer
  2123. files = []
  2124. remote_path = None
  2125. for timelapse_dir in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  2126. try:
  2127. files = await list_files_async(
  2128. printer.ip_address, printer.access_code, timelapse_dir, printer_model=printer.model
  2129. )
  2130. for f in files:
  2131. if f.get("name") == filename:
  2132. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  2133. break
  2134. if remote_path:
  2135. break
  2136. except Exception:
  2137. continue
  2138. if not remote_path:
  2139. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  2140. # Download and attach
  2141. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2142. if ftp_retry_enabled:
  2143. timelapse_data = await with_ftp_retry(
  2144. download_file_bytes_async,
  2145. printer.ip_address,
  2146. printer.access_code,
  2147. remote_path,
  2148. socket_timeout=ftp_timeout,
  2149. printer_model=printer.model,
  2150. max_retries=ftp_retry_count,
  2151. retry_delay=ftp_retry_delay,
  2152. operation_name=f"Download timelapse {filename}",
  2153. )
  2154. else:
  2155. timelapse_data = await download_file_bytes_async(
  2156. printer.ip_address,
  2157. printer.access_code,
  2158. remote_path,
  2159. socket_timeout=ftp_timeout,
  2160. printer_model=printer.model,
  2161. )
  2162. if not timelapse_data:
  2163. raise HTTPException(500, "Failed to download timelapse")
  2164. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  2165. if not success:
  2166. raise HTTPException(500, "Failed to attach timelapse")
  2167. return {
  2168. "status": "attached",
  2169. "message": f"Timelapse '{filename}' attached successfully",
  2170. "filename": filename,
  2171. }
  2172. @router.post("/{archive_id}/timelapse/upload")
  2173. async def upload_timelapse(
  2174. archive_id: int,
  2175. file: UploadFile = File(...),
  2176. db: AsyncSession = Depends(get_db),
  2177. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2178. ):
  2179. """Manually upload a timelapse video to an archive."""
  2180. service = ArchiveService(db)
  2181. archive = await service.get_archive(archive_id)
  2182. if not archive:
  2183. raise HTTPException(404, "Archive not found")
  2184. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  2185. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  2186. content = await file.read()
  2187. safe_filename = _safe_filename(file.filename)
  2188. success = await service.attach_timelapse(archive_id, content, safe_filename)
  2189. if not success:
  2190. raise HTTPException(500, "Failed to attach timelapse")
  2191. return {"status": "attached", "filename": safe_filename}
  2192. @router.get("/{archive_id}/timelapse/info")
  2193. async def get_timelapse_info(
  2194. archive_id: int,
  2195. db: AsyncSession = Depends(get_db),
  2196. auth_result: tuple[User | None, bool] = Depends(
  2197. require_ownership_permission(
  2198. Permission.ARCHIVES_READ_ALL,
  2199. Permission.ARCHIVES_READ_OWN,
  2200. )
  2201. ),
  2202. ):
  2203. """Get timelapse video metadata for editor."""
  2204. from backend.app.schemas.timelapse import TimelapseInfoResponse
  2205. from backend.app.services.timelapse_processor import TimelapseProcessor
  2206. user, can_read_all = auth_result
  2207. service = ArchiveService(db)
  2208. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2209. if not archive.timelapse_path:
  2210. raise HTTPException(404, "Timelapse not found")
  2211. timelapse_path = settings.base_dir / archive.timelapse_path
  2212. if not timelapse_path.exists():
  2213. raise HTTPException(404, "Timelapse file not found")
  2214. try:
  2215. processor = TimelapseProcessor(timelapse_path)
  2216. info = await processor.get_info()
  2217. return TimelapseInfoResponse(**info)
  2218. except Exception as e:
  2219. logger.error("Failed to get timelapse info: %s", e)
  2220. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  2221. @router.get("/{archive_id}/timelapse/thumbnails")
  2222. async def get_timelapse_thumbnails(
  2223. archive_id: int,
  2224. count: int = Query(10, ge=1, le=30),
  2225. width: int = Query(160, ge=80, le=320),
  2226. db: AsyncSession = Depends(get_db),
  2227. auth_result: tuple[User | None, bool] = Depends(
  2228. require_ownership_permission(
  2229. Permission.ARCHIVES_READ_ALL,
  2230. Permission.ARCHIVES_READ_OWN,
  2231. )
  2232. ),
  2233. ):
  2234. """Generate timeline thumbnail frames for visual scrubbing."""
  2235. import base64
  2236. from backend.app.schemas.timelapse import ThumbnailResponse
  2237. from backend.app.services.timelapse_processor import TimelapseProcessor
  2238. user, can_read_all = auth_result
  2239. service = ArchiveService(db)
  2240. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2241. if not archive.timelapse_path:
  2242. raise HTTPException(404, "Timelapse not found")
  2243. timelapse_path = settings.base_dir / archive.timelapse_path
  2244. if not timelapse_path.exists():
  2245. raise HTTPException(404, "Timelapse file not found")
  2246. try:
  2247. processor = TimelapseProcessor(timelapse_path)
  2248. thumbnails = await processor.generate_thumbnails(count, width)
  2249. return ThumbnailResponse(
  2250. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  2251. timestamps=[ts for ts, _ in thumbnails],
  2252. )
  2253. except Exception as e:
  2254. logger.error("Failed to generate thumbnails: %s", e)
  2255. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  2256. @router.post("/{archive_id}/timelapse/process")
  2257. async def process_timelapse(
  2258. archive_id: int,
  2259. trim_start: float = Form(0),
  2260. trim_end: float = Form(None),
  2261. speed: float = Form(1.0),
  2262. save_mode: str = Form("new"),
  2263. output_filename: str = Form(None),
  2264. audio: UploadFile = File(None),
  2265. db: AsyncSession = Depends(get_db),
  2266. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2267. ):
  2268. """Process timelapse with trim, speed, and optional audio overlay."""
  2269. import shutil
  2270. import tempfile
  2271. from backend.app.schemas.timelapse import ProcessResponse
  2272. from backend.app.services.timelapse_processor import TimelapseProcessor
  2273. # Validate speed
  2274. if not 0.25 <= speed <= 4.0:
  2275. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  2276. if save_mode not in ("replace", "new"):
  2277. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  2278. service = ArchiveService(db)
  2279. archive = await service.get_archive(archive_id)
  2280. if not archive or not archive.timelapse_path:
  2281. raise HTTPException(404, "Timelapse not found")
  2282. timelapse_path = settings.base_dir / archive.timelapse_path
  2283. if not timelapse_path.exists():
  2284. raise HTTPException(404, "Timelapse file not found")
  2285. archive_dir = timelapse_path.parent
  2286. # Handle audio file
  2287. audio_temp_path = None
  2288. if audio and audio.filename:
  2289. # Validate audio file extension
  2290. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  2291. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  2292. audio_content = await audio.read()
  2293. # Extract and validate suffix to prevent path injection
  2294. suffix = Path(audio.filename).suffix.lower()
  2295. if suffix not in (".mp3", ".wav", ".m4a", ".aac", ".ogg"):
  2296. raise HTTPException(400, "Invalid audio file extension")
  2297. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  2298. audio_temp_path.write_bytes(audio_content)
  2299. try:
  2300. processor = TimelapseProcessor(timelapse_path)
  2301. # Determine output path
  2302. if save_mode == "replace":
  2303. # Process to temp file first, then replace
  2304. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  2305. output_path = temp_output
  2306. else:
  2307. # Save as new file alongside original
  2308. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  2309. # Sanitize filename - remove path separators and traversal sequences
  2310. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  2311. # Prevent path traversal
  2312. if ".." in filename or not filename or filename.startswith("."):
  2313. filename = f"timelapse_{archive_id}_edited"
  2314. if not filename.endswith(".mp4"):
  2315. filename += ".mp4"
  2316. output_path = archive_dir / filename # SEC-PATH-OK: filename alnum-filtered + .. rejected above
  2317. success = await processor.process(
  2318. output_path=output_path,
  2319. trim_start=trim_start,
  2320. trim_end=trim_end,
  2321. speed=speed,
  2322. audio_path=audio_temp_path,
  2323. )
  2324. if not success:
  2325. raise HTTPException(500, "Video processing failed")
  2326. # Handle save mode
  2327. if save_mode == "replace":
  2328. # Replace original file
  2329. shutil.move(str(output_path), str(timelapse_path))
  2330. final_path = archive.timelapse_path
  2331. message = "Timelapse replaced successfully"
  2332. else:
  2333. final_path = str(output_path.relative_to(settings.base_dir))
  2334. message = f"Saved as {output_path.name}"
  2335. return ProcessResponse(
  2336. status="completed",
  2337. output_path=final_path,
  2338. message=message,
  2339. )
  2340. except HTTPException:
  2341. raise
  2342. except Exception as e:
  2343. logger.error("Timelapse processing failed: %s", e)
  2344. raise HTTPException(500, f"Processing failed: {str(e)}")
  2345. finally:
  2346. # Cleanup temp audio file
  2347. if audio_temp_path and audio_temp_path.exists():
  2348. audio_temp_path.unlink()
  2349. # ============================================
  2350. # Photo Endpoints
  2351. # ============================================
  2352. @router.post("/{archive_id}/photos")
  2353. async def upload_photo(
  2354. archive_id: int,
  2355. file: UploadFile = File(...),
  2356. db: AsyncSession = Depends(get_db),
  2357. auth_result: tuple[User | None, bool] = Depends(
  2358. require_ownership_permission(
  2359. Permission.ARCHIVES_UPDATE_ALL,
  2360. Permission.ARCHIVES_UPDATE_OWN,
  2361. )
  2362. ),
  2363. ):
  2364. """Upload a photo of the printed result."""
  2365. user, can_modify_all = auth_result
  2366. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2367. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  2368. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  2369. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  2370. # Get archive directory
  2371. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2372. photos_dir = archive_dir / "photos"
  2373. photos_dir.mkdir(exist_ok=True)
  2374. # Generate unique filename
  2375. import uuid
  2376. ext = Path(file.filename).suffix.lower()
  2377. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  2378. photo_path = photos_dir / photo_filename # SEC-PATH-OK: photo_filename = uuid.uuid4().hex[:8] + ext
  2379. # Save file
  2380. content = await file.read()
  2381. photo_path.write_bytes(content)
  2382. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  2383. photos = list(archive.photos or [])
  2384. photos.append(photo_filename)
  2385. archive.photos = photos
  2386. await db.commit()
  2387. await db.refresh(archive)
  2388. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  2389. @router.get("/{archive_id}/photos/{filename}")
  2390. async def get_photo(
  2391. archive_id: int,
  2392. filename: str,
  2393. db: AsyncSession = Depends(get_db),
  2394. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2395. ):
  2396. """Get a specific photo.
  2397. Requires a stream token query param (?token=xxx) when auth is enabled.
  2398. """
  2399. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2400. archive = result.scalar_one_or_none()
  2401. if not archive:
  2402. raise HTTPException(404, "Archive not found")
  2403. # Membership check first — UUID-generated names on upload mean any URL
  2404. # filename that doesn't appear here is by definition not a real photo.
  2405. # Mirrors the delete handler below; previously this endpoint had no
  2406. # membership check at all and joined `filename` straight to disk.
  2407. if not archive.photos or filename not in archive.photos:
  2408. raise HTTPException(404, "Photo not found")
  2409. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2410. photos_dir = archive_dir / "photos"
  2411. # Defence-in-depth: even though the membership check above already
  2412. # constrains `filename` to UUID-generated names from upload, the
  2413. # resolve + containment check guards against future code paths that
  2414. # might populate `archive.photos` from a less-trusted source.
  2415. photo_path = safe_join_under(photos_dir, filename)
  2416. if not photo_path.exists():
  2417. raise HTTPException(404, "Photo not found")
  2418. # Determine media type
  2419. ext = Path(filename).suffix.lower()
  2420. media_types = {
  2421. ".jpg": "image/jpeg",
  2422. ".jpeg": "image/jpeg",
  2423. ".png": "image/png",
  2424. ".webp": "image/webp",
  2425. }
  2426. media_type = media_types.get(ext, "image/jpeg")
  2427. return FileResponse(path=photo_path, media_type=media_type)
  2428. @router.delete("/{archive_id}/photos/{filename}")
  2429. async def delete_photo(
  2430. archive_id: int,
  2431. filename: str,
  2432. db: AsyncSession = Depends(get_db),
  2433. auth_result: tuple[User | None, bool] = Depends(
  2434. require_ownership_permission(
  2435. Permission.ARCHIVES_DELETE_ALL,
  2436. Permission.ARCHIVES_DELETE_OWN,
  2437. )
  2438. ),
  2439. ):
  2440. """Delete a photo."""
  2441. user, can_modify_all = auth_result
  2442. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2443. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  2444. if not archive.photos or filename not in archive.photos:
  2445. raise HTTPException(404, "Photo not found")
  2446. # Delete file — same defence-in-depth as get_photo above.
  2447. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2448. photos_dir = archive_dir / "photos"
  2449. photo_path = safe_join_under(photos_dir, filename)
  2450. if photo_path.exists():
  2451. photo_path.unlink()
  2452. # Update archive photos list
  2453. photos = [p for p in archive.photos if p != filename]
  2454. archive.photos = photos if photos else None
  2455. await db.commit()
  2456. return {"status": "deleted", "photos": archive.photos}
  2457. # ============================================
  2458. # QR Code Endpoint
  2459. # ============================================
  2460. @router.get("/{archive_id}/qrcode")
  2461. async def get_qrcode(
  2462. archive_id: int,
  2463. request: Request,
  2464. size: int = 200,
  2465. db: AsyncSession = Depends(get_db),
  2466. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2467. ):
  2468. """Generate a QR code that links to this archive.
  2469. Requires a stream token query param (?token=xxx) when auth is enabled.
  2470. """
  2471. try:
  2472. import qrcode
  2473. from PIL import Image as PILImage
  2474. except ImportError:
  2475. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  2476. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2477. archive = result.scalar_one_or_none()
  2478. if not archive:
  2479. raise HTTPException(404, "Archive not found")
  2480. # Build URL to archive download
  2481. base_url = str(request.base_url).rstrip("/")
  2482. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  2483. # Generate QR code
  2484. qr = qrcode.QRCode(
  2485. version=1,
  2486. error_correction=qrcode.constants.ERROR_CORRECT_M,
  2487. box_size=10,
  2488. border=2,
  2489. )
  2490. qr.add_data(archive_url)
  2491. qr.make(fit=True)
  2492. img = qr.make_image(fill_color="black", back_color="white")
  2493. # Convert to PIL Image for resizing
  2494. pil_img = img.get_image()
  2495. # Resize if needed
  2496. if size != 200:
  2497. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  2498. # Convert to bytes
  2499. buffer = io.BytesIO()
  2500. pil_img.save(buffer, format="PNG")
  2501. buffer.seek(0)
  2502. qr_filename = f"qr_{archive.print_name or archive_id}.png"
  2503. return Response(
  2504. content=buffer.getvalue(),
  2505. media_type="image/png",
  2506. headers={"Content-Disposition": build_content_disposition(qr_filename, disposition="inline")},
  2507. )
  2508. @router.get("/{archive_id}/capabilities")
  2509. async def get_archive_capabilities(
  2510. archive_id: int,
  2511. db: AsyncSession = Depends(get_db),
  2512. auth_result: tuple[User | None, bool] = Depends(
  2513. require_ownership_permission(
  2514. Permission.ARCHIVES_READ_ALL,
  2515. Permission.ARCHIVES_READ_OWN,
  2516. )
  2517. ),
  2518. ):
  2519. """Check what viewing capabilities are available for this 3MF file."""
  2520. import defusedxml.ElementTree as ET
  2521. user, can_read_all = auth_result
  2522. service = ArchiveService(db)
  2523. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2524. file_path = settings.base_dir / archive.file_path
  2525. if not file_path.is_file():
  2526. raise HTTPException(404, "File not found")
  2527. has_model = False
  2528. has_gcode = False
  2529. has_source = False
  2530. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  2531. filament_colors: list[str] = []
  2532. # Check if source 3MF exists - this is where actual mesh data typically lives
  2533. source_path = None
  2534. if archive.source_3mf_path:
  2535. source_path = settings.base_dir / archive.source_3mf_path
  2536. if source_path.exists():
  2537. has_source = True
  2538. # Helper function to check for mesh data and extract colors from a 3MF file
  2539. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  2540. """Extract mesh presence, colors, and build volume from a 3MF file."""
  2541. found_mesh = False
  2542. colors: list[str] = []
  2543. volume = {"x": 256, "y": 256, "z": 256}
  2544. try:
  2545. with zipfile.ZipFile(zf_path, "r") as zf:
  2546. names = zf.namelist()
  2547. # Check for 3D model - look for actual mesh data
  2548. for name in names:
  2549. if name.endswith(".model"):
  2550. try:
  2551. content = zf.read(name).decode("utf-8")
  2552. if "<vertex" in content or "<mesh" in content:
  2553. found_mesh = True
  2554. break
  2555. except Exception:
  2556. pass # Skip unreadable .model entries in archive
  2557. # Extract filament colors from project_settings.config
  2558. if "Metadata/project_settings.config" in names:
  2559. try:
  2560. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2561. config_data = json.loads(config_content)
  2562. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  2563. printable_area = config_data.get("printable_area", [])
  2564. if printable_area and len(printable_area) >= 3:
  2565. max_x = 0
  2566. max_y = 0
  2567. for coord in printable_area:
  2568. if "x" in coord:
  2569. parts = coord.split("x")
  2570. if len(parts) == 2:
  2571. try:
  2572. x, y = int(parts[0]), int(parts[1])
  2573. max_x = max(max_x, x)
  2574. max_y = max(max_y, y)
  2575. except ValueError:
  2576. pass # Skip non-numeric printable_area coordinate
  2577. if max_x > 0 and max_y > 0:
  2578. volume["x"] = max_x
  2579. volume["y"] = max_y
  2580. # Parse printable_height
  2581. printable_height = config_data.get("printable_height")
  2582. if printable_height:
  2583. try:
  2584. volume["z"] = int(printable_height)
  2585. except (ValueError, TypeError):
  2586. pass # Skip unparseable printable_height value
  2587. # Extract filament colors
  2588. raw_colors = config_data.get("filament_colour", [])
  2589. if raw_colors:
  2590. for color in raw_colors:
  2591. if color and isinstance(color, str):
  2592. colors.append(color)
  2593. except Exception:
  2594. pass # Skip malformed project_settings.config
  2595. except zipfile.BadZipFile:
  2596. pass # File is not a valid zip/3MF archive
  2597. return found_mesh, colors, volume
  2598. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  2599. if has_source and source_path:
  2600. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  2601. if source_has_mesh:
  2602. has_model = True
  2603. if source_colors:
  2604. filament_colors = source_colors
  2605. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  2606. build_volume = source_volume
  2607. try:
  2608. with zipfile.ZipFile(file_path, "r") as zf:
  2609. names = zf.namelist()
  2610. # Check for G-code in the sliced file
  2611. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  2612. # Check for 3D model in sliced file (fallback if no source)
  2613. if not has_model:
  2614. for name in names:
  2615. if name.endswith(".model"):
  2616. try:
  2617. content = zf.read(name).decode("utf-8")
  2618. if "<vertex" in content or "<mesh" in content:
  2619. has_model = True
  2620. break
  2621. except Exception:
  2622. pass # Skip unreadable .model entries in archive
  2623. # Extract filament colors from slice_info.config (for gcode preview)
  2624. # These are the actual filaments used in the print, indexed by tool/extruder
  2625. slice_colors: list[str] = []
  2626. if "Metadata/slice_info.config" in names:
  2627. try:
  2628. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2629. root = ET.fromstring(slice_content)
  2630. filaments = root.findall(".//filament")
  2631. filament_map: dict[int, str] = {}
  2632. for f in filaments:
  2633. fid = f.get("id")
  2634. fcolor = f.get("color")
  2635. used_g = f.get("used_g", "0")
  2636. try:
  2637. used_amount = float(used_g)
  2638. except (ValueError, TypeError):
  2639. used_amount = 0
  2640. if fid is not None and fcolor:
  2641. try:
  2642. tool_id = int(fid) - 1
  2643. if tool_id >= 0 and used_amount > 0:
  2644. filament_map[tool_id] = fcolor
  2645. except ValueError:
  2646. pass # Skip filament entry with non-numeric ID
  2647. if filament_map:
  2648. max_tool = max(filament_map.keys())
  2649. for i in range(max_tool + 1):
  2650. slice_colors.append(filament_map.get(i, "#00AE42"))
  2651. except Exception:
  2652. pass # Skip malformed slice_info.config XML
  2653. # Use slice_info colors if we don't have colors from source yet
  2654. if not filament_colors and slice_colors:
  2655. filament_colors = slice_colors
  2656. # Extract build volume from sliced file if not already set from source
  2657. if build_volume["x"] == 256 and build_volume["y"] == 256:
  2658. if "Metadata/project_settings.config" in names:
  2659. try:
  2660. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2661. config_data = json.loads(config_content)
  2662. printable_area = config_data.get("printable_area", [])
  2663. if printable_area and len(printable_area) >= 3:
  2664. max_x = 0
  2665. max_y = 0
  2666. for coord in printable_area:
  2667. if "x" in coord:
  2668. parts = coord.split("x")
  2669. if len(parts) == 2:
  2670. try:
  2671. x, y = int(parts[0]), int(parts[1])
  2672. max_x = max(max_x, x)
  2673. max_y = max(max_y, y)
  2674. except ValueError:
  2675. pass # Skip non-numeric printable_area coordinate
  2676. if max_x > 0 and max_y > 0:
  2677. build_volume["x"] = max_x
  2678. build_volume["y"] = max_y
  2679. printable_height = config_data.get("printable_height")
  2680. if printable_height:
  2681. try:
  2682. build_volume["z"] = int(printable_height)
  2683. except (ValueError, TypeError):
  2684. pass # Skip unparseable printable_height value
  2685. # Fallback colors from project_settings if still empty
  2686. if not filament_colors:
  2687. raw_colors = config_data.get("filament_colour", [])
  2688. if raw_colors:
  2689. for color in raw_colors:
  2690. if color and isinstance(color, str):
  2691. filament_colors.append(color)
  2692. except Exception:
  2693. pass # Skip malformed project_settings.config
  2694. except zipfile.BadZipFile:
  2695. raise HTTPException(400, "Invalid 3MF file")
  2696. return {
  2697. "has_model": has_model,
  2698. "has_gcode": has_gcode,
  2699. "has_source": has_source,
  2700. "build_volume": build_volume,
  2701. "filament_colors": filament_colors,
  2702. }
  2703. @router.get("/{archive_id}/gcode")
  2704. async def get_gcode(
  2705. archive_id: int,
  2706. plate: int | None = None,
  2707. db: AsyncSession = Depends(get_db),
  2708. auth_result: tuple[User | None, bool] = Depends(
  2709. require_ownership_permission(
  2710. Permission.ARCHIVES_READ_ALL,
  2711. Permission.ARCHIVES_READ_OWN,
  2712. )
  2713. ),
  2714. ):
  2715. """Extract and return G-code from the 3MF file.
  2716. When *plate* is provided, returns the G-code for that specific plate
  2717. (e.g. ``?plate=2`` returns ``Metadata/plate_2.gcode``). If omitted, falls
  2718. back to the first plate found in the archive (preserving the original
  2719. behaviour for callers that predate the multi-plate viewer).
  2720. """
  2721. user, can_read_all = auth_result
  2722. service = ArchiveService(db)
  2723. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2724. file_path = settings.base_dir / archive.file_path
  2725. if not file_path.is_file():
  2726. raise HTTPException(404, "File not found")
  2727. if plate is not None and plate < 1:
  2728. raise HTTPException(400, "Plate index must be >= 1")
  2729. try:
  2730. with zipfile.ZipFile(file_path, "r") as zf:
  2731. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  2732. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  2733. if not gcode_files:
  2734. raise HTTPException(
  2735. 404,
  2736. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  2737. )
  2738. if plate is not None:
  2739. # Resolve plate → filename via the same parsing the plates
  2740. # endpoint uses (int() on the suffix), so zero-padded names
  2741. # like plate_01.gcode are found when the plates endpoint
  2742. # reported index 1.
  2743. selected = None
  2744. for gf in gcode_files:
  2745. if not gf.startswith("Metadata/plate_"):
  2746. continue
  2747. suffix = gf[len("Metadata/plate_") : -len(".gcode")]
  2748. try:
  2749. if int(suffix) == plate:
  2750. selected = gf
  2751. break
  2752. except ValueError:
  2753. continue
  2754. if selected is None:
  2755. raise HTTPException(404, f"Plate {plate} not found in this archive")
  2756. else:
  2757. selected = gcode_files[0]
  2758. gcode_content = zf.read(selected).decode("utf-8")
  2759. return Response(content=gcode_content, media_type="text/plain")
  2760. except zipfile.BadZipFile:
  2761. raise HTTPException(400, "Invalid 3MF file")
  2762. except HTTPException:
  2763. raise
  2764. except Exception as e:
  2765. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  2766. @router.get("/{archive_id}/plate-preview")
  2767. async def get_plate_preview(
  2768. archive_id: int,
  2769. db: AsyncSession = Depends(get_db),
  2770. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2771. ):
  2772. """Get the plate preview image from the 3MF file.
  2773. Returns the slicer-generated plate thumbnail which shows the model
  2774. with correct colors and positioning.
  2775. Requires a stream token query param (?token=xxx) when auth is enabled.
  2776. """
  2777. service = ArchiveService(db)
  2778. archive = await service.get_archive(archive_id)
  2779. if not archive:
  2780. raise HTTPException(404, "Archive not found")
  2781. file_path = settings.base_dir / archive.file_path
  2782. if not file_path.is_file():
  2783. raise HTTPException(404, "File not found")
  2784. try:
  2785. with zipfile.ZipFile(file_path, "r") as zf:
  2786. names = zf.namelist()
  2787. # Try to find plate preview images in order of preference
  2788. # First look for the specific plate being printed (check slice_info for plate index)
  2789. plate_num = 1
  2790. if "Metadata/slice_info.config" in names:
  2791. try:
  2792. import defusedxml.ElementTree as ET
  2793. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2794. root = ET.fromstring(slice_content)
  2795. plate_elem = root.find(".//plate/metadata[@key='index']")
  2796. if plate_elem is not None:
  2797. plate_num = int(plate_elem.get("value", "1"))
  2798. except Exception:
  2799. pass # Default plate_num=1 if slice_info is missing or malformed
  2800. # Try plate-specific image first, then fall back to plate_1
  2801. preview_paths = [
  2802. f"Metadata/plate_{plate_num}.png",
  2803. "Metadata/plate_1.png",
  2804. "Metadata/thumbnail.png",
  2805. ]
  2806. for preview_path in preview_paths:
  2807. if preview_path in names:
  2808. image_data = zf.read(preview_path)
  2809. return Response(content=image_data, media_type="image/png")
  2810. # If no plate image, try any PNG in Metadata
  2811. for name in names:
  2812. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  2813. image_data = zf.read(name)
  2814. return Response(content=image_data, media_type="image/png")
  2815. raise HTTPException(404, "No plate preview found in 3MF file")
  2816. except zipfile.BadZipFile:
  2817. raise HTTPException(400, "Invalid 3MF file")
  2818. except HTTPException:
  2819. raise
  2820. except Exception as e:
  2821. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  2822. @router.post("/upload")
  2823. async def upload_archive(
  2824. file: UploadFile = File(...),
  2825. printer_id: int | None = None,
  2826. db: AsyncSession = Depends(get_db),
  2827. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2828. ):
  2829. """Manually upload a 3MF file to archive."""
  2830. if not file.filename or not file.filename.endswith(".3mf"):
  2831. raise HTTPException(400, "File must be a .3mf file")
  2832. # Save uploaded file temporarily — strip directory components to prevent path traversal
  2833. safe_filename = _safe_filename(file.filename)
  2834. temp_path = (
  2835. settings.archive_dir / "temp" / safe_filename
  2836. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  2837. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2838. try:
  2839. content = await file.read()
  2840. # #1401: same content validation as library upload — catches
  2841. # raw-gcode-renamed-to-.3mf and other unprintable shapes before
  2842. # archiving them and offering them up for print.
  2843. from backend.app.api.routes.library import validate_print_file_upload
  2844. validate_print_file_upload(file.filename, content)
  2845. temp_path.write_bytes(content)
  2846. service = ArchiveService(db)
  2847. archive = await service.archive_print(
  2848. printer_id=printer_id,
  2849. source_file=temp_path,
  2850. created_by_id=current_user.id if current_user else None,
  2851. )
  2852. if not archive:
  2853. raise HTTPException(400, "Failed to archive file")
  2854. return ArchiveResponse.model_validate(archive)
  2855. finally:
  2856. if temp_path.exists():
  2857. temp_path.unlink()
  2858. @router.post("/upload-bulk")
  2859. async def upload_archives_bulk(
  2860. files: list[UploadFile] = File(...),
  2861. printer_id: int | None = None,
  2862. db: AsyncSession = Depends(get_db),
  2863. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2864. ):
  2865. """Bulk upload multiple 3MF files to archive."""
  2866. from backend.app.api.routes.library import validate_print_file_upload
  2867. results = []
  2868. errors = []
  2869. for file in files:
  2870. if not file.filename or not file.filename.endswith(".3mf"):
  2871. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  2872. continue
  2873. safe_filename = _safe_filename(file.filename)
  2874. temp_path = (
  2875. settings.archive_dir / "temp" / safe_filename
  2876. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  2877. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2878. try:
  2879. content = await file.read()
  2880. # #1401: bulk-upload variant of the library validation. Collect
  2881. # the rejection per-file rather than aborting the whole batch
  2882. # so one bad file in a 10-file drag-drop doesn't lose the
  2883. # other nine.
  2884. try:
  2885. validate_print_file_upload(file.filename, content)
  2886. except HTTPException as exc:
  2887. errors.append({"filename": file.filename, "error": exc.detail})
  2888. continue
  2889. temp_path.write_bytes(content)
  2890. service = ArchiveService(db)
  2891. archive = await service.archive_print(
  2892. printer_id=printer_id,
  2893. source_file=temp_path,
  2894. created_by_id=current_user.id if current_user else None,
  2895. )
  2896. if archive:
  2897. results.append(
  2898. {
  2899. "filename": file.filename,
  2900. "id": archive.id,
  2901. "status": "success",
  2902. }
  2903. )
  2904. else:
  2905. errors.append({"filename": file.filename, "error": "Failed to process"})
  2906. except Exception as e:
  2907. logger.exception("Failed to upload archive %s: %s", file.filename, e)
  2908. errors.append({"filename": file.filename, "error": "Failed to process file"})
  2909. finally:
  2910. if temp_path.exists():
  2911. temp_path.unlink()
  2912. return {
  2913. "uploaded": len(results),
  2914. "failed": len(errors),
  2915. "results": results,
  2916. "errors": errors,
  2917. }
  2918. @router.get("/{archive_id}/plates")
  2919. async def get_archive_plates(
  2920. archive_id: int,
  2921. db: AsyncSession = Depends(get_db),
  2922. auth_result: tuple[User | None, bool] = Depends(
  2923. require_ownership_permission(
  2924. Permission.ARCHIVES_READ_ALL,
  2925. Permission.ARCHIVES_READ_OWN,
  2926. )
  2927. ),
  2928. ):
  2929. """Get available plates from a multi-plate 3MF archive.
  2930. Returns a list of plates with their index, name, thumbnail availability,
  2931. and filament requirements. For single-plate exports, returns a single plate.
  2932. """
  2933. import re
  2934. import defusedxml.ElementTree as ET
  2935. user, can_read_all = auth_result
  2936. service = ArchiveService(db)
  2937. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2938. file_path = settings.base_dir / archive.file_path
  2939. if not file_path.is_file():
  2940. raise HTTPException(404, "Archive file not found")
  2941. plates = []
  2942. # Initialize so the `has_gcode = bool(gcode_files)` after the try/except
  2943. # never raises NameError when the archive isn't a valid zip (e.g. plain
  2944. # .gcode file from a sliced-archive flow that didn't request 3MF output).
  2945. gcode_files: list[str] = []
  2946. # Printer / process preset names the 3MF was prepared with — used by the
  2947. # SliceModal to default its dropdowns (#1325).
  2948. embedded_presets: dict[str, str | None] = {"printer": None, "process": None}
  2949. try:
  2950. with zipfile.ZipFile(file_path, "r") as zf:
  2951. namelist = zf.namelist()
  2952. embedded_presets = extract_embedded_presets_from_3mf(zf)
  2953. # Find all plate gcode files to determine available plates
  2954. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  2955. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  2956. plate_indices: list[int] = []
  2957. if gcode_files:
  2958. # Extract plate indices from gcode filenames
  2959. for gf in gcode_files:
  2960. # "Metadata/plate_5.gcode" -> 5
  2961. try:
  2962. # Remove "Metadata/plate_" and ".gcode"
  2963. plate_str = gf[15:-6]
  2964. plate_indices.append(int(plate_str))
  2965. except ValueError:
  2966. pass # Skip gcode file with non-numeric plate index
  2967. else:
  2968. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  2969. plate_png_files = [
  2970. n
  2971. for n in namelist
  2972. if n.startswith("Metadata/plate_")
  2973. and n.endswith(".png")
  2974. and "_small" not in n
  2975. and "no_light" not in n
  2976. ]
  2977. plate_name_candidates = plate_json_files + plate_png_files
  2978. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  2979. seen_indices: set[int] = set()
  2980. for name in plate_name_candidates:
  2981. match = plate_re.match(name)
  2982. if match:
  2983. try:
  2984. index = int(match.group(1))
  2985. except ValueError:
  2986. continue
  2987. if index in seen_indices:
  2988. continue
  2989. seen_indices.add(index)
  2990. plate_indices.append(index)
  2991. if not plate_indices:
  2992. # No plate metadata found
  2993. return {
  2994. "archive_id": archive_id,
  2995. "filename": archive.filename,
  2996. "plates": [],
  2997. "is_multi_plate": False,
  2998. }
  2999. plate_indices.sort()
  3000. # Parse model_settings.config for plate names + object assignments
  3001. # Plate names are stored with plater_id and plater_name keys
  3002. plate_names = {} # plater_id -> name
  3003. plate_object_ids: dict[int, list[str]] = {}
  3004. object_names_by_id: dict[str, str] = {}
  3005. if "Metadata/model_settings.config" in namelist:
  3006. try:
  3007. model_content = zf.read("Metadata/model_settings.config").decode()
  3008. model_root = ET.fromstring(model_content)
  3009. # Build object ID -> name map
  3010. for obj_elem in model_root.findall(".//object"):
  3011. obj_id = obj_elem.get("id")
  3012. if not obj_id:
  3013. continue
  3014. name_meta = obj_elem.find("metadata[@key='name']")
  3015. obj_name = name_meta.get("value") if name_meta is not None else None
  3016. if obj_name:
  3017. object_names_by_id[obj_id] = obj_name
  3018. for plate_elem in model_root.findall(".//plate"):
  3019. plater_id = None
  3020. plater_name = None
  3021. for meta in plate_elem.findall("metadata"):
  3022. key = meta.get("key")
  3023. value = meta.get("value")
  3024. if key == "plater_id" and value:
  3025. try:
  3026. plater_id = int(value)
  3027. except ValueError:
  3028. pass # Skip plate with non-numeric plater_id
  3029. elif key == "plater_name" and value:
  3030. plater_name = value.strip()
  3031. if plater_id is not None and plater_name:
  3032. plate_names[plater_id] = plater_name
  3033. if plater_id is not None:
  3034. for instance_elem in plate_elem.findall("model_instance"):
  3035. for inst_meta in instance_elem.findall("metadata"):
  3036. if inst_meta.get("key") == "object_id":
  3037. obj_id = inst_meta.get("value")
  3038. if not obj_id:
  3039. continue
  3040. plate_object_ids.setdefault(plater_id, [])
  3041. if obj_id not in plate_object_ids[plater_id]:
  3042. plate_object_ids[plater_id].append(obj_id)
  3043. except Exception:
  3044. pass # model_settings.config parsing is optional
  3045. # Parse slice_info.config for plate metadata
  3046. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  3047. if "Metadata/slice_info.config" in namelist:
  3048. content = zf.read("Metadata/slice_info.config").decode()
  3049. root = ET.fromstring(content)
  3050. for plate_elem in root.findall(".//plate"):
  3051. plate_info = {
  3052. "filaments": [],
  3053. "prediction": None,
  3054. "weight": None,
  3055. "name": None,
  3056. "objects": [],
  3057. "bed_type": None,
  3058. }
  3059. # Get plate index from metadata
  3060. plate_index = None
  3061. for meta in plate_elem.findall("metadata"):
  3062. key = meta.get("key")
  3063. value = meta.get("value")
  3064. if key == "index" and value:
  3065. try:
  3066. plate_index = int(value)
  3067. except ValueError:
  3068. pass # Skip plate with non-numeric index
  3069. elif key == "prediction" and value:
  3070. try:
  3071. plate_info["prediction"] = int(value)
  3072. except ValueError:
  3073. pass # Skip non-numeric print time prediction
  3074. elif key == "weight" and value:
  3075. try:
  3076. plate_info["weight"] = float(value)
  3077. except ValueError:
  3078. pass # Skip non-numeric filament weight
  3079. elif key == "curr_bed_type" and value:
  3080. # Per-plate bed type so the PrintModal can show the
  3081. # right plate alongside each option (#1281).
  3082. plate_info["bed_type"] = value.strip()
  3083. # Get filaments used in this plate
  3084. for filament_elem in plate_elem.findall("filament"):
  3085. filament_id = filament_elem.get("id")
  3086. filament_type = filament_elem.get("type", "")
  3087. filament_color = filament_elem.get("color", "")
  3088. used_g = filament_elem.get("used_g", "0")
  3089. used_m = filament_elem.get("used_m", "0")
  3090. try:
  3091. used_grams = float(used_g)
  3092. except (ValueError, TypeError):
  3093. used_grams = 0
  3094. if used_grams > 0 and filament_id:
  3095. plate_info["filaments"].append(
  3096. {
  3097. "slot_id": int(filament_id),
  3098. "type": filament_type,
  3099. "color": filament_color,
  3100. "used_grams": round(used_grams, 1),
  3101. "used_meters": float(used_m) if used_m else 0,
  3102. }
  3103. )
  3104. # Sort filaments by slot ID
  3105. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  3106. # Collect all object names on this plate
  3107. for obj_elem in plate_elem.findall("object"):
  3108. obj_name = obj_elem.get("name")
  3109. if obj_name and obj_name not in plate_info["objects"]:
  3110. plate_info["objects"].append(obj_name)
  3111. # Set plate name: prefer custom name from model_settings.config,
  3112. # fall back to first object name if no custom name was set
  3113. if plate_index is not None:
  3114. custom_name = plate_names.get(plate_index)
  3115. if custom_name:
  3116. plate_info["name"] = custom_name
  3117. else:
  3118. # Fall back to first object name as hint
  3119. if plate_info["objects"]:
  3120. plate_info["name"] = plate_info["objects"][0]
  3121. plate_metadata[plate_index] = plate_info
  3122. # Parse plate_*.json for object lists when slice_info is missing
  3123. plate_json_objects: dict[int, list[str]] = {}
  3124. for name in namelist:
  3125. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  3126. if not match:
  3127. continue
  3128. try:
  3129. plate_index = int(match.group(1))
  3130. except ValueError:
  3131. continue
  3132. try:
  3133. payload = json.loads(zf.read(name).decode())
  3134. bbox_objects = payload.get("bbox_objects", [])
  3135. names = []
  3136. for obj in bbox_objects:
  3137. obj_name = obj.get("name") if isinstance(obj, dict) else None
  3138. if obj_name and obj_name not in names:
  3139. names.append(obj_name)
  3140. if names:
  3141. plate_json_objects[plate_index] = names
  3142. except Exception:
  3143. continue
  3144. # Build plate list
  3145. for idx in plate_indices:
  3146. meta = plate_metadata.get(idx, {})
  3147. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  3148. objects = meta.get("objects", [])
  3149. if not objects:
  3150. objects = plate_json_objects.get(idx, [])
  3151. if not objects and plate_object_ids.get(idx):
  3152. objects = [
  3153. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  3154. ]
  3155. plate_name = meta.get("name")
  3156. if not plate_name:
  3157. plate_name = plate_names.get(idx)
  3158. if not plate_name and objects:
  3159. plate_name = objects[0]
  3160. plates.append(
  3161. {
  3162. "index": idx,
  3163. "name": plate_name,
  3164. "objects": objects,
  3165. "object_count": len(objects),
  3166. "has_thumbnail": has_thumbnail,
  3167. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  3168. if has_thumbnail
  3169. else None,
  3170. "print_time_seconds": meta.get("prediction"),
  3171. "filament_used_grams": meta.get("weight"),
  3172. "filaments": meta.get("filaments", []),
  3173. "bed_type": meta.get("bed_type"),
  3174. }
  3175. )
  3176. except Exception as e:
  3177. logger.warning("Failed to parse plates from archive %s: %s", archive_id, e)
  3178. # Has gcode iff the plate list was built from .gcode filenames (as opposed
  3179. # to the JSON/PNG fallback for source-only 3MF projects). Callers that need
  3180. # to preview gcode — the viewer, skip-objects — can gate on this instead of
  3181. # 404-ing on every plate request.
  3182. has_gcode = bool(gcode_files)
  3183. return {
  3184. "archive_id": archive_id,
  3185. "filename": archive.filename,
  3186. "plates": plates,
  3187. "is_multi_plate": len(plates) > 1,
  3188. "has_gcode": has_gcode,
  3189. "embedded_printer": embedded_presets["printer"],
  3190. "embedded_process": embedded_presets["process"],
  3191. }
  3192. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  3193. async def get_plate_thumbnail(
  3194. archive_id: int,
  3195. plate_index: int,
  3196. db: AsyncSession = Depends(get_db),
  3197. _: None = RequireCameraStreamTokenIfAuthEnabled,
  3198. ):
  3199. """Get the thumbnail image for a specific plate.
  3200. Requires a stream token query param (?token=xxx) when auth is enabled.
  3201. """
  3202. service = ArchiveService(db)
  3203. archive = await service.get_archive(archive_id)
  3204. if not archive:
  3205. raise HTTPException(404, "Archive not found")
  3206. file_path = settings.base_dir / archive.file_path
  3207. if not file_path.is_file():
  3208. raise HTTPException(404, "Archive file not found")
  3209. try:
  3210. with zipfile.ZipFile(file_path, "r") as zf:
  3211. thumb_path = f"Metadata/plate_{plate_index}.png"
  3212. if thumb_path in zf.namelist():
  3213. data = zf.read(thumb_path)
  3214. return Response(content=data, media_type="image/png")
  3215. except Exception:
  3216. pass # Fall through to 404 if archive is unreadable or thumbnail missing
  3217. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  3218. async def _try_preview_slice_filaments(
  3219. db: AsyncSession,
  3220. *,
  3221. kind: str,
  3222. source_id: int,
  3223. plate_id: int,
  3224. file_path: Path,
  3225. request_id: str | None = None,
  3226. ) -> list[dict] | None:
  3227. """Run a preview slice via the user's configured sidecar so the filament
  3228. list endpoint can return real per-plate filaments for unsliced project
  3229. files. Returns ``None`` on any failure — the caller falls back to the
  3230. painted-face heuristic. ``request_id`` flows through to the sidecar
  3231. for live progress on the SliceModal's inline spinner + toast.
  3232. """
  3233. from backend.app.api.routes.settings import get_setting
  3234. from backend.app.services.slice_preview import get_preview_filaments
  3235. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  3236. if preferred == "orcaslicer":
  3237. configured = await get_setting(db, "orcaslicer_api_url")
  3238. api_url = (configured or settings.slicer_api_url).strip()
  3239. elif preferred == "bambu_studio":
  3240. configured = await get_setting(db, "bambu_studio_api_url")
  3241. api_url = (configured or settings.bambu_studio_api_url).strip()
  3242. else:
  3243. return None
  3244. if not api_url:
  3245. return None
  3246. try:
  3247. file_bytes = file_path.read_bytes()
  3248. except OSError:
  3249. return None
  3250. return await get_preview_filaments(
  3251. kind=kind,
  3252. source_id=source_id,
  3253. plate_id=plate_id,
  3254. file_bytes=file_bytes,
  3255. file_name=file_path.name,
  3256. api_url=api_url,
  3257. request_id=request_id,
  3258. )
  3259. @router.get("/{archive_id}/filament-requirements")
  3260. async def get_filament_requirements(
  3261. archive_id: int,
  3262. plate_id: int | None = None,
  3263. request_id: str | None = None,
  3264. db: AsyncSession = Depends(get_db),
  3265. auth_result: tuple[User | None, bool] = Depends(
  3266. require_ownership_permission(
  3267. Permission.ARCHIVES_READ_ALL,
  3268. Permission.ARCHIVES_READ_OWN,
  3269. )
  3270. ),
  3271. ):
  3272. """Get filament requirements from the archived 3MF file.
  3273. Returns the filaments used in this print with their slot IDs, types, colors,
  3274. and usage amounts. This can be compared with current AMS state before reprinting.
  3275. Args:
  3276. archive_id: The archive ID
  3277. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  3278. """
  3279. import defusedxml.ElementTree as ET
  3280. user, can_read_all = auth_result
  3281. service = ArchiveService(db)
  3282. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  3283. file_path = settings.base_dir / archive.file_path
  3284. if not file_path.is_file():
  3285. raise HTTPException(404, "Archive file not found")
  3286. filaments = []
  3287. try:
  3288. with zipfile.ZipFile(file_path, "r") as zf:
  3289. # Parse slice_info.config for filament requirements
  3290. if "Metadata/slice_info.config" in zf.namelist():
  3291. content = zf.read("Metadata/slice_info.config").decode()
  3292. root = ET.fromstring(content)
  3293. # If plate_id is specified, find filaments for that specific plate
  3294. if plate_id is not None:
  3295. # Find the plate element with matching index
  3296. for plate_elem in root.findall(".//plate"):
  3297. plate_index = None
  3298. for meta in plate_elem.findall("metadata"):
  3299. if meta.get("key") == "index":
  3300. try:
  3301. plate_index = int(meta.get("value", "0"))
  3302. except ValueError:
  3303. pass # Skip plate with non-numeric index metadata
  3304. break
  3305. if plate_index == plate_id:
  3306. # Extract filaments from this plate element
  3307. for filament_elem in plate_elem.findall("filament"):
  3308. filament_id = filament_elem.get("id")
  3309. filament_type = filament_elem.get("type", "")
  3310. filament_color = filament_elem.get("color", "")
  3311. used_g = filament_elem.get("used_g", "0")
  3312. used_m = filament_elem.get("used_m", "0")
  3313. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3314. try:
  3315. used_grams = float(used_g)
  3316. except (ValueError, TypeError):
  3317. used_grams = 0
  3318. if used_grams > 0 and filament_id:
  3319. filaments.append(
  3320. {
  3321. "slot_id": int(filament_id),
  3322. "type": filament_type,
  3323. "color": filament_color,
  3324. "used_grams": round(used_grams, 1),
  3325. "used_meters": float(used_m) if used_m else 0,
  3326. "tray_info_idx": tray_info_idx,
  3327. "used_in_plate": True,
  3328. }
  3329. )
  3330. break
  3331. else:
  3332. # No plate_id specified - extract all filaments with used_g > 0
  3333. # This is the legacy behavior for single-plate files
  3334. for filament_elem in root.findall(".//filament"):
  3335. filament_id = filament_elem.get("id")
  3336. filament_type = filament_elem.get("type", "")
  3337. filament_color = filament_elem.get("color", "")
  3338. used_g = filament_elem.get("used_g", "0")
  3339. used_m = filament_elem.get("used_m", "0")
  3340. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3341. # Only include filaments that are actually used
  3342. try:
  3343. used_grams = float(used_g)
  3344. except (ValueError, TypeError):
  3345. used_grams = 0
  3346. if used_grams > 0 and filament_id:
  3347. filaments.append(
  3348. {
  3349. "slot_id": int(filament_id),
  3350. "type": filament_type,
  3351. "color": filament_color,
  3352. "used_grams": round(used_grams, 1),
  3353. "used_meters": float(used_m) if used_m else 0,
  3354. "tray_info_idx": tray_info_idx,
  3355. "used_in_plate": True,
  3356. }
  3357. )
  3358. # Unsliced project files: see library.py for full rationale.
  3359. # Return the FULL project_settings.config slot list with a
  3360. # used_in_plate flag derived from the preview slice; the
  3361. # CLI needs every slot pre-filled to avoid silent default
  3362. # substitution.
  3363. if not filaments:
  3364. project_filaments = extract_project_filaments_from_3mf(zf)
  3365. used_slot_ids: set[int] = set()
  3366. if project_filaments and plate_id is not None:
  3367. preview = await _try_preview_slice_filaments(
  3368. db,
  3369. kind="archive",
  3370. source_id=archive_id,
  3371. plate_id=plate_id,
  3372. file_path=file_path,
  3373. request_id=request_id,
  3374. )
  3375. if preview is not None:
  3376. used_slot_ids = {f["slot_id"] for f in preview}
  3377. fallback_all_used = not used_slot_ids
  3378. for f in project_filaments:
  3379. f["used_in_plate"] = fallback_all_used or f["slot_id"] in used_slot_ids
  3380. filaments = project_filaments
  3381. # Sort by slot ID
  3382. filaments.sort(key=lambda x: x["slot_id"])
  3383. # Enrich with nozzle mapping for dual-nozzle printers
  3384. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  3385. if nozzle_mapping:
  3386. for filament in filaments:
  3387. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  3388. except Exception as e:
  3389. logger.warning("Failed to parse filament requirements from archive %s: %s", archive_id, e)
  3390. return {
  3391. "archive_id": archive_id,
  3392. "filename": archive.filename,
  3393. "plate_id": plate_id,
  3394. "filaments": filaments,
  3395. }
  3396. @router.post("/{archive_id}/slice", status_code=202)
  3397. async def slice_archive(
  3398. archive_id: int,
  3399. request: SliceRequest,
  3400. db: AsyncSession = Depends(get_db),
  3401. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  3402. ):
  3403. """Enqueue a slice job for an archive's source. Returns 202 + job_id;
  3404. the slice runs in the background, the caller polls `GET /slice-jobs/{id}`.
  3405. Source preference: ``source_3mf_path`` (the un-sliced project file the
  3406. user originally sent to slice) → ``file_path`` (the sliced 3MF/gcode that
  3407. actually printed).
  3408. """
  3409. from backend.app.api.routes.library import guard_nozzle_class_reslice, slice_and_persist_as_archive
  3410. from backend.app.core.database import async_session
  3411. from backend.app.services.slice_dispatch import (
  3412. http_exception_to_job_error,
  3413. slice_dispatch,
  3414. )
  3415. archive = await db.get(PrintArchive, archive_id)
  3416. if archive is None:
  3417. raise HTTPException(status_code=404, detail="Archive not found")
  3418. src_relative = archive.source_3mf_path or archive.file_path
  3419. if not src_relative:
  3420. raise HTTPException(
  3421. status_code=400,
  3422. detail="Archive has no source file to slice",
  3423. )
  3424. src_path = (
  3425. Path(settings.base_dir) / src_relative
  3426. ) # SEC-PATH-OK: src_relative is archive.source_3mf_path from DB, set by _resolve_source_3mf_path which already does resolve+relative_to containment
  3427. if not src_path.exists():
  3428. raise HTTPException(status_code=404, detail="Archive source file missing on disk")
  3429. raw_filename = archive.filename or src_path.name
  3430. src_lower = raw_filename.lower()
  3431. if not (
  3432. src_lower.endswith(".stl")
  3433. or src_lower.endswith(".3mf")
  3434. or src_lower.endswith(".step")
  3435. or src_lower.endswith(".stp")
  3436. ):
  3437. raise HTTPException(
  3438. status_code=400,
  3439. detail="Archive's source file must be STL, 3MF, or STEP to slice",
  3440. )
  3441. # Match the library route: derive the sliced output's filename from
  3442. # `print_name` when set, so the new archive row's display name lines
  3443. # up with the source's display.
  3444. src_ext = Path(raw_filename).suffix.lower() or ".3mf"
  3445. src_filename = (
  3446. f"{archive.print_name.strip()}{src_ext}" if archive.print_name and archive.print_name.strip() else raw_filename
  3447. )
  3448. model_bytes = src_path.read_bytes()
  3449. archive_id_local = archive.id
  3450. user_id = current_user.id if current_user else None
  3451. # Block a cross-nozzle-class re-slice (single-nozzle <-> H2D) up front —
  3452. # BambuStudio's multi-extruder validator would otherwise reject it with a
  3453. # cryptic error. No-op for same-class or un-sliced sources.
  3454. await guard_nozzle_class_reslice(db, current_user, request, archive.sliced_for_model)
  3455. async def _run(job_id: int):
  3456. async with async_session() as task_db:
  3457. # Re-fetch the source archive on the background-task session.
  3458. src_archive = await task_db.get(PrintArchive, archive_id_local)
  3459. if src_archive is None:
  3460. raise http_exception_to_job_error(
  3461. HTTPException(status_code=404, detail="Archive disappeared during slice")
  3462. )
  3463. try:
  3464. response = await slice_and_persist_as_archive(
  3465. task_db,
  3466. model_bytes=model_bytes,
  3467. model_filename=src_filename,
  3468. request=request,
  3469. source_archive=src_archive,
  3470. current_user_id=user_id,
  3471. job_id=job_id,
  3472. )
  3473. except HTTPException as exc:
  3474. raise http_exception_to_job_error(exc) from exc
  3475. return response.model_dump()
  3476. job = await slice_dispatch.enqueue(
  3477. kind="archive",
  3478. source_id=archive.id,
  3479. source_name=archive.print_name or archive.filename or f"archive {archive.id}",
  3480. run=_run,
  3481. )
  3482. return {
  3483. "job_id": job.id,
  3484. "status": job.status,
  3485. "status_url": f"/api/v1/slice-jobs/{job.id}",
  3486. }
  3487. @router.post("/{archive_id}/reprint")
  3488. async def reprint_archive(
  3489. archive_id: int,
  3490. printer_id: int,
  3491. # SECURITY.md SEC-AUTH-1: every route either has an explicit auth dep or
  3492. # is in the route-auth-coverage allowlist. Gating the deprecation stub on
  3493. # QUEUE_CREATE matches the replacement route (POST /queue/) and means
  3494. # anonymous callers bounce at auth instead of seeing the deprecation
  3495. # message — leaking "this route exists" to unauthenticated callers is
  3496. # exactly the shape the backstop guards against.
  3497. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  3498. ):
  3499. """Legacy direct reprint endpoint. Use POST /queue/ instead."""
  3500. logger.warning(
  3501. "Gone API used: POST /archives/%s/reprint?printer_id=%s; use POST /queue/ instead",
  3502. archive_id,
  3503. printer_id,
  3504. )
  3505. raise HTTPException(
  3506. status_code=410,
  3507. detail="Direct archive reprint has been removed. Create a print queue item with POST /queue/.",
  3508. )
  3509. # =============================================================================
  3510. # Project Page API
  3511. # =============================================================================
  3512. @router.get("/{archive_id}/project-page")
  3513. async def get_project_page(
  3514. archive_id: int,
  3515. db: AsyncSession = Depends(get_db),
  3516. auth_result: tuple[User | None, bool] = Depends(
  3517. require_ownership_permission(
  3518. Permission.ARCHIVES_READ_ALL,
  3519. Permission.ARCHIVES_READ_OWN,
  3520. )
  3521. ),
  3522. ):
  3523. """Get the project page data from the 3MF file."""
  3524. from backend.app.schemas.archive import ProjectPageResponse
  3525. from backend.app.services.archive import ProjectPageParser
  3526. user, can_read_all = auth_result
  3527. service = ArchiveService(db)
  3528. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  3529. file_path = settings.base_dir / archive.file_path
  3530. if not file_path.is_file():
  3531. raise HTTPException(404, "Archive file not found")
  3532. parser = ProjectPageParser(file_path)
  3533. data = parser.parse(archive_id)
  3534. return ProjectPageResponse(**data)
  3535. @router.patch("/{archive_id}/project-page")
  3536. async def update_project_page(
  3537. archive_id: int,
  3538. update_data: dict,
  3539. db: AsyncSession = Depends(get_db),
  3540. auth_result: tuple[User | None, bool] = Depends(
  3541. require_ownership_permission(
  3542. Permission.ARCHIVES_UPDATE_ALL,
  3543. Permission.ARCHIVES_UPDATE_OWN,
  3544. )
  3545. ),
  3546. ):
  3547. """Update project page metadata in the 3MF file."""
  3548. from backend.app.services.archive import ProjectPageParser
  3549. user, can_modify_all = auth_result
  3550. service = ArchiveService(db)
  3551. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_modify_all)
  3552. file_path = settings.base_dir / archive.file_path
  3553. if not file_path.is_file():
  3554. raise HTTPException(404, "Archive file not found")
  3555. parser = ProjectPageParser(file_path)
  3556. success = parser.update_metadata(update_data)
  3557. if not success:
  3558. raise HTTPException(500, "Failed to update project page")
  3559. # Return updated data
  3560. data = parser.parse(archive_id)
  3561. return data
  3562. @router.get("/{archive_id}/project-image/{image_path:path}")
  3563. async def get_project_image(
  3564. archive_id: int,
  3565. image_path: str,
  3566. db: AsyncSession = Depends(get_db),
  3567. _: None = RequireCameraStreamTokenIfAuthEnabled,
  3568. ):
  3569. """Get an image from the 3MF project page.
  3570. Requires a stream token query param (?token=xxx) when auth is enabled.
  3571. """
  3572. from backend.app.services.archive import ProjectPageParser
  3573. service = ArchiveService(db)
  3574. archive = await service.get_archive(archive_id)
  3575. if not archive:
  3576. raise HTTPException(404, "Archive not found")
  3577. file_path = settings.base_dir / archive.file_path
  3578. if not file_path.is_file():
  3579. raise HTTPException(404, "Archive file not found")
  3580. parser = ProjectPageParser(file_path)
  3581. result = parser.get_image(image_path)
  3582. if not result:
  3583. raise HTTPException(404, "Image not found in 3MF file")
  3584. image_data, content_type = result
  3585. return Response(
  3586. content=image_data,
  3587. media_type=content_type,
  3588. headers={"Cache-Control": "max-age=3600"},
  3589. )
  3590. # =============================================================================
  3591. # Source 3MF API (Original Project Files)
  3592. # =============================================================================
  3593. def _resolve_source_3mf_path(archive: PrintArchive, source_filename: str) -> Path:
  3594. """Resolve where to write a source 3MF for ``archive``.
  3595. Normal archives nest the source under ``<archive_file_dir>/source/``.
  3596. "Fallback" archives (created in main.py when MQTT reports a print start
  3597. but Bambuddy never saw the source 3MF — cloud / Handy / pre-existing
  3598. SD-card prints) carry ``file_path=""``. Joining that with ``base_dir``
  3599. via the ``/`` operator silently yields ``base_dir`` itself, whose parent
  3600. is ``base_dir.parent`` — which sent the upload to ``/app/source/`` and
  3601. raised a 500 on the final ``relative_to`` (#1531). Fallback archives
  3602. now land under ``<base_dir>/archive/no_source/<archive_id>/`` instead,
  3603. which stays inside the data volume and remains addressable by every
  3604. read site that does ``base_dir / archive.source_3mf_path``.
  3605. The resolved directory is asserted to be inside ``base_dir`` even when
  3606. ``archive.file_path`` is populated, so a row corrupted by an old import
  3607. or manual SQL edit fails with a clear 500 instead of writing outside
  3608. the data volume.
  3609. """
  3610. if archive.file_path:
  3611. archive_file = settings.base_dir / archive.file_path
  3612. source_dir = archive_file.parent / "source"
  3613. else:
  3614. source_dir = settings.base_dir / "archive" / "no_source" / str(archive.id)
  3615. # Containment check via resolve() — catches absolute file_path, `..`
  3616. # traversal, and any other shape that escapes the data volume — but we
  3617. # return the *literal* source_dir below. Resolving the returned path
  3618. # would canonicalise away a symlinked DATA_DIR (legitimate on TrueNAS /
  3619. # QNAP / Synology storage pools, and any `-v /symlink:/app/data`
  3620. # mount), which would then make the caller's
  3621. # ``source_path.relative_to(settings.base_dir)`` raise because the
  3622. # left side is canonical and the right is the symlink path.
  3623. try:
  3624. source_dir.resolve().relative_to(settings.base_dir.resolve())
  3625. except ValueError as exc:
  3626. raise HTTPException(
  3627. 500,
  3628. f"Archive {archive.id} resolves to a path outside the data directory; cannot attach source.",
  3629. ) from exc
  3630. source_dir.mkdir(parents=True, exist_ok=True)
  3631. return (
  3632. source_dir / source_filename
  3633. ) # SEC-PATH-OK: callers pass _safe_filename(...) basename-stripped; source_dir resolve+relative_to checked above
  3634. @router.post("/{archive_id}/source")
  3635. async def upload_source_3mf(
  3636. archive_id: int,
  3637. file: UploadFile = File(...),
  3638. db: AsyncSession = Depends(get_db),
  3639. auth_result: tuple[User | None, bool] = Depends(
  3640. require_ownership_permission(
  3641. Permission.ARCHIVES_UPDATE_ALL,
  3642. Permission.ARCHIVES_UPDATE_OWN,
  3643. )
  3644. ),
  3645. ):
  3646. """Upload the original source 3MF project file for an archive."""
  3647. user, can_modify_all = auth_result
  3648. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3649. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3650. if not file.filename or not file.filename.endswith(".3mf"):
  3651. raise HTTPException(400, "File must be a .3mf file")
  3652. # Save the source 3MF file - preserve original filename, strip directory components
  3653. source_filename = _safe_filename(file.filename)
  3654. source_path = _resolve_source_3mf_path(archive, source_filename)
  3655. # Delete old source file if exists
  3656. if archive.source_3mf_path:
  3657. old_source_path = settings.base_dir / archive.source_3mf_path
  3658. if old_source_path.exists():
  3659. old_source_path.unlink()
  3660. content = await file.read()
  3661. # #1401: validate zip header on source 3MF uploads too — source files
  3662. # are uploaded for reprint and slicing, so an invalid one breaks the
  3663. # same downstream paths as a bad sliced file.
  3664. from backend.app.api.routes.library import validate_print_file_upload
  3665. validate_print_file_upload(file.filename, content)
  3666. source_path.write_bytes(content)
  3667. # Update archive with source path (relative to base_dir)
  3668. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3669. await db.commit()
  3670. await db.refresh(archive)
  3671. return {
  3672. "status": "uploaded",
  3673. "source_3mf_path": archive.source_3mf_path,
  3674. "filename": source_filename,
  3675. }
  3676. @router.get("/{archive_id}/source")
  3677. async def download_source_3mf(
  3678. archive_id: int,
  3679. db: AsyncSession = Depends(get_db),
  3680. auth_result: tuple[User | None, bool] = Depends(
  3681. require_ownership_permission(
  3682. Permission.ARCHIVES_READ_ALL,
  3683. Permission.ARCHIVES_READ_OWN,
  3684. )
  3685. ),
  3686. ):
  3687. """Download the source 3MF project file."""
  3688. user, can_read_all = auth_result
  3689. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3690. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3691. if not archive.source_3mf_path:
  3692. raise HTTPException(404, "No source 3MF attached to this archive")
  3693. source_path = settings.base_dir / archive.source_3mf_path
  3694. if not source_path.exists():
  3695. raise HTTPException(404, "Source 3MF file not found on disk")
  3696. # Use the actual filename from the path
  3697. filename = source_path.name
  3698. return FileResponse(
  3699. path=source_path,
  3700. filename=filename,
  3701. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3702. )
  3703. @router.get("/{archive_id}/source/{filename}")
  3704. async def download_source_3mf_for_slicer(
  3705. archive_id: int,
  3706. filename: str,
  3707. db: AsyncSession = Depends(get_db),
  3708. auth_result: tuple[User | None, bool] = Depends(
  3709. require_ownership_permission(
  3710. Permission.ARCHIVES_READ_ALL,
  3711. Permission.ARCHIVES_READ_OWN,
  3712. )
  3713. ),
  3714. ):
  3715. """Download source 3MF with filename in URL."""
  3716. user, can_read_all = auth_result
  3717. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3718. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3719. if not archive.source_3mf_path:
  3720. raise HTTPException(404, "No source 3MF attached to this archive")
  3721. source_path = settings.base_dir / archive.source_3mf_path
  3722. if not source_path.exists():
  3723. raise HTTPException(404, "Source 3MF file not found on disk")
  3724. return FileResponse(
  3725. path=source_path,
  3726. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3727. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3728. )
  3729. @router.post("/{archive_id}/source-slicer-token")
  3730. async def create_source_slicer_token(
  3731. archive_id: int,
  3732. db: AsyncSession = Depends(get_db),
  3733. auth_result: tuple[User | None, bool] = Depends(
  3734. require_ownership_permission(
  3735. Permission.ARCHIVES_READ_ALL,
  3736. Permission.ARCHIVES_READ_OWN,
  3737. )
  3738. ),
  3739. ):
  3740. """Create a short-lived download token for opening source 3MF in slicer."""
  3741. from backend.app.core.auth import create_slicer_download_token
  3742. user, can_read_all = auth_result
  3743. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3744. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3745. if not archive.source_3mf_path:
  3746. raise HTTPException(404, "No source 3MF attached to this archive")
  3747. token = await create_slicer_download_token("source", archive_id)
  3748. return {"token": token}
  3749. @router.get("/{archive_id}/source-dl/{token}/{filename}")
  3750. async def download_source_3mf_for_slicer_with_token(
  3751. archive_id: int,
  3752. token: str,
  3753. filename: str,
  3754. db: AsyncSession = Depends(get_db),
  3755. ):
  3756. """Download source 3MF using a slicer download token.
  3757. Token-authenticated (no auth headers needed). The token is short-lived
  3758. and single-use, created by POST /{archive_id}/source-slicer-token.
  3759. """
  3760. from backend.app.core.auth import verify_slicer_download_token
  3761. if not await verify_slicer_download_token(token, "source", archive_id):
  3762. raise HTTPException(403, "Invalid or expired download token")
  3763. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3764. archive = result.scalar_one_or_none()
  3765. if not archive:
  3766. raise HTTPException(404, "Archive not found")
  3767. if not archive.source_3mf_path:
  3768. raise HTTPException(404, "No source 3MF attached to this archive")
  3769. source_path = settings.base_dir / archive.source_3mf_path
  3770. if not source_path.exists():
  3771. raise HTTPException(404, "Source 3MF file not found on disk")
  3772. return FileResponse(
  3773. path=source_path,
  3774. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3775. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3776. )
  3777. @router.post("/upload-source")
  3778. async def upload_source_3mf_by_name(
  3779. file: UploadFile = File(...),
  3780. print_name: str = Query(None, description="Match archive by print name"),
  3781. db: AsyncSession = Depends(get_db),
  3782. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3783. ):
  3784. """Upload source 3MF and match to archive by print name.
  3785. This endpoint is designed for slicer post-processing scripts.
  3786. It finds the most recent archive matching the print name and attaches the source.
  3787. """
  3788. if not file.filename or not file.filename.endswith(".3mf"):
  3789. raise HTTPException(400, "File must be a .3mf file")
  3790. safe_filename = _safe_filename(file.filename)
  3791. # Derive print name from filename if not provided
  3792. if not print_name:
  3793. # Remove .3mf extension and common suffixes
  3794. print_name = safe_filename.rsplit(".3mf", 1)[0]
  3795. # Remove _source suffix if present
  3796. if print_name.endswith("_source"):
  3797. print_name = print_name[:-7]
  3798. # Find matching archive - try exact match first, then fuzzy
  3799. result = await db.execute(
  3800. select(PrintArchive)
  3801. .where(PrintArchive.print_name == print_name)
  3802. .order_by(PrintArchive.created_at.desc())
  3803. .limit(1)
  3804. )
  3805. archive = result.scalar_one_or_none()
  3806. if not archive:
  3807. # Try matching filename without .gcode.3mf
  3808. result = await db.execute(
  3809. select(PrintArchive)
  3810. .where(PrintArchive.filename.like(f"{print_name}%"))
  3811. .order_by(PrintArchive.created_at.desc())
  3812. .limit(1)
  3813. )
  3814. archive = result.scalar_one_or_none()
  3815. if not archive:
  3816. # Try case-insensitive partial match on print_name
  3817. result = await db.execute(
  3818. select(PrintArchive)
  3819. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  3820. .order_by(PrintArchive.created_at.desc())
  3821. .limit(1)
  3822. )
  3823. archive = result.scalar_one_or_none()
  3824. if not archive:
  3825. raise HTTPException(404, f"No archive found matching '{print_name}'")
  3826. # Save the source 3MF file - preserve original filename, strip directory components
  3827. source_filename = safe_filename
  3828. source_path = _resolve_source_3mf_path(archive, source_filename)
  3829. # Delete old source file if exists
  3830. if archive.source_3mf_path:
  3831. old_source_path = settings.base_dir / archive.source_3mf_path
  3832. if old_source_path.exists():
  3833. old_source_path.unlink()
  3834. content = await file.read()
  3835. # #1401: same zip-header check as the other upload routes — the
  3836. # match-by-name endpoint is used by slicer post-processing scripts,
  3837. # so a misconfigured script is exactly how a bad 3MF would slip in.
  3838. from backend.app.api.routes.library import validate_print_file_upload
  3839. validate_print_file_upload(file.filename, content)
  3840. source_path.write_bytes(content)
  3841. # Update archive with source path
  3842. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3843. await db.commit()
  3844. await db.refresh(archive)
  3845. return {
  3846. "status": "uploaded",
  3847. "archive_id": archive.id,
  3848. "archive_name": archive.print_name or archive.filename,
  3849. "source_3mf_path": archive.source_3mf_path,
  3850. "filename": source_filename,
  3851. }
  3852. @router.delete("/{archive_id}/source")
  3853. async def delete_source_3mf(
  3854. archive_id: int,
  3855. db: AsyncSession = Depends(get_db),
  3856. auth_result: tuple[User | None, bool] = Depends(
  3857. require_ownership_permission(
  3858. Permission.ARCHIVES_DELETE_ALL,
  3859. Permission.ARCHIVES_DELETE_OWN,
  3860. )
  3861. ),
  3862. ):
  3863. """Delete the source 3MF project file from an archive."""
  3864. user, can_modify_all = auth_result
  3865. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3866. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3867. if not archive.source_3mf_path:
  3868. raise HTTPException(404, "No source 3MF attached to this archive")
  3869. # Delete the file
  3870. source_path = settings.base_dir / archive.source_3mf_path
  3871. if source_path.exists():
  3872. source_path.unlink()
  3873. # Clear the path in database
  3874. archive.source_3mf_path = None
  3875. await db.commit()
  3876. return {"status": "deleted"}
  3877. # =============================================================================
  3878. # F3D API (Fusion 360 Design Files)
  3879. # =============================================================================
  3880. @router.post("/{archive_id}/f3d")
  3881. async def upload_f3d(
  3882. archive_id: int,
  3883. file: UploadFile = File(...),
  3884. db: AsyncSession = Depends(get_db),
  3885. auth_result: tuple[User | None, bool] = Depends(
  3886. require_ownership_permission(
  3887. Permission.ARCHIVES_UPDATE_ALL,
  3888. Permission.ARCHIVES_UPDATE_OWN,
  3889. )
  3890. ),
  3891. ):
  3892. """Upload a Fusion 360 design file for an archive."""
  3893. user, can_modify_all = auth_result
  3894. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3895. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3896. if not file.filename or not file.filename.endswith(".f3d"):
  3897. raise HTTPException(400, "File must be a .f3d file")
  3898. # Get archive directory and create f3d subdirectory
  3899. file_path = settings.base_dir / archive.file_path
  3900. archive_dir = file_path.parent
  3901. f3d_dir = archive_dir / "f3d"
  3902. f3d_dir.mkdir(exist_ok=True)
  3903. # Delete old F3D file if exists
  3904. if archive.f3d_path:
  3905. old_f3d_path = settings.base_dir / archive.f3d_path
  3906. if old_f3d_path.exists():
  3907. old_f3d_path.unlink()
  3908. # Save the F3D file - preserve original filename, strip directory components
  3909. f3d_filename = _safe_filename(file.filename)
  3910. f3d_path = f3d_dir / f3d_filename # SEC-PATH-OK: f3d_filename = _safe_filename(...) basename-stripped above
  3911. content = await file.read()
  3912. f3d_path.write_bytes(content)
  3913. # Update archive with F3D path (relative to base_dir)
  3914. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  3915. await db.commit()
  3916. await db.refresh(archive)
  3917. return {
  3918. "status": "uploaded",
  3919. "f3d_path": archive.f3d_path,
  3920. "filename": f3d_filename,
  3921. }
  3922. @router.get("/{archive_id}/f3d")
  3923. async def download_f3d(
  3924. archive_id: int,
  3925. db: AsyncSession = Depends(get_db),
  3926. auth_result: tuple[User | None, bool] = Depends(
  3927. require_ownership_permission(
  3928. Permission.ARCHIVES_READ_ALL,
  3929. Permission.ARCHIVES_READ_OWN,
  3930. )
  3931. ),
  3932. ):
  3933. """Download the Fusion 360 design file."""
  3934. user, can_read_all = auth_result
  3935. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3936. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3937. if not archive.f3d_path:
  3938. raise HTTPException(404, "No F3D file attached to this archive")
  3939. f3d_path = settings.base_dir / archive.f3d_path
  3940. if not f3d_path.exists():
  3941. raise HTTPException(404, "F3D file not found on disk")
  3942. # Use the actual filename from the path
  3943. filename = f3d_path.name
  3944. return FileResponse(
  3945. path=f3d_path,
  3946. filename=filename,
  3947. media_type="application/octet-stream",
  3948. )
  3949. @router.delete("/{archive_id}/f3d")
  3950. async def delete_f3d(
  3951. archive_id: int,
  3952. db: AsyncSession = Depends(get_db),
  3953. auth_result: tuple[User | None, bool] = Depends(
  3954. require_ownership_permission(
  3955. Permission.ARCHIVES_DELETE_ALL,
  3956. Permission.ARCHIVES_DELETE_OWN,
  3957. )
  3958. ),
  3959. ):
  3960. """Delete the Fusion 360 design file from an archive."""
  3961. user, can_modify_all = auth_result
  3962. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3963. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3964. if not archive.f3d_path:
  3965. raise HTTPException(404, "No F3D file attached to this archive")
  3966. # Delete the file
  3967. f3d_path = settings.base_dir / archive.f3d_path
  3968. if f3d_path.exists():
  3969. f3d_path.unlink()
  3970. # Clear the path in database
  3971. archive.f3d_path = None
  3972. await db.commit()
  3973. return {"status": "deleted"}