archives.py 192 KB

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