archives.py 193 KB

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