library.py 223 KB

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