library.py 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623
  1. """API routes for File Manager (Library) functionality."""
  2. import base64
  3. import binascii
  4. import hashlib
  5. import logging
  6. import os
  7. import re
  8. import shutil
  9. import uuid
  10. import zipfile
  11. from pathlib import Path
  12. from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile
  13. from fastapi.responses import FileResponse as FastAPIFileResponse
  14. from sqlalchemy import func, select
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from sqlalchemy.orm import selectinload
  17. from backend.app.core.auth import (
  18. require_ownership_permission,
  19. require_permission_if_auth_enabled,
  20. )
  21. from backend.app.core.config import settings as app_settings
  22. from backend.app.core.database import get_db
  23. from backend.app.core.permissions import Permission
  24. from backend.app.models.archive import PrintArchive
  25. from backend.app.models.library import LibraryFile, LibraryFolder
  26. from backend.app.models.print_queue import PrintQueueItem
  27. from backend.app.models.project import Project
  28. from backend.app.models.user import User
  29. from backend.app.schemas.library import (
  30. AddToQueueError,
  31. AddToQueueRequest,
  32. AddToQueueResponse,
  33. AddToQueueResult,
  34. BatchThumbnailRequest,
  35. BatchThumbnailResponse,
  36. BatchThumbnailResult,
  37. BulkDeleteRequest,
  38. BulkDeleteResponse,
  39. ExternalFolderCreate,
  40. FileDuplicate,
  41. FileListResponse,
  42. FileMoveRequest,
  43. FilePrintRequest,
  44. FileResponse as FileResponseSchema,
  45. FileUpdate,
  46. FileUploadResponse,
  47. FolderCreate,
  48. FolderResponse,
  49. FolderTreeItem,
  50. FolderUpdate,
  51. ZipExtractError,
  52. ZipExtractResponse,
  53. ZipExtractResult,
  54. )
  55. from backend.app.services.archive import ThreeMFParser
  56. from backend.app.services.stl_thumbnail import generate_stl_thumbnail
  57. from backend.app.utils.threemf_tools import extract_nozzle_mapping_from_3mf
  58. logger = logging.getLogger(__name__)
  59. router = APIRouter(prefix="/library", tags=["library"])
  60. def get_library_dir() -> Path:
  61. """Get the library storage directory."""
  62. base_dir = Path(app_settings.archive_dir)
  63. library_dir = base_dir / "library"
  64. library_dir.mkdir(parents=True, exist_ok=True)
  65. return library_dir
  66. def get_library_files_dir() -> Path:
  67. """Get the directory for library files."""
  68. files_dir = get_library_dir() / "files"
  69. files_dir.mkdir(parents=True, exist_ok=True)
  70. return files_dir
  71. def get_library_thumbnails_dir() -> Path:
  72. """Get the directory for library thumbnails."""
  73. thumbnails_dir = get_library_dir() / "thumbnails"
  74. thumbnails_dir.mkdir(parents=True, exist_ok=True)
  75. return thumbnails_dir
  76. def to_relative_path(absolute_path: Path | str) -> str:
  77. """Convert an absolute path to a path relative to base_dir for storage."""
  78. if not absolute_path:
  79. return ""
  80. abs_path = Path(absolute_path)
  81. base_dir = Path(app_settings.base_dir)
  82. try:
  83. return str(abs_path.relative_to(base_dir))
  84. except ValueError:
  85. # Path is not under base_dir, return as-is (shouldn't happen normally)
  86. return str(abs_path)
  87. def to_absolute_path(relative_path: str | None) -> Path | None:
  88. """Convert a relative path (from database) to an absolute path for file operations."""
  89. if not relative_path:
  90. return None
  91. # Handle already-absolute paths (for backwards compatibility during migration)
  92. path = Path(relative_path)
  93. if path.is_absolute():
  94. return path
  95. return Path(app_settings.base_dir) / relative_path
  96. def calculate_file_hash(file_path: Path) -> str:
  97. """Calculate SHA256 hash of a file."""
  98. sha256_hash = hashlib.sha256()
  99. with open(file_path, "rb") as f:
  100. for byte_block in iter(lambda: f.read(4096), b""):
  101. sha256_hash.update(byte_block)
  102. return sha256_hash.hexdigest()
  103. def extract_gcode_thumbnail(file_path: Path) -> bytes | None:
  104. """Extract embedded thumbnail from gcode file.
  105. Supports PrusaSlicer/BambuStudio format:
  106. ; thumbnail begin WxH SIZE
  107. ; base64data...
  108. ; thumbnail end
  109. """
  110. try:
  111. thumbnail_data = None
  112. in_thumbnail = False
  113. thumbnail_lines = []
  114. best_size = 0
  115. with open(file_path, errors="ignore") as f:
  116. # Only read first 50KB for performance (thumbnails are at the start)
  117. content = f.read(50000)
  118. for line in content.split("\n"):
  119. line = line.strip()
  120. # Check for thumbnail start
  121. if line.startswith("; thumbnail begin"):
  122. in_thumbnail = True
  123. thumbnail_lines = []
  124. # Parse dimensions: "; thumbnail begin 300x300 12345"
  125. match = re.search(r"(\d+)x(\d+)", line)
  126. if match:
  127. width = int(match.group(1))
  128. # Prefer larger thumbnails (up to 300px)
  129. if width > best_size and width <= 300:
  130. best_size = width
  131. continue
  132. # Check for thumbnail end
  133. if line.startswith("; thumbnail end"):
  134. if in_thumbnail and thumbnail_lines:
  135. try:
  136. # Decode the base64 data
  137. b64_data = "".join(thumbnail_lines)
  138. decoded = base64.b64decode(b64_data)
  139. # Only keep if this is the best size or first valid thumbnail
  140. if thumbnail_data is None or best_size > 0:
  141. thumbnail_data = decoded
  142. except (binascii.Error, ValueError):
  143. pass # Skip thumbnail with invalid base64 data
  144. in_thumbnail = False
  145. thumbnail_lines = []
  146. continue
  147. # Collect thumbnail data
  148. if in_thumbnail and line.startswith(";"):
  149. # Remove the leading "; " or ";"
  150. data_line = line[1:].strip()
  151. if data_line:
  152. thumbnail_lines.append(data_line)
  153. return thumbnail_data
  154. except Exception as e:
  155. logger.warning("Failed to extract gcode thumbnail: %s", e)
  156. return None
  157. def create_image_thumbnail(file_path: Path, thumbnails_dir: Path, max_size: int = 256) -> str | None:
  158. """Create a thumbnail from an image file.
  159. For small images, copies directly. For larger images, resizes.
  160. Returns the thumbnail path or None on failure.
  161. """
  162. try:
  163. from PIL import Image
  164. thumb_filename = f"{uuid.uuid4().hex}.png"
  165. thumb_path = thumbnails_dir / thumb_filename
  166. with Image.open(file_path) as img:
  167. # Convert to RGB if necessary (for PNG with transparency, etc.)
  168. if img.mode in ("RGBA", "LA", "P"):
  169. # Create white background for transparency
  170. background = Image.new("RGB", img.size, (255, 255, 255))
  171. if img.mode == "P":
  172. img = img.convert("RGBA")
  173. background.paste(img, mask=img.split()[-1] if img.mode == "RGBA" else None)
  174. img = background
  175. elif img.mode != "RGB":
  176. img = img.convert("RGB")
  177. # Resize if larger than max_size
  178. if img.width > max_size or img.height > max_size:
  179. img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
  180. img.save(thumb_path, "PNG", optimize=True)
  181. return str(thumb_path)
  182. except ImportError:
  183. # PIL not installed, just copy the file if it's small enough
  184. logger.warning("PIL not installed, copying image as thumbnail")
  185. try:
  186. file_size = file_path.stat().st_size
  187. if file_size < 500000: # Less than 500KB
  188. thumb_filename = f"{uuid.uuid4().hex}{file_path.suffix}"
  189. thumb_path = thumbnails_dir / thumb_filename
  190. shutil.copy2(file_path, thumb_path)
  191. return str(thumb_path)
  192. except OSError:
  193. pass # File inaccessible; fall through to return None
  194. return None
  195. except Exception as e:
  196. logger.warning("Failed to create image thumbnail: %s", e)
  197. return None
  198. # Supported image extensions for thumbnails
  199. IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif"}
  200. # ============ Folder Endpoints ============
  201. @router.get("/folders", response_model=list[FolderTreeItem])
  202. @router.get("/folders/", response_model=list[FolderTreeItem])
  203. async def list_folders(
  204. response: Response,
  205. db: AsyncSession = Depends(get_db),
  206. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  207. ):
  208. """Get all folders as a tree structure."""
  209. # Prevent browser caching of folder list
  210. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  211. # Get all folders with project and archive joins
  212. result = await db.execute(
  213. select(LibraryFolder, Project.name, PrintArchive.print_name)
  214. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  215. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  216. .order_by(LibraryFolder.name)
  217. )
  218. rows = result.all()
  219. # Get file counts per folder
  220. file_counts_result = await db.execute(
  221. select(LibraryFile.folder_id, func.count(LibraryFile.id))
  222. .where(LibraryFile.folder_id.isnot(None))
  223. .group_by(LibraryFile.folder_id)
  224. )
  225. file_counts = dict(file_counts_result.all())
  226. # Build tree structure
  227. folder_map = {}
  228. root_folders = []
  229. for folder, project_name, archive_name in rows:
  230. folder_item = FolderTreeItem(
  231. id=folder.id,
  232. name=folder.name,
  233. parent_id=folder.parent_id,
  234. project_id=folder.project_id,
  235. archive_id=folder.archive_id,
  236. project_name=project_name,
  237. archive_name=archive_name,
  238. is_external=folder.is_external,
  239. external_path=folder.external_path,
  240. external_readonly=folder.external_readonly,
  241. file_count=file_counts.get(folder.id, 0),
  242. children=[],
  243. )
  244. folder_map[folder.id] = folder_item
  245. # Link children to parents
  246. for folder, _, _ in rows:
  247. folder_item = folder_map[folder.id]
  248. if folder.parent_id is None:
  249. root_folders.append(folder_item)
  250. elif folder.parent_id in folder_map:
  251. folder_map[folder.parent_id].children.append(folder_item)
  252. return root_folders
  253. @router.get("/folders/by-project/{project_id}", response_model=list[FolderResponse])
  254. async def get_folders_by_project(
  255. project_id: int,
  256. db: AsyncSession = Depends(get_db),
  257. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  258. ):
  259. """Get all folders linked to a specific project."""
  260. result = await db.execute(
  261. select(LibraryFolder, Project.name)
  262. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  263. .where(LibraryFolder.project_id == project_id)
  264. .order_by(LibraryFolder.name)
  265. )
  266. rows = result.all()
  267. folders = []
  268. for folder, project_name in rows:
  269. # Get file count
  270. file_count_result = await db.execute(
  271. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder.id)
  272. )
  273. file_count = file_count_result.scalar() or 0
  274. folders.append(
  275. FolderResponse(
  276. id=folder.id,
  277. name=folder.name,
  278. parent_id=folder.parent_id,
  279. project_id=folder.project_id,
  280. archive_id=folder.archive_id,
  281. project_name=project_name,
  282. archive_name=None,
  283. is_external=folder.is_external,
  284. external_path=folder.external_path,
  285. external_readonly=folder.external_readonly,
  286. external_show_hidden=folder.external_show_hidden,
  287. file_count=file_count,
  288. created_at=folder.created_at,
  289. updated_at=folder.updated_at,
  290. )
  291. )
  292. return folders
  293. @router.get("/folders/by-archive/{archive_id}", response_model=list[FolderResponse])
  294. async def get_folders_by_archive(
  295. archive_id: int,
  296. db: AsyncSession = Depends(get_db),
  297. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  298. ):
  299. """Get all folders linked to a specific archive."""
  300. result = await db.execute(
  301. select(LibraryFolder, PrintArchive.print_name)
  302. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  303. .where(LibraryFolder.archive_id == archive_id)
  304. .order_by(LibraryFolder.name)
  305. )
  306. rows = result.all()
  307. folders = []
  308. for folder, archive_name in rows:
  309. # Get file count
  310. file_count_result = await db.execute(
  311. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder.id)
  312. )
  313. file_count = file_count_result.scalar() or 0
  314. folders.append(
  315. FolderResponse(
  316. id=folder.id,
  317. name=folder.name,
  318. parent_id=folder.parent_id,
  319. project_id=folder.project_id,
  320. archive_id=folder.archive_id,
  321. project_name=None,
  322. archive_name=archive_name,
  323. is_external=folder.is_external,
  324. external_path=folder.external_path,
  325. external_readonly=folder.external_readonly,
  326. external_show_hidden=folder.external_show_hidden,
  327. file_count=file_count,
  328. created_at=folder.created_at,
  329. updated_at=folder.updated_at,
  330. )
  331. )
  332. return folders
  333. @router.post("/folders", response_model=FolderResponse)
  334. @router.post("/folders/", response_model=FolderResponse)
  335. async def create_folder(
  336. data: FolderCreate,
  337. db: AsyncSession = Depends(get_db),
  338. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  339. ):
  340. """Create a new folder."""
  341. # Verify parent exists if specified
  342. if data.parent_id is not None:
  343. parent_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.parent_id))
  344. if not parent_result.scalar_one_or_none():
  345. raise HTTPException(status_code=404, detail="Parent folder not found")
  346. # Verify project exists if specified
  347. project_name = None
  348. if data.project_id is not None:
  349. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  350. project = project_result.scalar_one_or_none()
  351. if not project:
  352. raise HTTPException(status_code=404, detail="Project not found")
  353. project_name = project.name
  354. # Verify archive exists if specified
  355. archive_name = None
  356. if data.archive_id is not None:
  357. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  358. archive = archive_result.scalar_one_or_none()
  359. if not archive:
  360. raise HTTPException(status_code=404, detail="Archive not found")
  361. archive_name = archive.print_name
  362. folder = LibraryFolder(
  363. name=data.name,
  364. parent_id=data.parent_id,
  365. project_id=data.project_id,
  366. archive_id=data.archive_id,
  367. )
  368. db.add(folder)
  369. await db.commit()
  370. await db.refresh(folder)
  371. return FolderResponse(
  372. id=folder.id,
  373. name=folder.name,
  374. parent_id=folder.parent_id,
  375. project_id=folder.project_id,
  376. archive_id=folder.archive_id,
  377. project_name=project_name,
  378. archive_name=archive_name,
  379. is_external=folder.is_external,
  380. external_path=folder.external_path,
  381. external_readonly=folder.external_readonly,
  382. external_show_hidden=folder.external_show_hidden,
  383. file_count=0,
  384. created_at=folder.created_at,
  385. updated_at=folder.updated_at,
  386. )
  387. @router.get("/folders/{folder_id}", response_model=FolderResponse)
  388. async def get_folder(
  389. folder_id: int,
  390. db: AsyncSession = Depends(get_db),
  391. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  392. ):
  393. """Get a folder by ID."""
  394. result = await db.execute(
  395. select(LibraryFolder, Project.name, PrintArchive.print_name)
  396. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  397. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  398. .where(LibraryFolder.id == folder_id)
  399. )
  400. row = result.one_or_none()
  401. if not row:
  402. raise HTTPException(status_code=404, detail="Folder not found")
  403. folder, project_name, archive_name = row
  404. # Get file count
  405. file_count_result = await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id))
  406. file_count = file_count_result.scalar() or 0
  407. return FolderResponse(
  408. id=folder.id,
  409. name=folder.name,
  410. parent_id=folder.parent_id,
  411. project_id=folder.project_id,
  412. archive_id=folder.archive_id,
  413. project_name=project_name,
  414. archive_name=archive_name,
  415. is_external=folder.is_external,
  416. external_path=folder.external_path,
  417. external_readonly=folder.external_readonly,
  418. external_show_hidden=folder.external_show_hidden,
  419. file_count=file_count,
  420. created_at=folder.created_at,
  421. updated_at=folder.updated_at,
  422. )
  423. @router.put("/folders/{folder_id}", response_model=FolderResponse)
  424. async def update_folder(
  425. folder_id: int,
  426. data: FolderUpdate,
  427. db: AsyncSession = Depends(get_db),
  428. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPDATE_ALL)),
  429. ):
  430. """Update a folder.
  431. Note: Folders require library:update_all permission since they don't have
  432. ownership tracking.
  433. """
  434. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  435. folder = result.scalar_one_or_none()
  436. if not folder:
  437. raise HTTPException(status_code=404, detail="Folder not found")
  438. if data.name is not None:
  439. folder.name = data.name
  440. if data.parent_id is not None:
  441. # Prevent circular reference
  442. if data.parent_id == folder_id:
  443. raise HTTPException(status_code=400, detail="Folder cannot be its own parent")
  444. # Check for circular reference in ancestors
  445. if data.parent_id != 0: # 0 means move to root
  446. current_id = data.parent_id
  447. while current_id is not None:
  448. if current_id == folder_id:
  449. raise HTTPException(status_code=400, detail="Cannot move folder into its own subtree")
  450. parent_result = await db.execute(select(LibraryFolder.parent_id).where(LibraryFolder.id == current_id))
  451. current_id = parent_result.scalar()
  452. folder.parent_id = data.parent_id
  453. else:
  454. folder.parent_id = None
  455. # Update project_id (0 to unlink)
  456. if data.project_id is not None:
  457. if data.project_id == 0:
  458. folder.project_id = None
  459. else:
  460. # Verify project exists
  461. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  462. if not project_result.scalar_one_or_none():
  463. raise HTTPException(status_code=404, detail="Project not found")
  464. folder.project_id = data.project_id
  465. # Update archive_id (0 to unlink)
  466. if data.archive_id is not None:
  467. if data.archive_id == 0:
  468. folder.archive_id = None
  469. else:
  470. # Verify archive exists
  471. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  472. if not archive_result.scalar_one_or_none():
  473. raise HTTPException(status_code=404, detail="Archive not found")
  474. folder.archive_id = data.archive_id
  475. await db.commit()
  476. await db.refresh(folder)
  477. # Get file count and names
  478. file_count_result = await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id))
  479. file_count = file_count_result.scalar() or 0
  480. # Get project and archive names
  481. project_name = None
  482. archive_name = None
  483. if folder.project_id:
  484. project_result = await db.execute(select(Project.name).where(Project.id == folder.project_id))
  485. project_name = project_result.scalar()
  486. if folder.archive_id:
  487. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == folder.archive_id))
  488. archive_name = archive_result.scalar()
  489. return FolderResponse(
  490. id=folder.id,
  491. name=folder.name,
  492. parent_id=folder.parent_id,
  493. project_id=folder.project_id,
  494. archive_id=folder.archive_id,
  495. project_name=project_name,
  496. archive_name=archive_name,
  497. is_external=folder.is_external,
  498. external_path=folder.external_path,
  499. external_readonly=folder.external_readonly,
  500. external_show_hidden=folder.external_show_hidden,
  501. file_count=file_count,
  502. created_at=folder.created_at,
  503. updated_at=folder.updated_at,
  504. )
  505. @router.delete("/folders/{folder_id}")
  506. async def delete_folder(
  507. folder_id: int,
  508. db: AsyncSession = Depends(get_db),
  509. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_DELETE_ALL)),
  510. ):
  511. """Delete a folder and all its contents (cascade).
  512. Note: Folders require library:delete_all permission since they don't have
  513. ownership tracking.
  514. """
  515. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  516. folder = result.scalar_one_or_none()
  517. if not folder:
  518. raise HTTPException(status_code=404, detail="Folder not found")
  519. # External folders: only remove DB records, never delete files from external path
  520. is_ext = folder.is_external
  521. # Get all files in this folder and subfolders to delete from disk
  522. async def get_all_file_ids(fid: int) -> list[int]:
  523. """Recursively get all file IDs in a folder tree."""
  524. file_ids = []
  525. # Get files in this folder
  526. files_result = await db.execute(
  527. select(LibraryFile.id, LibraryFile.file_path, LibraryFile.thumbnail_path, LibraryFile.is_external).where(
  528. LibraryFile.folder_id == fid
  529. )
  530. )
  531. for fid_val, file_path, thumb_path, file_is_ext in files_result.all():
  532. file_ids.append(fid_val)
  533. # Only delete non-external files from disk
  534. if not is_ext and not file_is_ext:
  535. try:
  536. if file_path and os.path.exists(file_path):
  537. os.remove(file_path)
  538. if thumb_path and os.path.exists(thumb_path):
  539. os.remove(thumb_path)
  540. except OSError as e:
  541. logger.warning("Failed to delete file: %s", e)
  542. # Get child folders and recurse
  543. children_result = await db.execute(select(LibraryFolder.id).where(LibraryFolder.parent_id == fid))
  544. for (child_id,) in children_result.all():
  545. file_ids.extend(await get_all_file_ids(child_id))
  546. return file_ids
  547. await get_all_file_ids(folder_id)
  548. # Delete folder (cascade will handle files and subfolders)
  549. await db.delete(folder)
  550. return {"status": "success", "message": "Folder deleted"}
  551. # ============ External Folder Endpoints ============
  552. # Blocked system directories that cannot be mounted
  553. _BLOCKED_PREFIXES = (
  554. "/proc",
  555. "/sys",
  556. "/dev",
  557. "/run",
  558. "/boot",
  559. "/sbin",
  560. "/bin",
  561. "/usr/sbin",
  562. "/usr/bin",
  563. "/lib",
  564. "/etc",
  565. )
  566. # Supported file extensions for external folder scanning
  567. _SCANNABLE_EXTENSIONS = {
  568. ".3mf",
  569. ".gcode",
  570. ".gcode.3mf",
  571. ".stl",
  572. ".obj",
  573. ".step",
  574. ".stp",
  575. ".png",
  576. ".jpg",
  577. ".jpeg",
  578. ".gif",
  579. ".webp",
  580. ".svg",
  581. }
  582. def _validate_external_path(path_str: str) -> Path:
  583. """Validate an external path is safe to mount."""
  584. path = Path(path_str).resolve()
  585. if not path.is_absolute():
  586. raise HTTPException(status_code=400, detail="Path must be absolute")
  587. for prefix in _BLOCKED_PREFIXES:
  588. if str(path).startswith(prefix):
  589. raise HTTPException(status_code=400, detail=f"Cannot mount system directory: {prefix}")
  590. if not path.exists():
  591. raise HTTPException(status_code=400, detail=f"Path does not exist: {path}")
  592. if not path.is_dir():
  593. raise HTTPException(status_code=400, detail=f"Path is not a directory: {path}")
  594. # Check readability
  595. if not os.access(path, os.R_OK):
  596. raise HTTPException(status_code=400, detail=f"Path is not readable: {path}")
  597. return path
  598. @router.post("/folders/external", response_model=FolderResponse)
  599. async def create_external_folder(
  600. data: ExternalFolderCreate,
  601. db: AsyncSession = Depends(get_db),
  602. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  603. ):
  604. """Create an external folder that points to a host directory."""
  605. resolved = _validate_external_path(data.external_path)
  606. # Check no other external folder already points to this path
  607. existing = await db.execute(
  608. select(LibraryFolder).where(
  609. LibraryFolder.is_external.is_(True),
  610. LibraryFolder.external_path == str(resolved),
  611. )
  612. )
  613. if existing.scalar_one_or_none():
  614. raise HTTPException(status_code=409, detail="An external folder already exists for this path")
  615. # Verify parent exists if specified
  616. if data.parent_id is not None:
  617. parent_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.parent_id))
  618. if not parent_result.scalar_one_or_none():
  619. raise HTTPException(status_code=404, detail="Parent folder not found")
  620. folder = LibraryFolder(
  621. name=data.name,
  622. parent_id=data.parent_id,
  623. is_external=True,
  624. external_path=str(resolved),
  625. external_readonly=data.readonly,
  626. external_show_hidden=data.show_hidden,
  627. )
  628. db.add(folder)
  629. await db.commit()
  630. await db.refresh(folder)
  631. return FolderResponse(
  632. id=folder.id,
  633. name=folder.name,
  634. parent_id=folder.parent_id,
  635. project_id=None,
  636. archive_id=None,
  637. is_external=True,
  638. external_path=folder.external_path,
  639. external_readonly=folder.external_readonly,
  640. external_show_hidden=folder.external_show_hidden,
  641. file_count=0,
  642. created_at=folder.created_at,
  643. updated_at=folder.updated_at,
  644. )
  645. @router.post("/folders/{folder_id}/scan")
  646. async def scan_external_folder(
  647. folder_id: int,
  648. db: AsyncSession = Depends(get_db),
  649. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  650. ):
  651. """Scan an external folder and sync files to the database.
  652. Discovers new files, removes DB entries for deleted files.
  653. Does not copy files — stores the external path directly.
  654. """
  655. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  656. folder = result.scalar_one_or_none()
  657. if not folder:
  658. raise HTTPException(status_code=404, detail="Folder not found")
  659. if not folder.is_external or not folder.external_path:
  660. raise HTTPException(status_code=400, detail="Not an external folder")
  661. ext_path = Path(folder.external_path)
  662. if not ext_path.exists() or not ext_path.is_dir():
  663. raise HTTPException(status_code=400, detail=f"External path is not accessible: {folder.external_path}")
  664. # Get existing DB files for this folder
  665. existing_result = await db.execute(
  666. select(LibraryFile).where(LibraryFile.folder_id == folder_id, LibraryFile.is_external.is_(True))
  667. )
  668. existing_files = {f.file_path: f for f in existing_result.scalars().all()}
  669. # Scan the directory
  670. added = 0
  671. removed = 0
  672. found_paths = set()
  673. for dirpath, _dirnames, filenames in os.walk(ext_path):
  674. for filename in filenames:
  675. # Skip hidden files unless configured
  676. if not folder.external_show_hidden and filename.startswith("."):
  677. continue
  678. filepath = Path(dirpath) / filename
  679. ext = filepath.suffix.lower()
  680. # Check for compound extensions like .gcode.3mf
  681. if ext not in _SCANNABLE_EXTENSIONS:
  682. # Check compound
  683. compound = "".join(filepath.suffixes[-2:]).lower() if len(filepath.suffixes) >= 2 else ""
  684. if compound not in _SCANNABLE_EXTENSIONS:
  685. continue
  686. # Resolve symlinks and ensure still under external_path
  687. try:
  688. real_path = filepath.resolve()
  689. real_path.relative_to(ext_path.resolve())
  690. except (ValueError, OSError):
  691. continue # Symlink escapes the external dir
  692. file_path_str = str(filepath)
  693. found_paths.add(file_path_str)
  694. if file_path_str in existing_files:
  695. continue # Already tracked
  696. # Get file info
  697. try:
  698. stat = filepath.stat()
  699. except OSError:
  700. continue
  701. file_type = ext[1:] if ext else "unknown"
  702. # For compound extensions, use the meaningful part
  703. if file_type in ("3mf",) and len(filepath.suffixes) >= 2:
  704. inner = filepath.suffixes[-2].lower()
  705. if inner == ".gcode":
  706. file_type = "gcode.3mf"
  707. # Extract thumbnail for 3mf files
  708. thumbnail_path = None
  709. file_metadata = None
  710. if file_type == "3mf":
  711. try:
  712. parser = ThreeMFParser(str(filepath))
  713. meta = parser.parse()
  714. if meta:
  715. file_metadata = meta
  716. thumb_data = parser.extract_thumbnail()
  717. if thumb_data:
  718. thumb_dir = get_library_thumbnails_dir()
  719. thumb_filename = f"{uuid.uuid4().hex}.png"
  720. thumb_full = thumb_dir / thumb_filename
  721. thumb_full.write_bytes(thumb_data)
  722. thumbnail_path = to_relative_path(thumb_full)
  723. except Exception as e:
  724. logger.debug("Failed to extract metadata from external 3mf %s: %s", filepath, e)
  725. # Generate thumbnail for STL files
  726. if file_type == "stl" and thumbnail_path is None:
  727. try:
  728. thumb_dir = get_library_thumbnails_dir()
  729. thumb_result = generate_stl_thumbnail(str(filepath), str(thumb_dir))
  730. if thumb_result:
  731. thumbnail_path = to_relative_path(Path(thumb_result))
  732. except Exception as e:
  733. logger.debug("Failed to generate STL thumbnail for external %s: %s", filepath, e)
  734. # Extract gcode thumbnail
  735. if file_type == "gcode" and thumbnail_path is None:
  736. thumb_data = extract_gcode_thumbnail(filepath)
  737. if thumb_data:
  738. thumb_dir = get_library_thumbnails_dir()
  739. thumb_filename = f"{uuid.uuid4().hex}.png"
  740. thumb_full = thumb_dir / thumb_filename
  741. thumb_full.write_bytes(thumb_data)
  742. thumbnail_path = to_relative_path(thumb_full)
  743. db_file = LibraryFile(
  744. folder_id=folder_id,
  745. is_external=True,
  746. filename=filename,
  747. file_path=file_path_str,
  748. file_type=file_type,
  749. file_size=stat.st_size,
  750. file_hash=None, # Skip hashing external files for performance
  751. thumbnail_path=thumbnail_path,
  752. file_metadata=file_metadata,
  753. )
  754. db.add(db_file)
  755. added += 1
  756. # Remove DB entries for files that no longer exist on disk
  757. for path_str, db_file in existing_files.items():
  758. if path_str not in found_paths:
  759. # Clean up thumbnail if we generated one
  760. if db_file.thumbnail_path:
  761. try:
  762. abs_thumb = to_absolute_path(db_file.thumbnail_path)
  763. if abs_thumb and abs_thumb.exists():
  764. abs_thumb.unlink()
  765. except OSError:
  766. pass
  767. await db.delete(db_file)
  768. removed += 1
  769. await db.commit()
  770. return {"status": "success", "added": added, "removed": removed}
  771. # ============ File Endpoints ============
  772. @router.get("/files", response_model=list[FileListResponse])
  773. @router.get("/files/", response_model=list[FileListResponse])
  774. async def list_files(
  775. response: Response,
  776. folder_id: int | None = None,
  777. include_root: bool = True,
  778. db: AsyncSession = Depends(get_db),
  779. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  780. ):
  781. """List files, optionally filtered by folder.
  782. Args:
  783. folder_id: Filter by folder ID. If None and include_root=True, returns root files.
  784. include_root: If True and folder_id is None, returns files at root level.
  785. If False and folder_id is None, returns all files.
  786. """
  787. query = select(LibraryFile).options(selectinload(LibraryFile.created_by))
  788. if folder_id is not None:
  789. query = query.where(LibraryFile.folder_id == folder_id)
  790. elif include_root:
  791. query = query.where(LibraryFile.folder_id.is_(None))
  792. query = query.order_by(LibraryFile.filename)
  793. result = await db.execute(query)
  794. files = result.scalars().all()
  795. # Get duplicate counts
  796. hash_counts = {}
  797. if files:
  798. hashes = [f.file_hash for f in files if f.file_hash]
  799. if hashes:
  800. dup_result = await db.execute(
  801. select(LibraryFile.file_hash, func.count(LibraryFile.id))
  802. .where(LibraryFile.file_hash.in_(hashes))
  803. .group_by(LibraryFile.file_hash)
  804. )
  805. hash_counts = {h: c - 1 for h, c in dup_result.all()} # -1 to exclude self
  806. # Prevent browser caching of file list
  807. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  808. file_list = []
  809. for f in files:
  810. # Extract key metadata for display
  811. print_name = None
  812. print_time = None
  813. filament_grams = None
  814. sliced_for_model = None
  815. if f.file_metadata:
  816. print_name = f.file_metadata.get("print_name")
  817. print_time = f.file_metadata.get("print_time_seconds")
  818. filament_grams = f.file_metadata.get("filament_used_grams")
  819. sliced_for_model = f.file_metadata.get("sliced_for_model")
  820. file_list.append(
  821. FileListResponse(
  822. id=f.id,
  823. folder_id=f.folder_id,
  824. is_external=f.is_external,
  825. filename=f.filename,
  826. file_type=f.file_type,
  827. file_size=f.file_size,
  828. thumbnail_path=f.thumbnail_path,
  829. print_count=f.print_count,
  830. duplicate_count=hash_counts.get(f.file_hash, 0) if f.file_hash else 0,
  831. created_by_id=f.created_by_id,
  832. created_by_username=f.created_by.username if f.created_by else None,
  833. created_at=f.created_at,
  834. print_name=print_name,
  835. print_time_seconds=print_time,
  836. filament_used_grams=filament_grams,
  837. sliced_for_model=sliced_for_model,
  838. )
  839. )
  840. return file_list
  841. @router.post("/files", response_model=FileUploadResponse)
  842. @router.post("/files/", response_model=FileUploadResponse)
  843. async def upload_file(
  844. file: UploadFile = File(...),
  845. folder_id: int | None = None,
  846. generate_stl_thumbnails: bool = Query(default=True),
  847. db: AsyncSession = Depends(get_db),
  848. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  849. ):
  850. """Upload a file to the library."""
  851. try:
  852. if not file.filename:
  853. raise HTTPException(status_code=400, detail="Filename is required")
  854. filename = file.filename
  855. ext = os.path.splitext(filename)[1].lower()
  856. # Handle files without extension
  857. file_type = ext[1:] if ext else "unknown"
  858. # Verify folder exists if specified
  859. if folder_id is not None:
  860. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  861. target_folder = folder_result.scalar_one_or_none()
  862. if not target_folder:
  863. raise HTTPException(status_code=404, detail="Folder not found")
  864. if target_folder.is_external and target_folder.external_readonly:
  865. raise HTTPException(status_code=403, detail="Cannot upload to a read-only external folder")
  866. # Generate unique filename for storage
  867. unique_filename = f"{uuid.uuid4().hex}{ext}"
  868. file_path = get_library_files_dir() / unique_filename
  869. # Save file
  870. content = await file.read()
  871. with open(file_path, "wb") as f:
  872. f.write(content)
  873. # Calculate hash
  874. file_hash = calculate_file_hash(file_path)
  875. # Check for duplicates
  876. dup_result = await db.execute(select(LibraryFile.id).where(LibraryFile.file_hash == file_hash).limit(1))
  877. duplicate_of = dup_result.scalar()
  878. # Extract metadata and thumbnail
  879. metadata = {}
  880. thumbnail_path = None
  881. thumbnails_dir = get_library_thumbnails_dir()
  882. if ext == ".3mf":
  883. try:
  884. parser = ThreeMFParser(str(file_path))
  885. raw_metadata = parser.parse()
  886. # Extract thumbnail before cleaning metadata
  887. thumbnail_data = raw_metadata.get("_thumbnail_data")
  888. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  889. # Save thumbnail if extracted
  890. if thumbnail_data:
  891. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  892. thumb_path = thumbnails_dir / thumb_filename
  893. with open(thumb_path, "wb") as f:
  894. f.write(thumbnail_data)
  895. thumbnail_path = str(thumb_path)
  896. # Clean metadata - remove non-JSON-serializable data (bytes, etc.)
  897. def clean_metadata(obj):
  898. if isinstance(obj, dict):
  899. return {
  900. k: clean_metadata(v)
  901. for k, v in obj.items()
  902. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  903. }
  904. elif isinstance(obj, list):
  905. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  906. elif isinstance(obj, bytes):
  907. return None
  908. return obj
  909. metadata = clean_metadata(raw_metadata)
  910. except Exception as e:
  911. logger.warning("Failed to parse 3MF: %s", e)
  912. elif ext == ".gcode":
  913. # Extract embedded thumbnail from gcode
  914. try:
  915. thumbnail_data = extract_gcode_thumbnail(file_path)
  916. if thumbnail_data:
  917. thumb_filename = f"{uuid.uuid4().hex}.png"
  918. thumb_path = thumbnails_dir / thumb_filename
  919. with open(thumb_path, "wb") as f:
  920. f.write(thumbnail_data)
  921. thumbnail_path = str(thumb_path)
  922. except Exception as e:
  923. logger.warning("Failed to extract gcode thumbnail: %s", e)
  924. elif ext.lower() in IMAGE_EXTENSIONS:
  925. # For image files, create a thumbnail from the image itself
  926. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  927. elif ext == ".stl":
  928. # Generate STL thumbnail if enabled
  929. if generate_stl_thumbnails:
  930. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  931. # Create database entry (store relative paths for portability)
  932. library_file = LibraryFile(
  933. folder_id=folder_id,
  934. filename=filename,
  935. file_path=to_relative_path(file_path),
  936. file_type=file_type,
  937. file_size=len(content),
  938. file_hash=file_hash,
  939. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  940. file_metadata=metadata if metadata else None,
  941. created_by_id=current_user.id if current_user else None,
  942. )
  943. db.add(library_file)
  944. await db.commit()
  945. await db.refresh(library_file)
  946. return FileUploadResponse(
  947. id=library_file.id,
  948. filename=library_file.filename,
  949. file_type=library_file.file_type,
  950. file_size=library_file.file_size,
  951. thumbnail_path=library_file.thumbnail_path,
  952. duplicate_of=duplicate_of,
  953. metadata=library_file.file_metadata,
  954. )
  955. except HTTPException:
  956. raise
  957. except Exception as e:
  958. logger.error("Upload failed for %s: %s", file.filename, e, exc_info=True)
  959. raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
  960. @router.post("/files/extract-zip", response_model=ZipExtractResponse)
  961. async def extract_zip_file(
  962. file: UploadFile = File(...),
  963. folder_id: int | None = Query(default=None),
  964. preserve_structure: bool = Query(default=True),
  965. create_folder_from_zip: bool = Query(default=False),
  966. generate_stl_thumbnails: bool = Query(default=True),
  967. db: AsyncSession = Depends(get_db),
  968. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  969. ):
  970. """Upload and extract a ZIP file to the library.
  971. Args:
  972. file: The ZIP file to extract
  973. folder_id: Target folder ID (None = root)
  974. preserve_structure: If True, recreate folder structure from ZIP; if False, extract all files flat
  975. create_folder_from_zip: If True, create a folder named after the ZIP file and extract into it
  976. generate_stl_thumbnails: If True, generate thumbnails for STL files
  977. """
  978. import tempfile
  979. if not file.filename or not file.filename.lower().endswith(".zip"):
  980. raise HTTPException(status_code=400, detail="Only ZIP files are supported")
  981. # Verify target folder exists if specified
  982. if folder_id is not None:
  983. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  984. target_folder = folder_result.scalar_one_or_none()
  985. if not target_folder:
  986. raise HTTPException(status_code=404, detail="Target folder not found")
  987. if target_folder.is_external and target_folder.external_readonly:
  988. raise HTTPException(status_code=403, detail="Cannot extract ZIP to a read-only external folder")
  989. # Save ZIP to temp file
  990. try:
  991. with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp:
  992. content = await file.read()
  993. tmp.write(content)
  994. tmp_path = tmp.name
  995. except Exception as e:
  996. raise HTTPException(status_code=500, detail=f"Failed to save ZIP file: {str(e)}")
  997. extracted_files: list[ZipExtractResult] = []
  998. errors: list[ZipExtractError] = []
  999. folders_created = 0
  1000. folder_cache: dict[str, int] = {} # path -> folder_id
  1001. # If create_folder_from_zip is True, create a folder named after the ZIP file
  1002. zip_folder_id = folder_id
  1003. logger.info(
  1004. f"ZIP extraction: create_folder_from_zip={create_folder_from_zip}, folder_id={folder_id}, filename={file.filename}"
  1005. )
  1006. if create_folder_from_zip and file.filename:
  1007. # Remove .zip extension to get folder name
  1008. zip_folder_name = file.filename[:-4] if file.filename.lower().endswith(".zip") else file.filename
  1009. # Check if folder already exists
  1010. existing = await db.execute(
  1011. select(LibraryFolder).where(
  1012. LibraryFolder.name == zip_folder_name,
  1013. LibraryFolder.parent_id == folder_id if folder_id else LibraryFolder.parent_id.is_(None),
  1014. )
  1015. )
  1016. existing_folder = existing.scalar_one_or_none()
  1017. if existing_folder:
  1018. zip_folder_id = existing_folder.id
  1019. logger.info("Reusing existing folder '%s' with id=%s", zip_folder_name, zip_folder_id)
  1020. else:
  1021. # Create folder
  1022. new_folder = LibraryFolder(name=zip_folder_name, parent_id=folder_id)
  1023. db.add(new_folder)
  1024. await db.flush()
  1025. await db.commit() # Commit folder creation immediately
  1026. zip_folder_id = new_folder.id
  1027. folders_created += 1
  1028. logger.info("Created new folder '%s' with id=%s", zip_folder_name, zip_folder_id)
  1029. try:
  1030. with zipfile.ZipFile(tmp_path, "r") as zf:
  1031. # Filter out directories and hidden/system files
  1032. file_list = [
  1033. name
  1034. for name in zf.namelist()
  1035. if not name.endswith("/")
  1036. and not name.startswith("__MACOSX")
  1037. and not os.path.basename(name).startswith(".")
  1038. ]
  1039. for zip_path in file_list:
  1040. try:
  1041. # Determine target folder (use zip_folder_id as base if create_folder_from_zip was used)
  1042. target_folder_id = zip_folder_id
  1043. if preserve_structure:
  1044. # Get directory path from ZIP
  1045. dir_path = os.path.dirname(zip_path)
  1046. if dir_path:
  1047. # Create folder structure
  1048. parts = dir_path.split("/")
  1049. current_parent = zip_folder_id
  1050. current_path = ""
  1051. for part in parts:
  1052. if not part:
  1053. continue
  1054. current_path = f"{current_path}/{part}" if current_path else part
  1055. if current_path in folder_cache:
  1056. current_parent = folder_cache[current_path]
  1057. else:
  1058. # Check if folder exists
  1059. existing = await db.execute(
  1060. select(LibraryFolder).where(
  1061. LibraryFolder.name == part,
  1062. LibraryFolder.parent_id == current_parent
  1063. if current_parent
  1064. else LibraryFolder.parent_id.is_(None),
  1065. )
  1066. )
  1067. existing_folder = existing.scalar_one_or_none()
  1068. if existing_folder:
  1069. current_parent = existing_folder.id
  1070. else:
  1071. # Create folder
  1072. new_folder = LibraryFolder(name=part, parent_id=current_parent)
  1073. db.add(new_folder)
  1074. await db.flush()
  1075. current_parent = new_folder.id
  1076. folders_created += 1
  1077. folder_cache[current_path] = current_parent
  1078. target_folder_id = current_parent
  1079. # Extract file
  1080. filename = os.path.basename(zip_path)
  1081. ext = os.path.splitext(filename)[1].lower()
  1082. file_type = ext[1:] if ext else "unknown"
  1083. # Generate unique filename for storage
  1084. unique_filename = f"{uuid.uuid4().hex}{ext}"
  1085. file_path = get_library_files_dir() / unique_filename
  1086. # Extract and save file
  1087. file_content = zf.read(zip_path)
  1088. with open(file_path, "wb") as f:
  1089. f.write(file_content)
  1090. # Calculate hash
  1091. file_hash = calculate_file_hash(file_path)
  1092. # Extract metadata and thumbnail for 3MF files
  1093. metadata = {}
  1094. thumbnail_path = None
  1095. thumbnails_dir = get_library_thumbnails_dir()
  1096. if ext == ".3mf":
  1097. try:
  1098. parser = ThreeMFParser(str(file_path))
  1099. raw_metadata = parser.parse()
  1100. thumbnail_data = raw_metadata.get("_thumbnail_data")
  1101. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  1102. if thumbnail_data:
  1103. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  1104. thumb_path = thumbnails_dir / thumb_filename
  1105. with open(thumb_path, "wb") as f:
  1106. f.write(thumbnail_data)
  1107. thumbnail_path = str(thumb_path)
  1108. def clean_metadata(obj):
  1109. if isinstance(obj, dict):
  1110. return {
  1111. k: clean_metadata(v)
  1112. for k, v in obj.items()
  1113. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  1114. }
  1115. elif isinstance(obj, list):
  1116. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  1117. elif isinstance(obj, bytes):
  1118. return None
  1119. return obj
  1120. metadata = clean_metadata(raw_metadata)
  1121. except Exception as e:
  1122. logger.warning("Failed to parse 3MF from ZIP: %s", e)
  1123. elif ext == ".gcode":
  1124. try:
  1125. thumbnail_data = extract_gcode_thumbnail(file_path)
  1126. if thumbnail_data:
  1127. thumb_filename = f"{uuid.uuid4().hex}.png"
  1128. thumb_path = thumbnails_dir / thumb_filename
  1129. with open(thumb_path, "wb") as f:
  1130. f.write(thumbnail_data)
  1131. thumbnail_path = str(thumb_path)
  1132. except Exception as e:
  1133. logger.warning("Failed to extract gcode thumbnail from ZIP: %s", e)
  1134. elif ext.lower() in IMAGE_EXTENSIONS:
  1135. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  1136. elif ext == ".stl":
  1137. # Generate STL thumbnail if enabled
  1138. if generate_stl_thumbnails:
  1139. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  1140. # Create database entry (store relative paths for portability)
  1141. library_file = LibraryFile(
  1142. folder_id=target_folder_id,
  1143. filename=filename,
  1144. file_path=to_relative_path(file_path),
  1145. file_type=file_type,
  1146. file_size=len(file_content),
  1147. file_hash=file_hash,
  1148. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  1149. file_metadata=metadata if metadata else None,
  1150. created_by_id=current_user.id if current_user else None,
  1151. )
  1152. db.add(library_file)
  1153. await db.flush()
  1154. await db.refresh(library_file)
  1155. extracted_files.append(
  1156. ZipExtractResult(
  1157. filename=filename,
  1158. file_id=library_file.id,
  1159. folder_id=target_folder_id,
  1160. )
  1161. )
  1162. # Commit after each file to release database lock
  1163. # This prevents long-running transactions from blocking other requests
  1164. await db.commit()
  1165. except Exception as e:
  1166. logger.error("Failed to extract %s: %s", zip_path, e)
  1167. errors.append(ZipExtractError(filename=os.path.basename(zip_path), error=str(e)))
  1168. # Rollback the failed file but continue with others
  1169. await db.rollback()
  1170. return ZipExtractResponse(
  1171. extracted=len(extracted_files),
  1172. folders_created=folders_created,
  1173. files=extracted_files,
  1174. errors=errors,
  1175. )
  1176. except zipfile.BadZipFile:
  1177. raise HTTPException(status_code=400, detail="Invalid or corrupted ZIP file")
  1178. except Exception as e:
  1179. logger.error("ZIP extraction failed: %s", e, exc_info=True)
  1180. raise HTTPException(status_code=500, detail=f"ZIP extraction failed: {str(e)}")
  1181. finally:
  1182. # Clean up temp file
  1183. try:
  1184. os.unlink(tmp_path)
  1185. except OSError:
  1186. pass # Best-effort temp file cleanup; ignore if already removed
  1187. # ============ STL Thumbnail Batch Generation ============
  1188. @router.post("/generate-stl-thumbnails", response_model=BatchThumbnailResponse)
  1189. async def batch_generate_stl_thumbnails(
  1190. request: BatchThumbnailRequest,
  1191. db: AsyncSession = Depends(get_db),
  1192. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPDATE_ALL)),
  1193. ):
  1194. """Generate thumbnails for STL files in batch.
  1195. Note: Requires library:update_all permission since this is a batch operation
  1196. that may affect files owned by different users.
  1197. Can generate thumbnails for:
  1198. - Specific file IDs (file_ids)
  1199. - All STL files in a folder (folder_id)
  1200. - All STL files missing thumbnails (all_missing=True)
  1201. """
  1202. thumbnails_dir = get_library_thumbnails_dir()
  1203. results: list[BatchThumbnailResult] = []
  1204. # Build query based on request
  1205. query = select(LibraryFile).where(LibraryFile.file_type == "stl")
  1206. if request.file_ids:
  1207. # Specific files
  1208. query = query.where(LibraryFile.id.in_(request.file_ids))
  1209. elif request.folder_id is not None:
  1210. # All STL files in a specific folder
  1211. query = query.where(LibraryFile.folder_id == request.folder_id)
  1212. if not request.all_missing:
  1213. # If not specifically asking for missing thumbnails, get all
  1214. pass
  1215. else:
  1216. query = query.where(LibraryFile.thumbnail_path.is_(None))
  1217. elif request.all_missing:
  1218. # All STL files without thumbnails
  1219. query = query.where(LibraryFile.thumbnail_path.is_(None))
  1220. else:
  1221. # No criteria specified - return empty
  1222. return BatchThumbnailResponse(
  1223. processed=0,
  1224. succeeded=0,
  1225. failed=0,
  1226. results=[],
  1227. )
  1228. result = await db.execute(query)
  1229. stl_files = result.scalars().all()
  1230. succeeded = 0
  1231. failed = 0
  1232. for stl_file in stl_files:
  1233. file_path = to_absolute_path(stl_file.file_path)
  1234. if not file_path or not file_path.exists():
  1235. results.append(
  1236. BatchThumbnailResult(
  1237. file_id=stl_file.id,
  1238. filename=stl_file.filename,
  1239. success=False,
  1240. error="File not found on disk",
  1241. )
  1242. )
  1243. failed += 1
  1244. continue
  1245. try:
  1246. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  1247. if thumbnail_path:
  1248. # Update database with relative path
  1249. stl_file.thumbnail_path = to_relative_path(thumbnail_path)
  1250. await db.flush()
  1251. results.append(
  1252. BatchThumbnailResult(
  1253. file_id=stl_file.id,
  1254. filename=stl_file.filename,
  1255. success=True,
  1256. )
  1257. )
  1258. succeeded += 1
  1259. else:
  1260. results.append(
  1261. BatchThumbnailResult(
  1262. file_id=stl_file.id,
  1263. filename=stl_file.filename,
  1264. success=False,
  1265. error="Thumbnail generation failed",
  1266. )
  1267. )
  1268. failed += 1
  1269. except Exception as e:
  1270. logger.error("Failed to generate thumbnail for %s: %s", stl_file.filename, e)
  1271. results.append(
  1272. BatchThumbnailResult(
  1273. file_id=stl_file.id,
  1274. filename=stl_file.filename,
  1275. success=False,
  1276. error=str(e),
  1277. )
  1278. )
  1279. failed += 1
  1280. await db.commit()
  1281. return BatchThumbnailResponse(
  1282. processed=len(stl_files),
  1283. succeeded=succeeded,
  1284. failed=failed,
  1285. results=results,
  1286. )
  1287. # ============ Queue Operations ============
  1288. # NOTE: These routes must be defined BEFORE /files/{file_id} to avoid path parameter conflicts
  1289. def is_sliced_file(filename: str) -> bool:
  1290. """Check if a file is a sliced (printable) file.
  1291. Sliced files are:
  1292. - .gcode files
  1293. - .3mf files that contain '.gcode.' in the name (e.g., filename.gcode.3mf)
  1294. """
  1295. lower = filename.lower()
  1296. return lower.endswith(".gcode") or ".gcode." in lower
  1297. @router.post("/files/add-to-queue", response_model=AddToQueueResponse)
  1298. async def add_files_to_queue(
  1299. request: AddToQueueRequest,
  1300. db: AsyncSession = Depends(get_db),
  1301. _: User | None = Depends(require_permission_if_auth_enabled(Permission.QUEUE_CREATE)),
  1302. ):
  1303. """Add library files to the print queue.
  1304. Only sliced files (.gcode or .gcode.3mf) can be added to the queue.
  1305. The archive will be created automatically when the print starts.
  1306. """
  1307. added: list[AddToQueueResult] = []
  1308. errors: list[AddToQueueError] = []
  1309. # Get all requested files
  1310. result = await db.execute(select(LibraryFile).where(LibraryFile.id.in_(request.file_ids)))
  1311. files = {f.id: f for f in result.scalars().all()}
  1312. # Get max position for queue ordering
  1313. pos_result = await db.execute(select(func.coalesce(func.max(PrintQueueItem.position), 0)))
  1314. max_position = pos_result.scalar() or 0
  1315. for file_id in request.file_ids:
  1316. lib_file = files.get(file_id)
  1317. if not lib_file:
  1318. errors.append(AddToQueueError(file_id=file_id, filename="(not found)", error="File not found"))
  1319. continue
  1320. # Validate file is sliced
  1321. if not is_sliced_file(lib_file.filename):
  1322. errors.append(
  1323. AddToQueueError(
  1324. file_id=file_id,
  1325. filename=lib_file.filename,
  1326. error="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1327. )
  1328. )
  1329. continue
  1330. try:
  1331. # Verify file exists on disk
  1332. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1333. if not file_path.exists():
  1334. errors.append(
  1335. AddToQueueError(file_id=file_id, filename=lib_file.filename, error="File not found on disk")
  1336. )
  1337. continue
  1338. # Create queue item referencing library file (archive created at print start)
  1339. max_position += 1
  1340. queue_item = PrintQueueItem(
  1341. printer_id=None, # Unassigned
  1342. library_file_id=file_id,
  1343. position=max_position,
  1344. status="pending",
  1345. )
  1346. db.add(queue_item)
  1347. await db.flush() # Get queue_item.id
  1348. added.append(
  1349. AddToQueueResult(
  1350. file_id=file_id,
  1351. filename=lib_file.filename,
  1352. queue_item_id=queue_item.id,
  1353. )
  1354. )
  1355. except Exception as e:
  1356. logger.exception("Error adding file %s to queue", file_id)
  1357. errors.append(AddToQueueError(file_id=file_id, filename=lib_file.filename, error=str(e)))
  1358. await db.commit()
  1359. return AddToQueueResponse(added=added, errors=errors)
  1360. @router.get("/files/{file_id}/plates")
  1361. async def get_library_file_plates(
  1362. file_id: int,
  1363. db: AsyncSession = Depends(get_db),
  1364. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1365. ):
  1366. """Get available plates from a multi-plate 3MF library file.
  1367. Returns a list of plates with their index, name, thumbnail availability,
  1368. and filament requirements. For single-plate exports, returns a single plate.
  1369. """
  1370. import json
  1371. import defusedxml.ElementTree as ET
  1372. # Get the library file
  1373. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1374. lib_file = result.scalar_one_or_none()
  1375. if not lib_file:
  1376. raise HTTPException(status_code=404, detail="File not found")
  1377. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1378. if not file_path.exists():
  1379. raise HTTPException(status_code=404, detail="File not found on disk")
  1380. # Only 3MF files have plates
  1381. if not lib_file.filename.lower().endswith(".3mf"):
  1382. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1383. plates = []
  1384. try:
  1385. with zipfile.ZipFile(file_path, "r") as zf:
  1386. namelist = zf.namelist()
  1387. # Find all plate gcode files to determine available plates
  1388. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1389. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  1390. plate_indices: list[int] = []
  1391. if gcode_files:
  1392. # Extract plate indices from gcode filenames
  1393. for gf in gcode_files:
  1394. try:
  1395. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1396. plate_indices.append(int(plate_str))
  1397. except ValueError:
  1398. pass # Skip gcode file with non-numeric plate index
  1399. else:
  1400. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  1401. plate_png_files = [
  1402. n
  1403. for n in namelist
  1404. if n.startswith("Metadata/plate_")
  1405. and n.endswith(".png")
  1406. and "_small" not in n
  1407. and "no_light" not in n
  1408. ]
  1409. plate_name_candidates = plate_json_files + plate_png_files
  1410. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  1411. seen_indices: set[int] = set()
  1412. for name in plate_name_candidates:
  1413. match = plate_re.match(name)
  1414. if match:
  1415. try:
  1416. index = int(match.group(1))
  1417. except ValueError:
  1418. continue
  1419. if index in seen_indices:
  1420. continue
  1421. seen_indices.add(index)
  1422. plate_indices.append(index)
  1423. if not plate_indices:
  1424. # No plate metadata found
  1425. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1426. plate_indices.sort()
  1427. # Parse model_settings.config for plate names + object assignments
  1428. plate_names = {}
  1429. plate_object_ids: dict[int, list[str]] = {}
  1430. object_names_by_id: dict[str, str] = {}
  1431. if "Metadata/model_settings.config" in namelist:
  1432. try:
  1433. model_content = zf.read("Metadata/model_settings.config").decode()
  1434. model_root = ET.fromstring(model_content)
  1435. for obj_elem in model_root.findall(".//object"):
  1436. obj_id = obj_elem.get("id")
  1437. if not obj_id:
  1438. continue
  1439. name_meta = obj_elem.find("metadata[@key='name']")
  1440. obj_name = name_meta.get("value") if name_meta is not None else None
  1441. if obj_name:
  1442. object_names_by_id[obj_id] = obj_name
  1443. for plate_elem in model_root.findall(".//plate"):
  1444. plater_id = None
  1445. plater_name = None
  1446. for meta in plate_elem.findall("metadata"):
  1447. key = meta.get("key")
  1448. value = meta.get("value")
  1449. if key == "plater_id" and value:
  1450. try:
  1451. plater_id = int(value)
  1452. except ValueError:
  1453. pass # Ignore plate with non-numeric plater_id
  1454. elif key == "plater_name" and value:
  1455. plater_name = value.strip()
  1456. if plater_id is not None and plater_name:
  1457. plate_names[plater_id] = plater_name
  1458. if plater_id is not None:
  1459. for instance_elem in plate_elem.findall("model_instance"):
  1460. for inst_meta in instance_elem.findall("metadata"):
  1461. if inst_meta.get("key") == "object_id":
  1462. obj_id = inst_meta.get("value")
  1463. if not obj_id:
  1464. continue
  1465. plate_object_ids.setdefault(plater_id, [])
  1466. if obj_id not in plate_object_ids[plater_id]:
  1467. plate_object_ids[plater_id].append(obj_id)
  1468. except Exception:
  1469. pass # model_settings.config is optional; skip if missing or malformed
  1470. # Parse slice_info.config for plate metadata
  1471. plate_metadata = {}
  1472. if "Metadata/slice_info.config" in namelist:
  1473. content = zf.read("Metadata/slice_info.config").decode()
  1474. root = ET.fromstring(content)
  1475. for plate_elem in root.findall(".//plate"):
  1476. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1477. plate_index = None
  1478. for meta in plate_elem.findall("metadata"):
  1479. key = meta.get("key")
  1480. value = meta.get("value")
  1481. if key == "index" and value:
  1482. try:
  1483. plate_index = int(value)
  1484. except ValueError:
  1485. pass # Ignore plate with non-numeric index
  1486. elif key == "prediction" and value:
  1487. try:
  1488. plate_info["prediction"] = int(value)
  1489. except ValueError:
  1490. pass # Leave prediction as None if not a valid integer
  1491. elif key == "weight" and value:
  1492. try:
  1493. plate_info["weight"] = float(value)
  1494. except ValueError:
  1495. pass # Leave weight as None if not a valid number
  1496. # Get filaments used in this plate
  1497. for filament_elem in plate_elem.findall("filament"):
  1498. filament_id = filament_elem.get("id")
  1499. filament_type = filament_elem.get("type", "")
  1500. filament_color = filament_elem.get("color", "")
  1501. used_g = filament_elem.get("used_g", "0")
  1502. used_m = filament_elem.get("used_m", "0")
  1503. try:
  1504. used_grams = float(used_g)
  1505. except (ValueError, TypeError):
  1506. used_grams = 0
  1507. if used_grams > 0 and filament_id:
  1508. plate_info["filaments"].append(
  1509. {
  1510. "slot_id": int(filament_id),
  1511. "type": filament_type,
  1512. "color": filament_color,
  1513. "used_grams": round(used_grams, 1),
  1514. "used_meters": float(used_m) if used_m else 0,
  1515. }
  1516. )
  1517. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1518. # Collect object names
  1519. for obj_elem in plate_elem.findall("object"):
  1520. obj_name = obj_elem.get("name")
  1521. if obj_name and obj_name not in plate_info["objects"]:
  1522. plate_info["objects"].append(obj_name)
  1523. # Set plate name
  1524. if plate_index is not None:
  1525. custom_name = plate_names.get(plate_index)
  1526. if custom_name:
  1527. plate_info["name"] = custom_name
  1528. elif plate_info["objects"]:
  1529. plate_info["name"] = plate_info["objects"][0]
  1530. plate_metadata[plate_index] = plate_info
  1531. # Parse plate_*.json for object lists when slice_info is missing
  1532. plate_json_objects: dict[int, list[str]] = {}
  1533. for name in namelist:
  1534. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  1535. if not match:
  1536. continue
  1537. try:
  1538. plate_index = int(match.group(1))
  1539. except ValueError:
  1540. continue
  1541. try:
  1542. payload = json.loads(zf.read(name).decode())
  1543. bbox_objects = payload.get("bbox_objects", [])
  1544. names: list[str] = []
  1545. for obj in bbox_objects:
  1546. obj_name = obj.get("name") if isinstance(obj, dict) else None
  1547. if obj_name and obj_name not in names:
  1548. names.append(obj_name)
  1549. if names:
  1550. plate_json_objects[plate_index] = names
  1551. except Exception:
  1552. continue
  1553. # Build plate list
  1554. for idx in plate_indices:
  1555. meta = plate_metadata.get(idx, {})
  1556. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1557. objects = meta.get("objects", [])
  1558. if not objects:
  1559. objects = plate_json_objects.get(idx, [])
  1560. if not objects and plate_object_ids.get(idx):
  1561. objects = [
  1562. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  1563. ]
  1564. plate_name = meta.get("name")
  1565. if not plate_name:
  1566. plate_name = plate_names.get(idx)
  1567. if not plate_name and objects:
  1568. plate_name = objects[0]
  1569. plates.append(
  1570. {
  1571. "index": idx,
  1572. "name": plate_name,
  1573. "objects": objects,
  1574. "object_count": len(objects),
  1575. "has_thumbnail": has_thumbnail,
  1576. "thumbnail_url": f"/api/v1/library/files/{file_id}/plate-thumbnail/{idx}"
  1577. if has_thumbnail
  1578. else None,
  1579. "print_time_seconds": meta.get("prediction"),
  1580. "filament_used_grams": meta.get("weight"),
  1581. "filaments": meta.get("filaments", []),
  1582. }
  1583. )
  1584. except Exception as e:
  1585. logger.warning("Failed to parse plates from library file %s: %s", file_id, e)
  1586. return {
  1587. "file_id": file_id,
  1588. "filename": lib_file.filename,
  1589. "plates": plates,
  1590. "is_multi_plate": len(plates) > 1,
  1591. }
  1592. @router.get("/files/{file_id}/plate-thumbnail/{plate_index}")
  1593. async def get_library_file_plate_thumbnail(
  1594. file_id: int,
  1595. plate_index: int,
  1596. db: AsyncSession = Depends(get_db),
  1597. ):
  1598. """Get the thumbnail image for a specific plate from a library file."""
  1599. from starlette.responses import Response
  1600. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1601. lib_file = result.scalar_one_or_none()
  1602. if not lib_file:
  1603. raise HTTPException(status_code=404, detail="File not found")
  1604. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1605. if not file_path.exists():
  1606. raise HTTPException(status_code=404, detail="File not found on disk")
  1607. try:
  1608. with zipfile.ZipFile(file_path, "r") as zf:
  1609. thumb_path = f"Metadata/plate_{plate_index}.png"
  1610. if thumb_path in zf.namelist():
  1611. data = zf.read(thumb_path)
  1612. return Response(content=data, media_type="image/png")
  1613. except Exception:
  1614. pass # Archive unreadable or thumbnail missing; fall through to 404
  1615. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1616. @router.get("/files/{file_id}/filament-requirements")
  1617. async def get_library_file_filament_requirements(
  1618. file_id: int,
  1619. plate_id: int | None = None,
  1620. db: AsyncSession = Depends(get_db),
  1621. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1622. ):
  1623. """Get filament requirements from a library file.
  1624. Parses the 3MF file to extract filament slot IDs, types, colors, and usage.
  1625. This enables AMS slot assignment when printing from the file manager.
  1626. Args:
  1627. file_id: The library file ID
  1628. plate_id: Optional plate index to get filaments for a specific plate
  1629. """
  1630. import defusedxml.ElementTree as ET
  1631. # Get the library file
  1632. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1633. lib_file = result.scalar_one_or_none()
  1634. if not lib_file:
  1635. raise HTTPException(status_code=404, detail="File not found")
  1636. # Get the full file path
  1637. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1638. if not file_path.exists():
  1639. raise HTTPException(status_code=404, detail="File not found on disk")
  1640. # Only 3MF files have parseable filament info
  1641. if not lib_file.filename.lower().endswith(".3mf"):
  1642. return {"file_id": file_id, "filename": lib_file.filename, "plate_id": plate_id, "filaments": []}
  1643. filaments = []
  1644. try:
  1645. with zipfile.ZipFile(file_path, "r") as zf:
  1646. # Parse slice_info.config for filament requirements
  1647. if "Metadata/slice_info.config" in zf.namelist():
  1648. content = zf.read("Metadata/slice_info.config").decode()
  1649. root = ET.fromstring(content)
  1650. if plate_id is not None:
  1651. # Find filaments for specific plate
  1652. for plate_elem in root.findall(".//plate"):
  1653. # Check if this is the requested plate
  1654. plate_index = None
  1655. for meta in plate_elem.findall("metadata"):
  1656. if meta.get("key") == "index":
  1657. try:
  1658. plate_index = int(meta.get("value", ""))
  1659. except ValueError:
  1660. pass # Skip plate with non-numeric index value
  1661. break
  1662. if plate_index == plate_id:
  1663. # Extract filaments from this plate
  1664. for filament_elem in plate_elem.findall("filament"):
  1665. filament_id = filament_elem.get("id")
  1666. filament_type = filament_elem.get("type", "")
  1667. filament_color = filament_elem.get("color", "")
  1668. used_g = filament_elem.get("used_g", "0")
  1669. used_m = filament_elem.get("used_m", "0")
  1670. tray_info_idx = filament_elem.get("tray_info_idx", "")
  1671. try:
  1672. used_grams = float(used_g)
  1673. except (ValueError, TypeError):
  1674. used_grams = 0
  1675. if used_grams > 0 and filament_id:
  1676. filaments.append(
  1677. {
  1678. "slot_id": int(filament_id),
  1679. "type": filament_type,
  1680. "color": filament_color,
  1681. "used_grams": round(used_grams, 1),
  1682. "used_meters": float(used_m) if used_m else 0,
  1683. "tray_info_idx": tray_info_idx,
  1684. }
  1685. )
  1686. break
  1687. else:
  1688. # Extract all filaments with used_g > 0 (for single-plate or overview)
  1689. for filament_elem in root.findall(".//filament"):
  1690. filament_id = filament_elem.get("id")
  1691. filament_type = filament_elem.get("type", "")
  1692. filament_color = filament_elem.get("color", "")
  1693. used_g = filament_elem.get("used_g", "0")
  1694. used_m = filament_elem.get("used_m", "0")
  1695. tray_info_idx = filament_elem.get("tray_info_idx", "")
  1696. try:
  1697. used_grams = float(used_g)
  1698. except (ValueError, TypeError):
  1699. used_grams = 0
  1700. if used_grams > 0 and filament_id:
  1701. filaments.append(
  1702. {
  1703. "slot_id": int(filament_id),
  1704. "type": filament_type,
  1705. "color": filament_color,
  1706. "used_grams": round(used_grams, 1),
  1707. "used_meters": float(used_m) if used_m else 0,
  1708. "tray_info_idx": tray_info_idx,
  1709. }
  1710. )
  1711. # Sort by slot ID
  1712. filaments.sort(key=lambda x: x["slot_id"])
  1713. # Enrich with nozzle mapping for dual-nozzle printers
  1714. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  1715. if nozzle_mapping:
  1716. for filament in filaments:
  1717. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  1718. except Exception as e:
  1719. logger.warning("Failed to parse filament requirements from library file %s: %s", file_id, e)
  1720. return {
  1721. "file_id": file_id,
  1722. "filename": lib_file.filename,
  1723. "plate_id": plate_id,
  1724. "filaments": filaments,
  1725. }
  1726. @router.post("/files/{file_id}/print")
  1727. async def print_library_file(
  1728. file_id: int,
  1729. printer_id: int,
  1730. body: FilePrintRequest | None = None,
  1731. db: AsyncSession = Depends(get_db),
  1732. _: User | None = Depends(require_permission_if_auth_enabled(Permission.PRINTERS_CONTROL)),
  1733. ):
  1734. """Dispatch a library file for send/start on a printer.
  1735. The actual send/start work is handled asynchronously by background
  1736. dispatch so the UI can continue immediately.
  1737. Only sliced files (.gcode or .gcode.3mf) can be printed.
  1738. """
  1739. from backend.app.models.printer import Printer
  1740. from backend.app.services.background_dispatch import DispatchEnqueueRejected, background_dispatch
  1741. from backend.app.services.printer_manager import printer_manager
  1742. # Use defaults if no body provided
  1743. if body is None:
  1744. body = FilePrintRequest()
  1745. # Get the library file
  1746. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1747. lib_file = result.scalar_one_or_none()
  1748. if not lib_file:
  1749. raise HTTPException(status_code=404, detail="File not found")
  1750. # Validate file is sliced
  1751. if not is_sliced_file(lib_file.filename):
  1752. raise HTTPException(
  1753. status_code=400,
  1754. detail="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1755. )
  1756. # Get the full file path
  1757. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1758. if not file_path.exists():
  1759. raise HTTPException(status_code=404, detail="File not found on disk")
  1760. # Get printer
  1761. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1762. printer = result.scalar_one_or_none()
  1763. if not printer:
  1764. raise HTTPException(status_code=404, detail="Printer not found")
  1765. # Check printer is connected
  1766. if not printer_manager.is_connected(printer_id):
  1767. raise HTTPException(status_code=400, detail="Printer is not connected")
  1768. plate_name = body.plate_name
  1769. if not plate_name and body.plate_id is not None:
  1770. plate_name = f"Plate {body.plate_id}"
  1771. dispatch_source_name = lib_file.filename
  1772. if plate_name:
  1773. dispatch_source_name = f"{lib_file.filename} • {plate_name}"
  1774. try:
  1775. dispatch_result = await background_dispatch.dispatch_print_library_file(
  1776. file_id=file_id,
  1777. filename=dispatch_source_name,
  1778. printer_id=printer_id,
  1779. printer_name=printer.name,
  1780. options=body.model_dump(exclude_none=True),
  1781. requested_by_user_id=None,
  1782. requested_by_username=None,
  1783. )
  1784. except DispatchEnqueueRejected as e:
  1785. raise HTTPException(status_code=409, detail=str(e)) from e
  1786. return {
  1787. "status": "dispatched",
  1788. "printer_id": printer_id,
  1789. "archive_id": None,
  1790. "filename": lib_file.filename,
  1791. "dispatch_job_id": dispatch_result["dispatch_job_id"],
  1792. "dispatch_position": dispatch_result["dispatch_position"],
  1793. }
  1794. # ============ File Detail Endpoints ============
  1795. @router.get("/files/{file_id}", response_model=FileResponseSchema)
  1796. async def get_file(
  1797. file_id: int,
  1798. db: AsyncSession = Depends(get_db),
  1799. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1800. ):
  1801. """Get a file by ID with full details."""
  1802. result = await db.execute(
  1803. select(LibraryFile).options(selectinload(LibraryFile.created_by)).where(LibraryFile.id == file_id)
  1804. )
  1805. file = result.scalar_one_or_none()
  1806. if not file:
  1807. raise HTTPException(status_code=404, detail="File not found")
  1808. # Get folder name
  1809. folder_name = None
  1810. if file.folder_id:
  1811. folder_result = await db.execute(select(LibraryFolder.name).where(LibraryFolder.id == file.folder_id))
  1812. folder_name = folder_result.scalar()
  1813. # Get project name
  1814. project_name = None
  1815. if file.project_id:
  1816. project_result = await db.execute(select(Project.name).where(Project.id == file.project_id))
  1817. project_name = project_result.scalar()
  1818. # Get duplicates
  1819. duplicates = []
  1820. duplicate_count = 0
  1821. if file.file_hash:
  1822. dup_result = await db.execute(
  1823. select(LibraryFile, LibraryFolder.name)
  1824. .outerjoin(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  1825. .where(LibraryFile.file_hash == file.file_hash, LibraryFile.id != file.id)
  1826. )
  1827. for dup_file, dup_folder_name in dup_result.all():
  1828. duplicates.append(
  1829. FileDuplicate(
  1830. id=dup_file.id,
  1831. filename=dup_file.filename,
  1832. folder_id=dup_file.folder_id,
  1833. folder_name=dup_folder_name,
  1834. created_at=dup_file.created_at,
  1835. )
  1836. )
  1837. duplicate_count = len(duplicates)
  1838. # Extract key metadata fields
  1839. print_name = None
  1840. print_time = None
  1841. filament_grams = None
  1842. sliced_for_model = None
  1843. if file.file_metadata:
  1844. print_name = file.file_metadata.get("print_name")
  1845. print_time = file.file_metadata.get("print_time_seconds")
  1846. filament_grams = file.file_metadata.get("filament_used_grams")
  1847. sliced_for_model = file.file_metadata.get("sliced_for_model")
  1848. return FileResponseSchema(
  1849. id=file.id,
  1850. folder_id=file.folder_id,
  1851. folder_name=folder_name,
  1852. project_id=file.project_id,
  1853. project_name=project_name,
  1854. filename=file.filename,
  1855. file_path=file.file_path,
  1856. file_type=file.file_type,
  1857. file_size=file.file_size,
  1858. file_hash=file.file_hash,
  1859. thumbnail_path=file.thumbnail_path,
  1860. metadata=file.file_metadata,
  1861. print_count=file.print_count,
  1862. last_printed_at=file.last_printed_at,
  1863. notes=file.notes,
  1864. duplicates=duplicates if duplicates else None,
  1865. duplicate_count=duplicate_count,
  1866. created_by_id=file.created_by_id,
  1867. created_by_username=file.created_by.username if file.created_by else None,
  1868. created_at=file.created_at,
  1869. updated_at=file.updated_at,
  1870. print_name=print_name,
  1871. print_time_seconds=print_time,
  1872. filament_used_grams=filament_grams,
  1873. sliced_for_model=sliced_for_model,
  1874. )
  1875. @router.put("/files/{file_id}", response_model=FileResponseSchema)
  1876. async def update_file(
  1877. file_id: int,
  1878. data: FileUpdate,
  1879. db: AsyncSession = Depends(get_db),
  1880. auth_result: tuple[User | None, bool] = Depends(
  1881. require_ownership_permission(
  1882. Permission.LIBRARY_UPDATE_ALL,
  1883. Permission.LIBRARY_UPDATE_OWN,
  1884. )
  1885. ),
  1886. ):
  1887. """Update a file's metadata."""
  1888. user, can_modify_all = auth_result
  1889. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1890. file = result.scalar_one_or_none()
  1891. if not file:
  1892. raise HTTPException(status_code=404, detail="File not found")
  1893. # Ownership check
  1894. if not can_modify_all:
  1895. if file.created_by_id != user.id:
  1896. raise HTTPException(status_code=403, detail="You can only update your own files")
  1897. if data.filename is not None:
  1898. # Validate filename doesn't contain path separators
  1899. if "/" in data.filename or "\\" in data.filename:
  1900. raise HTTPException(status_code=400, detail="Filename cannot contain path separators")
  1901. file.filename = data.filename
  1902. # Also update print_name in file_metadata so the display name matches
  1903. if file.file_metadata and "print_name" in file.file_metadata:
  1904. file.file_metadata = {**file.file_metadata, "print_name": data.filename}
  1905. if data.folder_id is not None:
  1906. if data.folder_id == 0:
  1907. file.folder_id = None
  1908. else:
  1909. # Verify folder exists
  1910. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  1911. if not folder_result.scalar_one_or_none():
  1912. raise HTTPException(status_code=404, detail="Folder not found")
  1913. file.folder_id = data.folder_id
  1914. if data.project_id is not None:
  1915. if data.project_id == 0:
  1916. file.project_id = None
  1917. else:
  1918. # Verify project exists
  1919. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  1920. if not project_result.scalar_one_or_none():
  1921. raise HTTPException(status_code=404, detail="Project not found")
  1922. file.project_id = data.project_id
  1923. if data.notes is not None:
  1924. file.notes = data.notes if data.notes else None
  1925. await db.commit()
  1926. await db.refresh(file)
  1927. # Return full response (reuse get_file logic)
  1928. return await get_file(file_id, db)
  1929. @router.delete("/files/{file_id}")
  1930. async def delete_file(
  1931. file_id: int,
  1932. db: AsyncSession = Depends(get_db),
  1933. auth_result: tuple[User | None, bool] = Depends(
  1934. require_ownership_permission(
  1935. Permission.LIBRARY_DELETE_ALL,
  1936. Permission.LIBRARY_DELETE_OWN,
  1937. )
  1938. ),
  1939. ):
  1940. """Delete a file."""
  1941. user, can_modify_all = auth_result
  1942. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1943. file = result.scalar_one_or_none()
  1944. if not file:
  1945. raise HTTPException(status_code=404, detail="File not found")
  1946. # Ownership check
  1947. if not can_modify_all:
  1948. if file.created_by_id != user.id:
  1949. raise HTTPException(status_code=403, detail="You can only delete your own files")
  1950. # External files: only remove DB entry and thumbnail, never delete the actual file
  1951. try:
  1952. if not file.is_external:
  1953. abs_file_path = to_absolute_path(file.file_path)
  1954. if abs_file_path and abs_file_path.exists():
  1955. abs_file_path.unlink()
  1956. # Always clean up thumbnails we generated
  1957. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  1958. if abs_thumb_path and abs_thumb_path.exists():
  1959. abs_thumb_path.unlink()
  1960. except OSError as e:
  1961. logger.warning("Failed to delete file from disk: %s", e)
  1962. await db.delete(file)
  1963. return {"status": "success", "message": "File deleted"}
  1964. # ============ File Content Endpoints ============
  1965. @router.get("/files/{file_id}/download")
  1966. async def download_file(
  1967. file_id: int,
  1968. db: AsyncSession = Depends(get_db),
  1969. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1970. ):
  1971. """Download a file."""
  1972. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1973. file = result.scalar_one_or_none()
  1974. if not file:
  1975. raise HTTPException(status_code=404, detail="File not found")
  1976. abs_path = to_absolute_path(file.file_path)
  1977. if not abs_path or not abs_path.exists():
  1978. raise HTTPException(status_code=404, detail="File not found on disk")
  1979. return FastAPIFileResponse(
  1980. str(abs_path),
  1981. filename=file.filename,
  1982. media_type="application/octet-stream",
  1983. )
  1984. @router.post("/files/{file_id}/slicer-token")
  1985. async def create_library_slicer_token(
  1986. file_id: int,
  1987. db: AsyncSession = Depends(get_db),
  1988. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1989. ):
  1990. """Create a short-lived download token for opening files in slicer applications.
  1991. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  1992. auth headers, so they use this token in the URL path instead.
  1993. """
  1994. from backend.app.core.auth import create_slicer_download_token
  1995. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1996. file = result.scalar_one_or_none()
  1997. if not file:
  1998. raise HTTPException(status_code=404, detail="File not found")
  1999. token = create_slicer_download_token("library", file_id)
  2000. return {"token": token}
  2001. @router.get("/files/{file_id}/dl/{token}/{filename}")
  2002. async def download_library_file_for_slicer(
  2003. file_id: int,
  2004. token: str,
  2005. filename: str,
  2006. db: AsyncSession = Depends(get_db),
  2007. ):
  2008. """Download a library file using a slicer download token.
  2009. Token-authenticated (no auth headers needed). The token is short-lived
  2010. and single-use, created by POST /files/{file_id}/slicer-token.
  2011. Filename is at the end of the URL so slicers can detect the file format.
  2012. """
  2013. from backend.app.core.auth import verify_slicer_download_token
  2014. if not verify_slicer_download_token(token, "library", file_id):
  2015. raise HTTPException(status_code=403, detail="Invalid or expired download token")
  2016. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2017. file = result.scalar_one_or_none()
  2018. if not file:
  2019. raise HTTPException(status_code=404, detail="File not found")
  2020. abs_path = to_absolute_path(file.file_path)
  2021. if not abs_path or not abs_path.exists():
  2022. raise HTTPException(status_code=404, detail="File not found on disk")
  2023. return FastAPIFileResponse(
  2024. str(abs_path),
  2025. filename=file.filename,
  2026. media_type="application/octet-stream",
  2027. )
  2028. @router.get("/files/{file_id}/thumbnail")
  2029. async def get_thumbnail(file_id: int, db: AsyncSession = Depends(get_db)):
  2030. """Get a file's thumbnail."""
  2031. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2032. file = result.scalar_one_or_none()
  2033. if not file:
  2034. raise HTTPException(status_code=404, detail="File not found")
  2035. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  2036. if not abs_thumb_path or not abs_thumb_path.exists():
  2037. raise HTTPException(status_code=404, detail="Thumbnail not found")
  2038. # Detect media type from extension
  2039. thumb_ext = abs_thumb_path.suffix.lower()
  2040. media_types = {
  2041. ".png": "image/png",
  2042. ".jpg": "image/jpeg",
  2043. ".jpeg": "image/jpeg",
  2044. ".gif": "image/gif",
  2045. ".webp": "image/webp",
  2046. }
  2047. media_type = media_types.get(thumb_ext, "image/png")
  2048. return FastAPIFileResponse(str(abs_thumb_path), media_type=media_type)
  2049. @router.get("/files/{file_id}/gcode")
  2050. async def get_gcode(
  2051. file_id: int,
  2052. db: AsyncSession = Depends(get_db),
  2053. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  2054. ):
  2055. """Get gcode for a file (for preview)."""
  2056. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2057. file = result.scalar_one_or_none()
  2058. if not file:
  2059. raise HTTPException(status_code=404, detail="File not found")
  2060. abs_path = to_absolute_path(file.file_path)
  2061. if not abs_path or not abs_path.exists():
  2062. raise HTTPException(status_code=404, detail="File not found on disk")
  2063. if file.file_type == "gcode":
  2064. return FastAPIFileResponse(str(abs_path), media_type="text/plain")
  2065. elif file.file_type == "3mf":
  2066. # Extract gcode from 3mf
  2067. try:
  2068. with zipfile.ZipFile(str(abs_path), "r") as zf:
  2069. # Find gcode file
  2070. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  2071. if not gcode_files:
  2072. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  2073. gcode_content = zf.read(gcode_files[0])
  2074. from fastapi.responses import Response
  2075. return Response(content=gcode_content, media_type="text/plain")
  2076. except zipfile.BadZipFile:
  2077. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  2078. else:
  2079. raise HTTPException(status_code=400, detail="Unsupported file type")
  2080. # ============ Bulk Operations ============
  2081. @router.post("/files/move")
  2082. async def move_files(
  2083. data: FileMoveRequest,
  2084. db: AsyncSession = Depends(get_db),
  2085. auth_result: tuple[User | None, bool] = Depends(
  2086. require_ownership_permission(
  2087. Permission.LIBRARY_UPDATE_ALL,
  2088. Permission.LIBRARY_UPDATE_OWN,
  2089. )
  2090. ),
  2091. ):
  2092. """Move multiple files to a folder.
  2093. Files not owned by the user are skipped (unless user has *_all permission).
  2094. """
  2095. user, can_modify_all = auth_result
  2096. # Verify folder exists if specified
  2097. if data.folder_id is not None:
  2098. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  2099. target_folder = folder_result.scalar_one_or_none()
  2100. if not target_folder:
  2101. raise HTTPException(status_code=404, detail="Folder not found")
  2102. if target_folder.is_external and target_folder.external_readonly:
  2103. raise HTTPException(status_code=403, detail="Cannot move files to a read-only external folder")
  2104. # Update files
  2105. moved = 0
  2106. skipped = 0
  2107. for file_id in data.file_ids:
  2108. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2109. file = result.scalar_one_or_none()
  2110. if file:
  2111. # Ownership check
  2112. if not can_modify_all and file.created_by_id != user.id:
  2113. skipped += 1
  2114. continue
  2115. # Cannot move external files out of their folder
  2116. if file.is_external:
  2117. skipped += 1
  2118. continue
  2119. file.folder_id = data.folder_id
  2120. moved += 1
  2121. return {"status": "success", "moved": moved, "skipped": skipped}
  2122. @router.post("/bulk-delete", response_model=BulkDeleteResponse)
  2123. async def bulk_delete(
  2124. data: BulkDeleteRequest,
  2125. db: AsyncSession = Depends(get_db),
  2126. auth_result: tuple[User | None, bool] = Depends(
  2127. require_ownership_permission(
  2128. Permission.LIBRARY_DELETE_ALL,
  2129. Permission.LIBRARY_DELETE_OWN,
  2130. )
  2131. ),
  2132. ):
  2133. """Delete multiple files and/or folders.
  2134. Files not owned by the user are skipped (unless user has *_all permission).
  2135. """
  2136. user, can_modify_all = auth_result
  2137. deleted_files = 0
  2138. deleted_folders = 0
  2139. skipped_files = 0
  2140. # Delete files first
  2141. for file_id in data.file_ids:
  2142. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2143. file = result.scalar_one_or_none()
  2144. if file:
  2145. # Ownership check
  2146. if not can_modify_all and file.created_by_id != user.id:
  2147. skipped_files += 1
  2148. continue
  2149. try:
  2150. if not file.is_external:
  2151. abs_file_path = to_absolute_path(file.file_path)
  2152. if abs_file_path and abs_file_path.exists():
  2153. abs_file_path.unlink()
  2154. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  2155. if abs_thumb_path and abs_thumb_path.exists():
  2156. abs_thumb_path.unlink()
  2157. except OSError as e:
  2158. logger.warning("Failed to delete file from disk: %s", e)
  2159. await db.delete(file)
  2160. deleted_files += 1
  2161. # Delete folders (cascade will handle contents)
  2162. # Note: Folders don't have ownership tracking currently, require *_all permission
  2163. for folder_id in data.folder_ids:
  2164. if not can_modify_all:
  2165. # Users without *_all permission cannot delete folders
  2166. continue
  2167. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  2168. folder = result.scalar_one_or_none()
  2169. if folder:
  2170. # Count files that will be deleted
  2171. file_count_result = await db.execute(
  2172. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id)
  2173. )
  2174. deleted_files += file_count_result.scalar() or 0
  2175. await db.delete(folder)
  2176. deleted_folders += 1
  2177. return BulkDeleteResponse(deleted_files=deleted_files, deleted_folders=deleted_folders)
  2178. # ============ Stats Endpoint ============
  2179. @router.get("/stats")
  2180. async def get_library_stats(
  2181. db: AsyncSession = Depends(get_db),
  2182. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  2183. ):
  2184. """Get library statistics."""
  2185. # Total files
  2186. total_files_result = await db.execute(select(func.count(LibraryFile.id)))
  2187. total_files = total_files_result.scalar() or 0
  2188. # Total folders
  2189. total_folders_result = await db.execute(select(func.count(LibraryFolder.id)))
  2190. total_folders = total_folders_result.scalar() or 0
  2191. # Total size
  2192. total_size_result = await db.execute(select(func.sum(LibraryFile.file_size)))
  2193. total_size = total_size_result.scalar() or 0
  2194. # Files by type
  2195. type_result = await db.execute(
  2196. select(LibraryFile.file_type, func.count(LibraryFile.id)).group_by(LibraryFile.file_type)
  2197. )
  2198. files_by_type = dict(type_result.all())
  2199. # Total prints
  2200. total_prints_result = await db.execute(select(func.sum(LibraryFile.print_count)))
  2201. total_prints = total_prints_result.scalar() or 0
  2202. # Disk space info
  2203. library_dir = get_library_dir()
  2204. try:
  2205. disk_stat = shutil.disk_usage(library_dir)
  2206. disk_free_bytes = disk_stat.free
  2207. disk_total_bytes = disk_stat.total
  2208. disk_used_bytes = disk_stat.used
  2209. except OSError:
  2210. disk_free_bytes = 0
  2211. disk_total_bytes = 0
  2212. disk_used_bytes = 0
  2213. return {
  2214. "total_files": total_files,
  2215. "total_folders": total_folders,
  2216. "total_size_bytes": total_size,
  2217. "files_by_type": files_by_type,
  2218. "total_prints": total_prints,
  2219. "disk_free_bytes": disk_free_bytes,
  2220. "disk_total_bytes": disk_total_bytes,
  2221. "disk_used_bytes": disk_used_bytes,
  2222. }