library.py 247 KB

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