library.py 167 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111
  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_embedded_presets_from_3mf,
  66. extract_nozzle_mapping_from_3mf,
  67. extract_project_filaments_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. # Printer / process preset names the 3MF was prepared with — used by the
  1895. # SliceModal to default its dropdowns (#1325). Initialised here so the
  1896. # final return never raises NameError when the file isn't a valid zip.
  1897. embedded_presets: dict[str, str | None] = {"printer": None, "process": None}
  1898. try:
  1899. with zipfile.ZipFile(file_path, "r") as zf:
  1900. namelist = zf.namelist()
  1901. embedded_presets = extract_embedded_presets_from_3mf(zf)
  1902. # Find all plate gcode files to determine available plates
  1903. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1904. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  1905. plate_indices: list[int] = []
  1906. if gcode_files:
  1907. # Extract plate indices from gcode filenames
  1908. for gf in gcode_files:
  1909. try:
  1910. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1911. plate_indices.append(int(plate_str))
  1912. except ValueError:
  1913. pass # Skip gcode file with non-numeric plate index
  1914. else:
  1915. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  1916. plate_png_files = [
  1917. n
  1918. for n in namelist
  1919. if n.startswith("Metadata/plate_")
  1920. and n.endswith(".png")
  1921. and "_small" not in n
  1922. and "no_light" not in n
  1923. ]
  1924. plate_name_candidates = plate_json_files + plate_png_files
  1925. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  1926. seen_indices: set[int] = set()
  1927. for name in plate_name_candidates:
  1928. match = plate_re.match(name)
  1929. if match:
  1930. try:
  1931. index = int(match.group(1))
  1932. except ValueError:
  1933. continue
  1934. if index in seen_indices:
  1935. continue
  1936. seen_indices.add(index)
  1937. plate_indices.append(index)
  1938. if not plate_indices:
  1939. # No plate metadata found
  1940. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1941. plate_indices.sort()
  1942. # Parse model_settings.config for plate names + object assignments
  1943. plate_names = {}
  1944. plate_object_ids: dict[int, list[str]] = {}
  1945. object_names_by_id: dict[str, str] = {}
  1946. if "Metadata/model_settings.config" in namelist:
  1947. try:
  1948. model_content = zf.read("Metadata/model_settings.config").decode()
  1949. model_root = ET.fromstring(model_content)
  1950. for obj_elem in model_root.findall(".//object"):
  1951. obj_id = obj_elem.get("id")
  1952. if not obj_id:
  1953. continue
  1954. name_meta = obj_elem.find("metadata[@key='name']")
  1955. obj_name = name_meta.get("value") if name_meta is not None else None
  1956. if obj_name:
  1957. object_names_by_id[obj_id] = obj_name
  1958. for plate_elem in model_root.findall(".//plate"):
  1959. plater_id = None
  1960. plater_name = None
  1961. for meta in plate_elem.findall("metadata"):
  1962. key = meta.get("key")
  1963. value = meta.get("value")
  1964. if key == "plater_id" and value:
  1965. try:
  1966. plater_id = int(value)
  1967. except ValueError:
  1968. pass # Ignore plate with non-numeric plater_id
  1969. elif key == "plater_name" and value:
  1970. plater_name = value.strip()
  1971. if plater_id is not None and plater_name:
  1972. plate_names[plater_id] = plater_name
  1973. if plater_id is not None:
  1974. for instance_elem in plate_elem.findall("model_instance"):
  1975. for inst_meta in instance_elem.findall("metadata"):
  1976. if inst_meta.get("key") == "object_id":
  1977. obj_id = inst_meta.get("value")
  1978. if not obj_id:
  1979. continue
  1980. plate_object_ids.setdefault(plater_id, [])
  1981. if obj_id not in plate_object_ids[plater_id]:
  1982. plate_object_ids[plater_id].append(obj_id)
  1983. except Exception:
  1984. pass # model_settings.config is optional; skip if missing or malformed
  1985. # Parse slice_info.config for plate metadata
  1986. plate_metadata = {}
  1987. if "Metadata/slice_info.config" in namelist:
  1988. content = zf.read("Metadata/slice_info.config").decode()
  1989. root = ET.fromstring(content)
  1990. for plate_elem in root.findall(".//plate"):
  1991. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1992. plate_index = None
  1993. for meta in plate_elem.findall("metadata"):
  1994. key = meta.get("key")
  1995. value = meta.get("value")
  1996. if key == "index" and value:
  1997. try:
  1998. plate_index = int(value)
  1999. except ValueError:
  2000. pass # Ignore plate with non-numeric index
  2001. elif key == "prediction" and value:
  2002. try:
  2003. plate_info["prediction"] = int(value)
  2004. except ValueError:
  2005. pass # Leave prediction as None if not a valid integer
  2006. elif key == "weight" and value:
  2007. try:
  2008. plate_info["weight"] = float(value)
  2009. except ValueError:
  2010. pass # Leave weight as None if not a valid number
  2011. # Get filaments used in this plate
  2012. for filament_elem in plate_elem.findall("filament"):
  2013. filament_id = filament_elem.get("id")
  2014. filament_type = filament_elem.get("type", "")
  2015. filament_color = filament_elem.get("color", "")
  2016. used_g = filament_elem.get("used_g", "0")
  2017. used_m = filament_elem.get("used_m", "0")
  2018. try:
  2019. used_grams = float(used_g)
  2020. except (ValueError, TypeError):
  2021. used_grams = 0
  2022. if used_grams > 0 and filament_id:
  2023. plate_info["filaments"].append(
  2024. {
  2025. "slot_id": int(filament_id),
  2026. "type": filament_type,
  2027. "color": filament_color,
  2028. "used_grams": round(used_grams, 1),
  2029. "used_meters": float(used_m) if used_m else 0,
  2030. }
  2031. )
  2032. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  2033. # Collect object names
  2034. for obj_elem in plate_elem.findall("object"):
  2035. obj_name = obj_elem.get("name")
  2036. if obj_name and obj_name not in plate_info["objects"]:
  2037. plate_info["objects"].append(obj_name)
  2038. # Set plate name
  2039. if plate_index is not None:
  2040. custom_name = plate_names.get(plate_index)
  2041. if custom_name:
  2042. plate_info["name"] = custom_name
  2043. elif plate_info["objects"]:
  2044. plate_info["name"] = plate_info["objects"][0]
  2045. plate_metadata[plate_index] = plate_info
  2046. # Parse plate_*.json for object lists when slice_info is missing
  2047. plate_json_objects: dict[int, list[str]] = {}
  2048. for name in namelist:
  2049. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  2050. if not match:
  2051. continue
  2052. try:
  2053. plate_index = int(match.group(1))
  2054. except ValueError:
  2055. continue
  2056. try:
  2057. payload = json.loads(zf.read(name).decode())
  2058. bbox_objects = payload.get("bbox_objects", [])
  2059. names: list[str] = []
  2060. for obj in bbox_objects:
  2061. obj_name = obj.get("name") if isinstance(obj, dict) else None
  2062. if obj_name and obj_name not in names:
  2063. names.append(obj_name)
  2064. if names:
  2065. plate_json_objects[plate_index] = names
  2066. except Exception:
  2067. continue
  2068. # Build plate list
  2069. for idx in plate_indices:
  2070. meta = plate_metadata.get(idx, {})
  2071. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  2072. objects = meta.get("objects", [])
  2073. if not objects:
  2074. objects = plate_json_objects.get(idx, [])
  2075. if not objects and plate_object_ids.get(idx):
  2076. objects = [
  2077. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  2078. ]
  2079. plate_name = meta.get("name")
  2080. if not plate_name:
  2081. plate_name = plate_names.get(idx)
  2082. if not plate_name and objects:
  2083. plate_name = objects[0]
  2084. plates.append(
  2085. {
  2086. "index": idx,
  2087. "name": plate_name,
  2088. "objects": objects,
  2089. "object_count": len(objects),
  2090. "has_thumbnail": has_thumbnail,
  2091. "thumbnail_url": f"/api/v1/library/files/{file_id}/plate-thumbnail/{idx}"
  2092. if has_thumbnail
  2093. else None,
  2094. "print_time_seconds": meta.get("prediction"),
  2095. "filament_used_grams": meta.get("weight"),
  2096. "filaments": meta.get("filaments", []),
  2097. }
  2098. )
  2099. except Exception as e:
  2100. logger.warning("Failed to parse plates from library file %s: %s", file_id, e)
  2101. return {
  2102. "file_id": file_id,
  2103. "filename": lib_file.filename,
  2104. "plates": plates,
  2105. "is_multi_plate": len(plates) > 1,
  2106. "embedded_printer": embedded_presets["printer"],
  2107. "embedded_process": embedded_presets["process"],
  2108. }
  2109. @router.get("/files/{file_id}/plate-thumbnail/{plate_index}")
  2110. async def get_library_file_plate_thumbnail(
  2111. file_id: int,
  2112. plate_index: int,
  2113. db: AsyncSession = Depends(get_db),
  2114. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2115. ):
  2116. """Get the thumbnail image for a specific plate from a library file."""
  2117. from starlette.responses import Response
  2118. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  2119. lib_file = result.scalar_one_or_none()
  2120. if not lib_file:
  2121. raise HTTPException(status_code=404, detail="File not found")
  2122. file_path = Path(app_settings.base_dir) / lib_file.file_path
  2123. if not file_path.exists():
  2124. raise HTTPException(status_code=404, detail="File not found on disk")
  2125. try:
  2126. with zipfile.ZipFile(file_path, "r") as zf:
  2127. thumb_path = f"Metadata/plate_{plate_index}.png"
  2128. if thumb_path in zf.namelist():
  2129. data = zf.read(thumb_path)
  2130. return Response(content=data, media_type="image/png")
  2131. except Exception:
  2132. pass # Archive unreadable or thumbnail missing; fall through to 404
  2133. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  2134. async def _try_preview_slice_filaments(
  2135. db: AsyncSession,
  2136. *,
  2137. kind: str,
  2138. source_id: int,
  2139. plate_id: int,
  2140. file_path: Path,
  2141. request_id: str | None = None,
  2142. bundle_id: str | None = None,
  2143. printer_name: str | None = None,
  2144. process_name: str | None = None,
  2145. filament_names: list[str] | None = None,
  2146. ) -> list[dict] | None:
  2147. """Run a preview slice via the user's configured sidecar. Same shape as
  2148. the matching helper in archives.py — see that module for rationale.
  2149. ``request_id``: when supplied, forwarded to the sidecar so the
  2150. SliceModal's inline spinner + toast can poll the matching progress
  2151. endpoint and show "Generating G-code (45%)" for the preview as well.
  2152. ``bundle_id`` / ``printer_name`` / ``process_name`` / ``filament_names``:
  2153. when all are supplied, the preview uses ``slice_with_bundle`` against
  2154. the named bundle's preset triplet so the preview's gram numbers reflect
  2155. the same profiles the real print will use. Partial context falls back
  2156. to the embedded-settings path so a half-completed Bundle-tier selection
  2157. in the modal doesn't error out.
  2158. """
  2159. from backend.app.api.routes.settings import get_setting
  2160. from backend.app.services.slice_preview import get_preview_filaments
  2161. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  2162. if preferred == "orcaslicer":
  2163. configured = await get_setting(db, "orcaslicer_api_url")
  2164. api_url = (configured or app_settings.slicer_api_url).strip()
  2165. elif preferred == "bambu_studio":
  2166. configured = await get_setting(db, "bambu_studio_api_url")
  2167. api_url = (configured or app_settings.bambu_studio_api_url).strip()
  2168. else:
  2169. return None
  2170. if not api_url:
  2171. return None
  2172. try:
  2173. file_bytes = file_path.read_bytes()
  2174. except OSError:
  2175. return None
  2176. return await get_preview_filaments(
  2177. kind=kind,
  2178. source_id=source_id,
  2179. plate_id=plate_id,
  2180. file_bytes=file_bytes,
  2181. file_name=file_path.name,
  2182. api_url=api_url,
  2183. request_id=request_id,
  2184. bundle_id=bundle_id,
  2185. printer_name=printer_name,
  2186. process_name=process_name,
  2187. filament_names=filament_names,
  2188. )
  2189. @router.get("/files/{file_id}/filament-requirements")
  2190. async def get_library_file_filament_requirements(
  2191. file_id: int,
  2192. plate_id: int | None = None,
  2193. request_id: str | None = None,
  2194. bundle_id: str | None = None,
  2195. printer_name: str | None = None,
  2196. process_name: str | None = None,
  2197. filament_names: str | None = None,
  2198. db: AsyncSession = Depends(get_db),
  2199. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  2200. ):
  2201. """Get filament requirements from a library file.
  2202. Parses the 3MF file to extract filament slot IDs, types, colors, and usage.
  2203. This enables AMS slot assignment when printing from the file manager.
  2204. Args:
  2205. file_id: The library file ID
  2206. plate_id: Optional plate index to get filaments for a specific plate
  2207. bundle_id / printer_name / process_name / filament_names: Optional
  2208. bundle context. When all four are supplied, the preview slice
  2209. (run for unsliced project files) uses ``slice_with_bundle``
  2210. against the named preset triplet instead of the embedded-
  2211. settings fallback. ``filament_names`` is comma- or semicolon-
  2212. separated to mirror the slice route's multi-color form.
  2213. """
  2214. import defusedxml.ElementTree as ET
  2215. # Get the library file
  2216. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  2217. lib_file = result.scalar_one_or_none()
  2218. if not lib_file:
  2219. raise HTTPException(status_code=404, detail="File not found")
  2220. # Get the full file path
  2221. file_path = Path(app_settings.base_dir) / lib_file.file_path
  2222. if not file_path.exists():
  2223. raise HTTPException(status_code=404, detail="File not found on disk")
  2224. # Only 3MF files have parseable filament info
  2225. if not lib_file.filename.lower().endswith(".3mf"):
  2226. return {"file_id": file_id, "filename": lib_file.filename, "plate_id": plate_id, "filaments": []}
  2227. filaments = []
  2228. try:
  2229. with zipfile.ZipFile(file_path, "r") as zf:
  2230. # Parse slice_info.config for filament requirements
  2231. if "Metadata/slice_info.config" in zf.namelist():
  2232. content = zf.read("Metadata/slice_info.config").decode()
  2233. root = ET.fromstring(content)
  2234. if plate_id is not None:
  2235. # Find filaments for specific plate
  2236. for plate_elem in root.findall(".//plate"):
  2237. # Check if this is the requested plate
  2238. plate_index = None
  2239. for meta in plate_elem.findall("metadata"):
  2240. if meta.get("key") == "index":
  2241. try:
  2242. plate_index = int(meta.get("value", ""))
  2243. except ValueError:
  2244. pass # Skip plate with non-numeric index value
  2245. break
  2246. if plate_index == plate_id:
  2247. # Extract filaments from this plate
  2248. for filament_elem in plate_elem.findall("filament"):
  2249. filament_id = filament_elem.get("id")
  2250. filament_type = filament_elem.get("type", "")
  2251. filament_color = filament_elem.get("color", "")
  2252. used_g = filament_elem.get("used_g", "0")
  2253. used_m = filament_elem.get("used_m", "0")
  2254. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2255. try:
  2256. used_grams = float(used_g)
  2257. except (ValueError, TypeError):
  2258. used_grams = 0
  2259. if used_grams > 0 and filament_id:
  2260. filaments.append(
  2261. {
  2262. "slot_id": int(filament_id),
  2263. "type": filament_type,
  2264. "color": filament_color,
  2265. "used_grams": round(used_grams, 1),
  2266. "used_meters": float(used_m) if used_m else 0,
  2267. "tray_info_idx": tray_info_idx,
  2268. # Sliced output already pre-filtered by used_g>0,
  2269. # so every entry that survives is in fact used by
  2270. # this plate. Print-dispatch consumers ignore the
  2271. # flag; SliceModal uses it to enable/disable rows.
  2272. "used_in_plate": True,
  2273. }
  2274. )
  2275. break
  2276. else:
  2277. # Extract all filaments with used_g > 0 (for single-plate or overview)
  2278. for filament_elem in root.findall(".//filament"):
  2279. filament_id = filament_elem.get("id")
  2280. filament_type = filament_elem.get("type", "")
  2281. filament_color = filament_elem.get("color", "")
  2282. used_g = filament_elem.get("used_g", "0")
  2283. used_m = filament_elem.get("used_m", "0")
  2284. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2285. try:
  2286. used_grams = float(used_g)
  2287. except (ValueError, TypeError):
  2288. used_grams = 0
  2289. if used_grams > 0 and filament_id:
  2290. filaments.append(
  2291. {
  2292. "slot_id": int(filament_id),
  2293. "type": filament_type,
  2294. "color": filament_color,
  2295. "used_grams": round(used_grams, 1),
  2296. "used_meters": float(used_m) if used_m else 0,
  2297. "tray_info_idx": tray_info_idx,
  2298. "used_in_plate": True,
  2299. }
  2300. )
  2301. # Unsliced project files: slice_info had no per-plate data.
  2302. # Return the FULL project_settings.config AMS slot list so
  2303. # the slicer CLI receives a profile for every project slot
  2304. # (otherwise it silently fills the gap from embedded
  2305. # defaults — surfaces as "I picked white but the print has
  2306. # grey" because the source's grey support filament leaks
  2307. # into the output). Use the preview slice to mark which
  2308. # slots the picked plate actually consumes; the SliceModal
  2309. # disables the unused rows so the user only interacts with
  2310. # the dropdowns that matter, while the backend still has
  2311. # the complete list to pass to the CLI.
  2312. if not filaments:
  2313. project_filaments = extract_project_filaments_from_3mf(zf)
  2314. used_slot_ids: set[int] = set()
  2315. if project_filaments and plate_id is not None:
  2316. # Bundle context flows through optional query params so
  2317. # callers without a Bundle-tier selection (the common
  2318. # case) hit the same path as before.
  2319. parsed_filament_names: list[str] | None = None
  2320. if filament_names:
  2321. parsed_filament_names = [
  2322. n.strip() for n in filament_names.replace(";", ",").split(",") if n.strip()
  2323. ] or None
  2324. preview = await _try_preview_slice_filaments(
  2325. db,
  2326. kind="library_file",
  2327. source_id=file_id,
  2328. plate_id=plate_id,
  2329. file_path=file_path,
  2330. request_id=request_id,
  2331. bundle_id=bundle_id,
  2332. printer_name=printer_name,
  2333. process_name=process_name,
  2334. filament_names=parsed_filament_names,
  2335. )
  2336. if preview is not None:
  2337. used_slot_ids = {f["slot_id"] for f in preview}
  2338. # Default to "every slot is used" when preview-slice
  2339. # didn't produce data: better to over-enable dropdowns
  2340. # than under-enable and have the user unable to pick a
  2341. # filament the plate actually uses.
  2342. fallback_all_used = not used_slot_ids
  2343. for f in project_filaments:
  2344. f["used_in_plate"] = fallback_all_used or f["slot_id"] in used_slot_ids
  2345. filaments = project_filaments
  2346. # Sort by slot ID
  2347. filaments.sort(key=lambda x: x["slot_id"])
  2348. # Enrich with nozzle mapping for dual-nozzle printers
  2349. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  2350. if nozzle_mapping:
  2351. for filament in filaments:
  2352. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  2353. except Exception as e:
  2354. logger.warning("Failed to parse filament requirements from library file %s: %s", file_id, e)
  2355. return {
  2356. "file_id": file_id,
  2357. "filename": lib_file.filename,
  2358. "plate_id": plate_id,
  2359. "filaments": filaments,
  2360. }
  2361. _STRIPPABLE_3MF_CONFIGS = frozenset(
  2362. {
  2363. # Settings dump used by --load-settings validation; the CLI tries to
  2364. # match its sentinel values (`prime_tower_brim_width: -1`, empty
  2365. # arrays) against the supplied profile and rejects out-of-range.
  2366. "Metadata/project_settings.config",
  2367. # Per-object settings overrides referencing the source plate's
  2368. # filament IDs / printer IDs. When the user picks a different
  2369. # printer / filament triplet, the IDs no longer resolve and the
  2370. # CLI exits non-zero on input validation.
  2371. "Metadata/model_settings.config",
  2372. # Slicer-version + plate-config + filament-mapping snapshot from
  2373. # the original slice. Includes the original printer model and
  2374. # filament references; mismatches against `--load-settings`
  2375. # consistently surfaced as `Slicer CLI failed (500)` for every
  2376. # 3MF in production. Removing it lets the CLI build a fresh slice
  2377. # plan from the supplied profile triplet.
  2378. "Metadata/slice_info.config",
  2379. # Multi-part / split-mesh metadata referencing object IDs from the
  2380. # original slice. Strip for the same reason — preserves the geometry
  2381. # in `3D/3dmodel.model` while dropping the orphan references.
  2382. "Metadata/cut_information.xml",
  2383. }
  2384. )
  2385. def _strip_3mf_embedded_settings(zip_bytes: bytes) -> bytes:
  2386. """Remove embedded slicer-config metadata from a 3MF.
  2387. Bambuddy supplies the slicer profile triplet via the sidecar's
  2388. ``--load-settings`` path; the 3MF's embedded settings would otherwise be
  2389. validated by the CLI first and can fail with sentinel-value range
  2390. checks (`prime_tower_brim_width: -1 not in range`, etc.) regardless of
  2391. what we pass via ``--load-settings``. Stripping the embedded configs
  2392. forces the CLI to use the supplied profiles only. Geometry
  2393. (``3D/3dmodel.model``), thumbnails, color, and multi-part data inside
  2394. the 3MF are preserved.
  2395. The set of strippable filenames is centralised in
  2396. ``_STRIPPABLE_3MF_CONFIGS`` — see that constant for the per-file
  2397. rationale. Project-settings alone wasn't enough: real-world Bambu
  2398. Studio 3MFs cross-reference printer / filament IDs from the other
  2399. metadata configs, and any single leftover triggered the validation
  2400. failure that made every profile-driven slice fall back to embedded
  2401. settings.
  2402. """
  2403. from io import BytesIO
  2404. src = BytesIO(zip_bytes)
  2405. dst = BytesIO()
  2406. with zipfile.ZipFile(src, "r") as zin, zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as zout:
  2407. for item in zin.infolist():
  2408. if item.filename in _STRIPPABLE_3MF_CONFIGS:
  2409. continue
  2410. zout.writestr(item, zin.read(item.filename))
  2411. return dst.getvalue()
  2412. # Keys in ``Metadata/project_settings.config`` that BambuStudio writes ``"-1"``
  2413. # to when the user wants the value inherited from the parent process preset.
  2414. # The CLI's ``StaticPrintConfig`` validator runs against the embedded settings
  2415. # *before* ``--load-settings`` overrides apply, so a sentinel ``"-1"`` trips
  2416. # the field's lower-bound range check and the CLI exits non-zero before our
  2417. # profile triplet is ever consulted (#1201 — MakerWorld P2S models).
  2418. #
  2419. # Allowlisted (rather than "strip every '-1' value") because some fields
  2420. # legitimately accept negative numbers (z_offset, translation values, etc.)
  2421. # and a blanket strip would silently corrupt those.
  2422. #
  2423. # Add new entries here as more reports surface — the slicer's error message
  2424. # names the offending field directly (`<field>: -1 not in range [...]`).
  2425. _PROJECT_SETTINGS_SENTINEL_KEYS = frozenset(
  2426. {
  2427. # Reported in #1201 (MakerWorld P2S 3MFs).
  2428. "raft_first_layer_expansion",
  2429. "tree_support_wall_count",
  2430. # Cited in the strip-experiment comment block above as a known sentinel
  2431. # case from earlier reports.
  2432. "prime_tower_brim_width",
  2433. }
  2434. )
  2435. def _sanitize_project_settings_sentinels(zip_bytes: bytes) -> bytes:
  2436. """Strip ``"-1"`` inherit-from-parent sentinels from the 3MF's
  2437. ``Metadata/project_settings.config`` so the slicer CLI's range validator
  2438. accepts the file (#1201).
  2439. Removes only allowlisted keys (see ``_PROJECT_SETTINGS_SENTINEL_KEYS``)
  2440. when their value is exactly ``"-1"``. The rest of the config — and every
  2441. other entry in the zip — is preserved byte-for-byte. Unlike the earlier
  2442. full-strip experiment (see ``_strip_3mf_embedded_settings`` and the
  2443. cautionary comment in ``_run_slicer_with_fallback``) this leaves
  2444. ``StaticPrintConfig`` initialisation intact: the file is still present,
  2445. still parses, and the slicer falls back to the supplied
  2446. ``--load-settings`` value for the removed key.
  2447. Returns the original bytes unchanged when no sanitisation is needed
  2448. (input isn't a valid zip, no ``project_settings.config``, no allowlisted
  2449. sentinels present, or any other parse failure) so the caller can pass
  2450. the result on without further checks.
  2451. """
  2452. from io import BytesIO
  2453. try:
  2454. with zipfile.ZipFile(BytesIO(zip_bytes), "r") as zin:
  2455. if "Metadata/project_settings.config" not in zin.namelist():
  2456. return zip_bytes
  2457. try:
  2458. config = json.loads(zin.read("Metadata/project_settings.config").decode("utf-8"))
  2459. except (json.JSONDecodeError, UnicodeDecodeError):
  2460. return zip_bytes
  2461. if not isinstance(config, dict):
  2462. return zip_bytes
  2463. removed = [key for key in _PROJECT_SETTINGS_SENTINEL_KEYS if config.get(key) == "-1"]
  2464. if not removed:
  2465. return zip_bytes
  2466. for key in removed:
  2467. config.pop(key, None)
  2468. patched = json.dumps(config)
  2469. logger.info(
  2470. "3MF sanitiser: removed sentinel '-1' for keys %s — slicer will use --load-settings defaults",
  2471. sorted(removed),
  2472. )
  2473. dst = BytesIO()
  2474. with zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as zout:
  2475. for item in zin.infolist():
  2476. if item.filename == "Metadata/project_settings.config":
  2477. zout.writestr(item, patched)
  2478. else:
  2479. zout.writestr(item, zin.read(item.filename))
  2480. return dst.getvalue()
  2481. except (zipfile.BadZipFile, OSError):
  2482. return zip_bytes
  2483. def _patch_process_bed_type(process_json: str, bed_type: str) -> str:
  2484. """Overwrite ``curr_bed_type`` in a process-profile JSON before forwarding
  2485. to the slicer sidecar.
  2486. The slicer CLI reads the build-plate type from the process profile's
  2487. ``curr_bed_type`` field. When the user picks a non-default plate in the
  2488. SliceModal (#1337), we patch the resolved JSON in place rather than
  2489. asking them to clone the preset just to switch a plate. Returns the
  2490. original string unchanged when the JSON can't be parsed or isn't a
  2491. dict — the slicer will then run with whatever the preset originally
  2492. specified, which is the safe fall-back path.
  2493. """
  2494. try:
  2495. profile = json.loads(process_json)
  2496. except json.JSONDecodeError:
  2497. logger.warning("Bed-type override skipped: process profile is not valid JSON")
  2498. return process_json
  2499. if not isinstance(profile, dict):
  2500. return process_json
  2501. profile["curr_bed_type"] = bed_type
  2502. return json.dumps(profile)
  2503. async def _run_slicer_with_fallback(
  2504. db: AsyncSession,
  2505. *,
  2506. model_bytes: bytes,
  2507. model_filename: str,
  2508. request: SliceRequest,
  2509. current_user_id: int | None = None,
  2510. job_id: int | None = None,
  2511. ):
  2512. """Validate presets, dispatch to the right sidecar, run the slicer with
  2513. the auto-fallback for 3MF inputs whose `--load-settings` path crashes the
  2514. CLI. Returns ``(SliceResult, used_embedded_settings: bool)``. Raises
  2515. ``HTTPException`` for any caller-facing error.
  2516. `current_user_id` is needed to resolve **cloud** presets — the cloud token
  2517. is per-user when auth is enabled. For the legacy / local-only path it can
  2518. be left ``None``.
  2519. `job_id`: when set, a request_id is generated and a parallel poller
  2520. pushes the sidecar's --pipe-fed progress events onto
  2521. ``slice_dispatch.set_progress(job_id, ...)`` so the UI's persistent
  2522. toast can show "Generating G-code (75%)" instead of just elapsed
  2523. time. Pass None for synchronous routes that aren't tracked by the
  2524. dispatcher.
  2525. """
  2526. from backend.app.api.routes.settings import get_setting
  2527. from backend.app.services.preset_resolver import resolve_preset_ref
  2528. from backend.app.services.slicer_api import (
  2529. SlicerApiServerError,
  2530. SlicerApiService,
  2531. SlicerApiUnavailableError,
  2532. SlicerInputError,
  2533. )
  2534. # Bundle dispatch path: when SliceRequest.bundle is set, the schema
  2535. # validator short-circuited the presets-required check, so the
  2536. # PresetRef fields may all be None. Skip resolve_preset_ref entirely
  2537. # — the sidecar will materialise the per-category JSONs from the
  2538. # bundle's extracted directory at slice time.
  2539. use_bundle = request.bundle is not None
  2540. user: User | None = None
  2541. presets: dict[str, str] = {}
  2542. filament_jsons: list[str] = []
  2543. if not use_bundle:
  2544. # Resolve each slot via the source-aware resolver. The schema
  2545. # validator has already normalised legacy `*_preset_id: int`
  2546. # fields into `PresetRef(source='local', id=str(int))`, so all
  2547. # three are guaranteed non-None here.
  2548. if current_user_id is not None:
  2549. user = await db.get(User, current_user_id)
  2550. refs = {
  2551. "printer": request.printer_preset,
  2552. "process": request.process_preset,
  2553. }
  2554. for slot, ref in refs.items():
  2555. assert ref is not None, "schema validator guarantees PresetRef is set"
  2556. presets[slot] = await resolve_preset_ref(db, user, ref, slot)
  2557. # Multi-color: resolve each filament slot in plate order. The schema
  2558. # validator backfilled `filament_presets` from the legacy `filament_preset`
  2559. # field for single-color callers, so this list is always non-empty.
  2560. for ref in request.filament_presets:
  2561. assert ref is not None, "schema validator guarantees filament list is non-None"
  2562. filament_jsons.append(await resolve_preset_ref(db, user, ref, "filament"))
  2563. # Bed-type override (#1337): patch curr_bed_type onto the resolved
  2564. # process JSON so the slicer's StaticPrintConfig pass picks up the
  2565. # user's pick instead of whatever the process preset defaults to.
  2566. # Without this, slicing an STL of ABS onto a process preset whose
  2567. # default is "Cool Plate" fails with "Plate 1: Cool Plate does not
  2568. # support filament 1" — the reporter's exact scenario. Only applies
  2569. # to the resolved-preset path; bundle mode would need a sidecar-side
  2570. # mechanism to patch presets it materialises from disk.
  2571. if request.bed_type:
  2572. presets["process"] = _patch_process_bed_type(presets["process"], request.bed_type)
  2573. # Slicer routing — pick the sidecar URL by preferred_slicer.
  2574. # The per-install URL setting (Settings UI → Slicer card) wins; an
  2575. # empty value falls back to the SLICER_API_URL / BAMBU_STUDIO_API_URL
  2576. # env defaults defined in core/config.py.
  2577. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  2578. if preferred == "orcaslicer":
  2579. configured = await get_setting(db, "orcaslicer_api_url")
  2580. api_url = (configured or app_settings.slicer_api_url).strip()
  2581. elif preferred == "bambu_studio":
  2582. configured = await get_setting(db, "bambu_studio_api_url")
  2583. api_url = (configured or app_settings.bambu_studio_api_url).strip()
  2584. else:
  2585. raise HTTPException(
  2586. status_code=400,
  2587. detail=f"Unknown preferred_slicer setting: '{preferred}'. Expected 'orcaslicer' or 'bambu_studio'.",
  2588. )
  2589. # Note: an earlier version of this code stripped Metadata/project_settings.
  2590. # config + model_settings.config + slice_info.config + cut_information.xml
  2591. # before forwarding the 3MF, the theory being that --load-settings would
  2592. # then take precedence cleanly. That theory was wrong: model_settings.
  2593. # config carries the plate definitions the CLI needs to map `--slice N`
  2594. # to a real plate, and slice_info / project_settings supply baseline
  2595. # config the CLI's StaticPrintConfig pass needs at all. Stripping ANY
  2596. # of them caused the CLI to silently exit immediately after
  2597. # "Initializing StaticPrintConfigs" — exit code 0, no result.json, no
  2598. # stderr — which Node's child_process treated as failure and Bambuddy
  2599. # then masked by falling back to slice_without_profiles using the
  2600. # un-stripped bytes (and the source's embedded printer). Net effect:
  2601. # every 3MF slice with profiles silently produced wrong-printer output.
  2602. # Forwarding the original bytes lets --load-settings override the
  2603. # specific fields the user changed (printer/process/filament) while
  2604. # the embedded plate / model definitions remain intact.
  2605. is_3mf = model_filename.lower().endswith(".3mf")
  2606. primary_bytes = model_bytes
  2607. if is_3mf:
  2608. # Strip "-1" inherit-from-parent sentinels from
  2609. # Metadata/project_settings.config so the CLI's StaticPrintConfig
  2610. # range validator accepts the file (#1201). Surgical — keeps the
  2611. # config present, just removes the offending keys; the supplied
  2612. # --load-settings (and the fallback's embedded values for keys we
  2613. # didn't touch) still drive the slice.
  2614. primary_bytes = _sanitize_project_settings_sentinels(primary_bytes)
  2615. used_embedded_settings = False
  2616. service = SlicerApiService(api_url)
  2617. # When this slice is dispatcher-tracked, generate a request_id so
  2618. # the sidecar publishes progress under it, and wire a callback that
  2619. # forwards each frame onto SliceDispatchService.set_progress for the
  2620. # status-poll endpoint to surface to the UI.
  2621. progress_request_id: str | None = None
  2622. progress_callback = None
  2623. if job_id is not None:
  2624. from uuid import uuid4
  2625. from backend.app.services.slice_dispatch import slice_dispatch as _dispatch
  2626. progress_request_id = str(uuid4())
  2627. def _on_progress(snapshot: dict) -> None:
  2628. _dispatch.set_progress(job_id, snapshot)
  2629. progress_callback = _on_progress
  2630. try:
  2631. try:
  2632. if use_bundle:
  2633. # Bundle dispatch: sidecar materialises the JSON triplet
  2634. # from the stored .bbscfg by name. ``request.bundle`` is
  2635. # guaranteed non-None here by the use_bundle branch above.
  2636. assert request.bundle is not None
  2637. result = await service.slice_with_bundle(
  2638. model_bytes=primary_bytes,
  2639. model_filename=model_filename,
  2640. bundle_id=request.bundle.bundle_id,
  2641. printer_name=request.bundle.printer_name,
  2642. process_name=request.bundle.process_name,
  2643. filament_names=request.bundle.filament_names,
  2644. plate=request.plate,
  2645. export_3mf=request.export_3mf,
  2646. bed_type=request.bed_type,
  2647. request_id=progress_request_id,
  2648. on_progress=progress_callback,
  2649. )
  2650. else:
  2651. result = await service.slice_with_profiles(
  2652. model_bytes=primary_bytes,
  2653. model_filename=model_filename,
  2654. printer_profile_json=presets["printer"],
  2655. process_profile_json=presets["process"],
  2656. filament_profile_jsons=filament_jsons,
  2657. plate=request.plate,
  2658. export_3mf=request.export_3mf,
  2659. request_id=progress_request_id,
  2660. on_progress=progress_callback,
  2661. )
  2662. except SlicerApiServerError as exc:
  2663. if not is_3mf:
  2664. raise
  2665. logger.warning(
  2666. "Slicer CLI rejected --load-settings for %s (%s); retrying with embedded settings",
  2667. model_filename,
  2668. exc,
  2669. )
  2670. # Forward the same request_id + callback so the toast's live
  2671. # progress keeps updating across the fallback retry instead
  2672. # of going blank for the rest of the slice. Use the sanitised
  2673. # bytes — the embedded-settings path also reads the same
  2674. # project_settings.config and the same range validator runs
  2675. # there too, so without sanitisation the fallback would die
  2676. # on the same sentinel error (#1201). Same fallback applies
  2677. # to the bundle path: if the resolved triplet crashes the CLI,
  2678. # embedded settings give the user *something* rather than a
  2679. # hard failure (the SliceModal flags the difference via
  2680. # used_embedded_settings).
  2681. result = await service.slice_without_profiles(
  2682. model_bytes=primary_bytes,
  2683. model_filename=model_filename,
  2684. plate=request.plate,
  2685. export_3mf=request.export_3mf,
  2686. request_id=progress_request_id,
  2687. on_progress=progress_callback,
  2688. )
  2689. used_embedded_settings = True
  2690. except SlicerInputError as exc:
  2691. raise HTTPException(status_code=400, detail=str(exc)) from exc
  2692. except SlicerApiServerError as exc:
  2693. raise HTTPException(status_code=502, detail=str(exc)) from exc
  2694. except SlicerApiUnavailableError as exc:
  2695. raise HTTPException(status_code=502, detail=str(exc)) from exc
  2696. finally:
  2697. await service.close()
  2698. return result, used_embedded_settings
  2699. async def slice_and_persist(
  2700. db: AsyncSession,
  2701. *,
  2702. model_bytes: bytes,
  2703. model_filename: str,
  2704. folder_id: int | None,
  2705. extra_metadata: dict | None,
  2706. request: SliceRequest,
  2707. current_user_id: int | None,
  2708. job_id: int | None = None,
  2709. ) -> SliceResponse:
  2710. """Slice a model and save the result as a new ``LibraryFile`` in
  2711. ``folder_id`` (same folder as the source by convention).
  2712. Always exports as ``.gcode.3mf`` so the existing library thumbnail
  2713. pipeline works on the new file. Plain ``.gcode`` would have no
  2714. embedded thumbnail to extract.
  2715. """
  2716. from backend.app.services.archive import ThreeMFParser
  2717. library_request = request.model_copy(update={"export_3mf": True})
  2718. result, used_embedded_settings = await _run_slicer_with_fallback(
  2719. db,
  2720. model_bytes=model_bytes,
  2721. model_filename=model_filename,
  2722. request=library_request,
  2723. current_user_id=current_user_id,
  2724. job_id=job_id,
  2725. )
  2726. base_name = model_filename.rsplit(".", 1)[0]
  2727. out_filename = f"{base_name}.gcode.3mf"
  2728. unique_name = f"{uuid.uuid4().hex}.gcode.3mf"
  2729. out_path = get_library_files_dir() / unique_name
  2730. out_path.write_bytes(result.content)
  2731. # Extract thumbnail from the produced 3MF so the library card shows a
  2732. # preview. Failures here aren't fatal — the file is still useful
  2733. # without a thumbnail.
  2734. thumbnail_relative: str | None = None
  2735. parsed_metadata: dict = {}
  2736. try:
  2737. parser = ThreeMFParser(str(out_path))
  2738. parsed = parser.parse()
  2739. thumb_data = parsed.get("_thumbnail_data")
  2740. thumb_ext = parsed.get("_thumbnail_ext", ".png")
  2741. if thumb_data:
  2742. thumb_filename = f"{uuid.uuid4().hex}{thumb_ext}"
  2743. thumb_path = get_library_thumbnails_dir() / thumb_filename
  2744. thumb_path.write_bytes(thumb_data)
  2745. thumbnail_relative = to_relative_path(thumb_path)
  2746. cleaned = _clean_3mf_metadata(parsed)
  2747. if isinstance(cleaned, dict):
  2748. parsed_metadata = cleaned
  2749. except Exception as exc:
  2750. logger.warning("Failed to parse sliced 3MF metadata for %s: %s", out_filename, exc)
  2751. # The parsed 3MF metadata carries a `print_name` lifted from the source
  2752. # file's embedded settings (BambuStudio always sets this; OrcaSlicer
  2753. # often leaves it blank). The FileManager listing prefers print_name
  2754. # over filename for display, which makes a sliced row indistinguishable
  2755. # from its source. Drop print_name so the listing falls back to the
  2756. # actual filename — which already ends in ".gcode.3mf" and self-describes
  2757. # as the sliced output.
  2758. metadata: dict = {k: v for k, v in parsed_metadata.items() if k != "print_name"}
  2759. metadata.update(
  2760. {
  2761. "print_time_seconds": result.print_time_seconds,
  2762. "filament_used_g": result.filament_used_g,
  2763. "filament_used_mm": result.filament_used_mm,
  2764. }
  2765. )
  2766. if used_embedded_settings:
  2767. metadata["used_embedded_settings"] = True
  2768. if extra_metadata:
  2769. metadata.update(extra_metadata)
  2770. new_file = LibraryFile(
  2771. folder_id=folder_id,
  2772. filename=out_filename,
  2773. file_path=to_relative_path(out_path),
  2774. # Sliced output is a `.gcode.3mf` zip with embedded G-code, but the
  2775. # user-facing meaning is "ready-to-print G-code" — using "gcode"
  2776. # gives it the same badge as plain .gcode files and distinguishes
  2777. # it from un-sliced `.3mf` source models.
  2778. file_type="gcode",
  2779. file_size=len(result.content),
  2780. file_hash=hashlib.sha256(result.content).hexdigest(),
  2781. thumbnail_path=thumbnail_relative,
  2782. file_metadata=metadata,
  2783. source_type="sliced",
  2784. created_by_id=current_user_id,
  2785. )
  2786. db.add(new_file)
  2787. await db.commit()
  2788. # No refresh: expire_on_commit=False keeps id/filename accessible, and
  2789. # refreshing here flakes under pytest-xdist when teardown of a sibling
  2790. # test races the SELECT.
  2791. return SliceResponse(
  2792. library_file_id=new_file.id,
  2793. name=new_file.filename,
  2794. print_time_seconds=result.print_time_seconds,
  2795. filament_used_g=result.filament_used_g,
  2796. filament_used_mm=result.filament_used_mm,
  2797. used_embedded_settings=used_embedded_settings,
  2798. )
  2799. async def slice_and_persist_as_archive(
  2800. db: AsyncSession,
  2801. *,
  2802. model_bytes: bytes,
  2803. model_filename: str,
  2804. request: SliceRequest,
  2805. source_archive, # PrintArchive — hint kept loose to avoid cyclic import
  2806. current_user_id: int | None,
  2807. job_id: int | None = None,
  2808. ):
  2809. """Slice a model and save the result as a new ``PrintArchive`` row,
  2810. inheriting printer / project / makerworld metadata from the source
  2811. archive. Always exports as a `.gcode.3mf` so the existing thumbnail
  2812. and plates infrastructure (which expects a zip-shaped 3MF) works on
  2813. the new archive. Returns ``SliceArchiveResponse``.
  2814. """
  2815. from backend.app.models.archive import PrintArchive
  2816. from backend.app.schemas.slicer import SliceArchiveResponse
  2817. from backend.app.services.archive import ThreeMFParser
  2818. # Archive sinks always want a 3MF. The library route still respects the
  2819. # caller's `export_3mf` flag; here we override.
  2820. archive_request = request.model_copy(update={"export_3mf": True})
  2821. result, used_embedded_settings = await _run_slicer_with_fallback(
  2822. db,
  2823. model_bytes=model_bytes,
  2824. model_filename=model_filename,
  2825. request=archive_request,
  2826. job_id=job_id,
  2827. current_user_id=current_user_id,
  2828. )
  2829. base_name = model_filename.rsplit(".", 1)[0]
  2830. out_filename = f"{base_name}.gcode.3mf"
  2831. timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
  2832. printer_folder = str(source_archive.printer_id) if source_archive.printer_id is not None else "unassigned"
  2833. archive_subdir = f"{timestamp}_{base_name}_sliced"
  2834. archive_dir = app_settings.archive_dir / printer_folder / archive_subdir
  2835. archive_dir.mkdir(parents=True, exist_ok=True)
  2836. out_path = archive_dir / out_filename
  2837. out_path.write_bytes(result.content)
  2838. # Extract a thumbnail from the produced 3MF so the new archive card has
  2839. # a preview. The 3MF parser pulls Metadata/plate_*.png; failures here
  2840. # shouldn't fail the whole slice — the archive row is still useful
  2841. # without a thumbnail.
  2842. thumbnail_path: str | None = None
  2843. parsed_metadata: dict = {}
  2844. try:
  2845. parser = ThreeMFParser(str(out_path))
  2846. parsed = parser.parse()
  2847. thumb_data = parsed.get("_thumbnail_data")
  2848. thumb_ext = parsed.get("_thumbnail_ext", ".png")
  2849. if thumb_data:
  2850. thumb_dest = archive_dir / f"thumbnail{thumb_ext}"
  2851. thumb_dest.write_bytes(thumb_data)
  2852. thumbnail_path = str(thumb_dest.relative_to(app_settings.base_dir))
  2853. parsed_metadata = {k: v for k, v in parsed.items() if not k.startswith("_")}
  2854. except Exception as exc:
  2855. logger.warning("Failed to parse sliced 3MF metadata for %s: %s", out_filename, exc)
  2856. metadata = dict(source_archive.extra_data) if source_archive.extra_data else {}
  2857. metadata.update(parsed_metadata)
  2858. metadata.update(
  2859. {
  2860. "sliced_from_archive_id": source_archive.id,
  2861. "print_time_seconds": result.print_time_seconds,
  2862. "filament_used_g": result.filament_used_g,
  2863. "filament_used_mm": result.filament_used_mm,
  2864. }
  2865. )
  2866. if used_embedded_settings:
  2867. metadata["used_embedded_settings"] = True
  2868. # Prefer the actually-used filament list from the sliced output's
  2869. # slice_info.config (parsed_metadata.filament_* — only entries with
  2870. # used_g > 0). Falling back to the source_archive's list would
  2871. # surface every project-wide AMS slot, including ones the picked
  2872. # plate doesn't use (16+ swatches on the card for a 2-color print).
  2873. new_filament_type = parsed_metadata.get("filament_type") or source_archive.filament_type
  2874. new_filament_color = parsed_metadata.get("filament_color") or source_archive.filament_color
  2875. new_archive = PrintArchive(
  2876. printer_id=source_archive.printer_id,
  2877. project_id=source_archive.project_id,
  2878. filename=out_filename,
  2879. file_path=str(out_path.relative_to(app_settings.base_dir)),
  2880. file_size=len(result.content),
  2881. content_hash=hashlib.sha256(result.content).hexdigest(),
  2882. thumbnail_path=thumbnail_path,
  2883. # Inherit identity from the source archive so the new entry shows
  2884. # up alongside its sibling in the archives list.
  2885. print_name=(source_archive.print_name or base_name) + " (re-sliced)",
  2886. print_time_seconds=result.print_time_seconds,
  2887. filament_used_grams=result.filament_used_g or None,
  2888. filament_type=new_filament_type,
  2889. filament_color=new_filament_color,
  2890. layer_height=source_archive.layer_height,
  2891. nozzle_diameter=source_archive.nozzle_diameter,
  2892. sliced_for_model=source_archive.sliced_for_model,
  2893. makerworld_url=source_archive.makerworld_url,
  2894. designer=source_archive.designer,
  2895. # Sliced-but-not-printed: keep status default ("completed") so it
  2896. # surfaces in the normal archives list, but do not stamp
  2897. # started/completed_at — the user hasn't actually printed it yet.
  2898. extra_data=metadata,
  2899. created_by_id=current_user_id,
  2900. )
  2901. db.add(new_archive)
  2902. await db.commit()
  2903. await db.refresh(new_archive)
  2904. return SliceArchiveResponse(
  2905. archive_id=new_archive.id,
  2906. name=new_archive.print_name or out_filename,
  2907. print_time_seconds=result.print_time_seconds,
  2908. filament_used_g=result.filament_used_g,
  2909. filament_used_mm=result.filament_used_mm,
  2910. used_embedded_settings=used_embedded_settings,
  2911. )
  2912. @router.post("/files/{file_id}/slice", status_code=202)
  2913. async def slice_library_file(
  2914. file_id: int,
  2915. request: SliceRequest,
  2916. db: AsyncSession = Depends(get_db),
  2917. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  2918. api_key_cloud_owner: User | None = Depends(resolve_api_key_cloud_owner),
  2919. ):
  2920. """Enqueue a slice job for a library file. Returns 202 + job_id; the
  2921. slice runs in the background, the caller polls `GET /slice-jobs/{id}`.
  2922. """
  2923. from backend.app.core.database import async_session
  2924. from backend.app.services.slice_dispatch import (
  2925. http_exception_to_job_error,
  2926. slice_dispatch,
  2927. )
  2928. src_result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  2929. lib_file = src_result.scalar_one_or_none()
  2930. if not lib_file:
  2931. raise HTTPException(status_code=404, detail="File not found")
  2932. src_lower = (lib_file.filename or "").lower()
  2933. if not (
  2934. src_lower.endswith(".stl")
  2935. or src_lower.endswith(".3mf")
  2936. or src_lower.endswith(".step")
  2937. or src_lower.endswith(".stp")
  2938. ):
  2939. raise HTTPException(status_code=400, detail="Source file must be STL, 3MF, or STEP")
  2940. src_path = Path(app_settings.base_dir) / lib_file.file_path
  2941. if not src_path.exists():
  2942. raise HTTPException(status_code=404, detail="Source file missing on disk")
  2943. # Capture inputs the bg task needs — the request DB session is closed
  2944. # before the background task runs.
  2945. model_bytes = src_path.read_bytes()
  2946. folder_id = lib_file.folder_id
  2947. source_lib_file_id = lib_file.id
  2948. # API-keyed callers get None from the auth gate (auth.py keeps that
  2949. # behaviour to avoid a wider scope expansion). Fall back to the API
  2950. # key's owner so cloud-preset resolution can read the stored
  2951. # cloud_token (#1182 follow-up).
  2952. cloud_token_user = current_user or api_key_cloud_owner
  2953. user_id = cloud_token_user.id if cloud_token_user else None
  2954. # If the source has a `print_name` in its metadata (BambuStudio always
  2955. # sets this; OrcaSlicer often leaves it blank), derive the sliced
  2956. # output's filename from it instead of the raw filename. The source
  2957. # row's display already prefers print_name, so the sliced row's
  2958. # filename ("Piggo the piggy bank.gcode.3mf") will match the source's
  2959. # display name ("Piggo the piggy bank") with the gcode extension added.
  2960. src_print_name = None
  2961. if lib_file.file_metadata:
  2962. candidate = lib_file.file_metadata.get("print_name")
  2963. if isinstance(candidate, str) and candidate.strip():
  2964. src_print_name = candidate.strip()
  2965. src_ext = Path(lib_file.filename).suffix.lower() or ".3mf"
  2966. model_filename = f"{src_print_name}{src_ext}" if src_print_name else lib_file.filename
  2967. async def _run(job_id: int):
  2968. async with async_session() as task_db:
  2969. try:
  2970. response = await slice_and_persist(
  2971. task_db,
  2972. model_bytes=model_bytes,
  2973. model_filename=model_filename,
  2974. folder_id=folder_id,
  2975. extra_metadata={"sliced_from_library_file_id": source_lib_file_id},
  2976. request=request,
  2977. current_user_id=user_id,
  2978. job_id=job_id,
  2979. )
  2980. except HTTPException as exc:
  2981. raise http_exception_to_job_error(exc) from exc
  2982. return response.model_dump()
  2983. job = await slice_dispatch.enqueue(
  2984. kind="library_file",
  2985. source_id=lib_file.id,
  2986. source_name=lib_file.filename,
  2987. run=_run,
  2988. )
  2989. return {
  2990. "job_id": job.id,
  2991. "status": job.status,
  2992. "status_url": f"/api/v1/slice-jobs/{job.id}",
  2993. }
  2994. @router.post("/files/{file_id}/print")
  2995. async def print_library_file(
  2996. file_id: int,
  2997. printer_id: int,
  2998. body: FilePrintRequest | None = None,
  2999. db: AsyncSession = Depends(get_db),
  3000. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.PRINTERS_CONTROL)),
  3001. ):
  3002. """Dispatch a library file for send/start on a printer.
  3003. The actual send/start work is handled asynchronously by background
  3004. dispatch so the UI can continue immediately.
  3005. Only sliced files (.gcode or .gcode.3mf) can be printed.
  3006. """
  3007. from backend.app.models.printer import Printer
  3008. from backend.app.services.background_dispatch import DispatchEnqueueRejected, background_dispatch
  3009. from backend.app.services.printer_manager import printer_manager
  3010. # Use defaults if no body provided
  3011. if body is None:
  3012. body = FilePrintRequest()
  3013. # Get the library file
  3014. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3015. lib_file = result.scalar_one_or_none()
  3016. if not lib_file:
  3017. raise HTTPException(status_code=404, detail="File not found")
  3018. # Validate file is sliced
  3019. if not is_sliced_file(lib_file.filename):
  3020. raise HTTPException(
  3021. status_code=400,
  3022. detail="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  3023. )
  3024. # Get the full file path
  3025. file_path = Path(app_settings.base_dir) / lib_file.file_path
  3026. if not file_path.exists():
  3027. raise HTTPException(status_code=404, detail="File not found on disk")
  3028. # Get printer
  3029. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3030. printer = result.scalar_one_or_none()
  3031. if not printer:
  3032. raise HTTPException(status_code=404, detail="Printer not found")
  3033. # Check printer is connected
  3034. if not printer_manager.is_connected(printer_id):
  3035. raise HTTPException(status_code=400, detail="Printer is not connected")
  3036. # Validate project exists before dispatching so a bogus ID yields 404, not a FK-constraint 500
  3037. if body.project_id is not None:
  3038. project_result = await db.execute(select(Project).where(Project.id == body.project_id))
  3039. if not project_result.scalar_one_or_none():
  3040. raise HTTPException(status_code=404, detail="Project not found")
  3041. plate_name = body.plate_name
  3042. if not plate_name and body.plate_id is not None:
  3043. plate_name = f"Plate {body.plate_id}"
  3044. dispatch_source_name = lib_file.filename
  3045. if plate_name:
  3046. dispatch_source_name = f"{lib_file.filename} • {plate_name}"
  3047. try:
  3048. dispatch_result = await background_dispatch.dispatch_print_library_file(
  3049. file_id=file_id,
  3050. filename=dispatch_source_name,
  3051. printer_id=printer_id,
  3052. printer_name=printer.name,
  3053. options=body.model_dump(exclude_none=True, exclude={"cleanup_library_after_dispatch"}),
  3054. project_id=body.project_id,
  3055. requested_by_user_id=current_user.id if current_user else None,
  3056. requested_by_username=current_user.username if current_user else None,
  3057. cleanup_library_after_dispatch=body.cleanup_library_after_dispatch,
  3058. )
  3059. except DispatchEnqueueRejected as e:
  3060. raise HTTPException(status_code=409, detail=str(e)) from e
  3061. return {
  3062. "status": "dispatched",
  3063. "printer_id": printer_id,
  3064. "archive_id": None,
  3065. "filename": lib_file.filename,
  3066. "dispatch_job_id": dispatch_result["dispatch_job_id"],
  3067. "dispatch_position": dispatch_result["dispatch_position"],
  3068. }
  3069. # ============ File Detail Endpoints ============
  3070. @router.get("/files/{file_id}", response_model=FileResponseSchema)
  3071. async def get_file(
  3072. file_id: int,
  3073. db: AsyncSession = Depends(get_db),
  3074. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  3075. ):
  3076. """Get a file by ID with full details."""
  3077. result = await db.execute(
  3078. LibraryFile.active().options(selectinload(LibraryFile.created_by)).where(LibraryFile.id == file_id)
  3079. )
  3080. file = result.scalar_one_or_none()
  3081. if not file:
  3082. raise HTTPException(status_code=404, detail="File not found")
  3083. # Get folder name
  3084. folder_name = None
  3085. if file.folder_id:
  3086. folder_result = await db.execute(select(LibraryFolder.name).where(LibraryFolder.id == file.folder_id))
  3087. folder_name = folder_result.scalar()
  3088. # Get project name
  3089. project_name = None
  3090. if file.project_id:
  3091. project_result = await db.execute(select(Project.name).where(Project.id == file.project_id))
  3092. project_name = project_result.scalar()
  3093. # Get duplicates
  3094. duplicates = []
  3095. duplicate_count = 0
  3096. if file.file_hash:
  3097. dup_result = await db.execute(
  3098. select(LibraryFile, LibraryFolder.name)
  3099. .outerjoin(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  3100. .where(
  3101. LibraryFile.file_hash == file.file_hash,
  3102. LibraryFile.id != file.id,
  3103. LibraryFile.deleted_at.is_(None),
  3104. )
  3105. )
  3106. for dup_file, dup_folder_name in dup_result.all():
  3107. duplicates.append(
  3108. FileDuplicate(
  3109. id=dup_file.id,
  3110. filename=dup_file.filename,
  3111. folder_id=dup_file.folder_id,
  3112. folder_name=dup_folder_name,
  3113. created_at=dup_file.created_at,
  3114. )
  3115. )
  3116. duplicate_count = len(duplicates)
  3117. # Extract key metadata fields
  3118. print_name = None
  3119. print_time = None
  3120. filament_grams = None
  3121. sliced_for_model = None
  3122. if file.file_metadata:
  3123. print_name = file.file_metadata.get("print_name")
  3124. print_time = file.file_metadata.get("print_time_seconds")
  3125. filament_grams = file.file_metadata.get("filament_used_grams")
  3126. sliced_for_model = file.file_metadata.get("sliced_for_model")
  3127. return FileResponseSchema(
  3128. id=file.id,
  3129. folder_id=file.folder_id,
  3130. folder_name=folder_name,
  3131. project_id=file.project_id,
  3132. project_name=project_name,
  3133. filename=file.filename,
  3134. file_path=file.file_path,
  3135. file_type=file.file_type,
  3136. file_size=file.file_size,
  3137. file_hash=file.file_hash,
  3138. thumbnail_path=file.thumbnail_path,
  3139. metadata=file.file_metadata,
  3140. print_count=file.print_count,
  3141. last_printed_at=file.last_printed_at,
  3142. notes=file.notes,
  3143. duplicates=duplicates if duplicates else None,
  3144. duplicate_count=duplicate_count,
  3145. created_by_id=file.created_by_id,
  3146. created_by_username=file.created_by.username if file.created_by else None,
  3147. created_at=file.created_at,
  3148. updated_at=file.updated_at,
  3149. print_name=print_name,
  3150. print_time_seconds=print_time,
  3151. filament_used_grams=filament_grams,
  3152. sliced_for_model=sliced_for_model,
  3153. )
  3154. @router.put("/files/{file_id}", response_model=FileResponseSchema)
  3155. async def update_file(
  3156. file_id: int,
  3157. data: FileUpdate,
  3158. db: AsyncSession = Depends(get_db),
  3159. auth_result: tuple[User | None, bool] = Depends(
  3160. require_ownership_permission(
  3161. Permission.LIBRARY_UPDATE_ALL,
  3162. Permission.LIBRARY_UPDATE_OWN,
  3163. )
  3164. ),
  3165. ):
  3166. """Update a file's metadata."""
  3167. user, can_modify_all = auth_result
  3168. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3169. file = result.scalar_one_or_none()
  3170. if not file:
  3171. raise HTTPException(status_code=404, detail="File not found")
  3172. # Ownership check
  3173. if not can_modify_all:
  3174. if file.created_by_id != user.id:
  3175. raise HTTPException(status_code=403, detail="You can only update your own files")
  3176. if data.filename is not None:
  3177. # Validate filename doesn't contain path separators
  3178. if "/" in data.filename or "\\" in data.filename:
  3179. raise HTTPException(status_code=400, detail="Filename cannot contain path separators")
  3180. file.filename = data.filename
  3181. # Also update print_name in file_metadata so the display name matches
  3182. if file.file_metadata and "print_name" in file.file_metadata:
  3183. file.file_metadata = {**file.file_metadata, "print_name": data.filename}
  3184. if data.folder_id is not None:
  3185. if data.folder_id == 0:
  3186. file.folder_id = None
  3187. else:
  3188. # Verify folder exists
  3189. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  3190. if not folder_result.scalar_one_or_none():
  3191. raise HTTPException(status_code=404, detail="Folder not found")
  3192. file.folder_id = data.folder_id
  3193. if data.project_id is not None:
  3194. if data.project_id == 0:
  3195. file.project_id = None
  3196. else:
  3197. # Verify project exists
  3198. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  3199. if not project_result.scalar_one_or_none():
  3200. raise HTTPException(status_code=404, detail="Project not found")
  3201. file.project_id = data.project_id
  3202. if data.notes is not None:
  3203. file.notes = data.notes if data.notes else None
  3204. await db.commit()
  3205. await db.refresh(file)
  3206. # Return full response (reuse get_file logic)
  3207. return await get_file(file_id, db)
  3208. @router.delete("/files/{file_id}")
  3209. async def delete_file(
  3210. file_id: int,
  3211. db: AsyncSession = Depends(get_db),
  3212. auth_result: tuple[User | None, bool] = Depends(
  3213. require_ownership_permission(
  3214. Permission.LIBRARY_DELETE_ALL,
  3215. Permission.LIBRARY_DELETE_OWN,
  3216. )
  3217. ),
  3218. ):
  3219. """Move a file to the trash (soft-delete).
  3220. The file's bytes and thumbnail stay on disk until the trash sweeper
  3221. hard-deletes the row after the retention window (see #1008). External
  3222. files skip the trash entirely — they can't be restored from disk and the
  3223. underlying file is outside Bambuddy's control, so we just drop the DB
  3224. record and thumbnail.
  3225. """
  3226. user, can_modify_all = auth_result
  3227. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3228. file = result.scalar_one_or_none()
  3229. if not file:
  3230. raise HTTPException(status_code=404, detail="File not found")
  3231. # Ownership check
  3232. if not can_modify_all:
  3233. if file.created_by_id != user.id:
  3234. raise HTTPException(status_code=403, detail="You can only delete your own files")
  3235. if file.is_external:
  3236. # External files bypass the trash — just drop the DB row + our thumbnail.
  3237. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  3238. if abs_thumb_path and abs_thumb_path.exists():
  3239. try:
  3240. abs_thumb_path.unlink()
  3241. except OSError as e:
  3242. logger.warning("Failed to delete thumbnail from disk: %s", e)
  3243. await db.delete(file)
  3244. await db.commit()
  3245. return {"status": "success", "message": "File deleted", "trashed": False}
  3246. # Managed file: soft-delete. Sweeper removes bytes + thumbnail after retention.
  3247. file.deleted_at = datetime.now(timezone.utc)
  3248. await db.commit()
  3249. return {"status": "success", "message": "File moved to trash", "trashed": True}
  3250. # ============ File Content Endpoints ============
  3251. @router.get("/files/{file_id}/download")
  3252. async def download_file(
  3253. file_id: int,
  3254. db: AsyncSession = Depends(get_db),
  3255. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  3256. ):
  3257. """Download a file."""
  3258. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3259. file = result.scalar_one_or_none()
  3260. if not file:
  3261. raise HTTPException(status_code=404, detail="File not found")
  3262. abs_path = to_absolute_path(file.file_path)
  3263. if not abs_path or not abs_path.exists():
  3264. raise HTTPException(status_code=404, detail="File not found on disk")
  3265. return FastAPIFileResponse(
  3266. str(abs_path),
  3267. filename=file.filename,
  3268. media_type="application/octet-stream",
  3269. )
  3270. @router.post("/files/{file_id}/slicer-token")
  3271. async def create_library_slicer_token(
  3272. file_id: int,
  3273. db: AsyncSession = Depends(get_db),
  3274. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  3275. ):
  3276. """Create a short-lived download token for opening files in slicer applications.
  3277. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  3278. auth headers, so they use this token in the URL path instead.
  3279. """
  3280. from backend.app.core.auth import create_slicer_download_token
  3281. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3282. file = result.scalar_one_or_none()
  3283. if not file:
  3284. raise HTTPException(status_code=404, detail="File not found")
  3285. token = await create_slicer_download_token("library", file_id)
  3286. return {"token": token}
  3287. @router.get("/files/{file_id}/dl/{token}/{filename}")
  3288. async def download_library_file_for_slicer(
  3289. file_id: int,
  3290. token: str,
  3291. filename: str,
  3292. db: AsyncSession = Depends(get_db),
  3293. ):
  3294. """Download a library file using a slicer download token.
  3295. Token-authenticated (no auth headers needed). The token is short-lived
  3296. and single-use, created by POST /files/{file_id}/slicer-token.
  3297. Filename is at the end of the URL so slicers can detect the file format.
  3298. """
  3299. from backend.app.core.auth import verify_slicer_download_token
  3300. if not await verify_slicer_download_token(token, "library", file_id):
  3301. raise HTTPException(status_code=403, detail="Invalid or expired download token")
  3302. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3303. file = result.scalar_one_or_none()
  3304. if not file:
  3305. raise HTTPException(status_code=404, detail="File not found")
  3306. abs_path = to_absolute_path(file.file_path)
  3307. if not abs_path or not abs_path.exists():
  3308. raise HTTPException(status_code=404, detail="File not found on disk")
  3309. return FastAPIFileResponse(
  3310. str(abs_path),
  3311. filename=file.filename,
  3312. media_type="application/octet-stream",
  3313. )
  3314. @router.get("/files/{file_id}/thumbnail")
  3315. async def get_thumbnail(
  3316. file_id: int,
  3317. db: AsyncSession = Depends(get_db),
  3318. _: None = RequireCameraStreamTokenIfAuthEnabled,
  3319. ):
  3320. """Get a file's thumbnail."""
  3321. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3322. file = result.scalar_one_or_none()
  3323. if not file:
  3324. raise HTTPException(status_code=404, detail="File not found")
  3325. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  3326. if not abs_thumb_path or not abs_thumb_path.exists():
  3327. raise HTTPException(status_code=404, detail="Thumbnail not found")
  3328. # Detect media type from extension
  3329. thumb_ext = abs_thumb_path.suffix.lower()
  3330. media_types = {
  3331. ".png": "image/png",
  3332. ".jpg": "image/jpeg",
  3333. ".jpeg": "image/jpeg",
  3334. ".gif": "image/gif",
  3335. ".webp": "image/webp",
  3336. }
  3337. media_type = media_types.get(thumb_ext, "image/png")
  3338. return FastAPIFileResponse(str(abs_thumb_path), media_type=media_type)
  3339. @router.get("/files/{file_id}/gcode")
  3340. async def get_gcode(
  3341. file_id: int,
  3342. db: AsyncSession = Depends(get_db),
  3343. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  3344. ):
  3345. """Get gcode for a file (for preview)."""
  3346. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3347. file = result.scalar_one_or_none()
  3348. if not file:
  3349. raise HTTPException(status_code=404, detail="File not found")
  3350. abs_path = to_absolute_path(file.file_path)
  3351. if not abs_path or not abs_path.exists():
  3352. raise HTTPException(status_code=404, detail="File not found on disk")
  3353. if file.file_type == "gcode":
  3354. return FastAPIFileResponse(str(abs_path), media_type="text/plain")
  3355. elif file.file_type == "3mf":
  3356. # Extract gcode from 3mf
  3357. try:
  3358. with zipfile.ZipFile(str(abs_path), "r") as zf:
  3359. # Find gcode file
  3360. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  3361. if not gcode_files:
  3362. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  3363. gcode_content = zf.read(gcode_files[0])
  3364. from fastapi.responses import Response
  3365. return Response(content=gcode_content, media_type="text/plain")
  3366. except zipfile.BadZipFile:
  3367. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  3368. else:
  3369. raise HTTPException(status_code=400, detail="Unsupported file type")
  3370. # ============ Bulk Operations ============
  3371. @router.post("/files/move")
  3372. async def move_files(
  3373. data: FileMoveRequest,
  3374. db: AsyncSession = Depends(get_db),
  3375. auth_result: tuple[User | None, bool] = Depends(
  3376. require_ownership_permission(
  3377. Permission.LIBRARY_UPDATE_ALL,
  3378. Permission.LIBRARY_UPDATE_OWN,
  3379. )
  3380. ),
  3381. ):
  3382. """Move multiple files to a folder.
  3383. Cross-boundary moves (managed ↔ external, or external ↔ external)
  3384. physically relocate the bytes — see ``_move_file_bytes``. Same-boundary
  3385. moves stay DB-only because the file's on-disk location doesn't depend
  3386. on which managed folder owns it.
  3387. Files not owned by the user are skipped (unless user has ``*_all``
  3388. permission). Each skip carries a structured reason so the UI can
  3389. surface "5 of 10 files were skipped: 3 had filename collisions on
  3390. the NAS, 2 are no longer on disk" rather than a blank "skipped: 5".
  3391. """
  3392. user, can_modify_all = auth_result
  3393. # Verify folder exists if specified
  3394. target_folder: LibraryFolder | None = None
  3395. if data.folder_id is not None:
  3396. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  3397. target_folder = folder_result.scalar_one_or_none()
  3398. if not target_folder:
  3399. raise HTTPException(status_code=404, detail="Folder not found")
  3400. if target_folder.is_external and target_folder.external_readonly:
  3401. raise HTTPException(status_code=403, detail="Cannot move files to a read-only external folder")
  3402. target_is_external = target_folder is not None and target_folder.is_external
  3403. moved = 0
  3404. skipped = 0
  3405. skipped_reasons: list[dict] = []
  3406. for file_id in data.file_ids:
  3407. result = await db.execute(
  3408. LibraryFile.active().options(selectinload(LibraryFile.folder)).where(LibraryFile.id == file_id)
  3409. )
  3410. file = result.scalar_one_or_none()
  3411. if not file:
  3412. continue
  3413. # Ownership check
  3414. if not can_modify_all and file.created_by_id != user.id:
  3415. skipped += 1
  3416. skipped_reasons.append({"file_id": file_id, "code": "not_owner", "reason": "not the file owner"})
  3417. continue
  3418. # No bytes need to move when both ends are managed (same-boundary).
  3419. if not file.is_external and not target_is_external:
  3420. file.folder_id = data.folder_id
  3421. moved += 1
  3422. continue
  3423. # Block moves out of a read-only external mount. The user only has
  3424. # read access to the source, and a move is semantically a delete on
  3425. # the source — which a read-only mount can't fulfil. Without this
  3426. # guard we'd succeed at copying to the target, fail to unlink the
  3427. # source, and the same file would now exist in two places (with
  3428. # the DB pointing at only one).
  3429. if file.is_external and file.folder is not None and file.folder.external_readonly:
  3430. skipped += 1
  3431. skipped_reasons.append(
  3432. {"file_id": file_id, "code": "source_readonly", "reason": "source is on a read-only external folder"}
  3433. )
  3434. continue
  3435. # Otherwise relocate the bytes, then update the DB row to match.
  3436. try:
  3437. new_file_path = _move_file_bytes(file, target_folder)
  3438. except _MoveSkip as e:
  3439. skipped += 1
  3440. skipped_reasons.append({"file_id": file_id, "code": e.code, "reason": e.reason})
  3441. continue
  3442. file.is_external = target_is_external
  3443. file.folder_id = data.folder_id
  3444. file.file_path = new_file_path
  3445. # External rows historically carry `file_hash=None` (scan skips
  3446. # hashing). When pulling an external file into managed storage,
  3447. # compute the hash so dedup detection works for future uploads
  3448. # of the same content.
  3449. if not target_is_external and file.file_hash is None:
  3450. try:
  3451. abs_path = to_absolute_path(new_file_path)
  3452. if abs_path:
  3453. file.file_hash = calculate_file_hash(abs_path)
  3454. except OSError:
  3455. pass # leave hash null; dedup just won't match this row
  3456. moved += 1
  3457. await db.commit()
  3458. return {
  3459. "status": "success",
  3460. "moved": moved,
  3461. "skipped": skipped,
  3462. "skipped_reasons": skipped_reasons,
  3463. }
  3464. @router.post("/bulk-delete", response_model=BulkDeleteResponse)
  3465. async def bulk_delete(
  3466. data: BulkDeleteRequest,
  3467. db: AsyncSession = Depends(get_db),
  3468. auth_result: tuple[User | None, bool] = Depends(
  3469. require_ownership_permission(
  3470. Permission.LIBRARY_DELETE_ALL,
  3471. Permission.LIBRARY_DELETE_OWN,
  3472. )
  3473. ),
  3474. ):
  3475. """Delete multiple files and/or folders.
  3476. Files not owned by the user are skipped (unless user has *_all permission).
  3477. """
  3478. user, can_modify_all = auth_result
  3479. deleted_files = 0
  3480. deleted_folders = 0
  3481. skipped_files = 0
  3482. # Delete files first. Managed files go to trash (sweeper hard-deletes bytes
  3483. # later); external files bypass trash since their disk state is outside our
  3484. # control and can't be restored from trash anyway.
  3485. now = datetime.now(timezone.utc)
  3486. for file_id in data.file_ids:
  3487. result = await db.execute(LibraryFile.active().where(LibraryFile.id == file_id))
  3488. file = result.scalar_one_or_none()
  3489. if not file:
  3490. continue
  3491. if not can_modify_all and file.created_by_id != user.id:
  3492. skipped_files += 1
  3493. continue
  3494. if file.is_external:
  3495. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  3496. if abs_thumb_path and abs_thumb_path.exists():
  3497. try:
  3498. abs_thumb_path.unlink()
  3499. except OSError as e:
  3500. logger.warning("Failed to delete thumbnail from disk: %s", e)
  3501. await db.delete(file)
  3502. else:
  3503. file.deleted_at = now
  3504. deleted_files += 1
  3505. # Delete folders (cascade will handle contents)
  3506. # Note: Folders don't have ownership tracking currently, require *_all permission
  3507. for folder_id in data.folder_ids:
  3508. if not can_modify_all:
  3509. # Users without *_all permission cannot delete folders
  3510. continue
  3511. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  3512. folder = result.scalar_one_or_none()
  3513. if folder:
  3514. # Count files that will be deleted
  3515. file_count_result = await db.execute(
  3516. select(func.count(LibraryFile.id)).where(
  3517. LibraryFile.folder_id == folder_id,
  3518. LibraryFile.deleted_at.is_(None),
  3519. )
  3520. )
  3521. deleted_files += file_count_result.scalar() or 0
  3522. await db.delete(folder)
  3523. deleted_folders += 1
  3524. await db.commit()
  3525. return BulkDeleteResponse(deleted_files=deleted_files, deleted_folders=deleted_folders)
  3526. # ============ Stats Endpoint ============
  3527. @router.get("/stats")
  3528. async def get_library_stats(
  3529. db: AsyncSession = Depends(get_db),
  3530. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  3531. ):
  3532. """Get library statistics."""
  3533. # Stats exclude trashed files — users see counts/sizes for what's actually in the library.
  3534. active_only = LibraryFile.deleted_at.is_(None)
  3535. # Total files
  3536. total_files_result = await db.execute(select(func.count(LibraryFile.id)).where(active_only))
  3537. total_files = total_files_result.scalar() or 0
  3538. # Total folders
  3539. total_folders_result = await db.execute(select(func.count(LibraryFolder.id)))
  3540. total_folders = total_folders_result.scalar() or 0
  3541. # Total size
  3542. total_size_result = await db.execute(select(func.sum(LibraryFile.file_size)).where(active_only))
  3543. total_size = total_size_result.scalar() or 0
  3544. # Files by type
  3545. type_result = await db.execute(
  3546. select(LibraryFile.file_type, func.count(LibraryFile.id)).where(active_only).group_by(LibraryFile.file_type)
  3547. )
  3548. files_by_type = dict(type_result.all())
  3549. # Total prints
  3550. total_prints_result = await db.execute(select(func.sum(LibraryFile.print_count)).where(active_only))
  3551. total_prints = total_prints_result.scalar() or 0
  3552. # Disk space info
  3553. library_dir = get_library_dir()
  3554. try:
  3555. disk_stat = shutil.disk_usage(library_dir)
  3556. disk_free_bytes = disk_stat.free
  3557. disk_total_bytes = disk_stat.total
  3558. disk_used_bytes = disk_stat.used
  3559. except OSError:
  3560. disk_free_bytes = 0
  3561. disk_total_bytes = 0
  3562. disk_used_bytes = 0
  3563. return {
  3564. "total_files": total_files,
  3565. "total_folders": total_folders,
  3566. "total_size_bytes": total_size,
  3567. "files_by_type": files_by_type,
  3568. "total_prints": total_prints,
  3569. "disk_free_bytes": disk_free_bytes,
  3570. "disk_total_bytes": disk_total_bytes,
  3571. "disk_used_bytes": disk_used_bytes,
  3572. }