library.py 212 KB

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