library.py 187 KB

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