library.py 285 KB

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