library.py 235 KB

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