library.py 238 KB

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