library.py 224 KB

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