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