library.py 245 KB

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