library.py 143 KB

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