library.py 192 KB

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