library.py 167 KB

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