library.py 235 KB

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