library.py 234 KB

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