library.py 241 KB

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