library.py 151 KB

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