library.py 197 KB

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