library.py 195 KB

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