archives.py 270 KB

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