library.py 219 KB

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