library.py 192 KB

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