library.py 231 KB

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