archives.py 191 KB

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