library.py 164 KB

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