archives.py 267 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364
  1. import asyncio
  2. import io
  3. import json
  4. import logging
  5. import re as _re
  6. import zipfile
  7. from collections import defaultdict
  8. from dataclasses import replace
  9. from datetime import date, datetime, timedelta, timezone
  10. from html import escape as html_escape
  11. from pathlib import Path
  12. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  13. from fastapi.responses import FileResponse, Response
  14. from pydantic import BaseModel, Field
  15. from sqlalchemy import and_, case, func, or_, select
  16. from sqlalchemy.ext.asyncio import AsyncSession
  17. from sqlalchemy.sql.elements import ColumnElement
  18. from backend.app.core import database
  19. from backend.app.core.auth import (
  20. ApiKeyActor,
  21. MediaOrRequestPrinterScope,
  22. RequestActor,
  23. RequestPrinterScope,
  24. RequirePermissionIfAuthEnabled,
  25. probe_permissions_if_auth_enabled,
  26. require_media_token_ownership,
  27. require_ownership_permission,
  28. )
  29. from backend.app.core.config import settings
  30. from backend.app.core.database import get_db
  31. from backend.app.core.permissions import Permission
  32. from backend.app.core.printer_scope import PrinterScope
  33. from backend.app.core.row_visibility import archive_scope_clause, whole_archive_scope_clause
  34. from backend.app.models.archive import PrintArchive
  35. from backend.app.models.filament import Filament
  36. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  37. from backend.app.models.printer import Printer
  38. from backend.app.models.project import Project
  39. from backend.app.models.spool_usage_history import SpoolUsageHistory
  40. from backend.app.models.user import User
  41. from backend.app.schemas.archive import ArchiveResponse, ArchiveSlim, ArchiveStats, ArchiveUpdate
  42. from backend.app.schemas.print_log import PrintLogResponse
  43. from backend.app.schemas.slicer import SliceRequest
  44. from backend.app.services.archive import ArchiveService, printed_on_clause
  45. from backend.app.services.archive_scope import (
  46. ScopedView,
  47. ensure_whole_archive_in_scope,
  48. printed_in_scope,
  49. scoped_view,
  50. scoped_views,
  51. )
  52. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  53. from backend.app.services.design_settings import overrides_from_config
  54. from backend.app.services.filament_requirements import annotate_rack_groups
  55. from backend.app.services.print_confirmation import (
  56. is_one_tap_request,
  57. is_unattended_fetch,
  58. )
  59. from backend.app.services.print_cost_estimate import default_cost_per_kg as _default_cost_per_kg, price_one_print
  60. from backend.app.services.print_log import owns_media, runs_with_timelapse
  61. from backend.app.services.print_storage import (
  62. REASON_FTP_TRANSFER_FAILED,
  63. REASON_FTPS_COOLOFF,
  64. REASON_INTERNAL_HISTORY,
  65. REASON_INTERNAL_STORAGE,
  66. REASON_NO_EXTERNAL_STORAGE,
  67. )
  68. from backend.app.services.printer_media import VIDEO_SUFFIXES, match_ipcam_chunks
  69. from backend.app.utils.archive_paths import archive_photos_dir, find_archive_photo
  70. from backend.app.utils.http import build_content_disposition, download_error_response, safe_download_filename
  71. from backend.app.utils.local_time import day_zone, local_date_end, local_date_start, to_naive_utc
  72. from backend.app.utils.threemf_tools import (
  73. default_plate_gcode_name,
  74. expand_to_project_slots,
  75. extract_embedded_presets_from_3mf,
  76. extract_nozzle_mapping_from_3mf,
  77. extract_project_filaments_from_3mf,
  78. names_carry_gcode,
  79. select_plate_gcode_name,
  80. )
  81. logger = logging.getLogger(__name__)
  82. router = APIRouter(prefix="/archives", tags=["archives"])
  83. _PRINTER_MEDIA_LIST_TIMEOUT_SECONDS = 8.0
  84. # Path of the embedded slicer config inside a BambuStudio/OrcaSlicer 3MF.
  85. _PROJECT_SETTINGS_PATH = "Metadata/project_settings.config"
  86. def _safe_filename(filename: str) -> str:
  87. """Extract basename from a client-supplied filename, preventing path traversal.
  88. Normalizes backslashes (Windows paths) before extracting so that
  89. '..\\\\..\\\\evil.3mf' is correctly stripped to 'evil.3mf' on Linux.
  90. """
  91. return Path(filename.replace("\\", "/")).name
  92. _TIMELAPSE_FILENAME_TS_RE = _re.compile(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})")
  93. _DEFAULT_TIMELAPSE_OFFSETS_HOURS: tuple[int, ...] = (0, 8, -8, 7, -7, 1, -1)
  94. _DEFAULT_TIMELAPSE_TOLERANCE = timedelta(hours=4)
  95. _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN = timedelta(minutes=15)
  96. def _match_timelapse_by_timestamp(
  97. video_files: list[dict],
  98. archive_start: datetime | None,
  99. *,
  100. tolerance: timedelta = _DEFAULT_TIMELAPSE_TOLERANCE,
  101. ambiguity_margin: timedelta = _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN,
  102. offsets_hours: tuple[int, ...] = _DEFAULT_TIMELAPSE_OFFSETS_HOURS,
  103. ) -> tuple[dict | None, timedelta | None]:
  104. """Pick the timelapse whose filename timestamp best matches the print start time.
  105. Bambu timelapse filenames embed the printer-local START time (e.g.
  106. "video_2026-05-08_09-41-29.mp4"). The printer's clock may be offset from the
  107. server's — especially in LAN-Only mode where NTP is unreachable — so we try a
  108. small set of common UTC offsets and keep the (video, offset) pair with the
  109. smallest absolute distance from archive_start. We deliberately do NOT consider
  110. archive_end here: the filename is start time, not end time, so comparing it to
  111. completion is not a real signal (Strategy 3 handles end via file mtime).
  112. Because the offset list densely covers a wide span, an unrelated video's
  113. filename can coincidentally land near a later print's start at some offset.
  114. To avoid that false positive, we require the best (video, offset) pair to
  115. beat the next-best pair *from a different video* by at least `ambiguity_margin`.
  116. When the top two candidates from different videos are too close to call,
  117. we return None and let the caller fall back to manual selection.
  118. """
  119. if archive_start is None:
  120. return None, None
  121. # (diff, video) for every (video, offset) pair within tolerance.
  122. candidates: list[tuple[timedelta, dict]] = []
  123. for f in video_files:
  124. fname = f.get("name", "")
  125. m = _TIMELAPSE_FILENAME_TS_RE.search(fname)
  126. if not m:
  127. continue
  128. try:
  129. file_time = datetime.strptime(m.group(1), "%Y-%m-%d_%H-%M-%S")
  130. except ValueError:
  131. continue
  132. for hour_offset in offsets_hours:
  133. adjusted = file_time - timedelta(hours=hour_offset)
  134. diff = abs(adjusted - archive_start)
  135. if diff <= tolerance:
  136. candidates.append((diff, f))
  137. if not candidates:
  138. return None, None
  139. candidates.sort(key=lambda c: c[0])
  140. best_diff, best_video = candidates[0]
  141. best_name = best_video.get("name")
  142. for diff, video in candidates[1:]:
  143. if video.get("name") != best_name and (diff - best_diff) < ambiguity_margin:
  144. # Another video matches almost as well — refuse to auto-pick.
  145. return None, None
  146. return best_video, best_diff
  147. async def _claimed_timelapse_stems(db, printer_id: int | None, exclude_archive_id: int) -> set[str]:
  148. """Video filenames already attached to another print of this printer
  149. (#2704): ``print_log.claimed_timelapse_stems``, for the print the archive
  150. shows, its newest run."""
  151. from backend.app.services.print_log import claimed_timelapse_stems, newest_run
  152. run = await newest_run(db, exclude_archive_id)
  153. return await claimed_timelapse_stems(
  154. db, printer_id, archive_id=exclude_archive_id, run_id=run.id if run is not None else None
  155. )
  156. def _visible_archive_clauses(
  157. user, can_read_all: bool, printer_scope: PrinterScope, *, whole: bool = False, by_runs: bool = True
  158. ) -> list:
  159. """WHERE clauses for the archives a caller may see, as _ensure_archive_visible decides one by one.
  160. ``whole``: only those every print of which they see, for a change to the
  161. whole archive (``ensure_whole_archive_in_scope``). Not ``by_runs``: only
  162. those on their printers, for listings that show the archive's latest
  163. print as it is, without the caller's view of it (``_scoped``)."""
  164. clauses = []
  165. if whole:
  166. scope_clause = whole_archive_scope_clause(printer_scope)
  167. elif by_runs:
  168. scope_clause = archive_scope_clause(printer_scope)
  169. else:
  170. scope_clause = printer_scope.where(PrintArchive.printer_id)
  171. if scope_clause is not None:
  172. clauses.append(scope_clause)
  173. if not can_read_all:
  174. # Own archives only; an ownerless one needs read-all, and no user sees none.
  175. clauses.append(PrintArchive.created_by_id == user.id if user is not None else PrintArchive.id.is_(None))
  176. return clauses
  177. async def _ensure_archive_visible(
  178. archive: PrintArchive | None,
  179. user: User | ApiKeyActor | None,
  180. can_read_all: bool,
  181. printer_scope: PrinterScope,
  182. ) -> PrintArchive:
  183. """Per-archive visibility gate for ownership-scoped reads (#1726-adjacent).
  184. Returns ``archive`` if the caller is allowed to see it; raises 404 otherwise.
  185. Single enforcement point used by every detail / download / sub-resource
  186. route so we can't accidentally leak a row through a less-guarded sibling.
  187. Rules:
  188. - Missing archive or soft-deleted (``deleted_at != None``) → 404.
  189. - Caller with ARCHIVES_READ_ALL or auth disabled (``can_read_all=True``,
  190. ``user`` may be None) → archive returned.
  191. - Caller without ARCHIVES_READ_ALL and ``archive.created_by_id != user.id``
  192. → 404, deliberately NOT 403. 403 leaks "this id exists but you can't
  193. see it" — enumeration-friendly. 404 is indistinguishable from a
  194. nonexistent id. Pre-GHSA fix the caller saw 200 here (the PoC vector).
  195. - Ownerless rows (``created_by_id is None``) require ALL — fail-closed
  196. per ``feedback_no_fail_open_in_auth``.
  197. - An archive neither on a printer in ``printer_scope`` nor printed on
  198. one (any of its runs) → 404 (#1727, archive redesign).
  199. """
  200. if not archive or archive.deleted_at is not None:
  201. raise HTTPException(404, "Archive not found")
  202. # An archive from a printer the caller can't see is as missing as the
  203. # printer itself (#1727), unless one of its prints ran on one of theirs:
  204. # plates of one archive print on several printers. Archives with no
  205. # printer stay governed by ownership alone.
  206. if not printer_scope.allows(archive.printer_id):
  207. async with database.async_session() as db:
  208. if not await printed_in_scope(db, archive, printer_scope):
  209. raise HTTPException(404, "Archive not found")
  210. if can_read_all:
  211. return archive
  212. # Auth enabled, caller has _OWN only.
  213. if user is None:
  214. # Defensive: should be unreachable (RequirePermissionIfAuthEnabled
  215. # would have 401'd already), but never trust user identity to be
  216. # non-None when can_read_all is False.
  217. raise HTTPException(404, "Archive not found")
  218. if archive.created_by_id is None or archive.created_by_id != user.id:
  219. raise HTTPException(404, "Archive not found")
  220. return archive
  221. async def _ensure_whole_archive(archive: PrintArchive, printer_scope: PrinterScope) -> None:
  222. """For a change to the whole archive (its file, its video, the archive
  223. itself): 404 when the caller can't see it, 403 when it also printed on
  224. printers outside their scope (``ensure_whole_archive_in_scope``)."""
  225. if printer_scope.is_unrestricted:
  226. return
  227. async with database.async_session() as db:
  228. if not await printed_in_scope(db, archive, printer_scope):
  229. raise HTTPException(404, "Archive not found")
  230. await ensure_whole_archive_in_scope(db, archive, printer_scope)
  231. async def _media_hidden(archive: PrintArchive, printer_scope: PrinterScope, photo: str | None = None) -> bool:
  232. """Whether the archive's video (or ``photo``) is of a print on a printer
  233. outside the caller's scope: a camera's images go no further than the
  234. printer does (#1727, archive redesign)."""
  235. if printer_scope.is_unrestricted:
  236. return False
  237. async with database.async_session() as db:
  238. view = await scoped_view(db, archive, printer_scope)
  239. if view is None:
  240. return False
  241. if photo is not None:
  242. return photo in view.hidden_photos
  243. return view.hidden_timelapse is not None and view.hidden_timelapse == archive.timelapse_path
  244. async def _visible_photos(archive: PrintArchive, printer_scope: PrinterScope) -> list[str] | None:
  245. """The archive's photos the caller may see (``_media_hidden``)."""
  246. if printer_scope.is_unrestricted or not archive.photos:
  247. return archive.photos
  248. async with database.async_session() as db:
  249. view = await scoped_view(db, archive, printer_scope)
  250. if view is None:
  251. return archive.photos
  252. return [p for p in archive.photos if p not in view.hidden_photos] or None
  253. async def _ensure_media_visible(archive: PrintArchive, printer_scope: PrinterScope, photo: str | None = None) -> None:
  254. """404 for media ``_media_hidden`` hides, as for media that isn't there."""
  255. if await _media_hidden(archive, printer_scope, photo):
  256. raise HTTPException(404, "Photo not found" if photo is not None else "Timelapse not found")
  257. def _validate_user_filter_permission(current_user: User | ApiKeyActor | None, created_by_id: int | None):
  258. """Raise 403 if created_by_id filter is used without stats:filter_by_user permission."""
  259. if created_by_id is None or current_user is None:
  260. return
  261. if current_user.is_admin:
  262. return
  263. if not current_user.has_permission(Permission.STATS_FILTER_BY_USER.value):
  264. raise HTTPException(status_code=403, detail="Permission stats:filter_by_user required")
  265. def _apply_run_user_filter(conditions: list, created_by_id: int | None):
  266. """Append created_by_id filter scoped to PrintLogEntry rows."""
  267. from backend.app.models.print_log import PrintLogEntry
  268. if created_by_id is not None:
  269. if created_by_id == -1:
  270. conditions.append(PrintLogEntry.created_by_id.is_(None))
  271. else:
  272. conditions.append(PrintLogEntry.created_by_id == created_by_id)
  273. def compute_time_accuracy(archive: PrintArchive, run_aggregate: dict | None = None) -> dict:
  274. """Compute actual print time and accuracy for an archive.
  275. Returns dict with actual_time_seconds and time_accuracy.
  276. time_accuracy = (estimated / actual) * 100
  277. - 100% = perfect estimate
  278. - >100% = print was faster than estimated
  279. - <100% = print took longer than estimated
  280. When ``run_aggregate`` indicates the archive has more than one logged
  281. run (multi-plate file printed plate-by-plate, or reprints), both
  282. fields are suppressed: ``archive.started_at / completed_at`` reflect
  283. the LATEST run only, while ``archive.print_time_seconds`` is the
  284. whole-file estimate (post-#1593 the parser sums across plates), so
  285. comparing the two describes different scopes. The card-rendering
  286. frontend falls through to ``archive.print_time_seconds`` for the
  287. time display and hides the badge when ``time_accuracy`` is null —
  288. that's the desired "show estimate, no badge" presentation for
  289. multi-run archives (#1608). Single-run archives keep the original
  290. badge behaviour verbatim.
  291. """
  292. result: dict[str, int | float | None] = {"actual_time_seconds": None, "time_accuracy": None}
  293. # Multi-run archives: the per-run actual (started_at..completed_at on
  294. # the archive row) is incommensurable with the whole-file estimate.
  295. # Both fields are cleared so the card shows estimate + no badge.
  296. if run_aggregate and (run_aggregate.get("run_count") or 0) > 1:
  297. return result
  298. # A run whose times were not measured (#3310): its end is the slicer's
  299. # estimate or the reconnect. The card shows the estimate and no badge,
  300. # as for multi-run archives.
  301. if run_aggregate and run_aggregate.get("unmeasured_run_count"):
  302. return result
  303. if archive.started_at and archive.completed_at and archive.status == "completed":
  304. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  305. if actual_seconds > 0:
  306. result["actual_time_seconds"] = actual_seconds
  307. if archive.print_time_seconds and archive.print_time_seconds > 0:
  308. # Calculate accuracy as percentage
  309. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  310. # Sanity check: skip unreasonable values (e.g., manually changed status)
  311. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  312. if 5 <= accuracy <= 500:
  313. result["time_accuracy"] = round(accuracy, 1)
  314. return result
  315. async def _load_run_aggregates(
  316. db: AsyncSession, archive_ids: list[int], printer_scope: PrinterScope | None = None, printer_id: int | None = None
  317. ) -> dict[int, dict]:
  318. """Batch-load per-archive run aggregates from PrintLogEntry.
  319. Returns ``{archive_id: {run_count, last_run_at, total_filament_actual_grams,
  320. successful_run_count, failed_run_count, unmeasured_run_count, latest_run_id}}``. Archives with no logged runs are
  321. absent from the map; callers should treat that as zero/none.
  322. With ``printer_scope``, only the runs on its printers count: a caller
  323. limited to some printers sees only their prints (archive redesign). With
  324. ``printer_id`` (the list's printer filter) the counts are of the prints
  325. on that printer; ``latest_run_id`` stays the archive's latest.
  326. """
  327. from backend.app.models.print_log import PrintLogEntry
  328. if not archive_ids:
  329. return {}
  330. rows = await db.execute(
  331. select(
  332. PrintLogEntry.archive_id,
  333. func.count(PrintLogEntry.id).label("run_count"),
  334. func.max(PrintLogEntry.started_at).label("last_run_at"),
  335. func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0).label("total_filament"),
  336. func.sum(case((PrintLogEntry.status == "completed", 1), else_=0)).label("successful"),
  337. func.sum(case((PrintLogEntry.status.in_(("failed", "aborted")), 1), else_=0)).label("failed"),
  338. func.sum(case((PrintLogEntry.duration_unmeasured.is_(True), 1), else_=0)).label("estimated"),
  339. )
  340. .where(
  341. PrintLogEntry.archive_id.in_(archive_ids),
  342. *(
  343. [clause]
  344. if printer_scope is not None and (clause := printer_scope.where(PrintLogEntry.printer_id)) is not None
  345. else []
  346. ),
  347. *([PrintLogEntry.printer_id == printer_id] if printer_id is not None else []),
  348. )
  349. .group_by(PrintLogEntry.archive_id)
  350. )
  351. aggregates: dict[int, dict] = {}
  352. for archive_id, run_count, last_run_at, total_filament, successful, failed, estimated in rows.all():
  353. aggregates[archive_id] = {
  354. "run_count": int(run_count or 0),
  355. "last_run_at": last_run_at,
  356. "total_filament_actual_grams": float(total_filament) if total_filament else None,
  357. "successful_run_count": int(successful or 0),
  358. "failed_run_count": int(failed or 0),
  359. "unmeasured_run_count": int(estimated or 0),
  360. }
  361. # The latest print of each (by start), which the archive shows: a print
  362. # running now included, as the archive shows it while it runs.
  363. scope = printer_scope.where(PrintLogEntry.printer_id) if printer_scope is not None else None
  364. ranked = (
  365. select(
  366. PrintLogEntry.archive_id,
  367. PrintLogEntry.id,
  368. func.row_number()
  369. .over(
  370. partition_by=PrintLogEntry.archive_id,
  371. order_by=(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc()),
  372. )
  373. .label("rn"),
  374. )
  375. .where(PrintLogEntry.archive_id.in_(archive_ids), *([scope] if scope is not None else []))
  376. .subquery()
  377. )
  378. latest = await db.execute(
  379. select(ranked.c.archive_id, ranked.c.id).where(ranked.c.rn == 1).execution_options(**{INCLUDE_OPEN_RUNS: True})
  380. )
  381. for archive_id, run_id in latest.all():
  382. aggregates.setdefault(archive_id, {})["latest_run_id"] = run_id
  383. return aggregates
  384. # What PATCH may change of an archive printed on printers outside the
  385. # caller's scope: the file's own notes, tags, favourite and project.
  386. _FILE_FIELDS = frozenset({"tags", "notes", "is_favorite", "project_id"})
  387. # What PATCH with a run_id may change: one run's outcome.
  388. _RUN_OUTCOME_FIELDS = frozenset({"user_verdict", "failure_reason", "status"})
  389. def _with_run_outcome(data: dict, run: PrintLogEntry) -> dict:
  390. """An archive response showing one of its runs: that print's printer,
  391. outcome, times, plate and verdict instead of the latest run's."""
  392. data.update(
  393. {
  394. "run_id": run.id,
  395. "printer_id": run.printer_id if run.printer_id is not None else data["printer_id"],
  396. "status": run.status,
  397. "started_at": run.started_at,
  398. "completed_at": run.completed_at,
  399. "plate_id": run.plate_id if run.plate_id is not None else data["plate_id"],
  400. "failure_reason": run.failure_reason,
  401. "user_verdict": run.user_verdict,
  402. "user_verdict_source": run.user_verdict_source,
  403. "user_verdict_at": run.user_verdict_at,
  404. # A run logged before runs carried the opt-in asks as its archive.
  405. "confirm_requested": bool(run.confirm_requested)
  406. if run.confirm_requested is not None
  407. else data["confirm_requested"],
  408. }
  409. )
  410. # Its own video and finish photos, once it keeps them; one logged before
  411. # shares the archive's.
  412. if owns_media(run):
  413. data["timelapse_path"] = run.timelapse_path
  414. if run.photos is not None:
  415. data["photos"] = run.photos or None
  416. return data
  417. def _scoped(data: dict, view: ScopedView | None) -> dict:
  418. """An archive response as a caller limited to some printers sees it
  419. (#1727, archive redesign): their latest print of it when the archive's
  420. latest is on a printer outside their scope, and without the video and
  421. finish photos of prints outside it."""
  422. if view is None:
  423. return data
  424. if view.run is not None:
  425. _with_run_outcome(data, view.run)
  426. # The archive's times and its energy and wear are of its latest and
  427. # first prints, maybe on a printer outside the scope: the badge reads as
  428. # for any archive printed more than once, and the figures are the shown
  429. # print's own.
  430. data["actual_time_seconds"] = data["time_accuracy"] = None
  431. for name in ("energy_kwh", "energy_cost", "wear_cost"):
  432. data[name] = getattr(view.shown, name) if view.shown is not None else None
  433. if view.hidden_timelapse is not None and data["timelapse_path"] == view.hidden_timelapse:
  434. data["timelapse_path"] = None
  435. if data["photos"]:
  436. data["photos"] = [p for p in data["photos"] if p not in view.hidden_photos] or None
  437. return data
  438. def archive_to_response(
  439. archive: PrintArchive,
  440. duplicates: list[dict] | None = None,
  441. duplicate_count: int = 0,
  442. duplicate_sequence: int = 0,
  443. original_archive_id: int | None = None,
  444. run_aggregate: dict | None = None,
  445. ) -> dict:
  446. """Convert archive model to response dict with computed fields."""
  447. data = {
  448. "id": archive.id,
  449. "printer_id": archive.printer_id,
  450. "project_id": archive.project_id,
  451. "project_name": archive.project.name if archive.project else None,
  452. "filename": archive.filename,
  453. "file_path": archive.file_path,
  454. "file_size": archive.file_size,
  455. "content_hash": archive.content_hash,
  456. "thumbnail_path": archive.thumbnail_path,
  457. "timelapse_path": archive.timelapse_path,
  458. "source_3mf_path": archive.source_3mf_path,
  459. "f3d_path": archive.f3d_path,
  460. "duplicates": duplicates,
  461. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  462. "duplicate_sequence": duplicate_sequence,
  463. "original_archive_id": original_archive_id,
  464. "print_name": archive.print_name,
  465. "plate_id": archive.plate_id,
  466. "print_time_seconds": archive.print_time_seconds,
  467. "filament_used_grams": archive.filament_used_grams,
  468. "filament_type": archive.filament_type,
  469. "filament_color": archive.filament_color,
  470. "layer_height": archive.layer_height,
  471. "total_layers": archive.total_layers,
  472. "nozzle_diameter": archive.nozzle_diameter,
  473. "bed_temperature": archive.bed_temperature,
  474. "bed_type": archive.bed_type,
  475. "nozzle_temperature": archive.nozzle_temperature,
  476. "sliced_for_model": archive.sliced_for_model,
  477. "status": archive.status,
  478. "started_at": archive.started_at,
  479. "completed_at": archive.completed_at,
  480. "extra_data": archive.extra_data,
  481. "makerworld_url": archive.makerworld_url,
  482. "designer": archive.designer,
  483. "external_url": archive.external_url,
  484. "is_favorite": archive.is_favorite,
  485. "tags": archive.tags,
  486. "notes": archive.notes,
  487. "cost": archive.cost,
  488. "photos": archive.photos,
  489. "failure_reason": archive.failure_reason,
  490. # Post-print outcome confirmation (#1898). confirm_token stays
  491. # server-side — it is a capability and never belongs in a response.
  492. "user_verdict": archive.user_verdict,
  493. "user_verdict_source": archive.user_verdict_source,
  494. "user_verdict_at": archive.user_verdict_at,
  495. # bool() because the column is nullable to match the migration; the
  496. # response contract stays a strict bool either way.
  497. "confirm_requested": bool(archive.confirm_requested),
  498. "quantity": archive.quantity,
  499. "energy_kwh": archive.energy_kwh,
  500. "energy_cost": archive.energy_cost,
  501. "wear_cost": archive.wear_cost,
  502. "created_at": archive.created_at,
  503. # User tracking (Issue #206)
  504. "created_by_id": archive.created_by_id,
  505. "created_by_username": archive.created_by.username if archive.created_by else None,
  506. }
  507. # Add computed time accuracy fields. ``run_aggregate`` lets
  508. # ``compute_time_accuracy`` suppress the badge for multi-run archives
  509. # where the per-run actual / whole-file estimate scopes don't match
  510. # (#1608).
  511. accuracy_data = compute_time_accuracy(archive, run_aggregate)
  512. data.update(accuracy_data)
  513. if run_aggregate:
  514. data["run_count"] = run_aggregate.get("run_count", 0)
  515. data["last_run_at"] = run_aggregate.get("last_run_at")
  516. data["total_filament_actual_grams"] = run_aggregate.get("total_filament_actual_grams")
  517. data["successful_run_count"] = run_aggregate.get("successful_run_count", 0)
  518. data["failed_run_count"] = run_aggregate.get("failed_run_count", 0)
  519. data["latest_run_id"] = run_aggregate.get("latest_run_id")
  520. return data
  521. @router.get("/", response_model=list[ArchiveResponse])
  522. async def list_archives(
  523. printer_id: int | None = None,
  524. project_id: int | None = None,
  525. date_from: date | None = Query(None),
  526. date_to: date | None = Query(None),
  527. tz: str | None = Query(
  528. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  529. ),
  530. limit: int = 50,
  531. offset: int = 0,
  532. db: AsyncSession = Depends(get_db, scope="function"),
  533. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  534. require_ownership_permission(
  535. Permission.ARCHIVES_READ_ALL,
  536. Permission.ARCHIVES_READ_OWN,
  537. )
  538. ),
  539. printer_scope: PrinterScope = RequestPrinterScope,
  540. ):
  541. """List archived prints."""
  542. user, can_read_all = auth_result
  543. visible_to_user_id = user.id if (user is not None and not can_read_all) else None
  544. service = ArchiveService(db)
  545. archives = await service.list_archives(
  546. printer_id=printer_id,
  547. project_id=project_id,
  548. date_from=date_from,
  549. date_to=date_to,
  550. limit=limit,
  551. offset=offset,
  552. visible_to_user_id=visible_to_user_id,
  553. printer_scope=printer_scope,
  554. day_zone=day_zone(tz),
  555. )
  556. # Get sets of duplicate hashes and duplicate (name, hash) pairs (efficient single queries),
  557. # counted among the archives this caller may see, as the duplicates view lists them.
  558. visible = _visible_archive_clauses(user, can_read_all, printer_scope)
  559. duplicate_hashes, duplicate_name_hash_pairs = await service.get_duplicate_hashes_and_names(visible)
  560. # Batch-load duplicate groups once for the current page keys.
  561. duplicate_hashes_in_page = {
  562. a.content_hash for a in archives if a.content_hash and a.content_hash in duplicate_hashes
  563. }
  564. duplicate_name_hash_keys_in_page = {
  565. (a.print_name.lower(), a.content_hash)
  566. for a in archives
  567. if a.print_name and a.content_hash and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  568. }
  569. duplicate_meta_by_archive_id: dict[int, tuple[int, int, int]] = {}
  570. if duplicate_hashes_in_page or duplicate_name_hash_keys_in_page:
  571. duplicate_group_conditions = []
  572. if duplicate_hashes_in_page:
  573. duplicate_group_conditions.append(PrintArchive.content_hash.in_(duplicate_hashes_in_page))
  574. if duplicate_name_hash_keys_in_page:
  575. name_hash_conditions = [
  576. and_(func.lower(PrintArchive.print_name) == name, PrintArchive.content_hash == hash_)
  577. for name, hash_ in duplicate_name_hash_keys_in_page
  578. ]
  579. duplicate_group_conditions.extend(name_hash_conditions)
  580. duplicate_group_rows = await db.execute(
  581. select(
  582. PrintArchive.id,
  583. PrintArchive.created_at,
  584. PrintArchive.content_hash,
  585. func.lower(PrintArchive.print_name).label("print_name_lower"),
  586. ).where(or_(*duplicate_group_conditions), PrintArchive.deleted_at.is_(None), *visible)
  587. )
  588. duplicate_groups_by_hash: dict[str, list[tuple[int, datetime]]] = defaultdict(list)
  589. duplicate_groups_by_name_hash: dict[tuple[str, str], list[tuple[int, datetime]]] = defaultdict(list)
  590. for archive_id, created_at, content_hash, print_name_lower in duplicate_group_rows.all():
  591. if content_hash and content_hash in duplicate_hashes_in_page:
  592. duplicate_groups_by_hash[content_hash].append((archive_id, created_at))
  593. if (
  594. print_name_lower
  595. and content_hash
  596. and (print_name_lower, content_hash) in duplicate_name_hash_keys_in_page
  597. ):
  598. duplicate_groups_by_name_hash[(print_name_lower, content_hash)].append((archive_id, created_at))
  599. for group in duplicate_groups_by_hash.values():
  600. if len(group) < 2:
  601. continue
  602. group.sort(key=lambda x: x[1])
  603. original_id = group[0][0]
  604. duplicate_count = len(group) - 1
  605. for sequence, (archive_id, _) in enumerate(group):
  606. duplicate_meta_by_archive_id[archive_id] = (sequence, original_id, duplicate_count)
  607. # Keep hash-based grouping precedence; name/hash groups only fill missing items.
  608. for group in duplicate_groups_by_name_hash.values():
  609. if len(group) < 2:
  610. continue
  611. group.sort(key=lambda x: x[1])
  612. original_id = group[0][0]
  613. duplicate_count = len(group) - 1
  614. for sequence, (archive_id, _) in enumerate(group):
  615. duplicate_meta_by_archive_id.setdefault(archive_id, (sequence, original_id, duplicate_count))
  616. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives], printer_scope, printer_id)
  617. views = await scoped_views(db, archives, printer_scope)
  618. # Build response with duplicate sequence and original archive ID pre-computed
  619. result = []
  620. for a in archives:
  621. has_hash_dup = a.content_hash in duplicate_hashes if a.content_hash else False
  622. has_name_dup = (
  623. bool(a.print_name and a.content_hash)
  624. and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  625. )
  626. has_duplicate = has_hash_dup or has_name_dup
  627. # Pre-compute duplicate sequence and original archive ID
  628. duplicate_sequence = 0
  629. original_archive_id: int | None = None
  630. duplicate_count = 1 if has_duplicate else 0
  631. if has_duplicate and a.id in duplicate_meta_by_archive_id:
  632. duplicate_sequence, original_archive_id, duplicate_count = duplicate_meta_by_archive_id[a.id]
  633. result.append(
  634. _scoped(
  635. archive_to_response(
  636. a,
  637. duplicate_count=duplicate_count,
  638. duplicate_sequence=duplicate_sequence,
  639. original_archive_id=original_archive_id,
  640. run_aggregate=run_aggregates.get(a.id),
  641. ),
  642. views.get(a.id),
  643. )
  644. )
  645. return result
  646. @router.get("/merge-count")
  647. async def count_archive_merge_groups(
  648. db: AsyncSession = Depends(get_db, scope="function"),
  649. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL, Permission.ARCHIVES_DELETE_ALL),
  650. printer_scope: PrinterScope = RequestPrinterScope,
  651. ):
  652. """How many groups of duplicate archives there are (archive redesign P2):
  653. what the archives page and a restore offer to merge. Cheap: it reads no
  654. files and does not check which group can merge now (``/merge-preview``)."""
  655. from backend.app.services.archive_merge import count_groups, merge_scope_clauses
  656. return {"groups": await count_groups(db, merge_scope_clauses(printer_scope))}
  657. @router.get("/merge-preview")
  658. async def preview_archive_merge(
  659. db: AsyncSession = Depends(get_db, scope="function"),
  660. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL, Permission.ARCHIVES_DELETE_ALL),
  661. printer_scope: PrinterScope = RequestPrinterScope,
  662. ):
  663. """The archives that hold the same file, which "Merge duplicates" makes
  664. one (archive redesign P2): same file, owner and project. The oldest stays;
  665. a group with an archive at work (printing, queued, just printed) is left
  666. out for now (``skipped``)."""
  667. from backend.app.services.archive_merge import find_groups, merge_scope_clauses
  668. def brief(archive: PrintArchive, runs: int) -> dict:
  669. return {
  670. "id": archive.id,
  671. "print_name": archive.print_name,
  672. "filename": archive.filename,
  673. "created_at": archive.created_at,
  674. "run_count": runs,
  675. }
  676. groups = await find_groups(db, merge_scope_clauses(printer_scope))
  677. return {
  678. "groups": [
  679. {
  680. "survivor": brief(g.survivor, g.run_counts.get(g.survivor.id, 0)),
  681. "merged": [brief(a, g.run_counts.get(a.id, 0)) for a in g.merged],
  682. "skipped": g.skipped,
  683. }
  684. for g in groups
  685. ]
  686. }
  687. class ArchiveMergeRequest(BaseModel):
  688. # Each group by its oldest archive, the one that stays; its members are
  689. # taken as they stand when the merge runs.
  690. survivor_ids: list[int] = Field(min_length=1, max_length=500)
  691. @router.post("/merge")
  692. async def merge_archives(
  693. body: ArchiveMergeRequest,
  694. db: AsyncSession = Depends(get_db, scope="function"),
  695. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL, Permission.ARCHIVES_DELETE_ALL),
  696. printer_scope: PrinterScope = RequestPrinterScope,
  697. ):
  698. """Merge the duplicate groups of ``survivor_ids`` (see ``/merge-preview``)."""
  699. from backend.app.core.websocket import ws_manager
  700. from backend.app.services.archive_merge import merge, merge_scope_clauses
  701. merged, skipped = await merge(db, list(dict.fromkeys(body.survivor_ids)), merge_scope_clauses(printer_scope))
  702. for group in merged:
  703. await ws_manager.send_archive_updated({"id": group["survivor_id"]})
  704. return {"merged": merged, "skipped": skipped}
  705. @router.get("/last-per-printer", response_model=list[ArchiveResponse])
  706. async def list_last_archive_per_printer(
  707. db: AsyncSession = Depends(get_db, scope="function"),
  708. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  709. require_ownership_permission(
  710. Permission.ARCHIVES_READ_ALL,
  711. Permission.ARCHIVES_READ_OWN,
  712. )
  713. ),
  714. printer_scope: PrinterScope = RequestPrinterScope,
  715. ):
  716. """The latest print of every printer, for the printer cards: its archive
  717. as that run printed (``run_id``, its outcome and verdict).
  718. By the printer's latest run: plates of one archive on two printers are
  719. each their printer's last print, while the archive names only the one
  720. started last. A printer with no run logged gets its latest archive, as
  721. before runs. One query for the whole Printers page instead of one list
  722. request per card. Leaves out the duplicate detection the full listing
  723. does: the card shows a name and an outcome prompt, and on a farm that scan
  724. ran once per printer on every page load.
  725. """
  726. from sqlalchemy.orm import selectinload
  727. user, can_read_all = auth_result
  728. filters: list[ColumnElement[bool]] = [PrintArchive.deleted_at.is_(None)]
  729. if user is not None and not can_read_all:
  730. filters.append(PrintArchive.created_by_id == user.id)
  731. run_filters: list[ColumnElement[bool]] = [PrintLogEntry.printer_id.isnot(None)]
  732. # Only printers the caller may see (#1727): the run's. Its archive is
  733. # theirs to see by that run (archive redesign).
  734. if (clause := printer_scope.where(PrintLogEntry.printer_id)) is not None:
  735. run_filters.append(clause)
  736. ranked_runs = (
  737. select(
  738. PrintLogEntry.id,
  739. func.row_number()
  740. .over(
  741. partition_by=PrintLogEntry.printer_id,
  742. # As the archives below: a run without a start (logged
  743. # without one) by when it was logged.
  744. order_by=(
  745. func.coalesce(PrintLogEntry.started_at, PrintLogEntry.created_at).desc(),
  746. PrintLogEntry.id.desc(),
  747. ),
  748. )
  749. .label("rn"),
  750. )
  751. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  752. .where(*run_filters, *filters)
  753. .subquery()
  754. )
  755. # The print running now counts: its card shows it, not the one before.
  756. runs = (
  757. await db.scalars(
  758. select(PrintLogEntry)
  759. .where(PrintLogEntry.id.in_(select(ranked_runs.c.id).where(ranked_runs.c.rn == 1)))
  760. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  761. )
  762. ).all()
  763. printers_with_runs = {r.printer_id for r in runs}
  764. archive_filters: list[ColumnElement[bool]] = [*filters, PrintArchive.printer_id.isnot(None)]
  765. if (clause := printer_scope.where(PrintArchive.printer_id)) is not None:
  766. archive_filters.append(clause)
  767. if printers_with_runs:
  768. archive_filters.append(PrintArchive.printer_id.not_in(printers_with_runs))
  769. ranked = (
  770. select(
  771. PrintArchive.id,
  772. func.row_number()
  773. .over(
  774. partition_by=PrintArchive.printer_id,
  775. # A reprint reuses its archive row, moving it to the printer it
  776. # runs on with a fresh started_at, so the latest run start, not
  777. # the row's age, tells which print a printer ran last.
  778. order_by=(
  779. func.coalesce(PrintArchive.started_at, PrintArchive.created_at).desc(),
  780. PrintArchive.id.desc(),
  781. ),
  782. )
  783. .label("rn"),
  784. )
  785. .where(*archive_filters)
  786. .subquery()
  787. )
  788. without_runs = set((await db.scalars(select(ranked.c.id).where(ranked.c.rn == 1))).all())
  789. archive_ids = {r.archive_id for r in runs} | without_runs
  790. result = await db.execute(
  791. select(PrintArchive)
  792. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  793. .where(PrintArchive.id.in_(archive_ids))
  794. )
  795. archives = {a.id: a for a in result.scalars().all()}
  796. run_aggregates = await _load_run_aggregates(db, list(archives), printer_scope)
  797. views = await scoped_views(db, archives.values(), printer_scope)
  798. def response(archive: PrintArchive) -> dict:
  799. return _scoped(
  800. archive_to_response(archive, run_aggregate=run_aggregates.get(archive.id)), views.get(archive.id)
  801. )
  802. cards = [_with_run_outcome(response(archives[r.archive_id]), r) for r in runs if r.archive_id in archives]
  803. cards += [response(archives[i]) for i in without_runs if i in archives]
  804. return sorted(cards, key=lambda card: card["printer_id"])
  805. @router.get("/no-3mf-warning")
  806. async def no_3mf_warning(
  807. db: AsyncSession = Depends(get_db, scope="function"),
  808. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  809. require_ownership_permission(
  810. Permission.ARCHIVES_READ_ALL,
  811. Permission.ARCHIVES_READ_OWN,
  812. )
  813. ),
  814. printer_scope: PrinterScope = RequestPrinterScope,
  815. ):
  816. """Whether to nudge the user about a print that archived without its 3MF,
  817. and why. True iff any archive in the last 30 days was created via the
  818. no-3MF fallback path.
  819. Also returns ``reason``, because the advice differs and the original
  820. single-cause wording sent people the wrong way. Historically the only
  821. known cause was install step 4 ("Store sent files on external storage")
  822. being off in the slicer, so the banner said so unconditionally. On
  823. H2-series, P2S and X2D that advice is actively wrong: the setting is already
  824. on and turning it on again changes nothing, because the printer keeps the
  825. sliced file on internal storage that FTPS does not serve at all (#2780).
  826. ``reason`` is the slug from :mod:`print_storage` when we recorded one,
  827. else None for the original slicer-setting case. When archives disagree the
  828. most specific known reason wins — one printer storing internally is a real
  829. finding worth explaining, and it should not be masked by another printer's
  830. plain missing-file fallback.
  831. Complements the connection-diagnostic ``external_storage`` check, which
  832. only catches the printer-side variant of the setting. On older slicers
  833. where the toggle lives only in BambuStudio, the printer never reports it
  834. and the diagnostic passes — this endpoint surfaces the symptom instead.
  835. Dismissal is handled client-side via localStorage (one-shot): once the
  836. user has been told, no further nudge until they clear browser storage.
  837. The backend stays stateless.
  838. """
  839. user, can_read_all = auth_result
  840. cutoff = datetime.now(timezone.utc) - timedelta(days=30)
  841. conditions = [
  842. PrintArchive.created_at >= cutoff,
  843. PrintArchive.deleted_at.is_(None),
  844. PrintArchive.extra_data.isnot(None),
  845. ]
  846. if user is not None and not can_read_all:
  847. conditions.append(PrintArchive.created_by_id == user.id)
  848. if (scope_clause := archive_scope_clause(printer_scope)) is not None:
  849. conditions.append(scope_clause)
  850. result = await db.execute(select(PrintArchive.extra_data).where(*conditions))
  851. reasons: set[str] = set()
  852. has_fallback = False
  853. for (extra_data,) in result.all():
  854. if not extra_data or not extra_data.get("no_3mf_available"):
  855. continue
  856. has_fallback = True
  857. reason = extra_data.get("no_3mf_reason")
  858. if reason:
  859. reasons.add(reason)
  860. if not has_fallback:
  861. return {"has_fallback": False, "reason": None}
  862. # Most specific first. Archives predating this field carry no reason at
  863. # all, so an install with one H2C and three older printers still gets the
  864. # H2C explanation rather than the generic one.
  865. #
  866. # REASON_FTPS_COOLOFF leads, and it is the only one of these that reports a
  867. # fault rather than a choice: the printer's file service refused a TLS
  868. # handshake, so the sweep never ran and nothing about where the file went
  869. # was ever tested. The other three describe an install working as
  870. # configured, and each ends in something the operator can change. This one
  871. # ends in "your printer is doing something we cannot yet explain", which is
  872. # both the more urgent thing to say and the thing that produces a useful
  873. # report. It also has to outrank them because the banner dismisses one-shot
  874. # into localStorage: a reason ranked below another is not merely deferred,
  875. # it is never shown to that user again (#2780).
  876. #
  877. # Ranking it first cannot mask a permanent cause, because a cool-off row is
  878. # not permanent. The retry #2957 schedules clears the row's markers when it
  879. # lands, so a row still carrying this slug is one where the retry failed too
  880. # -- a printer whose file service is still refusing, days later.
  881. #
  882. # REASON_FTP_TRANSFER_FAILED sits second for the same reasons and one more:
  883. # it is the only slug here whose remedy is a Bambuddy setting rather than a
  884. # slicer one or a card. It ranks below the cool-off because a printer that
  885. # will not complete a TLS handshake is the worse fault of the two, and its
  886. # own retry (#3063) clears the row the same way, so a row still carrying
  887. # this slug is one where three later attempts also ran out of time.
  888. #
  889. # REASON_INTERNAL_HISTORY comes last on purpose, even though it is the
  890. # narrowest: it is the one cause with no remedy at all -- the file was
  891. # already on the printer, in an area port 990 does not serve. The two ahead
  892. # of it each end in something the operator can do, so when an install has
  893. # both, the actionable explanation is the one worth the banner (#1820).
  894. for candidate in (
  895. REASON_FTPS_COOLOFF,
  896. REASON_FTP_TRANSFER_FAILED,
  897. REASON_INTERNAL_STORAGE,
  898. REASON_NO_EXTERNAL_STORAGE,
  899. REASON_INTERNAL_HISTORY,
  900. ):
  901. if candidate in reasons:
  902. return {"has_fallback": True, "reason": candidate}
  903. return {"has_fallback": True, "reason": None}
  904. @router.get("/slim", response_model=list[ArchiveSlim])
  905. async def list_archives_slim(
  906. date_from: date | None = Query(None),
  907. date_to: date | None = Query(None),
  908. tz: str | None = Query(
  909. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  910. ),
  911. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  912. limit: int = Query(default=10000, le=50000),
  913. offset: int = 0,
  914. db: AsyncSession = Depends(get_db, scope="function"),
  915. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  916. require_ownership_permission(
  917. Permission.ARCHIVES_READ_ALL,
  918. Permission.ARCHIVES_READ_OWN,
  919. )
  920. ),
  921. printer_scope: PrinterScope = RequestPrinterScope,
  922. ):
  923. """Per-event listing for stats/dashboard widgets.
  924. Reads from print_log_entries so reprints contribute each run and
  925. orphaned events (archive deleted, log row survived via ON DELETE
  926. SET NULL) still aggregate consistently with Quick Stats. The sliced
  927. print_time_seconds is joined from the archive when available; for
  928. orphan events it is null and downstream widgets fall back to the
  929. measured duration_seconds.
  930. """
  931. from backend.app.models.print_log import PrintLogEntry
  932. current_user, can_read_all = auth_result
  933. _validate_user_filter_permission(current_user, created_by_id)
  934. # Callers without ARCHIVES_READ_ALL can only see their own runs — pin
  935. # the filter unconditionally so a caller-supplied ?created_by_id=
  936. # can't widen the listing past their own scope. The existing
  937. # _validate_user_filter_permission rejects ?created_by_id= without
  938. # STATS_FILTER_BY_USER, so the only way to reach this is owner-self
  939. # filtering anyway, but pinning here is the fail-closed default.
  940. if current_user is not None and not can_read_all:
  941. created_by_id = current_user.id
  942. filters = []
  943. if date_from:
  944. dt_from = local_date_start(date_from, day_zone(tz))
  945. filters.append(PrintLogEntry.created_at >= dt_from)
  946. if date_to:
  947. dt_to = local_date_end(date_to, day_zone(tz))
  948. filters.append(PrintLogEntry.created_at <= dt_to)
  949. _apply_run_user_filter(filters, created_by_id)
  950. if (clause := printer_scope.where(PrintLogEntry.printer_id)) is not None:
  951. filters.append(clause)
  952. query = (
  953. select(
  954. PrintLogEntry.printer_id,
  955. PrintLogEntry.print_name,
  956. PrintArchive.print_time_seconds,
  957. PrintLogEntry.started_at,
  958. PrintLogEntry.completed_at,
  959. PrintLogEntry.duration_seconds,
  960. PrintLogEntry.filament_used_grams,
  961. PrintLogEntry.filament_type,
  962. PrintLogEntry.filament_color,
  963. PrintLogEntry.status,
  964. PrintLogEntry.cost,
  965. PrintLogEntry.energy_kwh,
  966. PrintLogEntry.energy_cost,
  967. PrintLogEntry.wear_cost,
  968. PrintLogEntry.created_at,
  969. )
  970. .outerjoin(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  971. .where(*filters)
  972. .order_by(PrintLogEntry.created_at.desc())
  973. .limit(limit)
  974. .offset(offset)
  975. )
  976. result = await db.execute(query)
  977. rows = result.all()
  978. return [
  979. {
  980. "printer_id": r.printer_id,
  981. "print_name": r.print_name,
  982. "print_time_seconds": r.print_time_seconds,
  983. "actual_time_seconds": (
  984. # Measured elapsed time for every status (#1390): failed /
  985. # cancelled prints still ran for some duration, and Quick
  986. # Stats already counts that. Widgets that fall back to
  987. # print_time_seconds (slicer estimate) for non-completed
  988. # events would diverge from Quick Stats — so expose the
  989. # measured value here unconditionally.
  990. #
  991. # Trust an explicit 0 (reconciled aborts store it deliberately;
  992. # their real end time is unknown) instead of recomputing the
  993. # multi-day disconnect gap from the timestamps (#2592).
  994. r.duration_seconds
  995. if r.duration_seconds is not None
  996. else (
  997. int((r.completed_at - r.started_at).total_seconds())
  998. if r.started_at and r.completed_at and (r.completed_at - r.started_at).total_seconds() > 0
  999. else None
  1000. )
  1001. ),
  1002. "filament_used_grams": r.filament_used_grams,
  1003. "filament_type": r.filament_type,
  1004. "filament_color": r.filament_color,
  1005. "status": r.status,
  1006. "started_at": r.started_at,
  1007. "completed_at": r.completed_at,
  1008. "cost": r.cost,
  1009. "energy_kwh": r.energy_kwh,
  1010. "energy_cost": r.energy_cost,
  1011. "wear_cost": r.wear_cost,
  1012. "quantity": 1,
  1013. "created_at": r.created_at,
  1014. }
  1015. for r in rows
  1016. ]
  1017. @router.get("/prints", response_model=PrintLogResponse)
  1018. async def list_archive_prints(
  1019. date_from: date = Query(...),
  1020. date_to: date = Query(...),
  1021. tz: str | None = Query(
  1022. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  1023. ),
  1024. printer_id: int | None = None,
  1025. limit: int = Query(default=500, ge=1, le=1000),
  1026. offset: int = Query(default=0, ge=0),
  1027. db: AsyncSession = Depends(get_db, scope="function"),
  1028. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1029. require_ownership_permission(
  1030. Permission.ARCHIVES_READ_ALL,
  1031. Permission.ARCHIVES_READ_OWN,
  1032. )
  1033. ),
  1034. printer_scope: PrinterScope = RequestPrinterScope,
  1035. ):
  1036. """The prints of the archives the caller sees that ended in a date range
  1037. (archive redesign P4): the archives calendar. Visibility as the archive
  1038. list: archives they own (or all, with read-all), and of those only the
  1039. prints on their printers. Ordered by id, so a print logged while the
  1040. pages are read lands on the last one instead of shifting the others.
  1041. """
  1042. user, can_read_all = auth_result
  1043. if printer_id is not None and not printer_scope.allows(printer_id):
  1044. return PrintLogResponse(items=[], total=0)
  1045. zone = day_zone(tz)
  1046. ended = func.coalesce(PrintLogEntry.completed_at, PrintLogEntry.created_at)
  1047. visible = select(PrintArchive.id).where(
  1048. PrintArchive.deleted_at.is_(None), *_visible_archive_clauses(user, can_read_all, printer_scope)
  1049. )
  1050. conditions = [
  1051. PrintLogEntry.archive_id.in_(visible),
  1052. ended >= local_date_start(date_from, zone),
  1053. ended <= local_date_end(date_to, zone),
  1054. ]
  1055. if (clause := printer_scope.where(PrintLogEntry.printer_id)) is not None:
  1056. conditions.append(clause)
  1057. if printer_id is not None:
  1058. conditions.append(PrintLogEntry.printer_id == printer_id)
  1059. total = await db.scalar(select(func.count(PrintLogEntry.id)).where(*conditions)) or 0
  1060. rows = await db.scalars(
  1061. select(PrintLogEntry).where(*conditions).order_by(PrintLogEntry.id).offset(offset).limit(limit)
  1062. )
  1063. from backend.app.schemas.print_log import PrintLogEntrySchema
  1064. return PrintLogResponse(items=[PrintLogEntrySchema.model_validate(r) for r in rows.all()], total=total)
  1065. @router.get("/search", response_model=list[ArchiveResponse])
  1066. async def search_archives(
  1067. q: str = Query(..., min_length=2, description="Search query"),
  1068. printer_id: int | None = None,
  1069. project_id: int | None = None,
  1070. status: str | None = None,
  1071. limit: int = 50,
  1072. offset: int = 0,
  1073. db: AsyncSession = Depends(get_db, scope="function"),
  1074. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1075. require_ownership_permission(
  1076. Permission.ARCHIVES_READ_ALL,
  1077. Permission.ARCHIVES_READ_OWN,
  1078. )
  1079. ),
  1080. printer_scope: PrinterScope = RequestPrinterScope,
  1081. ):
  1082. """Full-text search across archives.
  1083. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  1084. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  1085. """
  1086. from sqlalchemy import text
  1087. from sqlalchemy.orm import selectinload
  1088. from backend.app.core.db_dialect import is_sqlite
  1089. user, can_read_all = auth_result
  1090. own_only = user is not None and not can_read_all
  1091. search_term = q.strip()
  1092. # A printer outside the caller's scope finds nothing, as in the list.
  1093. if printer_id is not None and not printer_scope.allows(printer_id):
  1094. return []
  1095. # Build dialect-specific full-text search query
  1096. if is_sqlite():
  1097. # SQLite FTS5: wildcard suffix for partial matches
  1098. if not search_term.endswith("*"):
  1099. search_term = f"{search_term}*"
  1100. fts_query = text("""
  1101. SELECT rowid FROM archive_fts
  1102. WHERE archive_fts MATCH :search_term
  1103. ORDER BY rank
  1104. LIMIT :limit OFFSET :offset
  1105. """)
  1106. else:
  1107. # PostgreSQL: tsvector + plainto_tsquery with prefix matching
  1108. fts_query = text("""
  1109. SELECT id FROM print_archives
  1110. WHERE to_tsvector('simple',
  1111. COALESCE(print_name, '') || ' ' ||
  1112. COALESCE(filename, '') || ' ' ||
  1113. COALESCE(tags, '') || ' ' ||
  1114. COALESCE(notes, '') || ' ' ||
  1115. COALESCE(designer, '') || ' ' ||
  1116. COALESCE(filament_type, '')
  1117. ) @@ to_tsquery('simple', :search_term)
  1118. LIMIT :limit OFFSET :offset
  1119. """)
  1120. # Convert "benchy" to "benchy:*" for prefix matching in tsquery
  1121. search_term = " & ".join(f"{word}:*" for word in search_term.split() if word)
  1122. try:
  1123. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  1124. matched_ids = [row[0] for row in result.fetchall()]
  1125. except Exception as e:
  1126. logger.warning("FTS search failed, falling back to LIKE search: %s", e)
  1127. # Fallback to LIKE search if FTS fails
  1128. like_pattern = f"%{q}%"
  1129. query = (
  1130. select(PrintArchive)
  1131. .options(selectinload(PrintArchive.project))
  1132. .where(
  1133. (
  1134. (PrintArchive.print_name.ilike(like_pattern))
  1135. | (PrintArchive.filename.ilike(like_pattern))
  1136. | (PrintArchive.tags.ilike(like_pattern))
  1137. | (PrintArchive.notes.ilike(like_pattern))
  1138. | (PrintArchive.designer.ilike(like_pattern))
  1139. | (PrintArchive.filament_type.ilike(like_pattern))
  1140. ),
  1141. PrintArchive.deleted_at.is_(None),
  1142. )
  1143. .order_by(PrintArchive.created_at.desc())
  1144. )
  1145. if printer_id:
  1146. query = query.where(printed_on_clause(printer_id))
  1147. if project_id:
  1148. query = query.where(PrintArchive.project_id == project_id)
  1149. if status:
  1150. query = query.where(PrintArchive.status == status)
  1151. if own_only:
  1152. query = query.where(PrintArchive.created_by_id == user.id)
  1153. if (clause := archive_scope_clause(printer_scope)) is not None:
  1154. query = query.where(clause)
  1155. query = query.limit(limit).offset(offset)
  1156. result = await db.execute(query)
  1157. archives = result.scalars().all()
  1158. # Load run aggregates so multi-run archives' time/accuracy badge is
  1159. # suppressed consistently with the main list endpoint (#1608).
  1160. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives], printer_scope, printer_id)
  1161. views = await scoped_views(db, archives, printer_scope)
  1162. return [
  1163. _scoped(archive_to_response(a, run_aggregate=run_aggregates.get(a.id)), views.get(a.id)) for a in archives
  1164. ]
  1165. if not matched_ids:
  1166. return []
  1167. # Fetch full archive records for matched IDs (excluding soft-deleted, #1343)
  1168. query = (
  1169. select(PrintArchive)
  1170. .options(selectinload(PrintArchive.project))
  1171. .where(PrintArchive.id.in_(matched_ids), PrintArchive.deleted_at.is_(None))
  1172. )
  1173. if own_only:
  1174. query = query.where(PrintArchive.created_by_id == user.id)
  1175. if (clause := archive_scope_clause(printer_scope)) is not None:
  1176. query = query.where(clause)
  1177. # Apply additional filters
  1178. if printer_id:
  1179. query = query.where(printed_on_clause(printer_id))
  1180. if project_id:
  1181. query = query.where(PrintArchive.project_id == project_id)
  1182. if status:
  1183. query = query.where(PrintArchive.status == status)
  1184. result = await db.execute(query)
  1185. archives_dict = {a.id: a for a in result.scalars().all()}
  1186. # Preserve FTS ranking order and apply pagination
  1187. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  1188. paginated = ordered_archives[offset : offset + limit]
  1189. # Load run aggregates so multi-run archives' time/accuracy badge is
  1190. # suppressed consistently with the main list endpoint (#1608).
  1191. run_aggregates = await _load_run_aggregates(db, [a.id for a in paginated], printer_scope, printer_id)
  1192. views = await scoped_views(db, paginated, printer_scope)
  1193. return [_scoped(archive_to_response(a, run_aggregate=run_aggregates.get(a.id)), views.get(a.id)) for a in paginated]
  1194. @router.post("/search/rebuild-index")
  1195. async def rebuild_search_index(
  1196. db: AsyncSession = Depends(get_db, scope="function"),
  1197. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1198. ):
  1199. """Rebuild the full-text search index from existing archives.
  1200. Use this if search results seem incomplete or incorrect.
  1201. """
  1202. from sqlalchemy import text
  1203. from backend.app.core.db_dialect import is_sqlite
  1204. try:
  1205. if is_sqlite():
  1206. # SQLite: rebuild FTS5 virtual table
  1207. await db.execute(text("DELETE FROM archive_fts"))
  1208. await db.execute(
  1209. text("""
  1210. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  1211. SELECT id, print_name, filename, tags, notes, designer, filament_type
  1212. FROM print_archives
  1213. """)
  1214. )
  1215. await db.commit()
  1216. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  1217. count = result.scalar() or 0
  1218. else:
  1219. # PostgreSQL: GIN index is auto-maintained, just reindex
  1220. await db.execute(text("REINDEX INDEX idx_archives_fulltext"))
  1221. await db.commit()
  1222. result = await db.execute(text("SELECT COUNT(*) FROM print_archives"))
  1223. count = result.scalar() or 0
  1224. return {"message": f"Search index rebuilt with {count} entries"}
  1225. except Exception as e:
  1226. logger.error("Failed to rebuild search index: %s", e)
  1227. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  1228. @router.get("/analysis/failures")
  1229. async def analyze_failures(
  1230. days: int | None = None,
  1231. date_from: date | None = Query(None),
  1232. date_to: date | None = Query(None),
  1233. tz: str | None = Query(
  1234. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  1235. ),
  1236. printer_id: int | None = None,
  1237. project_id: int | None = None,
  1238. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  1239. db: AsyncSession = Depends(get_db, scope="function"),
  1240. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1241. require_ownership_permission(
  1242. Permission.ARCHIVES_READ_ALL,
  1243. Permission.ARCHIVES_READ_OWN,
  1244. )
  1245. ),
  1246. printer_scope: PrinterScope = RequestPrinterScope,
  1247. ):
  1248. """Analyze failure patterns across prints.
  1249. Returns failure statistics including:
  1250. - Overall failure rate
  1251. - Failures by reason, filament type, printer
  1252. - Time of day distribution
  1253. - Recent failures
  1254. - Weekly trend
  1255. """
  1256. current_user, can_read_all = auth_result
  1257. _validate_user_filter_permission(current_user, created_by_id)
  1258. # Callers without ARCHIVES_READ_ALL are scoped to their own runs (#2).
  1259. if current_user is not None and not can_read_all:
  1260. created_by_id = current_user.id
  1261. from backend.app.services.failure_analysis import FailureAnalysisService
  1262. service = FailureAnalysisService(db)
  1263. return await service.analyze_failures(
  1264. days=days,
  1265. date_from=date_from,
  1266. date_to=date_to,
  1267. printer_id=printer_id,
  1268. project_id=project_id,
  1269. created_by_id=created_by_id,
  1270. printer_scope=printer_scope,
  1271. day_zone=day_zone(tz),
  1272. )
  1273. @router.get("/compare")
  1274. async def compare_archives(
  1275. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  1276. db: AsyncSession = Depends(get_db, scope="function"),
  1277. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1278. require_ownership_permission(
  1279. Permission.ARCHIVES_READ_ALL,
  1280. Permission.ARCHIVES_READ_OWN,
  1281. )
  1282. ),
  1283. printer_scope: PrinterScope = RequestPrinterScope,
  1284. ):
  1285. """Compare multiple archives side by side.
  1286. Compares print settings, filament usage, and print times.
  1287. Also analyzes correlation between settings and success/failure.
  1288. Args:
  1289. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  1290. """
  1291. from backend.app.services.archive_comparison import ArchiveComparisonService
  1292. user, can_read_all = auth_result
  1293. # Parse and validate archive IDs
  1294. try:
  1295. ids = [int(id.strip()) for id in archive_ids.split(",")]
  1296. except ValueError:
  1297. raise HTTPException(400, "Invalid archive IDs format")
  1298. if len(ids) < 2:
  1299. raise HTTPException(400, "At least 2 archives required for comparison")
  1300. if len(ids) > 5:
  1301. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  1302. # Verify the caller is allowed to see every archive in the comparison —
  1303. # one not-owned id in the list would otherwise leak its full detail block.
  1304. # _ensure_archive_visible raises 404 on the first miss (same 404 the
  1305. # single-archive endpoint would return).
  1306. if user is not None and not can_read_all:
  1307. existing = await db.execute(
  1308. select(PrintArchive.id, PrintArchive.created_by_id, PrintArchive.deleted_at).where(PrintArchive.id.in_(ids))
  1309. )
  1310. owners_by_id = {row.id: row for row in existing.all()}
  1311. for archive_id in ids:
  1312. row = owners_by_id.get(archive_id)
  1313. if row is None or row.deleted_at is not None or row.created_by_id != user.id:
  1314. raise HTTPException(404, "Archive not found")
  1315. # Every compared archive must be on a printer the caller can see (#1727).
  1316. # Not one seen by a run only: the comparison shows each archive's latest
  1317. # print as it is, which may be on a printer outside their scope.
  1318. if (scope_clause := printer_scope.where(PrintArchive.printer_id)) is not None:
  1319. seen = await db.scalar(select(func.count(PrintArchive.id)).where(PrintArchive.id.in_(ids), scope_clause))
  1320. if seen != len(set(ids)):
  1321. raise HTTPException(404, "Archive not found")
  1322. service = ArchiveComparisonService(db)
  1323. try:
  1324. return await service.compare_archives(ids)
  1325. except ValueError as e:
  1326. raise HTTPException(400, str(e))
  1327. @router.get("/export")
  1328. async def export_archives(
  1329. format: str = Query("csv", description="Export format: csv or xlsx"),
  1330. fields: str | None = Query(None, description="Comma-separated field names"),
  1331. printer_id: int | None = None,
  1332. project_id: int | None = None,
  1333. status: str | None = None,
  1334. date_from: str | None = Query(None, description="Start date (ISO format)"),
  1335. date_to: str | None = Query(None, description="End date (ISO format)"),
  1336. tz: str | None = Query(
  1337. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  1338. ),
  1339. search: str | None = None,
  1340. db: AsyncSession = Depends(get_db, scope="function"),
  1341. printer_scope: PrinterScope = RequestPrinterScope,
  1342. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1343. require_ownership_permission(
  1344. Permission.ARCHIVES_READ_ALL,
  1345. Permission.ARCHIVES_READ_OWN,
  1346. )
  1347. ),
  1348. ):
  1349. """Export archives to CSV or Excel format.
  1350. Returns a downloadable file with archive data.
  1351. """
  1352. from datetime import datetime
  1353. from fastapi.responses import StreamingResponse
  1354. from backend.app.services.export import ExportService
  1355. user, can_read_all = auth_result
  1356. visible_to_user_id = user.id if (user is not None and not can_read_all) else None
  1357. if format not in ("csv", "xlsx"):
  1358. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  1359. # Parse fields
  1360. field_list = None
  1361. if fields:
  1362. field_list = [f.strip() for f in fields.split(",") if f.strip()]
  1363. if unknown := ExportService.unknown_fields(field_list):
  1364. raise HTTPException(400, f"Unknown export fields: {', '.join(unknown)}")
  1365. # Parse dates
  1366. date_from_dt = None
  1367. date_to_dt = None
  1368. if date_from:
  1369. try:
  1370. # A date on its own is a local calendar day (DB-C12).
  1371. if len(date_from) == 10:
  1372. date_from_dt = to_naive_utc(local_date_start(date.fromisoformat(date_from), day_zone(tz)))
  1373. else:
  1374. date_from_dt = to_naive_utc(datetime.fromisoformat(date_from))
  1375. except (ValueError, OverflowError):
  1376. raise HTTPException(400, "Invalid date_from format")
  1377. if date_to:
  1378. try:
  1379. # A date on its own ends with that day, as every other date filter
  1380. # here reads it; read as midnight it left out the whole day.
  1381. if len(date_to) == 10:
  1382. date_to_dt = to_naive_utc(local_date_end(date.fromisoformat(date_to), day_zone(tz)))
  1383. else:
  1384. date_to_dt = to_naive_utc(datetime.fromisoformat(date_to))
  1385. except (ValueError, OverflowError):
  1386. raise HTTPException(400, "Invalid date_to format")
  1387. service = ExportService(db)
  1388. try:
  1389. file_bytes, filename, content_type = await service.export_archives(
  1390. format=format,
  1391. fields=field_list,
  1392. printer_id=printer_id,
  1393. project_id=project_id,
  1394. status=status,
  1395. date_from=date_from_dt,
  1396. date_to=date_to_dt,
  1397. search=search,
  1398. visible_to_user_id=visible_to_user_id,
  1399. printer_scope=printer_scope,
  1400. )
  1401. except ImportError as e:
  1402. raise HTTPException(500, str(e))
  1403. return StreamingResponse(
  1404. io.BytesIO(file_bytes),
  1405. media_type=content_type,
  1406. headers={"Content-Disposition": build_content_disposition(filename)},
  1407. )
  1408. @router.get("/stats/export")
  1409. async def export_stats(
  1410. format: str = Query("csv", description="Export format: csv or xlsx"),
  1411. days: int = 30,
  1412. printer_id: int | None = None,
  1413. project_id: int | None = None,
  1414. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  1415. db: AsyncSession = Depends(get_db, scope="function"),
  1416. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  1417. printer_scope: PrinterScope = RequestPrinterScope,
  1418. actor: User | ApiKeyActor | None = RequestActor,
  1419. ):
  1420. """Export statistics summary to CSV or Excel format."""
  1421. _validate_user_filter_permission(actor, created_by_id)
  1422. from fastapi.responses import StreamingResponse
  1423. from backend.app.services.export import ExportService
  1424. if format not in ("csv", "xlsx"):
  1425. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  1426. service = ExportService(db)
  1427. try:
  1428. file_bytes, filename, content_type = await service.export_stats(
  1429. format=format,
  1430. days=days,
  1431. printer_id=printer_id,
  1432. project_id=project_id,
  1433. created_by_id=created_by_id,
  1434. printer_scope=printer_scope,
  1435. )
  1436. except ImportError as e:
  1437. raise HTTPException(500, str(e))
  1438. return StreamingResponse(
  1439. io.BytesIO(file_bytes),
  1440. media_type=content_type,
  1441. headers={"Content-Disposition": build_content_disposition(filename)},
  1442. )
  1443. @router.get("/stats", response_model=ArchiveStats)
  1444. async def get_archive_stats(
  1445. date_from: date | None = Query(None, description="Start date (inclusive), YYYY-MM-DD"),
  1446. date_to: date | None = Query(None, description="End date (inclusive), YYYY-MM-DD"),
  1447. tz: str | None = Query(
  1448. None, max_length=64, description="IANA zone the dates are calendar days in; the server's when omitted"
  1449. ),
  1450. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  1451. db: AsyncSession = Depends(get_db, scope="function"),
  1452. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  1453. printer_scope: PrinterScope = RequestPrinterScope,
  1454. actor: User | ApiKeyActor | None = RequestActor,
  1455. ):
  1456. """Get statistics across all archives.
  1457. Stats aggregate over PrintLogEntry (one row per print event), not over
  1458. PrintArchive (one row per file). A reprint contributes a new PrintLogEntry
  1459. so its filament/cost/time/energy add to the totals instead of overwriting
  1460. the source archive's first-run values (#1378).
  1461. """
  1462. from backend.app.models.print_log import PrintLogEntry
  1463. _validate_user_filter_permission(actor, created_by_id)
  1464. # Build date filter conditions scoped to PrintLogEntry (event-time).
  1465. base_conditions = []
  1466. if date_from:
  1467. dt_from = local_date_start(date_from, day_zone(tz))
  1468. base_conditions.append(PrintLogEntry.created_at >= dt_from)
  1469. if date_to:
  1470. dt_to = local_date_end(date_to, day_zone(tz))
  1471. base_conditions.append(PrintLogEntry.created_at <= dt_to)
  1472. _apply_run_user_filter(base_conditions, created_by_id)
  1473. # Only prints on printers the caller may see (#1727)
  1474. if (clause := printer_scope.where(PrintLogEntry.printer_id)) is not None:
  1475. base_conditions.append(clause)
  1476. # Total counts (one row per print event).
  1477. total_result = await db.execute(select(func.count(PrintLogEntry.id)).where(*base_conditions))
  1478. total_prints = total_result.scalar() or 0
  1479. successful_result = await db.execute(
  1480. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status == "completed", *base_conditions)
  1481. )
  1482. successful_prints = successful_result.scalar() or 0
  1483. failed_result = await db.execute(
  1484. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status.in_(("failed", "aborted")), *base_conditions)
  1485. )
  1486. failed_prints = failed_result.scalar() or 0
  1487. # User/system-stopped prints — stopped/cancelled/skipped are distinct from
  1488. # quality failures: the user (or the queue) interrupted them, the printer
  1489. # didn't detect a fault. Bucketed separately so the Success Rate gauge
  1490. # divides by completed + failed only (a cancelled print shouldn't drag
  1491. # the gauge down), while still being visible in the breakdown so they
  1492. # don't silently vanish from Total Prints (#1390).
  1493. cancelled_result = await db.execute(
  1494. select(func.count(PrintLogEntry.id)).where(
  1495. PrintLogEntry.status.in_(("stopped", "cancelled", "skipped")), *base_conditions
  1496. )
  1497. )
  1498. cancelled_prints = cancelled_result.scalar() or 0
  1499. # Total elapsed time — PrintLogEntry stores duration_seconds directly so we
  1500. # can sum it server-side. Rows missing duration fall back to the slicer
  1501. # estimate from the archive (joined for that case only).
  1502. time_rows = await db.execute(
  1503. select(
  1504. PrintLogEntry.duration_seconds,
  1505. PrintLogEntry.started_at,
  1506. PrintLogEntry.completed_at,
  1507. ).where(*base_conditions)
  1508. )
  1509. total_seconds = 0
  1510. for duration_seconds, started_at, completed_at in time_rows.all():
  1511. # Trust an explicitly stored duration, INCLUDING 0: a reconciled abort
  1512. # stores 0 on purpose because its real end time is unknown, and the
  1513. # started_at→completed_at fallback would otherwise bank the whole
  1514. # multi-day disconnect gap as print time (#2592). Only rows with a NULL
  1515. # duration (legacy entries that never recorded one) fall back.
  1516. if duration_seconds is not None:
  1517. total_seconds += duration_seconds
  1518. elif started_at and completed_at:
  1519. elapsed = (completed_at - started_at).total_seconds()
  1520. if elapsed > 0:
  1521. total_seconds += int(elapsed)
  1522. total_time = total_seconds / 3600 # Convert to hours
  1523. filament_result = await db.execute(
  1524. select(func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0)).where(*base_conditions)
  1525. )
  1526. total_filament = filament_result.scalar() or 0
  1527. cost_result = await db.execute(select(func.sum(PrintLogEntry.cost)).where(*base_conditions))
  1528. total_cost = cost_result.scalar() or 0
  1529. wear_result = await db.execute(select(func.sum(PrintLogEntry.wear_cost)).where(*base_conditions))
  1530. total_wear_cost = wear_result.scalar() or 0
  1531. # By filament type (split comma-separated values for multi-material prints)
  1532. filament_type_result = await db.execute(
  1533. select(PrintLogEntry.filament_type).where(PrintLogEntry.filament_type.isnot(None), *base_conditions)
  1534. )
  1535. prints_by_filament: dict[str, int] = {}
  1536. for (filament_types,) in filament_type_result.all():
  1537. for ftype in filament_types.split(","):
  1538. ftype = ftype.strip()
  1539. if ftype:
  1540. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  1541. # By printer
  1542. printer_result = await db.execute(
  1543. select(PrintLogEntry.printer_id, func.count(PrintLogEntry.id))
  1544. .where(*base_conditions)
  1545. .group_by(PrintLogEntry.printer_id)
  1546. )
  1547. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  1548. # Names for printers the client can no longer look up. The breakdowns above
  1549. # key on the id each run recorded, and deleting a printer while keeping its
  1550. # history leaves that id pointing at nothing, so a chart that used to read
  1551. # "Ultron" fell back to "Printer 1" (#2873). Every run also stored the name
  1552. # it printed on, so the last one recorded is what that id was called. The
  1553. # client still prefers a live printer's current name, which keeps a rename
  1554. # showing up straight away.
  1555. last_named_run = (
  1556. select(func.max(PrintLogEntry.id).label("entry_id"))
  1557. .where(
  1558. PrintLogEntry.printer_id.isnot(None),
  1559. PrintLogEntry.printer_name.isnot(None),
  1560. *base_conditions,
  1561. )
  1562. .group_by(PrintLogEntry.printer_id)
  1563. .subquery()
  1564. )
  1565. name_result = await db.execute(
  1566. select(PrintLogEntry.printer_id, PrintLogEntry.printer_name).join(
  1567. last_named_run, PrintLogEntry.id == last_named_run.c.entry_id
  1568. )
  1569. )
  1570. printer_names = {str(printer_id): name for printer_id, name in name_result.all()}
  1571. # Time accuracy — compare each completed run's actual duration to the
  1572. # slicer's estimate on the linked archive. Runs without a linked archive
  1573. # (NULL archive_id) or without an estimate are excluded.
  1574. accuracy_rows = await db.execute(
  1575. select(
  1576. PrintLogEntry.duration_seconds,
  1577. PrintLogEntry.started_at,
  1578. PrintLogEntry.completed_at,
  1579. PrintLogEntry.printer_id,
  1580. PrintArchive.print_time_seconds,
  1581. )
  1582. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  1583. .where(
  1584. PrintLogEntry.status == "completed",
  1585. PrintArchive.print_time_seconds.isnot(None),
  1586. # A run whose times were not measured is no sample (#3310).
  1587. PrintLogEntry.duration_unmeasured.is_not(True),
  1588. *base_conditions,
  1589. )
  1590. )
  1591. # Accuracy is meaningful only when the estimate roughly describes the
  1592. # work the run actually performed. Two shapes produce wildly-off ratios
  1593. # that are pure noise:
  1594. # - multi-plate ``.gcode.3mf`` printed plate-by-plate: each run's
  1595. # actual is one plate, the archive's estimate is the sum across
  1596. # plates (post-#1593 parser fix), so the ratio is roughly N×100%
  1597. # for an N-plate file. Pre-fix this shape was also broken, just
  1598. # less dramatically — the estimate was plate-1-only so the ratio
  1599. # was meaningless rather than N×.
  1600. # - manual interventions / purge waste blowing the actual far past
  1601. # the estimate.
  1602. # Clamp to the [50%, 200%] band so the printer-level average reflects
  1603. # real slicer-vs-reality drift, not multi-plate accounting or one-off
  1604. # outliers. Single-plate archives — the case the metric is actually
  1605. # designed for — stay fully included.
  1606. _ACCURACY_BAND_LO = 50.0
  1607. _ACCURACY_BAND_HI = 200.0
  1608. average_accuracy = None
  1609. accuracy_by_printer: dict[str, float] = {}
  1610. accuracies: list[float] = []
  1611. printer_accuracies: dict[str, list[float]] = {}
  1612. for duration_seconds, started_at, completed_at, run_printer_id, estimate_seconds in accuracy_rows.all():
  1613. actual_seconds = duration_seconds
  1614. if not actual_seconds and started_at and completed_at:
  1615. elapsed = (completed_at - started_at).total_seconds()
  1616. actual_seconds = int(elapsed) if elapsed > 0 else None
  1617. if not actual_seconds or not estimate_seconds:
  1618. continue
  1619. accuracy = (estimate_seconds / actual_seconds) * 100
  1620. if accuracy < _ACCURACY_BAND_LO or accuracy > _ACCURACY_BAND_HI:
  1621. continue
  1622. accuracies.append(accuracy)
  1623. printer_key = str(run_printer_id) if run_printer_id else "unknown"
  1624. printer_accuracies.setdefault(printer_key, []).append(accuracy)
  1625. if accuracies:
  1626. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  1627. for printer_key, accs in printer_accuracies.items():
  1628. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  1629. # Energy totals - check which mode to use
  1630. from backend.app.api.routes.settings import get_setting
  1631. from backend.app.services.energy_price import (
  1632. all_time_cost,
  1633. cost_at_average_price,
  1634. snapshot_cost,
  1635. stored_price,
  1636. )
  1637. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  1638. # The last price known. Not read from Home Assistant here: the snapshot
  1639. # loop refreshes it hourly, and it only prices the energy since then.
  1640. energy_cost_per_kwh = await stored_price(db)
  1641. total_energy_kwh: float = 0.0
  1642. total_energy_cost: float = 0.0
  1643. energy_data_warming_up = False
  1644. if energy_tracking_mode == "total" and not date_from and not date_to:
  1645. # All-time total consumption — read live lifetime counters, costed at
  1646. # the price of each hour the snapshots cover (#1251).
  1647. total_energy_kwh = await _sum_live_plug_totals(db)
  1648. total_energy_cost = await all_time_cost(db, total_energy_kwh, energy_cost_per_kwh)
  1649. elif energy_tracking_mode == "total":
  1650. # Total consumption mode with a date filter (#941): use hourly snapshots
  1651. # to compute per-plug (endpoint - baseline) deltas.
  1652. dt_from = local_date_start(date_from, day_zone(tz)) if date_from else None
  1653. dt_to = local_date_end(date_to, day_zone(tz)) if date_to else None
  1654. total_energy_kwh, energy_data_warming_up = await _sum_snapshot_deltas(db, dt_from=dt_from, dt_to=dt_to)
  1655. costed = await snapshot_cost(db, fallback_price=energy_cost_per_kwh, dt_from=dt_from, dt_to=dt_to)
  1656. total_energy_cost = cost_at_average_price(total_energy_kwh, costed.kwh, costed.cost, energy_cost_per_kwh)
  1657. else:
  1658. # Per-print mode: sum the per-run energy column from PrintLogEntry.
  1659. energy_kwh_result = await db.execute(select(func.sum(PrintLogEntry.energy_kwh)).where(*base_conditions))
  1660. total_energy_kwh = energy_kwh_result.scalar() or 0
  1661. energy_cost_result = await db.execute(select(func.sum(PrintLogEntry.energy_cost)).where(*base_conditions))
  1662. total_energy_cost = energy_cost_result.scalar() or 0
  1663. return ArchiveStats(
  1664. total_prints=total_prints,
  1665. successful_prints=successful_prints,
  1666. failed_prints=failed_prints,
  1667. cancelled_prints=cancelled_prints,
  1668. total_print_time_hours=round(total_time, 1),
  1669. total_filament_grams=round(total_filament, 1),
  1670. total_cost=round(total_cost, 2),
  1671. prints_by_filament_type=prints_by_filament,
  1672. prints_by_printer=prints_by_printer,
  1673. printer_names=printer_names,
  1674. average_time_accuracy=average_accuracy,
  1675. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  1676. total_energy_kwh=round(total_energy_kwh, 3),
  1677. total_energy_cost=round(total_energy_cost, 3),
  1678. total_wear_cost=round(total_wear_cost, 2),
  1679. energy_data_warming_up=energy_data_warming_up,
  1680. )
  1681. async def _sum_live_plug_totals(db: AsyncSession) -> float:
  1682. """Sum the live lifetime counter from every smart plug.
  1683. Used for all-time "total consumption" mode. Only the current value is
  1684. available so this can't be date-filtered — use `_sum_snapshot_deltas` for
  1685. that case.
  1686. """
  1687. from backend.app.api.routes.settings import get_homeassistant_settings
  1688. from backend.app.models.smart_plug import SmartPlug
  1689. from backend.app.services.homeassistant import homeassistant_service
  1690. from backend.app.services.mqtt_relay import mqtt_relay
  1691. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  1692. from backend.app.services.tasmota import tasmota_service
  1693. plugs_result = await db.execute(select(SmartPlug))
  1694. plugs = list(plugs_result.scalars().all())
  1695. ha_settings = await get_homeassistant_settings(db)
  1696. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  1697. total = 0.0
  1698. for plug in plugs:
  1699. if plug.plug_type == "tasmota":
  1700. energy = await tasmota_service.get_energy(plug)
  1701. if energy and energy.get("total") is not None:
  1702. total += energy["total"]
  1703. elif plug.plug_type == "homeassistant":
  1704. energy = await homeassistant_service.get_energy(plug)
  1705. if energy and energy.get("total") is not None:
  1706. total += energy["total"]
  1707. elif plug.plug_type == "mqtt":
  1708. # MQTT plugs only expose today's counter, not lifetime.
  1709. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  1710. if mqtt_data and mqtt_data.energy is not None:
  1711. total += mqtt_data.energy
  1712. elif plug.plug_type == "rest":
  1713. # A REST device that exposes only a lifetime counter (Shelly
  1714. # ``aenergy.total`` via ``rest_energy_total_path``) returns no
  1715. # ``today`` key, so read the lifetime total first, like the
  1716. # Tasmota/HA branches above. ``today`` stays as the fallback for
  1717. # devices that only have a daily counter.
  1718. energy = await rest_smart_plug_service.get_energy(plug)
  1719. if energy:
  1720. value = energy.get("total")
  1721. if value is None:
  1722. value = energy.get("today")
  1723. if value is not None:
  1724. total += value
  1725. return total
  1726. async def _sum_snapshot_deltas(
  1727. db: AsyncSession,
  1728. *,
  1729. dt_from: datetime | None,
  1730. dt_to: datetime | None,
  1731. ) -> tuple[float, bool]:
  1732. """Sum per-plug energy consumption over a date range using hourly snapshots.
  1733. For each plug:
  1734. * baseline = last snapshot at or before `dt_from` (ideal)
  1735. — if missing, fall back to the earliest snapshot ever
  1736. recorded for the plug and flag the result as warming up.
  1737. * endpoint = last snapshot at or before `dt_to` (or most recent overall)
  1738. * delta = max(0, endpoint - baseline) — clamp counter resets to 0.
  1739. Returns (total_kwh, warming_up). `warming_up = True` means at least one plug
  1740. had no baseline before `dt_from` (fresh install or fresh upgrade), so the
  1741. result undercounts the beginning of the range.
  1742. """
  1743. from backend.app.models.smart_plug import SmartPlug
  1744. from backend.app.models.smart_plug_energy_snapshot import SmartPlugEnergySnapshot
  1745. from backend.app.utils.local_time import to_naive_utc
  1746. # ``recorded_at`` is a naive column holding UTC. Binding an aware datetime
  1747. # against it raises DataError on asyncpg (SQLite silently drops the offset),
  1748. # which took the whole date-filtered energy figure down on Postgres.
  1749. dt_from = to_naive_utc(dt_from)
  1750. dt_to = to_naive_utc(dt_to)
  1751. plug_ids_result = await db.execute(select(SmartPlug.id))
  1752. plug_ids = [row[0] for row in plug_ids_result.all()]
  1753. if not plug_ids:
  1754. return 0.0, False
  1755. total = 0.0
  1756. warming_up = False
  1757. for plug_id in plug_ids:
  1758. baseline: float | None = None
  1759. if dt_from is not None:
  1760. baseline_q = await db.execute(
  1761. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1762. .where(
  1763. SmartPlugEnergySnapshot.plug_id == plug_id,
  1764. SmartPlugEnergySnapshot.recorded_at <= dt_from,
  1765. )
  1766. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  1767. .limit(1)
  1768. )
  1769. baseline = baseline_q.scalar()
  1770. if baseline is None:
  1771. # No snapshot before range start — fall back to the earliest
  1772. # snapshot ever recorded. Result undercounts the pre-first-snapshot
  1773. # portion of the range; signal that to the frontend.
  1774. earliest_q = await db.execute(
  1775. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1776. .where(SmartPlugEnergySnapshot.plug_id == plug_id)
  1777. .order_by(SmartPlugEnergySnapshot.recorded_at.asc())
  1778. .limit(1)
  1779. )
  1780. baseline = earliest_q.scalar()
  1781. if baseline is None:
  1782. # No snapshots at all for this plug yet.
  1783. warming_up = True
  1784. continue
  1785. warming_up = True
  1786. endpoint_conditions = [SmartPlugEnergySnapshot.plug_id == plug_id]
  1787. if dt_to is not None:
  1788. endpoint_conditions.append(SmartPlugEnergySnapshot.recorded_at <= dt_to)
  1789. endpoint_q = await db.execute(
  1790. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1791. .where(*endpoint_conditions)
  1792. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  1793. .limit(1)
  1794. )
  1795. endpoint = endpoint_q.scalar()
  1796. if endpoint is None:
  1797. continue
  1798. total += max(0.0, endpoint - baseline)
  1799. return total, warming_up
  1800. @router.get("/tags")
  1801. async def get_all_tags(
  1802. db: AsyncSession = Depends(get_db, scope="function"),
  1803. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1804. require_ownership_permission(
  1805. Permission.ARCHIVES_READ_ALL,
  1806. Permission.ARCHIVES_READ_OWN,
  1807. )
  1808. ),
  1809. printer_scope: PrinterScope = RequestPrinterScope,
  1810. ):
  1811. """List all unique tags with usage counts.
  1812. Returns a list of tags sorted by count (descending), then by name.
  1813. """
  1814. user, can_read_all = auth_result
  1815. # Query all archives with non-null tags
  1816. tag_conditions: list[ColumnElement[bool]] = [PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None)]
  1817. if user is not None and not can_read_all:
  1818. tag_conditions.append(PrintArchive.created_by_id == user.id)
  1819. if (scope_clause := archive_scope_clause(printer_scope)) is not None:
  1820. tag_conditions.append(scope_clause)
  1821. result = await db.execute(select(PrintArchive.tags).where(*tag_conditions))
  1822. all_tags_rows = result.all()
  1823. # Count occurrences of each tag
  1824. tag_counts: dict[str, int] = {}
  1825. for (tags_str,) in all_tags_rows:
  1826. if tags_str:
  1827. for tag in tags_str.split(","):
  1828. tag = tag.strip()
  1829. if tag:
  1830. tag_counts[tag] = tag_counts.get(tag, 0) + 1
  1831. # Convert to list and sort by count (desc), then name (asc)
  1832. tags_list = [{"name": name, "count": count} for name, count in tag_counts.items()]
  1833. tags_list.sort(key=lambda x: (-x["count"], x["name"].lower()))
  1834. return tags_list
  1835. @router.put("/tags/{tag_name}")
  1836. async def rename_tag(
  1837. tag_name: str,
  1838. request: Request,
  1839. db: AsyncSession = Depends(get_db, scope="function"),
  1840. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1841. printer_scope: PrinterScope = RequestPrinterScope,
  1842. ):
  1843. """Rename a tag across all archives.
  1844. Request body should contain {"new_name": "new tag name"}.
  1845. Returns the count of affected archives.
  1846. """
  1847. body = await request.json()
  1848. new_name = body.get("new_name", "").strip()
  1849. if not new_name:
  1850. raise HTTPException(400, "new_name is required")
  1851. if new_name == tag_name:
  1852. return {"affected": 0}
  1853. # Find all archives containing the old tag
  1854. result = await db.execute(
  1855. select(PrintArchive).where(
  1856. PrintArchive.tags.isnot(None),
  1857. PrintArchive.deleted_at.is_(None),
  1858. *_visible_archive_clauses(None, True, printer_scope),
  1859. )
  1860. )
  1861. archives = list(result.scalars().all())
  1862. affected = 0
  1863. for archive in archives:
  1864. if not archive.tags:
  1865. continue
  1866. tags = [t.strip() for t in archive.tags.split(",")]
  1867. if tag_name in tags:
  1868. # Replace old tag with new tag
  1869. new_tags = [new_name if t == tag_name else t for t in tags]
  1870. # Remove duplicates while preserving order
  1871. seen = set()
  1872. unique_tags = []
  1873. for t in new_tags:
  1874. if t not in seen:
  1875. seen.add(t)
  1876. unique_tags.append(t)
  1877. archive.tags = ", ".join(unique_tags)
  1878. affected += 1
  1879. await db.commit()
  1880. return {"affected": affected}
  1881. @router.delete("/tags/{tag_name}")
  1882. async def delete_tag(
  1883. tag_name: str,
  1884. db: AsyncSession = Depends(get_db, scope="function"),
  1885. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1886. printer_scope: PrinterScope = RequestPrinterScope,
  1887. ):
  1888. """Delete a tag from all archives.
  1889. Returns the count of affected archives.
  1890. """
  1891. # Find all archives containing the tag
  1892. result = await db.execute(
  1893. select(PrintArchive).where(
  1894. PrintArchive.tags.isnot(None),
  1895. PrintArchive.deleted_at.is_(None),
  1896. *_visible_archive_clauses(None, True, printer_scope),
  1897. )
  1898. )
  1899. archives = list(result.scalars().all())
  1900. affected = 0
  1901. for archive in archives:
  1902. if not archive.tags:
  1903. continue
  1904. tags = [t.strip() for t in archive.tags.split(",")]
  1905. if tag_name in tags:
  1906. # Remove the tag
  1907. new_tags = [t for t in tags if t != tag_name]
  1908. archive.tags = ", ".join(new_tags) if new_tags else None
  1909. affected += 1
  1910. await db.commit()
  1911. return {"affected": affected}
  1912. @router.get("/{archive_id}", response_model=ArchiveResponse)
  1913. async def get_archive(
  1914. archive_id: int,
  1915. db: AsyncSession = Depends(get_db, scope="function"),
  1916. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1917. require_ownership_permission(
  1918. Permission.ARCHIVES_READ_ALL,
  1919. Permission.ARCHIVES_READ_OWN,
  1920. )
  1921. ),
  1922. printer_scope: PrinterScope = RequestPrinterScope,
  1923. run_id: int | None = Query(None, description="Show this run's outcome instead of the latest run's"),
  1924. ):
  1925. """Get a specific archive. With ``run_id``, as that run of it printed."""
  1926. from backend.app.services.print_confirmation import run_of_archive
  1927. user, can_read_all = auth_result
  1928. service = ArchiveService(db)
  1929. found = await service.get_archive(archive_id)
  1930. if found is None or found.deleted_at is not None:
  1931. # Merged into another archive (archive redesign P2): that one, as a
  1932. # link or bookmark to the merged archive meant.
  1933. from backend.app.services.archive_merge import resolve_alias
  1934. if (into := await resolve_alias(db, archive_id)) is not None:
  1935. found = await service.get_archive(into)
  1936. archive = await _ensure_archive_visible(found, user, can_read_all, printer_scope)
  1937. run = await run_of_archive(db, archive.id, run_id) if run_id is not None else None
  1938. if run_id is not None and (run is None or not printer_scope.allows(run.printer_id)):
  1939. raise HTTPException(404, "Run not found")
  1940. # Find duplicates
  1941. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1942. duplicates = await service.find_duplicates(
  1943. archive_id=archive.id,
  1944. content_hash=archive.content_hash,
  1945. print_name=archive.print_name,
  1946. makerworld_model_id=makerworld_id,
  1947. visible=_visible_archive_clauses(user, can_read_all, printer_scope),
  1948. )
  1949. run_aggregates = await _load_run_aggregates(db, [archive.id], printer_scope)
  1950. data = archive_to_response(archive, duplicates, run_aggregate=run_aggregates.get(archive.id))
  1951. view = await scoped_view(db, archive, printer_scope)
  1952. if view is None:
  1953. return _with_run_outcome(data, run) if run is not None else data
  1954. if run is not None:
  1955. # The run asked for, in the caller's scope (checked above).
  1956. view = replace(view, run=run, shown=run)
  1957. return _scoped(data, view)
  1958. @router.get("/{archive_id}/delete-impact")
  1959. async def get_archive_delete_impact(
  1960. archive_id: int,
  1961. db: AsyncSession = Depends(get_db, scope="function"),
  1962. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1963. require_ownership_permission(
  1964. Permission.ARCHIVES_READ_ALL,
  1965. Permission.ARCHIVES_READ_OWN,
  1966. )
  1967. ),
  1968. printer_scope: PrinterScope = RequestPrinterScope,
  1969. ):
  1970. """Pre-flight for the delete-confirm modal (#1734).
  1971. Returns the number of related queue items the user is about to remove
  1972. AND whether any of them are currently printing (which would block the
  1973. delete with a 409 — surfaced to the modal so it can disable the
  1974. confirm button instead of failing on submit). Cheap, single endpoint —
  1975. not folded into the archive GET response so the much larger list
  1976. endpoint isn't forced to run the same query per row.
  1977. """
  1978. user, can_read_all = auth_result
  1979. service = ArchiveService(db)
  1980. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  1981. from backend.app.services.archive import _count_related_queue_items
  1982. total, printing = await _count_related_queue_items(db, archive.id)
  1983. return {"related_queue_items": total, "currently_printing": printing}
  1984. @router.get("/{archive_id}/runs", response_model=PrintLogResponse)
  1985. async def list_archive_runs(
  1986. archive_id: int,
  1987. db: AsyncSession = Depends(get_db, scope="function"),
  1988. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1989. require_ownership_permission(
  1990. Permission.ARCHIVES_READ_ALL,
  1991. Permission.ARCHIVES_READ_OWN,
  1992. )
  1993. ),
  1994. printer_scope: PrinterScope = RequestPrinterScope,
  1995. ):
  1996. """List PrintLogEntry rows for this archive — one per print event.
  1997. Newest first. Drives the per-archive "Print Log" view (#1378).
  1998. """
  1999. from backend.app.models.print_log import PrintLogEntry
  2000. from backend.app.schemas.print_log import PrintLogEntrySchema
  2001. user, can_read_all = auth_result
  2002. archive = await _ensure_archive_visible(await db.get(PrintArchive, archive_id), user, can_read_all, printer_scope)
  2003. # Only the prints on the caller's printers (#1727), as the print log.
  2004. scope_clause = printer_scope.where(PrintLogEntry.printer_id)
  2005. rows = await db.execute(
  2006. select(PrintLogEntry)
  2007. .where(PrintLogEntry.archive_id == archive_id, *([scope_clause] if scope_clause is not None else []))
  2008. .order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc())
  2009. )
  2010. entries = list(rows.scalars().all())
  2011. items = [PrintLogEntrySchema.model_validate(e, from_attributes=True) for e in entries]
  2012. # A print's photos as the archive's photo route serves them: one removed
  2013. # from the archive is gone, whatever a run still lists.
  2014. archive_photos = set(archive.photos or [])
  2015. for item in items:
  2016. if item.photos is not None:
  2017. item.photos = [p for p in item.photos if p in archive_photos] or None
  2018. return PrintLogResponse(items=items, total=len(items))
  2019. @router.get("/{archive_id}/runs/{run_id}/timelapse")
  2020. async def get_run_timelapse(
  2021. archive_id: int,
  2022. run_id: int,
  2023. db: AsyncSession = Depends(get_db, scope="function"),
  2024. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2025. require_media_token_ownership(
  2026. Permission.ARCHIVES_READ_ALL,
  2027. Permission.ARCHIVES_READ_OWN,
  2028. )
  2029. ),
  2030. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  2031. ):
  2032. """One print's timelapse video (archive redesign): plates of one archive
  2033. each keep their own, while the archive's timelapse route serves only the
  2034. latest print's. 404 for a print on a printer outside the caller's scope.
  2035. """
  2036. from backend.app.models.print_log import PrintLogEntry
  2037. user, can_read_all = auth_result
  2038. archive = await _ensure_archive_visible(await db.get(PrintArchive, archive_id), user, can_read_all, printer_scope)
  2039. run = await db.get(PrintLogEntry, run_id)
  2040. if run is None or run.archive_id != archive.id or not printer_scope.allows(run.printer_id):
  2041. raise HTTPException(404, "Run not found")
  2042. if not run.timelapse_path:
  2043. raise HTTPException(404, "Timelapse not found")
  2044. base = settings.base_dir.resolve()
  2045. timelapse_path = (settings.base_dir / run.timelapse_path).resolve()
  2046. if not timelapse_path.is_relative_to(base) or not timelapse_path.is_file():
  2047. raise HTTPException(404, "Timelapse file not found")
  2048. mtime = int(timelapse_path.stat().st_mtime)
  2049. suffix = timelapse_path.suffix.lower()
  2050. media_type = {".mp4": "video/mp4", ".avi": "video/x-msvideo", ".mkv": "video/x-matroska"}.get(suffix, "video/mp4")
  2051. ext = suffix if suffix in (".mp4", ".avi", ".mkv") else ".mp4"
  2052. return FileResponse(
  2053. path=timelapse_path,
  2054. media_type=media_type,
  2055. filename=f"{archive.print_name or 'timelapse'}{ext}",
  2056. headers={"Cache-Control": "no-cache, must-revalidate", "ETag": f'"{mtime}"'},
  2057. )
  2058. @router.get("/{archive_id}/similar")
  2059. async def find_similar_archives(
  2060. archive_id: int,
  2061. limit: int = 10,
  2062. db: AsyncSession = Depends(get_db, scope="function"),
  2063. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2064. require_ownership_permission(
  2065. Permission.ARCHIVES_READ_ALL,
  2066. Permission.ARCHIVES_READ_OWN,
  2067. )
  2068. ),
  2069. printer_scope: PrinterScope = RequestPrinterScope,
  2070. ):
  2071. """Find archives with similar settings for comparison.
  2072. Returns archives that match by:
  2073. - Same print name (highest priority)
  2074. - Same file content hash
  2075. - Same filament type
  2076. """
  2077. from backend.app.services.archive_comparison import ArchiveComparisonService
  2078. user, can_read_all = auth_result
  2079. await _ensure_archive_visible(await db.get(PrintArchive, archive_id), user, can_read_all, printer_scope)
  2080. service = ArchiveComparisonService(db)
  2081. try:
  2082. return await service.find_similar_archives(
  2083. archive_id, limit=limit, visible=_visible_archive_clauses(user, can_read_all, printer_scope, by_runs=False)
  2084. )
  2085. except ValueError as e:
  2086. raise HTTPException(404, str(e))
  2087. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  2088. async def update_archive(
  2089. archive_id: int,
  2090. update_data: ArchiveUpdate,
  2091. db: AsyncSession = Depends(get_db, scope="function"),
  2092. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2093. require_ownership_permission(
  2094. Permission.ARCHIVES_UPDATE_ALL,
  2095. Permission.ARCHIVES_UPDATE_OWN,
  2096. )
  2097. ),
  2098. printer_scope: PrinterScope = RequestPrinterScope,
  2099. ):
  2100. """Update archive metadata (tags, notes, cost, filament grams, is_favorite, project_id)."""
  2101. from sqlalchemy.orm import selectinload
  2102. user, can_modify_all = auth_result
  2103. result = await db.execute(
  2104. select(PrintArchive)
  2105. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  2106. .where(PrintArchive.id == archive_id)
  2107. )
  2108. archive = result.scalar_one_or_none()
  2109. if not archive:
  2110. raise HTTPException(404, "Archive not found")
  2111. if not printer_scope.allows(archive.printer_id) and not await printed_in_scope(db, archive, printer_scope):
  2112. raise HTTPException(404, "Archive not found")
  2113. # Ownership check
  2114. if not can_modify_all:
  2115. if archive.created_by_id != user.id:
  2116. raise HTTPException(403, "You can only update your own archives")
  2117. # Read before the writes below: the mirror needs to know whether the run's
  2118. # figure was inherited from this archive or measured on its own (#1820).
  2119. previous_filament_grams = archive.filament_used_grams
  2120. previous_cost = archive.cost
  2121. previous_status = archive.status
  2122. update_payload = update_data.model_dump(exclude_unset=True)
  2123. # Anything but its file's own notes, tags, favourite and project, or one
  2124. # of the caller's runs' outcome (run_id, checked below), is the whole
  2125. # archive's: its outcome, cost and printer are its prints' (archive
  2126. # redesign).
  2127. if update_payload.get("run_id") is None and set(update_payload) - _FILE_FIELDS - {"run_id"}:
  2128. await _ensure_whole_archive(archive, printer_scope)
  2129. # Later runs of the archive are charged from its cost and weight: a caller
  2130. # limited to their own archives sets neither. The one exception is the
  2131. # weight of an archive without its 3MF (#1820), which has none and cannot
  2132. # be printed again.
  2133. if not can_modify_all:
  2134. if "cost" in update_payload:
  2135. raise HTTPException(403, "Only users who can edit all archives can set an archive's cost")
  2136. if "filament_used_grams" in update_payload and update_payload["filament_used_grams"] != previous_filament_grams:
  2137. if previous_filament_grams is not None or archive.file_path:
  2138. raise HTTPException(403, "Only users who can edit all archives can change an archive's filament weight")
  2139. # A new printer must be one the caller may use (as on upload), and both
  2140. # targets must exist. None clears either: a printer-less archive is in
  2141. # every scope, like one uploaded without a printer.
  2142. new_printer_id = update_payload.get("printer_id")
  2143. if new_printer_id is not None and new_printer_id != archive.printer_id:
  2144. printer_scope.ensure(new_printer_id)
  2145. if await db.get(Printer, new_printer_id) is None:
  2146. raise HTTPException(400, "Printer not found")
  2147. new_project_id = update_payload.get("project_id")
  2148. if new_project_id is not None and new_project_id != archive.project_id:
  2149. if await db.get(Project, new_project_id) is None:
  2150. raise HTTPException(400, "Project not found")
  2151. # #1898: how the verdict arrived is recorded with it, never on its own.
  2152. verdict_source = update_payload.pop("user_verdict_source", None)
  2153. verdict_given = "user_verdict" in update_payload
  2154. new_verdict = update_payload.pop("user_verdict", None)
  2155. # The outcome of one run of the archive (a plate printed on its own): that
  2156. # run's, and the archive's only when it is the archive's latest.
  2157. from backend.app.services.print_confirmation import latest_run, record_verdict, run_of_archive
  2158. target_run = None
  2159. run_outcome: dict = {}
  2160. if (run_id := update_payload.pop("run_id", None)) is not None:
  2161. if set(update_payload) - _RUN_OUTCOME_FIELDS:
  2162. raise HTTPException(400, "run_id applies to a run's outcome only: its verdict, status and failure reason")
  2163. target_run = await run_of_archive(db, archive_id, run_id)
  2164. # A run printed on a printer outside the caller's scope is not theirs
  2165. # to judge, as on the print log (#1727).
  2166. if target_run is None or not printer_scope.allows(target_run.printer_id):
  2167. raise HTTPException(404, "Run not found")
  2168. run_outcome = {field: update_payload.pop(field) for field in list(update_payload)}
  2169. for field, value in update_payload.items():
  2170. setattr(archive, field, value)
  2171. # New grams are a new price, unless the caller set the cost as well.
  2172. repriced = False
  2173. if (
  2174. update_payload.get("filament_used_grams")
  2175. and "cost" not in update_payload
  2176. and update_payload["filament_used_grams"] != previous_filament_grams
  2177. and (can_modify_all or archive.cost is None)
  2178. ):
  2179. archive.cost = await _one_print_cost(db, archive, previous_grams=previous_filament_grams)
  2180. repriced = True
  2181. # #1444: Mirror per-run classification fields to the most recent
  2182. # PrintLogEntry for this archive. PrintLogEntry.failure_reason is captured
  2183. # once at print-completion time from archive.failure_reason — which is
  2184. # NULL until the user classifies the failure via the Edit Archive modal.
  2185. # Without this mirror the Failure Analysis widget (which groups by
  2186. # print_log_entries.failure_reason) keeps showing "Unknown" forever.
  2187. # Same desync hits status: flipping it in the modal wouldn't update the
  2188. # entry either. Only the latest entry is touched because that's the run
  2189. # the modal is implicitly showing (archive.failure_reason / status are
  2190. # overwritten on each reprint to reflect the latest run's outcome).
  2191. # filament_used_grams rides along for the same reason (#1820): the filament
  2192. # totals on the Projects page and in the Prometheus metrics sum the LOG
  2193. # ENTRY's grams, not the archive's, so correcting only the archive would fix
  2194. # the card and leave every aggregate reading the old figure -- or, for a
  2195. # print that archived without its 3MF, no figure at all.
  2196. # While the archive is being reprinted its newest entry is the previous
  2197. # run's, whose outcome this edit is not about.
  2198. mirror_fields = {"failure_reason", "status", "filament_used_grams"}
  2199. to_mirror = {k: v for k, v in update_payload.items() if k in mirror_fields}
  2200. if to_mirror and previous_status != "printing":
  2201. from backend.app.models.print_log import PrintLogEntry
  2202. # The latest by its start, the run the archive shows: ids follow the
  2203. # starts too, but plates on two printers can end the other way round.
  2204. latest_entry = await db.scalar(
  2205. select(PrintLogEntry)
  2206. .where(PrintLogEntry.archive_id == archive_id)
  2207. .order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc())
  2208. .limit(1)
  2209. )
  2210. if latest_entry is not None:
  2211. # ...but never over a figure the run measured for itself. A run's
  2212. # grams come from the tracked spool delta when there is one, and
  2213. # only fall back to copying the archive's estimate when there is
  2214. # not (see _compute_run_filament_grams). Overwriting a measurement
  2215. # with a typed estimate would lose the better number; the case this
  2216. # edit exists for -- a print archived with no 3MF -- leaves the run
  2217. # with nothing at all, so it is covered by the None arm.
  2218. if "filament_used_grams" in to_mirror and not (
  2219. latest_entry.filament_used_grams is None or latest_entry.filament_used_grams == previous_filament_grams
  2220. ):
  2221. del to_mirror["filament_used_grams"]
  2222. # The run's cost was inherited with its grams, so it follows them.
  2223. if "filament_used_grams" in to_mirror and repriced:
  2224. to_mirror["cost"] = archive.cost
  2225. for field, value in to_mirror.items():
  2226. setattr(latest_entry, field, value)
  2227. # A cost set by hand reaches the run that had the archive's (statistics,
  2228. # project totals and batch sums read the run's cost).
  2229. if "cost" in update_payload and previous_status != "printing":
  2230. from backend.app.services.print_log import mirror_archive_cost
  2231. await mirror_archive_cost(db, archive, previous_cost)
  2232. if target_run is not None:
  2233. for field, value in run_outcome.items():
  2234. setattr(target_run, field, value)
  2235. # #1898: the verdict lands on its run (the one asked about, else the
  2236. # archive's latest; not while the archive is being reprinted, its latest
  2237. # being the previous print) and retires that run's one-tap token: the links
  2238. # stop changing anything once someone decided, and report the recorded
  2239. # verdict instead. Clearing the verdict drops the provenance but leaves the
  2240. # token spent: it was used.
  2241. if verdict_given:
  2242. verdict_run = target_run
  2243. if verdict_run is None and previous_status != "printing":
  2244. verdict_run = await latest_run(db, archive_id)
  2245. await record_verdict(db, archive, new_verdict, source=verdict_source or "api", run=verdict_run)
  2246. if target_run is not None:
  2247. from backend.app.services.print_log import mirror_latest_run
  2248. await db.flush()
  2249. await mirror_latest_run(db, archive_id)
  2250. await db.commit()
  2251. # Re-fetch with relationships loaded after commit
  2252. result = await db.execute(
  2253. select(PrintArchive)
  2254. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  2255. .where(PrintArchive.id == archive_id)
  2256. )
  2257. archive = result.scalar_one_or_none()
  2258. # Load run aggregate so the time/accuracy badge stays consistent with
  2259. # the list / detail endpoints when the frontend re-renders the card
  2260. # after a PATCH (#1608).
  2261. run_aggregates = await _load_run_aggregates(db, [archive.id], printer_scope) if archive else {}
  2262. data = archive_to_response(archive, run_aggregate=run_aggregates.get(archive.id) if archive else None)
  2263. return _scoped(data, await scoped_view(db, archive, printer_scope)) if archive else data
  2264. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  2265. async def toggle_favorite(
  2266. archive_id: int,
  2267. db: AsyncSession = Depends(get_db, scope="function"),
  2268. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2269. require_ownership_permission(
  2270. Permission.ARCHIVES_UPDATE_ALL,
  2271. Permission.ARCHIVES_UPDATE_OWN,
  2272. )
  2273. ),
  2274. printer_scope: PrinterScope = RequestPrinterScope,
  2275. ):
  2276. """Toggle favorite status for an archive."""
  2277. user, can_modify_all = auth_result
  2278. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2279. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  2280. archive.is_favorite = not archive.is_favorite
  2281. await db.commit()
  2282. await db.refresh(archive)
  2283. view = await scoped_view(db, archive, printer_scope)
  2284. # As the list shows it (its run figures; to a caller limited to some
  2285. # printers, their view of it).
  2286. from sqlalchemy.orm import selectinload
  2287. loaded = await db.scalar(
  2288. select(PrintArchive)
  2289. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  2290. .where(PrintArchive.id == archive_id)
  2291. )
  2292. if loaded is None:
  2293. raise HTTPException(404, "Archive not found")
  2294. run_aggregates = await _load_run_aggregates(db, [archive_id], printer_scope)
  2295. return _scoped(archive_to_response(loaded, run_aggregate=run_aggregates.get(archive_id)), view)
  2296. async def _spoolman_owns_cost(db: AsyncSession) -> bool:
  2297. """True when per-spool pricing lives in Spoolman rather than in our tables.
  2298. Both cost recalculations below rebuild a print's cost from
  2299. ``SpoolUsageHistory``, and fall back to the built-in Filament catalogue or
  2300. the global default rate when there are no rows for it. In Spoolman mode a
  2301. print has rows only since #3407, when Spoolman charges started being
  2302. recorded; for an older print, or one whose charges Spoolman refused, that
  2303. fallback is not a recalculation, it is a downgrade: it would overwrite the
  2304. Spoolman-priced figure ``spoolman_tracking`` recorded at completion with a
  2305. default-rate one, and the per-slot spool resolution it came from is
  2306. transient and cannot be rebuilt here (#2591).
  2307. """
  2308. from backend.app.api.routes.settings import get_setting
  2309. setting = await get_setting(db, "spoolman_enabled")
  2310. return bool(setting) and setting.lower() == "true"
  2311. def _priced_usage_totals():
  2312. """Priced spool usage per archive. A row recorded without a price is left
  2313. out of both sums, so its grams are priced at the default rate instead of
  2314. counting as free filament."""
  2315. priced = SpoolUsageHistory.cost.is_not(None)
  2316. return (
  2317. func.sum(SpoolUsageHistory.cost),
  2318. func.sum(case((priced, SpoolUsageHistory.weight_used), else_=0.0)),
  2319. )
  2320. async def _one_print_cost(db: AsyncSession, archive: PrintArchive, previous_grams: float | None = None) -> float | None:
  2321. """The archive's cost for one print of its grams (see ``price_one_print``).
  2322. A Spoolman-priced cost has no usage rows to rebuild it from (#2591); it is
  2323. kept, scaled to new grams when they were edited.
  2324. """
  2325. from backend.app.models.print_log import PrintLogEntry
  2326. grams = archive.filament_used_grams
  2327. default_cost = await _default_cost_per_kg(db)
  2328. usage_cost, tracked_grams = (
  2329. await db.execute(select(*_priced_usage_totals()).where(SpoolUsageHistory.archive_id == archive.id))
  2330. ).one()
  2331. if usage_cost is not None and usage_cost > 0:
  2332. printed_grams, runs = (
  2333. await db.execute(
  2334. select(func.sum(PrintLogEntry.filament_used_grams), func.count(PrintLogEntry.id)).where(
  2335. PrintLogEntry.archive_id == archive.id
  2336. )
  2337. )
  2338. ).one()
  2339. return price_one_print(
  2340. grams,
  2341. float(usage_cost),
  2342. float(tracked_grams or 0),
  2343. float(printed_grams or 0),
  2344. int(runs or 0),
  2345. default_cost,
  2346. default_cost,
  2347. )
  2348. if not grams:
  2349. return archive.cost
  2350. if archive.cost is not None and await _spoolman_owns_cost(db):
  2351. if previous_grams:
  2352. return round(archive.cost * grams / previous_grams, 2)
  2353. return archive.cost
  2354. fallback = default_cost
  2355. if archive.filament_type:
  2356. primary_type = archive.filament_type.split(",")[0].strip()
  2357. catalog = await db.scalar(select(Filament.cost_per_kg).where(Filament.type == primary_type).limit(1))
  2358. if catalog is not None:
  2359. fallback = catalog
  2360. return price_one_print(grams, None, 0.0, 0.0, 0, fallback, default_cost)
  2361. @router.post("/recalculate-costs")
  2362. async def recalculate_all_costs(
  2363. db: AsyncSession = Depends(get_db, scope="function"),
  2364. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2365. printer_scope: PrinterScope = RequestPrinterScope,
  2366. ):
  2367. """Recalculate costs for all archives based on filament usage and prices."""
  2368. from backend.app.services.print_log import mirror_archive_cost
  2369. from backend.app.services.usage_repricing import reprice_usage
  2370. # Only archives every print of which is on the caller's printers: it
  2371. # reprices the archive and its runs (archive redesign).
  2372. query = select(PrintArchive)
  2373. scoped_ids = None
  2374. if (clause := whole_archive_scope_clause(printer_scope)) is not None:
  2375. query = query.where(clause)
  2376. scoped_ids = select(PrintArchive.id).where(clause)
  2377. result = await db.execute(query)
  2378. archives = list(result.scalars().all())
  2379. # Load all filaments for lookup
  2380. filament_result = await db.execute(select(Filament))
  2381. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  2382. default_cost_per_kg = await _default_cost_per_kg(db)
  2383. spoolman_owns = await _spoolman_owns_cost(db)
  2384. # The usage first, at the spools' current prices: the sums below read it,
  2385. # and a price corrected since the print changed nothing otherwise (#3414).
  2386. # A caller limited to some printers leaves the usage of no archive alone.
  2387. repriced = await reprice_usage(
  2388. db, scoped_ids, default_cost_per_kg=default_cost_per_kg, spoolman_enabled=spoolman_owns
  2389. )
  2390. await db.flush()
  2391. # Pre-fetch all usage costs and tracked weight by archive_id.
  2392. # Tracked weight is used to top-up the cost at the default rate for any
  2393. # filament grams not covered by an inventory spool (#1344).
  2394. usage_costs_result = await db.execute(
  2395. select(SpoolUsageHistory.archive_id, *_priced_usage_totals()).group_by(SpoolUsageHistory.archive_id)
  2396. )
  2397. usage_costs = usage_costs_result.fetchall()
  2398. cost_map = {
  2399. row[0]: (row[1], float(row[2] or 0))
  2400. for row in usage_costs
  2401. if row[0] is not None and row[1] is not None and row[1] > 0
  2402. }
  2403. from backend.app.models.print_log import PrintLogEntry
  2404. run_totals = {
  2405. row[0]: (float(row[1] or 0), int(row[2] or 0))
  2406. for row in (
  2407. await db.execute(
  2408. select(
  2409. PrintLogEntry.archive_id,
  2410. func.sum(PrintLogEntry.filament_used_grams),
  2411. func.count(PrintLogEntry.id),
  2412. ).group_by(PrintLogEntry.archive_id)
  2413. )
  2414. ).all()
  2415. }
  2416. updated = 0
  2417. preserved = 0
  2418. for archive in archives:
  2419. usage = cost_map.get(archive.id)
  2420. if usage is not None:
  2421. usage_cost, tracked_grams = usage
  2422. printed_grams, runs = run_totals.get(archive.id, (0.0, 0))
  2423. new_cost = price_one_print(
  2424. archive.filament_used_grams,
  2425. usage_cost,
  2426. tracked_grams,
  2427. printed_grams,
  2428. runs,
  2429. default_cost_per_kg,
  2430. default_cost_per_kg,
  2431. )
  2432. else:
  2433. # No usage linked to this archive. Usage without an archive link
  2434. # (recorded before usage was linked, with archiving off, or of a
  2435. # deleted archive) is not matched by print name: that charged one
  2436. # print's spool cost to every archive of the same name.
  2437. if spoolman_owns and archive.cost is not None:
  2438. # Priced from the linked Spoolman spools at completion; there is
  2439. # nothing better to recompute it from here (#2591).
  2440. new_cost = None
  2441. preserved += 1
  2442. elif archive.filament_used_grams and archive.filament_type:
  2443. primary_type = archive.filament_type.split(",")[0].strip()
  2444. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  2445. new_cost = price_one_print(
  2446. archive.filament_used_grams, None, 0.0, 0.0, 0, cost_per_kg, default_cost_per_kg
  2447. )
  2448. else:
  2449. new_cost = None
  2450. if new_cost is not None and archive.cost != new_cost:
  2451. previous_cost = archive.cost
  2452. archive.cost = new_cost
  2453. # Its run had the old figure: statistics read the run's cost. A
  2454. # run its own usage priced keeps that, repriced above.
  2455. await mirror_archive_cost(db, archive, previous_cost, skip_runs=repriced.priced_runs)
  2456. updated += 1
  2457. await db.commit()
  2458. message = f"Recalculated costs for {updated} archives"
  2459. if preserved:
  2460. message += f"; kept {preserved} priced from Spoolman"
  2461. if repriced.spoolman_unreachable:
  2462. message += f"; Spoolman not reachable, {repriced.spoolman_unreachable} usage records kept their price"
  2463. return {
  2464. "message": message,
  2465. "updated": updated,
  2466. "preserved": preserved,
  2467. "usage_repriced": repriced.repriced,
  2468. "spoolman_unreachable": repriced.spoolman_unreachable,
  2469. }
  2470. @router.get("/{archive_id}/duplicates")
  2471. async def get_archive_duplicates(
  2472. archive_id: int,
  2473. db: AsyncSession = Depends(get_db, scope="function"),
  2474. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2475. require_ownership_permission(
  2476. Permission.ARCHIVES_READ_ALL,
  2477. Permission.ARCHIVES_READ_OWN,
  2478. )
  2479. ),
  2480. printer_scope: PrinterScope = RequestPrinterScope,
  2481. ):
  2482. """Get duplicates for a specific archive."""
  2483. user, can_read_all = auth_result
  2484. service = ArchiveService(db)
  2485. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  2486. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  2487. duplicates = await service.find_duplicates(
  2488. archive_id=archive.id,
  2489. content_hash=archive.content_hash,
  2490. print_name=archive.print_name,
  2491. makerworld_model_id=makerworld_id,
  2492. visible=_visible_archive_clauses(user, can_read_all, printer_scope),
  2493. )
  2494. return {"duplicates": duplicates, "count": len(duplicates)}
  2495. @router.post("/backfill-hashes")
  2496. async def backfill_content_hashes(
  2497. db: AsyncSession = Depends(get_db, scope="function"),
  2498. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2499. printer_scope: PrinterScope = RequestPrinterScope,
  2500. ):
  2501. """Compute and store content hashes for all archives missing them."""
  2502. result = await db.execute(
  2503. select(PrintArchive).where(
  2504. PrintArchive.content_hash.is_(None), *_visible_archive_clauses(None, True, printer_scope)
  2505. )
  2506. )
  2507. archives = list(result.scalars().all())
  2508. updated = 0
  2509. errors = []
  2510. for archive in archives:
  2511. try:
  2512. file_path = settings.base_dir / archive.file_path
  2513. if not file_path.is_file():
  2514. errors.append({"id": archive.id, "error": "File not found"})
  2515. continue
  2516. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  2517. updated += 1
  2518. except Exception as e:
  2519. logger.exception("Failed to compute hash for archive %s: %s", archive.id, e)
  2520. errors.append({"id": archive.id, "error": "Failed to compute hash"})
  2521. await db.commit()
  2522. return {"updated": updated, "errors": errors}
  2523. @router.delete("/{archive_id}")
  2524. async def delete_archive(
  2525. archive_id: int,
  2526. purge_stats: bool = Query(
  2527. False,
  2528. description=(
  2529. "When false (default) the archive is soft-deleted — files removed "
  2530. "from disk, row hidden from listings, but its filament / energy / "
  2531. "time / cost contribution stays in Quick Stats. Set true to also "
  2532. "drop the row from statistics (#1343)."
  2533. ),
  2534. ),
  2535. db: AsyncSession = Depends(get_db, scope="function"),
  2536. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2537. require_ownership_permission(
  2538. Permission.ARCHIVES_DELETE_ALL,
  2539. Permission.ARCHIVES_DELETE_OWN,
  2540. )
  2541. ),
  2542. printer_scope: PrinterScope = RequestPrinterScope,
  2543. ):
  2544. """Delete an archive (soft by default; ``?purge_stats=true`` to hard-delete).
  2545. Both delete paths now cascade to related ``print_queue`` rows (#1734) —
  2546. hard delete via the ``ON DELETE CASCADE`` FK, soft delete via the
  2547. ``_delete_related_queue_items`` helper. A 409 guard blocks the delete
  2548. when any related queue item is currently mid-print so the dispatcher
  2549. doesn't lose its metadata trail under the running print.
  2550. """
  2551. user, can_modify_all = auth_result
  2552. # Get archive first to check ownership
  2553. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2554. archive = result.scalar_one_or_none()
  2555. if not archive:
  2556. raise HTTPException(404, "Archive not found")
  2557. # Its prints on other printers would go with it (archive redesign).
  2558. await _ensure_whole_archive(archive, printer_scope)
  2559. # Ownership check
  2560. if not can_modify_all:
  2561. if archive.created_by_id != user.id:
  2562. raise HTTPException(403, "You can only delete your own archives")
  2563. # #1734: block delete when any related queue item is currently printing.
  2564. # Both soft and hard delete are gated — an in-flight print needs its
  2565. # backing archive to stay around for the metadata trail (filament,
  2566. # plate, ams_mapping). The user can stop the print first, then retry.
  2567. from backend.app.services.archive import _count_related_queue_items
  2568. _related_total, related_printing = await _count_related_queue_items(db, archive_id)
  2569. if related_printing > 0:
  2570. raise HTTPException(
  2571. 409,
  2572. f"Cannot delete archive — {related_printing} related queue item(s) are "
  2573. f"currently printing. Stop the print first, then retry.",
  2574. )
  2575. service = ArchiveService(db)
  2576. if purge_stats:
  2577. # Hard-delete the linked PrintLogEntry rows first so their filament /
  2578. # cost / count contributions disappear from /archives/stats. The FK is
  2579. # ON DELETE SET NULL, so without this delete the runs would survive
  2580. # the archive row and keep showing up in totals (#1343 / #1378).
  2581. from sqlalchemy import delete as sa_delete
  2582. from backend.app.models.print_log import PrintLogEntry
  2583. # Its open run too (a print started on the printer, with no queue item
  2584. # to refuse the delete): it has no archive left to end on.
  2585. await db.execute(
  2586. sa_delete(PrintLogEntry)
  2587. .where(PrintLogEntry.archive_id == archive_id)
  2588. .execution_options(include_open_runs=True)
  2589. )
  2590. await db.commit()
  2591. if not await service.delete_archive(archive_id):
  2592. raise HTTPException(404, "Archive not found")
  2593. return {"status": "deleted", "purged_from_stats": True}
  2594. if not await service.soft_delete_archive(archive_id):
  2595. raise HTTPException(404, "Archive not found")
  2596. return {"status": "deleted", "purged_from_stats": False}
  2597. @router.get("/{archive_id}/download")
  2598. async def download_archive(
  2599. archive_id: int,
  2600. inline: bool = False,
  2601. db: AsyncSession = Depends(get_db, scope="function"),
  2602. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2603. require_ownership_permission(
  2604. Permission.ARCHIVES_READ_ALL,
  2605. Permission.ARCHIVES_READ_OWN,
  2606. )
  2607. ),
  2608. printer_scope: PrinterScope = RequestPrinterScope,
  2609. ):
  2610. """Download the 3MF file."""
  2611. user, can_read_all = auth_result
  2612. service = ArchiveService(db)
  2613. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  2614. file_path = settings.base_dir / archive.file_path
  2615. if not file_path.is_file():
  2616. raise HTTPException(404, "File not found")
  2617. # Use inline disposition to let browser/OS handle file association
  2618. content_disposition = "inline" if inline else "attachment"
  2619. return FileResponse(
  2620. path=file_path,
  2621. filename=archive.filename,
  2622. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2623. content_disposition_type=content_disposition,
  2624. )
  2625. @router.get("/{archive_id}/file/{filename}")
  2626. async def download_archive_with_filename(
  2627. archive_id: int,
  2628. filename: str,
  2629. db: AsyncSession = Depends(get_db, scope="function"),
  2630. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2631. require_ownership_permission(
  2632. Permission.ARCHIVES_READ_ALL,
  2633. Permission.ARCHIVES_READ_OWN,
  2634. )
  2635. ),
  2636. printer_scope: PrinterScope = RequestPrinterScope,
  2637. ):
  2638. """Download the 3MF file with filename in URL."""
  2639. user, can_read_all = auth_result
  2640. service = ArchiveService(db)
  2641. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  2642. file_path = settings.base_dir / archive.file_path
  2643. if not file_path.is_file():
  2644. raise HTTPException(404, "File not found")
  2645. return FileResponse(
  2646. path=file_path,
  2647. filename=archive.filename,
  2648. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2649. )
  2650. @router.post("/{archive_id}/slicer-token")
  2651. async def create_archive_slicer_token(
  2652. archive_id: int,
  2653. db: AsyncSession = Depends(get_db, scope="function"),
  2654. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2655. require_ownership_permission(
  2656. Permission.ARCHIVES_READ_ALL,
  2657. Permission.ARCHIVES_READ_OWN,
  2658. )
  2659. ),
  2660. printer_scope: PrinterScope = RequestPrinterScope,
  2661. ):
  2662. """Create a short-lived download token for opening files in slicer applications.
  2663. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  2664. auth headers, so they use this token in the URL path instead.
  2665. """
  2666. from backend.app.core.auth import create_slicer_download_token
  2667. user, can_read_all = auth_result
  2668. service = ArchiveService(db)
  2669. await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  2670. token = await create_slicer_download_token("archive", archive_id)
  2671. return {"token": token}
  2672. @router.get("/{archive_id}/dl/{token}/{filename}")
  2673. async def download_archive_for_slicer(
  2674. archive_id: int,
  2675. token: str,
  2676. filename: str,
  2677. db: AsyncSession = Depends(get_db, scope="function"),
  2678. ):
  2679. """Download 3MF file using a slicer download token.
  2680. Token-authenticated (no auth headers needed). The token is short-lived and
  2681. archive-bound, created by POST /{archive_id}/slicer-token, and redeemable
  2682. for the rest of its TTL rather than exactly once -- the slicer is a separate
  2683. process that may fetch the URL more than once (#3029).
  2684. Filename is at the end of the URL so slicers can detect the file format.
  2685. """
  2686. from backend.app.core.auth import verify_slicer_download_token
  2687. if not await verify_slicer_download_token(token, "archive", archive_id, single_use=False):
  2688. raise HTTPException(403, "Invalid or expired download token")
  2689. service = ArchiveService(db)
  2690. archive = await service.get_archive(archive_id)
  2691. if not archive:
  2692. raise HTTPException(404, "Archive not found")
  2693. file_path = settings.base_dir / archive.file_path
  2694. if not file_path.is_file():
  2695. raise HTTPException(404, "File not found")
  2696. return FileResponse(
  2697. path=file_path,
  2698. filename=archive.filename,
  2699. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2700. )
  2701. @router.get("/{archive_id}/thumbnail")
  2702. async def get_thumbnail(
  2703. archive_id: int,
  2704. db: AsyncSession = Depends(get_db, scope="function"),
  2705. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2706. require_media_token_ownership(
  2707. Permission.ARCHIVES_READ_ALL,
  2708. Permission.ARCHIVES_READ_OWN,
  2709. )
  2710. ),
  2711. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  2712. ):
  2713. """Get the thumbnail image.
  2714. Requires a media token query param (?token=xxx) when auth is enabled, and
  2715. returns 404 for an archive the caller may not read (#3025).
  2716. """
  2717. user, can_read_all = auth_result
  2718. service = ArchiveService(db)
  2719. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  2720. if not archive.thumbnail_path:
  2721. raise HTTPException(404, "Thumbnail not found")
  2722. thumb_path = settings.base_dir / archive.thumbnail_path
  2723. if not thumb_path.exists():
  2724. raise HTTPException(404, "Thumbnail file not found")
  2725. # Use file modification time as ETag to bust cache
  2726. mtime = int(thumb_path.stat().st_mtime)
  2727. return FileResponse(
  2728. path=thumb_path,
  2729. media_type="image/png",
  2730. headers={
  2731. "Cache-Control": "no-cache, must-revalidate",
  2732. "ETag": f'"{mtime}"',
  2733. },
  2734. )
  2735. @router.get("/{archive_id}/printer-media")
  2736. async def get_archive_printer_media(
  2737. archive_id: int,
  2738. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2739. require_ownership_permission(
  2740. Permission.ARCHIVES_READ_ALL,
  2741. Permission.ARCHIVES_READ_OWN,
  2742. )
  2743. ),
  2744. can_list_printer_files: bool = Depends(probe_permissions_if_auth_enabled(Permission.PRINTERS_FILES)),
  2745. printer_scope: PrinterScope = RequestPrinterScope,
  2746. ):
  2747. """Find downloadable timelapse and `/ipcam` files for one print.
  2748. Local attached timelapses are returned without touching the printer.
  2749. Printer directories are listed only when the caller also has
  2750. ``printers:files``; otherwise the local result is returned with a warning.
  2751. Files are downloaded only after the user explicitly selects them in the UI.
  2752. """
  2753. user, can_read_all = auth_result
  2754. async with database.async_session() as db:
  2755. archive = await _ensure_archive_visible(
  2756. await ArchiveService(db).get_archive(archive_id), user, can_read_all, printer_scope
  2757. )
  2758. printer = None
  2759. claimed_timelapse_stems: set[str] = set()
  2760. if archive.printer_id is not None:
  2761. printer = (await db.execute(select(Printer).where(Printer.id == archive.printer_id))).scalar_one_or_none()
  2762. if printer is not None and archive.timelapse_path is None:
  2763. claimed_timelapse_stems = await _claimed_timelapse_stems(db, archive.printer_id, archive_id)
  2764. local_timelapse = None
  2765. if archive.timelapse_path and not await _media_hidden(archive, printer_scope):
  2766. local_path = settings.base_dir / archive.timelapse_path
  2767. if await asyncio.to_thread(local_path.is_file):
  2768. local_timelapse = {
  2769. "name": local_path.name,
  2770. "size": (await asyncio.to_thread(local_path.stat)).st_size,
  2771. }
  2772. response = {
  2773. "archive_id": archive.id,
  2774. # Not a printer outside the caller's scope, seen through a run of theirs.
  2775. "printer_id": archive.printer_id if printer_scope.allows(archive.printer_id) else None,
  2776. "local_timelapse": local_timelapse,
  2777. "remote_files": [],
  2778. "warnings": [],
  2779. }
  2780. if archive.printer_id is None or archive.started_at is None:
  2781. return response
  2782. if not can_list_printer_files:
  2783. response["warnings"].append("printer_files_forbidden")
  2784. return response
  2785. if printer is None or not printer_scope.allows(printer.id):
  2786. response["warnings"].append("printer_missing")
  2787. return response
  2788. if ftps_handshake_blocked(printer.ip_address):
  2789. if local_timelapse is None:
  2790. response["warnings"].append("timelapse_unavailable")
  2791. response["warnings"].append("ipcam_unavailable")
  2792. return response
  2793. remote_files: list[dict] = []
  2794. # If no copy was attached to the archive, offer the matching printer-side
  2795. # timelapse without mutating the archive or deleting anything from the SD.
  2796. if local_timelapse is None:
  2797. videos: list[dict] = []
  2798. any_timelapse_directory_available = False
  2799. for timelapse_dir in ("/timelapse", "/timelapse/video", "/record", "/recording"):
  2800. if ftps_handshake_blocked(printer.ip_address):
  2801. break
  2802. listing = await list_files_result_async(
  2803. printer.ip_address,
  2804. printer.access_code,
  2805. timelapse_dir,
  2806. timeout=_PRINTER_MEDIA_LIST_TIMEOUT_SECONDS,
  2807. printer_model=printer.model,
  2808. )
  2809. any_timelapse_directory_available |= listing.available
  2810. candidates = [
  2811. file
  2812. for file in listing.files
  2813. if not file.get("is_directory") and str(file.get("name") or "").lower().endswith(VIDEO_SUFFIXES)
  2814. ]
  2815. if candidates:
  2816. videos = candidates
  2817. break
  2818. if not any_timelapse_directory_available:
  2819. response["warnings"].append("timelapse_unavailable")
  2820. if videos:
  2821. baseline = set(archive.timelapse_baseline or [])
  2822. eligible = [
  2823. file
  2824. for file in videos
  2825. if str(file.get("name") or "") not in baseline
  2826. and Path(str(file.get("name") or "")).stem not in claimed_timelapse_stems
  2827. ]
  2828. if archive.timelapse_baseline is not None:
  2829. candidate = eligible[0] if len(eligible) == 1 else None
  2830. else:
  2831. candidate, _ = _match_timelapse_by_timestamp(eligible, archive.started_at)
  2832. if candidate is not None:
  2833. remote_files.append(
  2834. {
  2835. "name": candidate.get("name"),
  2836. "path": candidate.get("path"),
  2837. "size": candidate.get("size") or 0,
  2838. "mtime": candidate.get("mtime"),
  2839. "kind": "timelapse",
  2840. }
  2841. )
  2842. if ftps_handshake_blocked(printer.ip_address):
  2843. response["warnings"].append("ipcam_unavailable")
  2844. response["remote_files"] = remote_files
  2845. return response
  2846. ipcam_listing = await list_files_result_async(
  2847. printer.ip_address,
  2848. printer.access_code,
  2849. "/ipcam",
  2850. timeout=_PRINTER_MEDIA_LIST_TIMEOUT_SECONDS,
  2851. printer_model=printer.model,
  2852. )
  2853. if ipcam_listing.available:
  2854. for file in match_ipcam_chunks(ipcam_listing.files, archive.started_at, archive.completed_at):
  2855. remote_files.append(
  2856. {
  2857. "name": file.get("name"),
  2858. "path": file.get("path") or f"/ipcam/{file.get('name')}",
  2859. "size": file.get("size") or 0,
  2860. "mtime": file.get("mtime"),
  2861. "kind": "ipcam",
  2862. }
  2863. )
  2864. else:
  2865. response["warnings"].append("ipcam_unavailable")
  2866. response["remote_files"] = remote_files
  2867. return response
  2868. @router.post("/{archive_id}/media-download-token")
  2869. async def create_archive_media_download_token(
  2870. archive_id: int,
  2871. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2872. require_ownership_permission(Permission.ARCHIVES_READ_ALL, Permission.ARCHIVES_READ_OWN)
  2873. ),
  2874. printer_scope: PrinterScope = RequestPrinterScope,
  2875. ):
  2876. """Mint a single-use token bound to an archive's attached timelapse."""
  2877. from backend.app.core.auth import create_slicer_download_token
  2878. user, can_read_all = auth_result
  2879. async with database.async_session() as db:
  2880. archive = await _ensure_archive_visible(
  2881. await ArchiveService(db).get_archive(archive_id), user, can_read_all, printer_scope
  2882. )
  2883. if not archive.timelapse_path:
  2884. raise HTTPException(404, "Timelapse not found")
  2885. await _ensure_media_visible(archive, printer_scope)
  2886. timelapse_path = settings.base_dir / archive.timelapse_path
  2887. if not await asyncio.to_thread(timelapse_path.is_file):
  2888. raise HTTPException(404, "Timelapse file not found")
  2889. return {
  2890. "token": await create_slicer_download_token("archive-timelapse", archive_id),
  2891. "filename": timelapse_path.name,
  2892. }
  2893. @router.get("/{archive_id}/media/dl/{token}/{filename}")
  2894. async def download_archive_media_with_token(
  2895. archive_id: int,
  2896. token: str,
  2897. filename: str,
  2898. ):
  2899. """Consume a resource-bound token and stream an attached timelapse."""
  2900. from backend.app.core.auth import verify_slicer_download_token
  2901. if not await verify_slicer_download_token(token, "archive-timelapse", archive_id):
  2902. return download_error_response(403, "This download link has already been used or has expired.")
  2903. async with database.async_session() as db:
  2904. archive = await ArchiveService(db).get_archive(archive_id)
  2905. if not archive or not archive.timelapse_path:
  2906. return download_error_response(404, "This print has no attached timelapse.")
  2907. timelapse_path = settings.base_dir / archive.timelapse_path
  2908. if not await asyncio.to_thread(timelapse_path.is_file):
  2909. return download_error_response(404, "The attached timelapse is no longer on disk.")
  2910. safe_filename = safe_download_filename(filename, fallback=timelapse_path.name)
  2911. return FileResponse(
  2912. path=timelapse_path,
  2913. filename=safe_filename,
  2914. headers={"Content-Disposition": build_content_disposition(safe_filename)},
  2915. )
  2916. @router.get("/{archive_id}/timelapse")
  2917. async def get_timelapse(
  2918. archive_id: int,
  2919. db: AsyncSession = Depends(get_db, scope="function"),
  2920. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2921. require_media_token_ownership(
  2922. Permission.ARCHIVES_READ_ALL,
  2923. Permission.ARCHIVES_READ_OWN,
  2924. )
  2925. ),
  2926. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  2927. ):
  2928. """Get the timelapse video.
  2929. Requires a media token query param (?token=xxx) when auth is enabled, and
  2930. returns 404 for an archive the caller may not read (#3025).
  2931. """
  2932. user, can_read_all = auth_result
  2933. service = ArchiveService(db)
  2934. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  2935. if not archive.timelapse_path:
  2936. raise HTTPException(404, "Timelapse not found")
  2937. await _ensure_media_visible(archive, printer_scope)
  2938. timelapse_path = settings.base_dir / archive.timelapse_path
  2939. if not timelapse_path.exists():
  2940. raise HTTPException(404, "Timelapse file not found")
  2941. # Use file modification time as ETag to bust cache after processing
  2942. mtime = int(timelapse_path.stat().st_mtime)
  2943. # Detect media type from file extension (AVI from P1S before background conversion)
  2944. suffix = timelapse_path.suffix.lower()
  2945. media_type = {".mp4": "video/mp4", ".avi": "video/x-msvideo", ".mkv": "video/x-matroska"}.get(suffix, "video/mp4")
  2946. ext = suffix if suffix in (".mp4", ".avi", ".mkv") else ".mp4"
  2947. return FileResponse(
  2948. path=timelapse_path,
  2949. media_type=media_type,
  2950. filename=f"{archive.print_name or 'timelapse'}{ext}",
  2951. headers={
  2952. "Cache-Control": "no-cache, must-revalidate",
  2953. "ETag": f'"{mtime}"',
  2954. },
  2955. )
  2956. @router.delete("/{archive_id}/timelapse")
  2957. async def delete_timelapse(
  2958. archive_id: int,
  2959. db: AsyncSession = Depends(get_db, scope="function"),
  2960. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2961. require_ownership_permission(
  2962. Permission.ARCHIVES_DELETE_ALL,
  2963. Permission.ARCHIVES_DELETE_OWN,
  2964. )
  2965. ),
  2966. printer_scope: PrinterScope = RequestPrinterScope,
  2967. ):
  2968. """Remove the timelapse video from an archive."""
  2969. user, can_modify_all = auth_result
  2970. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2971. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  2972. await _ensure_whole_archive(archive, printer_scope)
  2973. if not archive.timelapse_path:
  2974. raise HTTPException(404, "No timelapse attached to this archive")
  2975. # Delete the file
  2976. timelapse_path = settings.base_dir / archive.timelapse_path
  2977. if timelapse_path.exists():
  2978. timelapse_path.unlink()
  2979. # Clear the path in database, on the runs that held it too
  2980. for run in await runs_with_timelapse(db, archive.id, archive.timelapse_path):
  2981. run.timelapse_path = None
  2982. archive.timelapse_path = None
  2983. archive.timelapse_plate_id = None
  2984. await db.commit()
  2985. from backend.app.services.archive import _announce_timelapse
  2986. await _announce_timelapse(archive_id, attached=False)
  2987. return {"status": "deleted"}
  2988. @router.post("/{archive_id}/timelapse/scan")
  2989. async def scan_timelapse(
  2990. archive_id: int,
  2991. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2992. printer_scope: PrinterScope = RequestPrinterScope,
  2993. ):
  2994. """Scan printer for timelapse matching this archive and attach it."""
  2995. from backend.app.core.database import async_session
  2996. from backend.app.models.printer import Printer
  2997. from backend.app.services.bambu_ftp import (
  2998. DownloadDeadlineExceeded,
  2999. delete_archived_timelapse,
  3000. download_file_bytes_async,
  3001. ftps_handshake_blocked,
  3002. get_ftp_retry_settings,
  3003. list_files_async,
  3004. remote_file_settled,
  3005. with_ftp_retry,
  3006. )
  3007. # Read the archive + printer in a short session and release the pooled DB
  3008. # connection BEFORE the FTP scan/download below — a timelapse pull walks
  3009. # several directories and fetches a 100MB+ video, so holding Depends(get_db, scope="function")
  3010. # across it pinned one connection idle-in-transaction for minutes (#2572).
  3011. # Scalar columns stay readable on the detached rows (expire_on_commit=False);
  3012. # the attach at the end runs in its own fresh short session.
  3013. async with async_session() as db:
  3014. archive = await ArchiveService(db).get_archive(archive_id)
  3015. if not archive:
  3016. raise HTTPException(404, "Archive not found")
  3017. if archive.timelapse_path:
  3018. return {"status": "exists", "message": "Timelapse already attached"}
  3019. if not archive.printer_id:
  3020. raise HTTPException(400, "Archive has no associated printer")
  3021. printer_scope.ensure(archive.printer_id)
  3022. await _ensure_whole_archive(archive, printer_scope)
  3023. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  3024. printer = result.scalar_one_or_none()
  3025. if not printer:
  3026. raise HTTPException(404, "Printer not found")
  3027. # Get base name from archive filename (without .3mf extension)
  3028. base_name = Path(archive.filename).stem
  3029. # Scan timelapse directory on printer
  3030. # Different printer models use different paths
  3031. files = []
  3032. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  3033. if ftps_handshake_blocked(printer.ip_address):
  3034. break
  3035. try:
  3036. files = await list_files_async(
  3037. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  3038. )
  3039. if files:
  3040. break
  3041. except Exception:
  3042. continue
  3043. if not files:
  3044. # "Couldn't reach the printer" and "the printer has no timelapse
  3045. # directory" are different problems with different fixes, and both used
  3046. # to come back as one 500 (#2780). Nothing here will work while the
  3047. # printer's file service is not answering over TLS, so say that rather
  3048. # than reporting an empty directory.
  3049. if ftps_handshake_blocked(printer.ip_address):
  3050. raise HTTPException(
  3051. 503,
  3052. f"Printer {printer.ip_address} is not answering its file service over TLS. "
  3053. "Bambuddy will try again shortly.",
  3054. )
  3055. raise HTTPException(404, "No timelapse directory found on the printer")
  3056. # Look for matching timelapse
  3057. matching_file = None
  3058. video_files = [
  3059. f for f in files if not f.get("is_directory") and f.get("name", "").lower().endswith((".mp4", ".avi"))
  3060. ]
  3061. # Strategy 0: snapshot diff against the baseline captured at print start
  3062. # (#2704). This is the same comparison the automatic scan makes, and the
  3063. # only one here that doesn't depend on the printer's clock — a printer in
  3064. # LAN-only mode can't reach Bambu's NTP server, so the timestamps in both
  3065. # the filename and the FTP mtime can be days out. One reporter's P1S was
  3066. # six and a half days off, which defeats every strategy below.
  3067. #
  3068. # When a baseline exists it is authoritative and the clock-based strategies
  3069. # are skipped entirely: they can only turn an honest "pick one yourself"
  3070. # into a confident wrong answer. Those strategies stay for archives created
  3071. # before the baseline was persisted.
  3072. used_baseline = archive.timelapse_baseline is not None
  3073. # A video another archive of this printer holds is that print's, whichever
  3074. # strategy below would pick it (a short name like "1" is in every video's
  3075. # timestamp). Picking by hand still offers it: that is how a wrong match
  3076. # is corrected.
  3077. offered = video_files
  3078. async with async_session() as db:
  3079. claimed = await _claimed_timelapse_stems(db, archive.printer_id, archive_id)
  3080. video_files = [f for f in video_files if Path(f.get("name", "")).stem not in claimed]
  3081. if used_baseline:
  3082. baseline = set(archive.timelapse_baseline)
  3083. candidates = [f for f in video_files if f.get("name", "") not in baseline]
  3084. if len(candidates) == 1:
  3085. matching_file = candidates[0]
  3086. logger.info("Matched timelapse by print-start baseline: %s", matching_file.get("name"))
  3087. elif candidates:
  3088. # Ambiguous — offer only the plausible files instead of guessing.
  3089. offered = candidates
  3090. logger.info("Baseline left %s unclaimed candidates for archive %s", len(candidates), archive_id)
  3091. else:
  3092. logger.info("Baseline shows no unclaimed new video on the printer for archive %s", archive_id)
  3093. # Strategy 1: Match by print name in filename
  3094. if not used_baseline:
  3095. for f in video_files:
  3096. fname = f.get("name", "")
  3097. if base_name.lower() in fname.lower():
  3098. matching_file = f
  3099. break
  3100. # Strategy 2: Match by timestamp proximity against print START time.
  3101. # Bambu timelapse filename embeds the print start time in printer-local clock.
  3102. # See _match_timelapse_by_timestamp for the offset-search rationale and why we
  3103. # intentionally don't try to match filename against end time here.
  3104. if not used_baseline and not matching_file and archive.started_at:
  3105. candidate, diff = _match_timelapse_by_timestamp(video_files, archive.started_at)
  3106. if candidate is not None:
  3107. matching_file = candidate
  3108. logger.info("Matched timelapse by timestamp: %s (diff: %s)", candidate.get("name"), diff)
  3109. # Strategy 3: Use file modification time from FTP listing
  3110. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  3111. if not used_baseline and not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  3112. from datetime import datetime, timedelta
  3113. _archive_start = archive.started_at
  3114. archive_end = archive.completed_at or archive.created_at
  3115. best_match = None
  3116. best_diff = timedelta(hours=24)
  3117. for f in video_files:
  3118. mtime = f.get("mtime")
  3119. if mtime:
  3120. # Timelapse file should be modified during or shortly after the print
  3121. # The mtime should be close to completion time (video finishes when print ends)
  3122. if archive_end:
  3123. diff = abs(mtime - archive_end)
  3124. if diff < best_diff:
  3125. best_diff = diff
  3126. best_match = f
  3127. logger.debug(
  3128. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  3129. )
  3130. if best_match and best_diff < timedelta(hours=2):
  3131. matching_file = best_match
  3132. logger.info("Matched timelapse by file mtime: %s (diff: %s)", best_match.get("name"), best_diff)
  3133. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  3134. # This handles cases where printer clock is wrong or timezone issues exist
  3135. if not used_baseline and not matching_file and len(video_files) == 1:
  3136. from datetime import datetime, timedelta, timezone
  3137. archive_completed = archive.completed_at or archive.created_at
  3138. if archive_completed:
  3139. if archive_completed.tzinfo is None:
  3140. archive_completed = archive_completed.replace(tzinfo=timezone.utc)
  3141. time_since_completion = datetime.now(timezone.utc) - archive_completed
  3142. # If archive was completed within the last hour, assume the single timelapse is for it
  3143. if time_since_completion < timedelta(hours=1):
  3144. matching_file = video_files[0]
  3145. logger.info("Using single timelapse file as fallback: %s", video_files[0].get("name"))
  3146. # Note: We intentionally don't use a "most recent file" fallback because
  3147. # we can't verify if timelapse was actually enabled for this print.
  3148. # Instead, return the list of available files for manual selection.
  3149. if not matching_file:
  3150. # Return available files for manual selection
  3151. available_files = [
  3152. {
  3153. "name": f.get("name"),
  3154. "path": f.get("path"),
  3155. "size": f.get("size"),
  3156. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  3157. }
  3158. for f in offered
  3159. ]
  3160. # Sort by mtime descending (most recent first)
  3161. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  3162. return {
  3163. "status": "not_found",
  3164. "message": "No matching timelapse found - please select manually",
  3165. "available_files": available_files,
  3166. }
  3167. # Download the timelapse - use the full path from the file listing
  3168. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  3169. # Get FTP retry settings
  3170. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3171. try:
  3172. if ftp_retry_enabled:
  3173. timelapse_data = await with_ftp_retry(
  3174. download_file_bytes_async,
  3175. printer.ip_address,
  3176. printer.access_code,
  3177. remote_path,
  3178. socket_timeout=ftp_timeout,
  3179. printer_model=printer.model,
  3180. expected_size=matching_file.get("size"),
  3181. max_retries=ftp_retry_count,
  3182. retry_delay=ftp_retry_delay,
  3183. operation_name=f"Download timelapse {matching_file['name']}",
  3184. cooloff_ip=printer.ip_address,
  3185. )
  3186. else:
  3187. timelapse_data = await download_file_bytes_async(
  3188. printer.ip_address,
  3189. printer.access_code,
  3190. remote_path,
  3191. socket_timeout=ftp_timeout,
  3192. printer_model=printer.model,
  3193. expected_size=matching_file.get("size"),
  3194. )
  3195. except DownloadDeadlineExceeded as exc:
  3196. # Not retried: the deadline already fitted the file's size.
  3197. raise HTTPException(504, "The timelapse download took longer than its size allows") from exc
  3198. if not timelapse_data:
  3199. raise HTTPException(502, "Could not download the timelapse from the printer")
  3200. # Confirm the printer has finished writing before we commit to this file and
  3201. # delete the original: matching the listing's size proves we got what it
  3202. # said, not that the file was complete (#2704).
  3203. if not await remote_file_settled(
  3204. printer.ip_address,
  3205. printer.access_code,
  3206. remote_path,
  3207. len(timelapse_data),
  3208. printer_model=printer.model,
  3209. ):
  3210. raise HTTPException(409, "The printer is still writing this video — try again in a moment")
  3211. # Attach in a fresh short session (the read session was released before FTP).
  3212. async with async_session() as db:
  3213. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  3214. if not success:
  3215. raise HTTPException(500, "Failed to attach timelapse")
  3216. # Safe now, and only now: the transfer matched the size the listing reported
  3217. # and the bytes are committed to the archive (#2704).
  3218. await delete_archived_timelapse(
  3219. printer.ip_address,
  3220. printer.access_code,
  3221. remote_path,
  3222. verified=matching_file.get("size") is not None,
  3223. printer_model=printer.model,
  3224. printer_name=printer.name,
  3225. )
  3226. return {
  3227. "status": "attached",
  3228. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  3229. "filename": matching_file["name"],
  3230. }
  3231. @router.post("/{archive_id}/timelapse/select")
  3232. async def select_timelapse(
  3233. archive_id: int,
  3234. filename: str = Query(..., description="Timelapse filename to attach"),
  3235. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3236. printer_scope: PrinterScope = RequestPrinterScope,
  3237. ):
  3238. """Manually select a timelapse from the printer to attach."""
  3239. from backend.app.core.database import async_session
  3240. from backend.app.models.printer import Printer
  3241. from backend.app.services.bambu_ftp import (
  3242. DownloadDeadlineExceeded,
  3243. delete_archived_timelapse,
  3244. download_file_bytes_async,
  3245. get_ftp_retry_settings,
  3246. list_files_async,
  3247. remote_file_settled,
  3248. with_ftp_retry,
  3249. )
  3250. # Read the archive + printer in a short session and release the pooled DB
  3251. # connection BEFORE the FTP scan/download below (#2572); scalars stay
  3252. # readable after close (expire_on_commit=False), the attach reopens one.
  3253. async with async_session() as db:
  3254. archive = await ArchiveService(db).get_archive(archive_id)
  3255. if not archive:
  3256. raise HTTPException(404, "Archive not found")
  3257. if not archive.printer_id:
  3258. raise HTTPException(400, "Archive has no associated printer")
  3259. printer_scope.ensure(archive.printer_id)
  3260. await _ensure_whole_archive(archive, printer_scope)
  3261. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  3262. printer = result.scalar_one_or_none()
  3263. if not printer:
  3264. raise HTTPException(404, "Printer not found")
  3265. # Find the file on the printer
  3266. files = []
  3267. remote_path = None
  3268. expected_size = None
  3269. for timelapse_dir in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  3270. try:
  3271. files = await list_files_async(
  3272. printer.ip_address, printer.access_code, timelapse_dir, printer_model=printer.model
  3273. )
  3274. for f in files:
  3275. if f.get("name") == filename:
  3276. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  3277. expected_size = f.get("size")
  3278. break
  3279. if remote_path:
  3280. break
  3281. except Exception:
  3282. continue
  3283. if not remote_path:
  3284. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  3285. # Download and attach
  3286. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3287. try:
  3288. if ftp_retry_enabled:
  3289. timelapse_data = await with_ftp_retry(
  3290. download_file_bytes_async,
  3291. printer.ip_address,
  3292. printer.access_code,
  3293. remote_path,
  3294. socket_timeout=ftp_timeout,
  3295. printer_model=printer.model,
  3296. expected_size=expected_size,
  3297. max_retries=ftp_retry_count,
  3298. retry_delay=ftp_retry_delay,
  3299. operation_name=f"Download timelapse {filename}",
  3300. cooloff_ip=printer.ip_address,
  3301. )
  3302. else:
  3303. timelapse_data = await download_file_bytes_async(
  3304. printer.ip_address,
  3305. printer.access_code,
  3306. remote_path,
  3307. socket_timeout=ftp_timeout,
  3308. printer_model=printer.model,
  3309. expected_size=expected_size,
  3310. )
  3311. except DownloadDeadlineExceeded as exc:
  3312. # Not retried: the deadline already fitted the file's size.
  3313. raise HTTPException(504, "The timelapse download took longer than its size allows") from exc
  3314. if not timelapse_data:
  3315. raise HTTPException(502, "Could not download the timelapse from the printer")
  3316. # Confirm the printer has finished writing before we commit to this file and
  3317. # delete the original: matching the listing's size proves we got what it
  3318. # said, not that the file was complete (#2704).
  3319. if not await remote_file_settled(
  3320. printer.ip_address,
  3321. printer.access_code,
  3322. remote_path,
  3323. len(timelapse_data),
  3324. printer_model=printer.model,
  3325. ):
  3326. raise HTTPException(409, "The printer is still writing this video — try again in a moment")
  3327. # Attach in a fresh short session (the read session was released before FTP).
  3328. async with async_session() as db:
  3329. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, filename)
  3330. if not success:
  3331. raise HTTPException(500, "Failed to attach timelapse")
  3332. # Safe now, and only now: the transfer matched the size the listing reported
  3333. # and the bytes are committed to the archive (#2704).
  3334. await delete_archived_timelapse(
  3335. printer.ip_address,
  3336. printer.access_code,
  3337. remote_path,
  3338. verified=expected_size is not None,
  3339. printer_model=printer.model,
  3340. printer_name=printer.name,
  3341. )
  3342. return {
  3343. "status": "attached",
  3344. "message": f"Timelapse '{filename}' attached successfully",
  3345. "filename": filename,
  3346. }
  3347. @router.post("/{archive_id}/timelapse/upload")
  3348. async def upload_timelapse(
  3349. archive_id: int,
  3350. file: UploadFile = File(...),
  3351. db: AsyncSession = Depends(get_db, scope="function"),
  3352. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3353. printer_scope: PrinterScope = RequestPrinterScope,
  3354. ):
  3355. """Manually upload a timelapse video to an archive."""
  3356. service = ArchiveService(db)
  3357. archive = await service.get_archive(archive_id)
  3358. if not archive:
  3359. raise HTTPException(404, "Archive not found")
  3360. await _ensure_whole_archive(archive, printer_scope)
  3361. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  3362. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  3363. content = await file.read()
  3364. safe_filename = _safe_filename(file.filename)
  3365. success = await service.attach_timelapse(archive_id, content, safe_filename)
  3366. if not success:
  3367. raise HTTPException(500, "Failed to attach timelapse")
  3368. return {"status": "attached", "filename": safe_filename}
  3369. @router.get("/{archive_id}/timelapse/info")
  3370. async def get_timelapse_info(
  3371. archive_id: int,
  3372. db: AsyncSession = Depends(get_db, scope="function"),
  3373. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3374. require_ownership_permission(
  3375. Permission.ARCHIVES_READ_ALL,
  3376. Permission.ARCHIVES_READ_OWN,
  3377. )
  3378. ),
  3379. printer_scope: PrinterScope = RequestPrinterScope,
  3380. ):
  3381. """Get timelapse video metadata for editor."""
  3382. from backend.app.schemas.timelapse import TimelapseInfoResponse
  3383. from backend.app.services.timelapse_processor import TimelapseProcessor
  3384. user, can_read_all = auth_result
  3385. service = ArchiveService(db)
  3386. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  3387. if not archive.timelapse_path:
  3388. raise HTTPException(404, "Timelapse not found")
  3389. await _ensure_media_visible(archive, printer_scope)
  3390. timelapse_path = settings.base_dir / archive.timelapse_path
  3391. if not timelapse_path.exists():
  3392. raise HTTPException(404, "Timelapse file not found")
  3393. try:
  3394. processor = TimelapseProcessor(timelapse_path)
  3395. info = await processor.get_info()
  3396. return TimelapseInfoResponse(**info)
  3397. except Exception as e:
  3398. logger.error("Failed to get timelapse info: %s", e)
  3399. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  3400. @router.get("/{archive_id}/timelapse/thumbnails")
  3401. async def get_timelapse_thumbnails(
  3402. archive_id: int,
  3403. count: int = Query(10, ge=1, le=30),
  3404. width: int = Query(160, ge=80, le=320),
  3405. db: AsyncSession = Depends(get_db, scope="function"),
  3406. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3407. require_ownership_permission(
  3408. Permission.ARCHIVES_READ_ALL,
  3409. Permission.ARCHIVES_READ_OWN,
  3410. )
  3411. ),
  3412. printer_scope: PrinterScope = RequestPrinterScope,
  3413. ):
  3414. """Generate timeline thumbnail frames for visual scrubbing."""
  3415. import base64
  3416. from backend.app.schemas.timelapse import ThumbnailResponse
  3417. from backend.app.services.timelapse_processor import TimelapseProcessor
  3418. user, can_read_all = auth_result
  3419. service = ArchiveService(db)
  3420. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  3421. if not archive.timelapse_path:
  3422. raise HTTPException(404, "Timelapse not found")
  3423. await _ensure_media_visible(archive, printer_scope)
  3424. timelapse_path = settings.base_dir / archive.timelapse_path
  3425. if not timelapse_path.exists():
  3426. raise HTTPException(404, "Timelapse file not found")
  3427. try:
  3428. processor = TimelapseProcessor(timelapse_path)
  3429. thumbnails = await processor.generate_thumbnails(count, width)
  3430. return ThumbnailResponse(
  3431. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  3432. timestamps=[ts for ts, _ in thumbnails],
  3433. )
  3434. except Exception as e:
  3435. logger.error("Failed to generate thumbnails: %s", e)
  3436. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  3437. @router.post("/{archive_id}/timelapse/process", status_code=202)
  3438. async def process_timelapse(
  3439. archive_id: int,
  3440. trim_start: float = Form(0),
  3441. trim_end: float = Form(None),
  3442. speed: float = Form(1.0),
  3443. audio_volume: float = Form(1.0),
  3444. save_mode: str = Form("new"),
  3445. output_filename: str = Form(None),
  3446. audio: UploadFile = File(None),
  3447. db: AsyncSession = Depends(get_db, scope="function"),
  3448. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3449. printer_scope: PrinterScope = RequestPrinterScope,
  3450. ):
  3451. """Start re-encoding the timelapse with trim, speed and optional audio.
  3452. Runs as a background job: poll ``GET .../timelapse/job`` for progress and
  3453. the result, ``DELETE .../timelapse/job`` cancels it.
  3454. """
  3455. import shutil
  3456. import tempfile
  3457. import uuid
  3458. from backend.app.schemas.timelapse import TimelapseJobResponse
  3459. from backend.app.services import timelapse_jobs
  3460. from backend.app.services.timelapse_processor import TimelapseProcessor
  3461. # Validate speed
  3462. if not 0.25 <= speed <= 4.0:
  3463. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  3464. if not 0.0 <= audio_volume <= 1.0:
  3465. raise HTTPException(400, "audio_volume must be between 0 and 1")
  3466. if save_mode not in ("replace", "new"):
  3467. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  3468. service = ArchiveService(db)
  3469. archive = await service.get_archive(archive_id)
  3470. if not archive or not archive.timelapse_path:
  3471. raise HTTPException(404, "Timelapse not found")
  3472. await _ensure_whole_archive(archive, printer_scope)
  3473. timelapse_path = settings.base_dir / archive.timelapse_path
  3474. if not timelapse_path.exists():
  3475. raise HTTPException(404, "Timelapse file not found")
  3476. current = timelapse_jobs.get_job(archive_id)
  3477. if current is not None and current.status == timelapse_jobs.RUNNING:
  3478. raise HTTPException(409, "This timelapse is already being processed")
  3479. try:
  3480. processor = TimelapseProcessor(timelapse_path)
  3481. except RuntimeError as e:
  3482. raise HTTPException(500, f"Processing failed: {e}") from None
  3483. archive_dir = timelapse_path.parent
  3484. stored_timelapse_path = archive.timelapse_path
  3485. # What is being edited, so a replace does not overwrite a timelapse removed
  3486. # or swapped for another one while the job ran.
  3487. source = timelapse_path.stat()
  3488. source_signature = (source.st_size, source.st_mtime_ns, source.st_ino)
  3489. # Determine output path. Unique temp names: two archives' jobs run at once.
  3490. if save_mode == "replace":
  3491. # Process to temp file first, then replace
  3492. output_path = Path(tempfile.gettempdir()) / f"processed_{archive_id}_{uuid.uuid4().hex}.mp4"
  3493. else:
  3494. # Save as new file alongside original
  3495. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  3496. # Sanitize filename - remove path separators and traversal sequences
  3497. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  3498. # Prevent path traversal
  3499. if ".." in filename or not filename or filename.startswith("."):
  3500. filename = f"timelapse_{archive_id}_edited"
  3501. if not filename.endswith(".mp4"):
  3502. filename += ".mp4"
  3503. output_path = archive_dir / filename # SEC-PATH-OK: filename alnum-filtered + .. rejected above
  3504. # Handle audio file
  3505. audio_temp_path = None
  3506. if audio and audio.filename:
  3507. # Validate audio file extension
  3508. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  3509. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  3510. audio_content = await audio.read()
  3511. # Extract and validate suffix to prevent path injection
  3512. suffix = Path(audio.filename).suffix.lower()
  3513. if suffix not in (".mp3", ".wav", ".m4a", ".aac", ".ogg"):
  3514. raise HTTPException(400, "Invalid audio file extension")
  3515. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}_{uuid.uuid4().hex}{suffix}"
  3516. audio_temp_path.write_bytes(audio_content)
  3517. async def run(job: timelapse_jobs.TimelapseJob) -> tuple[str, str]:
  3518. try:
  3519. success = await processor.process(
  3520. output_path=output_path,
  3521. trim_start=trim_start,
  3522. trim_end=trim_end,
  3523. speed=speed,
  3524. audio_path=audio_temp_path,
  3525. audio_volume=audio_volume,
  3526. on_progress=job.set_progress,
  3527. )
  3528. if not success:
  3529. raise RuntimeError("Video processing failed")
  3530. if save_mode == "replace":
  3531. await _ensure_timelapse_unchanged(archive_id, stored_timelapse_path, timelapse_path, source_signature)
  3532. shutil.move(str(output_path), str(timelapse_path))
  3533. return stored_timelapse_path, "Timelapse replaced successfully"
  3534. return str(output_path.relative_to(settings.base_dir)), f"Saved as {output_path.name}"
  3535. finally:
  3536. if save_mode == "replace":
  3537. output_path.unlink(missing_ok=True)
  3538. if audio_temp_path:
  3539. audio_temp_path.unlink(missing_ok=True)
  3540. try:
  3541. job = timelapse_jobs.start_job(archive_id, run)
  3542. except timelapse_jobs.JobAlreadyRunning:
  3543. # Started by another request while this one read its audio upload.
  3544. if audio_temp_path:
  3545. audio_temp_path.unlink(missing_ok=True)
  3546. raise HTTPException(409, "This timelapse is already being processed") from None
  3547. return TimelapseJobResponse.from_job(job)
  3548. async def _ensure_timelapse_unchanged(
  3549. archive_id: int, stored_path: str, timelapse_path: Path, signature: tuple[int, int, int]
  3550. ) -> None:
  3551. async with database.async_session() as db:
  3552. current = (
  3553. await db.execute(select(PrintArchive.timelapse_path).where(PrintArchive.id == archive_id))
  3554. ).scalar_one_or_none()
  3555. try:
  3556. now = timelapse_path.stat()
  3557. except FileNotFoundError:
  3558. now = None
  3559. if current != stored_path or now is None or (now.st_size, now.st_mtime_ns, now.st_ino) != signature:
  3560. raise RuntimeError("The timelapse was removed or replaced while it was being edited; the edit was not saved")
  3561. async def _timelapse_job_archive(archive_id: int, db: AsyncSession, printer_scope: PrinterScope) -> None:
  3562. archive = await ArchiveService(db).get_archive(archive_id)
  3563. if not archive:
  3564. raise HTTPException(404, "Timelapse not found")
  3565. # The job edits the archive's video, which is the whole archive's.
  3566. await _ensure_whole_archive(archive, printer_scope)
  3567. @router.get("/{archive_id}/timelapse/job")
  3568. async def get_timelapse_job(
  3569. archive_id: int,
  3570. db: AsyncSession = Depends(get_db, scope="function"),
  3571. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3572. printer_scope: PrinterScope = RequestPrinterScope,
  3573. ):
  3574. """The archive's running or last timelapse job: status, progress, result."""
  3575. from backend.app.schemas.timelapse import TimelapseJobResponse
  3576. from backend.app.services import timelapse_jobs
  3577. await _timelapse_job_archive(archive_id, db, printer_scope)
  3578. job = timelapse_jobs.get_job(archive_id)
  3579. if job is None:
  3580. raise HTTPException(404, "No timelapse job")
  3581. return TimelapseJobResponse.from_job(job)
  3582. @router.delete("/{archive_id}/timelapse/job")
  3583. async def cancel_timelapse_job(
  3584. archive_id: int,
  3585. db: AsyncSession = Depends(get_db, scope="function"),
  3586. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3587. printer_scope: PrinterScope = RequestPrinterScope,
  3588. ):
  3589. """Cancel the running timelapse job; stops ffmpeg and drops its output."""
  3590. from backend.app.schemas.timelapse import TimelapseJobResponse
  3591. from backend.app.services import timelapse_jobs
  3592. await _timelapse_job_archive(archive_id, db, printer_scope)
  3593. if not await timelapse_jobs.cancel_job(archive_id):
  3594. raise HTTPException(404, "No timelapse job is running")
  3595. job = timelapse_jobs.get_job(archive_id)
  3596. assert job is not None
  3597. return TimelapseJobResponse.from_job(job)
  3598. # ============================================
  3599. # Photo Endpoints
  3600. # ============================================
  3601. @router.post("/{archive_id}/photos")
  3602. async def upload_photo(
  3603. archive_id: int,
  3604. file: UploadFile = File(...),
  3605. db: AsyncSession = Depends(get_db, scope="function"),
  3606. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3607. require_ownership_permission(
  3608. Permission.ARCHIVES_UPDATE_ALL,
  3609. Permission.ARCHIVES_UPDATE_OWN,
  3610. )
  3611. ),
  3612. printer_scope: PrinterScope = RequestPrinterScope,
  3613. ):
  3614. """Upload a photo of the printed result."""
  3615. user, can_modify_all = auth_result
  3616. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3617. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  3618. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  3619. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  3620. # Get archive directory. parents=True because an archive with no 3MF owns
  3621. # <archive_dir>/<id>/, which nothing else has necessarily created yet.
  3622. photos_dir = archive_photos_dir(archive)
  3623. photos_dir.mkdir(parents=True, exist_ok=True)
  3624. # Generate unique filename
  3625. import uuid
  3626. ext = Path(file.filename).suffix.lower()
  3627. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  3628. photo_path = photos_dir / photo_filename # SEC-PATH-OK: photo_filename = uuid.uuid4().hex[:8] + ext
  3629. # Save file
  3630. content = await file.read()
  3631. photo_path.write_bytes(content)
  3632. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  3633. photos = list(archive.photos or [])
  3634. photos.append(photo_filename)
  3635. archive.photos = photos
  3636. await db.commit()
  3637. await db.refresh(archive)
  3638. return {"status": "uploaded", "filename": photo_filename, "photos": await _visible_photos(archive, printer_scope)}
  3639. @router.get("/{archive_id}/photos/{filename}")
  3640. async def get_photo(
  3641. archive_id: int,
  3642. filename: str,
  3643. db: AsyncSession = Depends(get_db, scope="function"),
  3644. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3645. require_media_token_ownership(
  3646. Permission.ARCHIVES_READ_ALL,
  3647. Permission.ARCHIVES_READ_OWN,
  3648. )
  3649. ),
  3650. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  3651. ):
  3652. """Get a specific photo.
  3653. Requires a media token query param (?token=xxx) when auth is enabled, and
  3654. returns 404 for an archive the caller may not read (#3025).
  3655. """
  3656. user, can_read_all = auth_result
  3657. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3658. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all, printer_scope)
  3659. await _ensure_media_visible(archive, printer_scope, filename)
  3660. # Membership check first — UUID-generated names on upload mean any URL
  3661. # filename that doesn't appear here is by definition not a real photo.
  3662. # Mirrors the delete handler below; previously this endpoint had no
  3663. # membership check at all and joined `filename` straight to disk.
  3664. if not archive.photos or filename not in archive.photos:
  3665. raise HTTPException(404, "Photo not found")
  3666. # Defence-in-depth: even though the membership check above already
  3667. # constrains `filename` to UUID-generated names from upload,
  3668. # find_archive_photo resolves and containment-checks each candidate,
  3669. # guarding against future code paths that might populate
  3670. # `archive.photos` from a less-trusted source.
  3671. photo_path = find_archive_photo(archive, filename)
  3672. if photo_path is None:
  3673. raise HTTPException(404, "Photo not found")
  3674. # Determine media type
  3675. ext = Path(filename).suffix.lower()
  3676. media_types = {
  3677. ".jpg": "image/jpeg",
  3678. ".jpeg": "image/jpeg",
  3679. ".png": "image/png",
  3680. ".webp": "image/webp",
  3681. }
  3682. media_type = media_types.get(ext, "image/jpeg")
  3683. return FileResponse(path=photo_path, media_type=media_type)
  3684. @router.delete("/{archive_id}/photos/{filename}")
  3685. async def delete_photo(
  3686. archive_id: int,
  3687. filename: str,
  3688. db: AsyncSession = Depends(get_db, scope="function"),
  3689. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3690. require_ownership_permission(
  3691. Permission.ARCHIVES_DELETE_ALL,
  3692. Permission.ARCHIVES_DELETE_OWN,
  3693. )
  3694. ),
  3695. printer_scope: PrinterScope = RequestPrinterScope,
  3696. ):
  3697. """Delete a photo."""
  3698. user, can_modify_all = auth_result
  3699. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3700. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  3701. await _ensure_media_visible(archive, printer_scope, filename)
  3702. if not archive.photos or filename not in archive.photos:
  3703. raise HTTPException(404, "Photo not found")
  3704. # Delete file — same lookup as get_photo above, so a photo that is
  3705. # readable is also deletable. Removing the name while leaving the file is
  3706. # how a no-3MF archive accumulated photos nobody could see or remove.
  3707. photo_path = find_archive_photo(archive, filename)
  3708. if photo_path is not None:
  3709. photo_path.unlink()
  3710. # Update archive photos list, and the list of the run it was taken for
  3711. photos = [p for p in archive.photos if p != filename]
  3712. archive.photos = photos if photos else None
  3713. runs = select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id)
  3714. for run in await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})):
  3715. if run.photos and filename in run.photos:
  3716. run.photos = [p for p in run.photos if p != filename]
  3717. await db.commit()
  3718. return {"status": "deleted", "photos": await _visible_photos(archive, printer_scope)}
  3719. # ============================================
  3720. # Post-print outcome confirmation (#1898)
  3721. # ============================================
  3722. # English-only on purpose: this page is rendered by the backend for a phone
  3723. # browser that carries no session and therefore no language preference.
  3724. _VERDICT_LABELS = {"good": "Good part", "reject": "Rejected"}
  3725. _VERDICT_SOURCE_PHRASES = {
  3726. "dialog": "in the app",
  3727. "link": "with a one-tap link",
  3728. "plate_clear": "automatically when the print plate was cleared",
  3729. "printer_card": "from the printer card",
  3730. "api": "through the API",
  3731. "reaction": "with a reaction in chat",
  3732. }
  3733. def _confirm_page(glyph: str, heading: str, body: str) -> str:
  3734. """The small HTML page every one-tap outcome link renders."""
  3735. return (
  3736. "<!doctype html><html><head><meta name='viewport' content='width=device-width, initial-scale=1'>"
  3737. "<title>Bambuddy</title></head>"
  3738. "<body style='font-family: system-ui, sans-serif; background:#1a1d21; color:#fff; display:flex;"
  3739. " align-items:center; justify-content:center; min-height:90vh; margin:0'>"
  3740. f"<div style='text-align:center; padding:0 1.5rem; max-width:32rem'>"
  3741. f"<div style='font-size:3rem'>{glyph}</div><h2>{heading}</h2>{body}</div></body></html>"
  3742. )
  3743. async def _render_already_answered_page(
  3744. db: AsyncSession, archive: PrintArchive, run: PrintLogEntry | None = None
  3745. ) -> str:
  3746. """Explain a spent one-tap link instead of calling it invalid.
  3747. The plate-clear default, the app and the other link all answer the same
  3748. prompt, so the button in a push notification is routinely tapped after the
  3749. question is settled. Report the verdict on file, when and how it landed,
  3750. and where to change it: of the run the link asked about, when it did.
  3751. """
  3752. from backend.app.api.routes.settings import get_external_base_url
  3753. name = html_escape(archive.print_name or archive.filename or "")
  3754. answered = run if run is not None else archive
  3755. # The verdict's own timestamp, not the moment the token was spent: a
  3756. # verdict changed later in the app would otherwise be dated by the older
  3757. # event. Pre-#1898 rows have neither, and then the page omits the date.
  3758. used_at = answered.user_verdict_at or answered.confirm_token_used_at
  3759. if used_at is not None and used_at.tzinfo is not None:
  3760. used_at = used_at.astimezone(timezone.utc)
  3761. when = used_at.strftime("%Y-%m-%d %H:%M UTC") if used_at else None
  3762. how = _VERDICT_SOURCE_PHRASES.get(answered.user_verdict_source or "")
  3763. label = _VERDICT_LABELS.get(answered.user_verdict or "")
  3764. if label:
  3765. recorded = f"Recorded as <strong>{label}</strong>"
  3766. if how:
  3767. recorded += f" {how}"
  3768. if when:
  3769. recorded += f" on {when}"
  3770. recorded += "."
  3771. else:
  3772. # The verdict was cleared again in the app; the link stays spent.
  3773. recorded = "This prompt was already answered and the verdict has since been cleared."
  3774. base = await get_external_base_url(db)
  3775. run_param = f"&run={run.id}" if run is not None else ""
  3776. link = html_escape(f"{base}/archives?confirm={archive.id}{run_param}", quote=True)
  3777. glyph = "&#10003;" if answered.user_verdict == "good" else "&#10007;" if answered.user_verdict else "&#8505;"
  3778. return _confirm_page(
  3779. glyph,
  3780. "Already answered",
  3781. f"<p style='color:#9ca3af'>{name}</p>"
  3782. f"<p style='color:#9ca3af'>{recorded}</p>"
  3783. f"<p><a style='color:#00ae42' href='{link}'>Open this print in Bambuddy</a> to change it.</p>",
  3784. )
  3785. def _render_confirm_prompt_page(request: Request, archive: PrintArchive, verdict: str) -> str:
  3786. """The page a one-tap verdict link opens. It has recorded nothing yet.
  3787. GET is where link unfurlers, mail-security scanners and browser prefetchers
  3788. arrive, uninvited and within seconds of the message being sent, so GET
  3789. writes nothing at all -- the verdict is recorded by the form below, over
  3790. POST, which none of them issue.
  3791. The form submits itself only for a page opened from a notification button,
  3792. which is what keeps the operator at one tap. The marker for that
  3793. (``?tap=1``) is put on the Telegram inline keyboard's URLs and nowhere else
  3794. -- never on a URL that travels in message text -- so a mail-security
  3795. sandbox that renders HTML and runs JavaScript cannot press the button for
  3796. the operator: it only ever sees the unmarked URL out of the body. The
  3797. User-Agent heuristic still runs on top of that, but it is no longer the
  3798. only thing between a scanner and the write; it cannot be, because such a
  3799. sandbox sends an ordinary Chrome string.
  3800. Every other arrival -- an unmarked link somebody typed or mailed, a browser
  3801. with JavaScript off -- gets the same page and presses the button.
  3802. """
  3803. name = html_escape(archive.print_name or archive.filename or "")
  3804. # Escaped although the route only lets good/reject through: the page must
  3805. # not depend on a check made in another function.
  3806. label = html_escape(_VERDICT_LABELS.get(verdict, verdict))
  3807. # No action attribute: the form posts back to the URL the page was loaded
  3808. # from, so it works behind a reverse proxy and on a host external_url does
  3809. # not name.
  3810. form = (
  3811. "<form method='post' id='confirm-form'>"
  3812. "<button type='submit' style='font: inherit; font-size:1.1rem; padding:0.9rem 2rem;"
  3813. " border:0; border-radius:0.5rem; background:#00ae42; color:#fff'>Yes, record it</button>"
  3814. "</form>"
  3815. )
  3816. # The SPA's CSP allows inline scripts only with the per-request nonce the
  3817. # security-headers middleware mints (main.py). Without one -- no middleware,
  3818. # an unmarked URL, or an unattended-looking caller -- the page simply waits
  3819. # for the button.
  3820. nonce = getattr(request.state, "csp_nonce", None)
  3821. script = ""
  3822. if nonce and is_one_tap_request(request.query_params) and not is_unattended_fetch(request.method, request.headers):
  3823. script = (
  3824. f"<script nonce='{html_escape(nonce, quote=True)}'>"
  3825. "document.getElementById('confirm-form').submit();</script>"
  3826. )
  3827. return _confirm_page(
  3828. "&#63;",
  3829. "Confirm this outcome",
  3830. f"<p style='color:#9ca3af'>{name}</p>"
  3831. f"<p style='color:#9ca3af'>Record this print as <strong>{label}</strong>?</p>"
  3832. f"{form}{script}",
  3833. )
  3834. def _confirm_response(html: str):
  3835. """The one-tap pages, never cached.
  3836. A proxy holding on to "Saved" or to the prompt would answer a later tap
  3837. from its cache, and the prompt page is a capability URL either way.
  3838. """
  3839. from fastapi.responses import HTMLResponse
  3840. return HTMLResponse(html, headers={"Cache-Control": "no-store"})
  3841. async def _load_confirmable_archive(
  3842. db: AsyncSession, token: str, verdict: str
  3843. ) -> tuple[PrintArchive, PrintLogEntry | None]:
  3844. """Resolve a one-tap capability token, or raise the route's 400/404: the
  3845. archive with the run the token asks about (None for an archive's own
  3846. token, minted before runs had theirs)."""
  3847. from backend.app.services.print_confirmation import confirm_token_holder
  3848. if verdict not in ("good", "reject"):
  3849. raise HTTPException(400, "Verdict must be 'good' or 'reject'")
  3850. found = await confirm_token_holder(db, token)
  3851. if found is None:
  3852. raise HTTPException(404, "Confirmation link is invalid or was already used")
  3853. return found
  3854. @router.get("/confirm/{token}/{verdict}")
  3855. async def confirm_outcome_page(
  3856. request: Request,
  3857. token: str,
  3858. verdict: str,
  3859. db: AsyncSession = Depends(get_db, scope="function"),
  3860. ):
  3861. """Open a one-tap verdict link. Reads only — the verdict is recorded by POST.
  3862. This used to be the route that recorded, and that was the defect: a GET
  3863. that changes state is answered by everything that walks a URL. Telegram
  3864. and Slack fetch the links in a message body to build a preview card, mail
  3865. gateways detonate them before delivery, browsers prefetch them — any one
  3866. of those spent the single-use token and settled the outcome before the
  3867. operator had read the question, always in the "good" direction because
  3868. good_url came first. Suppressing previews per channel does not cover the
  3869. proxies and scanners in between; only removing the write from GET does.
  3870. So GET now hands back the prompt page and nothing else. The page's form
  3871. POSTs to this same URL, and :func:`confirm_outcome_by_token` records it.
  3872. The human cost is zero for the path the feature is built around: a URL
  3873. opened from a notification button carries ``?tap=1`` and the page submits
  3874. itself, so that tap is still the only tap. Nothing else gets that script,
  3875. including a scanner that runs JavaScript -- the marker is on the buttons,
  3876. not in the message text a scanner reads.
  3877. """
  3878. archive, run = await _load_confirmable_archive(db, token, verdict)
  3879. if (run or archive).confirm_token_used_at is not None:
  3880. # Answered already — by hand, by the other link, by the plate-clear
  3881. # default or by a reaction. Report what is on file and change nothing.
  3882. return _confirm_response(await _render_already_answered_page(db, archive, run))
  3883. return _confirm_response(_render_confirm_prompt_page(request, archive, verdict))
  3884. @router.post("/confirm/{token}/{verdict}")
  3885. async def confirm_outcome_by_token(
  3886. token: str,
  3887. verdict: str,
  3888. db: AsyncSession = Depends(get_db, scope="function"),
  3889. ):
  3890. """Record a print-outcome verdict via the capability token from a push notification.
  3891. Deliberately unauthenticated: the token IS the credential. It is a 256-bit
  3892. per-archive capability, minted when the confirmation prompt fires, and it
  3893. only ever grants writing good/reject on that one archive, exactly once.
  3894. "Exactly once" is enforced by ``confirm_token_used_at`` rather than by
  3895. dropping the token value, so a link for a print that was already answered
  3896. can be recognised and explained instead of looking broken.
  3897. POST is what keeps the capability the operator's: unfurlers, scanners and
  3898. prefetchers issue GET, and the GET route above writes nothing. The two
  3899. callers that reach here are the prompt page's form and the ntfy action
  3900. button, which performs its own request from the phone and is configured
  3901. with ``method=POST``. Returns a small HTML page for the phone browser.
  3902. """
  3903. from backend.app.services.print_confirmation import latest_run, record_verdict
  3904. archive, run = await _load_confirmable_archive(db, token, verdict)
  3905. if (run or archive).confirm_token_used_at is not None:
  3906. return _confirm_response(await _render_already_answered_page(db, archive, run))
  3907. # The run the link asks about; an archive's own token, sent before runs
  3908. # had theirs, answers its latest. Verdict-aware statistics read the run.
  3909. await record_verdict(db, archive, verdict, source="link", run=run or await latest_run(db, archive.id))
  3910. await db.commit()
  3911. label = "Good part" if verdict == "good" else "Rejected"
  3912. name = archive.print_name or archive.filename
  3913. return _confirm_response(
  3914. _confirm_page(
  3915. "&#10003;" if verdict == "good" else "&#10007;",
  3916. label,
  3917. f"<p style='color:#9ca3af'>{html_escape(name)}</p>"
  3918. "<p style='color:#9ca3af'>Saved &mdash; you can close this page.</p>",
  3919. )
  3920. )
  3921. # ============================================
  3922. # QR Code Endpoint
  3923. # ============================================
  3924. @router.get("/{archive_id}/qrcode")
  3925. async def get_qrcode(
  3926. archive_id: int,
  3927. request: Request,
  3928. size: int = 200,
  3929. db: AsyncSession = Depends(get_db, scope="function"),
  3930. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3931. require_media_token_ownership(
  3932. Permission.ARCHIVES_READ_ALL,
  3933. Permission.ARCHIVES_READ_OWN,
  3934. )
  3935. ),
  3936. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  3937. ):
  3938. """Generate a QR code that links to this archive.
  3939. Requires a media token query param (?token=xxx) when auth is enabled, and
  3940. returns 404 for an archive the caller may not read (#3025).
  3941. """
  3942. user, can_read_all = auth_result
  3943. try:
  3944. import qrcode
  3945. from PIL import Image as PILImage
  3946. except ImportError:
  3947. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  3948. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3949. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all, printer_scope)
  3950. # Build URL to archive download
  3951. base_url = str(request.base_url).rstrip("/")
  3952. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  3953. # Generate QR code
  3954. qr = qrcode.QRCode(
  3955. version=1,
  3956. error_correction=qrcode.constants.ERROR_CORRECT_M,
  3957. box_size=10,
  3958. border=2,
  3959. )
  3960. qr.add_data(archive_url)
  3961. qr.make(fit=True)
  3962. img = qr.make_image(fill_color="black", back_color="white")
  3963. # Convert to PIL Image for resizing
  3964. pil_img = img.get_image()
  3965. # Resize if needed
  3966. if size != 200:
  3967. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  3968. # Convert to bytes
  3969. buffer = io.BytesIO()
  3970. pil_img.save(buffer, format="PNG")
  3971. buffer.seek(0)
  3972. qr_filename = f"qr_{archive.print_name or archive_id}.png"
  3973. return Response(
  3974. content=buffer.getvalue(),
  3975. media_type="image/png",
  3976. headers={"Content-Disposition": build_content_disposition(qr_filename, disposition="inline")},
  3977. )
  3978. @router.get("/{archive_id}/capabilities")
  3979. async def get_archive_capabilities(
  3980. archive_id: int,
  3981. db: AsyncSession = Depends(get_db, scope="function"),
  3982. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3983. require_ownership_permission(
  3984. Permission.ARCHIVES_READ_ALL,
  3985. Permission.ARCHIVES_READ_OWN,
  3986. )
  3987. ),
  3988. printer_scope: PrinterScope = RequestPrinterScope,
  3989. ):
  3990. """Check what viewing capabilities are available for this 3MF file."""
  3991. import defusedxml.ElementTree as ET
  3992. user, can_read_all = auth_result
  3993. service = ArchiveService(db)
  3994. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  3995. file_path = settings.base_dir / archive.file_path
  3996. if not file_path.is_file():
  3997. raise HTTPException(404, "File not found")
  3998. has_model = False
  3999. has_gcode = False
  4000. has_source = False
  4001. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  4002. filament_colors: list[str] = []
  4003. # Check if source 3MF exists - this is where actual mesh data typically lives
  4004. source_path = None
  4005. if archive.source_3mf_path:
  4006. source_path = settings.base_dir / archive.source_3mf_path
  4007. if source_path.exists():
  4008. has_source = True
  4009. # Helper function to check for mesh data and extract colors from a 3MF file
  4010. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  4011. """Extract mesh presence, colors, and build volume from a 3MF file."""
  4012. found_mesh = False
  4013. colors: list[str] = []
  4014. volume = {"x": 256, "y": 256, "z": 256}
  4015. try:
  4016. with zipfile.ZipFile(zf_path, "r") as zf:
  4017. names = zf.namelist()
  4018. # Check for 3D model - look for actual mesh data
  4019. for name in names:
  4020. if name.endswith(".model"):
  4021. try:
  4022. content = zf.read(name).decode("utf-8")
  4023. if "<vertex" in content or "<mesh" in content:
  4024. found_mesh = True
  4025. break
  4026. except Exception:
  4027. pass # Skip unreadable .model entries in archive
  4028. # Extract filament colors from project_settings.config
  4029. if "Metadata/project_settings.config" in names:
  4030. try:
  4031. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  4032. config_data = json.loads(config_content)
  4033. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  4034. printable_area = config_data.get("printable_area", [])
  4035. if printable_area and len(printable_area) >= 3:
  4036. max_x = 0
  4037. max_y = 0
  4038. for coord in printable_area:
  4039. if "x" in coord:
  4040. parts = coord.split("x")
  4041. if len(parts) == 2:
  4042. try:
  4043. x, y = int(parts[0]), int(parts[1])
  4044. max_x = max(max_x, x)
  4045. max_y = max(max_y, y)
  4046. except ValueError:
  4047. pass # Skip non-numeric printable_area coordinate
  4048. if max_x > 0 and max_y > 0:
  4049. volume["x"] = max_x
  4050. volume["y"] = max_y
  4051. # Parse printable_height
  4052. printable_height = config_data.get("printable_height")
  4053. if printable_height:
  4054. try:
  4055. volume["z"] = int(printable_height)
  4056. except (ValueError, TypeError):
  4057. pass # Skip unparseable printable_height value
  4058. # Extract filament colors
  4059. raw_colors = config_data.get("filament_colour", [])
  4060. if raw_colors:
  4061. for color in raw_colors:
  4062. if color and isinstance(color, str):
  4063. colors.append(color)
  4064. except Exception:
  4065. pass # Skip malformed project_settings.config
  4066. except zipfile.BadZipFile:
  4067. pass # File is not a valid zip/3MF archive
  4068. return found_mesh, colors, volume
  4069. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  4070. if has_source and source_path:
  4071. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  4072. if source_has_mesh:
  4073. has_model = True
  4074. if source_colors:
  4075. filament_colors = source_colors
  4076. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  4077. build_volume = source_volume
  4078. try:
  4079. with zipfile.ZipFile(file_path, "r") as zf:
  4080. names = zf.namelist()
  4081. # Check for G-code in the sliced file. Shared with the library's
  4082. # file-type classification so the card's badge and what the File
  4083. # Manager makes of the same file cannot disagree (#2993).
  4084. has_gcode = names_carry_gcode(names)
  4085. # Check for 3D model in sliced file (fallback if no source)
  4086. if not has_model:
  4087. for name in names:
  4088. if name.endswith(".model"):
  4089. try:
  4090. content = zf.read(name).decode("utf-8")
  4091. if "<vertex" in content or "<mesh" in content:
  4092. has_model = True
  4093. break
  4094. except Exception:
  4095. pass # Skip unreadable .model entries in archive
  4096. # Extract filament colors from slice_info.config (for gcode preview)
  4097. # These are the actual filaments used in the print, indexed by tool/extruder
  4098. slice_colors: list[str] = []
  4099. if "Metadata/slice_info.config" in names:
  4100. try:
  4101. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  4102. root = ET.fromstring(slice_content)
  4103. filaments = root.findall(".//filament")
  4104. filament_map: dict[int, str] = {}
  4105. for f in filaments:
  4106. fid = f.get("id")
  4107. fcolor = f.get("color")
  4108. used_g = f.get("used_g", "0")
  4109. try:
  4110. used_amount = float(used_g)
  4111. except (ValueError, TypeError):
  4112. used_amount = 0
  4113. if fid is not None and fcolor:
  4114. try:
  4115. tool_id = int(fid) - 1
  4116. if tool_id >= 0 and used_amount > 0:
  4117. filament_map[tool_id] = fcolor
  4118. except ValueError:
  4119. pass # Skip filament entry with non-numeric ID
  4120. if filament_map:
  4121. max_tool = max(filament_map.keys())
  4122. for i in range(max_tool + 1):
  4123. slice_colors.append(filament_map.get(i, "#00AE42"))
  4124. except Exception:
  4125. pass # Skip malformed slice_info.config XML
  4126. # Use slice_info colors if we don't have colors from source yet
  4127. if not filament_colors and slice_colors:
  4128. filament_colors = slice_colors
  4129. # Extract build volume from sliced file if not already set from source
  4130. if build_volume["x"] == 256 and build_volume["y"] == 256:
  4131. if "Metadata/project_settings.config" in names:
  4132. try:
  4133. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  4134. config_data = json.loads(config_content)
  4135. printable_area = config_data.get("printable_area", [])
  4136. if printable_area and len(printable_area) >= 3:
  4137. max_x = 0
  4138. max_y = 0
  4139. for coord in printable_area:
  4140. if "x" in coord:
  4141. parts = coord.split("x")
  4142. if len(parts) == 2:
  4143. try:
  4144. x, y = int(parts[0]), int(parts[1])
  4145. max_x = max(max_x, x)
  4146. max_y = max(max_y, y)
  4147. except ValueError:
  4148. pass # Skip non-numeric printable_area coordinate
  4149. if max_x > 0 and max_y > 0:
  4150. build_volume["x"] = max_x
  4151. build_volume["y"] = max_y
  4152. printable_height = config_data.get("printable_height")
  4153. if printable_height:
  4154. try:
  4155. build_volume["z"] = int(printable_height)
  4156. except (ValueError, TypeError):
  4157. pass # Skip unparseable printable_height value
  4158. # Fallback colors from project_settings if still empty
  4159. if not filament_colors:
  4160. raw_colors = config_data.get("filament_colour", [])
  4161. if raw_colors:
  4162. for color in raw_colors:
  4163. if color and isinstance(color, str):
  4164. filament_colors.append(color)
  4165. except Exception:
  4166. pass # Skip malformed project_settings.config
  4167. except zipfile.BadZipFile:
  4168. raise HTTPException(400, "Invalid 3MF file")
  4169. return {
  4170. "has_model": has_model,
  4171. "has_gcode": has_gcode,
  4172. "has_source": has_source,
  4173. "build_volume": build_volume,
  4174. "filament_colors": filament_colors,
  4175. }
  4176. @router.get("/{archive_id}/gcode")
  4177. async def get_gcode(
  4178. archive_id: int,
  4179. plate: int | None = None,
  4180. db: AsyncSession = Depends(get_db, scope="function"),
  4181. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4182. require_ownership_permission(
  4183. Permission.ARCHIVES_READ_ALL,
  4184. Permission.ARCHIVES_READ_OWN,
  4185. )
  4186. ),
  4187. printer_scope: PrinterScope = RequestPrinterScope,
  4188. ):
  4189. """Extract and return G-code from the 3MF file.
  4190. When *plate* is provided, returns the G-code for that specific plate
  4191. (e.g. ``?plate=2`` returns ``Metadata/plate_2.gcode``). If omitted, falls
  4192. back to the archive's lowest-numbered plate — not the first member in the
  4193. zip, which is whatever order the slicer wrote and routinely puts plate 2
  4194. ahead of plate 1.
  4195. """
  4196. user, can_read_all = auth_result
  4197. service = ArchiveService(db)
  4198. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  4199. file_path = settings.base_dir / archive.file_path
  4200. if not file_path.is_file():
  4201. raise HTTPException(404, "File not found")
  4202. if plate is not None and plate < 1:
  4203. raise HTTPException(400, "Plate index must be >= 1")
  4204. try:
  4205. with zipfile.ZipFile(file_path, "r") as zf:
  4206. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  4207. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  4208. if not gcode_files:
  4209. raise HTTPException(
  4210. 404,
  4211. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  4212. )
  4213. if plate is not None:
  4214. selected = select_plate_gcode_name(gcode_files, plate)
  4215. if selected is None:
  4216. raise HTTPException(404, f"Plate {plate} not found in this archive")
  4217. else:
  4218. selected = default_plate_gcode_name(gcode_files)
  4219. gcode_content = zf.read(selected).decode("utf-8")
  4220. return Response(content=gcode_content, media_type="text/plain")
  4221. except zipfile.BadZipFile:
  4222. raise HTTPException(400, "Invalid 3MF file")
  4223. except HTTPException:
  4224. raise
  4225. except Exception as e:
  4226. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  4227. @router.get("/{archive_id}/plate-preview")
  4228. async def get_plate_preview(
  4229. archive_id: int,
  4230. db: AsyncSession = Depends(get_db, scope="function"),
  4231. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4232. require_media_token_ownership(
  4233. Permission.ARCHIVES_READ_ALL,
  4234. Permission.ARCHIVES_READ_OWN,
  4235. )
  4236. ),
  4237. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  4238. ):
  4239. """Get the plate preview image from the 3MF file.
  4240. Returns the slicer-generated plate thumbnail which shows the model
  4241. with correct colors and positioning.
  4242. Requires a media token query param (?token=xxx) when auth is enabled, and
  4243. returns 404 for an archive the caller may not read (#3025).
  4244. """
  4245. user, can_read_all = auth_result
  4246. service = ArchiveService(db)
  4247. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  4248. file_path = settings.base_dir / archive.file_path
  4249. if not file_path.is_file():
  4250. raise HTTPException(404, "File not found")
  4251. try:
  4252. with zipfile.ZipFile(file_path, "r") as zf:
  4253. names = zf.namelist()
  4254. # Try to find plate preview images in order of preference
  4255. # First look for the specific plate being printed (check slice_info for plate index)
  4256. plate_num = 1
  4257. if "Metadata/slice_info.config" in names:
  4258. try:
  4259. import defusedxml.ElementTree as ET
  4260. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  4261. root = ET.fromstring(slice_content)
  4262. plate_elem = root.find(".//plate/metadata[@key='index']")
  4263. if plate_elem is not None:
  4264. plate_num = int(plate_elem.get("value", "1"))
  4265. except Exception:
  4266. pass # Default plate_num=1 if slice_info is missing or malformed
  4267. # Try plate-specific image first, then fall back to plate_1
  4268. preview_paths = [
  4269. f"Metadata/plate_{plate_num}.png",
  4270. "Metadata/plate_1.png",
  4271. "Metadata/thumbnail.png",
  4272. ]
  4273. for preview_path in preview_paths:
  4274. if preview_path in names:
  4275. image_data = zf.read(preview_path)
  4276. return Response(content=image_data, media_type="image/png")
  4277. # If no plate image, try any PNG in Metadata
  4278. for name in names:
  4279. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  4280. image_data = zf.read(name)
  4281. return Response(content=image_data, media_type="image/png")
  4282. raise HTTPException(404, "No plate preview found in 3MF file")
  4283. except zipfile.BadZipFile:
  4284. raise HTTPException(400, "Invalid 3MF file")
  4285. except HTTPException:
  4286. raise
  4287. except Exception as e:
  4288. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  4289. @router.post("/upload")
  4290. async def upload_archive(
  4291. file: UploadFile = File(...),
  4292. printer_id: int | None = None,
  4293. prefer_filename_for_name: bool = Query(
  4294. False,
  4295. description=(
  4296. "Name the archive after the uploaded filename instead of the print_name "
  4297. "embedded in the 3MF's metadata. Off by default, which keeps the embedded "
  4298. "name. Turn it on when the filename you send is the meaningful one — an "
  4299. "integration naming files after its own jobs, or a file whose embedded "
  4300. "title is a stale name from whoever originally sliced it."
  4301. ),
  4302. ),
  4303. db: AsyncSession = Depends(get_db, scope="function"),
  4304. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  4305. printer_scope: PrinterScope = RequestPrinterScope,
  4306. ):
  4307. """Manually upload a 3MF file to archive.
  4308. prefer_filename_for_name is the same flag the FTP review flow and
  4309. virtual-printer dispatch already pass to ArchiveService.archive_print —
  4310. this endpoint just didn't expose it (#1152 follow-up). Those callers derive
  4311. it from the VP-scoped `virtual_printer_archive_name_source` setting; here it
  4312. is per-request, because the caller is an API client that knows whether the
  4313. filename it sent is the meaningful one (#2609).
  4314. """
  4315. printer_scope.ensure(printer_id)
  4316. if not file.filename or not file.filename.endswith(".3mf"):
  4317. raise HTTPException(400, "File must be a .3mf file")
  4318. # Save uploaded file temporarily — strip directory components to prevent path traversal
  4319. safe_filename = _safe_filename(file.filename)
  4320. temp_path = (
  4321. settings.archive_dir / "temp" / safe_filename
  4322. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  4323. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4324. try:
  4325. content = await file.read()
  4326. # #1401: same content validation as library upload — catches
  4327. # raw-gcode-renamed-to-.3mf and other unprintable shapes before
  4328. # archiving them and offering them up for print.
  4329. from backend.app.api.routes.library import validate_print_file_upload
  4330. validate_print_file_upload(file.filename, content)
  4331. temp_path.write_bytes(content)
  4332. service = ArchiveService(db)
  4333. archive = await service.archive_print(
  4334. printer_id=printer_id,
  4335. source_file=temp_path,
  4336. created_by_id=current_user.id if current_user else None,
  4337. prefer_filename_for_name=prefer_filename_for_name,
  4338. )
  4339. if not archive:
  4340. raise HTTPException(400, "Failed to archive file")
  4341. return ArchiveResponse.model_validate(archive)
  4342. finally:
  4343. if temp_path.exists():
  4344. temp_path.unlink()
  4345. @router.post("/upload-bulk")
  4346. async def upload_archives_bulk(
  4347. files: list[UploadFile] = File(...),
  4348. printer_id: int | None = None,
  4349. prefer_filename_for_name: bool = Query(
  4350. False,
  4351. description=(
  4352. "Name each archive after its uploaded filename instead of the print_name "
  4353. "embedded in the 3MF's metadata. Applies to every file in the batch. Off "
  4354. "by default, which keeps the embedded name."
  4355. ),
  4356. ),
  4357. db: AsyncSession = Depends(get_db, scope="function"),
  4358. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  4359. printer_scope: PrinterScope = RequestPrinterScope,
  4360. ):
  4361. """Bulk upload multiple 3MF files to archive.
  4362. prefer_filename_for_name applies to every file in the batch. See
  4363. upload_archive for the flag's lineage.
  4364. """
  4365. printer_scope.ensure(printer_id)
  4366. from backend.app.api.routes.library import validate_print_file_upload
  4367. # Each outcome carries its file's position in the request: two files of
  4368. # the same name cannot be told apart by name.
  4369. results = []
  4370. errors = []
  4371. for index, file in enumerate(files):
  4372. if not file.filename or not file.filename.endswith(".3mf"):
  4373. errors.append({"index": index, "filename": file.filename or "unknown", "error": "Not a .3mf file"})
  4374. continue
  4375. safe_filename = _safe_filename(file.filename)
  4376. temp_path = (
  4377. settings.archive_dir / "temp" / safe_filename
  4378. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  4379. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4380. try:
  4381. content = await file.read()
  4382. # #1401: bulk-upload variant of the library validation. Collect
  4383. # the rejection per-file rather than aborting the whole batch
  4384. # so one bad file in a 10-file drag-drop doesn't lose the
  4385. # other nine.
  4386. try:
  4387. validate_print_file_upload(file.filename, content)
  4388. except HTTPException as exc:
  4389. errors.append({"index": index, "filename": file.filename, "error": exc.detail})
  4390. continue
  4391. temp_path.write_bytes(content)
  4392. service = ArchiveService(db)
  4393. archive = await service.archive_print(
  4394. printer_id=printer_id,
  4395. source_file=temp_path,
  4396. created_by_id=current_user.id if current_user else None,
  4397. prefer_filename_for_name=prefer_filename_for_name,
  4398. )
  4399. if archive:
  4400. results.append(
  4401. {
  4402. "index": index,
  4403. "filename": file.filename,
  4404. "id": archive.id,
  4405. "status": "success",
  4406. }
  4407. )
  4408. else:
  4409. errors.append({"index": index, "filename": file.filename, "error": "Failed to process"})
  4410. except Exception as e:
  4411. logger.exception("Failed to upload archive %s: %s", file.filename, e)
  4412. errors.append({"index": index, "filename": file.filename, "error": "Failed to process file"})
  4413. finally:
  4414. if temp_path.exists():
  4415. temp_path.unlink()
  4416. return {
  4417. "uploaded": len(results),
  4418. "failed": len(errors),
  4419. "results": results,
  4420. "errors": errors,
  4421. }
  4422. @router.get("/{archive_id}/plates")
  4423. async def get_archive_plates(
  4424. archive_id: int,
  4425. db: AsyncSession = Depends(get_db, scope="function"),
  4426. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4427. require_ownership_permission(
  4428. Permission.ARCHIVES_READ_ALL,
  4429. Permission.ARCHIVES_READ_OWN,
  4430. )
  4431. ),
  4432. printer_scope: PrinterScope = RequestPrinterScope,
  4433. ):
  4434. """Get available plates from a multi-plate 3MF archive.
  4435. Returns a list of plates with their index, name, thumbnail availability,
  4436. and filament requirements. For single-plate exports, returns a single plate.
  4437. """
  4438. import re
  4439. import defusedxml.ElementTree as ET
  4440. user, can_read_all = auth_result
  4441. service = ArchiveService(db)
  4442. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  4443. file_path = settings.base_dir / archive.file_path
  4444. if not file_path.is_file():
  4445. raise HTTPException(404, "Archive file not found")
  4446. plates = []
  4447. # Initialize so the `has_gcode = bool(gcode_files)` after the try/except
  4448. # never raises NameError when the archive isn't a valid zip (e.g. plain
  4449. # .gcode file from a sliced-archive flow that didn't request 3MF output).
  4450. gcode_files: list[str] = []
  4451. # Printer / process preset names the 3MF was prepared with — used by the
  4452. # SliceModal to default its dropdowns (#1325).
  4453. embedded_presets: dict[str, str | None] = {"printer": None, "process": None}
  4454. # Process settings the designer changed away from the stock preset (#2622),
  4455. # offered in the SliceModal for a cross-printer re-slice. Same payload the
  4456. # library plates endpoint returns — SliceModal reads one shape for both.
  4457. design_overrides: list[dict] = []
  4458. try:
  4459. with zipfile.ZipFile(file_path, "r") as zf:
  4460. namelist = zf.namelist()
  4461. embedded_presets = extract_embedded_presets_from_3mf(zf)
  4462. if _PROJECT_SETTINGS_PATH in namelist:
  4463. try:
  4464. design_overrides = [
  4465. o._asdict()
  4466. for o in overrides_from_config(json.loads(zf.read(_PROJECT_SETTINGS_PATH).decode("utf-8")))
  4467. ]
  4468. except (ValueError, OSError, KeyError):
  4469. design_overrides = []
  4470. # Find all plate gcode files to determine available plates
  4471. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  4472. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  4473. plate_indices: list[int] = []
  4474. if gcode_files:
  4475. # Extract plate indices from gcode filenames
  4476. for gf in gcode_files:
  4477. # "Metadata/plate_5.gcode" -> 5
  4478. try:
  4479. # Remove "Metadata/plate_" and ".gcode"
  4480. plate_str = gf[15:-6]
  4481. plate_indices.append(int(plate_str))
  4482. except ValueError:
  4483. pass # Skip gcode file with non-numeric plate index
  4484. else:
  4485. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  4486. plate_png_files = [
  4487. n
  4488. for n in namelist
  4489. if n.startswith("Metadata/plate_")
  4490. and n.endswith(".png")
  4491. and "_small" not in n
  4492. and "no_light" not in n
  4493. ]
  4494. plate_name_candidates = plate_json_files + plate_png_files
  4495. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  4496. seen_indices: set[int] = set()
  4497. for name in plate_name_candidates:
  4498. match = plate_re.match(name)
  4499. if match:
  4500. try:
  4501. index = int(match.group(1))
  4502. except ValueError:
  4503. continue
  4504. if index in seen_indices:
  4505. continue
  4506. seen_indices.add(index)
  4507. plate_indices.append(index)
  4508. if not plate_indices:
  4509. # No plate metadata found
  4510. return {
  4511. "archive_id": archive_id,
  4512. "filename": archive.filename,
  4513. "plates": [],
  4514. "is_multi_plate": False,
  4515. }
  4516. plate_indices.sort()
  4517. # Parse model_settings.config for plate names + object assignments
  4518. # Plate names are stored with plater_id and plater_name keys
  4519. plate_names = {} # plater_id -> name
  4520. plate_object_ids: dict[int, list[str]] = {}
  4521. object_names_by_id: dict[str, str] = {}
  4522. if "Metadata/model_settings.config" in namelist:
  4523. try:
  4524. model_content = zf.read("Metadata/model_settings.config").decode()
  4525. model_root = ET.fromstring(model_content)
  4526. # Build object ID -> name map
  4527. for obj_elem in model_root.findall(".//object"):
  4528. obj_id = obj_elem.get("id")
  4529. if not obj_id:
  4530. continue
  4531. name_meta = obj_elem.find("metadata[@key='name']")
  4532. obj_name = name_meta.get("value") if name_meta is not None else None
  4533. if obj_name:
  4534. object_names_by_id[obj_id] = obj_name
  4535. for plate_elem in model_root.findall(".//plate"):
  4536. plater_id = None
  4537. plater_name = None
  4538. for meta in plate_elem.findall("metadata"):
  4539. key = meta.get("key")
  4540. value = meta.get("value")
  4541. if key == "plater_id" and value:
  4542. try:
  4543. plater_id = int(value)
  4544. except ValueError:
  4545. pass # Skip plate with non-numeric plater_id
  4546. elif key == "plater_name" and value:
  4547. plater_name = value.strip()
  4548. if plater_id is not None and plater_name:
  4549. plate_names[plater_id] = plater_name
  4550. if plater_id is not None:
  4551. for instance_elem in plate_elem.findall("model_instance"):
  4552. for inst_meta in instance_elem.findall("metadata"):
  4553. if inst_meta.get("key") == "object_id":
  4554. obj_id = inst_meta.get("value")
  4555. if not obj_id:
  4556. continue
  4557. plate_object_ids.setdefault(plater_id, [])
  4558. if obj_id not in plate_object_ids[plater_id]:
  4559. plate_object_ids[plater_id].append(obj_id)
  4560. except Exception:
  4561. pass # model_settings.config parsing is optional
  4562. # Parse slice_info.config for plate metadata
  4563. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  4564. if "Metadata/slice_info.config" in namelist:
  4565. content = zf.read("Metadata/slice_info.config").decode()
  4566. root = ET.fromstring(content)
  4567. for plate_elem in root.findall(".//plate"):
  4568. plate_info = {
  4569. "filaments": [],
  4570. "prediction": None,
  4571. "weight": None,
  4572. "name": None,
  4573. "objects": [],
  4574. "bed_type": None,
  4575. }
  4576. # Get plate index from metadata
  4577. plate_index = None
  4578. for meta in plate_elem.findall("metadata"):
  4579. key = meta.get("key")
  4580. value = meta.get("value")
  4581. if key == "index" and value:
  4582. try:
  4583. plate_index = int(value)
  4584. except ValueError:
  4585. pass # Skip plate with non-numeric index
  4586. elif key == "prediction" and value:
  4587. try:
  4588. plate_info["prediction"] = int(value)
  4589. except ValueError:
  4590. pass # Skip non-numeric print time prediction
  4591. elif key == "weight" and value:
  4592. try:
  4593. plate_info["weight"] = float(value)
  4594. except ValueError:
  4595. pass # Skip non-numeric filament weight
  4596. elif key == "curr_bed_type" and value:
  4597. # Per-plate bed type so the PrintModal can show the
  4598. # right plate alongside each option (#1281).
  4599. plate_info["bed_type"] = value.strip()
  4600. # Get filaments used in this plate
  4601. for filament_elem in plate_elem.findall("filament"):
  4602. filament_id = filament_elem.get("id")
  4603. filament_type = filament_elem.get("type", "")
  4604. filament_color = filament_elem.get("color", "")
  4605. used_g = filament_elem.get("used_g", "0")
  4606. used_m = filament_elem.get("used_m", "0")
  4607. try:
  4608. used_grams = float(used_g)
  4609. except (ValueError, TypeError):
  4610. used_grams = 0
  4611. if used_grams > 0 and filament_id:
  4612. plate_info["filaments"].append(
  4613. {
  4614. "slot_id": int(filament_id),
  4615. "type": filament_type,
  4616. "color": filament_color,
  4617. # The preset the slicer assigned (GFA01, ...): names the product line
  4618. "tray_info_idx": filament_elem.get("tray_info_idx", "") or "",
  4619. "used_grams": round(used_grams, 1),
  4620. "used_meters": float(used_m) if used_m else 0,
  4621. }
  4622. )
  4623. # Sort filaments by slot ID
  4624. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  4625. # Collect all object names on this plate
  4626. for obj_elem in plate_elem.findall("object"):
  4627. obj_name = obj_elem.get("name")
  4628. if obj_name and obj_name not in plate_info["objects"]:
  4629. plate_info["objects"].append(obj_name)
  4630. # Set plate name: prefer custom name from model_settings.config,
  4631. # fall back to first object name if no custom name was set
  4632. if plate_index is not None:
  4633. custom_name = plate_names.get(plate_index)
  4634. if custom_name:
  4635. plate_info["name"] = custom_name
  4636. else:
  4637. # Fall back to first object name as hint
  4638. if plate_info["objects"]:
  4639. plate_info["name"] = plate_info["objects"][0]
  4640. plate_metadata[plate_index] = plate_info
  4641. # Parse plate_*.json for object lists when slice_info is missing
  4642. plate_json_objects: dict[int, list[str]] = {}
  4643. for name in namelist:
  4644. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  4645. if not match:
  4646. continue
  4647. try:
  4648. plate_index = int(match.group(1))
  4649. except ValueError:
  4650. continue
  4651. try:
  4652. payload = json.loads(zf.read(name).decode())
  4653. bbox_objects = payload.get("bbox_objects", [])
  4654. names = []
  4655. for obj in bbox_objects:
  4656. obj_name = obj.get("name") if isinstance(obj, dict) else None
  4657. if obj_name and obj_name not in names:
  4658. names.append(obj_name)
  4659. if names:
  4660. plate_json_objects[plate_index] = names
  4661. except Exception:
  4662. continue
  4663. # Build plate list
  4664. for idx in plate_indices:
  4665. meta = plate_metadata.get(idx, {})
  4666. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  4667. objects = meta.get("objects", [])
  4668. if not objects:
  4669. objects = plate_json_objects.get(idx, [])
  4670. if not objects and plate_object_ids.get(idx):
  4671. objects = [
  4672. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  4673. ]
  4674. plate_name = meta.get("name")
  4675. if not plate_name:
  4676. plate_name = plate_names.get(idx)
  4677. if not plate_name and objects:
  4678. plate_name = objects[0]
  4679. plates.append(
  4680. {
  4681. "index": idx,
  4682. "name": plate_name,
  4683. "objects": objects,
  4684. "object_count": len(objects),
  4685. "has_thumbnail": has_thumbnail,
  4686. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  4687. if has_thumbnail
  4688. else None,
  4689. "print_time_seconds": meta.get("prediction"),
  4690. "filament_used_grams": meta.get("weight"),
  4691. "filaments": meta.get("filaments", []),
  4692. "bed_type": meta.get("bed_type"),
  4693. }
  4694. )
  4695. except Exception as e:
  4696. logger.warning("Failed to parse plates from archive %s: %s", archive_id, e)
  4697. # Has gcode iff the plate list was built from .gcode filenames (as opposed
  4698. # to the JSON/PNG fallback for source-only 3MF projects). Callers that need
  4699. # to preview gcode — the viewer, skip-objects — can gate on this instead of
  4700. # 404-ing on every plate request.
  4701. has_gcode = bool(gcode_files)
  4702. return {
  4703. "archive_id": archive_id,
  4704. "filename": archive.filename,
  4705. "plates": plates,
  4706. "is_multi_plate": len(plates) > 1,
  4707. "has_gcode": has_gcode,
  4708. "embedded_printer": embedded_presets["printer"],
  4709. "embedded_process": embedded_presets["process"],
  4710. "design_overrides": design_overrides,
  4711. }
  4712. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  4713. async def get_plate_thumbnail(
  4714. archive_id: int,
  4715. plate_index: int,
  4716. db: AsyncSession = Depends(get_db, scope="function"),
  4717. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4718. require_media_token_ownership(
  4719. Permission.ARCHIVES_READ_ALL,
  4720. Permission.ARCHIVES_READ_OWN,
  4721. )
  4722. ),
  4723. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  4724. ):
  4725. """Get the thumbnail image for a specific plate.
  4726. Requires a media token query param (?token=xxx) when auth is enabled, and
  4727. returns 404 for an archive the caller may not read (#3025).
  4728. """
  4729. user, can_read_all = auth_result
  4730. service = ArchiveService(db)
  4731. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  4732. file_path = settings.base_dir / archive.file_path
  4733. if not file_path.is_file():
  4734. raise HTTPException(404, "Archive file not found")
  4735. try:
  4736. with zipfile.ZipFile(file_path, "r") as zf:
  4737. thumb_path = f"Metadata/plate_{plate_index}.png"
  4738. if thumb_path in zf.namelist():
  4739. data = zf.read(thumb_path)
  4740. return Response(content=data, media_type="image/png")
  4741. except Exception:
  4742. pass # Fall through to 404 if archive is unreadable or thumbnail missing
  4743. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  4744. async def _try_preview_slice_filaments(
  4745. db: AsyncSession,
  4746. *,
  4747. kind: str,
  4748. source_id: int,
  4749. plate_id: int,
  4750. file_path: Path,
  4751. request_id: str | None = None,
  4752. ) -> list[dict] | None:
  4753. """Run a preview slice via the user's configured sidecar so the filament
  4754. list endpoint can return real per-plate filaments for unsliced project
  4755. files. Returns ``None`` on any failure — the caller falls back to the
  4756. painted-face heuristic. ``request_id`` flows through to the sidecar
  4757. for live progress on the SliceModal's inline spinner + toast.
  4758. """
  4759. from backend.app.api.routes.settings import get_setting
  4760. from backend.app.services.slice_preview import get_preview_filaments
  4761. from backend.app.services.slicer_api import get_stall_timeout_seconds
  4762. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  4763. if preferred == "orcaslicer":
  4764. configured = await get_setting(db, "orcaslicer_api_url")
  4765. api_url = (configured or settings.slicer_api_url).strip()
  4766. elif preferred == "bambu_studio":
  4767. configured = await get_setting(db, "bambu_studio_api_url")
  4768. api_url = (configured or settings.bambu_studio_api_url).strip()
  4769. else:
  4770. return None
  4771. if not api_url:
  4772. return None
  4773. try:
  4774. file_bytes = file_path.read_bytes()
  4775. except OSError:
  4776. return None
  4777. return await get_preview_filaments(
  4778. kind=kind,
  4779. source_id=source_id,
  4780. plate_id=plate_id,
  4781. file_bytes=file_bytes,
  4782. file_name=file_path.name,
  4783. api_url=api_url,
  4784. request_id=request_id,
  4785. timeout_seconds=await get_stall_timeout_seconds(db),
  4786. )
  4787. @router.get("/{archive_id}/filament-requirements")
  4788. async def get_filament_requirements(
  4789. archive_id: int,
  4790. plate_id: int | None = None,
  4791. request_id: str | None = None,
  4792. full_slots: bool = False,
  4793. db: AsyncSession = Depends(get_db, scope="function"),
  4794. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4795. require_ownership_permission(
  4796. Permission.ARCHIVES_READ_ALL,
  4797. Permission.ARCHIVES_READ_OWN,
  4798. )
  4799. ),
  4800. printer_scope: PrinterScope = RequestPrinterScope,
  4801. ):
  4802. """Get filament requirements from the archived 3MF file.
  4803. Returns the filaments used in this print with their slot IDs, types, colors,
  4804. and usage amounts. This can be compared with current AMS state before reprinting.
  4805. Args:
  4806. archive_id: The archive ID
  4807. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  4808. """
  4809. import defusedxml.ElementTree as ET
  4810. user, can_read_all = auth_result
  4811. service = ArchiveService(db)
  4812. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  4813. file_path = settings.base_dir / archive.file_path
  4814. if not file_path.is_file():
  4815. raise HTTPException(404, "Archive file not found")
  4816. filaments = []
  4817. try:
  4818. with zipfile.ZipFile(file_path, "r") as zf:
  4819. # Parse slice_info.config for filament requirements
  4820. if "Metadata/slice_info.config" in zf.namelist():
  4821. content = zf.read("Metadata/slice_info.config").decode()
  4822. root = ET.fromstring(content)
  4823. # If plate_id is specified, find filaments for that specific plate
  4824. if plate_id is not None:
  4825. # Find the plate element with matching index
  4826. for plate_elem in root.findall(".//plate"):
  4827. plate_index = None
  4828. for meta in plate_elem.findall("metadata"):
  4829. if meta.get("key") == "index":
  4830. try:
  4831. plate_index = int(meta.get("value", "0"))
  4832. except ValueError:
  4833. pass # Skip plate with non-numeric index metadata
  4834. break
  4835. if plate_index == plate_id:
  4836. # Extract filaments from this plate element
  4837. for filament_elem in plate_elem.findall("filament"):
  4838. filament_id = filament_elem.get("id")
  4839. filament_type = filament_elem.get("type", "")
  4840. filament_color = filament_elem.get("color", "")
  4841. used_g = filament_elem.get("used_g", "0")
  4842. used_m = filament_elem.get("used_m", "0")
  4843. tray_info_idx = filament_elem.get("tray_info_idx", "")
  4844. try:
  4845. used_grams = float(used_g)
  4846. except (ValueError, TypeError):
  4847. used_grams = 0
  4848. if used_grams > 0 and filament_id:
  4849. filaments.append(
  4850. {
  4851. "slot_id": int(filament_id),
  4852. "type": filament_type,
  4853. "color": filament_color,
  4854. "used_grams": round(used_grams, 1),
  4855. "used_meters": float(used_m) if used_m else 0,
  4856. "tray_info_idx": tray_info_idx,
  4857. "used_in_plate": True,
  4858. }
  4859. )
  4860. break
  4861. else:
  4862. # No plate_id specified - extract all filaments with used_g > 0
  4863. # This is the legacy behavior for single-plate files
  4864. for filament_elem in root.findall(".//filament"):
  4865. filament_id = filament_elem.get("id")
  4866. filament_type = filament_elem.get("type", "")
  4867. filament_color = filament_elem.get("color", "")
  4868. used_g = filament_elem.get("used_g", "0")
  4869. used_m = filament_elem.get("used_m", "0")
  4870. tray_info_idx = filament_elem.get("tray_info_idx", "")
  4871. # Only include filaments that are actually used
  4872. try:
  4873. used_grams = float(used_g)
  4874. except (ValueError, TypeError):
  4875. used_grams = 0
  4876. if used_grams > 0 and filament_id:
  4877. filaments.append(
  4878. {
  4879. "slot_id": int(filament_id),
  4880. "type": filament_type,
  4881. "color": filament_color,
  4882. "used_grams": round(used_grams, 1),
  4883. "used_meters": float(used_m) if used_m else 0,
  4884. "tray_info_idx": tray_info_idx,
  4885. "used_in_plate": True,
  4886. }
  4887. )
  4888. # Re-slicing a source that already carries slice_info (#2712).
  4889. # See library.py for the full rationale: the slice modal's list is
  4890. # positional, so a source using only slot 4 must still present
  4891. # four slots or the pick lands on slot 1. The print path keeps the
  4892. # used-only list it depends on.
  4893. if full_slots and filaments:
  4894. filaments = expand_to_project_slots(zf, filaments)
  4895. # Unsliced project files: see library.py for full rationale.
  4896. # Return the FULL project_settings.config slot list with a
  4897. # used_in_plate flag derived from the preview slice; the
  4898. # CLI needs every slot pre-filled to avoid silent default
  4899. # substitution.
  4900. if not filaments:
  4901. project_filaments = extract_project_filaments_from_3mf(zf)
  4902. used_slot_ids: set[int] = set()
  4903. if project_filaments and plate_id is not None:
  4904. preview = await _try_preview_slice_filaments(
  4905. db,
  4906. kind="archive",
  4907. source_id=archive_id,
  4908. plate_id=plate_id,
  4909. file_path=file_path,
  4910. request_id=request_id,
  4911. )
  4912. if preview is not None:
  4913. used_slot_ids = {f["slot_id"] for f in preview}
  4914. fallback_all_used = not used_slot_ids
  4915. for f in project_filaments:
  4916. f["used_in_plate"] = fallback_all_used or f["slot_id"] in used_slot_ids
  4917. filaments = project_filaments
  4918. # Sort by slot ID
  4919. filaments.sort(key=lambda x: x["slot_id"])
  4920. # Enrich with nozzle mapping for dual-nozzle printers
  4921. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf, plate_id=plate_id)
  4922. if nozzle_mapping:
  4923. for filament in filaments:
  4924. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  4925. # Nozzle-rack machines (#1784): the print dialog offers a rack
  4926. # position per filament group, which needs the group table as well
  4927. # as the carriage above.
  4928. annotate_rack_groups(filaments, file_path, plate_id)
  4929. except Exception as e:
  4930. logger.warning("Failed to parse filament requirements from archive %s: %s", archive_id, e)
  4931. return {
  4932. "archive_id": archive_id,
  4933. "filename": archive.filename,
  4934. "plate_id": plate_id,
  4935. "filaments": filaments,
  4936. }
  4937. @router.post("/{archive_id}/slice", status_code=202)
  4938. async def slice_archive(
  4939. archive_id: int,
  4940. request: SliceRequest,
  4941. db: AsyncSession = Depends(get_db, scope="function"),
  4942. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  4943. printer_scope: PrinterScope = RequestPrinterScope,
  4944. actor: User | ApiKeyActor | None = RequestActor,
  4945. ):
  4946. """Enqueue a slice job for an archive's source. Returns 202 + job_id;
  4947. the slice runs in the background, the caller polls `GET /slice-jobs/{id}`.
  4948. Source preference: ``source_3mf_path`` (the un-sliced project file the
  4949. user originally sent to slice) → ``file_path`` (the sliced 3MF/gcode that
  4950. actually printed).
  4951. """
  4952. from backend.app.api.routes.library import guard_nozzle_class_reslice, slice_and_persist_as_archive
  4953. from backend.app.core.database import async_session
  4954. from backend.app.services.slice_dispatch import (
  4955. http_exception_to_job_error,
  4956. slice_dispatch,
  4957. )
  4958. archive = await db.get(PrintArchive, archive_id)
  4959. # Per-row ownership gate — mirror the archive read routes. LIBRARY_UPLOAD
  4960. # alone let a READ_OWN caller slice another user's archive by raw id even
  4961. # though GET on that id returned 404. An API key is checked as its owner
  4962. # (RequestActor); only auth off keeps can_read_all=True.
  4963. can_read_all = actor is None or actor.has_permission(Permission.ARCHIVES_READ_ALL.value)
  4964. archive = await _ensure_archive_visible(archive, actor, can_read_all, printer_scope)
  4965. # The re-sliced copy belongs to the caller and can be queued as their own,
  4966. # so slicing an archive needs the same right as printing it again.
  4967. from backend.app.api.routes.print_queue import _assert_can_queue_archive
  4968. await _assert_can_queue_archive(archive, actor, printer_scope)
  4969. src_relative = archive.source_3mf_path or archive.file_path
  4970. if not src_relative:
  4971. raise HTTPException(
  4972. status_code=400,
  4973. detail="Archive has no source file to slice",
  4974. )
  4975. src_path = (
  4976. Path(settings.base_dir) / src_relative
  4977. ) # 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
  4978. if not src_path.exists():
  4979. raise HTTPException(status_code=404, detail="Archive source file missing on disk")
  4980. raw_filename = archive.filename or src_path.name
  4981. src_lower = raw_filename.lower()
  4982. if not (
  4983. src_lower.endswith(".stl")
  4984. or src_lower.endswith(".3mf")
  4985. or src_lower.endswith(".step")
  4986. or src_lower.endswith(".stp")
  4987. ):
  4988. raise HTTPException(
  4989. status_code=400,
  4990. detail="Archive's source file must be STL, 3MF, or STEP to slice",
  4991. )
  4992. # Match the library route: derive the sliced output's filename from
  4993. # `print_name` when set, so the new archive row's display name lines
  4994. # up with the source's display.
  4995. src_ext = Path(raw_filename).suffix.lower() or ".3mf"
  4996. src_filename = (
  4997. f"{archive.print_name.strip()}{src_ext}" if archive.print_name and archive.print_name.strip() else raw_filename
  4998. )
  4999. model_bytes = src_path.read_bytes()
  5000. archive_id_local = archive.id
  5001. user_id = current_user.id if current_user else None
  5002. # The new archive is its owner's also when a key, which resolves no cloud
  5003. # presets, slices it.
  5004. owner_id = user_id if user_id is not None else (actor.id if isinstance(actor, ApiKeyActor) else None)
  5005. # Block a cross-nozzle-class re-slice (single-nozzle <-> H2D) up front —
  5006. # BambuStudio's multi-extruder validator would otherwise reject it with a
  5007. # cryptic error. No-op for same-class or un-sliced sources.
  5008. await guard_nozzle_class_reslice(db, current_user, request, archive.sliced_for_model)
  5009. async def _run(job_id: int):
  5010. async with async_session() as task_db:
  5011. # Re-fetch the source archive on the background-task session.
  5012. src_archive = await task_db.get(PrintArchive, archive_id_local)
  5013. if src_archive is None:
  5014. raise http_exception_to_job_error(
  5015. HTTPException(status_code=404, detail="Archive disappeared during slice")
  5016. )
  5017. try:
  5018. response = await slice_and_persist_as_archive(
  5019. task_db,
  5020. model_bytes=model_bytes,
  5021. model_filename=src_filename,
  5022. request=request,
  5023. source_archive=src_archive,
  5024. current_user_id=user_id,
  5025. job_id=job_id,
  5026. owner_id=owner_id,
  5027. )
  5028. except HTTPException as exc:
  5029. raise http_exception_to_job_error(exc) from exc
  5030. return response.model_dump()
  5031. job = await slice_dispatch.enqueue(
  5032. kind="archive",
  5033. source_id=archive.id,
  5034. source_name=archive.print_name or archive.filename or f"archive {archive.id}",
  5035. owner_id=owner_id,
  5036. run=_run,
  5037. )
  5038. return {
  5039. "job_id": job.id,
  5040. "status": job.status,
  5041. "status_url": f"/api/v1/slice-jobs/{job.id}",
  5042. }
  5043. @router.post("/{archive_id}/reprint")
  5044. async def reprint_archive(
  5045. archive_id: int,
  5046. printer_id: int,
  5047. # SECURITY.md SEC-AUTH-1: every route either has an explicit auth dep or
  5048. # is in the route-auth-coverage allowlist. Gating the deprecation stub on
  5049. # QUEUE_CREATE matches the replacement route (POST /queue/) and means
  5050. # anonymous callers bounce at auth instead of seeing the deprecation
  5051. # message — leaking "this route exists" to unauthenticated callers is
  5052. # exactly the shape the backstop guards against.
  5053. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  5054. ):
  5055. """Legacy direct reprint endpoint. Use POST /queue/ instead."""
  5056. logger.warning(
  5057. "Gone API used: POST /archives/%s/reprint?printer_id=%s; use POST /queue/ instead",
  5058. archive_id,
  5059. printer_id,
  5060. )
  5061. raise HTTPException(
  5062. status_code=410,
  5063. detail="Direct archive reprint has been removed. Create a print queue item with POST /queue/.",
  5064. )
  5065. # =============================================================================
  5066. # Project Page API
  5067. # =============================================================================
  5068. @router.get("/{archive_id}/project-page")
  5069. async def get_project_page(
  5070. archive_id: int,
  5071. db: AsyncSession = Depends(get_db, scope="function"),
  5072. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5073. require_ownership_permission(
  5074. Permission.ARCHIVES_READ_ALL,
  5075. Permission.ARCHIVES_READ_OWN,
  5076. )
  5077. ),
  5078. printer_scope: PrinterScope = RequestPrinterScope,
  5079. ):
  5080. """Get the project page data from the 3MF file."""
  5081. from backend.app.schemas.archive import ProjectPageResponse
  5082. from backend.app.services.archive import ProjectPageParser
  5083. user, can_read_all = auth_result
  5084. service = ArchiveService(db)
  5085. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  5086. file_path = settings.base_dir / archive.file_path
  5087. if not file_path.is_file():
  5088. raise HTTPException(404, "Archive file not found")
  5089. parser = ProjectPageParser(file_path)
  5090. data = parser.parse(archive_id)
  5091. return ProjectPageResponse(**data)
  5092. @router.patch("/{archive_id}/project-page")
  5093. async def update_project_page(
  5094. archive_id: int,
  5095. update_data: dict,
  5096. db: AsyncSession = Depends(get_db, scope="function"),
  5097. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5098. require_ownership_permission(
  5099. Permission.ARCHIVES_UPDATE_ALL,
  5100. Permission.ARCHIVES_UPDATE_OWN,
  5101. )
  5102. ),
  5103. printer_scope: PrinterScope = RequestPrinterScope,
  5104. ):
  5105. """Update project page metadata in the 3MF file."""
  5106. from backend.app.services.archive import ProjectPageParser
  5107. user, can_modify_all = auth_result
  5108. service = ArchiveService(db)
  5109. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_modify_all, printer_scope)
  5110. # It rewrites the archive's 3MF, the file of every print of it.
  5111. await _ensure_whole_archive(archive, printer_scope)
  5112. file_path = settings.base_dir / archive.file_path
  5113. if not file_path.is_file():
  5114. raise HTTPException(404, "Archive file not found")
  5115. parser = ProjectPageParser(file_path)
  5116. success = parser.update_metadata(update_data)
  5117. if not success:
  5118. raise HTTPException(500, "Failed to update project page")
  5119. # Return updated data
  5120. data = parser.parse(archive_id)
  5121. return data
  5122. @router.get("/{archive_id}/project-image/{image_path:path}")
  5123. async def get_project_image(
  5124. archive_id: int,
  5125. image_path: str,
  5126. db: AsyncSession = Depends(get_db, scope="function"),
  5127. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5128. require_media_token_ownership(
  5129. Permission.ARCHIVES_READ_ALL,
  5130. Permission.ARCHIVES_READ_OWN,
  5131. )
  5132. ),
  5133. printer_scope: PrinterScope = MediaOrRequestPrinterScope,
  5134. ):
  5135. """Get an image from the 3MF project page.
  5136. Requires a media token query param (?token=xxx) when auth is enabled, and
  5137. returns 404 for an archive the caller may not read (#3025).
  5138. """
  5139. user, can_read_all = auth_result
  5140. from backend.app.services.archive import ProjectPageParser
  5141. service = ArchiveService(db)
  5142. archive = await _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all, printer_scope)
  5143. file_path = settings.base_dir / archive.file_path
  5144. if not file_path.is_file():
  5145. raise HTTPException(404, "Archive file not found")
  5146. parser = ProjectPageParser(file_path)
  5147. result = parser.get_image(image_path)
  5148. if not result:
  5149. raise HTTPException(404, "Image not found in 3MF file")
  5150. image_data, content_type = result
  5151. return Response(
  5152. content=image_data,
  5153. media_type=content_type,
  5154. headers={"Cache-Control": "max-age=3600"},
  5155. )
  5156. # =============================================================================
  5157. # Source 3MF API (Original Project Files)
  5158. # =============================================================================
  5159. def _resolve_source_3mf_path(archive: PrintArchive, source_filename: str) -> Path:
  5160. """Resolve where to write a source 3MF for ``archive``.
  5161. Normal archives nest the source under ``<archive_file_dir>/source/``.
  5162. "Fallback" archives (created in main.py when MQTT reports a print start
  5163. but Bambuddy never saw the source 3MF — cloud / Handy / pre-existing
  5164. SD-card prints) carry ``file_path=""``. Joining that with ``base_dir``
  5165. via the ``/`` operator silently yields ``base_dir`` itself, whose parent
  5166. is ``base_dir.parent`` — which sent the upload to ``/app/source/`` and
  5167. raised a 500 on the final ``relative_to`` (#1531). Fallback archives
  5168. now land under ``<base_dir>/archive/no_source/<archive_id>/`` instead,
  5169. which stays inside the data volume and remains addressable by every
  5170. read site that does ``base_dir / archive.source_3mf_path``.
  5171. The resolved directory is asserted to be inside ``base_dir`` even when
  5172. ``archive.file_path`` is populated, so a row corrupted by an old import
  5173. or manual SQL edit fails with a clear 500 instead of writing outside
  5174. the data volume.
  5175. """
  5176. if archive.file_path:
  5177. archive_file = settings.base_dir / archive.file_path
  5178. source_dir = archive_file.parent / "source"
  5179. else:
  5180. source_dir = settings.base_dir / "archive" / "no_source" / str(archive.id)
  5181. # Containment check via resolve() — catches absolute file_path, `..`
  5182. # traversal, and any other shape that escapes the data volume — but we
  5183. # return the *literal* source_dir below. Resolving the returned path
  5184. # would canonicalise away a symlinked DATA_DIR (legitimate on TrueNAS /
  5185. # QNAP / Synology storage pools, and any `-v /symlink:/app/data`
  5186. # mount), which would then make the caller's
  5187. # ``source_path.relative_to(settings.base_dir)`` raise because the
  5188. # left side is canonical and the right is the symlink path.
  5189. try:
  5190. source_dir.resolve().relative_to(settings.base_dir.resolve())
  5191. except ValueError as exc:
  5192. raise HTTPException(
  5193. 500,
  5194. f"Archive {archive.id} resolves to a path outside the data directory; cannot attach source.",
  5195. ) from exc
  5196. source_dir.mkdir(parents=True, exist_ok=True)
  5197. return (
  5198. source_dir / source_filename
  5199. ) # SEC-PATH-OK: callers pass _safe_filename(...) basename-stripped; source_dir resolve+relative_to checked above
  5200. @router.post("/{archive_id}/source")
  5201. async def upload_source_3mf(
  5202. archive_id: int,
  5203. file: UploadFile = File(...),
  5204. db: AsyncSession = Depends(get_db, scope="function"),
  5205. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5206. require_ownership_permission(
  5207. Permission.ARCHIVES_UPDATE_ALL,
  5208. Permission.ARCHIVES_UPDATE_OWN,
  5209. )
  5210. ),
  5211. printer_scope: PrinterScope = RequestPrinterScope,
  5212. ):
  5213. """Upload the original source 3MF project file for an archive."""
  5214. user, can_modify_all = auth_result
  5215. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5216. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  5217. await _ensure_whole_archive(archive, printer_scope)
  5218. if not file.filename or not file.filename.endswith(".3mf"):
  5219. raise HTTPException(400, "File must be a .3mf file")
  5220. # Save the source 3MF file - preserve original filename, strip directory components
  5221. source_filename = _safe_filename(file.filename)
  5222. source_path = _resolve_source_3mf_path(archive, source_filename)
  5223. # Delete old source file if exists
  5224. if archive.source_3mf_path:
  5225. old_source_path = settings.base_dir / archive.source_3mf_path
  5226. if old_source_path.exists():
  5227. old_source_path.unlink()
  5228. content = await file.read()
  5229. # #1401: validate zip header on source 3MF uploads too — source files
  5230. # are uploaded for reprint and slicing, so an invalid one breaks the
  5231. # same downstream paths as a bad sliced file.
  5232. from backend.app.api.routes.library import validate_print_file_upload
  5233. validate_print_file_upload(file.filename, content)
  5234. source_path.write_bytes(content)
  5235. # Update archive with source path (relative to base_dir)
  5236. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  5237. await db.commit()
  5238. await db.refresh(archive)
  5239. return {
  5240. "status": "uploaded",
  5241. "source_3mf_path": archive.source_3mf_path,
  5242. "filename": source_filename,
  5243. }
  5244. @router.get("/{archive_id}/source")
  5245. async def download_source_3mf(
  5246. archive_id: int,
  5247. db: AsyncSession = Depends(get_db, scope="function"),
  5248. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5249. require_ownership_permission(
  5250. Permission.ARCHIVES_READ_ALL,
  5251. Permission.ARCHIVES_READ_OWN,
  5252. )
  5253. ),
  5254. printer_scope: PrinterScope = RequestPrinterScope,
  5255. ):
  5256. """Download the source 3MF project file."""
  5257. user, can_read_all = auth_result
  5258. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5259. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all, printer_scope)
  5260. if not archive.source_3mf_path:
  5261. raise HTTPException(404, "No source 3MF attached to this archive")
  5262. source_path = settings.base_dir / archive.source_3mf_path
  5263. if not source_path.exists():
  5264. raise HTTPException(404, "Source 3MF file not found on disk")
  5265. # Use the actual filename from the path
  5266. filename = source_path.name
  5267. return FileResponse(
  5268. path=source_path,
  5269. filename=filename,
  5270. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  5271. )
  5272. @router.get("/{archive_id}/source/{filename}")
  5273. async def download_source_3mf_for_slicer(
  5274. archive_id: int,
  5275. filename: str,
  5276. db: AsyncSession = Depends(get_db, scope="function"),
  5277. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5278. require_ownership_permission(
  5279. Permission.ARCHIVES_READ_ALL,
  5280. Permission.ARCHIVES_READ_OWN,
  5281. )
  5282. ),
  5283. printer_scope: PrinterScope = RequestPrinterScope,
  5284. ):
  5285. """Download source 3MF with filename in URL."""
  5286. user, can_read_all = auth_result
  5287. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5288. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all, printer_scope)
  5289. if not archive.source_3mf_path:
  5290. raise HTTPException(404, "No source 3MF attached to this archive")
  5291. source_path = settings.base_dir / archive.source_3mf_path
  5292. if not source_path.exists():
  5293. raise HTTPException(404, "Source 3MF file not found on disk")
  5294. return FileResponse(
  5295. path=source_path,
  5296. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  5297. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  5298. )
  5299. @router.post("/{archive_id}/source-slicer-token")
  5300. async def create_source_slicer_token(
  5301. archive_id: int,
  5302. db: AsyncSession = Depends(get_db, scope="function"),
  5303. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5304. require_ownership_permission(
  5305. Permission.ARCHIVES_READ_ALL,
  5306. Permission.ARCHIVES_READ_OWN,
  5307. )
  5308. ),
  5309. printer_scope: PrinterScope = RequestPrinterScope,
  5310. ):
  5311. """Create a short-lived download token for opening source 3MF in slicer."""
  5312. from backend.app.core.auth import create_slicer_download_token
  5313. user, can_read_all = auth_result
  5314. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5315. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all, printer_scope)
  5316. if not archive.source_3mf_path:
  5317. raise HTTPException(404, "No source 3MF attached to this archive")
  5318. token = await create_slicer_download_token("source", archive_id)
  5319. return {"token": token}
  5320. @router.get("/{archive_id}/source-dl/{token}/{filename}")
  5321. async def download_source_3mf_for_slicer_with_token(
  5322. archive_id: int,
  5323. token: str,
  5324. filename: str,
  5325. db: AsyncSession = Depends(get_db, scope="function"),
  5326. ):
  5327. """Download source 3MF using a slicer download token.
  5328. Token-authenticated (no auth headers needed). The token is short-lived and
  5329. archive-bound, created by POST /{archive_id}/source-slicer-token, and
  5330. redeemable for the rest of its TTL rather than exactly once (#3029).
  5331. """
  5332. from backend.app.core.auth import verify_slicer_download_token
  5333. if not await verify_slicer_download_token(token, "source", archive_id, single_use=False):
  5334. raise HTTPException(403, "Invalid or expired download token")
  5335. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5336. archive = result.scalar_one_or_none()
  5337. if not archive:
  5338. raise HTTPException(404, "Archive not found")
  5339. if not archive.source_3mf_path:
  5340. raise HTTPException(404, "No source 3MF attached to this archive")
  5341. source_path = settings.base_dir / archive.source_3mf_path
  5342. if not source_path.exists():
  5343. raise HTTPException(404, "Source 3MF file not found on disk")
  5344. return FileResponse(
  5345. path=source_path,
  5346. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  5347. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  5348. )
  5349. @router.post("/upload-source")
  5350. async def upload_source_3mf_by_name(
  5351. file: UploadFile = File(...),
  5352. print_name: str = Query(None, description="Match archive by print name"),
  5353. db: AsyncSession = Depends(get_db, scope="function"),
  5354. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  5355. printer_scope: PrinterScope = RequestPrinterScope,
  5356. ):
  5357. """Upload source 3MF and match to archive by print name.
  5358. This endpoint is designed for slicer post-processing scripts.
  5359. It finds the most recent archive matching the print name and attaches the source.
  5360. """
  5361. if not file.filename or not file.filename.endswith(".3mf"):
  5362. raise HTTPException(400, "File must be a .3mf file")
  5363. safe_filename = _safe_filename(file.filename)
  5364. # Derive print name from filename if not provided
  5365. if not print_name:
  5366. # Remove .3mf extension and common suffixes
  5367. print_name = safe_filename.rsplit(".3mf", 1)[0]
  5368. # Remove _source suffix if present
  5369. if print_name.endswith("_source"):
  5370. print_name = print_name[:-7]
  5371. # Find matching archive - try exact match first, then fuzzy
  5372. # Only an archive every print of which is on the caller's printers: its
  5373. # file is the whole archive's (archive redesign).
  5374. visible = _visible_archive_clauses(None, True, printer_scope, whole=True)
  5375. result = await db.execute(
  5376. select(PrintArchive)
  5377. .where(PrintArchive.print_name == print_name, *visible)
  5378. .order_by(PrintArchive.created_at.desc())
  5379. .limit(1)
  5380. )
  5381. archive = result.scalar_one_or_none()
  5382. if not archive:
  5383. # Try matching filename without .gcode.3mf
  5384. result = await db.execute(
  5385. select(PrintArchive)
  5386. .where(PrintArchive.filename.like(f"{print_name}%"), *visible)
  5387. .order_by(PrintArchive.created_at.desc())
  5388. .limit(1)
  5389. )
  5390. archive = result.scalar_one_or_none()
  5391. if not archive:
  5392. # Try case-insensitive partial match on print_name
  5393. result = await db.execute(
  5394. select(PrintArchive)
  5395. .where(PrintArchive.print_name.ilike(f"%{print_name}%"), *visible)
  5396. .order_by(PrintArchive.created_at.desc())
  5397. .limit(1)
  5398. )
  5399. archive = result.scalar_one_or_none()
  5400. if not archive:
  5401. raise HTTPException(404, f"No archive found matching '{print_name}'")
  5402. # Save the source 3MF file - preserve original filename, strip directory components
  5403. source_filename = safe_filename
  5404. source_path = _resolve_source_3mf_path(archive, source_filename)
  5405. # Delete old source file if exists
  5406. if archive.source_3mf_path:
  5407. old_source_path = settings.base_dir / archive.source_3mf_path
  5408. if old_source_path.exists():
  5409. old_source_path.unlink()
  5410. content = await file.read()
  5411. # #1401: same zip-header check as the other upload routes — the
  5412. # match-by-name endpoint is used by slicer post-processing scripts,
  5413. # so a misconfigured script is exactly how a bad 3MF would slip in.
  5414. from backend.app.api.routes.library import validate_print_file_upload
  5415. validate_print_file_upload(file.filename, content)
  5416. source_path.write_bytes(content)
  5417. # Update archive with source path
  5418. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  5419. await db.commit()
  5420. await db.refresh(archive)
  5421. return {
  5422. "status": "uploaded",
  5423. "archive_id": archive.id,
  5424. "archive_name": archive.print_name or archive.filename,
  5425. "source_3mf_path": archive.source_3mf_path,
  5426. "filename": source_filename,
  5427. }
  5428. @router.delete("/{archive_id}/source")
  5429. async def delete_source_3mf(
  5430. archive_id: int,
  5431. db: AsyncSession = Depends(get_db, scope="function"),
  5432. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5433. require_ownership_permission(
  5434. Permission.ARCHIVES_DELETE_ALL,
  5435. Permission.ARCHIVES_DELETE_OWN,
  5436. )
  5437. ),
  5438. printer_scope: PrinterScope = RequestPrinterScope,
  5439. ):
  5440. """Delete the source 3MF project file from an archive."""
  5441. user, can_modify_all = auth_result
  5442. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5443. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  5444. await _ensure_whole_archive(archive, printer_scope)
  5445. if not archive.source_3mf_path:
  5446. raise HTTPException(404, "No source 3MF attached to this archive")
  5447. # Delete the file
  5448. source_path = settings.base_dir / archive.source_3mf_path
  5449. if source_path.exists():
  5450. source_path.unlink()
  5451. # Clear the path in database
  5452. archive.source_3mf_path = None
  5453. await db.commit()
  5454. return {"status": "deleted"}
  5455. # =============================================================================
  5456. # F3D API (Fusion 360 Design Files)
  5457. # =============================================================================
  5458. @router.post("/{archive_id}/f3d")
  5459. async def upload_f3d(
  5460. archive_id: int,
  5461. file: UploadFile = File(...),
  5462. db: AsyncSession = Depends(get_db, scope="function"),
  5463. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5464. require_ownership_permission(
  5465. Permission.ARCHIVES_UPDATE_ALL,
  5466. Permission.ARCHIVES_UPDATE_OWN,
  5467. )
  5468. ),
  5469. printer_scope: PrinterScope = RequestPrinterScope,
  5470. ):
  5471. """Upload a Fusion 360 design file for an archive."""
  5472. user, can_modify_all = auth_result
  5473. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5474. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  5475. await _ensure_whole_archive(archive, printer_scope)
  5476. if not file.filename or not file.filename.endswith(".f3d"):
  5477. raise HTTPException(400, "File must be a .f3d file")
  5478. # Get archive directory and create f3d subdirectory
  5479. file_path = settings.base_dir / archive.file_path
  5480. archive_dir = file_path.parent
  5481. f3d_dir = archive_dir / "f3d"
  5482. f3d_dir.mkdir(exist_ok=True)
  5483. # Delete old F3D file if exists
  5484. if archive.f3d_path:
  5485. old_f3d_path = settings.base_dir / archive.f3d_path
  5486. if old_f3d_path.exists():
  5487. old_f3d_path.unlink()
  5488. # Save the F3D file - preserve original filename, strip directory components
  5489. f3d_filename = _safe_filename(file.filename)
  5490. f3d_path = f3d_dir / f3d_filename # SEC-PATH-OK: f3d_filename = _safe_filename(...) basename-stripped above
  5491. content = await file.read()
  5492. f3d_path.write_bytes(content)
  5493. # Update archive with F3D path (relative to base_dir)
  5494. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  5495. await db.commit()
  5496. await db.refresh(archive)
  5497. return {
  5498. "status": "uploaded",
  5499. "f3d_path": archive.f3d_path,
  5500. "filename": f3d_filename,
  5501. }
  5502. @router.get("/{archive_id}/f3d")
  5503. async def download_f3d(
  5504. archive_id: int,
  5505. db: AsyncSession = Depends(get_db, scope="function"),
  5506. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5507. require_ownership_permission(
  5508. Permission.ARCHIVES_READ_ALL,
  5509. Permission.ARCHIVES_READ_OWN,
  5510. )
  5511. ),
  5512. printer_scope: PrinterScope = RequestPrinterScope,
  5513. ):
  5514. """Download the Fusion 360 design file."""
  5515. user, can_read_all = auth_result
  5516. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5517. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all, printer_scope)
  5518. if not archive.f3d_path:
  5519. raise HTTPException(404, "No F3D file attached to this archive")
  5520. f3d_path = settings.base_dir / archive.f3d_path
  5521. if not f3d_path.exists():
  5522. raise HTTPException(404, "F3D file not found on disk")
  5523. # Use the actual filename from the path
  5524. filename = f3d_path.name
  5525. return FileResponse(
  5526. path=f3d_path,
  5527. filename=filename,
  5528. media_type="application/octet-stream",
  5529. )
  5530. @router.delete("/{archive_id}/f3d")
  5531. async def delete_f3d(
  5532. archive_id: int,
  5533. db: AsyncSession = Depends(get_db, scope="function"),
  5534. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5535. require_ownership_permission(
  5536. Permission.ARCHIVES_DELETE_ALL,
  5537. Permission.ARCHIVES_DELETE_OWN,
  5538. )
  5539. ),
  5540. printer_scope: PrinterScope = RequestPrinterScope,
  5541. ):
  5542. """Delete the Fusion 360 design file from an archive."""
  5543. user, can_modify_all = auth_result
  5544. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5545. archive = await _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all, printer_scope)
  5546. await _ensure_whole_archive(archive, printer_scope)
  5547. if not archive.f3d_path:
  5548. raise HTTPException(404, "No F3D file attached to this archive")
  5549. # Delete the file
  5550. f3d_path = settings.base_dir / archive.f3d_path
  5551. if f3d_path.exists():
  5552. f3d_path.unlink()
  5553. # Clear the path in database
  5554. archive.f3d_path = None
  5555. await db.commit()
  5556. return {"status": "deleted"}