library.py 195 KB

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