library.py 240 KB

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