library.py 260 KB

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