library.py 263 KB

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