archives.py 269 KB

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