library.py 275 KB

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