library.py 166 KB

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