library.py 259 KB

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