library.py 267 KB

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