library.py 203 KB

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