library.py 282 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354
  1. """API routes for File Manager (Library) functionality."""
  2. import asyncio
  3. import base64
  4. import binascii
  5. import contextlib
  6. import hashlib
  7. import json
  8. import logging
  9. import os
  10. import re
  11. import shutil
  12. import uuid
  13. import zipfile
  14. from concurrent.futures import ThreadPoolExecutor
  15. from datetime import datetime, timezone
  16. from pathlib import Path
  17. from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile
  18. from fastapi.responses import FileResponse as FastAPIFileResponse
  19. from sqlalchemy import delete, distinct, func, select, update
  20. from sqlalchemy.ext.asyncio import AsyncSession
  21. from sqlalchemy.orm import selectinload
  22. from backend.app.api.routes.cloud import resolve_api_key_cloud_owner
  23. from backend.app.api.routes.library_variants import normalize_model_name, resolve_variant_model
  24. from backend.app.api.routes.print_queue import _extract_filament_types_from_3mf, printed_plate_of_multi_plate_file
  25. from backend.app.core.auth import (
  26. ApiKeyActor,
  27. QueueReviewRequired,
  28. RequestActor,
  29. RequestPrinterScope,
  30. require_actor_still_exists,
  31. require_media_token_ownership,
  32. require_ownership_permission,
  33. require_permission_if_auth_enabled,
  34. )
  35. from backend.app.core.config import settings as app_settings
  36. from backend.app.core.database import async_session, get_db
  37. from backend.app.core.permissions import Permission
  38. from backend.app.core.printer_scope import PrinterScope, ensure_model_target_allowed
  39. from backend.app.core.row_visibility import visible_row_clauses
  40. from backend.app.core.tasks import spawn_background_task
  41. from backend.app.models.archive import PrintArchive
  42. from backend.app.models.library import LibraryFile, LibraryFileTag, LibraryFolder
  43. from backend.app.models.print_queue import PrintQueueItem
  44. from backend.app.models.printer import Printer
  45. from backend.app.models.project import Project
  46. from backend.app.models.user import User
  47. from backend.app.schemas.library import (
  48. AddToQueueError,
  49. AddToQueueRequest,
  50. AddToQueueResponse,
  51. AddToQueueResult,
  52. BatchThumbnailRequest,
  53. BatchThumbnailResponse,
  54. BatchThumbnailResult,
  55. BulkDeleteRequest,
  56. BulkDeleteResponse,
  57. ClientThumbnailResponse,
  58. CombineFilesRequest,
  59. ExternalFolderCreate,
  60. FileDuplicate,
  61. FileListResponse,
  62. FileMoveRequest,
  63. FileResponse as FileResponseSchema,
  64. FileUpdate,
  65. FileUploadResponse,
  66. FolderCreate,
  67. FolderReadmeResponse,
  68. FolderResponse,
  69. FolderTreeItem,
  70. FolderUpdate,
  71. TagSummary,
  72. ZipExtractError,
  73. ZipExtractResponse,
  74. ZipExtractResult,
  75. )
  76. from backend.app.schemas.slicer import SliceRequest, SliceResponse
  77. from backend.app.services.archive import ThreeMFParser, estimate_filament_cost
  78. from backend.app.services.design_settings import (
  79. DesignOverride,
  80. apply_design_overrides,
  81. extract_design_process_overrides,
  82. overrides_from_config,
  83. )
  84. from backend.app.services.filament_requirements import annotate_rack_groups
  85. from backend.app.services.library_folder_access import (
  86. FolderIndex,
  87. can_rename_folder,
  88. can_write_folder,
  89. folder_delete_blocker,
  90. get_visible_folder,
  91. get_writable_folder,
  92. load_folder_index,
  93. sees_all_folders,
  94. visible_folder_ids,
  95. )
  96. from backend.app.services.pdf_thumbnail import generate_pdf_thumbnail
  97. from backend.app.services.plate_thumbnail import inject_plate_thumbnails_if_missing
  98. from backend.app.services.print_confirmation import confirm_outcome_for_new_queue_item
  99. from backend.app.services.print_defaults import default_print_options
  100. from backend.app.services.process_overrides import apply_process_overrides
  101. from backend.app.services.queue_announcements import announce_queue_jobs_added
  102. from backend.app.services.slice_output_check import (
  103. missing_start_gcode_message,
  104. start_gcode_is_missing,
  105. unresolved_filament_message,
  106. unresolved_filament_slots,
  107. )
  108. from backend.app.services.stl_thumbnail import MIN_USABLE_STL_BYTES, generate_stl_thumbnail
  109. from backend.app.utils.filename import (
  110. MAX_FILENAME_BYTES,
  111. InvalidFilenameError,
  112. safe_path_component,
  113. validate_print_filename,
  114. )
  115. from backend.app.utils.library_paths import library_photos_dir, remove_library_photos_dir
  116. from backend.app.utils.printer_models import is_gcode_compatible
  117. from backend.app.utils.safe_path import PathTraversalError, assert_under, safe_join_under
  118. from backend.app.utils.threemf_tools import (
  119. carries_gcode,
  120. default_plate_gcode_name,
  121. expand_to_project_slots,
  122. extract_embedded_presets_from_3mf,
  123. extract_nozzle_mapping_from_3mf,
  124. extract_project_filaments_from_3mf,
  125. sanitize_project_settings_sentinels,
  126. select_plate_gcode_name,
  127. supports_enabled_in_config,
  128. )
  129. logger = logging.getLogger(__name__)
  130. router = APIRouter(prefix="/library", tags=["library"])
  131. # Path of the embedded slicer config inside a BambuStudio/OrcaSlicer 3MF.
  132. _PROJECT_SETTINGS_PATH = "Metadata/project_settings.config"
  133. def _ensure_library_file_visible(
  134. library_file: LibraryFile | None,
  135. user: User | ApiKeyActor | None,
  136. can_read_all: bool,
  137. ) -> LibraryFile:
  138. """Per-file visibility gate for ownership-scoped LIBRARY reads (#1726-adjacent).
  139. Mirrors archives.py::_ensure_archive_visible — single enforcement point so a
  140. less-guarded sibling route can't accidentally leak a row. Same shape:
  141. - Missing / soft-deleted → 404 (not 403, to avoid id-enumeration leaks).
  142. - ``can_read_all`` true (LIBRARY_READ_ALL or auth disabled) → file returned.
  143. - ``can_read_all`` false and ``created_by_id != user.id`` → 404.
  144. - Ownerless files (``created_by_id is None``) require ALL — fail-closed.
  145. """
  146. if library_file is None or getattr(library_file, "deleted_at", None) is not None:
  147. raise HTTPException(404, "File not found")
  148. if can_read_all:
  149. return library_file
  150. if user is None:
  151. raise HTTPException(404, "File not found")
  152. if library_file.created_by_id is None or library_file.created_by_id != user.id:
  153. raise HTTPException(404, "File not found")
  154. return library_file
  155. async def _linkable_archives(
  156. db: AsyncSession, archive_ids, printer_scope: PrinterScope, user: User | ApiKeyActor | None
  157. ) -> dict[int, str | None]:
  158. """Print names of the archives among ``archive_ids`` the caller sees in the archives.
  159. Live archives on the caller's printers, their own unless they see
  160. everyone's. A folder's link to any other archive reads as no link, and
  161. linking one answers as for a missing archive.
  162. """
  163. ids = {i for i in archive_ids if i}
  164. visible = visible_row_clauses(
  165. PrintArchive, printer_scope, user, Permission.ARCHIVES_READ_ALL, Permission.ARCHIVES_READ_OWN
  166. )
  167. if not ids or visible is None:
  168. return {}
  169. query = select(PrintArchive.id, PrintArchive.print_name).where(
  170. PrintArchive.id.in_(ids), PrintArchive.deleted_at.is_(None), *visible
  171. )
  172. return dict((await db.execute(query)).all())
  173. def _archive_link(archive_id: int | None, archives: dict[int, str | None]) -> dict:
  174. if archive_id not in archives:
  175. return {"archive_id": None, "archive_name": None}
  176. return {"archive_id": archive_id, "archive_name": archives[archive_id]}
  177. def _own_files_filter(user: User | ApiKeyActor | None) -> list:
  178. """Extra WHERE terms that count only ``user``'s files, for a read_own user.
  179. Folder file counts and activity times must not reveal files the user
  180. can't open (#3201).
  181. """
  182. if sees_all_folders(user):
  183. return []
  184. return [LibraryFile.created_by_id == user.id]
  185. async def _load_index(db: AsyncSession, user: User | ApiKeyActor | None) -> FolderIndex:
  186. """The folder index a response for ``user`` needs (#3201).
  187. Who owns which file is needed only to decide what a read_own user sees
  188. and what a delete_own user may delete. Everyone else skips that scan of
  189. the files table, which the folder tree would otherwise pay on every load.
  190. """
  191. needs_files = user is not None and not (
  192. sees_all_folders(user) and user.has_permission(Permission.LIBRARY_DELETE_ALL.value)
  193. )
  194. return await load_folder_index(db, with_files=needs_files)
  195. def _folder_access_fields(index: FolderIndex, folder: LibraryFolder, user: User | ApiKeyActor | None) -> dict:
  196. """The ownership fields of a folder response, for the user asking (#3201)."""
  197. return {
  198. "created_by_id": folder.created_by_id,
  199. "shared": bool(folder.shared),
  200. "can_write": can_write_folder(folder, user),
  201. "can_rename": can_rename_folder(folder, user),
  202. "can_delete": folder_delete_blocker(index, folder, user) is None,
  203. }
  204. def get_library_dir() -> Path:
  205. """Get the library storage directory."""
  206. base_dir = Path(app_settings.archive_dir)
  207. library_dir = base_dir / "library"
  208. library_dir.mkdir(parents=True, exist_ok=True)
  209. return library_dir
  210. def get_library_files_dir() -> Path:
  211. """Get the directory for library files."""
  212. files_dir = get_library_dir() / "files"
  213. files_dir.mkdir(parents=True, exist_ok=True)
  214. return files_dir
  215. def classify_file_type(filename: str, file_path: Path | str | None = None) -> str:
  216. """Return the canonical ``LibraryFile.file_type`` for *filename*.
  217. Compound extensions are preserved — a `.gcode.3mf` file (a sliced
  218. output, still a 3MF zip on disk) is classified ``gcode.3mf`` rather
  219. than ``3mf``. Pre-#1600 this was only done in the external-scan
  220. path; the upload / ZIP-extract / in-process paths all stripped to
  221. the trailing extension and stored ``3mf``, so the FE had to accept
  222. both. Unified here so every ingest path stores the same value and
  223. downstream gates (gcode download, file-type filter, thumbnail
  224. extraction) only need to handle one canonical name per file family.
  225. Files with no extension classify as ``unknown``.
  226. Pass ``file_path`` and a ``.3mf`` is judged on what the zip actually holds
  227. rather than on its name (#2993). The name is not evidence: a plate exported
  228. from Studio or a print dispatched through the cloud reaches the archive as
  229. ``Foo.3mf``, G-code and all, and downloading that and re-importing it used
  230. to land a fully printable file in the library as a source-only project. The
  231. file is not opened when the name already settles it, so the common case
  232. still costs nothing.
  233. """
  234. lower = filename.lower()
  235. if lower.endswith(".gcode.3mf"):
  236. return "gcode.3mf"
  237. ext = os.path.splitext(lower)[1]
  238. file_type = ext[1:] if ext else "unknown"
  239. if file_type == "3mf" and file_path is not None and carries_gcode(file_path):
  240. return "gcode.3mf"
  241. return file_type
  242. def get_library_thumbnails_dir() -> Path:
  243. """Get the directory for library thumbnails."""
  244. thumbnails_dir = get_library_dir() / "thumbnails"
  245. thumbnails_dir.mkdir(parents=True, exist_ok=True)
  246. return thumbnails_dir
  247. def to_relative_path(absolute_path: Path | str) -> str:
  248. """Convert an absolute path to a path relative to base_dir for storage."""
  249. if not absolute_path:
  250. return ""
  251. abs_path = Path(absolute_path)
  252. base_dir = Path(app_settings.base_dir)
  253. try:
  254. return str(abs_path.relative_to(base_dir))
  255. except ValueError:
  256. # Path is not under base_dir, return as-is (shouldn't happen normally)
  257. return str(abs_path)
  258. def to_absolute_path(relative_path: str | None) -> Path | None:
  259. """Convert a relative path (from database) to an absolute path for file operations."""
  260. if not relative_path:
  261. return None
  262. path = Path(relative_path)
  263. # Handle already-absolute paths verbatim (backwards compatibility during migration).
  264. # Legacy DB rows may store absolute paths that predate the base_dir layout; the
  265. # traversal guard below only applies to relative paths coming from user input.
  266. if path.is_absolute():
  267. return path.resolve()
  268. base = Path(app_settings.base_dir).resolve()
  269. resolved = (base / relative_path).resolve()
  270. # Guard against path traversal — resolved path must stay inside base_dir.
  271. # Use is_relative_to() to avoid the /data/app vs /data/app_evil prefix confusion
  272. # that a plain startswith(str(base)) check would miss.
  273. if not resolved.is_relative_to(base):
  274. raise ValueError(f"Path escapes base directory: {relative_path!r}")
  275. return resolved
  276. def calculate_file_hash(file_path: Path) -> str:
  277. """Calculate SHA256 hash of a file."""
  278. sha256_hash = hashlib.sha256()
  279. with open(file_path, "rb") as f:
  280. for byte_block in iter(lambda: f.read(4096), b""):
  281. sha256_hash.update(byte_block)
  282. return sha256_hash.hexdigest()
  283. def validate_print_file_upload(filename: str, content: bytes) -> None:
  284. """Reject obviously-unprintable uploads early so the printer doesn't see them (#1401).
  285. Bambu printers in network mode only parse ``.gcode.3mf`` zip containers
  286. — raw ``.gcode`` and corrupt/non-zip ``.3mf`` uploads cascade into a
  287. confusing "Printing stopped because the printer was unable to parse the
  288. 3mf file" rejection 30 seconds after the user clicks Print. The
  289. the queue dispatch path appends ``.3mf`` to a raw-gcode filename when
  290. constructing the FTP destination, which is how the printer ends up with a
  291. file named ``.gcode.3mf`` whose body is raw gcode — exactly the shape that
  292. triggers the firmware parse failure. Catching both classes here gives an
  293. actionable error at the
  294. upload itself.
  295. Compares the filename suffix rather than ``os.path.splitext`` because
  296. compound extensions like ``.gcode.3mf`` show up as just ``.3mf`` after
  297. ``splitext`` — same content validation needs to fire for both
  298. single-``.3mf`` and ``.gcode.3mf`` uploads.
  299. Raises ``HTTPException(400, ...)`` with a human-readable message on
  300. rejection; returns ``None`` for valid (or irrelevant — e.g. STL,
  301. image) uploads.
  302. """
  303. lower_filename = filename.lower()
  304. is_3mf_upload = lower_filename.endswith(".3mf")
  305. is_raw_gcode_upload = lower_filename.endswith(".gcode") and not lower_filename.endswith(".gcode.3mf")
  306. if is_raw_gcode_upload:
  307. raise HTTPException(
  308. status_code=400,
  309. detail=(
  310. "Raw .gcode files can't be printed on Bambu printers in network mode — "
  311. "they need a .gcode.3mf zip container (gcode plus metadata). Re-export from "
  312. "your slicer and make sure the file ends in '.gcode.3mf', not just '.gcode'. "
  313. "If your OS hides extensions, double-check the file with the extension visible."
  314. ),
  315. )
  316. if is_3mf_upload and not content.startswith(b"PK\x03\x04"):
  317. raise HTTPException(
  318. status_code=400,
  319. detail=(
  320. "This .3mf file isn't a valid ZIP container. 3MF files are ZIP archives — "
  321. "either the file is corrupted or it's raw gcode renamed to .3mf. Re-export "
  322. "from your slicer using its 'Export Plate Sliced File' action."
  323. ),
  324. )
  325. def _resolve_upload_destination(target_folder: LibraryFolder | None, filename: str) -> tuple[Path, bool]:
  326. """Resolve the on-disk destination for an uploaded file.
  327. Non-external target: returns ``(<library_files_dir>/<uuid><ext>, False)``.
  328. Writable external target: writes to ``<external_path>/<filename>``
  329. (preserves the real filename so the file is recognisable on the mount);
  330. returns ``(dest, True)``. Raises ``HTTPException`` for read-only external
  331. folders (403), missing/inaccessible/non-writable external paths (400), and
  332. filename collisions on the external mount (409). See #1112 — previously
  333. uploads to writable external folders were silently misrouted to the
  334. internal library dir.
  335. """
  336. if target_folder is not None and target_folder.is_external:
  337. if target_folder.external_readonly:
  338. raise HTTPException(status_code=403, detail="Cannot upload to a read-only external folder")
  339. if not target_folder.external_path:
  340. raise HTTPException(status_code=400, detail="External folder has no configured path")
  341. ext_dir = Path(target_folder.external_path)
  342. if not ext_dir.exists() or not ext_dir.is_dir():
  343. raise HTTPException(
  344. status_code=400,
  345. detail=f"External path is not accessible: {target_folder.external_path}",
  346. )
  347. if not os.access(ext_dir, os.W_OK):
  348. raise HTTPException(
  349. status_code=400,
  350. detail=f"External path is not writable: {target_folder.external_path}",
  351. )
  352. # Guard against path-traversal via a pathological filename — join then
  353. # verify the resolved destination is still inside the external dir.
  354. dest = (ext_dir / filename).resolve() # SEC-PATH-OK: resolve + relative_to containment check on next line
  355. try:
  356. dest.relative_to(ext_dir.resolve())
  357. except ValueError:
  358. raise HTTPException(status_code=400, detail="Invalid filename")
  359. if dest.exists():
  360. raise HTTPException(
  361. status_code=409,
  362. detail=f"A file named {filename!r} already exists in the external folder",
  363. )
  364. return dest, True
  365. ext = os.path.splitext(filename)[1].lower()
  366. return get_library_files_dir() / f"{uuid.uuid4().hex}{ext}", False
  367. def _unique_external_name(ext_dir: Path, filename: str) -> str:
  368. """Return ``filename``, or the first free ``<stem> (n)<suffix>`` variant.
  369. Splits on the *compound* extension so re-slicing ``Bidoof.3mf`` yields
  370. ``Bidoof (2).gcode.3mf`` rather than ``Bidoof.gcode (2).3mf``.
  371. Uploads answer a name collision with a 409, which is right for a file the
  372. user just chose to send. A slice is not that: re-slicing the same source
  373. with different settings is routine, and the second run has already spent
  374. minutes of CPU by the time the name is known -- refusing to store it would
  375. throw that away. Overwriting is worse still, since the target is somebody's
  376. NAS and the file being replaced may not even be ours.
  377. """
  378. stem = filename[: -len(".gcode.3mf")] if filename.endswith(".gcode.3mf") else Path(filename).stem
  379. suffix = ".gcode.3mf" if filename.endswith(".gcode.3mf") else Path(filename).suffix
  380. candidate = filename
  381. counter = 2
  382. # Bounded: a directory holding 999 re-slices of one model is pathological,
  383. # and an unbounded loop here would hang the request on a mount that lies
  384. # about exists() (some SMB shares do under contention).
  385. #
  386. # safe_join_under rather than `ext_dir / candidate`: `filename` derives
  387. # from a name read out of a 3MF, so the very first probe must not be able
  388. # to stat its way outside the mount. It raises PathTraversalError, which
  389. # the caller turns into a managed-storage fallback.
  390. while safe_join_under(ext_dir, candidate, http=False).exists() and counter < 1000:
  391. candidate = f"{stem} ({counter}){suffix}"
  392. counter += 1
  393. return candidate
  394. def _resolve_slice_destination(target_folder: LibraryFolder | None, out_filename: str) -> tuple[Path, bool, str | None]:
  395. """Resolve where a slice result should be written.
  396. Returns ``(path, is_external, fallback_reason)``. ``fallback_reason`` is
  397. ``None`` on the normal paths and otherwise names why an external folder
  398. could not receive the file, so the caller can tell the user instead of
  399. quietly filing it elsewhere.
  400. Slicing a file that lives on an external mount used to store the output in
  401. the managed library dir unconditionally, while giving the new row the
  402. external folder's ``folder_id`` (#2810). The file therefore appeared in the
  403. right folder in the UI and never arrived on the share, which is the one
  404. place the user was looking -- and made it un-reproducible from the web UI
  405. alone. Uploads learned this in #1112 (``_resolve_upload_destination``) and
  406. moves in its follow-up (``_move_file_bytes``); slicing was the last write
  407. path still assuming managed storage.
  408. Unlike uploads, a failure here does not raise. The bytes exist and cost
  409. real time to produce, so an unwritable target falls back to managed storage
  410. with a reason attached rather than discarding the slice.
  411. """
  412. if target_folder is None or not target_folder.is_external:
  413. return get_library_files_dir() / f"{uuid.uuid4().hex}.gcode.3mf", False, None
  414. if target_folder.external_readonly:
  415. return get_library_files_dir() / f"{uuid.uuid4().hex}.gcode.3mf", False, "external_readonly"
  416. if not target_folder.external_path:
  417. return get_library_files_dir() / f"{uuid.uuid4().hex}.gcode.3mf", False, "external_no_path"
  418. ext_dir = Path(target_folder.external_path)
  419. if not ext_dir.exists() or not ext_dir.is_dir():
  420. return get_library_files_dir() / f"{uuid.uuid4().hex}.gcode.3mf", False, "external_unreachable"
  421. if not os.access(ext_dir, os.W_OK):
  422. return get_library_files_dir() / f"{uuid.uuid4().hex}.gcode.3mf", False, "external_not_writable"
  423. try:
  424. dest = safe_join_under(ext_dir, _unique_external_name(ext_dir, out_filename), http=False)
  425. except PathTraversalError:
  426. # The source filename reached us from a 3MF on disk, so this is
  427. # defensive rather than expected -- but a name that escapes the mount
  428. # must land in managed storage, never outside it.
  429. return get_library_files_dir() / f"{uuid.uuid4().hex}.gcode.3mf", False, "external_invalid_name"
  430. return dest, True, None
  431. async def _folder_tree_file_ids(db: AsyncSession, folder_id: int) -> list[int]:
  432. """Every ``LibraryFile`` id under ``folder_id``, at any depth.
  433. Deleting a folder cascades to its whole subtree, so anything that has to be
  434. released before that delete (queue items, cross-model candidates) needs the
  435. subtree, not just the folder's own files.
  436. Trashed rows are included deliberately: they are still real rows and the
  437. cascade takes them too.
  438. """
  439. file_ids: list[int] = []
  440. pending = [folder_id]
  441. # The API refuses to make a folder its own ancestor, so a loop here would
  442. # mean the table is already corrupt -- but this walk runs inside a delete
  443. # request, and hanging one is worse than the cost of a set.
  444. seen: set[int] = set()
  445. while pending:
  446. current = pending.pop()
  447. if current in seen:
  448. continue
  449. seen.add(current)
  450. file_ids.extend(
  451. (await db.execute(select(LibraryFile.id).where(LibraryFile.folder_id == current))).scalars().all()
  452. )
  453. pending.extend(
  454. (await db.execute(select(LibraryFolder.id).where(LibraryFolder.parent_id == current))).scalars().all()
  455. )
  456. return file_ids
  457. def _stored_file_path(abs_path: Path, is_external: bool) -> str:
  458. """Produce the value to persist in ``LibraryFile.file_path``.
  459. External files store the absolute mount path directly (same as scan does),
  460. so ``to_absolute_path`` round-trips through its ``is_absolute()`` fast
  461. path. Managed files store a path relative to ``base_dir`` for portability.
  462. """
  463. return str(abs_path) if is_external else to_relative_path(abs_path)
  464. class _MoveSkip(Exception):
  465. """Signalled by ``_move_file_bytes`` to skip a file with a user-visible reason.
  466. Carries an optional `code` for machine-friendly grouping (the
  467. front-end can localise it) and a fallback English `reason` for logs.
  468. """
  469. def __init__(self, code: str, reason: str):
  470. super().__init__(reason)
  471. self.code = code
  472. self.reason = reason
  473. def _resolve_source_disk_path(file: LibraryFile) -> Path | None:
  474. """Return the absolute on-disk path for an existing LibraryFile, or None
  475. if it can't be located (legacy DB row, deleted file, etc.)."""
  476. if file.is_external:
  477. return Path(file.file_path) if file.file_path else None
  478. return to_absolute_path(file.file_path)
  479. def _move_file_bytes(file: LibraryFile, target_folder: LibraryFolder | None) -> str:
  480. """Physically relocate `file`'s bytes to match `target_folder`.
  481. Used by the move endpoint when source/target straddle the
  482. managed↔external boundary (#1112 follow-up — the prior implementation
  483. updated the DB row's ``folder_id`` but never moved the bytes, so a
  484. file moved to an external SMB folder showed up in Bambuddy's UI but
  485. not on the NAS).
  486. Returns the new ``file_path`` value to persist (relative for managed
  487. targets, absolute for external targets — matches the upload + scan
  488. paths). Raises ``_MoveSkip`` for any condition that would make the
  489. move unsafe (target unwritable, filename collision, source missing).
  490. The copy-then-unlink ordering means a partial copy followed by a
  491. failed unlink leaves both the source and the dest on disk — better
  492. than the symmetric "rename or move" which would lose the source if
  493. the target write didn't complete on a flaky mount. The DB row stays
  494. pointed at the source until the caller commits the new ``file_path``.
  495. """
  496. src = _resolve_source_disk_path(file)
  497. if not src or not src.exists():
  498. raise _MoveSkip("source_missing", "source file missing on disk")
  499. target_is_external = target_folder is not None and target_folder.is_external
  500. if target_is_external:
  501. if target_folder.external_readonly:
  502. # Already blocked at top level, but defence-in-depth.
  503. raise _MoveSkip("target_readonly", "target external folder is read-only")
  504. if not target_folder.external_path:
  505. raise _MoveSkip("target_misconfigured", "target external folder has no path")
  506. ext_dir = Path(target_folder.external_path)
  507. if not ext_dir.exists() or not ext_dir.is_dir():
  508. raise _MoveSkip("target_inaccessible", f"target path not accessible: {ext_dir}")
  509. if not os.access(ext_dir, os.W_OK):
  510. raise _MoveSkip("target_unwritable", f"target path not writable: {ext_dir}")
  511. dest = (ext_dir / file.filename).resolve() # SEC-PATH-OK: resolve + relative_to containment check on next line
  512. try:
  513. dest.relative_to(ext_dir.resolve())
  514. except ValueError:
  515. raise _MoveSkip("invalid_filename", f"unsafe filename: {file.filename!r}") from None
  516. if dest.exists():
  517. raise _MoveSkip("name_collision", f"a file named {file.filename!r} already exists in target")
  518. try:
  519. shutil.copy2(src, dest)
  520. except OSError as e:
  521. # Clean up partial dest so a retry can succeed.
  522. with contextlib.suppress(OSError):
  523. dest.unlink(missing_ok=True)
  524. raise _MoveSkip("copy_failed", f"copy failed: {e}") from e
  525. else:
  526. # → managed (root or non-external folder): generate a fresh UUID
  527. # filename in the internal store so we don't collide with another
  528. # file that happens to share `filename`.
  529. ext = src.suffix.lower()
  530. dest = get_library_files_dir() / f"{uuid.uuid4().hex}{ext}"
  531. try:
  532. shutil.copy2(src, dest)
  533. except OSError as e:
  534. with contextlib.suppress(OSError):
  535. dest.unlink(missing_ok=True)
  536. raise _MoveSkip("copy_failed", f"copy failed: {e}") from e
  537. # Copy succeeded — unlink the original. A failure here leaves an
  538. # orphan on disk but the DB row is consistent against the new dest.
  539. try:
  540. src.unlink(missing_ok=True)
  541. except OSError as e:
  542. logger.warning(
  543. "Move: copied %s → %s but couldn't remove source: %s",
  544. src,
  545. dest,
  546. e,
  547. )
  548. return _stored_file_path(dest, is_external=target_is_external)
  549. def _clean_3mf_metadata(obj):
  550. """Strip bytes and thumbnail-carrier keys so the payload is JSON-storable.
  551. Shared by ``upload_file`` and :func:`save_3mf_bytes_to_library` — the
  552. ``ThreeMFParser`` output embeds the thumbnail bytes under
  553. ``_thumbnail_data``/``_thumbnail_ext`` and may also include raw bytes in
  554. other fields, none of which can be JSON-encoded.
  555. """
  556. if isinstance(obj, dict):
  557. return {
  558. k: _clean_3mf_metadata(v)
  559. for k, v in obj.items()
  560. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  561. }
  562. if isinstance(obj, list):
  563. return [_clean_3mf_metadata(i) for i in obj if not isinstance(i, bytes)]
  564. if isinstance(obj, bytes):
  565. return None
  566. return obj
  567. def _read_3mf_entry(zip_path: Path, entry: str) -> bytes | None:
  568. """Return the raw bytes of an entry inside a 3MF (ZIP), or ``None`` when
  569. the file isn't a parseable zip / doesn't contain that entry / any IO
  570. error. Used to lift the source archive's per-plate render onto a
  571. re-sliced archive (#1493 follow-up) — the slicer CLI often doesn't
  572. emit a fresh ``Metadata/plate_N.png`` and the project-wide cover-art
  573. fallback in :class:`ThreeMFParser` looks unrelated to the actual slice.
  574. """
  575. try:
  576. with zipfile.ZipFile(zip_path, "r") as zf:
  577. if entry not in zf.namelist():
  578. return None
  579. return zf.read(entry)
  580. except (zipfile.BadZipFile, OSError, KeyError):
  581. return None
  582. def _without_print_name(metadata: dict | None) -> dict | None:
  583. """Drop the embedded 3MF Title (``print_name``) from library-file metadata.
  584. The 3MF ``<metadata name="Title">`` holds the in-app project title — the
  585. generic ``"Exported 3D Model"`` for a Bambu Studio "Save As", a marketing
  586. title for a MakerWorld download — never the filename the user saved as.
  587. The FileManager keys its display name, search and sort off ``print_name``,
  588. so storing it makes every card show the wrong name (#1489). A library
  589. file's display name is its filename; only ``PrintArchive`` carries a real
  590. ``print_name``. Returns the input unchanged when there's nothing to strip;
  591. otherwise a new dict (never mutates the argument).
  592. """
  593. if not metadata or "print_name" not in metadata:
  594. return metadata
  595. return {k: v for k, v in metadata.items() if k != "print_name"}
  596. async def save_3mf_bytes_to_library(
  597. db: AsyncSession,
  598. *,
  599. file_bytes: bytes,
  600. filename: str,
  601. folder_id: int | None = None,
  602. source_type: str | None = None,
  603. source_url: str | None = None,
  604. owner_id: int | None = None,
  605. dedupe_within: list | tuple | None = (),
  606. ) -> tuple[LibraryFile, bool]:
  607. """Save a fetched file into the library and return ``(library_file, was_existing)``.
  608. Used by routes that receive a file in-process rather than as a multipart
  609. upload: the MakerWorld import (3MF) and the Manyfold import (3MF, STL,
  610. STEP). Deduplicates by ``source_url`` when provided —
  611. if a LibraryFile with the same source_url already exists, the existing
  612. row is returned and the bytes are NOT re-saved (MakerWorld signed URLs
  613. change each download, so hash-based dedupe alone would miss re-imports).
  614. ``dedupe_within`` narrows the rows that count as that copy to the ones the
  615. importer may open; None imports a copy of their own regardless.
  616. Parses 3MF metadata + thumbnail the same way the multipart upload route
  617. does, via :class:`ThreeMFParser`, and renders an STL's thumbnail. Paths are stored as relative so the
  618. library is portable across installs.
  619. """
  620. # Source-URL-based dedupe: return the existing row untouched.
  621. if source_url and dedupe_within is not None:
  622. existing = await db.execute(
  623. LibraryFile.active().where(LibraryFile.source_url == source_url, *dedupe_within).limit(1)
  624. )
  625. existing_row = existing.scalar_one_or_none()
  626. if existing_row is not None:
  627. return existing_row, True
  628. # Resolve target folder so writable-external destinations land on the
  629. # mount with the real filename, instead of being silently misrouted to
  630. # the internal library dir with a UUID name (#1645). Mirrors what the
  631. # multipart-upload path has done since #1112. ``_resolve_upload_destination``
  632. # also enforces the 403 read-only / 400 unwritable / 409 collision
  633. # rejections — the makerworld route layer already pre-checks read-only,
  634. # but the helper's checks remain as defence-in-depth for any future
  635. # caller that skips that route gate.
  636. target_folder: LibraryFolder | None = None
  637. if folder_id is not None:
  638. folder_q = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  639. target_folder = folder_q.scalar_one_or_none()
  640. # Another user's copy of this very import, which the importer may not
  641. # open, may already sit on the mount under this name: theirs is stored
  642. # beside it under a free name, as a slice is. Any other file of that name
  643. # is still refused, so nothing put there outside Bambuddy is touched.
  644. if (
  645. source_url
  646. and target_folder is not None
  647. and target_folder.is_external
  648. and target_folder.external_path
  649. and Path(target_folder.external_path).is_dir()
  650. and await db.scalar(
  651. select(LibraryFile.id)
  652. .where(LibraryFile.source_url == source_url, LibraryFile.deleted_at.is_(None))
  653. .limit(1)
  654. )
  655. is not None
  656. ):
  657. with contextlib.suppress(PathTraversalError):
  658. filename = _unique_external_name(Path(target_folder.external_path), filename)
  659. file_path, is_external = _resolve_upload_destination(target_folder, filename)
  660. ext = file_path.suffix.lower() or ".3mf"
  661. with open(file_path, "wb") as fh:
  662. fh.write(file_bytes)
  663. file_hash = calculate_file_hash(file_path)
  664. # Extract metadata + thumbnail from the 3MF.
  665. metadata: dict | None = None
  666. thumbnail_path: str | None = None
  667. if ext == ".3mf":
  668. try:
  669. # Off the event loop: the parser still decompresses the whole model
  670. # entry, which for a combined plate is hundreds of MB (#3162).
  671. parser = ThreeMFParser(str(file_path))
  672. raw_metadata = await asyncio.to_thread(parser.parse)
  673. thumb_data = raw_metadata.get("_thumbnail_data")
  674. thumb_ext = raw_metadata.get("_thumbnail_ext", ".png")
  675. if thumb_data:
  676. thumbs_dir = get_library_thumbnails_dir()
  677. thumb_filename = f"{uuid.uuid4().hex}{thumb_ext}"
  678. thumb_path = thumbs_dir / thumb_filename # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + thumb_ext
  679. with open(thumb_path, "wb") as fh:
  680. fh.write(thumb_data)
  681. thumbnail_path = str(thumb_path)
  682. metadata = _clean_3mf_metadata(raw_metadata) or None
  683. except Exception as exc:
  684. # Matches the multipart upload route's behaviour — a bad 3MF should
  685. # still land in the library so the user can see / delete it rather
  686. # than failing the whole request.
  687. logger.warning("Failed to parse 3MF %s: %s", filename, exc)
  688. elif ext == ".stl":
  689. # Manyfold imports (#1471) bring STLs. Same thumbnail as the multipart
  690. # upload gives them, with the same pre-skip for stubs too small to hold
  691. # a triangle.
  692. try:
  693. if file_path.stat().st_size >= MIN_USABLE_STL_BYTES:
  694. thumbnail_path = await _render_stl_thumbnail(file_path, get_library_thumbnails_dir())
  695. except Exception as exc: # noqa: BLE001 — a thumbnail must never fail the import
  696. logger.warning("Failed to render STL thumbnail for %s: %s", filename, exc)
  697. library_file = LibraryFile(
  698. folder_id=folder_id,
  699. is_external=is_external,
  700. filename=filename,
  701. file_path=_stored_file_path(file_path, is_external),
  702. file_type=classify_file_type(filename, file_path),
  703. file_size=len(file_bytes),
  704. file_hash=file_hash,
  705. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  706. file_metadata=_without_print_name(metadata),
  707. source_type=source_type,
  708. source_url=source_url,
  709. created_by_id=owner_id,
  710. )
  711. db.add(library_file)
  712. await db.commit()
  713. await db.refresh(library_file)
  714. return library_file, False
  715. def extract_gcode_thumbnail(file_path: Path) -> bytes | None:
  716. """Extract embedded thumbnail from gcode file.
  717. Supports PrusaSlicer/BambuStudio format:
  718. ; thumbnail begin WxH SIZE
  719. ; base64data...
  720. ; thumbnail end
  721. """
  722. try:
  723. thumbnail_data = None
  724. in_thumbnail = False
  725. thumbnail_lines = []
  726. best_size = 0
  727. with open(file_path, errors="ignore") as f:
  728. # Only read first 50KB for performance (thumbnails are at the start)
  729. content = f.read(50000)
  730. for line in content.split("\n"):
  731. line = line.strip()
  732. # Check for thumbnail start
  733. if line.startswith("; thumbnail begin"):
  734. in_thumbnail = True
  735. thumbnail_lines = []
  736. # Parse dimensions: "; thumbnail begin 300x300 12345"
  737. match = re.search(r"(\d+)x(\d+)", line)
  738. if match:
  739. width = int(match.group(1))
  740. # Prefer larger thumbnails (up to 300px)
  741. if width > best_size and width <= 300:
  742. best_size = width
  743. continue
  744. # Check for thumbnail end
  745. if line.startswith("; thumbnail end"):
  746. if in_thumbnail and thumbnail_lines:
  747. try:
  748. # Decode the base64 data
  749. b64_data = "".join(thumbnail_lines)
  750. decoded = base64.b64decode(b64_data)
  751. # Only keep if this is the best size or first valid thumbnail
  752. if thumbnail_data is None or best_size > 0:
  753. thumbnail_data = decoded
  754. except (binascii.Error, ValueError):
  755. pass # Skip thumbnail with invalid base64 data
  756. in_thumbnail = False
  757. thumbnail_lines = []
  758. continue
  759. # Collect thumbnail data
  760. if in_thumbnail and line.startswith(";"):
  761. # Remove the leading "; " or ";"
  762. data_line = line[1:].strip()
  763. if data_line:
  764. thumbnail_lines.append(data_line)
  765. return thumbnail_data
  766. except Exception as e:
  767. logger.warning("Failed to extract gcode thumbnail: %s", e)
  768. return None
  769. def create_image_thumbnail(file_path: Path, thumbnails_dir: Path, max_size: int = 256) -> str | None:
  770. """Create a thumbnail from an image file.
  771. For small images, copies directly. For larger images, resizes.
  772. Returns the thumbnail path or None on failure.
  773. """
  774. try:
  775. from PIL import Image
  776. thumb_filename = f"{uuid.uuid4().hex}.png"
  777. thumb_path = thumbnails_dir / thumb_filename # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + ".png"
  778. with Image.open(file_path) as img:
  779. # Convert to RGB if necessary (for PNG with transparency, etc.)
  780. if img.mode in ("RGBA", "LA", "P"):
  781. # Create white background for transparency
  782. background = Image.new("RGB", img.size, (255, 255, 255))
  783. if img.mode == "P":
  784. img = img.convert("RGBA")
  785. background.paste(img, mask=img.split()[-1] if img.mode == "RGBA" else None)
  786. img = background
  787. elif img.mode != "RGB":
  788. img = img.convert("RGB")
  789. # Resize if larger than max_size
  790. if img.width > max_size or img.height > max_size:
  791. img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
  792. img.save(thumb_path, "PNG", optimize=True)
  793. return str(thumb_path)
  794. except ImportError:
  795. # PIL not installed, just copy the file if it's small enough
  796. logger.warning("PIL not installed, copying image as thumbnail")
  797. try:
  798. file_size = file_path.stat().st_size
  799. if file_size < 500000: # Less than 500KB
  800. thumb_filename = f"{uuid.uuid4().hex}{file_path.suffix}"
  801. thumb_path = (
  802. thumbnails_dir / thumb_filename
  803. ) # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + file_path.suffix
  804. shutil.copy2(file_path, thumb_path)
  805. return str(thumb_path)
  806. except OSError:
  807. pass # File inaccessible; fall through to return None
  808. return None
  809. except Exception as e:
  810. logger.warning("Failed to create image thumbnail: %s", e)
  811. return None
  812. # Supported image extensions for thumbnails
  813. IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif"}
  814. # File types whose thumbnails are rendered client-side and uploaded back
  815. # (#2976). The server has no renderer for STEP (that would need OpenCascade)
  816. # or the spreadsheet types, so the browser posts its first preview render to
  817. # POST /files/{id}/preview-thumbnail instead. PDF is rendered server-side with
  818. # PDFium when it lands and stays here for a PDF that renderer cannot read.
  819. # Kept to exactly these types so the endpoint can never overwrite a
  820. # server-generated STL/3MF/G-code/image thumbnail.
  821. CLIENT_THUMBNAIL_TYPES = {"step", "stp", "pdf", "csv", "xlsx", "ods"}
  822. # Photos of the printed result (#3077): same allowlist and naming as the
  823. # archive photo routes. 10 MB is ample for a phone camera JPEG.
  824. PHOTO_EXTENSIONS = (".jpg", ".jpeg", ".png", ".webp")
  825. PHOTO_MEDIA_TYPES = {
  826. ".jpg": "image/jpeg",
  827. ".jpeg": "image/jpeg",
  828. ".png": "image/png",
  829. ".webp": "image/webp",
  830. }
  831. MAX_PHOTO_BYTES = 10 * 1024 * 1024
  832. # Upper bound for an uploaded client-rendered thumbnail. The FE sends a
  833. # 256px PNG (a few tens of KB); anything near this limit is not a thumbnail.
  834. MAX_CLIENT_THUMBNAIL_BYTES = 2 * 1024 * 1024
  835. # Upper bound on the *decoded* size, checked against the header before any
  836. # pixels are allocated: a few-KB PNG can declare 12000x7000 and still be under
  837. # PIL's own decompression-bomb limit, which would be ~340 MB of RGBA.
  838. MAX_CLIENT_THUMBNAIL_EDGE = 2048
  839. # What the endpoint stores. The grid renders at ~256px, so anything larger is
  840. # downscaled rather than kept.
  841. STORED_CLIENT_THUMBNAIL_EDGE = 512
  842. # STL thumbnails get their own single worker thread. They are made one at a
  843. # time anyway (stl_thumbnail._RENDER_LOCK), and in the shared default pool the
  844. # ones waiting their turn would hold threads that every other to_thread call in
  845. # the app needs: a burst of STL uploads would stall them all.
  846. _STL_THUMBNAIL_EXECUTOR = ThreadPoolExecutor(max_workers=1, thread_name_prefix="stl-thumbnail")
  847. async def _render_stl_thumbnail(stl_path: Path, thumbnails_dir: Path) -> str | None:
  848. """generate_stl_thumbnail, off the event loop: a large mesh takes seconds."""
  849. loop = asyncio.get_running_loop()
  850. return await loop.run_in_executor(_STL_THUMBNAIL_EXECUTOR, generate_stl_thumbnail, stl_path, thumbnails_dir)
  851. async def _backfill_external_thumbnails(folder_ids: list[int]) -> None:
  852. """Generate STL and PDF thumbnails for an external folder tree in the background.
  853. Spawned via ``asyncio.create_task`` from ``scan_external_folder`` so the
  854. HTTP request can return as soon as the filesystem walk + folder/file rows
  855. are committed. Thumbnails for thousands of STL files would otherwise hold
  856. the request open for many minutes (each file triggers a ``trimesh.load``
  857. + matplotlib render, ~1-5s each) and the FE modal times out before the
  858. final ``db.commit()`` runs — causing the original symptom in #1299 where
  859. subdirectories never showed up because nothing got committed. PDFs are
  860. faster (a PDFium page render) but a share holding hundreds of them would
  861. still hold the request open, so they are rendered here too.
  862. Opens its own session because the request session is closed by the time
  863. this task starts running. Commits per-file so a worker restart mid-run
  864. only loses the in-flight file. Caps STL load to a single file at a time
  865. to avoid memory pressure on systems with many huge STLs.
  866. """
  867. if not folder_ids:
  868. return
  869. thumbnails_dir = get_library_thumbnails_dir()
  870. async with async_session() as db:
  871. result = await db.execute(
  872. LibraryFile.active().where(
  873. LibraryFile.folder_id.in_(folder_ids),
  874. LibraryFile.file_type.in_(("stl", "pdf")),
  875. LibraryFile.thumbnail_path.is_(None),
  876. )
  877. )
  878. target_files = result.scalars().all()
  879. if not target_files:
  880. return
  881. logger.info(
  882. "Backfilling STL/PDF thumbnails: %d file(s) across %d folder(s)",
  883. len(target_files),
  884. len(folder_ids),
  885. )
  886. for target_file in target_files:
  887. abs_path = to_absolute_path(target_file.file_path)
  888. if not abs_path or not abs_path.exists():
  889. continue
  890. if target_file.file_type == "pdf":
  891. # generate_pdf_thumbnail never raises; an unreadable PDF
  892. # returns None and keeps the browser-preview fallback.
  893. thumb_path = await asyncio.to_thread(generate_pdf_thumbnail, abs_path, thumbnails_dir)
  894. if thumb_path:
  895. target_file.thumbnail_path = to_relative_path(Path(thumb_path))
  896. await db.commit()
  897. continue
  898. # Pre-skip files too small to contain even a single triangle.
  899. # Bulk-uploaded ZIPs of stub STLs would otherwise trigger one
  900. # trimesh.load() call + one debug log line per stub.
  901. try:
  902. if abs_path.stat().st_size < MIN_USABLE_STL_BYTES:
  903. continue
  904. except OSError:
  905. continue
  906. try:
  907. thumb_path = await _render_stl_thumbnail(abs_path, thumbnails_dir)
  908. except Exception as exc: # noqa: BLE001 — never let one bad STL kill the rest
  909. logger.debug("STL thumbnail backfill skipped %s: %s", abs_path, exc)
  910. continue
  911. if thumb_path:
  912. target_file.thumbnail_path = to_relative_path(Path(thumb_path))
  913. await db.commit()
  914. # ============ Folder Endpoints ============
  915. @router.get("/folders", response_model=list[FolderTreeItem])
  916. @router.get("/folders/", response_model=list[FolderTreeItem])
  917. async def list_folders(
  918. response: Response,
  919. db: AsyncSession = Depends(get_db, scope="function"),
  920. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  921. require_ownership_permission(
  922. Permission.LIBRARY_READ_ALL,
  923. Permission.LIBRARY_READ_OWN,
  924. )
  925. ),
  926. printer_scope: PrinterScope = RequestPrinterScope,
  927. actor: User | ApiKeyActor | None = RequestActor,
  928. ):
  929. """Get all folders as a tree structure.
  930. A library:read_own user gets only the folders they may see (#3201), and
  931. the file counts and activity times of their own files only.
  932. """
  933. user, _ = auth_result
  934. # Prevent browser caching of folder list
  935. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  936. index = await _load_index(db, user)
  937. visible = visible_folder_ids(index, user)
  938. # Get all folders with project and archive joins
  939. result = await db.execute(
  940. select(LibraryFolder, Project.name)
  941. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  942. .order_by(LibraryFolder.name)
  943. )
  944. rows = [row for row in result.all() if visible is None or row[0].id in visible]
  945. archives = await _linkable_archives(db, [row[0].archive_id for row in rows], printer_scope, actor)
  946. own_files = _own_files_filter(user)
  947. # Get file counts per folder
  948. file_counts_result = await db.execute(
  949. select(LibraryFile.folder_id, func.count(LibraryFile.id))
  950. .where(LibraryFile.folder_id.isnot(None), LibraryFile.deleted_at.is_(None), *own_files)
  951. .group_by(LibraryFile.folder_id)
  952. )
  953. file_counts = dict(file_counts_result.all())
  954. # Latest immediate-child file activity per folder (#1770/#2680). Real on-disk
  955. # mtime when we have it (external scans populate ``fs_modified_at``), else the
  956. # DB ``updated_at`` — COALESCE so external rows scanned before this field
  957. # existed, and internal uploads, still contribute a signal. This is the
  958. # per-folder *leaf* value; subtree descent is aggregated recursively below.
  959. latest_file_activity_result = await db.execute(
  960. select(
  961. LibraryFile.folder_id,
  962. func.max(func.coalesce(LibraryFile.fs_modified_at, LibraryFile.updated_at)),
  963. )
  964. .where(LibraryFile.folder_id.isnot(None), LibraryFile.deleted_at.is_(None), *own_files)
  965. .group_by(LibraryFile.folder_id)
  966. )
  967. latest_file_activity = dict(latest_file_activity_result.all())
  968. # Build tree structure. Each folder's initial ``latest_activity_at`` is its own
  969. # leaf activity: the newer of its real directory mtime (fallback updated_at)
  970. # and its immediate files' mtime. The recursive bubble below then rolls each
  971. # subtree's newest descendant up to its ancestors (#2680 — sorting must match
  972. # ``ls -t`` recursively, so a freshly-added deep file lifts every parent).
  973. folder_map = {}
  974. root_folders = []
  975. for folder, project_name in rows:
  976. own_activity = folder.fs_modified_at or folder.updated_at
  977. latest_file = latest_file_activity.get(folder.id)
  978. if latest_file is not None and latest_file > own_activity:
  979. own_activity = latest_file
  980. folder_item = FolderTreeItem(
  981. id=folder.id,
  982. name=folder.name,
  983. parent_id=folder.parent_id,
  984. project_id=folder.project_id,
  985. project_name=project_name,
  986. **_archive_link(folder.archive_id, archives),
  987. is_external=folder.is_external,
  988. external_path=folder.external_path,
  989. external_readonly=folder.external_readonly,
  990. file_count=file_counts.get(folder.id, 0),
  991. latest_activity_at=own_activity,
  992. **_folder_access_fields(index, folder, user),
  993. children=[],
  994. )
  995. folder_map[folder.id] = folder_item
  996. # Link children to parents
  997. for folder, _ in rows:
  998. folder_item = folder_map[folder.id]
  999. if folder.parent_id is None:
  1000. root_folders.append(folder_item)
  1001. elif folder.parent_id in folder_map:
  1002. folder_map[folder.parent_id].children.append(folder_item)
  1003. # Recursive newest-descendant bubble (#2680). Post-order: a folder's activity
  1004. # becomes the max of its own leaf activity and every descendant's, so sorting
  1005. # the tree by ``latest_activity_at`` surfaces the branch with the most recent
  1006. # activity anywhere inside it. Iterative stack keeps deep external mounts off
  1007. # Python's recursion limit.
  1008. def _bubble(root: FolderTreeItem) -> None:
  1009. order: list[FolderTreeItem] = []
  1010. stack = [root]
  1011. while stack:
  1012. node = stack.pop()
  1013. order.append(node)
  1014. stack.extend(node.children)
  1015. for node in reversed(order): # deepest first
  1016. for child in node.children:
  1017. if child.latest_activity_at is not None and (
  1018. node.latest_activity_at is None or child.latest_activity_at > node.latest_activity_at
  1019. ):
  1020. node.latest_activity_at = child.latest_activity_at
  1021. for root in root_folders:
  1022. _bubble(root)
  1023. return root_folders
  1024. @router.get("/folders/by-project/{project_id}", response_model=list[FolderResponse])
  1025. async def get_folders_by_project(
  1026. project_id: int,
  1027. db: AsyncSession = Depends(get_db, scope="function"),
  1028. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1029. require_ownership_permission(
  1030. Permission.LIBRARY_READ_ALL,
  1031. Permission.LIBRARY_READ_OWN,
  1032. )
  1033. ),
  1034. printer_scope: PrinterScope = RequestPrinterScope,
  1035. actor: User | ApiKeyActor | None = RequestActor,
  1036. ):
  1037. """Get all folders linked to a specific project, those the user may see (#3201)."""
  1038. user, _ = auth_result
  1039. index = await _load_index(db, user)
  1040. visible = visible_folder_ids(index, user)
  1041. own_files = _own_files_filter(user)
  1042. result = await db.execute(
  1043. select(LibraryFolder, Project.name)
  1044. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  1045. .where(LibraryFolder.project_id == project_id)
  1046. .order_by(LibraryFolder.name)
  1047. )
  1048. rows = [row for row in result.all() if visible is None or row[0].id in visible]
  1049. archives = await _linkable_archives(db, [row[0].archive_id for row in rows], printer_scope, actor)
  1050. folders = []
  1051. for folder, project_name in rows:
  1052. # Get file count + latest file activity (#1770/#2680) in one trip. Prefer
  1053. # the real on-disk mtime (external scans), fall back to the DB updated_at.
  1054. agg_result = await db.execute(
  1055. select(
  1056. func.count(LibraryFile.id),
  1057. func.max(func.coalesce(LibraryFile.fs_modified_at, LibraryFile.updated_at)),
  1058. ).where(
  1059. LibraryFile.folder_id == folder.id,
  1060. LibraryFile.deleted_at.is_(None),
  1061. *own_files,
  1062. )
  1063. )
  1064. file_count, latest_file = agg_result.one()
  1065. file_count = file_count or 0
  1066. own_activity = folder.fs_modified_at or folder.updated_at
  1067. latest_activity_at = max(own_activity, latest_file) if latest_file is not None else own_activity
  1068. folders.append(
  1069. FolderResponse(
  1070. id=folder.id,
  1071. name=folder.name,
  1072. parent_id=folder.parent_id,
  1073. project_id=folder.project_id,
  1074. project_name=project_name,
  1075. **_archive_link(folder.archive_id, archives),
  1076. is_external=folder.is_external,
  1077. external_path=folder.external_path,
  1078. external_readonly=folder.external_readonly,
  1079. external_show_hidden=folder.external_show_hidden,
  1080. file_count=file_count,
  1081. latest_activity_at=latest_activity_at,
  1082. **_folder_access_fields(index, folder, user),
  1083. created_at=folder.created_at,
  1084. updated_at=folder.updated_at,
  1085. )
  1086. )
  1087. return folders
  1088. @router.get("/folders/by-archive/{archive_id}", response_model=list[FolderResponse])
  1089. async def get_folders_by_archive(
  1090. archive_id: int,
  1091. db: AsyncSession = Depends(get_db, scope="function"),
  1092. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1093. require_ownership_permission(
  1094. Permission.LIBRARY_READ_ALL,
  1095. Permission.LIBRARY_READ_OWN,
  1096. )
  1097. ),
  1098. printer_scope: PrinterScope = RequestPrinterScope,
  1099. actor: User | ApiKeyActor | None = RequestActor,
  1100. ):
  1101. """Get all folders linked to a specific archive, those the user may see (#3201)."""
  1102. user, _ = auth_result
  1103. return (await _folders_by_archive(db, user, [archive_id], printer_scope, actor))[archive_id]
  1104. async def _folders_by_archive(
  1105. db: AsyncSession,
  1106. user: User | ApiKeyActor | None,
  1107. archive_ids: list[int],
  1108. printer_scope: PrinterScope,
  1109. actor: User | ApiKeyActor | None,
  1110. ) -> dict[int, list]:
  1111. """The folders linked to each archive that *user* may see (#3201), by archive id.
  1112. An archive *actor* (the caller, as ``RequestActor`` gives it) does not see
  1113. in the archives has none.
  1114. """
  1115. folders: dict[int, list] = {archive_id: [] for archive_id in archive_ids}
  1116. archives = await _linkable_archives(db, archive_ids, printer_scope, actor)
  1117. if not archives:
  1118. return folders
  1119. index = await _load_index(db, user)
  1120. visible = visible_folder_ids(index, user)
  1121. own_files = _own_files_filter(user)
  1122. result = await db.execute(
  1123. select(LibraryFolder).where(LibraryFolder.archive_id.in_(list(archives))).order_by(LibraryFolder.name)
  1124. )
  1125. rows = [folder for folder in result.scalars().all() if visible is None or folder.id in visible]
  1126. for folder in rows:
  1127. # Get file count + latest file activity (#1770/#2680) in one trip. Prefer
  1128. # the real on-disk mtime (external scans), fall back to the DB updated_at.
  1129. agg_result = await db.execute(
  1130. select(
  1131. func.count(LibraryFile.id),
  1132. func.max(func.coalesce(LibraryFile.fs_modified_at, LibraryFile.updated_at)),
  1133. ).where(
  1134. LibraryFile.folder_id == folder.id,
  1135. LibraryFile.deleted_at.is_(None),
  1136. *own_files,
  1137. )
  1138. )
  1139. file_count, latest_file = agg_result.one()
  1140. file_count = file_count or 0
  1141. own_activity = folder.fs_modified_at or folder.updated_at
  1142. latest_activity_at = max(own_activity, latest_file) if latest_file is not None else own_activity
  1143. assert folder.archive_id is not None # selected by archive_id
  1144. folders[folder.archive_id].append(
  1145. FolderResponse(
  1146. id=folder.id,
  1147. name=folder.name,
  1148. parent_id=folder.parent_id,
  1149. project_id=folder.project_id,
  1150. project_name=None,
  1151. **_archive_link(folder.archive_id, archives),
  1152. is_external=folder.is_external,
  1153. external_path=folder.external_path,
  1154. external_readonly=folder.external_readonly,
  1155. external_show_hidden=folder.external_show_hidden,
  1156. file_count=file_count,
  1157. latest_activity_at=latest_activity_at,
  1158. **_folder_access_fields(index, folder, user),
  1159. created_at=folder.created_at,
  1160. updated_at=folder.updated_at,
  1161. )
  1162. )
  1163. return folders
  1164. @router.post("/folders", response_model=FolderResponse)
  1165. @router.post("/folders/", response_model=FolderResponse)
  1166. async def create_folder(
  1167. data: FolderCreate,
  1168. db: AsyncSession = Depends(get_db, scope="function"),
  1169. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  1170. actor: User | ApiKeyActor | None = RequestActor,
  1171. printer_scope: PrinterScope = RequestPrinterScope,
  1172. ):
  1173. """Create a new folder, owned by the user who makes it (#3201)."""
  1174. # A read_own user may only create inside their own or a shared folder.
  1175. if data.parent_id is not None:
  1176. await get_writable_folder(db, data.parent_id, actor)
  1177. # Verify project exists if specified
  1178. project_name = None
  1179. if data.project_id is not None:
  1180. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  1181. project = project_result.scalar_one_or_none()
  1182. if not project:
  1183. raise HTTPException(status_code=404, detail="Project not found")
  1184. project_name = project.name
  1185. # Verify archive exists if specified
  1186. archives = await _linkable_archives(db, [data.archive_id], printer_scope, actor)
  1187. if data.archive_id is not None and data.archive_id not in archives:
  1188. raise HTTPException(status_code=404, detail="Archive not found")
  1189. folder = LibraryFolder(
  1190. name=data.name,
  1191. parent_id=data.parent_id,
  1192. project_id=data.project_id,
  1193. archive_id=data.archive_id,
  1194. created_by_id=actor.id if actor else None,
  1195. # Made without a user (auth off, a key without an owner): everyone's, as before #3201.
  1196. shared=actor is None or actor.id is None,
  1197. )
  1198. db.add(folder)
  1199. await db.commit()
  1200. await db.refresh(folder)
  1201. index = await _load_index(db, actor)
  1202. return FolderResponse(
  1203. id=folder.id,
  1204. name=folder.name,
  1205. parent_id=folder.parent_id,
  1206. project_id=folder.project_id,
  1207. project_name=project_name,
  1208. **_archive_link(folder.archive_id, archives),
  1209. is_external=folder.is_external,
  1210. external_path=folder.external_path,
  1211. external_readonly=folder.external_readonly,
  1212. external_show_hidden=folder.external_show_hidden,
  1213. file_count=0,
  1214. # New folder has no files yet — fall back to the folder's own
  1215. # updated_at so this matches the list-route semantics (#1770).
  1216. latest_activity_at=folder.updated_at,
  1217. **_folder_access_fields(index, folder, actor),
  1218. created_at=folder.created_at,
  1219. updated_at=folder.updated_at,
  1220. )
  1221. @router.get("/folders/{folder_id}", response_model=FolderResponse)
  1222. async def get_folder(
  1223. folder_id: int,
  1224. db: AsyncSession = Depends(get_db, scope="function"),
  1225. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1226. require_ownership_permission(
  1227. Permission.LIBRARY_READ_ALL,
  1228. Permission.LIBRARY_READ_OWN,
  1229. )
  1230. ),
  1231. printer_scope: PrinterScope = RequestPrinterScope,
  1232. actor: User | ApiKeyActor | None = RequestActor,
  1233. ):
  1234. """Get a folder by ID; 404 for a folder the user may not see (#3201)."""
  1235. user, _ = auth_result
  1236. index = await _load_index(db, user)
  1237. visible = visible_folder_ids(index, user)
  1238. if visible is not None and folder_id not in visible:
  1239. raise HTTPException(status_code=404, detail="Folder not found")
  1240. result = await db.execute(
  1241. select(LibraryFolder, Project.name)
  1242. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  1243. .where(LibraryFolder.id == folder_id)
  1244. )
  1245. row = result.one_or_none()
  1246. if not row:
  1247. raise HTTPException(status_code=404, detail="Folder not found")
  1248. folder, project_name = row
  1249. archives = await _linkable_archives(db, [folder.archive_id], printer_scope, actor)
  1250. # Get file count + latest file activity (#1770) in one trip
  1251. agg_result = await db.execute(
  1252. select(
  1253. func.count(LibraryFile.id),
  1254. func.max(LibraryFile.updated_at),
  1255. ).where(
  1256. LibraryFile.folder_id == folder_id,
  1257. LibraryFile.deleted_at.is_(None),
  1258. *_own_files_filter(user),
  1259. )
  1260. )
  1261. file_count, latest_file = agg_result.one()
  1262. file_count = file_count or 0
  1263. latest_activity_at = max(folder.updated_at, latest_file) if latest_file is not None else folder.updated_at
  1264. return FolderResponse(
  1265. id=folder.id,
  1266. name=folder.name,
  1267. parent_id=folder.parent_id,
  1268. project_id=folder.project_id,
  1269. project_name=project_name,
  1270. **_archive_link(folder.archive_id, archives),
  1271. is_external=folder.is_external,
  1272. external_path=folder.external_path,
  1273. external_readonly=folder.external_readonly,
  1274. external_show_hidden=folder.external_show_hidden,
  1275. file_count=file_count,
  1276. latest_activity_at=latest_activity_at,
  1277. **_folder_access_fields(index, folder, user),
  1278. created_at=folder.created_at,
  1279. updated_at=folder.updated_at,
  1280. )
  1281. _README_BYTES_CAP = 512 * 1024 # 512 KiB — model descriptions don't need more
  1282. _README_PREFERRED_STEMS = ("readme", "description")
  1283. @router.get("/folders/{folder_id}/readme", response_model=FolderReadmeResponse)
  1284. async def get_folder_readme(
  1285. folder_id: int,
  1286. db: AsyncSession = Depends(get_db, scope="function"),
  1287. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1288. require_ownership_permission(
  1289. Permission.LIBRARY_READ_ALL,
  1290. Permission.LIBRARY_READ_OWN,
  1291. )
  1292. ),
  1293. ):
  1294. """Return the first markdown description file for a folder (#1268).
  1295. Picks ``README.md`` / ``readme.md`` / ``description.md`` first (any case),
  1296. otherwise the alphabetically-first ``*.md`` in the folder. 404 when no
  1297. markdown file is present so the FE can hide the side panel.
  1298. """
  1299. user, can_read_all = auth_result
  1300. await get_visible_folder(db, folder_id, user)
  1301. query = LibraryFile.active().where(
  1302. LibraryFile.folder_id == folder_id,
  1303. func.lower(LibraryFile.filename).like("%.md"),
  1304. )
  1305. if user is not None and not can_read_all:
  1306. query = query.where(LibraryFile.created_by_id == user.id)
  1307. result = await db.execute(query)
  1308. candidates = result.scalars().all()
  1309. if not candidates:
  1310. raise HTTPException(status_code=404, detail="No markdown description in folder")
  1311. def sort_key(f: LibraryFile) -> tuple[int, str]:
  1312. stem = os.path.splitext(f.filename.lower())[0]
  1313. try:
  1314. return (_README_PREFERRED_STEMS.index(stem), f.filename.lower())
  1315. except ValueError:
  1316. return (len(_README_PREFERRED_STEMS), f.filename.lower())
  1317. pick = sorted(candidates, key=sort_key)[0]
  1318. abs_path = to_absolute_path(pick.file_path)
  1319. if not abs_path or not abs_path.exists():
  1320. raise HTTPException(status_code=404, detail="Markdown file missing on disk")
  1321. try:
  1322. raw = abs_path.read_bytes()
  1323. except OSError as e:
  1324. logger.warning("Folder readme read failed for %s: %s", abs_path, e)
  1325. raise HTTPException(status_code=500, detail="Could not read markdown file") from None
  1326. truncated = len(raw) > _README_BYTES_CAP
  1327. if truncated:
  1328. raw = raw[:_README_BYTES_CAP]
  1329. # `errors="replace"` so a single bad byte never blanks the panel.
  1330. content = raw.decode("utf-8", errors="replace")
  1331. return FolderReadmeResponse(filename=pick.filename, content=content, truncated=truncated)
  1332. @router.put("/folders/{folder_id}", response_model=FolderResponse)
  1333. async def update_folder(
  1334. folder_id: int,
  1335. data: FolderUpdate,
  1336. db: AsyncSession = Depends(get_db, scope="function"),
  1337. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1338. require_ownership_permission(
  1339. Permission.LIBRARY_UPDATE_ALL,
  1340. Permission.LIBRARY_UPDATE_OWN,
  1341. )
  1342. ),
  1343. printer_scope: PrinterScope = RequestPrinterScope,
  1344. actor: User | ApiKeyActor | None = RequestActor,
  1345. ):
  1346. """Update a folder.
  1347. library:update_all changes any folder. With library:update_own a user may
  1348. rename their own folders and move them into another folder they can
  1349. write to (#3201); linking and sharing stay with library:update_all.
  1350. """
  1351. user, can_modify_all = auth_result
  1352. # library:update_all reaches every folder, seen or not, as before #3201.
  1353. folder = await get_visible_folder(db, folder_id, None if can_modify_all else user)
  1354. if not can_modify_all:
  1355. if not can_rename_folder(folder, user):
  1356. raise HTTPException(status_code=403, detail="Only the folder's owner can change it")
  1357. if data.project_id is not None or data.archive_id is not None:
  1358. raise HTTPException(status_code=403, detail="Linking folders requires library:update_all")
  1359. if data.shared is not None:
  1360. raise HTTPException(status_code=403, detail="Sharing folders requires library:update_all")
  1361. if data.parent_id:
  1362. await get_writable_folder(db, data.parent_id, user)
  1363. if data.shared is not None:
  1364. folder.shared = data.shared
  1365. if data.name is not None:
  1366. folder.name = data.name
  1367. if data.parent_id is not None:
  1368. # Prevent circular reference
  1369. if data.parent_id == folder_id:
  1370. raise HTTPException(status_code=400, detail="Folder cannot be its own parent")
  1371. # Check for circular reference in ancestors
  1372. if data.parent_id != 0: # 0 means move to root
  1373. current_id = data.parent_id
  1374. while current_id is not None:
  1375. if current_id == folder_id:
  1376. raise HTTPException(status_code=400, detail="Cannot move folder into its own subtree")
  1377. parent_result = await db.execute(select(LibraryFolder.parent_id).where(LibraryFolder.id == current_id))
  1378. current_id = parent_result.scalar()
  1379. folder.parent_id = data.parent_id
  1380. else:
  1381. folder.parent_id = None
  1382. # Update project_id (0 to unlink)
  1383. if data.project_id is not None:
  1384. if data.project_id == 0:
  1385. folder.project_id = None
  1386. else:
  1387. # Verify project exists
  1388. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  1389. if not project_result.scalar_one_or_none():
  1390. raise HTTPException(status_code=404, detail="Project not found")
  1391. folder.project_id = data.project_id
  1392. # Update archive_id (0 to unlink)
  1393. if data.archive_id is not None:
  1394. if data.archive_id == 0:
  1395. # A link the caller can't see is not theirs to remove.
  1396. if folder.archive_id in await _linkable_archives(db, [folder.archive_id], printer_scope, actor):
  1397. folder.archive_id = None
  1398. else:
  1399. # Verify archive exists
  1400. if data.archive_id not in await _linkable_archives(db, [data.archive_id], printer_scope, actor):
  1401. raise HTTPException(status_code=404, detail="Archive not found")
  1402. folder.archive_id = data.archive_id
  1403. await db.commit()
  1404. await db.refresh(folder)
  1405. # Get file count + latest file activity (#1770) and names
  1406. agg_result = await db.execute(
  1407. select(
  1408. func.count(LibraryFile.id),
  1409. func.max(LibraryFile.updated_at),
  1410. ).where(
  1411. LibraryFile.folder_id == folder_id,
  1412. LibraryFile.deleted_at.is_(None),
  1413. *_own_files_filter(user),
  1414. )
  1415. )
  1416. file_count, latest_file = agg_result.one()
  1417. file_count = file_count or 0
  1418. latest_activity_at = max(folder.updated_at, latest_file) if latest_file is not None else folder.updated_at
  1419. # Get project and archive names
  1420. project_name = None
  1421. if folder.project_id:
  1422. project_result = await db.execute(select(Project.name).where(Project.id == folder.project_id))
  1423. project_name = project_result.scalar()
  1424. archives = await _linkable_archives(db, [folder.archive_id], printer_scope, actor)
  1425. return FolderResponse(
  1426. id=folder.id,
  1427. name=folder.name,
  1428. parent_id=folder.parent_id,
  1429. project_id=folder.project_id,
  1430. project_name=project_name,
  1431. **_archive_link(folder.archive_id, archives),
  1432. is_external=folder.is_external,
  1433. external_path=folder.external_path,
  1434. external_readonly=folder.external_readonly,
  1435. external_show_hidden=folder.external_show_hidden,
  1436. file_count=file_count,
  1437. latest_activity_at=latest_activity_at,
  1438. **_folder_access_fields(await _load_index(db, user), folder, user),
  1439. created_at=folder.created_at,
  1440. updated_at=folder.updated_at,
  1441. )
  1442. @router.delete("/folders/{folder_id}")
  1443. async def delete_folder(
  1444. folder_id: int,
  1445. db: AsyncSession = Depends(get_db, scope="function"),
  1446. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  1447. require_ownership_permission(
  1448. Permission.LIBRARY_DELETE_ALL,
  1449. Permission.LIBRARY_DELETE_OWN,
  1450. )
  1451. ),
  1452. ):
  1453. """Delete a folder and all its contents (cascade).
  1454. library:delete_all deletes any folder. With library:delete_own a user
  1455. deletes their own folder when everything in it is theirs too (#3201), or
  1456. an ownerless folder that is truly empty (#1781). See
  1457. ``library_folder_access.folder_delete_blocker``.
  1458. """
  1459. user, can_modify_all = auth_result
  1460. # library:delete_all reaches every folder, seen or not, as before #3201.
  1461. folder = await get_visible_folder(db, folder_id, None if can_modify_all else user)
  1462. if not can_modify_all:
  1463. blocker = folder_delete_blocker(await load_folder_index(db), folder, user)
  1464. if blocker:
  1465. raise HTTPException(status_code=403, detail=blocker)
  1466. # External folders: only remove DB records, never delete files from external path
  1467. is_ext = folder.is_external
  1468. # Get all files in this folder and subfolders to delete from disk
  1469. async def get_all_file_ids(fid: int) -> list[int]:
  1470. """Recursively get all file IDs in a folder tree."""
  1471. file_ids = []
  1472. # Get files in this folder
  1473. files_result = await db.execute(
  1474. select(LibraryFile.id, LibraryFile.file_path, LibraryFile.thumbnail_path, LibraryFile.is_external).where(
  1475. LibraryFile.folder_id == fid
  1476. )
  1477. )
  1478. for fid_val, file_path, thumb_path, file_is_ext in files_result.all():
  1479. file_ids.append(fid_val)
  1480. # Only delete non-external files from disk
  1481. if not is_ext and not file_is_ext:
  1482. try:
  1483. if file_path and os.path.exists(file_path):
  1484. os.remove(file_path)
  1485. if thumb_path and os.path.exists(thumb_path):
  1486. os.remove(thumb_path)
  1487. except OSError as e:
  1488. logger.warning("Failed to delete file: %s", e)
  1489. # Get child folders and recurse
  1490. children_result = await db.execute(select(LibraryFolder.id).where(LibraryFolder.parent_id == fid))
  1491. for (child_id,) in children_result.all():
  1492. file_ids.extend(await get_all_file_ids(child_id))
  1493. return file_ids
  1494. doomed_file_ids = await get_all_file_ids(folder_id)
  1495. # The folder cascade hard-deletes every file row under it, so the queue has
  1496. # to be taken off them first — same as the single-file delete below (#2819).
  1497. # The return value used to be discarded here, which is why this never
  1498. # happened for a folder delete.
  1499. from backend.app.services.library_trash import delete_dependent_variants, release_queue_references
  1500. await delete_dependent_variants(db, doomed_file_ids)
  1501. await release_queue_references(db, doomed_file_ids)
  1502. for doomed_id in doomed_file_ids:
  1503. remove_library_photos_dir(doomed_id)
  1504. # Delete folder (cascade will handle files and subfolders)
  1505. await db.delete(folder)
  1506. await db.commit()
  1507. return {"status": "success", "message": "Folder deleted"}
  1508. # ============ External Folder Endpoints ============
  1509. # GHSA-r2qv follow-up (audit finding I1): external-folder mount path uses an
  1510. # allowlist of operator-opted-in roots rather than the original denylist of
  1511. # system directories. The denylist shape was fail-open-on-growth — anything
  1512. # not enumerated (``/data`` containing other users' archives, ``/root``,
  1513. # arbitrary NFS/SMB mounts, the Bambuddy ``LOG_DIR``) could be mounted by any
  1514. # user with ``LIBRARY_UPLOAD``. The allowlist defaults to empty and is
  1515. # extended via the ``BAMBUDDY_EXTERNAL_ROOTS`` env var (colon-separated
  1516. # absolute paths). The route is additionally gated on ``SETTINGS_UPDATE``
  1517. # (admin scope) rather than ``LIBRARY_UPLOAD`` because mounting host paths
  1518. # is an operator-level capability that crosses user boundaries.
  1519. # Bambuddy-owned data directories. Hardcode-rejected even if the operator
  1520. # tries to add them to ``BAMBUDDY_EXTERNAL_ROOTS`` — mounting these would
  1521. # allow reading other users' archives, log files, or the static assets path.
  1522. def _bambuddy_reserved_roots() -> tuple[Path, ...]:
  1523. """Resolved Bambuddy-owned directories that may NEVER be mounted as an
  1524. external folder regardless of the operator's allowlist.
  1525. Resolved at call time because tests patch ``settings.base_dir`` /
  1526. ``settings.log_dir`` to a temp dir; resolving lazily picks up the
  1527. patched values rather than module-import-time values.
  1528. """
  1529. from backend.app.core.config import settings as app_settings
  1530. reserved = [app_settings.base_dir, app_settings.log_dir, app_settings.static_dir, app_settings.archive_dir]
  1531. return tuple(Path(p).resolve() for p in reserved if p is not None)
  1532. def _allowed_external_roots() -> tuple[Path, ...]:
  1533. """Parse ``BAMBUDDY_EXTERNAL_ROOTS`` into resolved allowed roots.
  1534. Empty env var (the default) means external folders are disabled.
  1535. Operators opt in explicitly: ``BAMBUDDY_EXTERNAL_ROOTS=/mnt/library:/srv/3d``
  1536. Returns a tuple of resolved ``Path`` objects; entries that don't
  1537. resolve to absolute paths are silently dropped (operator error, not
  1538. a security boundary). Resolved lazily so tests can monkeypatch.
  1539. """
  1540. raw = os.environ.get("BAMBUDDY_EXTERNAL_ROOTS", "")
  1541. roots: list[Path] = []
  1542. for entry in raw.split(":"):
  1543. entry = entry.strip()
  1544. if not entry:
  1545. continue
  1546. try:
  1547. resolved = Path(entry).resolve()
  1548. except (OSError, RuntimeError): # noqa: BLE001 — operator config error, not a security boundary
  1549. continue
  1550. if resolved.is_absolute():
  1551. roots.append(resolved)
  1552. return tuple(roots)
  1553. def _path_within(child: Path, parent: Path) -> bool:
  1554. """Return True if ``child`` is ``parent`` or any descendant.
  1555. Uses ``Path.relative_to`` semantics (raises ``ValueError`` on miss)
  1556. instead of string ``startswith``, which would falsely match
  1557. ``/data-other`` against ``/data``. ``Path.is_relative_to`` is the
  1558. sanctioned form on Python 3.9+; both are available here.
  1559. """
  1560. try:
  1561. child.relative_to(parent)
  1562. except ValueError:
  1563. return False
  1564. return True
  1565. # Supported file extensions for external folder scanning
  1566. _SCANNABLE_EXTENSIONS = {
  1567. ".3mf",
  1568. ".gcode",
  1569. ".gcode.3mf",
  1570. ".stl",
  1571. ".obj",
  1572. ".step",
  1573. ".stp",
  1574. ".png",
  1575. ".jpg",
  1576. ".jpeg",
  1577. ".gif",
  1578. ".webp",
  1579. ".svg",
  1580. ".md",
  1581. # Documents that ship alongside a job folder and now have in-app
  1582. # previews (#2976): drawings/datasheets and part lists.
  1583. ".pdf",
  1584. ".csv",
  1585. ".xlsx",
  1586. ".ods",
  1587. }
  1588. def _validate_external_path(path_str: str) -> Path:
  1589. """Validate an external path is safe to mount.
  1590. Allowlist semantics:
  1591. 1. Path must be absolute and resolve cleanly (symlink-escape rejected
  1592. implicitly by the resolved-startswith check below).
  1593. 2. Path must fall under one of the roots enumerated in
  1594. ``BAMBUDDY_EXTERNAL_ROOTS``; empty allowlist (the default)
  1595. means external folders are not available on this deployment.
  1596. 3. Path must NOT fall under any Bambuddy-owned directory (``base_dir``,
  1597. ``log_dir``, ``static_dir``, ``archive_dir``) — the reserved set
  1598. takes precedence over the allowlist, so an operator who accidentally
  1599. sets ``BAMBUDDY_EXTERNAL_ROOTS=/`` does not expose ``/data``.
  1600. 4. Existence + directory-type + readability gates remain.
  1601. """
  1602. path = Path(path_str).resolve()
  1603. if not path.is_absolute():
  1604. raise HTTPException(status_code=400, detail="Path must be absolute")
  1605. allowed_roots = _allowed_external_roots()
  1606. if not allowed_roots:
  1607. raise HTTPException(
  1608. status_code=400,
  1609. detail=(
  1610. "External folders are not enabled on this deployment. Ask the "
  1611. "operator to set BAMBUDDY_EXTERNAL_ROOTS=<colon-separated paths>."
  1612. ),
  1613. )
  1614. # Reserved (Bambuddy-owned) paths are rejected before the allowlist check
  1615. # so an over-broad allowlist (e.g. operator set "/" for testing) cannot
  1616. # expose Bambuddy's own data dir or log dir.
  1617. for reserved in _bambuddy_reserved_roots():
  1618. if _path_within(path, reserved):
  1619. raise HTTPException(
  1620. status_code=400,
  1621. detail=f"Cannot mount Bambuddy-managed directory: {reserved}",
  1622. )
  1623. if not any(_path_within(path, root) for root in allowed_roots):
  1624. raise HTTPException(
  1625. status_code=400,
  1626. detail=(
  1627. f"Path '{path}' is not within an allowed external root. "
  1628. f"Allowed roots: {', '.join(str(r) for r in allowed_roots)}"
  1629. ),
  1630. )
  1631. if not path.exists():
  1632. raise HTTPException(status_code=400, detail=f"Path does not exist: {path}")
  1633. if not path.is_dir():
  1634. raise HTTPException(status_code=400, detail=f"Path is not a directory: {path}")
  1635. # Check readability
  1636. if not os.access(path, os.R_OK):
  1637. raise HTTPException(status_code=400, detail=f"Path is not readable: {path}")
  1638. return path
  1639. @router.post("/folders/external", response_model=FolderResponse)
  1640. async def create_external_folder(
  1641. data: ExternalFolderCreate,
  1642. db: AsyncSession = Depends(get_db, scope="function"),
  1643. # GHSA-r2qv follow-up (I1): elevated from LIBRARY_UPLOAD to SETTINGS_UPDATE.
  1644. # Registering a host filesystem path as a Bambuddy library folder is an
  1645. # operator-level capability that crosses user boundaries (one user's
  1646. # registered external folder is visible to every other user via
  1647. # /api/v1/library/folders). LIBRARY_UPLOAD was always the wrong scope —
  1648. # SETTINGS_UPDATE is the admin-class gate that already protects every
  1649. # other host-affecting setting (SMTP, LDAP, cloud, smart plugs).
  1650. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.SETTINGS_UPDATE)),
  1651. ):
  1652. """Create an external folder that points to a host directory."""
  1653. resolved = _validate_external_path(data.external_path)
  1654. # Check no other external folder already points to this path
  1655. existing = await db.execute(
  1656. select(LibraryFolder).where(
  1657. LibraryFolder.is_external.is_(True),
  1658. LibraryFolder.external_path == str(resolved),
  1659. )
  1660. )
  1661. if existing.scalar_one_or_none():
  1662. raise HTTPException(status_code=409, detail="An external folder already exists for this path")
  1663. # Verify parent exists if specified
  1664. if data.parent_id is not None:
  1665. parent_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.parent_id))
  1666. if not parent_result.scalar_one_or_none():
  1667. raise HTTPException(status_code=404, detail="Parent folder not found")
  1668. folder = LibraryFolder(
  1669. name=data.name,
  1670. parent_id=data.parent_id,
  1671. is_external=True,
  1672. created_by_id=current_user.id if current_user else None,
  1673. # A mount is everyone's, as before #3201; an admin can stop sharing it.
  1674. shared=True,
  1675. external_path=str(resolved),
  1676. external_readonly=data.readonly,
  1677. external_show_hidden=data.show_hidden,
  1678. )
  1679. db.add(folder)
  1680. await db.commit()
  1681. await db.refresh(folder)
  1682. return FolderResponse(
  1683. id=folder.id,
  1684. name=folder.name,
  1685. parent_id=folder.parent_id,
  1686. project_id=None,
  1687. archive_id=None,
  1688. is_external=True,
  1689. external_path=folder.external_path,
  1690. external_readonly=folder.external_readonly,
  1691. external_show_hidden=folder.external_show_hidden,
  1692. file_count=0,
  1693. # Newly-created external folder hasn't been scanned yet — fall back
  1694. # to the folder's own updated_at (#1770).
  1695. latest_activity_at=folder.updated_at,
  1696. **_folder_access_fields(await _load_index(db, current_user), folder, current_user),
  1697. created_at=folder.created_at,
  1698. updated_at=folder.updated_at,
  1699. )
  1700. def _mtime_to_datetime(mtime: float) -> datetime:
  1701. """Convert an ``os.stat().st_mtime`` epoch value to a naive-UTC datetime (#2680).
  1702. Naive UTC to match the other library timestamp columns (``created_at`` /
  1703. ``updated_at`` are naive ``func.now()``), so activity comparisons never mix
  1704. naive and aware values on either dialect.
  1705. """
  1706. return datetime.fromtimestamp(mtime, tz=timezone.utc).replace(tzinfo=None)
  1707. @router.post("/folders/{folder_id}/scan")
  1708. async def scan_external_folder(
  1709. folder_id: int,
  1710. db: AsyncSession = Depends(get_db, scope="function"),
  1711. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  1712. actor: User | ApiKeyActor | None = RequestActor,
  1713. ):
  1714. """Scan an external folder and sync files to the database.
  1715. Discovers new files, removes DB entries for deleted files.
  1716. Does not copy files — stores the external path directly.
  1717. """
  1718. # A mount the user can't see is 404, like a missing one (#3201).
  1719. folder = await get_visible_folder(db, folder_id, actor)
  1720. if not folder.is_external or not folder.external_path:
  1721. raise HTTPException(status_code=400, detail="Not an external folder")
  1722. ext_path = Path(folder.external_path)
  1723. if not ext_path.exists() or not ext_path.is_dir():
  1724. raise HTTPException(status_code=400, detail=f"External path is not accessible: {folder.external_path}")
  1725. # Collect all existing child external subfolder IDs (single query)
  1726. all_folder_ids = [folder_id]
  1727. child_result = await db.execute(
  1728. select(LibraryFolder).where(
  1729. LibraryFolder.is_external.is_(True),
  1730. LibraryFolder.parent_id.isnot(None),
  1731. )
  1732. )
  1733. all_child_folders = child_result.scalars().all()
  1734. # Walk the parent chain to find all descendants of folder_id
  1735. parent_to_children: dict[int, list] = {}
  1736. for cf in all_child_folders:
  1737. parent_to_children.setdefault(cf.parent_id, []).append(cf)
  1738. queue = [folder_id]
  1739. while queue:
  1740. pid = queue.pop()
  1741. for child in parent_to_children.get(pid, []):
  1742. all_folder_ids.append(child.id)
  1743. queue.append(child.id)
  1744. # Get existing DB files across root and all subfolders
  1745. existing_result = await db.execute(
  1746. LibraryFile.active().where(
  1747. LibraryFile.folder_id.in_(all_folder_ids),
  1748. LibraryFile.is_external.is_(True),
  1749. )
  1750. )
  1751. existing_files = {f.file_path: f for f in existing_result.scalars().all()}
  1752. # Build folder cache: relative path -> folder_id (for resolving subfolders)
  1753. # Pre-populate with existing child folders keyed by their external_path
  1754. folder_cache: dict[str, int] = {"": folder_id}
  1755. for fid in all_folder_ids:
  1756. if fid == folder_id:
  1757. continue
  1758. # Find the child folder object
  1759. for cf in all_child_folders:
  1760. if cf.id == fid and cf.external_path:
  1761. try:
  1762. rel = str(Path(cf.external_path).relative_to(ext_path))
  1763. if rel != ".":
  1764. folder_cache[rel] = cf.id
  1765. except ValueError:
  1766. pass
  1767. # Scan the directory
  1768. added = 0
  1769. removed = 0
  1770. found_paths: set[str] = set()
  1771. seen_rel_dirs: set[str] = set()
  1772. # Real on-disk mtime per visited folder id (#2680), applied after the walk.
  1773. folder_mtimes: dict[int, datetime] = {}
  1774. for dirpath, dirnames, filenames in os.walk(ext_path):
  1775. # Filter hidden directories unless configured
  1776. if not folder.external_show_hidden:
  1777. dirnames[:] = [d for d in dirnames if not d.startswith(".")]
  1778. rel_dir = str(Path(dirpath).relative_to(ext_path))
  1779. if rel_dir == ".":
  1780. rel_dir = ""
  1781. seen_rel_dirs.add(rel_dir)
  1782. # Resolve or create subfolder chain for this directory
  1783. if rel_dir and rel_dir not in folder_cache:
  1784. parts = Path(rel_dir).parts
  1785. current_path = ""
  1786. current_parent = folder_id
  1787. for part in parts:
  1788. current_path = f"{current_path}/{part}".lstrip("/")
  1789. if current_path in folder_cache:
  1790. current_parent = folder_cache[current_path]
  1791. else:
  1792. existing_sub = await db.execute(
  1793. select(LibraryFolder).where(
  1794. LibraryFolder.name == part,
  1795. LibraryFolder.parent_id == current_parent,
  1796. LibraryFolder.is_external.is_(True),
  1797. )
  1798. )
  1799. existing_folder = existing_sub.scalar_one_or_none()
  1800. if existing_folder:
  1801. current_parent = existing_folder.id
  1802. else:
  1803. new_folder = LibraryFolder(
  1804. name=part,
  1805. parent_id=current_parent,
  1806. is_external=True,
  1807. external_path=str(
  1808. ext_path / current_path
  1809. ), # SEC-PATH-OK: current_path built from Path(rel_dir).parts of an os.walk descent under ext_path
  1810. external_readonly=folder.external_readonly,
  1811. external_show_hidden=folder.external_show_hidden,
  1812. # A scanned subfolder belongs with the mount (#3201).
  1813. created_by_id=folder.created_by_id,
  1814. shared=folder.shared,
  1815. )
  1816. db.add(new_folder)
  1817. await db.flush()
  1818. current_parent = new_folder.id
  1819. folder_cache[current_path] = current_parent
  1820. target_folder_id = folder_cache.get(rel_dir, folder_id)
  1821. # Record this directory's own mtime (#2680). os.walk visits every
  1822. # directory once, so this covers the root external folder and every
  1823. # subfolder (existing or just created). Applied to the folder rows
  1824. # after the walk completes.
  1825. try:
  1826. folder_mtimes[target_folder_id] = _mtime_to_datetime(os.stat(dirpath).st_mtime)
  1827. except OSError:
  1828. pass
  1829. for filename in filenames:
  1830. # Skip hidden files unless configured
  1831. if not folder.external_show_hidden and filename.startswith("."):
  1832. continue
  1833. filepath = (
  1834. Path(dirpath) / filename
  1835. ) # SEC-PATH-OK: dirpath + filename from os.walk(ext_path); filesystem-discovered, not user input
  1836. ext = filepath.suffix.lower()
  1837. # Check for compound extensions like .gcode.3mf
  1838. if ext not in _SCANNABLE_EXTENSIONS:
  1839. # Check compound
  1840. compound = "".join(filepath.suffixes[-2:]).lower() if len(filepath.suffixes) >= 2 else ""
  1841. if compound not in _SCANNABLE_EXTENSIONS:
  1842. continue
  1843. # Resolve symlinks and ensure still under external_path
  1844. try:
  1845. real_path = filepath.resolve()
  1846. real_path.relative_to(ext_path.resolve())
  1847. except (ValueError, OSError):
  1848. continue # Symlink escapes the external dir
  1849. file_path_str = str(filepath)
  1850. found_paths.add(file_path_str)
  1851. if file_path_str in existing_files:
  1852. # Already tracked — refresh its on-disk mtime (#2680) so a file
  1853. # edited/replaced over the mount (samba, etc.) re-sorts correctly
  1854. # and old rows scanned before this field existed get backfilled.
  1855. tracked = existing_files[file_path_str]
  1856. try:
  1857. fs_mtime = _mtime_to_datetime(filepath.stat().st_mtime)
  1858. except OSError:
  1859. fs_mtime = None
  1860. if fs_mtime is not None and tracked.fs_modified_at != fs_mtime:
  1861. tracked.fs_modified_at = fs_mtime
  1862. continue
  1863. # Get file info
  1864. try:
  1865. stat = filepath.stat()
  1866. except OSError:
  1867. continue
  1868. # The zip is opened for the thumbnail immediately below either way,
  1869. # so judging a `.3mf` on its contents rather than its name (#2993)
  1870. # costs this scan nothing.
  1871. file_type = classify_file_type(filename, filepath)
  1872. # Extract thumbnail for 3mf files (including .gcode.3mf sliced
  1873. # outputs — those are 3MF zips on disk and carry the same
  1874. # thumbnail Metadata/plate_1.png the parser reads). Pre-#1600
  1875. # the gate was `file_type == "3mf"` alone, so .gcode.3mf files
  1876. # in external folders silently got no thumbnail.
  1877. thumbnail_path = None
  1878. file_metadata = None
  1879. if file_type in ("3mf", "gcode.3mf"):
  1880. try:
  1881. parser = ThreeMFParser(str(filepath))
  1882. raw_metadata = parser.parse()
  1883. if raw_metadata:
  1884. # Extract thumbnail before cleaning metadata
  1885. thumb_data = raw_metadata.get("_thumbnail_data")
  1886. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  1887. if thumb_data:
  1888. thumb_dir = get_library_thumbnails_dir()
  1889. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  1890. thumb_full = (
  1891. thumb_dir / thumb_filename
  1892. ) # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + thumbnail_ext
  1893. thumb_full.write_bytes(thumb_data)
  1894. thumbnail_path = to_relative_path(thumb_full)
  1895. # Clean metadata - remove non-JSON-serializable data (bytes, etc.)
  1896. def clean_metadata(obj):
  1897. if isinstance(obj, dict):
  1898. return {
  1899. k: clean_metadata(v)
  1900. for k, v in obj.items()
  1901. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  1902. }
  1903. elif isinstance(obj, list):
  1904. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  1905. elif isinstance(obj, bytes):
  1906. return None
  1907. return obj
  1908. file_metadata = clean_metadata(raw_metadata)
  1909. except Exception as e:
  1910. logger.debug("Failed to extract metadata from external 3mf %s: %s", filepath, e)
  1911. # STL and PDF thumbnails are deferred to a background task spawned
  1912. # after the scan's db.commit() — see _backfill_external_thumbnails.
  1913. # Doing them inline would block the HTTP request for minutes on a
  1914. # large NAS mount (#1299).
  1915. # Extract gcode thumbnail
  1916. if file_type == "gcode" and thumbnail_path is None:
  1917. thumb_data = extract_gcode_thumbnail(filepath)
  1918. if thumb_data:
  1919. thumb_dir = get_library_thumbnails_dir()
  1920. thumb_filename = f"{uuid.uuid4().hex}.png"
  1921. thumb_full = thumb_dir / thumb_filename # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + ".png"
  1922. thumb_full.write_bytes(thumb_data)
  1923. thumbnail_path = to_relative_path(thumb_full)
  1924. # Create thumbnail for image files
  1925. if ext.lower() in IMAGE_EXTENSIONS and thumbnail_path is None:
  1926. thumbnail_path_str = create_image_thumbnail(filepath, get_library_thumbnails_dir())
  1927. if thumbnail_path_str:
  1928. thumbnail_path = to_relative_path(Path(thumbnail_path_str))
  1929. db_file = LibraryFile(
  1930. folder_id=target_folder_id,
  1931. is_external=True,
  1932. filename=filename,
  1933. file_path=file_path_str,
  1934. file_type=file_type,
  1935. file_size=stat.st_size,
  1936. file_hash=None, # Skip hashing external files for performance
  1937. thumbnail_path=thumbnail_path,
  1938. file_metadata=_without_print_name(file_metadata),
  1939. fs_modified_at=_mtime_to_datetime(stat.st_mtime), # #2680: real on-disk mtime
  1940. )
  1941. db.add(db_file)
  1942. added += 1
  1943. # Remove DB entries for files that no longer exist on disk.
  1944. #
  1945. # Gate on actual disk presence, NOT merely absence from found_paths:
  1946. # found_paths only collects extensions in _SCANNABLE_EXTENSIONS, so a
  1947. # record for any other file the upload path admitted (e.g. a .md README,
  1948. # #2520) would otherwise be treated as "deleted from disk" and purged on
  1949. # every scan even though the file is still there. os.path.exists keeps
  1950. # such records; genuinely-deleted files (absent from disk) are still
  1951. # cleaned up. External file_path is the absolute on-disk path.
  1952. vanished_ids: list[int] = []
  1953. for path_str, db_file in existing_files.items():
  1954. if path_str not in found_paths and not os.path.exists(path_str):
  1955. # Clean up thumbnail if we generated one
  1956. if db_file.thumbnail_path:
  1957. try:
  1958. abs_thumb = to_absolute_path(db_file.thumbnail_path)
  1959. if abs_thumb and abs_thumb.exists():
  1960. abs_thumb.unlink()
  1961. except OSError:
  1962. pass
  1963. # The row is gone for good — external files skip the trash — so
  1964. # its photos go with it rather than being orphaned under an id
  1965. # nothing points at any more (#3077).
  1966. remove_library_photos_dir(db_file.id)
  1967. vanished_ids.append(db_file.id)
  1968. if vanished_ids:
  1969. # Same clean-up as every other hard delete of library rows, once for
  1970. # all of them: a share that lost thousands of files must not run it
  1971. # per file while holding the SQLite write lock.
  1972. from backend.app.services.library_trash import delete_dependent_variants, release_queue_references
  1973. await delete_dependent_variants(db, vanished_ids)
  1974. await release_queue_references(db, vanished_ids)
  1975. await db.execute(delete(LibraryFile).where(LibraryFile.id.in_(vanished_ids)))
  1976. removed += len(vanished_ids)
  1977. # Remove empty subfolders whose directories no longer exist on disk
  1978. # Process deepest-first by sorting on path depth (descending)
  1979. subfolder_entries = [(rel, fid) for rel, fid in folder_cache.items() if rel and fid != folder_id]
  1980. subfolder_entries.sort(key=lambda x: x[0].count("/"), reverse=True)
  1981. for rel_path, sub_fid in subfolder_entries:
  1982. if rel_path in seen_rel_dirs:
  1983. continue # Directory still exists on disk
  1984. # Check if subfolder has any remaining files
  1985. file_count_result = await db.execute(
  1986. select(func.count(LibraryFile.id)).where(
  1987. LibraryFile.folder_id == sub_fid,
  1988. LibraryFile.deleted_at.is_(None),
  1989. )
  1990. )
  1991. if (file_count_result.scalar() or 0) == 0:
  1992. # Check if it has any remaining child folders
  1993. child_count_result = await db.execute(
  1994. select(func.count(LibraryFolder.id)).where(LibraryFolder.parent_id == sub_fid)
  1995. )
  1996. if (child_count_result.scalar() or 0) == 0:
  1997. sub_folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == sub_fid))
  1998. sub_folder_obj = sub_folder_result.scalar_one_or_none()
  1999. if sub_folder_obj:
  2000. await db.delete(sub_folder_obj)
  2001. folder_mtimes.pop(sub_fid, None)
  2002. # Persist each visited folder's real directory mtime (#2680). Fetched in one
  2003. # trip; folders deleted by the cleanup above were dropped from folder_mtimes.
  2004. if folder_mtimes:
  2005. folders_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id.in_(list(folder_mtimes.keys()))))
  2006. for folder_obj in folders_result.scalars().all():
  2007. new_mtime = folder_mtimes.get(folder_obj.id)
  2008. if new_mtime is not None and folder_obj.fs_modified_at != new_mtime:
  2009. folder_obj.fs_modified_at = new_mtime
  2010. await db.commit()
  2011. # Spawn STL/PDF thumbnail backfill in the background — the scan endpoint
  2012. # returns immediately so the FE modal closes and subdirectories are
  2013. # visible right away; thumbnails fill in over the following seconds /
  2014. # minutes as the task processes each file. Survives FE refresh —
  2015. # the task lives in the FastAPI event loop, not the request scope.
  2016. # folder_cache.values() covers the root + every pre-existing subfolder
  2017. # + every subfolder created during this scan. all_folder_ids on its own
  2018. # would miss the newly-created ones (it's snapshotted before the walk).
  2019. spawn_background_task(
  2020. _backfill_external_thumbnails(list(set(folder_cache.values()))),
  2021. name=f"thumbnail-backfill-folder-{folder_id}",
  2022. )
  2023. return {"status": "success", "added": added, "removed": removed}
  2024. # ============ File Endpoints ============
  2025. @router.get("/files", response_model=list[FileListResponse])
  2026. @router.get("/files/", response_model=list[FileListResponse])
  2027. async def list_files(
  2028. response: Response,
  2029. folder_id: int | None = None,
  2030. project_id: int | None = None,
  2031. include_root: bool = True,
  2032. internal_only: bool = False,
  2033. external_only: bool = False,
  2034. recursive: bool = False,
  2035. tag_ids: list[int] = Query(default_factory=list),
  2036. db: AsyncSession = Depends(get_db, scope="function"),
  2037. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2038. require_ownership_permission(
  2039. Permission.LIBRARY_READ_ALL,
  2040. Permission.LIBRARY_READ_OWN,
  2041. )
  2042. ),
  2043. ):
  2044. """List files, optionally filtered by folder or project.
  2045. Args:
  2046. folder_id: Filter by folder ID. If None and include_root=True, returns root files.
  2047. project_id: Return all files across folders linked to this project (bulk fetch, avoids N+1).
  2048. include_root: If True and folder_id is None, returns files at root level.
  2049. If False and folder_id is None, returns all files.
  2050. internal_only: Restrict the result to files in managed storage (`is_external=False`).
  2051. Used by the File Manager's "All Files" sidebar entry so a linked NAS
  2052. with hundreds of files doesn't drown the user's own uploads (#1621).
  2053. external_only: Restrict the result to files under external folders
  2054. (`is_external=True`) — the symmetric combined view for users with
  2055. multiple linked external sources (#1621).
  2056. recursive: When combined with ``folder_id``, also include files in every
  2057. descendant subfolder (#1268). Implemented via a recursive CTE
  2058. that walks ``library_folders.parent_id``. Default off so
  2059. existing callers (folder browsing, etc.) keep their narrow
  2060. single-folder semantics.
  2061. tag_ids: Restrict the listing to files carrying ALL of these tags
  2062. (AND semantics, #1268). When non-empty the folder filter is
  2063. intentionally bypassed — tags are cross-cutting and the user
  2064. wants "every file with this tag" regardless of where it lives.
  2065. ``recursive`` becomes irrelevant in that case.
  2066. """
  2067. if internal_only and external_only:
  2068. raise HTTPException(
  2069. status_code=400,
  2070. detail="internal_only and external_only are mutually exclusive",
  2071. )
  2072. user, can_read_all = auth_result
  2073. query = LibraryFile.active().options(
  2074. selectinload(LibraryFile.created_by),
  2075. selectinload(LibraryFile.tags),
  2076. )
  2077. if user is not None and not can_read_all:
  2078. query = query.where(LibraryFile.created_by_id == user.id)
  2079. if tag_ids:
  2080. # Cross-cutting filter — every requested tag must be present on the
  2081. # file. JOIN + GROUP BY + HAVING COUNT(DISTINCT) is portable across
  2082. # SQLite and Postgres without dialect tricks. We deliberately skip
  2083. # the folder / project / include_root scoping below so the result
  2084. # is the global "all files carrying these tags".
  2085. unique_tag_ids = list(dict.fromkeys(tag_ids))
  2086. query = (
  2087. query.join(LibraryFileTag, LibraryFileTag.file_id == LibraryFile.id)
  2088. .where(LibraryFileTag.tag_id.in_(unique_tag_ids))
  2089. .group_by(LibraryFile.id)
  2090. .having(func.count(distinct(LibraryFileTag.tag_id)) == len(unique_tag_ids))
  2091. )
  2092. elif folder_id is not None and recursive:
  2093. # Walk the subtree starting at folder_id and collect every descendant
  2094. # id. Recursive CTE works on both SQLite (>=3.8.3, shipped 2014) and
  2095. # Postgres without dialect branching.
  2096. roots = (
  2097. select(LibraryFolder.id).where(LibraryFolder.id == folder_id).cte(name="folder_descendants", recursive=True)
  2098. )
  2099. descendants = roots.union_all(select(LibraryFolder.id).join(roots, LibraryFolder.parent_id == roots.c.id))
  2100. query = query.where(LibraryFile.folder_id.in_(select(descendants.c.id)))
  2101. elif folder_id is not None:
  2102. query = query.where(LibraryFile.folder_id == folder_id)
  2103. elif project_id is not None:
  2104. # Single join instead of one query per folder (avoids N+1 pattern)
  2105. query = query.join(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  2106. query = query.where(LibraryFolder.project_id == project_id)
  2107. elif include_root:
  2108. query = query.where(LibraryFile.folder_id.is_(None))
  2109. if internal_only:
  2110. query = query.where(LibraryFile.is_external.is_(False))
  2111. elif external_only:
  2112. query = query.where(LibraryFile.is_external.is_(True))
  2113. query = query.order_by(LibraryFile.filename)
  2114. result = await db.execute(query)
  2115. files = result.scalars().unique().all() if tag_ids else result.scalars().all()
  2116. # Get duplicate counts
  2117. hash_counts = {}
  2118. if files:
  2119. hashes = [f.file_hash for f in files if f.file_hash]
  2120. if hashes:
  2121. dup_result = await db.execute(
  2122. select(LibraryFile.file_hash, func.count(LibraryFile.id))
  2123. .where(LibraryFile.file_hash.in_(hashes), LibraryFile.deleted_at.is_(None))
  2124. .group_by(LibraryFile.file_hash)
  2125. )
  2126. hash_counts = {h: c - 1 for h, c in dup_result.all()} # -1 to exclude self
  2127. # Variant group sizes (#671 / #2570). Counted across the whole group rather
  2128. # than the rows on screen — members can sit in different folders, so counting
  2129. # the listing would under-report and the "2 versions" badge would blink in
  2130. # and out as the user navigated.
  2131. variant_counts: dict[int, int] = {}
  2132. group_ids = {f.variant_group_id for f in files if f.variant_group_id}
  2133. if group_ids:
  2134. count_result = await db.execute(
  2135. select(LibraryFile.variant_group_id, func.count(LibraryFile.id))
  2136. .where(LibraryFile.variant_group_id.in_(group_ids), LibraryFile.deleted_at.is_(None))
  2137. .group_by(LibraryFile.variant_group_id)
  2138. )
  2139. variant_counts = dict(count_result.all())
  2140. # Prevent browser caching of file list
  2141. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  2142. file_list = []
  2143. for f in files:
  2144. # Extract key metadata for display
  2145. print_name = None
  2146. print_time = None
  2147. filament_grams = None
  2148. sliced_for_model = None
  2149. if f.file_metadata:
  2150. print_name = f.file_metadata.get("print_name")
  2151. print_time = f.file_metadata.get("print_time_seconds")
  2152. filament_grams = f.file_metadata.get("filament_used_grams")
  2153. sliced_for_model = f.file_metadata.get("sliced_for_model")
  2154. file_list.append(
  2155. FileListResponse(
  2156. id=f.id,
  2157. folder_id=f.folder_id,
  2158. is_external=f.is_external,
  2159. filename=f.filename,
  2160. file_type=f.file_type,
  2161. file_size=f.file_size,
  2162. thumbnail_path=f.thumbnail_path,
  2163. print_count=f.print_count,
  2164. duplicate_count=hash_counts.get(f.file_hash, 0) if f.file_hash else 0,
  2165. created_by_id=f.created_by_id,
  2166. created_by_username=f.created_by.username if f.created_by else None,
  2167. created_at=f.created_at,
  2168. fs_modified_at=f.fs_modified_at,
  2169. print_name=print_name,
  2170. print_time_seconds=print_time,
  2171. filament_used_grams=filament_grams,
  2172. sliced_for_model=sliced_for_model,
  2173. tags=[TagSummary(id=t.id, name=t.name) for t in f.tags],
  2174. variant_group_id=f.variant_group_id,
  2175. variant_count=variant_counts.get(f.variant_group_id, 0) if f.variant_group_id else 0,
  2176. external_url=f.external_url,
  2177. has_notes=bool(f.notes),
  2178. photo_count=len(f.photos or []),
  2179. )
  2180. )
  2181. return file_list
  2182. @router.post("/files", response_model=FileUploadResponse)
  2183. @router.post("/files/", response_model=FileUploadResponse)
  2184. async def upload_file(
  2185. file: UploadFile = File(...),
  2186. folder_id: int | None = None,
  2187. generate_stl_thumbnails: bool = Query(default=True),
  2188. db: AsyncSession = Depends(get_db, scope="function"),
  2189. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  2190. actor: User | ApiKeyActor | None = RequestActor,
  2191. ):
  2192. """Upload a file to the library."""
  2193. try:
  2194. if not file.filename:
  2195. raise HTTPException(status_code=400, detail="Filename is required")
  2196. filename = file.filename
  2197. # Reject FAT32/exFAT-incompatible filenames up front (#1540).
  2198. try:
  2199. validate_print_filename(filename)
  2200. except InvalidFilenameError as e:
  2201. raise HTTPException(status_code=400, detail=str(e)) from e
  2202. # `ext` stays the trailing extension because the on-disk filename uses
  2203. # it directly and the 3MF-parse branch below still gates on
  2204. # `ext == ".3mf"`, which is correct for both `.3mf` and `.gcode.3mf`.
  2205. # `file_type` is compound-aware and is decided further down, once the
  2206. # bytes are on disk to be read.
  2207. ext = os.path.splitext(filename)[1].lower()
  2208. # Verify folder exists if specified, and that the user may add to it (#3201)
  2209. target_folder = None
  2210. if folder_id is not None:
  2211. target_folder = await get_writable_folder(db, folder_id, actor)
  2212. # Writable external folders write through to the mount so the file is
  2213. # visible outside Bambuddy (#1112); everything else lands under the
  2214. # internal library dir with a UUID-scoped filename. Resolved BEFORE
  2215. # the content validation below so folder-permission rejections
  2216. # (403 read-only, 400 missing path, 409 collision) still surface
  2217. # before any "bad file format" 400 — preserves existing error
  2218. # ordering / tests.
  2219. file_path, is_external_upload = _resolve_upload_destination(target_folder, filename)
  2220. # Read upload now so the validation can sniff magic bytes; the file
  2221. # is written to disk only after the checks. #1401.
  2222. content = await file.read()
  2223. validate_print_file_upload(filename, content)
  2224. # Save file
  2225. with open(file_path, "wb") as f:
  2226. f.write(content)
  2227. # Now that the bytes are on disk the zip can settle what the name only
  2228. # guessed at: a sliced 3MF uploaded as `Foo.3mf` is a sliced 3MF (#2993).
  2229. file_type = classify_file_type(filename, file_path)
  2230. # Calculate hash
  2231. file_hash = calculate_file_hash(file_path)
  2232. # Check for duplicates
  2233. dup_result = await db.execute(
  2234. select(LibraryFile.id).where(LibraryFile.file_hash == file_hash, LibraryFile.deleted_at.is_(None)).limit(1)
  2235. )
  2236. duplicate_of = dup_result.scalar()
  2237. # Extract metadata and thumbnail
  2238. metadata = {}
  2239. thumbnail_path = None
  2240. thumbnails_dir = get_library_thumbnails_dir()
  2241. if ext == ".3mf":
  2242. try:
  2243. parser = ThreeMFParser(str(file_path))
  2244. raw_metadata = parser.parse()
  2245. # Extract thumbnail before cleaning metadata
  2246. thumbnail_data = raw_metadata.get("_thumbnail_data")
  2247. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  2248. # Save thumbnail if extracted
  2249. if thumbnail_data:
  2250. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  2251. thumb_path = (
  2252. thumbnails_dir / thumb_filename
  2253. ) # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + thumbnail_ext
  2254. with open(thumb_path, "wb") as f:
  2255. f.write(thumbnail_data)
  2256. thumbnail_path = str(thumb_path)
  2257. # Clean metadata - remove non-JSON-serializable data (bytes, etc.)
  2258. def clean_metadata(obj):
  2259. if isinstance(obj, dict):
  2260. return {
  2261. k: clean_metadata(v)
  2262. for k, v in obj.items()
  2263. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  2264. }
  2265. elif isinstance(obj, list):
  2266. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  2267. elif isinstance(obj, bytes):
  2268. return None
  2269. return obj
  2270. metadata = clean_metadata(raw_metadata)
  2271. except Exception as e:
  2272. logger.warning("Failed to parse 3MF: %s", e)
  2273. elif ext == ".gcode":
  2274. # Extract embedded thumbnail from gcode
  2275. try:
  2276. thumbnail_data = extract_gcode_thumbnail(file_path)
  2277. if thumbnail_data:
  2278. thumb_filename = f"{uuid.uuid4().hex}.png"
  2279. thumb_path = (
  2280. thumbnails_dir / thumb_filename
  2281. ) # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + ".png"
  2282. with open(thumb_path, "wb") as f:
  2283. f.write(thumbnail_data)
  2284. thumbnail_path = str(thumb_path)
  2285. except Exception as e:
  2286. logger.warning("Failed to extract gcode thumbnail: %s", e)
  2287. elif ext.lower() in IMAGE_EXTENSIONS:
  2288. # For image files, create a thumbnail from the image itself
  2289. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  2290. elif ext.lower() == ".pdf":
  2291. # Page one, rendered server-side; the browser preview's own
  2292. # render (POST /preview-thumbnail) remains the fallback.
  2293. thumbnail_path = await asyncio.to_thread(generate_pdf_thumbnail, file_path, thumbnails_dir)
  2294. elif ext == ".stl":
  2295. # Generate STL thumbnail if enabled. Same MIN_USABLE_STL_BYTES
  2296. # pre-skip as extract_zip_file — stubs / placeholders below this
  2297. # size can't contain a triangle so trimesh would return an empty
  2298. # mesh anyway.
  2299. if generate_stl_thumbnails:
  2300. try:
  2301. if file_path.stat().st_size >= MIN_USABLE_STL_BYTES:
  2302. thumbnail_path = await _render_stl_thumbnail(file_path, thumbnails_dir)
  2303. except OSError:
  2304. pass
  2305. # Create database entry (managed files store relative paths for portability;
  2306. # external files store the absolute mount path — same shape as scan produces)
  2307. library_file = LibraryFile(
  2308. folder_id=folder_id,
  2309. is_external=is_external_upload,
  2310. filename=filename,
  2311. file_path=_stored_file_path(file_path, is_external_upload),
  2312. file_type=file_type,
  2313. file_size=len(content),
  2314. file_hash=file_hash,
  2315. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  2316. file_metadata=_without_print_name(metadata) if metadata else None,
  2317. created_by_id=actor.id if actor else None,
  2318. )
  2319. db.add(library_file)
  2320. await db.commit()
  2321. await db.refresh(library_file)
  2322. return FileUploadResponse(
  2323. id=library_file.id,
  2324. filename=library_file.filename,
  2325. file_type=library_file.file_type,
  2326. file_size=library_file.file_size,
  2327. thumbnail_path=library_file.thumbnail_path,
  2328. duplicate_of=duplicate_of,
  2329. metadata=library_file.file_metadata,
  2330. )
  2331. except HTTPException:
  2332. raise
  2333. except Exception as e:
  2334. logger.error("Upload failed for %s: %s", file.filename, e, exc_info=True)
  2335. raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
  2336. @router.post("/files/extract-zip", response_model=ZipExtractResponse)
  2337. async def extract_zip_file(
  2338. file: UploadFile = File(...),
  2339. folder_id: int | None = Query(default=None),
  2340. preserve_structure: bool = Query(default=True),
  2341. create_folder_from_zip: bool = Query(default=False),
  2342. generate_stl_thumbnails: bool = Query(default=True),
  2343. db: AsyncSession = Depends(get_db, scope="function"),
  2344. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  2345. actor: User | ApiKeyActor | None = RequestActor,
  2346. ):
  2347. """Upload and extract a ZIP file to the library.
  2348. Args:
  2349. file: The ZIP file to extract
  2350. folder_id: Target folder ID (None = root)
  2351. preserve_structure: If True, recreate folder structure from ZIP; if False, extract all files flat
  2352. create_folder_from_zip: If True, create a folder named after the ZIP file and extract into it
  2353. generate_stl_thumbnails: If True, generate thumbnails for STL files
  2354. """
  2355. import tempfile
  2356. if not file.filename or not file.filename.lower().endswith(".zip"):
  2357. raise HTTPException(status_code=400, detail="Only ZIP files are supported")
  2358. # Verify target folder exists if specified, and that the user may add to it (#3201)
  2359. if folder_id is not None:
  2360. target_folder = await get_writable_folder(db, folder_id, actor)
  2361. if target_folder.is_external and target_folder.external_readonly:
  2362. raise HTTPException(status_code=403, detail="Cannot extract ZIP to a read-only external folder")
  2363. if target_folder.is_external:
  2364. # Writable external folders aren't supported by extract-zip because the
  2365. # nested-subfolder creation path would need to mkdir on the mount and
  2366. # create matching is_external=True LibraryFolder rows — a separate
  2367. # design. Direct the user at Scan, which already handles that shape
  2368. # (#1112).
  2369. raise HTTPException(
  2370. status_code=400,
  2371. detail=(
  2372. "Cannot extract ZIP directly into an external folder. "
  2373. "Extract the ZIP on the external mount and run 'Scan External Folder' instead."
  2374. ),
  2375. )
  2376. # Save ZIP to temp file
  2377. try:
  2378. with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp:
  2379. content = await file.read()
  2380. tmp.write(content)
  2381. tmp_path = tmp.name
  2382. except Exception as e:
  2383. raise HTTPException(status_code=500, detail=f"Failed to save ZIP file: {str(e)}")
  2384. extracted_files: list[ZipExtractResult] = []
  2385. errors: list[ZipExtractError] = []
  2386. folders_created = 0
  2387. folder_cache: dict[str, int] = {} # path -> folder_id
  2388. # The upload may have taken a while; and again before each file below.
  2389. await require_actor_still_exists(db, actor)
  2390. # If create_folder_from_zip is True, create a folder named after the ZIP file
  2391. zip_folder_id = folder_id
  2392. logger.info(
  2393. f"ZIP extraction: create_folder_from_zip={create_folder_from_zip}, folder_id={folder_id}, filename={file.filename}"
  2394. )
  2395. if create_folder_from_zip and file.filename:
  2396. # Remove .zip extension to get folder name
  2397. zip_folder_name = file.filename[:-4] if file.filename.lower().endswith(".zip") else file.filename
  2398. # Check if folder already exists
  2399. existing = await db.execute(
  2400. select(LibraryFolder).where(
  2401. LibraryFolder.name == zip_folder_name,
  2402. LibraryFolder.parent_id == folder_id if folder_id else LibraryFolder.parent_id.is_(None),
  2403. )
  2404. )
  2405. # Reuse a same-named folder only when the user may write to it; never
  2406. # extract into someone else's folder that happens to share the name (#3201).
  2407. existing_folder = next(
  2408. (f for f in existing.scalars().all() if can_write_folder(f, actor)),
  2409. None,
  2410. )
  2411. if existing_folder:
  2412. zip_folder_id = existing_folder.id
  2413. logger.info("Reusing existing folder '%s' with id=%s", zip_folder_name, zip_folder_id)
  2414. else:
  2415. # Create folder
  2416. new_folder = LibraryFolder(
  2417. name=zip_folder_name,
  2418. parent_id=folder_id,
  2419. created_by_id=actor.id if actor else None,
  2420. # Made without a user (auth off, an API key): everyone's, as before #3201.
  2421. shared=actor is None or actor.id is None,
  2422. )
  2423. db.add(new_folder)
  2424. await db.flush()
  2425. await db.commit() # Commit folder creation immediately
  2426. zip_folder_id = new_folder.id
  2427. folders_created += 1
  2428. logger.info("Created new folder '%s' with id=%s", zip_folder_name, zip_folder_id)
  2429. try:
  2430. with zipfile.ZipFile(tmp_path, "r") as zf:
  2431. # Filter out directories and hidden/system files
  2432. file_list = [
  2433. name
  2434. for name in zf.namelist()
  2435. if not name.endswith("/")
  2436. and not name.startswith("__MACOSX")
  2437. and not os.path.basename(name).startswith(".")
  2438. ]
  2439. for zip_path in file_list:
  2440. # An extract can run for minutes; a user deleted meanwhile must
  2441. # not have the rest saved under their id (SQLite reuses it).
  2442. await require_actor_still_exists(db, actor)
  2443. try:
  2444. # Determine target folder (use zip_folder_id as base if create_folder_from_zip was used)
  2445. target_folder_id = zip_folder_id
  2446. if preserve_structure:
  2447. # Get directory path from ZIP
  2448. dir_path = os.path.dirname(zip_path)
  2449. if dir_path:
  2450. # Create folder structure
  2451. parts = dir_path.split("/")
  2452. current_parent = zip_folder_id
  2453. current_path = ""
  2454. for part in parts:
  2455. if not part:
  2456. continue
  2457. current_path = f"{current_path}/{part}" if current_path else part
  2458. if current_path in folder_cache:
  2459. current_parent = folder_cache[current_path]
  2460. else:
  2461. # Check if folder exists
  2462. existing = await db.execute(
  2463. select(LibraryFolder).where(
  2464. LibraryFolder.name == part,
  2465. LibraryFolder.parent_id == current_parent
  2466. if current_parent
  2467. else LibraryFolder.parent_id.is_(None),
  2468. )
  2469. )
  2470. existing_folder = next(
  2471. (f for f in existing.scalars().all() if can_write_folder(f, actor)),
  2472. None,
  2473. )
  2474. if existing_folder:
  2475. current_parent = existing_folder.id
  2476. else:
  2477. # Create folder
  2478. new_folder = LibraryFolder(
  2479. name=part,
  2480. parent_id=current_parent,
  2481. created_by_id=actor.id if actor else None,
  2482. # Made without a user (auth off, an API key): everyone's, as before #3201.
  2483. shared=actor is None or actor.id is None,
  2484. )
  2485. db.add(new_folder)
  2486. await db.flush()
  2487. current_parent = new_folder.id
  2488. folders_created += 1
  2489. folder_cache[current_path] = current_parent
  2490. target_folder_id = current_parent
  2491. # Extract file
  2492. filename = os.path.basename(zip_path)
  2493. ext = os.path.splitext(filename)[1].lower()
  2494. # Generate unique filename for storage
  2495. unique_filename = f"{uuid.uuid4().hex}{ext}"
  2496. file_path = (
  2497. get_library_files_dir() / unique_filename
  2498. ) # SEC-PATH-OK: unique_filename = uuid.uuid4().hex + ext
  2499. # Extract and save file
  2500. file_content = zf.read(zip_path)
  2501. with open(file_path, "wb") as f:
  2502. f.write(file_content)
  2503. # Classified once the bytes are on disk so a sliced 3MF
  2504. # named `Foo.3mf` inside the zip is recognised as sliced
  2505. # (#2993) rather than trusted to say so in its name.
  2506. file_type = classify_file_type(filename, file_path)
  2507. # Calculate hash
  2508. file_hash = calculate_file_hash(file_path)
  2509. # Extract metadata and thumbnail for 3MF files
  2510. metadata = {}
  2511. thumbnail_path = None
  2512. thumbnails_dir = get_library_thumbnails_dir()
  2513. if ext == ".3mf":
  2514. try:
  2515. parser = ThreeMFParser(str(file_path))
  2516. raw_metadata = parser.parse()
  2517. thumbnail_data = raw_metadata.get("_thumbnail_data")
  2518. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  2519. if thumbnail_data:
  2520. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  2521. thumb_path = (
  2522. thumbnails_dir / thumb_filename
  2523. ) # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + thumbnail_ext
  2524. with open(thumb_path, "wb") as f:
  2525. f.write(thumbnail_data)
  2526. thumbnail_path = str(thumb_path)
  2527. def clean_metadata(obj):
  2528. if isinstance(obj, dict):
  2529. return {
  2530. k: clean_metadata(v)
  2531. for k, v in obj.items()
  2532. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  2533. }
  2534. elif isinstance(obj, list):
  2535. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  2536. elif isinstance(obj, bytes):
  2537. return None
  2538. return obj
  2539. metadata = clean_metadata(raw_metadata)
  2540. except Exception as e:
  2541. logger.warning("Failed to parse 3MF from ZIP: %s", e)
  2542. elif ext == ".gcode":
  2543. try:
  2544. thumbnail_data = extract_gcode_thumbnail(file_path)
  2545. if thumbnail_data:
  2546. thumb_filename = f"{uuid.uuid4().hex}.png"
  2547. thumb_path = (
  2548. thumbnails_dir / thumb_filename
  2549. ) # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + ".png"
  2550. with open(thumb_path, "wb") as f:
  2551. f.write(thumbnail_data)
  2552. thumbnail_path = str(thumb_path)
  2553. except Exception as e:
  2554. logger.warning("Failed to extract gcode thumbnail from ZIP: %s", e)
  2555. elif ext.lower() in IMAGE_EXTENSIONS:
  2556. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  2557. elif ext.lower() == ".pdf":
  2558. thumbnail_path = await asyncio.to_thread(generate_pdf_thumbnail, file_path, thumbnails_dir)
  2559. elif ext == ".stl":
  2560. # Generate STL thumbnail if enabled. Pre-skip files
  2561. # below MIN_USABLE_STL_BYTES — they can't contain
  2562. # even a single triangle, and bulk-uploaded ZIPs of
  2563. # stub STLs would otherwise log one debug line per
  2564. # file via the empty-mesh branch in trimesh.load.
  2565. if generate_stl_thumbnails and len(file_content) >= MIN_USABLE_STL_BYTES:
  2566. thumbnail_path = await _render_stl_thumbnail(file_path, thumbnails_dir)
  2567. # Create database entry (store relative paths for portability)
  2568. library_file = LibraryFile(
  2569. folder_id=target_folder_id,
  2570. filename=filename,
  2571. file_path=to_relative_path(file_path),
  2572. file_type=file_type,
  2573. file_size=len(file_content),
  2574. file_hash=file_hash,
  2575. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  2576. file_metadata=_without_print_name(metadata) if metadata else None,
  2577. created_by_id=actor.id if actor else None,
  2578. )
  2579. db.add(library_file)
  2580. await db.flush()
  2581. await db.refresh(library_file)
  2582. extracted_files.append(
  2583. ZipExtractResult(
  2584. filename=filename,
  2585. file_id=library_file.id,
  2586. folder_id=target_folder_id,
  2587. )
  2588. )
  2589. # Commit after each file to release database lock
  2590. # This prevents long-running transactions from blocking other requests
  2591. await db.commit()
  2592. except Exception as e:
  2593. logger.error("Failed to extract %s: %s", zip_path, e)
  2594. errors.append(ZipExtractError(filename=os.path.basename(zip_path), error=str(e)))
  2595. # Rollback the failed file but continue with others
  2596. await db.rollback()
  2597. return ZipExtractResponse(
  2598. extracted=len(extracted_files),
  2599. folders_created=folders_created,
  2600. files=extracted_files,
  2601. errors=errors,
  2602. )
  2603. except zipfile.BadZipFile:
  2604. raise HTTPException(status_code=400, detail="Invalid or corrupted ZIP file")
  2605. except HTTPException:
  2606. raise
  2607. except Exception as e:
  2608. logger.error("ZIP extraction failed: %s", e, exc_info=True)
  2609. raise HTTPException(status_code=500, detail=f"ZIP extraction failed: {str(e)}")
  2610. finally:
  2611. # Clean up temp file
  2612. try:
  2613. os.unlink(tmp_path)
  2614. except OSError:
  2615. pass # Best-effort temp file cleanup; ignore if already removed
  2616. # ============ STL Thumbnail Batch Generation ============
  2617. @router.post("/generate-stl-thumbnails", response_model=BatchThumbnailResponse)
  2618. async def batch_generate_stl_thumbnails(
  2619. request: BatchThumbnailRequest,
  2620. db: AsyncSession = Depends(get_db, scope="function"),
  2621. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  2622. require_ownership_permission(
  2623. Permission.LIBRARY_UPDATE_ALL,
  2624. Permission.LIBRARY_UPDATE_OWN,
  2625. )
  2626. ),
  2627. ):
  2628. """Generate thumbnails for STL and PDF files in batch.
  2629. With library:update_all this covers every matching file; with only
  2630. library:update_own it is narrowed to the caller's own files, the same
  2631. rule as update_file. The File Manager offers the toolbar button and the
  2632. per-file "Generate Thumbnail" entry to update_own users, and both land
  2633. here.
  2634. PDFs are included so the ones added before server-side PDF thumbnails
  2635. existed can be backfilled without opening each preview. The route keeps
  2636. its name for API compatibility.
  2637. Can generate thumbnails for:
  2638. - Specific file IDs (file_ids)
  2639. - All STL/PDF files in a folder (folder_id)
  2640. - All STL/PDF files missing thumbnails (all_missing=True)
  2641. """
  2642. thumbnails_dir = get_library_thumbnails_dir()
  2643. results: list[BatchThumbnailResult] = []
  2644. # Build query based on request
  2645. query = LibraryFile.active().where(LibraryFile.file_type.in_(("stl", "pdf")))
  2646. user, can_modify_all = auth_result
  2647. if not can_modify_all:
  2648. query = query.where(LibraryFile.created_by_id == user.id)
  2649. if request.file_ids:
  2650. # Specific files
  2651. query = query.where(LibraryFile.id.in_(request.file_ids))
  2652. elif request.folder_id is not None:
  2653. # All STL/PDF files in a specific folder
  2654. query = query.where(LibraryFile.folder_id == request.folder_id)
  2655. if not request.all_missing:
  2656. # If not specifically asking for missing thumbnails, get all
  2657. pass
  2658. else:
  2659. query = query.where(LibraryFile.thumbnail_path.is_(None))
  2660. elif request.all_missing:
  2661. # All STL/PDF files without thumbnails
  2662. query = query.where(LibraryFile.thumbnail_path.is_(None))
  2663. else:
  2664. # No criteria specified - return empty
  2665. return BatchThumbnailResponse(
  2666. processed=0,
  2667. succeeded=0,
  2668. failed=0,
  2669. results=[],
  2670. )
  2671. result = await db.execute(query)
  2672. target_files = result.scalars().all()
  2673. succeeded = 0
  2674. failed = 0
  2675. for target_file in target_files:
  2676. file_path = to_absolute_path(target_file.file_path)
  2677. if not file_path or not file_path.exists():
  2678. results.append(
  2679. BatchThumbnailResult(
  2680. file_id=target_file.id,
  2681. filename=target_file.filename,
  2682. success=False,
  2683. error="File not found on disk",
  2684. )
  2685. )
  2686. failed += 1
  2687. continue
  2688. try:
  2689. if target_file.file_type == "pdf":
  2690. thumbnail_path = await asyncio.to_thread(generate_pdf_thumbnail, file_path, thumbnails_dir)
  2691. else:
  2692. thumbnail_path = await _render_stl_thumbnail(file_path, thumbnails_dir)
  2693. if thumbnail_path:
  2694. # Update database with relative path
  2695. target_file.thumbnail_path = to_relative_path(thumbnail_path)
  2696. await db.flush()
  2697. results.append(
  2698. BatchThumbnailResult(
  2699. file_id=target_file.id,
  2700. filename=target_file.filename,
  2701. success=True,
  2702. )
  2703. )
  2704. succeeded += 1
  2705. else:
  2706. results.append(
  2707. BatchThumbnailResult(
  2708. file_id=target_file.id,
  2709. filename=target_file.filename,
  2710. success=False,
  2711. error="Thumbnail generation failed",
  2712. )
  2713. )
  2714. failed += 1
  2715. except Exception as e:
  2716. logger.error("Failed to generate thumbnail for %s: %s", target_file.filename, e)
  2717. results.append(
  2718. BatchThumbnailResult(
  2719. file_id=target_file.id,
  2720. filename=target_file.filename,
  2721. success=False,
  2722. error=str(e),
  2723. )
  2724. )
  2725. failed += 1
  2726. await db.commit()
  2727. return BatchThumbnailResponse(
  2728. processed=len(target_files),
  2729. succeeded=succeeded,
  2730. failed=failed,
  2731. results=results,
  2732. )
  2733. # ============ Queue Operations ============
  2734. # NOTE: These routes must be defined BEFORE /files/{file_id} to avoid path parameter conflicts
  2735. def is_sliced_file(filename: str) -> bool:
  2736. """Check if a file is a sliced (printable) file.
  2737. Sliced files are:
  2738. - .gcode files
  2739. - .3mf files that contain '.gcode.' in the name (e.g., filename.gcode.3mf)
  2740. """
  2741. lower = filename.lower()
  2742. return lower.endswith(".gcode") or ".gcode." in lower
  2743. @router.post("/files/combine", response_model=FileUploadResponse)
  2744. async def combine_files(
  2745. request: CombineFilesRequest,
  2746. db: AsyncSession = Depends(get_db, scope="function"),
  2747. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  2748. actor: User | ApiKeyActor | None = RequestActor,
  2749. ):
  2750. """Combine STL library files into one multi-object 3MF.
  2751. The slicer sidecar takes one model per slice, so putting several separate
  2752. STLs (or several copies of one, #2999) on one plate means building that
  2753. file first. The result is a new library file that slices like any other
  2754. 3MF; with auto-arrange on, the slicer lays the objects out on the bed.
  2755. The sources are left untouched.
  2756. """
  2757. from backend.app.services.mesh_combine import CombinePart, MeshCombineError, combine_parts_to_3mf
  2758. filename = request.filename.strip()
  2759. if not filename.lower().endswith(".3mf"):
  2760. filename = f"{filename}.3mf"
  2761. try:
  2762. validate_print_filename(filename)
  2763. except InvalidFilenameError as e:
  2764. raise HTTPException(status_code=400, detail=str(e)) from e
  2765. if request.folder_id is not None:
  2766. await get_writable_folder(db, request.folder_id, actor)
  2767. # Same per-row visibility the slice route applies: a READ_OWN caller must
  2768. # not be able to pull another user's model into their own file by raw id.
  2769. can_read_all = actor is None or actor.has_permission(Permission.LIBRARY_READ_ALL.value)
  2770. # The same file listed twice is one object with the copies added up, so
  2771. # its mesh is loaded and stored once. Order follows first appearance.
  2772. copies_by_id: dict[int, int] = {}
  2773. for item in request.items:
  2774. copies_by_id[item.file_id] = copies_by_id.get(item.file_id, 0) + item.copies
  2775. rows = (await db.execute(LibraryFile.active().where(LibraryFile.id.in_(copies_by_id)))).scalars().all()
  2776. by_id = {row.id: row for row in rows}
  2777. # Gate every source before touching any of them on disk, so the answer for
  2778. # a file the caller can't see is the same 404 whatever else is in the list.
  2779. sources = [_ensure_library_file_visible(by_id.get(file_id), actor, can_read_all) for file_id in copies_by_id]
  2780. parts: list[CombinePart] = []
  2781. for lib_file in sources:
  2782. if not lib_file.filename.lower().endswith(".stl"):
  2783. raise HTTPException(status_code=400, detail=f"Only STL files can be combined: {lib_file.filename}")
  2784. src_path = _resolve_source_disk_path(lib_file)
  2785. if src_path is None or not src_path.exists():
  2786. raise HTTPException(status_code=404, detail=f"Source file missing on disk: {lib_file.filename}")
  2787. parts.append(CombinePart(name=lib_file.filename, path=src_path, copies=copies_by_id[lib_file.id]))
  2788. try:
  2789. content = await asyncio.to_thread(combine_parts_to_3mf, parts)
  2790. except MeshCombineError as e:
  2791. raise HTTPException(status_code=400, detail=str(e)) from e
  2792. # The preview is embedded as Metadata/thumbnail.png by combine_parts_to_3mf,
  2793. # so ThreeMFParser picks it up here like any other 3MF's thumbnail. Loading
  2794. # the combined file back to render one would expand every copy.
  2795. await require_actor_still_exists(db, actor) # the combine may have taken a while
  2796. library_file, _ = await save_3mf_bytes_to_library(
  2797. db,
  2798. file_bytes=content,
  2799. filename=filename,
  2800. folder_id=request.folder_id,
  2801. source_type="combined",
  2802. owner_id=actor.id if actor else None,
  2803. )
  2804. return FileUploadResponse(
  2805. id=library_file.id,
  2806. filename=library_file.filename,
  2807. file_type=library_file.file_type,
  2808. file_size=library_file.file_size,
  2809. thumbnail_path=library_file.thumbnail_path,
  2810. metadata=library_file.file_metadata,
  2811. )
  2812. @router.post("/files/add-to-queue", response_model=AddToQueueResponse)
  2813. async def add_files_to_queue(
  2814. request: AddToQueueRequest,
  2815. db: AsyncSession = Depends(get_db, scope="function"),
  2816. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.QUEUE_CREATE)),
  2817. printer_scope: PrinterScope = RequestPrinterScope,
  2818. review_required: bool = QueueReviewRequired,
  2819. actor: User | ApiKeyActor | None = RequestActor,
  2820. ):
  2821. """Add library files to the print queue.
  2822. Only sliced files (.gcode or .gcode.3mf) can be added to the queue.
  2823. The archive will be created automatically when the print starts.
  2824. A caller may name a printer or a target model for the whole batch; with
  2825. neither, each file is aimed at the model it says it was sliced for. The
  2826. gates are the ones ``POST /queue/`` applies to a single item, because an
  2827. item that reaches the scheduler through this route has to be as printable
  2828. as one that reaches it through that one (#3112).
  2829. """
  2830. added: list[AddToQueueResult] = []
  2831. errors: list[AddToQueueError] = []
  2832. # Batch-level targeting. Rejected outright rather than per file: the whole
  2833. # request names one destination, so a bad one is not a property of any
  2834. # single file and reporting it fourteen times would say nothing extra.
  2835. target_model_norm = normalize_model_name(request.target_model)
  2836. if request.printer_id is not None and target_model_norm:
  2837. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  2838. if request.printer_id is not None:
  2839. printer_scope.ensure(request.printer_id)
  2840. printer_row = (await db.execute(select(Printer).where(Printer.id == request.printer_id))).scalar_one_or_none()
  2841. if not printer_row:
  2842. raise HTTPException(400, "Printer not found")
  2843. else:
  2844. # Without a printer, every file goes to "any printer of a model"
  2845. ensure_model_target_allowed(current_user, printer_scope)
  2846. # Active printers of every model, read once, and only when the batch has no
  2847. # printer of its own -- with one named, neither the check below nor the
  2848. # inference in the loop consults it. The explicit target is validated for
  2849. # the same reason POST /queue/ validates: a model nobody owns is a queue
  2850. # item that waits forever. The inferred target reads the same set and
  2851. # silently declines when it finds nothing, because there, owning no such
  2852. # printer is the user's situation rather than their mistake -- the file
  2853. # still queues, as the unassigned row it has always been.
  2854. # Keyed without regard to case, as the scheduler matches a model, to the
  2855. # printers' own spelling, which the items store.
  2856. active_models: dict[str, str] = {}
  2857. if request.printer_id is None:
  2858. for (model,) in (
  2859. await db.execute(select(Printer.model).where(Printer.is_active == True).order_by(Printer.id)) # noqa: E712
  2860. ).all():
  2861. if model:
  2862. active_models.setdefault(model.lower(), model)
  2863. if target_model_norm:
  2864. if target_model_norm.lower() not in active_models:
  2865. raise HTTPException(400, f"No active printers for model: {target_model_norm}")
  2866. target_model_norm = active_models[target_model_norm.lower()]
  2867. # Get all requested files
  2868. result = await db.execute(LibraryFile.active().where(LibraryFile.id.in_(request.file_ids)))
  2869. files = {f.id: f for f in result.scalars().all()}
  2870. # Ownership-scoped reads apply here as everywhere else in this module: a
  2871. # file the caller may not read is a file they may not print. Dropped from
  2872. # the map rather than refused by name, so the per-file error below is the
  2873. # same "File not found" an unknown id gets and the response says nothing
  2874. # about which ids exist. Ownerless rows need LIBRARY_READ_ALL, matching
  2875. # _ensure_library_file_visible.
  2876. if actor is not None and not actor.has_permission(Permission.LIBRARY_READ_ALL.value):
  2877. files = {fid: f for fid, f in files.items() if f.created_by_id is not None and f.created_by_id == actor.id}
  2878. # Project attribution (#1897): a file queued from a project-linked folder
  2879. # inherits that project, so the resulting archive counts toward the
  2880. # project's progress. A file's own project link wins over its folder's.
  2881. folder_ids = {f.folder_id for f in files.values() if f.folder_id is not None}
  2882. folder_projects: dict[int, int | None] = {}
  2883. if folder_ids:
  2884. folder_result = await db.execute(
  2885. select(LibraryFolder.id, LibraryFolder.project_id).where(LibraryFolder.id.in_(folder_ids))
  2886. )
  2887. folder_projects = dict(folder_result.all())
  2888. # Get max position for queue ordering
  2889. pos_result = await db.execute(select(func.coalesce(func.max(PrintQueueItem.position), 0)))
  2890. max_position = pos_result.scalar() or 0
  2891. # There is no per-job ask-for-outcome toggle on a bulk add, so the rows take
  2892. # the same default the print dialog seeds itself from (#1898).
  2893. confirm_outcome = await confirm_outcome_for_new_queue_item(db)
  2894. # No print options on a bulk add either: the install's defaults, as the
  2895. # print dialog would have offered them.
  2896. print_options = await default_print_options(db)
  2897. for file_id in request.file_ids:
  2898. lib_file = files.get(file_id)
  2899. if not lib_file:
  2900. errors.append(AddToQueueError(file_id=file_id, filename="(not found)", error="File not found"))
  2901. continue
  2902. # Validate file is sliced
  2903. if not is_sliced_file(lib_file.filename):
  2904. errors.append(
  2905. AddToQueueError(
  2906. file_id=file_id,
  2907. filename=lib_file.filename,
  2908. error="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  2909. )
  2910. )
  2911. continue
  2912. try:
  2913. # Verify file exists on disk
  2914. file_path = Path(app_settings.base_dir) / lib_file.file_path
  2915. if not file_path.exists():
  2916. errors.append(
  2917. AddToQueueError(file_id=file_id, filename=lib_file.filename, error="File not found on disk")
  2918. )
  2919. continue
  2920. # The Bambu SD card is FAT32/exFAT, so an illegal character 553s at
  2921. # upload time. POST /queue/ rejects those at queue time (#1540) and
  2922. # this route did not, which turned a nameable mistake into a print
  2923. # that failed hours later.
  2924. try:
  2925. validate_print_filename(lib_file.filename)
  2926. except InvalidFilenameError as e:
  2927. errors.append(AddToQueueError(file_id=file_id, filename=lib_file.filename, error=str(e)))
  2928. continue
  2929. # Where this file is aimed. An explicit printer wins; an explicit
  2930. # model applies to every file and has to be one this file can
  2931. # legally run on; with neither, the file's own declaration is used
  2932. # when some active printer answers to it.
  2933. item_printer_id = request.printer_id
  2934. item_target_model: str | None = None
  2935. if item_printer_id is None:
  2936. if target_model_norm:
  2937. sliced_for = (lib_file.file_metadata or {}).get("sliced_for_model")
  2938. if not is_gcode_compatible(sliced_for, target_model_norm):
  2939. errors.append(
  2940. AddToQueueError(
  2941. file_id=file_id,
  2942. filename=lib_file.filename,
  2943. error=(
  2944. f"File was sliced for {sliced_for} and cannot be dispatched to "
  2945. f"{target_model_norm} printers"
  2946. ),
  2947. )
  2948. )
  2949. continue
  2950. item_target_model = target_model_norm
  2951. else:
  2952. inferred = resolve_variant_model(lib_file)
  2953. item_target_model = active_models.get(inferred.lower()) if inferred else None
  2954. # Filament the scheduler must match before handing a model-based
  2955. # item to hardware. Without it the item goes to whichever printer
  2956. # of that model is idle, whatever is loaded in it.
  2957. # The plate that prints: added without one, a multi-plate file
  2958. # prints its default plate. Stored on the item, so the filament a
  2959. # printer must have, the AMS mapping and the unmatched-filament
  2960. # check all read that plate rather than every plate.
  2961. printed_plate = await asyncio.to_thread(printed_plate_of_multi_plate_file, file_path)
  2962. required_filament_types = None
  2963. if item_target_model:
  2964. # POST /queue/'s own extractor, borrowed rather than
  2965. # reimplemented: a second copy of this rule is a second thing
  2966. # to keep in step.
  2967. #
  2968. # Off the loop, unlike there: that route parses one 3MF per
  2969. # request and this one parses every file in the batch, so on a
  2970. # bulk add of a few hundred -- especially from an external
  2971. # folder on a NAS -- the zip reads add up to a stall the whole
  2972. # event loop takes, status ingest included.
  2973. filament_types = await asyncio.to_thread(_extract_filament_types_from_3mf, file_path, printed_plate)
  2974. if filament_types:
  2975. required_filament_types = json.dumps(filament_types)
  2976. # Create queue item referencing library file (archive created at print start)
  2977. max_position += 1
  2978. queue_item = PrintQueueItem(
  2979. printer_id=item_printer_id,
  2980. target_model=item_target_model,
  2981. required_filament_types=required_filament_types,
  2982. plate_id=printed_plate,
  2983. library_file_id=file_id,
  2984. project_id=lib_file.project_id
  2985. or (folder_projects.get(lib_file.folder_id) if lib_file.folder_id is not None else None),
  2986. position=max_position,
  2987. status="pending",
  2988. confirm_outcome=confirm_outcome,
  2989. # Without this the row is ownerless, and `queue:read_own` filters
  2990. # on `created_by_id` — so the user who queued the file could not
  2991. # see it in their own queue.
  2992. created_by_id=actor.id if actor else None,
  2993. # Waits for someone to start it unless they may print without review (#1620)
  2994. manual_start=review_required,
  2995. **print_options,
  2996. )
  2997. db.add(queue_item)
  2998. await db.flush() # Get queue_item.id
  2999. added.append(
  3000. AddToQueueResult(
  3001. file_id=file_id,
  3002. filename=lib_file.filename,
  3003. queue_item_id=queue_item.id,
  3004. )
  3005. )
  3006. except Exception as e:
  3007. logger.exception("Error adding file %s to queue", file_id)
  3008. errors.append(AddToQueueError(file_id=file_id, filename=lib_file.filename, error=str(e)))
  3009. # Nothing queued and something to say about why. Returning 200 here is what
  3010. # made this look like a working call that quietly did nothing: a client that
  3011. # checks the status code sees success, and the reasons sit in a body it had
  3012. # no cause to read (#3112). Partial success stays 200 -- items really were
  3013. # created, and the per-file errors belong with them.
  3014. if not added and errors:
  3015. raise HTTPException(
  3016. 400,
  3017. detail={
  3018. "message": "No files could be added to the queue.",
  3019. "errors": [e.model_dump() for e in errors],
  3020. },
  3021. )
  3022. await db.commit()
  3023. await announce_queue_jobs_added(db, [a.queue_item_id for a in added])
  3024. return AddToQueueResponse(added=added, errors=errors)
  3025. @router.get("/files/{file_id}/plates")
  3026. async def get_library_file_plates(
  3027. file_id: int,
  3028. db: AsyncSession = Depends(get_db, scope="function"),
  3029. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3030. require_ownership_permission(
  3031. Permission.LIBRARY_READ_ALL,
  3032. Permission.LIBRARY_READ_OWN,
  3033. )
  3034. ),
  3035. ):
  3036. """Get available plates from a multi-plate 3MF library file.
  3037. Returns a list of plates with their index, name, thumbnail availability,
  3038. and filament requirements. For single-plate exports, returns a single plate.
  3039. """
  3040. import json
  3041. import defusedxml.ElementTree as ET
  3042. user, can_read_all = auth_result
  3043. # Get the library file
  3044. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3045. lib_file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  3046. if not lib_file:
  3047. raise HTTPException(status_code=404, detail="File not found")
  3048. file_path = Path(app_settings.base_dir) / lib_file.file_path
  3049. if not file_path.exists():
  3050. raise HTTPException(status_code=404, detail="File not found on disk")
  3051. # Only 3MF files have plates
  3052. if not lib_file.filename.lower().endswith(".3mf"):
  3053. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  3054. plates = []
  3055. # Printer / process preset names the 3MF was prepared with — used by the
  3056. # SliceModal to default its dropdowns (#1325). Initialised here so the
  3057. # final return never raises NameError when the file isn't a valid zip.
  3058. embedded_presets: dict[str, str | None] = {"printer": None, "process": None}
  3059. # Process settings the designer changed away from the stock preset (#2622).
  3060. # Offered in the SliceModal so a cross-printer re-slice can carry them
  3061. # instead of silently losing them to the picked process profile.
  3062. design_overrides: list[dict] = []
  3063. try:
  3064. with zipfile.ZipFile(file_path, "r") as zf:
  3065. namelist = zf.namelist()
  3066. embedded_presets = extract_embedded_presets_from_3mf(zf)
  3067. if _PROJECT_SETTINGS_PATH in namelist:
  3068. try:
  3069. design_overrides = [
  3070. o._asdict()
  3071. for o in overrides_from_config(json.loads(zf.read(_PROJECT_SETTINGS_PATH).decode("utf-8")))
  3072. ]
  3073. except (ValueError, OSError, KeyError):
  3074. design_overrides = []
  3075. # Find all plate gcode files to determine available plates
  3076. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  3077. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  3078. plate_indices: list[int] = []
  3079. if gcode_files:
  3080. # Extract plate indices from gcode filenames
  3081. for gf in gcode_files:
  3082. try:
  3083. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  3084. plate_indices.append(int(plate_str))
  3085. except ValueError:
  3086. pass # Skip gcode file with non-numeric plate index
  3087. else:
  3088. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  3089. plate_png_files = [
  3090. n
  3091. for n in namelist
  3092. if n.startswith("Metadata/plate_")
  3093. and n.endswith(".png")
  3094. and "_small" not in n
  3095. and "no_light" not in n
  3096. ]
  3097. plate_name_candidates = plate_json_files + plate_png_files
  3098. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  3099. seen_indices: set[int] = set()
  3100. for name in plate_name_candidates:
  3101. match = plate_re.match(name)
  3102. if match:
  3103. try:
  3104. index = int(match.group(1))
  3105. except ValueError:
  3106. continue
  3107. if index in seen_indices:
  3108. continue
  3109. seen_indices.add(index)
  3110. plate_indices.append(index)
  3111. if not plate_indices:
  3112. # No plate metadata found
  3113. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  3114. plate_indices.sort()
  3115. # Parse model_settings.config for plate names + object assignments
  3116. plate_names = {}
  3117. plate_object_ids: dict[int, list[str]] = {}
  3118. object_names_by_id: dict[str, str] = {}
  3119. if "Metadata/model_settings.config" in namelist:
  3120. try:
  3121. model_content = zf.read("Metadata/model_settings.config").decode()
  3122. model_root = ET.fromstring(model_content)
  3123. for obj_elem in model_root.findall(".//object"):
  3124. obj_id = obj_elem.get("id")
  3125. if not obj_id:
  3126. continue
  3127. name_meta = obj_elem.find("metadata[@key='name']")
  3128. obj_name = name_meta.get("value") if name_meta is not None else None
  3129. if obj_name:
  3130. object_names_by_id[obj_id] = obj_name
  3131. for plate_elem in model_root.findall(".//plate"):
  3132. plater_id = None
  3133. plater_name = None
  3134. for meta in plate_elem.findall("metadata"):
  3135. key = meta.get("key")
  3136. value = meta.get("value")
  3137. if key == "plater_id" and value:
  3138. try:
  3139. plater_id = int(value)
  3140. except ValueError:
  3141. pass # Ignore plate with non-numeric plater_id
  3142. elif key == "plater_name" and value:
  3143. plater_name = value.strip()
  3144. if plater_id is not None and plater_name:
  3145. plate_names[plater_id] = plater_name
  3146. if plater_id is not None:
  3147. for instance_elem in plate_elem.findall("model_instance"):
  3148. for inst_meta in instance_elem.findall("metadata"):
  3149. if inst_meta.get("key") == "object_id":
  3150. obj_id = inst_meta.get("value")
  3151. if not obj_id:
  3152. continue
  3153. plate_object_ids.setdefault(plater_id, [])
  3154. if obj_id not in plate_object_ids[plater_id]:
  3155. plate_object_ids[plater_id].append(obj_id)
  3156. except Exception:
  3157. pass # model_settings.config is optional; skip if missing or malformed
  3158. # Parse slice_info.config for plate metadata
  3159. plate_metadata = {}
  3160. if "Metadata/slice_info.config" in namelist:
  3161. content = zf.read("Metadata/slice_info.config").decode()
  3162. root = ET.fromstring(content)
  3163. for plate_elem in root.findall(".//plate"):
  3164. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  3165. plate_index = None
  3166. for meta in plate_elem.findall("metadata"):
  3167. key = meta.get("key")
  3168. value = meta.get("value")
  3169. if key == "index" and value:
  3170. try:
  3171. plate_index = int(value)
  3172. except ValueError:
  3173. pass # Ignore plate with non-numeric index
  3174. elif key == "prediction" and value:
  3175. try:
  3176. plate_info["prediction"] = int(value)
  3177. except ValueError:
  3178. pass # Leave prediction as None if not a valid integer
  3179. elif key == "weight" and value:
  3180. try:
  3181. plate_info["weight"] = float(value)
  3182. except ValueError:
  3183. pass # Leave weight as None if not a valid number
  3184. # Get filaments used in this plate
  3185. for filament_elem in plate_elem.findall("filament"):
  3186. filament_id = filament_elem.get("id")
  3187. filament_type = filament_elem.get("type", "")
  3188. filament_color = filament_elem.get("color", "")
  3189. used_g = filament_elem.get("used_g", "0")
  3190. used_m = filament_elem.get("used_m", "0")
  3191. try:
  3192. used_grams = float(used_g)
  3193. except (ValueError, TypeError):
  3194. used_grams = 0
  3195. if used_grams > 0 and filament_id:
  3196. plate_info["filaments"].append(
  3197. {
  3198. "slot_id": int(filament_id),
  3199. "type": filament_type,
  3200. "color": filament_color,
  3201. # The preset the slicer assigned (GFA01, ...): names the product line
  3202. "tray_info_idx": filament_elem.get("tray_info_idx", "") or "",
  3203. "used_grams": round(used_grams, 1),
  3204. "used_meters": float(used_m) if used_m else 0,
  3205. }
  3206. )
  3207. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  3208. # Collect object names
  3209. for obj_elem in plate_elem.findall("object"):
  3210. obj_name = obj_elem.get("name")
  3211. if obj_name and obj_name not in plate_info["objects"]:
  3212. plate_info["objects"].append(obj_name)
  3213. # Set plate name
  3214. if plate_index is not None:
  3215. custom_name = plate_names.get(plate_index)
  3216. if custom_name:
  3217. plate_info["name"] = custom_name
  3218. elif plate_info["objects"]:
  3219. plate_info["name"] = plate_info["objects"][0]
  3220. plate_metadata[plate_index] = plate_info
  3221. # Parse plate_*.json for object lists when slice_info is missing
  3222. plate_json_objects: dict[int, list[str]] = {}
  3223. for name in namelist:
  3224. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  3225. if not match:
  3226. continue
  3227. try:
  3228. plate_index = int(match.group(1))
  3229. except ValueError:
  3230. continue
  3231. try:
  3232. payload = json.loads(zf.read(name).decode())
  3233. bbox_objects = payload.get("bbox_objects", [])
  3234. names: list[str] = []
  3235. for obj in bbox_objects:
  3236. obj_name = obj.get("name") if isinstance(obj, dict) else None
  3237. if obj_name and obj_name not in names:
  3238. names.append(obj_name)
  3239. if names:
  3240. plate_json_objects[plate_index] = names
  3241. except Exception:
  3242. continue
  3243. # Build plate list
  3244. for idx in plate_indices:
  3245. meta = plate_metadata.get(idx, {})
  3246. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  3247. objects = meta.get("objects", [])
  3248. if not objects:
  3249. objects = plate_json_objects.get(idx, [])
  3250. if not objects and plate_object_ids.get(idx):
  3251. objects = [
  3252. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  3253. ]
  3254. plate_name = meta.get("name")
  3255. if not plate_name:
  3256. plate_name = plate_names.get(idx)
  3257. if not plate_name and objects:
  3258. plate_name = objects[0]
  3259. plates.append(
  3260. {
  3261. "index": idx,
  3262. "name": plate_name,
  3263. "objects": objects,
  3264. "object_count": len(objects),
  3265. "has_thumbnail": has_thumbnail,
  3266. "thumbnail_url": f"/api/v1/library/files/{file_id}/plate-thumbnail/{idx}"
  3267. if has_thumbnail
  3268. else None,
  3269. "print_time_seconds": meta.get("prediction"),
  3270. "filament_used_grams": meta.get("weight"),
  3271. "filaments": meta.get("filaments", []),
  3272. }
  3273. )
  3274. except Exception as e:
  3275. logger.warning("Failed to parse plates from library file %s: %s", file_id, e)
  3276. return {
  3277. "file_id": file_id,
  3278. "filename": lib_file.filename,
  3279. "plates": plates,
  3280. "is_multi_plate": len(plates) > 1,
  3281. "embedded_printer": embedded_presets["printer"],
  3282. "embedded_process": embedded_presets["process"],
  3283. "design_overrides": design_overrides,
  3284. }
  3285. @router.get("/files/{file_id}/plate-thumbnail/{plate_index}")
  3286. async def get_library_file_plate_thumbnail(
  3287. file_id: int,
  3288. plate_index: int,
  3289. db: AsyncSession = Depends(get_db, scope="function"),
  3290. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3291. require_media_token_ownership(
  3292. Permission.LIBRARY_READ_ALL,
  3293. Permission.LIBRARY_READ_OWN,
  3294. )
  3295. ),
  3296. ):
  3297. """Get the thumbnail image for a specific plate from a library file.
  3298. Ownership-gated on the same terms as the file itself (#3025).
  3299. """
  3300. from starlette.responses import Response
  3301. user, can_read_all = auth_result
  3302. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3303. lib_file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  3304. file_path = Path(app_settings.base_dir) / lib_file.file_path
  3305. if not file_path.exists():
  3306. raise HTTPException(status_code=404, detail="File not found on disk")
  3307. try:
  3308. with zipfile.ZipFile(file_path, "r") as zf:
  3309. thumb_path = f"Metadata/plate_{plate_index}.png"
  3310. if thumb_path in zf.namelist():
  3311. data = zf.read(thumb_path)
  3312. return Response(content=data, media_type="image/png")
  3313. except Exception:
  3314. pass # Archive unreadable or thumbnail missing; fall through to 404
  3315. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  3316. async def _try_preview_slice_filaments(
  3317. db: AsyncSession,
  3318. *,
  3319. kind: str,
  3320. source_id: int,
  3321. plate_id: int,
  3322. file_path: Path,
  3323. request_id: str | None = None,
  3324. ) -> list[dict] | None:
  3325. """Run a preview slice via the user's configured sidecar. Same shape as
  3326. the matching helper in archives.py — see that module for rationale.
  3327. ``request_id``: when supplied, forwarded to the sidecar so the
  3328. SliceModal's inline spinner + toast can poll the matching progress
  3329. endpoint and show "Generating G-code (45%)" for the preview as well.
  3330. """
  3331. from backend.app.api.routes.settings import get_setting
  3332. from backend.app.services.slice_preview import get_preview_filaments
  3333. from backend.app.services.slicer_api import get_stall_timeout_seconds
  3334. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  3335. if preferred == "orcaslicer":
  3336. configured = await get_setting(db, "orcaslicer_api_url")
  3337. api_url = (configured or app_settings.slicer_api_url).strip()
  3338. elif preferred == "bambu_studio":
  3339. configured = await get_setting(db, "bambu_studio_api_url")
  3340. api_url = (configured or app_settings.bambu_studio_api_url).strip()
  3341. else:
  3342. return None
  3343. if not api_url:
  3344. return None
  3345. try:
  3346. file_bytes = file_path.read_bytes()
  3347. except OSError:
  3348. return None
  3349. return await get_preview_filaments(
  3350. kind=kind,
  3351. source_id=source_id,
  3352. plate_id=plate_id,
  3353. file_bytes=file_bytes,
  3354. file_name=file_path.name,
  3355. api_url=api_url,
  3356. request_id=request_id,
  3357. timeout_seconds=await get_stall_timeout_seconds(db),
  3358. )
  3359. @router.get("/files/{file_id}/filament-requirements")
  3360. async def get_library_file_filament_requirements(
  3361. file_id: int,
  3362. plate_id: int | None = None,
  3363. request_id: str | None = None,
  3364. full_slots: bool = False,
  3365. db: AsyncSession = Depends(get_db, scope="function"),
  3366. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  3367. require_ownership_permission(
  3368. Permission.LIBRARY_READ_ALL,
  3369. Permission.LIBRARY_READ_OWN,
  3370. )
  3371. ),
  3372. ):
  3373. """Get filament requirements from a library file.
  3374. Parses the 3MF file to extract filament slot IDs, types, colors, and usage.
  3375. This enables AMS slot assignment when printing from the file manager.
  3376. Args:
  3377. file_id: The library file ID
  3378. plate_id: Optional plate index to get filaments for a specific plate
  3379. full_slots: Return one entry per *project* slot rather than only the
  3380. slots the plate consumes. See :func:`_expand_to_project_slots`.
  3381. Only the slice modal wants this; print-time AMS matching must keep
  3382. the used-only list.
  3383. """
  3384. import defusedxml.ElementTree as ET
  3385. user, can_read_all = auth_result
  3386. # Get the library file
  3387. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3388. lib_file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  3389. # Get the full file path
  3390. file_path = Path(app_settings.base_dir) / lib_file.file_path
  3391. if not file_path.exists():
  3392. raise HTTPException(status_code=404, detail="File not found on disk")
  3393. # Only 3MF files have parseable filament info
  3394. if not lib_file.filename.lower().endswith(".3mf"):
  3395. return {"file_id": file_id, "filename": lib_file.filename, "plate_id": plate_id, "filaments": []}
  3396. filaments = []
  3397. try:
  3398. with zipfile.ZipFile(file_path, "r") as zf:
  3399. # Parse slice_info.config for filament requirements
  3400. if "Metadata/slice_info.config" in zf.namelist():
  3401. content = zf.read("Metadata/slice_info.config").decode()
  3402. root = ET.fromstring(content)
  3403. if plate_id is not None:
  3404. # Find filaments for specific plate
  3405. for plate_elem in root.findall(".//plate"):
  3406. # Check if this is the requested plate
  3407. plate_index = None
  3408. for meta in plate_elem.findall("metadata"):
  3409. if meta.get("key") == "index":
  3410. try:
  3411. plate_index = int(meta.get("value", ""))
  3412. except ValueError:
  3413. pass # Skip plate with non-numeric index value
  3414. break
  3415. if plate_index == plate_id:
  3416. # Extract filaments from this plate
  3417. for filament_elem in plate_elem.findall("filament"):
  3418. filament_id = filament_elem.get("id")
  3419. filament_type = filament_elem.get("type", "")
  3420. filament_color = filament_elem.get("color", "")
  3421. used_g = filament_elem.get("used_g", "0")
  3422. used_m = filament_elem.get("used_m", "0")
  3423. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3424. try:
  3425. used_grams = float(used_g)
  3426. except (ValueError, TypeError):
  3427. used_grams = 0
  3428. if used_grams > 0 and filament_id:
  3429. filaments.append(
  3430. {
  3431. "slot_id": int(filament_id),
  3432. "type": filament_type,
  3433. "color": filament_color,
  3434. "used_grams": round(used_grams, 1),
  3435. "used_meters": float(used_m) if used_m else 0,
  3436. "tray_info_idx": tray_info_idx,
  3437. # Sliced output already pre-filtered by used_g>0,
  3438. # so every entry that survives is in fact used by
  3439. # this plate. Print-dispatch consumers ignore the
  3440. # flag; SliceModal uses it to enable/disable rows.
  3441. "used_in_plate": True,
  3442. }
  3443. )
  3444. break
  3445. else:
  3446. # Extract all filaments with used_g > 0 (for single-plate or overview)
  3447. for filament_elem in root.findall(".//filament"):
  3448. filament_id = filament_elem.get("id")
  3449. filament_type = filament_elem.get("type", "")
  3450. filament_color = filament_elem.get("color", "")
  3451. used_g = filament_elem.get("used_g", "0")
  3452. used_m = filament_elem.get("used_m", "0")
  3453. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3454. try:
  3455. used_grams = float(used_g)
  3456. except (ValueError, TypeError):
  3457. used_grams = 0
  3458. if used_grams > 0 and filament_id:
  3459. filaments.append(
  3460. {
  3461. "slot_id": int(filament_id),
  3462. "type": filament_type,
  3463. "color": filament_color,
  3464. "used_grams": round(used_grams, 1),
  3465. "used_meters": float(used_m) if used_m else 0,
  3466. "tray_info_idx": tray_info_idx,
  3467. "used_in_plate": True,
  3468. }
  3469. )
  3470. # Re-slicing a source that already carries slice_info (#2712).
  3471. # The block above answers "what does this plate consume", which is
  3472. # what print-time AMS matching needs. The slice modal needs "what
  3473. # slots exist", because its list is positional and the CLI binds
  3474. # entry N to slot N — so a source using only slot 4 handed the
  3475. # user's single pick to slot 1 and sliced slot 4 with the source's
  3476. # embedded default. Widen here rather than in the modal so the
  3477. # print path keeps the narrow list it depends on.
  3478. if full_slots and filaments:
  3479. filaments = expand_to_project_slots(zf, filaments)
  3480. # Unsliced project files: slice_info had no per-plate data.
  3481. # Return the FULL project_settings.config AMS slot list so
  3482. # the slicer CLI receives a profile for every project slot
  3483. # (otherwise it silently fills the gap from embedded
  3484. # defaults — surfaces as "I picked white but the print has
  3485. # grey" because the source's grey support filament leaks
  3486. # into the output). Use the preview slice to mark which
  3487. # slots the picked plate actually consumes; the SliceModal
  3488. # disables the unused rows so the user only interacts with
  3489. # the dropdowns that matter, while the backend still has
  3490. # the complete list to pass to the CLI.
  3491. if not filaments:
  3492. project_filaments = extract_project_filaments_from_3mf(zf)
  3493. used_slot_ids: set[int] = set()
  3494. if project_filaments and plate_id is not None:
  3495. preview = await _try_preview_slice_filaments(
  3496. db,
  3497. kind="library_file",
  3498. source_id=file_id,
  3499. plate_id=plate_id,
  3500. file_path=file_path,
  3501. request_id=request_id,
  3502. )
  3503. if preview is not None:
  3504. used_slot_ids = {f["slot_id"] for f in preview}
  3505. # Default to "every slot is used" when preview-slice
  3506. # didn't produce data: better to over-enable dropdowns
  3507. # than under-enable and have the user unable to pick a
  3508. # filament the plate actually uses.
  3509. fallback_all_used = not used_slot_ids
  3510. for f in project_filaments:
  3511. f["used_in_plate"] = fallback_all_used or f["slot_id"] in used_slot_ids
  3512. filaments = project_filaments
  3513. # Sort by slot ID
  3514. filaments.sort(key=lambda x: x["slot_id"])
  3515. # Enrich with nozzle mapping for dual-nozzle printers
  3516. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf, plate_id=plate_id)
  3517. if nozzle_mapping:
  3518. for filament in filaments:
  3519. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  3520. # Nozzle-rack machines (#1784): the print dialog offers a rack
  3521. # position per filament group, which needs the group table as well
  3522. # as the carriage above.
  3523. annotate_rack_groups(filaments, file_path, plate_id)
  3524. except Exception as e:
  3525. logger.warning("Failed to parse filament requirements from library file %s: %s", file_id, e)
  3526. return {
  3527. "file_id": file_id,
  3528. "filename": lib_file.filename,
  3529. "plate_id": plate_id,
  3530. "filaments": filaments,
  3531. }
  3532. def _patch_process_bed_type(process_json: str, bed_type: str) -> str:
  3533. """Overwrite ``curr_bed_type`` in a process-profile JSON before forwarding
  3534. to the slicer sidecar.
  3535. The slicer CLI reads the build-plate type from the process profile's
  3536. ``curr_bed_type`` field. When the user picks a non-default plate in the
  3537. SliceModal (#1337), we patch the resolved JSON in place rather than
  3538. asking them to clone the preset just to switch a plate. Returns the
  3539. original string unchanged when the JSON can't be parsed or isn't a
  3540. dict — the slicer will then run with whatever the preset originally
  3541. specified, which is the safe fall-back path.
  3542. """
  3543. try:
  3544. profile = json.loads(process_json)
  3545. except json.JSONDecodeError:
  3546. logger.warning("Bed-type override skipped: process profile is not valid JSON")
  3547. return process_json
  3548. if not isinstance(profile, dict):
  3549. return process_json
  3550. profile["curr_bed_type"] = bed_type
  3551. return json.dumps(profile)
  3552. def _source_plate_colours(model_bytes: bytes) -> list[str]:
  3553. """Per-slot colours the source 3MF was designed with, or ``[]``.
  3554. Read from ``project_settings.config`` rather than ``slice_info.config``:
  3555. the latter records the colour the file was *last sliced* with, which for a
  3556. source that never carried one is the slicer's own #00AE42 default — the
  3557. exact value #2977 is about, so using it as a fallback would be circular.
  3558. STL and mesh-only 3MF sources have no project settings and yield ``[]``.
  3559. """
  3560. from io import BytesIO
  3561. try:
  3562. with zipfile.ZipFile(BytesIO(model_bytes), "r") as zf:
  3563. return [str(f.get("color") or "") for f in extract_project_filaments_from_3mf(zf)]
  3564. except (zipfile.BadZipFile, OSError, ValueError):
  3565. return []
  3566. def _preset_default_colour(profile: dict) -> str:
  3567. """A filament preset's own ``default_filament_colour``, or ``""``.
  3568. OrcaSlicer's third-party vendor profiles carry this; Bambu Studio's
  3569. bundled BBL filament profiles carry it nowhere (checked across the whole
  3570. shipped `resources/profiles/BBL/filament/` tree — zero occurrences), which
  3571. is why it can only ever be one link in the chain and never the whole fix.
  3572. It is read here and rewritten as ``filament_colour`` because the CLI does
  3573. not read it itself. Measured against a 02.08.02.61 sidecar: a profile
  3574. carrying only ``default_filament_colour: ["#FF00FF"]`` still slices to
  3575. ``filament_colour: ["#00AE42"]``. Bambu Studio consumes the default in the
  3576. GUI when a project is created, not in ``--load-filaments``.
  3577. """
  3578. raw = profile.get("default_filament_colour")
  3579. if isinstance(raw, list):
  3580. raw = raw[0] if raw else None
  3581. return raw.strip() if isinstance(raw, str) else ""
  3582. def _patch_filament_colours(
  3583. filament_jsons: list[str],
  3584. requested: list[str],
  3585. model_bytes: bytes,
  3586. ) -> list[str]:
  3587. """Write ``filament_colour`` onto each resolved filament profile (#2977).
  3588. Neither slicer stores a colour on a filament *preset* — it is a per-project
  3589. property their GUIs set from the plate — so a CLI slice with no colour
  3590. supplied records Bambu Studio's compiled-in default for every slot. That
  3591. default is `#00AE42`, which is why every internal-slicer output was green
  3592. regardless of the filament picked, and why the print dialog's AMS mapping
  3593. reported a colour mismatch against whatever was actually loaded.
  3594. Per slot, first non-empty of:
  3595. 1. the caller's explicit colour (the SliceModal's per-slot swatch),
  3596. 2. the preset's own ``default_filament_colour``,
  3597. 3. the colour the source 3MF's plate was designed with.
  3598. All three empty means the slot is left untouched rather than being given a
  3599. guess: the slicer's default is then still wrong, but it is at least the
  3600. same wrong value the file would have had before this function existed.
  3601. Returns a new list; a profile that isn't parseable JSON is passed through
  3602. unchanged, on the same reasoning as ``_patch_process_bed_type`` — a colour
  3603. is not worth failing a slice that would otherwise succeed.
  3604. """
  3605. source_colours = _source_plate_colours(model_bytes) if filament_jsons else []
  3606. patched: list[str] = []
  3607. for i, raw in enumerate(filament_jsons):
  3608. try:
  3609. profile = json.loads(raw)
  3610. except json.JSONDecodeError:
  3611. logger.warning("Filament colour skipped for slot %d: profile is not valid JSON", i + 1)
  3612. patched.append(raw)
  3613. continue
  3614. if not isinstance(profile, dict):
  3615. patched.append(raw)
  3616. continue
  3617. colour = (
  3618. (requested[i].strip() if i < len(requested) and requested[i] else "")
  3619. or _preset_default_colour(profile)
  3620. or (source_colours[i].strip() if i < len(source_colours) and source_colours[i] else "")
  3621. )
  3622. if not colour:
  3623. patched.append(raw)
  3624. continue
  3625. # One-element array: the same shape the CLI uses for every other
  3626. # per-filament field (`filament_type`, `filament_vendor`), and the
  3627. # shape a `--load-filaments` profile is parsed as. A bare string is
  3628. # accepted by the JSON parser but not by the config deserialiser.
  3629. profile["filament_colour"] = [colour]
  3630. patched.append(json.dumps(profile))
  3631. return patched
  3632. # Support-related keys we lift from the source 3MF's project_settings.config
  3633. # into the picked process preset before `--load-settings` sees it (#1881).
  3634. # BambuStudio's shipped process presets ("0.20mm Standard @BBL H2D" etc.)
  3635. # define `enable_support: 0` as their default — supports are a per-print
  3636. # decision, not a per-quality one. `--load-settings` is authoritative, so
  3637. # without preserving these fields the source's per-project support intent
  3638. # (supports on, PVA in the interface slot, tree vs normal) gets discarded
  3639. # and the slicer produces a single-material output with no supports at all.
  3640. _SOURCE_PROCESS_SUPPORT_KEYS_TO_PRESERVE = (
  3641. "enable_support",
  3642. "support_filament",
  3643. "support_interface_filament",
  3644. "support_type",
  3645. )
  3646. def _declined_source_keys(offered: list[DesignOverride], requested: list[str] | None) -> set[str]:
  3647. """Settings the file offered and the caller left unticked (#2942).
  3648. The slice dialog lists what the designer changed and applies only the keys
  3649. that are switched on, so the answer to "which of these does this slice
  3650. want" is already in the request. This reads the other half of it — the
  3651. ones that were on offer and turned down — which the support carry-over
  3652. below must not put back.
  3653. ``requested`` of ``None`` is a caller that predates the per-key choice and
  3654. so cannot have declined anything; an empty list is one that was shown the
  3655. file's settings and took none. Collapsing those two into "nothing
  3656. selected" is what made an empty panel indistinguishable from an old
  3657. client, and only one of them means the user said no.
  3658. """
  3659. if requested is None:
  3660. return set()
  3661. return {override.key for override in offered} - set(requested)
  3662. def _patch_process_support_settings(
  3663. process_json: str,
  3664. source_3mf_bytes: bytes,
  3665. declined: set[str] | frozenset[str] = frozenset(),
  3666. ) -> str:
  3667. """Overlay the source 3MF's support configuration onto the process JSON.
  3668. The carry is deliberately one-way: a source can switch supports *on*,
  3669. never off (#2820). The original #1881 rule was "source wins in both
  3670. directions", which quietly stripped supports from every custom process
  3671. preset that enabled them — a MakerWorld download nearly always ships
  3672. `enable_support: 0`, so the reporter's own preset (supports on, normal
  3673. (auto)) came back out of the slicer disabled and set to tree(auto).
  3674. Nothing is lost by not carrying the off direction: a process preset
  3675. with supports *on* is by definition a deliberate user preset, since
  3676. Bambu's shipped ones all ship them off.
  3677. ``declined`` names keys the caller offered the user as the file's own
  3678. (#2622) and that the user left unticked, which this carry must then not
  3679. reinstate behind their back (#2942). It is empty for a source that offers
  3680. nothing — an OrcaSlicer export carries no ``different_settings_to_system``,
  3681. so there is nothing to tick and #1881's blanket carry still applies — and
  3682. for a client that predates the per-key ticks.
  3683. Only fires on 3MF sources — STL / STEP don't carry `project_settings.
  3684. config`. Silently no-ops when the source doesn't have the config, has
  3685. a malformed one, or when the process JSON isn't parseable — the slice
  3686. then runs with the process preset's own defaults, which is the safe
  3687. fall-back for both this bug and the pre-fix behaviour.
  3688. """
  3689. from io import BytesIO
  3690. try:
  3691. with zipfile.ZipFile(BytesIO(source_3mf_bytes), "r") as zf:
  3692. if "Metadata/project_settings.config" not in zf.namelist():
  3693. return process_json
  3694. src_cfg = json.loads(zf.read("Metadata/project_settings.config").decode("utf-8"))
  3695. except (zipfile.BadZipFile, json.JSONDecodeError, UnicodeDecodeError, OSError, KeyError):
  3696. return process_json
  3697. if not isinstance(src_cfg, dict):
  3698. return process_json
  3699. if not supports_enabled_in_config(src_cfg):
  3700. return process_json
  3701. try:
  3702. process_cfg = json.loads(process_json)
  3703. except json.JSONDecodeError:
  3704. return process_json
  3705. if not isinstance(process_cfg, dict):
  3706. return process_json
  3707. carried = {
  3708. key: src_cfg[key] for key in _SOURCE_PROCESS_SUPPORT_KEYS_TO_PRESERVE if key in src_cfg and key not in declined
  3709. }
  3710. if not carried:
  3711. return process_json
  3712. process_cfg.update(carried)
  3713. # Logged because this is the one layer of the process JSON the user
  3714. # can't see coming: the slice modal shows the picked preset's values,
  3715. # so a carried key silently disagrees with what was on screen.
  3716. logger.info(
  3717. "Carried support settings from the source 3MF onto the process preset: %s",
  3718. dict(sorted(carried.items())),
  3719. )
  3720. return json.dumps(process_cfg)
  3721. # The sidecar prefixes the slicer CLI's own error_string with this when the
  3722. # slicer ran and rejected the job (model off the bed, incompatible filament
  3723. # temps, range validation) — as opposed to the CLI crashing before it could
  3724. # evaluate the job at all.
  3725. _SLICER_REJECTION_MARKER = "Slicing failed with error from slicer:"
  3726. # The CLI writes its real diagnostic to stdout/stderr on the `[error]` level.
  3727. # Format is `[<timestamp>] [error] run <NNNN>: <message>` (or sometimes without
  3728. # the `run NNNN:` prefix). The bracketed timestamp is optional; the `[error]`
  3729. # tag is what we anchor on. Used to recover the actual rejection reason for
  3730. # the `error_string: "The input preset file is invalid and can not be parsed."`
  3731. # case (#1851) — the CLI emits that generic placeholder for every -5 exit
  3732. # including real preset-compat rejections, and the per-incident specifics
  3733. # only live in the stdout dump.
  3734. _CLI_ERROR_LINE_RE = re.compile(r"\[error\]\s*(?:run\s+\d+:\s*)?(.+?)\s*$", re.MULTILINE)
  3735. # The placeholder error_string Bambu Studio writes to result.json for any
  3736. # `--load-settings` parse / compat rejection (-5 exit). When the sidecar
  3737. # surfaces this, the real reason lives in the stdout `[error]` line that we
  3738. # mine via _CLI_ERROR_LINE_RE.
  3739. _INPUT_PRESET_INVALID_PLACEHOLDER = "The input preset file is invalid and can not be parsed."
  3740. def _slicer_rejection_message(error_text: str) -> str | None:
  3741. """Extract the slicer's own rejection reason from a sidecar error string,
  3742. or ``None`` when the failure is not a slicer content rejection.
  3743. A content rejection means ``--load-settings`` *was* applied — the slicer
  3744. got far enough to evaluate the model against the chosen printer and say
  3745. no. Retrying with the 3MF's embedded settings would then only "succeed"
  3746. by silently reverting to the source file's original printer, masking the
  3747. real problem; such failures must reach the user instead.
  3748. When the sidecar's `error_string` is Bambu Studio's generic
  3749. "The input preset file is invalid and can not be parsed." placeholder
  3750. (#1851) — emitted for every -5 exit, including the actual preset-compat
  3751. rejections whose real reason is logged to stdout as
  3752. `[error] run NNNN: <diagnostic>` — prefer the stdout `[error]` line so
  3753. the user sees which preset clashed with which printer.
  3754. """
  3755. if _SLICER_REJECTION_MARKER not in error_text:
  3756. return None
  3757. reason = error_text.split(_SLICER_REJECTION_MARKER, 1)[1]
  3758. # Mine the stdout/stderr dump for a more specific CLI diagnostic before
  3759. # we trim it off below. Done first so the lookup window covers the full
  3760. # response, not just the headline.
  3761. cli_diagnostic_match = _CLI_ERROR_LINE_RE.search(reason)
  3762. cli_diagnostic = cli_diagnostic_match.group(1).strip() if cli_diagnostic_match else None
  3763. # Trim the sidecar's trailing exit-code note and any stderr/stdout dump.
  3764. for cut in (": Slicer process failed", "\nstderr:", "\nstdout:"):
  3765. idx = reason.find(cut)
  3766. if idx != -1:
  3767. reason = reason[:idx]
  3768. reason = reason.strip() or None
  3769. # When the headline is Bambu Studio's catch-all placeholder, the real
  3770. # reason is in the stdout `[error]` line. Substitute it. The placeholder
  3771. # by itself tells the user nothing about why their slice was rejected.
  3772. if cli_diagnostic and (reason is None or reason == _INPUT_PRESET_INVALID_PLACEHOLDER):
  3773. return cli_diagnostic
  3774. return reason
  3775. async def _run_slicer_with_fallback(
  3776. db: AsyncSession,
  3777. *,
  3778. model_bytes: bytes,
  3779. model_filename: str,
  3780. request: SliceRequest,
  3781. current_user_id: int | None = None,
  3782. job_id: int | None = None,
  3783. ):
  3784. """Validate presets, dispatch to the right sidecar, run the slicer with
  3785. the auto-fallback for 3MF inputs whose `--load-settings` path crashes the
  3786. CLI. Returns ``(SliceResult, used_embedded_settings: bool)``. Raises
  3787. ``HTTPException`` for any caller-facing error.
  3788. `current_user_id` is needed to resolve **cloud** presets — the cloud token
  3789. is per-user when auth is enabled. For the legacy / local-only path it can
  3790. be left ``None``.
  3791. `job_id`: when set, a request_id is generated and a parallel poller
  3792. pushes the sidecar's --pipe-fed progress events onto
  3793. ``slice_dispatch.set_progress(job_id, ...)`` so the UI's persistent
  3794. toast can show "Generating G-code (75%)" instead of just elapsed
  3795. time. Pass None for synchronous routes that aren't tracked by the
  3796. dispatcher.
  3797. """
  3798. from backend.app.api.routes.settings import get_setting
  3799. from backend.app.services.preset_resolver import resolve_preset_ref
  3800. from backend.app.services.slicer_api import (
  3801. SlicerApiServerError,
  3802. SlicerApiService,
  3803. SlicerApiUnavailableError,
  3804. SlicerInputError,
  3805. SlicerTimeoutError,
  3806. get_stall_timeout_seconds,
  3807. )
  3808. user: User | None = None
  3809. presets: dict[str, str] = {}
  3810. filament_jsons: list[str] = []
  3811. # Resolve each slot via the source-aware resolver. The schema
  3812. # validator has already normalised legacy `*_preset_id: int`
  3813. # fields into `PresetRef(source='local', id=str(int))`, so all
  3814. # three are guaranteed non-None here.
  3815. if current_user_id is not None:
  3816. user = await db.get(User, current_user_id)
  3817. refs = {
  3818. "printer": request.printer_preset,
  3819. "process": request.process_preset,
  3820. }
  3821. for slot, ref in refs.items():
  3822. assert ref is not None, "schema validator guarantees PresetRef is set"
  3823. presets[slot] = await resolve_preset_ref(db, user, ref, slot)
  3824. # Multi-color: resolve each filament slot in plate order. The schema
  3825. # validator backfilled `filament_presets` from the legacy `filament_preset`
  3826. # field for single-color callers, so this list is always non-empty.
  3827. for ref in request.filament_presets:
  3828. assert ref is not None, "schema validator guarantees filament list is non-None"
  3829. filament_jsons.append(await resolve_preset_ref(db, user, ref, "filament"))
  3830. # Give every slot a colour before anything else touches the list, so the
  3831. # unused-slot substitution below propagates a complete profile rather than
  3832. # one that still has to be patched afterwards (#2977).
  3833. filament_jsons = _patch_filament_colours(filament_jsons, request.filament_colours, model_bytes)
  3834. # Bed-type override (#1337): patch curr_bed_type onto the resolved
  3835. # process JSON so the slicer's StaticPrintConfig pass picks up the
  3836. # user's pick instead of whatever the process preset defaults to.
  3837. # Without this, slicing an STL of ABS onto a process preset whose
  3838. # default is "Cool Plate" fails with "Plate 1: Cool Plate does not
  3839. # support filament 1" — the reporter's exact scenario.
  3840. if request.bed_type:
  3841. presets["process"] = _patch_process_bed_type(presets["process"], request.bed_type)
  3842. # Slicer routing — pick the sidecar URL by preferred_slicer.
  3843. # The per-install URL setting (Settings UI → Slicer card) wins; an
  3844. # empty value falls back to the SLICER_API_URL / BAMBU_STUDIO_API_URL
  3845. # env defaults defined in core/config.py.
  3846. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  3847. if preferred == "orcaslicer":
  3848. configured = await get_setting(db, "orcaslicer_api_url")
  3849. api_url = (configured or app_settings.slicer_api_url).strip()
  3850. elif preferred == "bambu_studio":
  3851. configured = await get_setting(db, "bambu_studio_api_url")
  3852. api_url = (configured or app_settings.bambu_studio_api_url).strip()
  3853. else:
  3854. raise HTTPException(
  3855. status_code=400,
  3856. detail=f"Unknown preferred_slicer setting: '{preferred}'. Expected 'orcaslicer' or 'bambu_studio'.",
  3857. )
  3858. # Note: an earlier version of this code stripped Metadata/project_settings.
  3859. # config + model_settings.config + slice_info.config + cut_information.xml
  3860. # before forwarding the 3MF, the theory being that --load-settings would
  3861. # then take precedence cleanly. That theory was wrong: model_settings.
  3862. # config carries the plate definitions the CLI needs to map `--slice N`
  3863. # to a real plate, and slice_info / project_settings supply baseline
  3864. # config the CLI's StaticPrintConfig pass needs at all. Stripping ANY
  3865. # of them caused the CLI to silently exit immediately after
  3866. # "Initializing StaticPrintConfigs" — exit code 0, no result.json, no
  3867. # stderr — which Node's child_process treated as failure and Bambuddy
  3868. # then masked by falling back to slice_without_profiles using the
  3869. # un-stripped bytes (and the source's embedded printer). Net effect:
  3870. # every 3MF slice with profiles silently produced wrong-printer output.
  3871. # Forwarding the original bytes lets --load-settings override the
  3872. # specific fields the user changed (printer/process/filament) while
  3873. # the embedded plate / model definitions remain intact.
  3874. is_3mf = model_filename.lower().endswith(".3mf")
  3875. primary_bytes = model_bytes
  3876. if is_3mf:
  3877. # Strip inherit/unset sentinels from Metadata/project_settings.config
  3878. # so the CLI's StaticPrintConfig range validator accepts the file
  3879. # (#1201, #3030). Surgical — keeps the config present, just removes
  3880. # the offending keys; the supplied --load-settings (and the fallback's
  3881. # embedded values for keys we didn't touch) still drive the slice.
  3882. # The preview-slice path applies the same sanitiser in
  3883. # ``slice_preview.get_preview_filaments``.
  3884. primary_bytes = sanitize_project_settings_sentinels(primary_bytes)
  3885. # #2622: the process settings the file's designer moved off the stock
  3886. # preset. Read once — the support patch below needs to know which of
  3887. # them the user was shown, and the carry after it needs their values.
  3888. design_offered = extract_design_process_overrides(primary_bytes)
  3889. declined_from_file = _declined_source_keys(design_offered, request.design_overrides)
  3890. # #1881: preserve the source 3MF's support configuration on top of
  3891. # the picked process preset. Bambu's shipped process presets set
  3892. # `enable_support: 0` by default (supports are a per-print, not
  3893. # per-quality, decision); `--load-settings` is authoritative so
  3894. # without patching, the source's `enable_support: 1` + support-slot
  3895. # assignments get discarded and the slice comes out single-material
  3896. # with a PVA slot loaded but never used. Bounded by the ticks: this
  3897. # runs for a source that offers no per-key choice at all, and for the
  3898. # keys of one that does but whose ticks the user left on.
  3899. presets["process"] = _patch_process_support_settings(
  3900. presets["process"], primary_bytes, declined=declined_from_file
  3901. )
  3902. # Carry the designer's tweaks onto the picked preset. BambuStudio
  3903. # records exactly which keys deviate from the system preset in
  3904. # `different_settings_to_system`, so a MakerWorld author's 5 walls /
  3905. # 100% infill / 0.1mm first layer survive a re-slice for another printer
  3906. # instead of being flattened by --load-settings. Opt-in per key: only the
  3907. # keys the caller names are applied, and only if the source really lists
  3908. # them as changed. Runs after the #1881 support patch so an explicit
  3909. # design pick wins over the blanket support carry-over.
  3910. if request.design_overrides:
  3911. presets["process"] = apply_design_overrides(
  3912. presets["process"],
  3913. design_offered,
  3914. request.design_overrides,
  3915. )
  3916. # The user's own edits from the slice modal's settings panel. Applied last
  3917. # and for every model type (not just 3MF): unlike the two patches above this
  3918. # doesn't read anything out of the source file, it is what the user typed.
  3919. # Last write wins, so an explicit choice beats both the carried support
  3920. # config (#1881) and the designer's tweaks (#2622).
  3921. if request.process_overrides:
  3922. presets["process"] = apply_process_overrides(presets["process"], request.process_overrides)
  3923. used_embedded_settings = False
  3924. # "Slice as designed" (#2611): honour the file's embedded
  3925. # project_settings.config instead of the picked profile triplet. Only
  3926. # meaningful for a 3MF that actually carries embedded settings; the UI
  3927. # gates the toggle on the picked printer matching the design's target,
  3928. # so this path never re-targets across printer models.
  3929. embedded_mode = bool(request.use_embedded_settings and is_3mf)
  3930. # Bounds silence rather than total slicing time (#2730), so a heavy model
  3931. # that keeps reporting progress runs to completion however long it takes.
  3932. service = SlicerApiService(api_url, timeout_seconds=await get_stall_timeout_seconds(db))
  3933. # #1493: cross-nozzle-class re-slice (single <-> dual). Without
  3934. # intervention the slicer rejects with either "G-code in unprintable
  3935. # area of multi-extruder printers" (the source's X1C-coordinate layout
  3936. # lands in the H2D's per-nozzle dead zone) or — worse — segfaults
  3937. # inside ZFiller's polygon clipping when the geometry pipeline trips
  3938. # on the cross-class transition. Forwarding the sidecar's --arrange
  3939. # flag for these cases lets BambuStudio reposition objects for the
  3940. # target bed and reconcile the embedded project_settings.config
  3941. # against the new printer, the same way the GUI's "Switch Printer"
  3942. # operation does. --arrange WILL reposition objects, so we only
  3943. # enable it on a true class crossing — same-printer slices keep the
  3944. # user's deliberate layout. The bed-type and arrange flags are
  3945. # orthogonal so this decision doesn't interact with the #1337 build-
  3946. # plate override.
  3947. cross_class_arrange = False
  3948. if is_3mf:
  3949. from backend.app.services.slicer_3mf_convert import (
  3950. extract_source_printer_model,
  3951. )
  3952. from backend.app.utils.printer_models import is_dual_nozzle_model
  3953. source_model = extract_source_printer_model(primary_bytes)
  3954. target_model = await _resolve_target_printer_model(db, user, request)
  3955. if source_model and target_model and is_dual_nozzle_model(source_model) != is_dual_nozzle_model(target_model):
  3956. logger.info(
  3957. "Cross-nozzle-class re-slice (%s -> %s): enabling --arrange so BS reconciles "
  3958. "the embedded project layout against the target printer",
  3959. source_model,
  3960. target_model,
  3961. )
  3962. cross_class_arrange = True
  3963. # #2548: the user can also ask for either layout pass per-slice. Arrange
  3964. # is a union with the cross-class decision above — a user opt-out must
  3965. # not be able to switch off the flag that keeps a class-crossing slice
  3966. # from crashing — while orient is user-driven only.
  3967. arrange_flag = cross_class_arrange or request.auto_arrange
  3968. orient_flag = request.auto_orient
  3969. # When this slice is dispatcher-tracked, generate a request_id so
  3970. # the sidecar publishes progress under it, and wire a callback that
  3971. # forwards each frame onto SliceDispatchService.set_progress for the
  3972. # status-poll endpoint to surface to the UI.
  3973. progress_request_id: str | None = None
  3974. progress_callback = None
  3975. if job_id is not None:
  3976. from uuid import uuid4
  3977. from backend.app.services.slice_dispatch import slice_dispatch as _dispatch
  3978. progress_request_id = str(uuid4())
  3979. def _on_progress(snapshot: dict) -> None:
  3980. _dispatch.set_progress(job_id, snapshot)
  3981. progress_callback = _on_progress
  3982. # SliceModal lets the user pick a filament profile per slot, but each
  3983. # plate uses only a subset of the slots. The unused-slot dropdowns get
  3984. # whatever default the modal serves up — and a heterogeneous default
  3985. # (e.g. ABS in slot 2 next to a PLA in the used slot 1) makes
  3986. # BambuStudio reject the slice with "the temperature difference of
  3987. # the filaments used is too large" (exit 194) even though the G-code
  3988. # never touches the unused slot; a default scoped to another printer
  3989. # gets it rejected with "filament preset (slot N) is not compatible
  3990. # with printer …" (#2628). Replace unused-slot entries with the
  3991. # plate's lowest used slot before the real slice so the loaded set is
  3992. # materially homogeneous and printer-correct.
  3993. #
  3994. # ``plate`` is absent for single-plate and STL sources — the SliceModal
  3995. # skips the picker and omits the field — and absent means plate 1, the
  3996. # same reading as ``plate_num`` further down and as the schema's own
  3997. # description. Treating it as "unknown plate" instead is what left every
  3998. # single-plate 3MF unsubstituted (#2711): a MakerWorld project defining
  3999. # four filaments but painting only one reached the CLI with the other
  4000. # three still holding presets baked into the source for a different
  4001. # printer, and the slice died on the first of them.
  4002. #
  4003. # ``plate=0`` is the slice-all sentinel, not a plate: every slot is used
  4004. # by some plate, so there is nothing to substitute. It has to be excluded
  4005. # explicitly because the support-filament slots unioned in below are
  4006. # read from the project config and are not plate-scoped — they would
  4007. # survive the (empty) geometry lookup for plate 0 and become the anchor,
  4008. # collapsing every colour of a slice-all onto the support filament.
  4009. if is_3mf and request.plate != 0:
  4010. from backend.app.services.slicer_3mf_convert import substitute_unused_plate_filaments
  4011. filament_jsons = substitute_unused_plate_filaments(primary_bytes, request.plate or 1, filament_jsons)
  4012. # Arrange slice-all loop (#1493): when the user asks for ``plate=0``
  4013. # (all plates) AND arrange is on, ``--slice 0 --arrange 1``
  4014. # consolidates every plate's objects onto a single target bed (BS's
  4015. # ``--arrange`` is project-wide) — either packing them all together or
  4016. # rejecting with "Some objects are located over the boundary of the
  4017. # heated bed" when nothing fits. Slice each plate independently with
  4018. # ``--arrange 1`` and merge the per-plate outputs into one multi-plate
  4019. # 3MF instead. Slice-all without arrange goes through the regular path
  4020. # below — the sidecar's native ``--slice 0`` produces the right shape
  4021. # directly.
  4022. #
  4023. # Keyed on ``arrange_flag``, not just the cross-class decision: the
  4024. # project-wide collapse is a property of ``--arrange`` itself, so a
  4025. # user-requested arrange over all plates (#2548) hits it identically.
  4026. # Orient doesn't — it rotates objects where they stand and never moves
  4027. # one between plates — so it isn't part of this condition.
  4028. use_arrange_slice_all = arrange_flag and request.plate == 0 and request.export_3mf
  4029. try:
  4030. try:
  4031. if use_arrange_slice_all:
  4032. from backend.app.services.slicer_3mf_convert import (
  4033. count_plates_in_3mf,
  4034. merge_plate_3mfs,
  4035. )
  4036. plate_count = count_plates_in_3mf(primary_bytes)
  4037. if plate_count == 0:
  4038. raise HTTPException(
  4039. status_code=400,
  4040. detail=(
  4041. "Couldn't read plate count from the source 3MF for cross-class "
  4042. "slice-all. The source may be malformed or missing "
  4043. "Metadata/model_settings.config."
  4044. ),
  4045. )
  4046. logger.info(
  4047. "Arrange slice-all: looping over %d plates with --arrange per plate, then merging "
  4048. "(embedded_settings=%s)",
  4049. plate_count,
  4050. embedded_mode,
  4051. )
  4052. from backend.app.services.slicer_api import SliceResult
  4053. per_plate_results: list[tuple[int, SliceResult]] = []
  4054. # Forward the same progress request_id + callback to each
  4055. # per-plate sub-call so the toast keeps showing the
  4056. # sidecar's stage messages ("Generating G-code 45%…").
  4057. # The sub-calls run sequentially, so the poller for plate
  4058. # N is cancelled before plate N+1's poller starts — no
  4059. # cross-talk between plate streams. Wrap the callback to
  4060. # surface "(plate N/M)" alongside the slicer's stage
  4061. # message so the user sees progress through the whole
  4062. # multi-plate loop, not just one plate at a time.
  4063. def _wrap_progress_for_plate(plate_num: int, total: int):
  4064. if progress_callback is None:
  4065. return None
  4066. def _cb(snapshot: dict) -> None:
  4067. snapshot = dict(snapshot)
  4068. snapshot["multi_plate_index"] = plate_num
  4069. snapshot["multi_plate_count"] = total
  4070. progress_callback(snapshot)
  4071. return _cb
  4072. for plate_num in range(1, plate_count + 1):
  4073. plate_cb = _wrap_progress_for_plate(plate_num, plate_count)
  4074. # "Slice as designed" has to take the loop too, not skip
  4075. # it: the project-wide collapse is caused by --arrange,
  4076. # and which config drives the slice has no bearing on
  4077. # that. Same call, minus --load-settings.
  4078. if embedded_mode:
  4079. per_plate = await service.slice_without_profiles(
  4080. model_bytes=primary_bytes,
  4081. model_filename=model_filename,
  4082. plate=plate_num,
  4083. export_3mf=True,
  4084. arrange=True,
  4085. orient=orient_flag,
  4086. request_id=progress_request_id,
  4087. on_progress=plate_cb,
  4088. )
  4089. else:
  4090. per_plate = await service.slice_with_profiles(
  4091. model_bytes=primary_bytes,
  4092. model_filename=model_filename,
  4093. printer_profile_json=presets["printer"],
  4094. process_profile_json=presets["process"],
  4095. filament_profile_jsons=filament_jsons,
  4096. plate=plate_num,
  4097. export_3mf=True,
  4098. arrange=True,
  4099. orient=orient_flag,
  4100. request_id=progress_request_id,
  4101. on_progress=plate_cb,
  4102. )
  4103. per_plate_results.append((plate_num, per_plate))
  4104. # Merge the N single-plate 3MFs into one multi-plate 3MF.
  4105. # ``primary_bytes`` is the source 3MF: it carries the
  4106. # original per-plate previews the slicer's --arrange
  4107. # pass doesn't regenerate, so the merger can fall back
  4108. # to those for each plate's cover image.
  4109. merged_bytes = merge_plate_3mfs(
  4110. [(n, r.content) for n, r in per_plate_results],
  4111. source_3mf_bytes=primary_bytes,
  4112. )
  4113. # Synthetic SliceResult: totals are the sum of each
  4114. # plate's so the archive card shows the project's print
  4115. # time and filament use, not just plate 1's.
  4116. result = SliceResult(
  4117. content=merged_bytes,
  4118. print_time_seconds=sum(r.print_time_seconds for _, r in per_plate_results),
  4119. filament_used_g=sum(r.filament_used_g for _, r in per_plate_results),
  4120. filament_used_mm=sum(r.filament_used_mm for _, r in per_plate_results),
  4121. )
  4122. # Report the path honestly: the loop can run either way, and
  4123. # the UI reads this flag to tell the user whose settings won.
  4124. used_embedded_settings = embedded_mode
  4125. elif embedded_mode:
  4126. # No --load-settings: feed the CLI the file's own
  4127. # project_settings.config untouched so the designer's tweaks
  4128. # (walls, infill, etc.) drive the slice. primary_bytes is
  4129. # already sentinel-sanitised above, the same bytes the
  4130. # crash-fallback uses. The resolved presets go unused here.
  4131. # Arrange / orient still apply: they are CLI actions on the
  4132. # geometry, not settings the embedded config could carry.
  4133. result = await service.slice_without_profiles(
  4134. model_bytes=primary_bytes,
  4135. model_filename=model_filename,
  4136. plate=request.plate,
  4137. export_3mf=request.export_3mf,
  4138. arrange=arrange_flag,
  4139. orient=orient_flag,
  4140. request_id=progress_request_id,
  4141. on_progress=progress_callback,
  4142. )
  4143. used_embedded_settings = True
  4144. else:
  4145. result = await service.slice_with_profiles(
  4146. model_bytes=primary_bytes,
  4147. model_filename=model_filename,
  4148. printer_profile_json=presets["printer"],
  4149. process_profile_json=presets["process"],
  4150. filament_profile_jsons=filament_jsons,
  4151. plate=request.plate,
  4152. export_3mf=request.export_3mf,
  4153. arrange=arrange_flag,
  4154. orient=orient_flag,
  4155. request_id=progress_request_id,
  4156. on_progress=progress_callback,
  4157. )
  4158. except SlicerApiServerError as exc:
  4159. rejection = _slicer_rejection_message(str(exc))
  4160. if rejection:
  4161. # The slicer ran and rejected the job for a content reason —
  4162. # the chosen printer/process/filament *were* applied. Falling
  4163. # back to embedded settings would silently re-slice for the
  4164. # source 3MF's original printer and hide the real problem
  4165. # (e.g. re-slicing an H2D model for an X1C: the object is off
  4166. # the smaller bed). Surface the slicer's reason instead.
  4167. raise HTTPException(status_code=400, detail=rejection) from exc
  4168. if not is_3mf or embedded_mode:
  4169. # embedded_mode already sliced with the file's own settings —
  4170. # there is nothing to fall back TO, so surface the server
  4171. # error (the outer handler turns it into a 502) instead of
  4172. # re-running the same embedded slice.
  4173. raise
  4174. if use_arrange_slice_all:
  4175. # The fallback is a single ``--slice 0`` call, and with
  4176. # arrange on that collapses every plate onto one bed — the
  4177. # exact outcome the per-plate loop above exists to avoid.
  4178. # Retrying would hand back a one-plate result for a job the
  4179. # user asked to slice as N, which reads as a Bambuddy bug
  4180. # rather than a slicer failure. Surface the error instead.
  4181. raise
  4182. logger.warning(
  4183. "Slicer CLI failed on the --load-settings path for %s (%s); retrying with embedded settings",
  4184. model_filename,
  4185. exc,
  4186. )
  4187. # Forward the same request_id + callback so the toast's live
  4188. # progress keeps updating across the fallback retry instead
  4189. # of going blank for the rest of the slice. Use the sanitised
  4190. # bytes — the embedded-settings path also reads the same
  4191. # project_settings.config and the same range validator runs
  4192. # there too, so without sanitisation the fallback would die
  4193. # on the same sentinel error (#1201). The SliceModal flags
  4194. # the difference to the user via used_embedded_settings.
  4195. # Carry the layout flags across too — the retry is meant to
  4196. # differ from the failed attempt only in where the print
  4197. # config came from, so dropping them here would silently
  4198. # produce an un-arranged result the user did ask for.
  4199. result = await service.slice_without_profiles(
  4200. model_bytes=primary_bytes,
  4201. model_filename=model_filename,
  4202. plate=request.plate,
  4203. export_3mf=request.export_3mf,
  4204. arrange=arrange_flag,
  4205. orient=orient_flag,
  4206. request_id=progress_request_id,
  4207. on_progress=progress_callback,
  4208. )
  4209. used_embedded_settings = True
  4210. except SlicerInputError as exc:
  4211. raise HTTPException(status_code=400, detail=str(exc)) from exc
  4212. except SlicerTimeoutError as exc:
  4213. # 504, not 502: the sidecar answered for the whole run, we stopped
  4214. # waiting. Reported separately so the user is told the slice ran out of
  4215. # time and where to change that, rather than that the sidecar is
  4216. # unreachable — which is what a read timeout used to look like (#2730).
  4217. raise HTTPException(status_code=504, detail=str(exc)) from exc
  4218. except SlicerApiServerError as exc:
  4219. raise HTTPException(status_code=502, detail=str(exc)) from exc
  4220. except SlicerApiUnavailableError as exc:
  4221. raise HTTPException(status_code=502, detail=str(exc)) from exc
  4222. finally:
  4223. await service.close()
  4224. # Backstop for #2838. Only the standard tier, and only when the presets we
  4225. # sent were actually used: there the sidecar resolved a bundled preset by
  4226. # name and the bundle guarantees the start G-code, so its absence is a
  4227. # sidecar defect we can name. A cloud, local or Orca-cloud preset carries
  4228. # its own start G-code, and the embedded-settings fallback prints the
  4229. # source file's — both are the user's to author, and refusing them here
  4230. # would be us second-guessing a profile we did not resolve.
  4231. if (
  4232. not used_embedded_settings
  4233. and request.printer_preset is not None
  4234. and request.printer_preset.source == "standard"
  4235. and start_gcode_is_missing(result.content, export_3mf=bool(request.export_3mf))
  4236. ):
  4237. logger.error(
  4238. "Slice for printer preset %r came back without start G-code (%s); refusing it",
  4239. request.printer_preset.id,
  4240. "3mf" if request.export_3mf else "gcode",
  4241. )
  4242. raise HTTPException(status_code=502, detail=missing_start_gcode_message(request.printer_preset.id))
  4243. # Found while investigating #2977: a filament preset the sidecar's bundle
  4244. # cannot resolve is not an error there — the CLI inherits nothing and
  4245. # slices with its own defaults, so a PETG pick comes back as PLA at 200 C.
  4246. # Warned rather than refused: the file prints, and the user may well have
  4247. # meant to slice with a profile their sidecar image predates. Skipped on
  4248. # the embedded-settings path, which sends no filament profiles for the
  4249. # bundle to resolve in the first place.
  4250. if not used_embedded_settings:
  4251. unresolved = unresolved_filament_slots(result.content, export_3mf=bool(request.export_3mf))
  4252. if unresolved:
  4253. logger.warning(
  4254. "%s",
  4255. unresolved_filament_message(unresolved, [ref.id for ref in request.filament_presets]),
  4256. )
  4257. return result, used_embedded_settings
  4258. def _canonical_printer_model(raw: str | None) -> str | None:
  4259. """Normalise a printer-preset name / ``printer_model`` field to a canonical
  4260. model code. Strips the BambuStudio ``"# "`` user-clone prefix and the
  4261. ``" 0.4 nozzle"`` variant suffix that preset names carry but bare model
  4262. names don't — without this, ``"Bambu Lab H2D 0.4 nozzle"`` wouldn't
  4263. normalise to ``H2D``."""
  4264. import re
  4265. from backend.app.utils.printer_models import normalize_printer_model
  4266. if not raw:
  4267. return None
  4268. cleaned = str(raw).strip()
  4269. if cleaned.startswith("# "):
  4270. cleaned = cleaned[2:].strip()
  4271. cleaned = re.sub(r"\s+0\.\d+\s+nozzle$", "", cleaned, flags=re.IGNORECASE)
  4272. return normalize_printer_model(cleaned) if cleaned else None
  4273. async def _resolve_target_printer_model(db: AsyncSession, user: User | None, request: SliceRequest) -> str | None:
  4274. """Best-effort: the printer model a slice request targets.
  4275. Returns ``None`` when it can't be determined (the nozzle-class guard
  4276. then simply doesn't fire — fail-open, never blocks a slice spuriously).
  4277. """
  4278. from backend.app.services.preset_resolver import resolve_preset_ref
  4279. if request.printer_preset is None:
  4280. return None
  4281. try:
  4282. printer_json = await resolve_preset_ref(db, user, request.printer_preset, "printer")
  4283. data = json.loads(printer_json)
  4284. if not isinstance(data, dict):
  4285. return None
  4286. return _canonical_printer_model(
  4287. data.get("printer_model") or data.get("printer_settings_id") or data.get("name")
  4288. )
  4289. except Exception:
  4290. return None
  4291. async def guard_nozzle_class_reslice(
  4292. db: AsyncSession, user: User | None, request: SliceRequest, source_model: str | None
  4293. ) -> None:
  4294. """No-op guard, retained for call-site compatibility.
  4295. Cross-nozzle-class re-slicing is handled by ``_run_slicer_with_fallback``'s
  4296. two-pass conversion (#1493): a 1mm cube is sliced with the target triplet
  4297. via ``slice_with_profiles`` to produce a fresh target-shaped
  4298. ``Metadata/project_settings.config``, which is then spliced into the
  4299. source 3MF before the real slice. So this guard never needs to block
  4300. anymore.
  4301. The function and its call sites in ``archives.py`` / the library re-slice
  4302. route are kept so external pinned-version forks and downstream patches
  4303. don't break, but it does nothing on a successful slice path. If the
  4304. two-pass conversion fails inside the slicer, the existing
  4305. ``SlicerApiServerError`` / ``_slicer_rejection_message`` plumbing
  4306. surfaces the CLI's actual error to the user — which is more informative
  4307. than the old "isn't supported yet" 400 the guard used to raise.
  4308. """
  4309. return None
  4310. # slice_and_persist's default owner: the user it slices for.
  4311. _CALLER = object()
  4312. async def slice_and_persist(
  4313. db: AsyncSession,
  4314. *,
  4315. model_bytes: bytes,
  4316. model_filename: str,
  4317. folder_id: int | None,
  4318. extra_metadata: dict | None,
  4319. request: SliceRequest,
  4320. current_user_id: int | None,
  4321. job_id: int | None = None,
  4322. owner_id: int | None | object = _CALLER,
  4323. ) -> SliceResponse:
  4324. """Slice a model and save the result as a new ``LibraryFile`` in
  4325. ``folder_id`` (same folder as the source by convention).
  4326. ``current_user_id`` resolves cloud presets; the new file is ``owner_id``'s,
  4327. by default the same user.
  4328. Always exports as ``.gcode.3mf`` so the existing library thumbnail
  4329. pipeline works on the new file. Plain ``.gcode`` would have no
  4330. embedded thumbnail to extract.
  4331. """
  4332. from backend.app.services.archive import ThreeMFParser
  4333. library_request = request.model_copy(update={"export_3mf": True})
  4334. result, used_embedded_settings = await _run_slicer_with_fallback(
  4335. db,
  4336. model_bytes=model_bytes,
  4337. model_filename=model_filename,
  4338. request=library_request,
  4339. current_user_id=current_user_id,
  4340. job_id=job_id,
  4341. )
  4342. # Same reduction as the archive sink: ``model_filename`` may be built from
  4343. # the source's embedded ``print_name``, which is free text (#2832). Managed
  4344. # storage names the file after a UUID and never sees this, but an external
  4345. # folder writes it verbatim, where a "/" would mean a directory nobody
  4346. # created -- and the library row shows it either way.
  4347. base_name = model_filename.rsplit(".", 1)[0]
  4348. safe_base = safe_path_component(base_name, fallback="sliced", max_bytes=MAX_FILENAME_BYTES - len(b".gcode.3mf"))
  4349. out_filename = f"{safe_base}.gcode.3mf"
  4350. # Write next to the source when the source lives on an external mount
  4351. # (#2810). The folder is loaded here rather than passed in because every
  4352. # caller already has only the id.
  4353. target_folder: LibraryFolder | None = None
  4354. if folder_id is not None:
  4355. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  4356. target_folder = folder_result.scalar_one_or_none()
  4357. out_path, out_is_external, external_fallback = _resolve_slice_destination(target_folder, out_filename)
  4358. if out_is_external:
  4359. # _unique_external_name may have suffixed it; the library row has to
  4360. # show the name the file actually has on the share, or the two drift.
  4361. out_filename = out_path.name
  4362. if external_fallback:
  4363. logger.warning(
  4364. "Slice output for %s stored in managed library instead of external folder %s: %s",
  4365. model_filename,
  4366. target_folder.external_path if target_folder else None,
  4367. external_fallback,
  4368. )
  4369. # BS/Orca CLIs skip plate_N.png in headless --export-3mf — render +
  4370. # inject server-side so the library card has a thumbnail. Best-effort:
  4371. # no-op when the slicer did embed thumbs (desktop Studio path), and
  4372. # falls through to the unmodified bytes on any render error. In a thread:
  4373. # a large plate renders for seconds, and on the event loop that stalled
  4374. # every request and printer connection for as long (#3135).
  4375. result = result._replace(content=await asyncio.to_thread(inject_plate_thumbnails_if_missing, result.content))
  4376. out_path.write_bytes(result.content)
  4377. # Extract thumbnail from the produced 3MF so the library card shows a
  4378. # preview. Failures here aren't fatal — the file is still useful
  4379. # without a thumbnail.
  4380. thumbnail_relative: str | None = None
  4381. parsed_metadata: dict = {}
  4382. try:
  4383. parser = ThreeMFParser(str(out_path))
  4384. parsed = parser.parse()
  4385. thumb_data = parsed.get("_thumbnail_data")
  4386. thumb_ext = parsed.get("_thumbnail_ext", ".png")
  4387. if thumb_data:
  4388. thumb_filename = f"{uuid.uuid4().hex}{thumb_ext}"
  4389. thumb_path = get_library_thumbnails_dir() / thumb_filename
  4390. thumb_path.write_bytes(thumb_data)
  4391. thumbnail_relative = to_relative_path(thumb_path)
  4392. cleaned = _clean_3mf_metadata(parsed)
  4393. if isinstance(cleaned, dict):
  4394. parsed_metadata = cleaned
  4395. except Exception as exc:
  4396. logger.warning("Failed to parse sliced 3MF metadata for %s: %s", out_filename, exc)
  4397. # Drop the embedded `print_name` (see _without_print_name) so the sliced
  4398. # row's display falls back to its ".gcode.3mf" filename instead of the
  4399. # source file's project title, which would make the two indistinguishable.
  4400. metadata: dict = dict(_without_print_name(parsed_metadata) or {})
  4401. # Some slicer-sidecar builds leave the X-Filament-Used-* response headers
  4402. # unset, so result.filament_used_g/_mm arrive as 0 even for a real
  4403. # multi-hour print. Fall back to the totals ThreeMFParser read from the
  4404. # produced 3MF's own G-code header.
  4405. filament_g = result.filament_used_g or parsed_metadata.get("filament_used_grams") or 0.0
  4406. filament_mm = result.filament_used_mm or parsed_metadata.get("filament_used_mm") or 0.0
  4407. metadata.update(
  4408. {
  4409. "print_time_seconds": result.print_time_seconds,
  4410. "filament_used_g": filament_g,
  4411. "filament_used_mm": filament_mm,
  4412. }
  4413. )
  4414. if used_embedded_settings:
  4415. metadata["used_embedded_settings"] = True
  4416. if external_fallback:
  4417. metadata["external_write_fallback"] = external_fallback
  4418. if extra_metadata:
  4419. metadata.update(extra_metadata)
  4420. from backend.app.services.slice_dispatch import slice_dispatch as _dispatch
  4421. # Nobody's, when the user was deleted while it sliced: the id may be someone else's now.
  4422. file_owner_id = _dispatch.owner_now(job_id, current_user_id if owner_id is _CALLER else owner_id) # type: ignore[arg-type]
  4423. new_file = LibraryFile(
  4424. folder_id=folder_id,
  4425. is_external=out_is_external,
  4426. filename=out_filename,
  4427. file_path=_stored_file_path(out_path, out_is_external),
  4428. # The on-disk payload is a ZIP container — the file_type must
  4429. # record that so the preview endpoint opens it as a 3MF instead
  4430. # of returning the ZIP bytes as text/plain (#1709 / yanglei1980).
  4431. # Earlier code mis-typed sliced rows as "gcode" to share the
  4432. # plain-G-code badge; that broke the embedded viewer. UI badges
  4433. # and gates for "gcode.3mf" are explicit at the call sites.
  4434. file_type="gcode.3mf",
  4435. file_size=len(result.content),
  4436. file_hash=hashlib.sha256(result.content).hexdigest(),
  4437. thumbnail_path=thumbnail_relative,
  4438. file_metadata=metadata,
  4439. source_type="sliced",
  4440. created_by_id=file_owner_id,
  4441. )
  4442. db.add(new_file)
  4443. await db.commit()
  4444. # No refresh: expire_on_commit=False keeps id/filename accessible, and
  4445. # refreshing here flakes under pytest-xdist when teardown of a sibling
  4446. # test races the SELECT.
  4447. return SliceResponse(
  4448. library_file_id=new_file.id,
  4449. name=new_file.filename,
  4450. print_time_seconds=result.print_time_seconds,
  4451. filament_used_g=filament_g,
  4452. filament_used_mm=filament_mm,
  4453. used_embedded_settings=used_embedded_settings,
  4454. external_write_fallback=external_fallback,
  4455. )
  4456. async def slice_and_persist_as_archive(
  4457. db: AsyncSession,
  4458. *,
  4459. model_bytes: bytes,
  4460. model_filename: str,
  4461. request: SliceRequest,
  4462. source_archive, # PrintArchive — hint kept loose to avoid cyclic import
  4463. current_user_id: int | None,
  4464. job_id: int | None = None,
  4465. owner_id: int | None | object = _CALLER,
  4466. ):
  4467. """Slice a model and save the result as a new ``PrintArchive`` row,
  4468. inheriting printer / project / makerworld metadata from the source
  4469. archive. Always exports as a `.gcode.3mf` so the existing thumbnail
  4470. and plates infrastructure (which expects a zip-shaped 3MF) works on
  4471. the new archive. Returns ``SliceArchiveResponse``.
  4472. """
  4473. from backend.app.models.archive import PrintArchive
  4474. from backend.app.schemas.slicer import SliceArchiveResponse
  4475. from backend.app.services.archive import ThreeMFParser
  4476. # Archive sinks always want a 3MF. The library route still respects the
  4477. # caller's `export_3mf` flag; here we override.
  4478. archive_request = request.model_copy(update={"export_3mf": True})
  4479. result, used_embedded_settings = await _run_slicer_with_fallback(
  4480. db,
  4481. model_bytes=model_bytes,
  4482. model_filename=model_filename,
  4483. request=archive_request,
  4484. job_id=job_id,
  4485. current_user_id=current_user_id,
  4486. )
  4487. timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
  4488. printer_folder = str(source_archive.printer_id) if source_archive.printer_id is not None else "unassigned"
  4489. # ``model_filename`` is built from the archive's display name, which comes
  4490. # from the 3MF's own metadata and is whatever the model's author typed. A
  4491. # "/" in it is a path separator, not a character: the joins below silently
  4492. # gain a level and the write lands on a parent that was never created
  4493. # (#2832). Reduce it to a single component first, leaving room for the
  4494. # prefix and the extension wrapped around it.
  4495. base_name = model_filename.rsplit(".", 1)[0]
  4496. reserve = max(len(f"{timestamp}__sliced".encode()), len(b".gcode.3mf"))
  4497. safe_base = safe_path_component(
  4498. base_name, fallback=f"archive_{source_archive.id}", max_bytes=MAX_FILENAME_BYTES - reserve
  4499. )
  4500. out_filename = f"{safe_base}.gcode.3mf"
  4501. archive_subdir = f"{timestamp}_{safe_base}_sliced"
  4502. archive_dir = (
  4503. app_settings.archive_dir / printer_folder / archive_subdir
  4504. ) # SEC-PATH-OK: printer_folder = str(int|None); archive_subdir wraps safe_path_component output, asserted below
  4505. out_path = archive_dir / out_filename # SEC-PATH-OK: out_filename wraps safe_path_component output, asserted below
  4506. # The sanitiser is what makes the two joins single-component; this is the
  4507. # backstop that says so out loud, and would catch a future edit that reaches
  4508. # around it. Checked before mkdir so a rejected path creates nothing.
  4509. assert_under(app_settings.archive_dir, archive_dir, http=False)
  4510. assert_under(app_settings.archive_dir, out_path, http=False)
  4511. archive_dir.mkdir(parents=True, exist_ok=True)
  4512. # See library-slice path: BS/Orca sidecar CLIs don't embed plate_N.png
  4513. # in headless --export-3mf, so the produced 3MF often has no thumbnail
  4514. # at all. Server-side render fills the gap; no-op when the slicer did
  4515. # embed (desktop Studio path) and best-effort on any render error. Off the
  4516. # event loop, like the library-slice path (#3135).
  4517. result = result._replace(content=await asyncio.to_thread(inject_plate_thumbnails_if_missing, result.content))
  4518. out_path.write_bytes(result.content)
  4519. # Extract a thumbnail for the new archive card. Priority order:
  4520. # 1. Source archive's ``Metadata/plate_{N}.png`` — the GUI-rendered
  4521. # preview of the same plate the user is re-slicing. Closer to
  4522. # "what's actually printing" than any other available image
  4523. # (with --arrange the layout may differ slightly, but objects
  4524. # and colours match).
  4525. # 2. ``ThreeMFParser`` fallback chain on the sliced output: the
  4526. # slicer's own per-plate render if it wrote one, then the
  4527. # project-wide thumbnail under ``Auxiliaries/.thumbnails/``.
  4528. # BambuStudio CLI frequently doesn't emit a fresh per-plate render
  4529. # (slice writes the new gcode but leaves the preview slot empty),
  4530. # so without (1) the card falls all the way through to the
  4531. # MakerWorld-style cover art — visually unrelated to what the user
  4532. # picked, see #1493 follow-up. Failures don't fail the slice — the
  4533. # archive row is still useful without a thumbnail.
  4534. plate_num = request.plate or 1
  4535. thumbnail_path: str | None = None
  4536. parsed_metadata: dict = {}
  4537. src_3mf_path = app_settings.base_dir / source_archive.file_path
  4538. source_plate_bytes = _read_3mf_entry(src_3mf_path, f"Metadata/plate_{plate_num}.png")
  4539. if source_plate_bytes:
  4540. thumb_dest = archive_dir / "thumbnail.png"
  4541. thumb_dest.write_bytes(source_plate_bytes)
  4542. thumbnail_path = str(thumb_dest.relative_to(app_settings.base_dir))
  4543. try:
  4544. parser = ThreeMFParser(str(out_path), plate_number=plate_num)
  4545. parsed = parser.parse()
  4546. if thumbnail_path is None:
  4547. thumb_data = parsed.get("_thumbnail_data")
  4548. thumb_ext = parsed.get("_thumbnail_ext", ".png")
  4549. if thumb_data:
  4550. thumb_dest = archive_dir / f"thumbnail{thumb_ext}"
  4551. thumb_dest.write_bytes(thumb_data)
  4552. thumbnail_path = str(thumb_dest.relative_to(app_settings.base_dir))
  4553. parsed_metadata = {k: v for k, v in parsed.items() if not k.startswith("_")}
  4554. except Exception as exc:
  4555. logger.warning("Failed to parse sliced 3MF metadata for %s: %s", out_filename, exc)
  4556. metadata = dict(source_archive.extra_data) if source_archive.extra_data else {}
  4557. metadata.update(parsed_metadata)
  4558. # Fall back to the produced 3MF's G-code-header totals when the sidecar
  4559. # leaves the X-Filament-Used-* headers unset (result.filament_used_g == 0
  4560. # even for a real multi-hour print).
  4561. filament_g = result.filament_used_g or parsed_metadata.get("filament_used_grams") or 0.0
  4562. filament_mm = result.filament_used_mm or parsed_metadata.get("filament_used_mm") or 0.0
  4563. metadata.update(
  4564. {
  4565. "sliced_from_archive_id": source_archive.id,
  4566. "print_time_seconds": result.print_time_seconds,
  4567. "filament_used_g": filament_g,
  4568. "filament_used_mm": filament_mm,
  4569. }
  4570. )
  4571. if used_embedded_settings:
  4572. metadata["used_embedded_settings"] = True
  4573. # Prefer the actually-used filament list from the sliced output's
  4574. # slice_info.config (parsed_metadata.filament_* — only entries with
  4575. # used_g > 0). Falling back to the source_archive's list would
  4576. # surface every project-wide AMS slot, including ones the picked
  4577. # plate doesn't use (16+ swatches on the card for a 2-color print).
  4578. new_filament_type = parsed_metadata.get("filament_type") or source_archive.filament_type
  4579. new_filament_color = parsed_metadata.get("filament_color") or source_archive.filament_color
  4580. # When the user re-slices for a different printer model than the source,
  4581. # the source's printer_id (e.g. an H2D's "Workshop H2C") no longer
  4582. # represents where the new archive can be reprinted. The archive card
  4583. # and reprint modal both read printer_id first and only fall back to
  4584. # sliced_for_model when it's None, so leaving the inherited id makes
  4585. # the X1C-sliced card display the source H2D's printer name.
  4586. # Same pitfall as the sliced_for_model copy a few lines below.
  4587. new_target_model = parsed_metadata.get("sliced_for_model") or source_archive.sliced_for_model
  4588. is_cross_model_reslice = (
  4589. new_target_model is not None
  4590. and source_archive.sliced_for_model is not None
  4591. and new_target_model != source_archive.sliced_for_model
  4592. )
  4593. new_printer_id = None if is_cross_model_reslice else source_archive.printer_id
  4594. from backend.app.services.slice_dispatch import slice_dispatch as _dispatch
  4595. # Nobody's, when the user was deleted while it sliced: the id may be someone else's now.
  4596. current_user_id = _dispatch.owner_now(job_id, current_user_id if owner_id is _CALLER else owner_id) # type: ignore[arg-type]
  4597. new_archive = PrintArchive(
  4598. printer_id=new_printer_id,
  4599. project_id=source_archive.project_id,
  4600. filename=out_filename,
  4601. file_path=str(out_path.relative_to(app_settings.base_dir)),
  4602. file_size=len(result.content),
  4603. content_hash=hashlib.sha256(result.content).hexdigest(),
  4604. thumbnail_path=thumbnail_path,
  4605. # Inherit identity from the source archive so the new entry shows
  4606. # up alongside its sibling in the archives list.
  4607. print_name=(source_archive.print_name or base_name) + " (re-sliced)",
  4608. print_time_seconds=result.print_time_seconds,
  4609. filament_used_grams=filament_g or None,
  4610. filament_type=new_filament_type,
  4611. filament_color=new_filament_color,
  4612. layer_height=source_archive.layer_height,
  4613. nozzle_diameter=source_archive.nozzle_diameter,
  4614. # The re-sliced output is for whatever printer the user just picked,
  4615. # not the source archive's printer — read the model the slicer baked
  4616. # into the new 3MF, falling back to the source only if it's absent.
  4617. # (Copying source_archive.sliced_for_model kept a cross-printer
  4618. # re-slice, e.g. X1C→H2D, showing the old "X1C sliced" model.)
  4619. sliced_for_model=parsed_metadata.get("sliced_for_model") or source_archive.sliced_for_model,
  4620. # Build plate type that the sliced output was produced for (#1493
  4621. # follow-up): the frontend's ArchiveCard reads ``archive.bed_type``
  4622. # off the top-level column, not extra_data, so without this lift the
  4623. # re-sliced card had no plate badge. ThreeMFParser pulls it from the
  4624. # sliced 3MF's ``slice_info.config`` ``curr_bed_type``; if that's
  4625. # absent (older sidecar / older slice profile) the source archive's
  4626. # bed_type is the right default.
  4627. bed_type=parsed_metadata.get("bed_type") or source_archive.bed_type,
  4628. makerworld_url=source_archive.makerworld_url,
  4629. designer=source_archive.designer,
  4630. # Sliced, not printed: "archived", as archive_print files an unprinted
  4631. # 3MF. It is listed under "Not printed" and is not counted as a
  4632. # completed print; no started/completed_at either.
  4633. status="archived",
  4634. # Priced like any archive with grams, for the card's estimate.
  4635. # Statistics read the print log, so nothing is counted that did not print.
  4636. cost=await estimate_filament_cost(db, filament_g or None, new_filament_type),
  4637. extra_data=metadata,
  4638. created_by_id=current_user_id,
  4639. )
  4640. db.add(new_archive)
  4641. await db.commit()
  4642. await db.refresh(new_archive)
  4643. return SliceArchiveResponse(
  4644. archive_id=new_archive.id,
  4645. name=new_archive.print_name or out_filename,
  4646. print_time_seconds=result.print_time_seconds,
  4647. filament_used_g=filament_g,
  4648. filament_used_mm=filament_mm,
  4649. used_embedded_settings=used_embedded_settings,
  4650. )
  4651. @router.post("/files/{file_id}/slice", status_code=202)
  4652. async def slice_library_file(
  4653. file_id: int,
  4654. request: SliceRequest,
  4655. db: AsyncSession = Depends(get_db, scope="function"),
  4656. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  4657. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  4658. actor: User | ApiKeyActor | None = RequestActor,
  4659. ):
  4660. """Enqueue a slice job for a library file. Returns 202 + job_id; the
  4661. slice runs in the background, the caller polls `GET /slice-jobs/{id}`.
  4662. """
  4663. from backend.app.core.database import async_session
  4664. from backend.app.services.slice_dispatch import (
  4665. http_exception_to_job_error,
  4666. slice_dispatch,
  4667. )
  4668. src_result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  4669. lib_file = src_result.scalar_one_or_none()
  4670. # Per-row ownership gate. LIBRARY_UPLOAD alone let a READ_OWN caller (e.g. the
  4671. # built-in Operators group) slice another user's model by raw id even though
  4672. # GET on that id returned 404 — the sliced output was then attributed to and
  4673. # downloadable by the requester. Enforce the same visibility the read routes
  4674. # use before reading the source off disk. An API key is checked as its
  4675. # owner (RequestActor); only auth off keeps can_read_all=True.
  4676. can_read_all = actor is None or actor.has_permission(Permission.LIBRARY_READ_ALL.value)
  4677. lib_file = _ensure_library_file_visible(lib_file, actor, can_read_all)
  4678. src_lower = (lib_file.filename or "").lower()
  4679. if src_lower.endswith(".step") or src_lower.endswith(".stp"):
  4680. # Neither slicer's CLI can load STEP: OrcaSlicer 2.4.2 and BambuStudio
  4681. # 02.07.01.62 both answer "Unknown file format. Input file must have
  4682. # .stl, .obj, .amf(.xml) extension." Accepting the job here meant
  4683. # reading the file, converting it and uploading it before the sidecar
  4684. # rejected it as unparseable -- which reads as a corrupt model rather
  4685. # than an unsupported format. Say so before any of that happens.
  4686. raise HTTPException(
  4687. status_code=400,
  4688. detail=(
  4689. "STEP files cannot be sliced. The OrcaSlicer and Bambu Studio command-line "
  4690. "slicers load only STL and 3MF -- open the STEP in your slicer and export it "
  4691. "as one of those first."
  4692. ),
  4693. )
  4694. if not (src_lower.endswith(".stl") or src_lower.endswith(".3mf")):
  4695. raise HTTPException(status_code=400, detail="Source file must be STL or 3MF")
  4696. src_path = Path(app_settings.base_dir) / lib_file.file_path
  4697. if not src_path.exists():
  4698. raise HTTPException(status_code=404, detail="Source file missing on disk")
  4699. # Capture inputs the bg task needs — the request DB session is closed
  4700. # before the background task runs.
  4701. model_bytes = src_path.read_bytes()
  4702. folder_id = lib_file.folder_id
  4703. source_lib_file_id = lib_file.id
  4704. # API-keyed callers get None from the auth gate (auth.py keeps that
  4705. # behaviour to avoid a wider scope expansion). Fall back to the API
  4706. # key's owner so cloud-preset resolution can read the stored
  4707. # cloud_token (#1182 follow-up).
  4708. cloud_token_user = current_user or api_key_cloud_owner
  4709. user_id = cloud_token_user.id if cloud_token_user else None
  4710. # The sliced file is its owner's also when no one resolves cloud presets,
  4711. # as a pipeline run's is.
  4712. owner_id = user_id if user_id is not None else (actor.id if isinstance(actor, ApiKeyActor) else None)
  4713. # If the source has a `print_name` in its metadata (BambuStudio always
  4714. # sets this; OrcaSlicer often leaves it blank), derive the sliced
  4715. # output's filename from it instead of the raw filename. The source
  4716. # row's display already prefers print_name, so the sliced row's
  4717. # filename ("Piggo the piggy bank.gcode.3mf") will match the source's
  4718. # display name ("Piggo the piggy bank") with the gcode extension added.
  4719. src_print_name = None
  4720. if lib_file.file_metadata:
  4721. candidate = lib_file.file_metadata.get("print_name")
  4722. if isinstance(candidate, str) and candidate.strip():
  4723. src_print_name = candidate.strip()
  4724. src_ext = Path(lib_file.filename).suffix.lower() or ".3mf"
  4725. model_filename = f"{src_print_name}{src_ext}" if src_print_name else lib_file.filename
  4726. # Block a cross-nozzle-class re-slice (single-nozzle <-> H2D) up front.
  4727. # Fires only when the source is itself a sliced file (carries
  4728. # sliced_for_model); a plain un-sliced model has no source nozzle class.
  4729. await guard_nozzle_class_reslice(
  4730. db,
  4731. cloud_token_user,
  4732. request,
  4733. (lib_file.file_metadata or {}).get("sliced_for_model"),
  4734. )
  4735. async def _run(job_id: int):
  4736. async with async_session() as task_db:
  4737. try:
  4738. response = await slice_and_persist(
  4739. task_db,
  4740. model_bytes=model_bytes,
  4741. model_filename=model_filename,
  4742. folder_id=folder_id,
  4743. extra_metadata={"sliced_from_library_file_id": source_lib_file_id},
  4744. request=request,
  4745. current_user_id=user_id,
  4746. job_id=job_id,
  4747. owner_id=owner_id,
  4748. )
  4749. except HTTPException as exc:
  4750. raise http_exception_to_job_error(exc) from exc
  4751. return response.model_dump()
  4752. job = await slice_dispatch.enqueue(
  4753. kind="library_file",
  4754. source_id=lib_file.id,
  4755. source_name=lib_file.filename,
  4756. owner_id=owner_id,
  4757. run=_run,
  4758. )
  4759. return {
  4760. "job_id": job.id,
  4761. "status": job.status,
  4762. "status_url": f"/api/v1/slice-jobs/{job.id}",
  4763. }
  4764. @router.post("/files/{file_id}/print")
  4765. async def print_library_file(
  4766. file_id: int,
  4767. printer_id: int,
  4768. # SECURITY.md SEC-AUTH-1: every route either has an explicit auth dep or
  4769. # is in the route-auth-coverage allowlist. Gating the deprecation stub on
  4770. # QUEUE_CREATE matches the replacement route (POST /queue/) and means
  4771. # anonymous callers bounce at auth instead of seeing the deprecation
  4772. # message.
  4773. _: User | None = Depends(require_permission_if_auth_enabled(Permission.QUEUE_CREATE)),
  4774. ):
  4775. """Legacy direct library print endpoint. Use POST /queue/ instead."""
  4776. logger.warning(
  4777. "Gone API used: POST /library/files/%s/print?printer_id=%s; use POST /queue/ instead",
  4778. file_id,
  4779. printer_id,
  4780. )
  4781. raise HTTPException(
  4782. status_code=410,
  4783. detail="Direct library-file print has been removed. Create a print queue item with POST /queue/.",
  4784. )
  4785. # ============ File Detail Endpoints ============
  4786. @router.get("/files/{file_id}", response_model=FileResponseSchema)
  4787. async def get_file(
  4788. file_id: int,
  4789. db: AsyncSession = Depends(get_db, scope="function"),
  4790. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4791. require_ownership_permission(
  4792. Permission.LIBRARY_READ_ALL,
  4793. Permission.LIBRARY_READ_OWN,
  4794. )
  4795. ),
  4796. ):
  4797. """Get a file by ID with full details."""
  4798. user, can_read_all = auth_result
  4799. result = await db.execute(
  4800. LibraryFile.active().options(selectinload(LibraryFile.created_by)).where(LibraryFile.id == file_id)
  4801. )
  4802. file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  4803. # Get folder name
  4804. folder_name = None
  4805. if file.folder_id:
  4806. folder_result = await db.execute(select(LibraryFolder.name).where(LibraryFolder.id == file.folder_id))
  4807. folder_name = folder_result.scalar()
  4808. # Get project name
  4809. project_name = None
  4810. if file.project_id:
  4811. project_result = await db.execute(select(Project.name).where(Project.id == file.project_id))
  4812. project_name = project_result.scalar()
  4813. # Get duplicates
  4814. duplicates = []
  4815. duplicate_count = 0
  4816. if file.file_hash:
  4817. dup_result = await db.execute(
  4818. select(LibraryFile, LibraryFolder.name)
  4819. .outerjoin(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  4820. .where(
  4821. LibraryFile.file_hash == file.file_hash,
  4822. LibraryFile.id != file.id,
  4823. LibraryFile.deleted_at.is_(None),
  4824. )
  4825. )
  4826. for dup_file, dup_folder_name in dup_result.all():
  4827. duplicates.append(
  4828. FileDuplicate(
  4829. id=dup_file.id,
  4830. filename=dup_file.filename,
  4831. folder_id=dup_file.folder_id,
  4832. folder_name=dup_folder_name,
  4833. created_at=dup_file.created_at,
  4834. )
  4835. )
  4836. duplicate_count = len(duplicates)
  4837. # Extract key metadata fields
  4838. print_name = None
  4839. print_time = None
  4840. filament_grams = None
  4841. sliced_for_model = None
  4842. if file.file_metadata:
  4843. print_name = file.file_metadata.get("print_name")
  4844. print_time = file.file_metadata.get("print_time_seconds")
  4845. filament_grams = file.file_metadata.get("filament_used_grams")
  4846. sliced_for_model = file.file_metadata.get("sliced_for_model")
  4847. return FileResponseSchema(
  4848. id=file.id,
  4849. folder_id=file.folder_id,
  4850. folder_name=folder_name,
  4851. project_id=file.project_id,
  4852. project_name=project_name,
  4853. filename=file.filename,
  4854. file_path=file.file_path,
  4855. file_type=file.file_type,
  4856. file_size=file.file_size,
  4857. file_hash=file.file_hash,
  4858. thumbnail_path=file.thumbnail_path,
  4859. metadata=file.file_metadata,
  4860. print_count=file.print_count,
  4861. last_printed_at=file.last_printed_at,
  4862. notes=file.notes,
  4863. external_url=file.external_url,
  4864. photos=list(file.photos or []),
  4865. source_url=file.source_url,
  4866. duplicates=duplicates if duplicates else None,
  4867. duplicate_count=duplicate_count,
  4868. created_by_id=file.created_by_id,
  4869. created_by_username=file.created_by.username if file.created_by else None,
  4870. created_at=file.created_at,
  4871. updated_at=file.updated_at,
  4872. print_name=print_name,
  4873. print_time_seconds=print_time,
  4874. filament_used_grams=filament_grams,
  4875. sliced_for_model=sliced_for_model,
  4876. )
  4877. @router.put("/files/{file_id}", response_model=FileResponseSchema)
  4878. async def update_file(
  4879. file_id: int,
  4880. data: FileUpdate,
  4881. db: AsyncSession = Depends(get_db, scope="function"),
  4882. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4883. require_ownership_permission(
  4884. Permission.LIBRARY_UPDATE_ALL,
  4885. Permission.LIBRARY_UPDATE_OWN,
  4886. )
  4887. ),
  4888. ):
  4889. """Update a file's metadata."""
  4890. user, can_modify_all = auth_result
  4891. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  4892. file = result.scalar_one_or_none()
  4893. if not file:
  4894. raise HTTPException(status_code=404, detail="File not found")
  4895. # Ownership check
  4896. if not can_modify_all:
  4897. if file.created_by_id != user.id:
  4898. raise HTTPException(status_code=403, detail="You can only update your own files")
  4899. if data.filename is not None:
  4900. # Bambu printer SD cards are FAT32/exFAT; reject the same set Bambu
  4901. # Studio refuses on save so we fail here with a clear message
  4902. # instead of an obscure FTP 553 at print time (#1540).
  4903. try:
  4904. validate_print_filename(data.filename)
  4905. except InvalidFilenameError as e:
  4906. raise HTTPException(status_code=400, detail=str(e)) from e
  4907. file.filename = data.filename
  4908. # No print_name to keep in sync — library files display by filename,
  4909. # and _without_print_name strips the embedded 3MF Title on import (#1489).
  4910. if data.folder_id is not None:
  4911. target_folder = None
  4912. if data.folder_id != 0:
  4913. # library:update_all moves into any folder, as before (#3201).
  4914. target_folder = await get_writable_folder(db, data.folder_id, None if can_modify_all else user)
  4915. # Into or out of an external folder the bytes have to move too, and a
  4916. # read-only one refuses them: that is the move route's work. Here only
  4917. # folder_id changed, so the file showed in a folder its bytes were not
  4918. # in (F8).
  4919. unchanged = (target_folder.id if target_folder is not None else None) == file.folder_id
  4920. if not unchanged and (file.is_external or (target_folder is not None and target_folder.is_external)):
  4921. raise HTTPException(
  4922. status_code=400,
  4923. detail="Move a file into or out of an external folder with POST /api/v1/library/files/move",
  4924. )
  4925. file.folder_id = target_folder.id if target_folder is not None else None
  4926. if data.project_id is not None:
  4927. if data.project_id == 0:
  4928. file.project_id = None
  4929. else:
  4930. # Verify project exists
  4931. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  4932. if not project_result.scalar_one_or_none():
  4933. raise HTTPException(status_code=404, detail="Project not found")
  4934. file.project_id = data.project_id
  4935. if data.notes is not None:
  4936. file.notes = data.notes if data.notes else None
  4937. if data.external_url is not None:
  4938. file.external_url = data.external_url.strip() or None
  4939. await db.commit()
  4940. await db.refresh(file)
  4941. # Return full response. Bypass get_file's ownership gate — caller already
  4942. # passed update_file's ownership gate above, so we re-fetch + serialise
  4943. # directly instead of calling the route function (which would try to
  4944. # evaluate its own Depends() at call time and trip a TypeError).
  4945. return await get_file(file_id, db, auth_result=(None, True))
  4946. @router.delete("/files/{file_id}")
  4947. async def delete_file(
  4948. file_id: int,
  4949. db: AsyncSession = Depends(get_db, scope="function"),
  4950. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4951. require_ownership_permission(
  4952. Permission.LIBRARY_DELETE_ALL,
  4953. Permission.LIBRARY_DELETE_OWN,
  4954. )
  4955. ),
  4956. ):
  4957. """Move a file to the trash (soft-delete).
  4958. The file's bytes and thumbnail stay on disk until the trash sweeper
  4959. hard-deletes the row after the retention window (see #1008). External
  4960. files skip the trash entirely — they can't be restored from disk and the
  4961. underlying file is outside Bambuddy's control, so we just drop the DB
  4962. record and thumbnail.
  4963. """
  4964. user, can_modify_all = auth_result
  4965. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  4966. file = result.scalar_one_or_none()
  4967. if not file:
  4968. raise HTTPException(status_code=404, detail="File not found")
  4969. # Ownership check
  4970. if not can_modify_all:
  4971. if file.created_by_id != user.id:
  4972. raise HTTPException(status_code=403, detail="You can only delete your own files")
  4973. if file.is_external:
  4974. # External files bypass the trash — just drop the DB row + our thumbnail.
  4975. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  4976. if abs_thumb_path and abs_thumb_path.exists():
  4977. try:
  4978. abs_thumb_path.unlink()
  4979. except OSError as e:
  4980. logger.warning("Failed to delete thumbnail from disk: %s", e)
  4981. from backend.app.services.library_trash import delete_dependent_variants, release_queue_references
  4982. await delete_dependent_variants(db, [file.id])
  4983. await release_queue_references(db, [file.id])
  4984. remove_library_photos_dir(file.id)
  4985. await db.delete(file)
  4986. await db.commit()
  4987. return {"status": "success", "message": "File deleted", "trashed": False}
  4988. # Managed file: soft-delete. Sweeper removes bytes + thumbnail after retention.
  4989. file.deleted_at = datetime.now(timezone.utc)
  4990. await db.commit()
  4991. return {"status": "success", "message": "File moved to trash", "trashed": True}
  4992. # ============ File Content Endpoints ============
  4993. @router.get("/files/{file_id}/download")
  4994. async def download_file(
  4995. file_id: int,
  4996. db: AsyncSession = Depends(get_db, scope="function"),
  4997. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  4998. require_ownership_permission(
  4999. Permission.LIBRARY_READ_ALL,
  5000. Permission.LIBRARY_READ_OWN,
  5001. )
  5002. ),
  5003. ):
  5004. """Download a file."""
  5005. user, can_read_all = auth_result
  5006. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5007. file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  5008. abs_path = to_absolute_path(file.file_path)
  5009. if not abs_path or not abs_path.exists():
  5010. raise HTTPException(status_code=404, detail="File not found on disk")
  5011. return FastAPIFileResponse(
  5012. str(abs_path),
  5013. filename=file.filename,
  5014. media_type="application/octet-stream",
  5015. )
  5016. @router.post("/files/{file_id}/slicer-token")
  5017. async def create_library_slicer_token(
  5018. file_id: int,
  5019. db: AsyncSession = Depends(get_db, scope="function"),
  5020. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5021. require_ownership_permission(
  5022. Permission.LIBRARY_READ_ALL,
  5023. Permission.LIBRARY_READ_OWN,
  5024. )
  5025. ),
  5026. ):
  5027. """Create a short-lived download token for opening files in slicer applications.
  5028. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  5029. auth headers, so they use this token in the URL path instead.
  5030. """
  5031. from backend.app.core.auth import create_slicer_download_token
  5032. user, can_read_all = auth_result
  5033. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5034. _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  5035. token = await create_slicer_download_token("library", file_id)
  5036. return {"token": token}
  5037. @router.get("/files/{file_id}/dl/{token}/{filename}")
  5038. async def download_library_file_for_slicer(
  5039. file_id: int,
  5040. token: str,
  5041. filename: str,
  5042. db: AsyncSession = Depends(get_db, scope="function"),
  5043. ):
  5044. """Download a library file using a slicer download token.
  5045. Token-authenticated (no auth headers needed). The token is short-lived and
  5046. file-bound, created by POST /files/{file_id}/slicer-token, and redeemable
  5047. for the rest of its TTL rather than exactly once -- the slicer is a separate
  5048. process that may fetch the URL more than once (#3029).
  5049. Filename is at the end of the URL so slicers can detect the file format.
  5050. """
  5051. from backend.app.core.auth import verify_slicer_download_token
  5052. if not await verify_slicer_download_token(token, "library", file_id, single_use=False):
  5053. raise HTTPException(status_code=403, detail="Invalid or expired download token")
  5054. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5055. file = result.scalar_one_or_none()
  5056. if not file:
  5057. raise HTTPException(status_code=404, detail="File not found")
  5058. abs_path = to_absolute_path(file.file_path)
  5059. if not abs_path or not abs_path.exists():
  5060. raise HTTPException(status_code=404, detail="File not found on disk")
  5061. return FastAPIFileResponse(
  5062. str(abs_path),
  5063. filename=file.filename,
  5064. media_type="application/octet-stream",
  5065. )
  5066. @router.get("/files/{file_id}/thumbnail")
  5067. async def get_thumbnail(
  5068. file_id: int,
  5069. db: AsyncSession = Depends(get_db, scope="function"),
  5070. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5071. require_media_token_ownership(
  5072. Permission.LIBRARY_READ_ALL,
  5073. Permission.LIBRARY_READ_OWN,
  5074. )
  5075. ),
  5076. ):
  5077. """Get a file's thumbnail.
  5078. Accepts a media token in ``?token=`` because <img> cannot send headers.
  5079. Ownership is enforced here rather than assumed from the credential: until
  5080. #3025 this route took the anonymous camera-stream token, which carried no
  5081. principal, so any holder could read any user's thumbnail by walking IDs.
  5082. """
  5083. user, can_read_all = auth_result
  5084. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5085. file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  5086. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  5087. if not abs_thumb_path or not abs_thumb_path.exists():
  5088. raise HTTPException(status_code=404, detail="Thumbnail not found")
  5089. # Detect media type from extension
  5090. thumb_ext = abs_thumb_path.suffix.lower()
  5091. media_types = {
  5092. ".png": "image/png",
  5093. ".jpg": "image/jpeg",
  5094. ".jpeg": "image/jpeg",
  5095. ".gif": "image/gif",
  5096. ".webp": "image/webp",
  5097. }
  5098. media_type = media_types.get(thumb_ext, "image/png")
  5099. return FastAPIFileResponse(str(abs_thumb_path), media_type=media_type)
  5100. @router.post("/files/{file_id}/preview-thumbnail", response_model=ClientThumbnailResponse)
  5101. async def upload_preview_thumbnail(
  5102. file_id: int,
  5103. thumbnail: UploadFile = File(...),
  5104. db: AsyncSession = Depends(get_db, scope="function"),
  5105. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5106. require_ownership_permission(
  5107. Permission.LIBRARY_UPDATE_ALL,
  5108. Permission.LIBRARY_UPDATE_OWN,
  5109. )
  5110. ),
  5111. ):
  5112. """Store a client-rendered preview thumbnail for a file (#2976).
  5113. STEP, PDF and spreadsheet previews are rendered in the browser; the FE
  5114. posts its first render here so the grid gets a thumbnail without the
  5115. server needing OpenCascade. A PDF normally has its PDFium thumbnail from
  5116. upload already, so for PDFs this only fills the gap for a file PDFium
  5117. could not read. Only file types in ``CLIENT_THUMBNAIL_TYPES`` are
  5118. accepted, and only while the file has no thumbnail yet — a stored
  5119. thumbnail is never replaced by this route.
  5120. """
  5121. user, can_modify_all = auth_result
  5122. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5123. file = result.scalar_one_or_none()
  5124. if not file:
  5125. raise HTTPException(status_code=404, detail="File not found")
  5126. # Ownership check (same shape as update_file)
  5127. if not can_modify_all:
  5128. if file.created_by_id != user.id:
  5129. raise HTTPException(status_code=403, detail="You can only update your own files")
  5130. if file.file_type not in CLIENT_THUMBNAIL_TYPES:
  5131. raise HTTPException(status_code=400, detail="File type does not accept client-rendered thumbnails")
  5132. if file.thumbnail_path:
  5133. return ClientThumbnailResponse(updated=False)
  5134. content = await thumbnail.read(MAX_CLIENT_THUMBNAIL_BYTES + 1)
  5135. if len(content) > MAX_CLIENT_THUMBNAIL_BYTES:
  5136. raise HTTPException(status_code=413, detail="Thumbnail too large")
  5137. # Decode and re-encode through PIL: validates the bytes are a real PNG
  5138. # and strips anything that isn't pixel data before it lands on disk.
  5139. import io
  5140. from PIL import Image, UnidentifiedImageError
  5141. try:
  5142. # Image.open() reads the header only. Both checks below happen before
  5143. # load(), so a declared-but-never-delivered canvas is refused rather
  5144. # than allocated. DecompressionBombError derives straight from
  5145. # Exception, so it has to be named explicitly — open() itself raises
  5146. # it once the declared size passes PIL's own limit.
  5147. with Image.open(io.BytesIO(content)) as source:
  5148. if source.format != "PNG":
  5149. raise HTTPException(status_code=400, detail="Thumbnail must be a PNG image")
  5150. if max(source.size) > MAX_CLIENT_THUMBNAIL_EDGE:
  5151. raise HTTPException(status_code=400, detail="Thumbnail image dimensions too large")
  5152. source.load()
  5153. img = source.convert("RGBA") if source.mode not in ("RGB", "RGBA") else source.copy()
  5154. except HTTPException:
  5155. raise
  5156. except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as e:
  5157. raise HTTPException(status_code=400, detail="Invalid thumbnail image") from e
  5158. if max(img.size) > STORED_CLIENT_THUMBNAIL_EDGE:
  5159. img.thumbnail((STORED_CLIENT_THUMBNAIL_EDGE, STORED_CLIENT_THUMBNAIL_EDGE), Image.Resampling.LANCZOS)
  5160. thumbnails_dir = get_library_thumbnails_dir()
  5161. thumb_filename = f"{uuid.uuid4().hex}.png"
  5162. thumb_path = thumbnails_dir / thumb_filename # SEC-PATH-OK: thumb_filename = uuid.uuid4().hex + ".png"
  5163. # Outside the decode guard on purpose: a full disk or an unwritable
  5164. # thumbnail directory is ours, not "Invalid thumbnail image".
  5165. try:
  5166. img.save(thumb_path, "PNG", optimize=True)
  5167. except OSError as e:
  5168. logger.error("Failed to store preview thumbnail for file %s: %s", file_id, e)
  5169. raise HTTPException(status_code=500, detail="Failed to store thumbnail") from e
  5170. # Two previews of the same file can reach this point together; the loser
  5171. # of the UPDATE takes its PNG back off disk instead of orphaning it.
  5172. result = await db.execute(
  5173. update(LibraryFile)
  5174. .where(LibraryFile.id == file_id, LibraryFile.thumbnail_path.is_(None))
  5175. .values(thumbnail_path=to_relative_path(thumb_path))
  5176. )
  5177. await db.commit()
  5178. if result.rowcount == 0:
  5179. thumb_path.unlink(missing_ok=True)
  5180. return ClientThumbnailResponse(updated=False)
  5181. return ClientThumbnailResponse(updated=True)
  5182. # ============ Photo Endpoints (#3077) ============
  5183. @router.post("/files/{file_id}/photos")
  5184. async def upload_file_photo(
  5185. file_id: int,
  5186. file: UploadFile = File(...),
  5187. db: AsyncSession = Depends(get_db, scope="function"),
  5188. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5189. require_ownership_permission(
  5190. Permission.LIBRARY_UPDATE_ALL,
  5191. Permission.LIBRARY_UPDATE_OWN,
  5192. )
  5193. ),
  5194. ):
  5195. """Attach a photo of the printed result to a library file.
  5196. Photos are Bambuddy-side metadata, so external files take them too. Same
  5197. shape as the archive photo upload: extension allowlist, uuid-named on
  5198. disk, and the ``photos`` list re-assigned so SQLAlchemy sees the change.
  5199. """
  5200. user, can_modify_all = auth_result
  5201. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5202. library_file = result.scalar_one_or_none()
  5203. if not library_file:
  5204. raise HTTPException(status_code=404, detail="File not found")
  5205. # Ownership check (same shape as update_file)
  5206. if not can_modify_all:
  5207. if library_file.created_by_id != user.id:
  5208. raise HTTPException(status_code=403, detail="You can only update your own files")
  5209. if not file.filename or not file.filename.lower().endswith(PHOTO_EXTENSIONS):
  5210. raise HTTPException(status_code=400, detail="File must be an image (.jpg, .jpeg, .png, .webp)")
  5211. content = await file.read(MAX_PHOTO_BYTES + 1)
  5212. if len(content) > MAX_PHOTO_BYTES:
  5213. raise HTTPException(status_code=413, detail="Photo too large (max 10 MB)")
  5214. photos_dir = library_photos_dir(library_file.id)
  5215. photos_dir.mkdir(parents=True, exist_ok=True)
  5216. ext = Path(file.filename).suffix.lower()
  5217. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  5218. photo_path = photos_dir / photo_filename # SEC-PATH-OK: photo_filename = uuid.uuid4().hex[:8] + ext
  5219. photo_path.write_bytes(content)
  5220. photos = list(library_file.photos or [])
  5221. photos.append(photo_filename)
  5222. library_file.photos = photos
  5223. await db.commit()
  5224. await db.refresh(library_file)
  5225. return {"status": "uploaded", "filename": photo_filename, "photos": library_file.photos}
  5226. @router.get("/files/{file_id}/photos/{filename}")
  5227. async def get_file_photo(
  5228. file_id: int,
  5229. filename: str,
  5230. db: AsyncSession = Depends(get_db, scope="function"),
  5231. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5232. require_media_token_ownership(
  5233. Permission.LIBRARY_READ_ALL,
  5234. Permission.LIBRARY_READ_OWN,
  5235. )
  5236. ),
  5237. ):
  5238. """Serve one photo. Media-token auth like the thumbnail route (#3025)."""
  5239. user, can_read_all = auth_result
  5240. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5241. library_file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  5242. # Membership check first: names are uuid-generated on upload, so anything
  5243. # not in the stored list is not a photo, whatever is on disk.
  5244. if not library_file.photos or filename not in library_file.photos:
  5245. raise HTTPException(status_code=404, detail="Photo not found")
  5246. try:
  5247. photo_path = safe_join_under(library_photos_dir(library_file.id), filename, http=False)
  5248. except PathTraversalError:
  5249. raise HTTPException(status_code=404, detail="Photo not found") from None
  5250. if not photo_path.is_file():
  5251. raise HTTPException(status_code=404, detail="Photo not found")
  5252. media_type = PHOTO_MEDIA_TYPES.get(Path(filename).suffix.lower(), "image/jpeg")
  5253. return FastAPIFileResponse(str(photo_path), media_type=media_type)
  5254. @router.delete("/files/{file_id}/photos/{filename}")
  5255. async def delete_file_photo(
  5256. file_id: int,
  5257. filename: str,
  5258. db: AsyncSession = Depends(get_db, scope="function"),
  5259. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5260. require_ownership_permission(
  5261. Permission.LIBRARY_UPDATE_ALL,
  5262. Permission.LIBRARY_UPDATE_OWN,
  5263. )
  5264. ),
  5265. ):
  5266. """Remove a photo from a library file."""
  5267. user, can_modify_all = auth_result
  5268. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5269. library_file = result.scalar_one_or_none()
  5270. if not library_file:
  5271. raise HTTPException(status_code=404, detail="File not found")
  5272. if not can_modify_all:
  5273. if library_file.created_by_id != user.id:
  5274. raise HTTPException(status_code=403, detail="You can only update your own files")
  5275. if not library_file.photos or filename not in library_file.photos:
  5276. raise HTTPException(status_code=404, detail="Photo not found")
  5277. try:
  5278. photo_path = safe_join_under(library_photos_dir(library_file.id), filename, http=False)
  5279. except PathTraversalError:
  5280. raise HTTPException(status_code=404, detail="Photo not found") from None
  5281. if photo_path.is_file():
  5282. try:
  5283. photo_path.unlink()
  5284. except OSError as e:
  5285. logger.warning("Failed to delete photo from disk: %s", e)
  5286. photos = [p for p in library_file.photos if p != filename]
  5287. library_file.photos = photos if photos else None
  5288. await db.commit()
  5289. return {"status": "deleted", "photos": library_file.photos or []}
  5290. @router.get("/files/{file_id}/gcode")
  5291. async def get_gcode(
  5292. file_id: int,
  5293. plate: int | None = None,
  5294. db: AsyncSession = Depends(get_db, scope="function"),
  5295. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5296. require_ownership_permission(
  5297. Permission.LIBRARY_READ_ALL,
  5298. Permission.LIBRARY_READ_OWN,
  5299. )
  5300. ),
  5301. ):
  5302. """Get gcode for a file (for preview).
  5303. Mirrors the archive route: ``?plate=2`` returns ``Metadata/plate_2.gcode``,
  5304. and omitting it returns the lowest-numbered plate. The viewer has been
  5305. sending ``plate`` since it gained a multi-plate URL, but this route took no
  5306. such parameter and FastAPI drops unknown query parameters silently — so
  5307. every multi-plate library file opened on whichever plate the slicer wrote
  5308. first into the zip, which is not plate 1.
  5309. """
  5310. user, can_read_all = auth_result
  5311. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5312. file = _ensure_library_file_visible(result.scalar_one_or_none(), user, can_read_all)
  5313. abs_path = to_absolute_path(file.file_path)
  5314. if not abs_path or not abs_path.exists():
  5315. raise HTTPException(status_code=404, detail="File not found on disk")
  5316. # Legacy sliced rows from before #1709 stored a `.gcode.3mf` ZIP body
  5317. # under file_type="gcode" — the on-disk filename is the truth in that
  5318. # case, so detect by suffix before checking the type column.
  5319. is_gcode_3mf = file.file_type in ("3mf", "gcode.3mf") or file.filename.lower().endswith(".gcode.3mf")
  5320. if plate is not None and plate < 1:
  5321. raise HTTPException(status_code=400, detail="Plate index must be >= 1")
  5322. if is_gcode_3mf:
  5323. try:
  5324. with zipfile.ZipFile(str(abs_path), "r") as zf:
  5325. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  5326. if not gcode_files:
  5327. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  5328. if plate is not None:
  5329. selected = select_plate_gcode_name(gcode_files, plate)
  5330. if selected is None:
  5331. raise HTTPException(status_code=404, detail=f"Plate {plate} not found in this file")
  5332. else:
  5333. selected = default_plate_gcode_name(gcode_files)
  5334. gcode_content = zf.read(selected)
  5335. from fastapi.responses import Response
  5336. return Response(content=gcode_content, media_type="text/plain")
  5337. except zipfile.BadZipFile:
  5338. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  5339. elif file.file_type == "gcode":
  5340. return FastAPIFileResponse(str(abs_path), media_type="text/plain")
  5341. else:
  5342. raise HTTPException(status_code=400, detail="Unsupported file type")
  5343. # ============ Bulk Operations ============
  5344. @router.post("/files/move")
  5345. async def move_files(
  5346. data: FileMoveRequest,
  5347. db: AsyncSession = Depends(get_db, scope="function"),
  5348. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5349. require_ownership_permission(
  5350. Permission.LIBRARY_UPDATE_ALL,
  5351. Permission.LIBRARY_UPDATE_OWN,
  5352. )
  5353. ),
  5354. ):
  5355. """Move multiple files to a folder.
  5356. Cross-boundary moves (managed ↔ external, or external ↔ external)
  5357. physically relocate the bytes — see ``_move_file_bytes``. Same-boundary
  5358. moves stay DB-only because the file's on-disk location doesn't depend
  5359. on which managed folder owns it.
  5360. Files not owned by the user are skipped (unless user has ``*_all``
  5361. permission). Each skip carries a structured reason so the UI can
  5362. surface "5 of 10 files were skipped: 3 had filename collisions on
  5363. the NAS, 2 are no longer on disk" rather than a blank "skipped: 5".
  5364. """
  5365. user, can_modify_all = auth_result
  5366. # Verify folder exists if specified
  5367. target_folder: LibraryFolder | None = None
  5368. if data.folder_id is not None:
  5369. # Only into a folder the user may write to (#3201); library:update_all
  5370. # moves into any folder, as before.
  5371. target_folder = await get_writable_folder(db, data.folder_id, None if can_modify_all else user)
  5372. if target_folder.is_external and target_folder.external_readonly:
  5373. raise HTTPException(status_code=403, detail="Cannot move files to a read-only external folder")
  5374. target_is_external = target_folder is not None and target_folder.is_external
  5375. moved = 0
  5376. skipped = 0
  5377. skipped_reasons: list[dict] = []
  5378. for file_id in data.file_ids:
  5379. result = await db.execute(
  5380. LibraryFile.active().options(selectinload(LibraryFile.folder)).where(LibraryFile.id == file_id)
  5381. )
  5382. file = result.scalar_one_or_none()
  5383. if not file:
  5384. continue
  5385. # Ownership check
  5386. if not can_modify_all and file.created_by_id != user.id:
  5387. skipped += 1
  5388. skipped_reasons.append({"file_id": file_id, "code": "not_owner", "reason": "not the file owner"})
  5389. continue
  5390. # No bytes need to move when both ends are managed (same-boundary).
  5391. if not file.is_external and not target_is_external:
  5392. file.folder_id = data.folder_id
  5393. moved += 1
  5394. continue
  5395. # Block moves out of a read-only external mount. The user only has
  5396. # read access to the source, and a move is semantically a delete on
  5397. # the source — which a read-only mount can't fulfil. Without this
  5398. # guard we'd succeed at copying to the target, fail to unlink the
  5399. # source, and the same file would now exist in two places (with
  5400. # the DB pointing at only one).
  5401. if file.is_external and file.folder is not None and file.folder.external_readonly:
  5402. skipped += 1
  5403. skipped_reasons.append(
  5404. {"file_id": file_id, "code": "source_readonly", "reason": "source is on a read-only external folder"}
  5405. )
  5406. continue
  5407. # Otherwise relocate the bytes, then update the DB row to match.
  5408. try:
  5409. new_file_path = _move_file_bytes(file, target_folder)
  5410. except _MoveSkip as e:
  5411. skipped += 1
  5412. skipped_reasons.append({"file_id": file_id, "code": e.code, "reason": e.reason})
  5413. continue
  5414. file.is_external = target_is_external
  5415. file.folder_id = data.folder_id
  5416. file.file_path = new_file_path
  5417. # External rows historically carry `file_hash=None` (scan skips
  5418. # hashing). When pulling an external file into managed storage,
  5419. # compute the hash so dedup detection works for future uploads
  5420. # of the same content.
  5421. if not target_is_external and file.file_hash is None:
  5422. try:
  5423. abs_path = to_absolute_path(new_file_path)
  5424. if abs_path:
  5425. file.file_hash = calculate_file_hash(abs_path)
  5426. except OSError:
  5427. pass # leave hash null; dedup just won't match this row
  5428. moved += 1
  5429. await db.commit()
  5430. return {
  5431. "status": "success",
  5432. "moved": moved,
  5433. "skipped": skipped,
  5434. "skipped_reasons": skipped_reasons,
  5435. }
  5436. @router.post("/bulk-delete", response_model=BulkDeleteResponse)
  5437. async def bulk_delete(
  5438. data: BulkDeleteRequest,
  5439. db: AsyncSession = Depends(get_db, scope="function"),
  5440. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5441. require_ownership_permission(
  5442. Permission.LIBRARY_DELETE_ALL,
  5443. Permission.LIBRARY_DELETE_OWN,
  5444. )
  5445. ),
  5446. ):
  5447. """Delete multiple files and/or folders.
  5448. Files not owned by the user are skipped (unless user has *_all permission).
  5449. """
  5450. from backend.app.services.library_trash import delete_dependent_variants, release_queue_references
  5451. user, can_modify_all = auth_result
  5452. deleted_files = 0
  5453. deleted_folders = 0
  5454. skipped_files = 0
  5455. # External files bypass the trash and are removed for good, so the queue has
  5456. # to come off them. Collected here and dealt with once, below the loop.
  5457. hard_deleted: list[LibraryFile] = []
  5458. # Delete files first. Managed files go to trash (sweeper hard-deletes bytes
  5459. # later); external files bypass trash since their disk state is outside our
  5460. # control and can't be restored from trash anyway.
  5461. now = datetime.now(timezone.utc)
  5462. for file_id in data.file_ids:
  5463. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  5464. file = result.scalar_one_or_none()
  5465. if not file:
  5466. continue
  5467. if not can_modify_all and file.created_by_id != user.id:
  5468. skipped_files += 1
  5469. continue
  5470. if file.is_external:
  5471. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  5472. if abs_thumb_path and abs_thumb_path.exists():
  5473. try:
  5474. abs_thumb_path.unlink()
  5475. except OSError as e:
  5476. logger.warning("Failed to delete thumbnail from disk: %s", e)
  5477. hard_deleted.append(file)
  5478. else:
  5479. file.deleted_at = now
  5480. deleted_files += 1
  5481. # After the loop and before any delete is issued (#2819). Order matters
  5482. # twice over: a query run while a delete is pending autoflushes it, taking
  5483. # the cascade with it, and releasing once for the whole set is a couple of
  5484. # statements rather than a couple per file.
  5485. if hard_deleted:
  5486. hard_deleted_ids = [f.id for f in hard_deleted]
  5487. await delete_dependent_variants(db, hard_deleted_ids)
  5488. await release_queue_references(db, hard_deleted_ids)
  5489. for file in hard_deleted:
  5490. remove_library_photos_dir(file.id)
  5491. await db.delete(file)
  5492. # Delete folders (cascade will handle contents). Without *_all permission a
  5493. # user deletes only what DELETE /folders/{id} would let them (#1781, #3201);
  5494. # a folder they can't see is skipped like one that doesn't exist.
  5495. index = await load_folder_index(db) if data.folder_ids and not can_modify_all else None
  5496. visible = visible_folder_ids(index, user) if index is not None else None
  5497. for folder_id in data.folder_ids:
  5498. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  5499. folder = result.scalar_one_or_none()
  5500. if folder:
  5501. if visible is not None and folder.id not in visible:
  5502. continue
  5503. if not can_modify_all and folder_delete_blocker(index, folder, user):
  5504. continue
  5505. # Count files that will be deleted
  5506. file_count_result = await db.execute(
  5507. select(func.count(LibraryFile.id)).where(
  5508. LibraryFile.folder_id == folder_id,
  5509. LibraryFile.deleted_at.is_(None),
  5510. )
  5511. )
  5512. deleted_files += file_count_result.scalar() or 0
  5513. tree_file_ids = await _folder_tree_file_ids(db, folder_id)
  5514. await delete_dependent_variants(db, tree_file_ids)
  5515. await release_queue_references(db, tree_file_ids)
  5516. # The cascade hard-deletes every row in the subtree, so their
  5517. # photos go with them — same as DELETE /folders/{id} (#3077).
  5518. for doomed_id in tree_file_ids:
  5519. remove_library_photos_dir(doomed_id)
  5520. await db.delete(folder)
  5521. deleted_folders += 1
  5522. await db.commit()
  5523. return BulkDeleteResponse(deleted_files=deleted_files, deleted_folders=deleted_folders)
  5524. # ============ Stats Endpoint ============
  5525. @router.get("/stats")
  5526. async def get_library_stats(
  5527. db: AsyncSession = Depends(get_db, scope="function"),
  5528. auth_result: tuple[User | ApiKeyActor | None, bool] = Depends(
  5529. require_ownership_permission(
  5530. Permission.LIBRARY_READ_ALL,
  5531. Permission.LIBRARY_READ_OWN,
  5532. )
  5533. ),
  5534. ):
  5535. """Get library statistics."""
  5536. user, can_read_all = auth_result
  5537. # Stats exclude trashed files — users see counts/sizes for what's actually in the library.
  5538. # Without LIBRARY_READ_ALL the stats reflect only the caller's own files —
  5539. # match what the file list endpoint shows so the numbers stay consistent.
  5540. file_filters = [LibraryFile.deleted_at.is_(None)]
  5541. if user is not None and not can_read_all:
  5542. file_filters.append(LibraryFile.created_by_id == user.id)
  5543. # Total files
  5544. total_files_result = await db.execute(select(func.count(LibraryFile.id)).where(*file_filters))
  5545. total_files = total_files_result.scalar() or 0
  5546. # Total folders: the ones the user can see (#3201)
  5547. visible = None if sees_all_folders(user) else visible_folder_ids(await load_folder_index(db), user)
  5548. if visible is None:
  5549. total_folders_result = await db.execute(select(func.count(LibraryFolder.id)))
  5550. total_folders = total_folders_result.scalar() or 0
  5551. else:
  5552. total_folders = len(visible)
  5553. # Total size
  5554. total_size_result = await db.execute(select(func.sum(LibraryFile.file_size)).where(*file_filters))
  5555. total_size = total_size_result.scalar() or 0
  5556. # Files by type
  5557. type_result = await db.execute(
  5558. select(LibraryFile.file_type, func.count(LibraryFile.id)).where(*file_filters).group_by(LibraryFile.file_type)
  5559. )
  5560. files_by_type = dict(type_result.all())
  5561. # Total prints
  5562. total_prints_result = await db.execute(select(func.sum(LibraryFile.print_count)).where(*file_filters))
  5563. total_prints = total_prints_result.scalar() or 0
  5564. # Disk space info
  5565. library_dir = get_library_dir()
  5566. try:
  5567. disk_stat = shutil.disk_usage(library_dir)
  5568. disk_free_bytes = disk_stat.free
  5569. disk_total_bytes = disk_stat.total
  5570. disk_used_bytes = disk_stat.used
  5571. except OSError:
  5572. disk_free_bytes = 0
  5573. disk_total_bytes = 0
  5574. disk_used_bytes = 0
  5575. return {
  5576. "total_files": total_files,
  5577. "total_folders": total_folders,
  5578. "total_size_bytes": total_size,
  5579. "files_by_type": files_by_type,
  5580. "total_prints": total_prints,
  5581. "disk_free_bytes": disk_free_bytes,
  5582. "disk_total_bytes": disk_total_bytes,
  5583. "disk_used_bytes": disk_used_bytes,
  5584. }