library.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  1. """API routes for File Manager (Library) functionality."""
  2. import base64
  3. import hashlib
  4. import logging
  5. import os
  6. import re
  7. import shutil
  8. import uuid
  9. from pathlib import Path
  10. from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile
  11. from fastapi.responses import FileResponse as FastAPIFileResponse
  12. from sqlalchemy import func, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from sqlalchemy.orm import selectinload
  15. from backend.app.core.auth import (
  16. require_auth_if_enabled,
  17. require_ownership_permission,
  18. require_permission_if_auth_enabled,
  19. )
  20. from backend.app.core.config import settings as app_settings
  21. from backend.app.core.database import get_db
  22. from backend.app.core.permissions import Permission
  23. from backend.app.models.archive import PrintArchive
  24. from backend.app.models.library import LibraryFile, LibraryFolder
  25. from backend.app.models.print_queue import PrintQueueItem
  26. from backend.app.models.project import Project
  27. from backend.app.models.user import User
  28. from backend.app.schemas.library import (
  29. AddToQueueError,
  30. AddToQueueRequest,
  31. AddToQueueResponse,
  32. AddToQueueResult,
  33. BatchThumbnailRequest,
  34. BatchThumbnailResponse,
  35. BatchThumbnailResult,
  36. BulkDeleteRequest,
  37. BulkDeleteResponse,
  38. FileDuplicate,
  39. FileListResponse,
  40. FileMoveRequest,
  41. FilePrintRequest,
  42. FileResponse as FileResponseSchema,
  43. FileUpdate,
  44. FileUploadResponse,
  45. FolderCreate,
  46. FolderResponse,
  47. FolderTreeItem,
  48. FolderUpdate,
  49. ZipExtractError,
  50. ZipExtractResponse,
  51. ZipExtractResult,
  52. )
  53. from backend.app.services.archive import ArchiveService, ThreeMFParser
  54. from backend.app.services.stl_thumbnail import generate_stl_thumbnail
  55. logger = logging.getLogger(__name__)
  56. router = APIRouter(prefix="/library", tags=["library"])
  57. def get_library_dir() -> Path:
  58. """Get the library storage directory."""
  59. base_dir = Path(app_settings.archive_dir)
  60. library_dir = base_dir / "library"
  61. library_dir.mkdir(parents=True, exist_ok=True)
  62. return library_dir
  63. def get_library_files_dir() -> Path:
  64. """Get the directory for library files."""
  65. files_dir = get_library_dir() / "files"
  66. files_dir.mkdir(parents=True, exist_ok=True)
  67. return files_dir
  68. def get_library_thumbnails_dir() -> Path:
  69. """Get the directory for library thumbnails."""
  70. thumbnails_dir = get_library_dir() / "thumbnails"
  71. thumbnails_dir.mkdir(parents=True, exist_ok=True)
  72. return thumbnails_dir
  73. def to_relative_path(absolute_path: Path | str) -> str:
  74. """Convert an absolute path to a path relative to base_dir for storage."""
  75. if not absolute_path:
  76. return ""
  77. abs_path = Path(absolute_path)
  78. base_dir = Path(app_settings.base_dir)
  79. try:
  80. return str(abs_path.relative_to(base_dir))
  81. except ValueError:
  82. # Path is not under base_dir, return as-is (shouldn't happen normally)
  83. return str(abs_path)
  84. def to_absolute_path(relative_path: str | None) -> Path | None:
  85. """Convert a relative path (from database) to an absolute path for file operations."""
  86. if not relative_path:
  87. return None
  88. # Handle already-absolute paths (for backwards compatibility during migration)
  89. path = Path(relative_path)
  90. if path.is_absolute():
  91. return path
  92. return Path(app_settings.base_dir) / relative_path
  93. def calculate_file_hash(file_path: Path) -> str:
  94. """Calculate SHA256 hash of a file."""
  95. sha256_hash = hashlib.sha256()
  96. with open(file_path, "rb") as f:
  97. for byte_block in iter(lambda: f.read(4096), b""):
  98. sha256_hash.update(byte_block)
  99. return sha256_hash.hexdigest()
  100. def extract_gcode_thumbnail(file_path: Path) -> bytes | None:
  101. """Extract embedded thumbnail from gcode file.
  102. Supports PrusaSlicer/BambuStudio format:
  103. ; thumbnail begin WxH SIZE
  104. ; base64data...
  105. ; thumbnail end
  106. """
  107. try:
  108. thumbnail_data = None
  109. in_thumbnail = False
  110. thumbnail_lines = []
  111. best_size = 0
  112. with open(file_path, errors="ignore") as f:
  113. # Only read first 50KB for performance (thumbnails are at the start)
  114. content = f.read(50000)
  115. for line in content.split("\n"):
  116. line = line.strip()
  117. # Check for thumbnail start
  118. if line.startswith("; thumbnail begin"):
  119. in_thumbnail = True
  120. thumbnail_lines = []
  121. # Parse dimensions: "; thumbnail begin 300x300 12345"
  122. match = re.search(r"(\d+)x(\d+)", line)
  123. if match:
  124. width = int(match.group(1))
  125. # Prefer larger thumbnails (up to 300px)
  126. if width > best_size and width <= 300:
  127. best_size = width
  128. continue
  129. # Check for thumbnail end
  130. if line.startswith("; thumbnail end"):
  131. if in_thumbnail and thumbnail_lines:
  132. try:
  133. # Decode the base64 data
  134. b64_data = "".join(thumbnail_lines)
  135. decoded = base64.b64decode(b64_data)
  136. # Only keep if this is the best size or first valid thumbnail
  137. if thumbnail_data is None or best_size > 0:
  138. thumbnail_data = decoded
  139. except Exception:
  140. pass
  141. in_thumbnail = False
  142. thumbnail_lines = []
  143. continue
  144. # Collect thumbnail data
  145. if in_thumbnail and line.startswith(";"):
  146. # Remove the leading "; " or ";"
  147. data_line = line[1:].strip()
  148. if data_line:
  149. thumbnail_lines.append(data_line)
  150. return thumbnail_data
  151. except Exception as e:
  152. logger.warning(f"Failed to extract gcode thumbnail: {e}")
  153. return None
  154. def create_image_thumbnail(file_path: Path, thumbnails_dir: Path, max_size: int = 256) -> str | None:
  155. """Create a thumbnail from an image file.
  156. For small images, copies directly. For larger images, resizes.
  157. Returns the thumbnail path or None on failure.
  158. """
  159. try:
  160. from PIL import Image
  161. thumb_filename = f"{uuid.uuid4().hex}.png"
  162. thumb_path = thumbnails_dir / thumb_filename
  163. with Image.open(file_path) as img:
  164. # Convert to RGB if necessary (for PNG with transparency, etc.)
  165. if img.mode in ("RGBA", "LA", "P"):
  166. # Create white background for transparency
  167. background = Image.new("RGB", img.size, (255, 255, 255))
  168. if img.mode == "P":
  169. img = img.convert("RGBA")
  170. background.paste(img, mask=img.split()[-1] if img.mode == "RGBA" else None)
  171. img = background
  172. elif img.mode != "RGB":
  173. img = img.convert("RGB")
  174. # Resize if larger than max_size
  175. if img.width > max_size or img.height > max_size:
  176. img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
  177. img.save(thumb_path, "PNG", optimize=True)
  178. return str(thumb_path)
  179. except ImportError:
  180. # PIL not installed, just copy the file if it's small enough
  181. logger.warning("PIL not installed, copying image as thumbnail")
  182. try:
  183. file_size = file_path.stat().st_size
  184. if file_size < 500000: # Less than 500KB
  185. thumb_filename = f"{uuid.uuid4().hex}{file_path.suffix}"
  186. thumb_path = thumbnails_dir / thumb_filename
  187. shutil.copy2(file_path, thumb_path)
  188. return str(thumb_path)
  189. except Exception:
  190. pass
  191. return None
  192. except Exception as e:
  193. logger.warning(f"Failed to create image thumbnail: {e}")
  194. return None
  195. # Supported image extensions for thumbnails
  196. IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif"}
  197. # ============ Folder Endpoints ============
  198. @router.get("/folders", response_model=list[FolderTreeItem])
  199. @router.get("/folders/", response_model=list[FolderTreeItem])
  200. async def list_folders(response: Response, db: AsyncSession = Depends(get_db)):
  201. """Get all folders as a tree structure."""
  202. # Prevent browser caching of folder list
  203. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  204. # Get all folders with project and archive joins
  205. result = await db.execute(
  206. select(LibraryFolder, Project.name, PrintArchive.print_name)
  207. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  208. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  209. .order_by(LibraryFolder.name)
  210. )
  211. rows = result.all()
  212. # Get file counts per folder
  213. file_counts_result = await db.execute(
  214. select(LibraryFile.folder_id, func.count(LibraryFile.id))
  215. .where(LibraryFile.folder_id.isnot(None))
  216. .group_by(LibraryFile.folder_id)
  217. )
  218. file_counts = dict(file_counts_result.all())
  219. # Build tree structure
  220. folder_map = {}
  221. root_folders = []
  222. for folder, project_name, archive_name in rows:
  223. folder_item = FolderTreeItem(
  224. id=folder.id,
  225. name=folder.name,
  226. parent_id=folder.parent_id,
  227. project_id=folder.project_id,
  228. archive_id=folder.archive_id,
  229. project_name=project_name,
  230. archive_name=archive_name,
  231. file_count=file_counts.get(folder.id, 0),
  232. children=[],
  233. )
  234. folder_map[folder.id] = folder_item
  235. # Link children to parents
  236. for folder, _, _ in rows:
  237. folder_item = folder_map[folder.id]
  238. if folder.parent_id is None:
  239. root_folders.append(folder_item)
  240. elif folder.parent_id in folder_map:
  241. folder_map[folder.parent_id].children.append(folder_item)
  242. return root_folders
  243. @router.get("/folders/by-project/{project_id}", response_model=list[FolderResponse])
  244. async def get_folders_by_project(project_id: int, db: AsyncSession = Depends(get_db)):
  245. """Get all folders linked to a specific project."""
  246. result = await db.execute(
  247. select(LibraryFolder, Project.name)
  248. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  249. .where(LibraryFolder.project_id == project_id)
  250. .order_by(LibraryFolder.name)
  251. )
  252. rows = result.all()
  253. folders = []
  254. for folder, project_name in rows:
  255. # Get file count
  256. file_count_result = await db.execute(
  257. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder.id)
  258. )
  259. file_count = file_count_result.scalar() or 0
  260. folders.append(
  261. FolderResponse(
  262. id=folder.id,
  263. name=folder.name,
  264. parent_id=folder.parent_id,
  265. project_id=folder.project_id,
  266. archive_id=folder.archive_id,
  267. project_name=project_name,
  268. archive_name=None,
  269. file_count=file_count,
  270. created_at=folder.created_at,
  271. updated_at=folder.updated_at,
  272. )
  273. )
  274. return folders
  275. @router.get("/folders/by-archive/{archive_id}", response_model=list[FolderResponse])
  276. async def get_folders_by_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  277. """Get all folders linked to a specific archive."""
  278. result = await db.execute(
  279. select(LibraryFolder, PrintArchive.print_name)
  280. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  281. .where(LibraryFolder.archive_id == archive_id)
  282. .order_by(LibraryFolder.name)
  283. )
  284. rows = result.all()
  285. folders = []
  286. for folder, archive_name in rows:
  287. # Get file count
  288. file_count_result = await db.execute(
  289. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder.id)
  290. )
  291. file_count = file_count_result.scalar() or 0
  292. folders.append(
  293. FolderResponse(
  294. id=folder.id,
  295. name=folder.name,
  296. parent_id=folder.parent_id,
  297. project_id=folder.project_id,
  298. archive_id=folder.archive_id,
  299. project_name=None,
  300. archive_name=archive_name,
  301. file_count=file_count,
  302. created_at=folder.created_at,
  303. updated_at=folder.updated_at,
  304. )
  305. )
  306. return folders
  307. @router.post("/folders", response_model=FolderResponse)
  308. @router.post("/folders/", response_model=FolderResponse)
  309. async def create_folder(data: FolderCreate, db: AsyncSession = Depends(get_db)):
  310. """Create a new folder."""
  311. # Verify parent exists if specified
  312. if data.parent_id is not None:
  313. parent_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.parent_id))
  314. if not parent_result.scalar_one_or_none():
  315. raise HTTPException(status_code=404, detail="Parent folder not found")
  316. # Verify project exists if specified
  317. project_name = None
  318. if data.project_id is not None:
  319. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  320. project = project_result.scalar_one_or_none()
  321. if not project:
  322. raise HTTPException(status_code=404, detail="Project not found")
  323. project_name = project.name
  324. # Verify archive exists if specified
  325. archive_name = None
  326. if data.archive_id is not None:
  327. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  328. archive = archive_result.scalar_one_or_none()
  329. if not archive:
  330. raise HTTPException(status_code=404, detail="Archive not found")
  331. archive_name = archive.print_name
  332. folder = LibraryFolder(
  333. name=data.name,
  334. parent_id=data.parent_id,
  335. project_id=data.project_id,
  336. archive_id=data.archive_id,
  337. )
  338. db.add(folder)
  339. await db.flush()
  340. await db.refresh(folder)
  341. return FolderResponse(
  342. id=folder.id,
  343. name=folder.name,
  344. parent_id=folder.parent_id,
  345. project_id=folder.project_id,
  346. archive_id=folder.archive_id,
  347. project_name=project_name,
  348. archive_name=archive_name,
  349. file_count=0,
  350. created_at=folder.created_at,
  351. updated_at=folder.updated_at,
  352. )
  353. @router.get("/folders/{folder_id}", response_model=FolderResponse)
  354. async def get_folder(folder_id: int, db: AsyncSession = Depends(get_db)):
  355. """Get a folder by ID."""
  356. result = await db.execute(
  357. select(LibraryFolder, Project.name, PrintArchive.print_name)
  358. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  359. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  360. .where(LibraryFolder.id == folder_id)
  361. )
  362. row = result.one_or_none()
  363. if not row:
  364. raise HTTPException(status_code=404, detail="Folder not found")
  365. folder, project_name, archive_name = row
  366. # Get file count
  367. file_count_result = await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id))
  368. file_count = file_count_result.scalar() or 0
  369. return FolderResponse(
  370. id=folder.id,
  371. name=folder.name,
  372. parent_id=folder.parent_id,
  373. project_id=folder.project_id,
  374. archive_id=folder.archive_id,
  375. project_name=project_name,
  376. archive_name=archive_name,
  377. file_count=file_count,
  378. created_at=folder.created_at,
  379. updated_at=folder.updated_at,
  380. )
  381. @router.put("/folders/{folder_id}", response_model=FolderResponse)
  382. async def update_folder(folder_id: int, data: FolderUpdate, db: AsyncSession = Depends(get_db)):
  383. """Update a folder."""
  384. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  385. folder = result.scalar_one_or_none()
  386. if not folder:
  387. raise HTTPException(status_code=404, detail="Folder not found")
  388. if data.name is not None:
  389. folder.name = data.name
  390. if data.parent_id is not None:
  391. # Prevent circular reference
  392. if data.parent_id == folder_id:
  393. raise HTTPException(status_code=400, detail="Folder cannot be its own parent")
  394. # Check for circular reference in ancestors
  395. if data.parent_id != 0: # 0 means move to root
  396. current_id = data.parent_id
  397. while current_id is not None:
  398. if current_id == folder_id:
  399. raise HTTPException(status_code=400, detail="Cannot move folder into its own subtree")
  400. parent_result = await db.execute(select(LibraryFolder.parent_id).where(LibraryFolder.id == current_id))
  401. current_id = parent_result.scalar()
  402. folder.parent_id = data.parent_id
  403. else:
  404. folder.parent_id = None
  405. # Update project_id (0 to unlink)
  406. if data.project_id is not None:
  407. if data.project_id == 0:
  408. folder.project_id = None
  409. else:
  410. # Verify project exists
  411. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  412. if not project_result.scalar_one_or_none():
  413. raise HTTPException(status_code=404, detail="Project not found")
  414. folder.project_id = data.project_id
  415. # Update archive_id (0 to unlink)
  416. if data.archive_id is not None:
  417. if data.archive_id == 0:
  418. folder.archive_id = None
  419. else:
  420. # Verify archive exists
  421. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  422. if not archive_result.scalar_one_or_none():
  423. raise HTTPException(status_code=404, detail="Archive not found")
  424. folder.archive_id = data.archive_id
  425. await db.flush()
  426. await db.refresh(folder)
  427. # Get file count and names
  428. file_count_result = await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id))
  429. file_count = file_count_result.scalar() or 0
  430. # Get project and archive names
  431. project_name = None
  432. archive_name = None
  433. if folder.project_id:
  434. project_result = await db.execute(select(Project.name).where(Project.id == folder.project_id))
  435. project_name = project_result.scalar()
  436. if folder.archive_id:
  437. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == folder.archive_id))
  438. archive_name = archive_result.scalar()
  439. return FolderResponse(
  440. id=folder.id,
  441. name=folder.name,
  442. parent_id=folder.parent_id,
  443. project_id=folder.project_id,
  444. archive_id=folder.archive_id,
  445. project_name=project_name,
  446. archive_name=archive_name,
  447. file_count=file_count,
  448. created_at=folder.created_at,
  449. updated_at=folder.updated_at,
  450. )
  451. @router.delete("/folders/{folder_id}")
  452. async def delete_folder(
  453. folder_id: int,
  454. db: AsyncSession = Depends(get_db),
  455. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_DELETE_ALL)),
  456. ):
  457. """Delete a folder and all its contents (cascade).
  458. Note: Folders require library:delete_all permission since they don't have
  459. ownership tracking.
  460. """
  461. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  462. folder = result.scalar_one_or_none()
  463. if not folder:
  464. raise HTTPException(status_code=404, detail="Folder not found")
  465. # Get all files in this folder and subfolders to delete from disk
  466. async def get_all_file_ids(fid: int) -> list[int]:
  467. """Recursively get all file IDs in a folder tree."""
  468. file_ids = []
  469. # Get files in this folder
  470. files_result = await db.execute(
  471. select(LibraryFile.id, LibraryFile.file_path, LibraryFile.thumbnail_path).where(
  472. LibraryFile.folder_id == fid
  473. )
  474. )
  475. for file_id, file_path, thumb_path in files_result.all():
  476. file_ids.append(file_id)
  477. # Delete actual files
  478. try:
  479. if file_path and os.path.exists(file_path):
  480. os.remove(file_path)
  481. if thumb_path and os.path.exists(thumb_path):
  482. os.remove(thumb_path)
  483. except Exception as e:
  484. logger.warning(f"Failed to delete file: {e}")
  485. # Get child folders and recurse
  486. children_result = await db.execute(select(LibraryFolder.id).where(LibraryFolder.parent_id == fid))
  487. for (child_id,) in children_result.all():
  488. file_ids.extend(await get_all_file_ids(child_id))
  489. return file_ids
  490. await get_all_file_ids(folder_id)
  491. # Delete folder (cascade will handle files and subfolders)
  492. await db.delete(folder)
  493. return {"status": "success", "message": "Folder deleted"}
  494. # ============ File Endpoints ============
  495. @router.get("/files", response_model=list[FileListResponse])
  496. @router.get("/files/", response_model=list[FileListResponse])
  497. async def list_files(
  498. response: Response,
  499. folder_id: int | None = None,
  500. include_root: bool = True,
  501. db: AsyncSession = Depends(get_db),
  502. ):
  503. """List files, optionally filtered by folder.
  504. Args:
  505. folder_id: Filter by folder ID. If None and include_root=True, returns root files.
  506. include_root: If True and folder_id is None, returns files at root level.
  507. If False and folder_id is None, returns all files.
  508. """
  509. query = select(LibraryFile).options(selectinload(LibraryFile.created_by))
  510. if folder_id is not None:
  511. query = query.where(LibraryFile.folder_id == folder_id)
  512. elif include_root:
  513. query = query.where(LibraryFile.folder_id.is_(None))
  514. query = query.order_by(LibraryFile.filename)
  515. result = await db.execute(query)
  516. files = result.scalars().all()
  517. # Get duplicate counts
  518. hash_counts = {}
  519. if files:
  520. hashes = [f.file_hash for f in files if f.file_hash]
  521. if hashes:
  522. dup_result = await db.execute(
  523. select(LibraryFile.file_hash, func.count(LibraryFile.id))
  524. .where(LibraryFile.file_hash.in_(hashes))
  525. .group_by(LibraryFile.file_hash)
  526. )
  527. hash_counts = {h: c - 1 for h, c in dup_result.all()} # -1 to exclude self
  528. # Prevent browser caching of file list
  529. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  530. file_list = []
  531. for f in files:
  532. # Extract key metadata for display
  533. print_name = None
  534. print_time = None
  535. filament_grams = None
  536. if f.file_metadata:
  537. print_name = f.file_metadata.get("print_name")
  538. print_time = f.file_metadata.get("print_time_seconds")
  539. filament_grams = f.file_metadata.get("filament_used_grams")
  540. file_list.append(
  541. FileListResponse(
  542. id=f.id,
  543. folder_id=f.folder_id,
  544. filename=f.filename,
  545. file_type=f.file_type,
  546. file_size=f.file_size,
  547. thumbnail_path=f.thumbnail_path,
  548. print_count=f.print_count,
  549. duplicate_count=hash_counts.get(f.file_hash, 0) if f.file_hash else 0,
  550. created_by_id=f.created_by_id,
  551. created_by_username=f.created_by.username if f.created_by else None,
  552. created_at=f.created_at,
  553. print_name=print_name,
  554. print_time_seconds=print_time,
  555. filament_used_grams=filament_grams,
  556. )
  557. )
  558. return file_list
  559. @router.post("/files", response_model=FileUploadResponse)
  560. @router.post("/files/", response_model=FileUploadResponse)
  561. async def upload_file(
  562. file: UploadFile = File(...),
  563. folder_id: int | None = None,
  564. generate_stl_thumbnails: bool = Query(default=True),
  565. db: AsyncSession = Depends(get_db),
  566. current_user: User | None = Depends(require_auth_if_enabled),
  567. ):
  568. """Upload a file to the library."""
  569. try:
  570. if not file.filename:
  571. raise HTTPException(status_code=400, detail="Filename is required")
  572. filename = file.filename
  573. ext = os.path.splitext(filename)[1].lower()
  574. # Handle files without extension
  575. file_type = ext[1:] if ext else "unknown"
  576. # Verify folder exists if specified
  577. if folder_id is not None:
  578. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  579. if not folder_result.scalar_one_or_none():
  580. raise HTTPException(status_code=404, detail="Folder not found")
  581. # Generate unique filename for storage
  582. unique_filename = f"{uuid.uuid4().hex}{ext}"
  583. file_path = get_library_files_dir() / unique_filename
  584. # Save file
  585. content = await file.read()
  586. with open(file_path, "wb") as f:
  587. f.write(content)
  588. # Calculate hash
  589. file_hash = calculate_file_hash(file_path)
  590. # Check for duplicates
  591. dup_result = await db.execute(select(LibraryFile.id).where(LibraryFile.file_hash == file_hash).limit(1))
  592. duplicate_of = dup_result.scalar()
  593. # Extract metadata and thumbnail
  594. metadata = {}
  595. thumbnail_path = None
  596. thumbnails_dir = get_library_thumbnails_dir()
  597. if ext == ".3mf":
  598. try:
  599. parser = ThreeMFParser(str(file_path))
  600. raw_metadata = parser.parse()
  601. # Extract thumbnail before cleaning metadata
  602. thumbnail_data = raw_metadata.get("_thumbnail_data")
  603. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  604. # Save thumbnail if extracted
  605. if thumbnail_data:
  606. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  607. thumb_path = thumbnails_dir / thumb_filename
  608. with open(thumb_path, "wb") as f:
  609. f.write(thumbnail_data)
  610. thumbnail_path = str(thumb_path)
  611. # Clean metadata - remove non-JSON-serializable data (bytes, etc.)
  612. def clean_metadata(obj):
  613. if isinstance(obj, dict):
  614. return {
  615. k: clean_metadata(v)
  616. for k, v in obj.items()
  617. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  618. }
  619. elif isinstance(obj, list):
  620. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  621. elif isinstance(obj, bytes):
  622. return None
  623. return obj
  624. metadata = clean_metadata(raw_metadata)
  625. except Exception as e:
  626. logger.warning(f"Failed to parse 3MF: {e}")
  627. elif ext == ".gcode":
  628. # Extract embedded thumbnail from gcode
  629. try:
  630. thumbnail_data = extract_gcode_thumbnail(file_path)
  631. if thumbnail_data:
  632. thumb_filename = f"{uuid.uuid4().hex}.png"
  633. thumb_path = thumbnails_dir / thumb_filename
  634. with open(thumb_path, "wb") as f:
  635. f.write(thumbnail_data)
  636. thumbnail_path = str(thumb_path)
  637. except Exception as e:
  638. logger.warning(f"Failed to extract gcode thumbnail: {e}")
  639. elif ext.lower() in IMAGE_EXTENSIONS:
  640. # For image files, create a thumbnail from the image itself
  641. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  642. elif ext == ".stl":
  643. # Generate STL thumbnail if enabled
  644. if generate_stl_thumbnails:
  645. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  646. # Create database entry (store relative paths for portability)
  647. library_file = LibraryFile(
  648. folder_id=folder_id,
  649. filename=filename,
  650. file_path=to_relative_path(file_path),
  651. file_type=file_type,
  652. file_size=len(content),
  653. file_hash=file_hash,
  654. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  655. file_metadata=metadata if metadata else None,
  656. created_by_id=current_user.id if current_user else None,
  657. )
  658. db.add(library_file)
  659. await db.flush()
  660. await db.refresh(library_file)
  661. return FileUploadResponse(
  662. id=library_file.id,
  663. filename=library_file.filename,
  664. file_type=library_file.file_type,
  665. file_size=library_file.file_size,
  666. thumbnail_path=library_file.thumbnail_path,
  667. duplicate_of=duplicate_of,
  668. metadata=library_file.file_metadata,
  669. )
  670. except HTTPException:
  671. raise
  672. except Exception as e:
  673. logger.error(f"Upload failed for {file.filename}: {e}", exc_info=True)
  674. raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
  675. @router.post("/files/extract-zip", response_model=ZipExtractResponse)
  676. async def extract_zip_file(
  677. file: UploadFile = File(...),
  678. folder_id: int | None = Query(default=None),
  679. preserve_structure: bool = Query(default=True),
  680. create_folder_from_zip: bool = Query(default=False),
  681. generate_stl_thumbnails: bool = Query(default=True),
  682. db: AsyncSession = Depends(get_db),
  683. current_user: User | None = Depends(require_auth_if_enabled),
  684. ):
  685. """Upload and extract a ZIP file to the library.
  686. Args:
  687. file: The ZIP file to extract
  688. folder_id: Target folder ID (None = root)
  689. preserve_structure: If True, recreate folder structure from ZIP; if False, extract all files flat
  690. create_folder_from_zip: If True, create a folder named after the ZIP file and extract into it
  691. generate_stl_thumbnails: If True, generate thumbnails for STL files
  692. """
  693. import tempfile
  694. import zipfile
  695. if not file.filename or not file.filename.lower().endswith(".zip"):
  696. raise HTTPException(status_code=400, detail="Only ZIP files are supported")
  697. # Verify target folder exists if specified
  698. if folder_id is not None:
  699. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  700. if not folder_result.scalar_one_or_none():
  701. raise HTTPException(status_code=404, detail="Target folder not found")
  702. # Save ZIP to temp file
  703. try:
  704. with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp:
  705. content = await file.read()
  706. tmp.write(content)
  707. tmp_path = tmp.name
  708. except Exception as e:
  709. raise HTTPException(status_code=500, detail=f"Failed to save ZIP file: {str(e)}")
  710. extracted_files: list[ZipExtractResult] = []
  711. errors: list[ZipExtractError] = []
  712. folders_created = 0
  713. folder_cache: dict[str, int] = {} # path -> folder_id
  714. # If create_folder_from_zip is True, create a folder named after the ZIP file
  715. zip_folder_id = folder_id
  716. logger.info(
  717. f"ZIP extraction: create_folder_from_zip={create_folder_from_zip}, folder_id={folder_id}, filename={file.filename}"
  718. )
  719. if create_folder_from_zip and file.filename:
  720. # Remove .zip extension to get folder name
  721. zip_folder_name = file.filename[:-4] if file.filename.lower().endswith(".zip") else file.filename
  722. # Check if folder already exists
  723. existing = await db.execute(
  724. select(LibraryFolder).where(
  725. LibraryFolder.name == zip_folder_name,
  726. LibraryFolder.parent_id == folder_id if folder_id else LibraryFolder.parent_id.is_(None),
  727. )
  728. )
  729. existing_folder = existing.scalar_one_or_none()
  730. if existing_folder:
  731. zip_folder_id = existing_folder.id
  732. logger.info(f"Reusing existing folder '{zip_folder_name}' with id={zip_folder_id}")
  733. else:
  734. # Create folder
  735. new_folder = LibraryFolder(name=zip_folder_name, parent_id=folder_id)
  736. db.add(new_folder)
  737. await db.flush()
  738. await db.commit() # Commit folder creation immediately
  739. zip_folder_id = new_folder.id
  740. folders_created += 1
  741. logger.info(f"Created new folder '{zip_folder_name}' with id={zip_folder_id}")
  742. try:
  743. with zipfile.ZipFile(tmp_path, "r") as zf:
  744. # Filter out directories and hidden/system files
  745. file_list = [
  746. name
  747. for name in zf.namelist()
  748. if not name.endswith("/")
  749. and not name.startswith("__MACOSX")
  750. and not os.path.basename(name).startswith(".")
  751. ]
  752. for zip_path in file_list:
  753. try:
  754. # Determine target folder (use zip_folder_id as base if create_folder_from_zip was used)
  755. target_folder_id = zip_folder_id
  756. if preserve_structure:
  757. # Get directory path from ZIP
  758. dir_path = os.path.dirname(zip_path)
  759. if dir_path:
  760. # Create folder structure
  761. parts = dir_path.split("/")
  762. current_parent = zip_folder_id
  763. current_path = ""
  764. for part in parts:
  765. if not part:
  766. continue
  767. current_path = f"{current_path}/{part}" if current_path else part
  768. if current_path in folder_cache:
  769. current_parent = folder_cache[current_path]
  770. else:
  771. # Check if folder exists
  772. existing = await db.execute(
  773. select(LibraryFolder).where(
  774. LibraryFolder.name == part,
  775. LibraryFolder.parent_id == current_parent
  776. if current_parent
  777. else LibraryFolder.parent_id.is_(None),
  778. )
  779. )
  780. existing_folder = existing.scalar_one_or_none()
  781. if existing_folder:
  782. current_parent = existing_folder.id
  783. else:
  784. # Create folder
  785. new_folder = LibraryFolder(name=part, parent_id=current_parent)
  786. db.add(new_folder)
  787. await db.flush()
  788. current_parent = new_folder.id
  789. folders_created += 1
  790. folder_cache[current_path] = current_parent
  791. target_folder_id = current_parent
  792. # Extract file
  793. filename = os.path.basename(zip_path)
  794. ext = os.path.splitext(filename)[1].lower()
  795. file_type = ext[1:] if ext else "unknown"
  796. # Generate unique filename for storage
  797. unique_filename = f"{uuid.uuid4().hex}{ext}"
  798. file_path = get_library_files_dir() / unique_filename
  799. # Extract and save file
  800. file_content = zf.read(zip_path)
  801. with open(file_path, "wb") as f:
  802. f.write(file_content)
  803. # Calculate hash
  804. file_hash = calculate_file_hash(file_path)
  805. # Extract metadata and thumbnail for 3MF files
  806. metadata = {}
  807. thumbnail_path = None
  808. thumbnails_dir = get_library_thumbnails_dir()
  809. if ext == ".3mf":
  810. try:
  811. parser = ThreeMFParser(str(file_path))
  812. raw_metadata = parser.parse()
  813. thumbnail_data = raw_metadata.get("_thumbnail_data")
  814. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  815. if thumbnail_data:
  816. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  817. thumb_path = thumbnails_dir / thumb_filename
  818. with open(thumb_path, "wb") as f:
  819. f.write(thumbnail_data)
  820. thumbnail_path = str(thumb_path)
  821. def clean_metadata(obj):
  822. if isinstance(obj, dict):
  823. return {
  824. k: clean_metadata(v)
  825. for k, v in obj.items()
  826. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  827. }
  828. elif isinstance(obj, list):
  829. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  830. elif isinstance(obj, bytes):
  831. return None
  832. return obj
  833. metadata = clean_metadata(raw_metadata)
  834. except Exception as e:
  835. logger.warning(f"Failed to parse 3MF from ZIP: {e}")
  836. elif ext == ".gcode":
  837. try:
  838. thumbnail_data = extract_gcode_thumbnail(file_path)
  839. if thumbnail_data:
  840. thumb_filename = f"{uuid.uuid4().hex}.png"
  841. thumb_path = thumbnails_dir / thumb_filename
  842. with open(thumb_path, "wb") as f:
  843. f.write(thumbnail_data)
  844. thumbnail_path = str(thumb_path)
  845. except Exception as e:
  846. logger.warning(f"Failed to extract gcode thumbnail from ZIP: {e}")
  847. elif ext.lower() in IMAGE_EXTENSIONS:
  848. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  849. elif ext == ".stl":
  850. # Generate STL thumbnail if enabled
  851. if generate_stl_thumbnails:
  852. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  853. # Create database entry (store relative paths for portability)
  854. library_file = LibraryFile(
  855. folder_id=target_folder_id,
  856. filename=filename,
  857. file_path=to_relative_path(file_path),
  858. file_type=file_type,
  859. file_size=len(file_content),
  860. file_hash=file_hash,
  861. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  862. file_metadata=metadata if metadata else None,
  863. created_by_id=current_user.id if current_user else None,
  864. )
  865. db.add(library_file)
  866. await db.flush()
  867. await db.refresh(library_file)
  868. extracted_files.append(
  869. ZipExtractResult(
  870. filename=filename,
  871. file_id=library_file.id,
  872. folder_id=target_folder_id,
  873. )
  874. )
  875. # Commit after each file to release database lock
  876. # This prevents long-running transactions from blocking other requests
  877. await db.commit()
  878. except Exception as e:
  879. logger.error(f"Failed to extract {zip_path}: {e}")
  880. errors.append(ZipExtractError(filename=os.path.basename(zip_path), error=str(e)))
  881. # Rollback the failed file but continue with others
  882. await db.rollback()
  883. return ZipExtractResponse(
  884. extracted=len(extracted_files),
  885. folders_created=folders_created,
  886. files=extracted_files,
  887. errors=errors,
  888. )
  889. except zipfile.BadZipFile:
  890. raise HTTPException(status_code=400, detail="Invalid or corrupted ZIP file")
  891. except Exception as e:
  892. logger.error(f"ZIP extraction failed: {e}", exc_info=True)
  893. raise HTTPException(status_code=500, detail=f"ZIP extraction failed: {str(e)}")
  894. finally:
  895. # Clean up temp file
  896. try:
  897. os.unlink(tmp_path)
  898. except Exception:
  899. pass
  900. # ============ STL Thumbnail Batch Generation ============
  901. @router.post("/generate-stl-thumbnails", response_model=BatchThumbnailResponse)
  902. async def batch_generate_stl_thumbnails(
  903. request: BatchThumbnailRequest,
  904. db: AsyncSession = Depends(get_db),
  905. ):
  906. """Generate thumbnails for STL files in batch.
  907. Can generate thumbnails for:
  908. - Specific file IDs (file_ids)
  909. - All STL files in a folder (folder_id)
  910. - All STL files missing thumbnails (all_missing=True)
  911. """
  912. thumbnails_dir = get_library_thumbnails_dir()
  913. results: list[BatchThumbnailResult] = []
  914. # Build query based on request
  915. query = select(LibraryFile).where(LibraryFile.file_type == "stl")
  916. if request.file_ids:
  917. # Specific files
  918. query = query.where(LibraryFile.id.in_(request.file_ids))
  919. elif request.folder_id is not None:
  920. # All STL files in a specific folder
  921. query = query.where(LibraryFile.folder_id == request.folder_id)
  922. if not request.all_missing:
  923. # If not specifically asking for missing thumbnails, get all
  924. pass
  925. else:
  926. query = query.where(LibraryFile.thumbnail_path.is_(None))
  927. elif request.all_missing:
  928. # All STL files without thumbnails
  929. query = query.where(LibraryFile.thumbnail_path.is_(None))
  930. else:
  931. # No criteria specified - return empty
  932. return BatchThumbnailResponse(
  933. processed=0,
  934. succeeded=0,
  935. failed=0,
  936. results=[],
  937. )
  938. result = await db.execute(query)
  939. stl_files = result.scalars().all()
  940. succeeded = 0
  941. failed = 0
  942. for stl_file in stl_files:
  943. file_path = to_absolute_path(stl_file.file_path)
  944. if not file_path or not file_path.exists():
  945. results.append(
  946. BatchThumbnailResult(
  947. file_id=stl_file.id,
  948. filename=stl_file.filename,
  949. success=False,
  950. error="File not found on disk",
  951. )
  952. )
  953. failed += 1
  954. continue
  955. try:
  956. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  957. if thumbnail_path:
  958. # Update database with relative path
  959. stl_file.thumbnail_path = to_relative_path(thumbnail_path)
  960. await db.flush()
  961. results.append(
  962. BatchThumbnailResult(
  963. file_id=stl_file.id,
  964. filename=stl_file.filename,
  965. success=True,
  966. )
  967. )
  968. succeeded += 1
  969. else:
  970. results.append(
  971. BatchThumbnailResult(
  972. file_id=stl_file.id,
  973. filename=stl_file.filename,
  974. success=False,
  975. error="Thumbnail generation failed",
  976. )
  977. )
  978. failed += 1
  979. except Exception as e:
  980. logger.error(f"Failed to generate thumbnail for {stl_file.filename}: {e}")
  981. results.append(
  982. BatchThumbnailResult(
  983. file_id=stl_file.id,
  984. filename=stl_file.filename,
  985. success=False,
  986. error=str(e),
  987. )
  988. )
  989. failed += 1
  990. await db.commit()
  991. return BatchThumbnailResponse(
  992. processed=len(stl_files),
  993. succeeded=succeeded,
  994. failed=failed,
  995. results=results,
  996. )
  997. # ============ Queue Operations ============
  998. # NOTE: These routes must be defined BEFORE /files/{file_id} to avoid path parameter conflicts
  999. def is_sliced_file(filename: str) -> bool:
  1000. """Check if a file is a sliced (printable) file.
  1001. Sliced files are:
  1002. - .gcode files
  1003. - .3mf files that contain '.gcode.' in the name (e.g., filename.gcode.3mf)
  1004. """
  1005. lower = filename.lower()
  1006. return lower.endswith(".gcode") or ".gcode." in lower
  1007. @router.post("/files/add-to-queue", response_model=AddToQueueResponse)
  1008. async def add_files_to_queue(
  1009. request: AddToQueueRequest,
  1010. db: AsyncSession = Depends(get_db),
  1011. ):
  1012. """Add library files to the print queue.
  1013. Only sliced files (.gcode or .gcode.3mf) can be added to the queue.
  1014. The archive will be created automatically when the print starts.
  1015. """
  1016. added: list[AddToQueueResult] = []
  1017. errors: list[AddToQueueError] = []
  1018. # Get all requested files
  1019. result = await db.execute(select(LibraryFile).where(LibraryFile.id.in_(request.file_ids)))
  1020. files = {f.id: f for f in result.scalars().all()}
  1021. # Get max position for queue ordering
  1022. pos_result = await db.execute(select(func.coalesce(func.max(PrintQueueItem.position), 0)))
  1023. max_position = pos_result.scalar() or 0
  1024. for file_id in request.file_ids:
  1025. lib_file = files.get(file_id)
  1026. if not lib_file:
  1027. errors.append(AddToQueueError(file_id=file_id, filename="(not found)", error="File not found"))
  1028. continue
  1029. # Validate file is sliced
  1030. if not is_sliced_file(lib_file.filename):
  1031. errors.append(
  1032. AddToQueueError(
  1033. file_id=file_id,
  1034. filename=lib_file.filename,
  1035. error="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1036. )
  1037. )
  1038. continue
  1039. try:
  1040. # Verify file exists on disk
  1041. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1042. if not file_path.exists():
  1043. errors.append(
  1044. AddToQueueError(file_id=file_id, filename=lib_file.filename, error="File not found on disk")
  1045. )
  1046. continue
  1047. # Create queue item referencing library file (archive created at print start)
  1048. max_position += 1
  1049. queue_item = PrintQueueItem(
  1050. printer_id=None, # Unassigned
  1051. library_file_id=file_id,
  1052. position=max_position,
  1053. status="pending",
  1054. )
  1055. db.add(queue_item)
  1056. await db.flush() # Get queue_item.id
  1057. added.append(
  1058. AddToQueueResult(
  1059. file_id=file_id,
  1060. filename=lib_file.filename,
  1061. queue_item_id=queue_item.id,
  1062. )
  1063. )
  1064. except Exception as e:
  1065. logger.exception(f"Error adding file {file_id} to queue")
  1066. errors.append(AddToQueueError(file_id=file_id, filename=lib_file.filename, error=str(e)))
  1067. await db.commit()
  1068. return AddToQueueResponse(added=added, errors=errors)
  1069. @router.get("/files/{file_id}/plates")
  1070. async def get_library_file_plates(
  1071. file_id: int,
  1072. db: AsyncSession = Depends(get_db),
  1073. ):
  1074. """Get available plates from a multi-plate 3MF library file.
  1075. Returns a list of plates with their index, name, thumbnail availability,
  1076. and filament requirements. For single-plate exports, returns a single plate.
  1077. """
  1078. import xml.etree.ElementTree as ET
  1079. import zipfile
  1080. # Get the library file
  1081. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1082. lib_file = result.scalar_one_or_none()
  1083. if not lib_file:
  1084. raise HTTPException(status_code=404, detail="File not found")
  1085. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1086. if not file_path.exists():
  1087. raise HTTPException(status_code=404, detail="File not found on disk")
  1088. # Only 3MF files have plates
  1089. if not lib_file.filename.lower().endswith(".3mf"):
  1090. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1091. plates = []
  1092. try:
  1093. with zipfile.ZipFile(file_path, "r") as zf:
  1094. namelist = zf.namelist()
  1095. # Find all plate gcode files to determine available plates
  1096. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1097. if not gcode_files:
  1098. # No sliced plates found
  1099. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1100. # Extract plate indices from gcode filenames
  1101. plate_indices = []
  1102. for gf in gcode_files:
  1103. try:
  1104. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1105. plate_indices.append(int(plate_str))
  1106. except ValueError:
  1107. pass
  1108. plate_indices.sort()
  1109. # Parse model_settings.config for plate names
  1110. plate_names = {}
  1111. if "Metadata/model_settings.config" in namelist:
  1112. try:
  1113. model_content = zf.read("Metadata/model_settings.config").decode()
  1114. model_root = ET.fromstring(model_content)
  1115. for plate_elem in model_root.findall(".//plate"):
  1116. plater_id = None
  1117. plater_name = None
  1118. for meta in plate_elem.findall("metadata"):
  1119. key = meta.get("key")
  1120. value = meta.get("value")
  1121. if key == "plater_id" and value:
  1122. try:
  1123. plater_id = int(value)
  1124. except ValueError:
  1125. pass
  1126. elif key == "plater_name" and value:
  1127. plater_name = value.strip()
  1128. if plater_id is not None and plater_name:
  1129. plate_names[plater_id] = plater_name
  1130. except Exception:
  1131. pass
  1132. # Parse slice_info.config for plate metadata
  1133. plate_metadata = {}
  1134. if "Metadata/slice_info.config" in namelist:
  1135. content = zf.read("Metadata/slice_info.config").decode()
  1136. root = ET.fromstring(content)
  1137. for plate_elem in root.findall(".//plate"):
  1138. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1139. plate_index = None
  1140. for meta in plate_elem.findall("metadata"):
  1141. key = meta.get("key")
  1142. value = meta.get("value")
  1143. if key == "index" and value:
  1144. try:
  1145. plate_index = int(value)
  1146. except ValueError:
  1147. pass
  1148. elif key == "prediction" and value:
  1149. try:
  1150. plate_info["prediction"] = int(value)
  1151. except ValueError:
  1152. pass
  1153. elif key == "weight" and value:
  1154. try:
  1155. plate_info["weight"] = float(value)
  1156. except ValueError:
  1157. pass
  1158. # Get filaments used in this plate
  1159. for filament_elem in plate_elem.findall("filament"):
  1160. filament_id = filament_elem.get("id")
  1161. filament_type = filament_elem.get("type", "")
  1162. filament_color = filament_elem.get("color", "")
  1163. used_g = filament_elem.get("used_g", "0")
  1164. used_m = filament_elem.get("used_m", "0")
  1165. try:
  1166. used_grams = float(used_g)
  1167. except (ValueError, TypeError):
  1168. used_grams = 0
  1169. if used_grams > 0 and filament_id:
  1170. plate_info["filaments"].append(
  1171. {
  1172. "slot_id": int(filament_id),
  1173. "type": filament_type,
  1174. "color": filament_color,
  1175. "used_grams": round(used_grams, 1),
  1176. "used_meters": float(used_m) if used_m else 0,
  1177. }
  1178. )
  1179. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1180. # Collect object names
  1181. for obj_elem in plate_elem.findall("object"):
  1182. obj_name = obj_elem.get("name")
  1183. if obj_name and obj_name not in plate_info["objects"]:
  1184. plate_info["objects"].append(obj_name)
  1185. # Set plate name
  1186. if plate_index is not None:
  1187. custom_name = plate_names.get(plate_index)
  1188. if custom_name:
  1189. plate_info["name"] = custom_name
  1190. elif plate_info["objects"]:
  1191. plate_info["name"] = plate_info["objects"][0]
  1192. plate_metadata[plate_index] = plate_info
  1193. # Build plate list
  1194. for idx in plate_indices:
  1195. meta = plate_metadata.get(idx, {})
  1196. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1197. plates.append(
  1198. {
  1199. "index": idx,
  1200. "name": meta.get("name"),
  1201. "objects": meta.get("objects", []),
  1202. "has_thumbnail": has_thumbnail,
  1203. "thumbnail_url": f"/api/v1/library/files/{file_id}/plate-thumbnail/{idx}"
  1204. if has_thumbnail
  1205. else None,
  1206. "print_time_seconds": meta.get("prediction"),
  1207. "filament_used_grams": meta.get("weight"),
  1208. "filaments": meta.get("filaments", []),
  1209. }
  1210. )
  1211. except Exception as e:
  1212. logger.warning(f"Failed to parse plates from library file {file_id}: {e}")
  1213. return {
  1214. "file_id": file_id,
  1215. "filename": lib_file.filename,
  1216. "plates": plates,
  1217. "is_multi_plate": len(plates) > 1,
  1218. }
  1219. @router.get("/files/{file_id}/plate-thumbnail/{plate_index}")
  1220. async def get_library_file_plate_thumbnail(
  1221. file_id: int,
  1222. plate_index: int,
  1223. db: AsyncSession = Depends(get_db),
  1224. ):
  1225. """Get the thumbnail image for a specific plate from a library file."""
  1226. import zipfile
  1227. from starlette.responses import Response
  1228. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1229. lib_file = result.scalar_one_or_none()
  1230. if not lib_file:
  1231. raise HTTPException(status_code=404, detail="File not found")
  1232. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1233. if not file_path.exists():
  1234. raise HTTPException(status_code=404, detail="File not found on disk")
  1235. try:
  1236. with zipfile.ZipFile(file_path, "r") as zf:
  1237. thumb_path = f"Metadata/plate_{plate_index}.png"
  1238. if thumb_path in zf.namelist():
  1239. data = zf.read(thumb_path)
  1240. return Response(content=data, media_type="image/png")
  1241. except Exception:
  1242. pass
  1243. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1244. @router.get("/files/{file_id}/filament-requirements")
  1245. async def get_library_file_filament_requirements(
  1246. file_id: int,
  1247. plate_id: int | None = None,
  1248. db: AsyncSession = Depends(get_db),
  1249. ):
  1250. """Get filament requirements from a library file.
  1251. Parses the 3MF file to extract filament slot IDs, types, colors, and usage.
  1252. This enables AMS slot assignment when printing from the file manager.
  1253. Args:
  1254. file_id: The library file ID
  1255. plate_id: Optional plate index to get filaments for a specific plate
  1256. """
  1257. import xml.etree.ElementTree as ET
  1258. import zipfile
  1259. # Get the library file
  1260. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1261. lib_file = result.scalar_one_or_none()
  1262. if not lib_file:
  1263. raise HTTPException(status_code=404, detail="File not found")
  1264. # Get the full file path
  1265. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1266. if not file_path.exists():
  1267. raise HTTPException(status_code=404, detail="File not found on disk")
  1268. # Only 3MF files have parseable filament info
  1269. if not lib_file.filename.lower().endswith(".3mf"):
  1270. return {"file_id": file_id, "filename": lib_file.filename, "plate_id": plate_id, "filaments": []}
  1271. filaments = []
  1272. try:
  1273. with zipfile.ZipFile(file_path, "r") as zf:
  1274. # Parse slice_info.config for filament requirements
  1275. if "Metadata/slice_info.config" in zf.namelist():
  1276. content = zf.read("Metadata/slice_info.config").decode()
  1277. root = ET.fromstring(content)
  1278. if plate_id is not None:
  1279. # Find filaments for specific plate
  1280. for plate_elem in root.findall(".//plate"):
  1281. # Check if this is the requested plate
  1282. plate_index = None
  1283. for meta in plate_elem.findall("metadata"):
  1284. if meta.get("key") == "index":
  1285. try:
  1286. plate_index = int(meta.get("value", ""))
  1287. except ValueError:
  1288. pass
  1289. break
  1290. if plate_index == plate_id:
  1291. # Extract filaments from this plate
  1292. for filament_elem in plate_elem.findall("filament"):
  1293. filament_id = filament_elem.get("id")
  1294. filament_type = filament_elem.get("type", "")
  1295. filament_color = filament_elem.get("color", "")
  1296. used_g = filament_elem.get("used_g", "0")
  1297. used_m = filament_elem.get("used_m", "0")
  1298. try:
  1299. used_grams = float(used_g)
  1300. except (ValueError, TypeError):
  1301. used_grams = 0
  1302. if used_grams > 0 and filament_id:
  1303. filaments.append(
  1304. {
  1305. "slot_id": int(filament_id),
  1306. "type": filament_type,
  1307. "color": filament_color,
  1308. "used_grams": round(used_grams, 1),
  1309. "used_meters": float(used_m) if used_m else 0,
  1310. }
  1311. )
  1312. break
  1313. else:
  1314. # Extract all filaments with used_g > 0 (for single-plate or overview)
  1315. for filament_elem in root.findall(".//filament"):
  1316. filament_id = filament_elem.get("id")
  1317. filament_type = filament_elem.get("type", "")
  1318. filament_color = filament_elem.get("color", "")
  1319. used_g = filament_elem.get("used_g", "0")
  1320. used_m = filament_elem.get("used_m", "0")
  1321. try:
  1322. used_grams = float(used_g)
  1323. except (ValueError, TypeError):
  1324. used_grams = 0
  1325. if used_grams > 0 and filament_id:
  1326. filaments.append(
  1327. {
  1328. "slot_id": int(filament_id),
  1329. "type": filament_type,
  1330. "color": filament_color,
  1331. "used_grams": round(used_grams, 1),
  1332. "used_meters": float(used_m) if used_m else 0,
  1333. }
  1334. )
  1335. # Sort by slot ID
  1336. filaments.sort(key=lambda x: x["slot_id"])
  1337. except Exception as e:
  1338. logger.warning(f"Failed to parse filament requirements from library file {file_id}: {e}")
  1339. return {
  1340. "file_id": file_id,
  1341. "filename": lib_file.filename,
  1342. "plate_id": plate_id,
  1343. "filaments": filaments,
  1344. }
  1345. @router.post("/files/{file_id}/print")
  1346. async def print_library_file(
  1347. file_id: int,
  1348. printer_id: int,
  1349. body: FilePrintRequest | None = None,
  1350. db: AsyncSession = Depends(get_db),
  1351. ):
  1352. """Print a library file directly.
  1353. This endpoint:
  1354. 1. Creates an archive from the library file
  1355. 2. Uploads the file to the printer
  1356. 3. Starts the print
  1357. Only sliced files (.gcode or .gcode.3mf) can be printed.
  1358. """
  1359. import zipfile
  1360. from backend.app.main import register_expected_print
  1361. from backend.app.models.printer import Printer
  1362. from backend.app.services.bambu_ftp import (
  1363. delete_file_async,
  1364. get_ftp_retry_settings,
  1365. upload_file_async,
  1366. with_ftp_retry,
  1367. )
  1368. from backend.app.services.printer_manager import printer_manager
  1369. # Use defaults if no body provided
  1370. if body is None:
  1371. body = FilePrintRequest()
  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. # Validate file is sliced
  1378. if not is_sliced_file(lib_file.filename):
  1379. raise HTTPException(
  1380. status_code=400,
  1381. detail="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1382. )
  1383. # Get the full file path
  1384. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1385. if not file_path.exists():
  1386. raise HTTPException(status_code=404, detail="File not found on disk")
  1387. # Get printer
  1388. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1389. printer = result.scalar_one_or_none()
  1390. if not printer:
  1391. raise HTTPException(status_code=404, detail="Printer not found")
  1392. # Check printer is connected
  1393. if not printer_manager.is_connected(printer_id):
  1394. raise HTTPException(status_code=400, detail="Printer is not connected")
  1395. # Create archive from the library file
  1396. archive_service = ArchiveService(db)
  1397. archive = await archive_service.archive_print(
  1398. printer_id=printer_id,
  1399. source_file=file_path,
  1400. )
  1401. if not archive:
  1402. raise HTTPException(status_code=500, detail="Failed to create archive")
  1403. await db.flush()
  1404. # Prepare remote filename
  1405. base_name = lib_file.filename
  1406. if base_name.endswith(".gcode.3mf"):
  1407. base_name = base_name[:-10]
  1408. elif base_name.endswith(".3mf"):
  1409. base_name = base_name[:-4]
  1410. remote_filename = f"{base_name}.3mf"
  1411. remote_path = f"/{remote_filename}"
  1412. # Get FTP retry settings
  1413. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1414. # Delete existing file if present (avoids 553 error)
  1415. await delete_file_async(
  1416. printer.ip_address,
  1417. printer.access_code,
  1418. remote_path,
  1419. socket_timeout=ftp_timeout,
  1420. printer_model=printer.model,
  1421. )
  1422. # Upload file to printer
  1423. if ftp_retry_enabled:
  1424. uploaded = await with_ftp_retry(
  1425. upload_file_async,
  1426. printer.ip_address,
  1427. printer.access_code,
  1428. file_path,
  1429. remote_path,
  1430. socket_timeout=ftp_timeout,
  1431. printer_model=printer.model,
  1432. max_retries=ftp_retry_count,
  1433. retry_delay=ftp_retry_delay,
  1434. operation_name=f"Upload for print to {printer.name}",
  1435. )
  1436. else:
  1437. uploaded = await upload_file_async(
  1438. printer.ip_address,
  1439. printer.access_code,
  1440. file_path,
  1441. remote_path,
  1442. socket_timeout=ftp_timeout,
  1443. printer_model=printer.model,
  1444. )
  1445. if not uploaded:
  1446. raise HTTPException(status_code=500, detail="Failed to upload file to printer")
  1447. # Register this as an expected print so we don't create a duplicate archive
  1448. register_expected_print(printer_id, remote_filename, archive.id)
  1449. # Determine plate ID
  1450. if body.plate_id is not None:
  1451. plate_id = body.plate_id
  1452. else:
  1453. plate_id = 1
  1454. try:
  1455. with zipfile.ZipFile(file_path, "r") as zf:
  1456. for name in zf.namelist():
  1457. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1458. plate_str = name[15:-6]
  1459. plate_id = int(plate_str)
  1460. break
  1461. except Exception:
  1462. pass
  1463. logger.info(
  1464. f"Print library file {file_id}: archive_id={archive.id}, plate_id={plate_id}, "
  1465. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}"
  1466. )
  1467. # Start the print
  1468. started = printer_manager.start_print(
  1469. printer_id,
  1470. remote_filename,
  1471. plate_id,
  1472. ams_mapping=body.ams_mapping,
  1473. timelapse=body.timelapse,
  1474. bed_levelling=body.bed_levelling,
  1475. flow_cali=body.flow_cali,
  1476. vibration_cali=body.vibration_cali,
  1477. layer_inspect=body.layer_inspect,
  1478. use_ams=body.use_ams,
  1479. )
  1480. if not started:
  1481. raise HTTPException(status_code=500, detail="Failed to start print")
  1482. await db.commit()
  1483. return {
  1484. "status": "printing",
  1485. "printer_id": printer_id,
  1486. "archive_id": archive.id,
  1487. "filename": lib_file.filename,
  1488. }
  1489. # ============ File Detail Endpoints ============
  1490. @router.get("/files/{file_id}", response_model=FileResponseSchema)
  1491. async def get_file(file_id: int, db: AsyncSession = Depends(get_db)):
  1492. """Get a file by ID with full details."""
  1493. result = await db.execute(
  1494. select(LibraryFile).options(selectinload(LibraryFile.created_by)).where(LibraryFile.id == file_id)
  1495. )
  1496. file = result.scalar_one_or_none()
  1497. if not file:
  1498. raise HTTPException(status_code=404, detail="File not found")
  1499. # Get folder name
  1500. folder_name = None
  1501. if file.folder_id:
  1502. folder_result = await db.execute(select(LibraryFolder.name).where(LibraryFolder.id == file.folder_id))
  1503. folder_name = folder_result.scalar()
  1504. # Get project name
  1505. project_name = None
  1506. if file.project_id:
  1507. project_result = await db.execute(select(Project.name).where(Project.id == file.project_id))
  1508. project_name = project_result.scalar()
  1509. # Get duplicates
  1510. duplicates = []
  1511. duplicate_count = 0
  1512. if file.file_hash:
  1513. dup_result = await db.execute(
  1514. select(LibraryFile, LibraryFolder.name)
  1515. .outerjoin(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  1516. .where(LibraryFile.file_hash == file.file_hash, LibraryFile.id != file.id)
  1517. )
  1518. for dup_file, dup_folder_name in dup_result.all():
  1519. duplicates.append(
  1520. FileDuplicate(
  1521. id=dup_file.id,
  1522. filename=dup_file.filename,
  1523. folder_id=dup_file.folder_id,
  1524. folder_name=dup_folder_name,
  1525. created_at=dup_file.created_at,
  1526. )
  1527. )
  1528. duplicate_count = len(duplicates)
  1529. return FileResponseSchema(
  1530. id=file.id,
  1531. folder_id=file.folder_id,
  1532. folder_name=folder_name,
  1533. project_id=file.project_id,
  1534. project_name=project_name,
  1535. filename=file.filename,
  1536. file_path=file.file_path,
  1537. file_type=file.file_type,
  1538. file_size=file.file_size,
  1539. file_hash=file.file_hash,
  1540. thumbnail_path=file.thumbnail_path,
  1541. metadata=file.file_metadata,
  1542. print_count=file.print_count,
  1543. last_printed_at=file.last_printed_at,
  1544. notes=file.notes,
  1545. duplicates=duplicates if duplicates else None,
  1546. duplicate_count=duplicate_count,
  1547. created_by_id=file.created_by_id,
  1548. created_by_username=file.created_by.username if file.created_by else None,
  1549. created_at=file.created_at,
  1550. updated_at=file.updated_at,
  1551. )
  1552. @router.put("/files/{file_id}", response_model=FileResponseSchema)
  1553. async def update_file(
  1554. file_id: int,
  1555. data: FileUpdate,
  1556. db: AsyncSession = Depends(get_db),
  1557. auth_result: tuple[User | None, bool] = Depends(
  1558. require_ownership_permission(
  1559. Permission.LIBRARY_UPDATE_ALL,
  1560. Permission.LIBRARY_UPDATE_OWN,
  1561. )
  1562. ),
  1563. ):
  1564. """Update a file's metadata."""
  1565. user, can_modify_all = auth_result
  1566. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1567. file = result.scalar_one_or_none()
  1568. if not file:
  1569. raise HTTPException(status_code=404, detail="File not found")
  1570. # Ownership check
  1571. if not can_modify_all:
  1572. if file.created_by_id != user.id:
  1573. raise HTTPException(status_code=403, detail="You can only update your own files")
  1574. if data.filename is not None:
  1575. # Validate filename doesn't contain path separators
  1576. if "/" in data.filename or "\\" in data.filename:
  1577. raise HTTPException(status_code=400, detail="Filename cannot contain path separators")
  1578. file.filename = data.filename
  1579. if data.folder_id is not None:
  1580. if data.folder_id == 0:
  1581. file.folder_id = None
  1582. else:
  1583. # Verify folder exists
  1584. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  1585. if not folder_result.scalar_one_or_none():
  1586. raise HTTPException(status_code=404, detail="Folder not found")
  1587. file.folder_id = data.folder_id
  1588. if data.project_id is not None:
  1589. if data.project_id == 0:
  1590. file.project_id = None
  1591. else:
  1592. # Verify project exists
  1593. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  1594. if not project_result.scalar_one_or_none():
  1595. raise HTTPException(status_code=404, detail="Project not found")
  1596. file.project_id = data.project_id
  1597. if data.notes is not None:
  1598. file.notes = data.notes if data.notes else None
  1599. await db.flush()
  1600. await db.refresh(file)
  1601. # Return full response (reuse get_file logic)
  1602. return await get_file(file_id, db)
  1603. @router.delete("/files/{file_id}")
  1604. async def delete_file(
  1605. file_id: int,
  1606. db: AsyncSession = Depends(get_db),
  1607. auth_result: tuple[User | None, bool] = Depends(
  1608. require_ownership_permission(
  1609. Permission.LIBRARY_DELETE_ALL,
  1610. Permission.LIBRARY_DELETE_OWN,
  1611. )
  1612. ),
  1613. ):
  1614. """Delete a file."""
  1615. user, can_modify_all = auth_result
  1616. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1617. file = result.scalar_one_or_none()
  1618. if not file:
  1619. raise HTTPException(status_code=404, detail="File not found")
  1620. # Ownership check
  1621. if not can_modify_all:
  1622. if file.created_by_id != user.id:
  1623. raise HTTPException(status_code=403, detail="You can only delete your own files")
  1624. # Delete actual files
  1625. try:
  1626. abs_file_path = to_absolute_path(file.file_path)
  1627. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  1628. if abs_file_path and abs_file_path.exists():
  1629. abs_file_path.unlink()
  1630. if abs_thumb_path and abs_thumb_path.exists():
  1631. abs_thumb_path.unlink()
  1632. except Exception as e:
  1633. logger.warning(f"Failed to delete file from disk: {e}")
  1634. await db.delete(file)
  1635. return {"status": "success", "message": "File deleted"}
  1636. # ============ File Content Endpoints ============
  1637. @router.get("/files/{file_id}/download")
  1638. async def download_file(file_id: int, db: AsyncSession = Depends(get_db)):
  1639. """Download a file."""
  1640. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1641. file = result.scalar_one_or_none()
  1642. if not file:
  1643. raise HTTPException(status_code=404, detail="File not found")
  1644. abs_path = to_absolute_path(file.file_path)
  1645. if not abs_path or not abs_path.exists():
  1646. raise HTTPException(status_code=404, detail="File not found on disk")
  1647. return FastAPIFileResponse(
  1648. str(abs_path),
  1649. filename=file.filename,
  1650. media_type="application/octet-stream",
  1651. )
  1652. @router.get("/files/{file_id}/thumbnail")
  1653. async def get_thumbnail(file_id: int, db: AsyncSession = Depends(get_db)):
  1654. """Get a file's thumbnail."""
  1655. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1656. file = result.scalar_one_or_none()
  1657. if not file:
  1658. raise HTTPException(status_code=404, detail="File not found")
  1659. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  1660. if not abs_thumb_path or not abs_thumb_path.exists():
  1661. raise HTTPException(status_code=404, detail="Thumbnail not found")
  1662. # Detect media type from extension
  1663. thumb_ext = abs_thumb_path.suffix.lower()
  1664. media_types = {
  1665. ".png": "image/png",
  1666. ".jpg": "image/jpeg",
  1667. ".jpeg": "image/jpeg",
  1668. ".gif": "image/gif",
  1669. ".webp": "image/webp",
  1670. }
  1671. media_type = media_types.get(thumb_ext, "image/png")
  1672. return FastAPIFileResponse(str(abs_thumb_path), media_type=media_type)
  1673. @router.get("/files/{file_id}/gcode")
  1674. async def get_gcode(file_id: int, db: AsyncSession = Depends(get_db)):
  1675. """Get gcode for a file (for preview)."""
  1676. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1677. file = result.scalar_one_or_none()
  1678. if not file:
  1679. raise HTTPException(status_code=404, detail="File not found")
  1680. abs_path = to_absolute_path(file.file_path)
  1681. if not abs_path or not abs_path.exists():
  1682. raise HTTPException(status_code=404, detail="File not found on disk")
  1683. if file.file_type == "gcode":
  1684. return FastAPIFileResponse(str(abs_path), media_type="text/plain")
  1685. elif file.file_type == "3mf":
  1686. # Extract gcode from 3mf
  1687. import zipfile
  1688. try:
  1689. with zipfile.ZipFile(str(abs_path), "r") as zf:
  1690. # Find gcode file
  1691. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  1692. if not gcode_files:
  1693. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  1694. gcode_content = zf.read(gcode_files[0])
  1695. from fastapi.responses import Response
  1696. return Response(content=gcode_content, media_type="text/plain")
  1697. except zipfile.BadZipFile:
  1698. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  1699. else:
  1700. raise HTTPException(status_code=400, detail="Unsupported file type")
  1701. # ============ Bulk Operations ============
  1702. @router.post("/files/move")
  1703. async def move_files(data: FileMoveRequest, db: AsyncSession = Depends(get_db)):
  1704. """Move multiple files to a folder."""
  1705. # Verify folder exists if specified
  1706. if data.folder_id is not None:
  1707. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  1708. if not folder_result.scalar_one_or_none():
  1709. raise HTTPException(status_code=404, detail="Folder not found")
  1710. # Update files
  1711. moved = 0
  1712. for file_id in data.file_ids:
  1713. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1714. file = result.scalar_one_or_none()
  1715. if file:
  1716. file.folder_id = data.folder_id
  1717. moved += 1
  1718. return {"status": "success", "moved": moved}
  1719. @router.post("/bulk-delete", response_model=BulkDeleteResponse)
  1720. async def bulk_delete(
  1721. data: BulkDeleteRequest,
  1722. db: AsyncSession = Depends(get_db),
  1723. auth_result: tuple[User | None, bool] = Depends(
  1724. require_ownership_permission(
  1725. Permission.LIBRARY_DELETE_ALL,
  1726. Permission.LIBRARY_DELETE_OWN,
  1727. )
  1728. ),
  1729. ):
  1730. """Delete multiple files and/or folders.
  1731. Files not owned by the user are skipped (unless user has *_all permission).
  1732. """
  1733. user, can_modify_all = auth_result
  1734. deleted_files = 0
  1735. deleted_folders = 0
  1736. skipped_files = 0
  1737. # Delete files first
  1738. for file_id in data.file_ids:
  1739. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1740. file = result.scalar_one_or_none()
  1741. if file:
  1742. # Ownership check
  1743. if not can_modify_all and file.created_by_id != user.id:
  1744. skipped_files += 1
  1745. continue
  1746. try:
  1747. abs_file_path = to_absolute_path(file.file_path)
  1748. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  1749. if abs_file_path and abs_file_path.exists():
  1750. abs_file_path.unlink()
  1751. if abs_thumb_path and abs_thumb_path.exists():
  1752. abs_thumb_path.unlink()
  1753. except Exception as e:
  1754. logger.warning(f"Failed to delete file from disk: {e}")
  1755. await db.delete(file)
  1756. deleted_files += 1
  1757. # Delete folders (cascade will handle contents)
  1758. # Note: Folders don't have ownership tracking currently, require *_all permission
  1759. for folder_id in data.folder_ids:
  1760. if not can_modify_all:
  1761. # Users without *_all permission cannot delete folders
  1762. continue
  1763. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  1764. folder = result.scalar_one_or_none()
  1765. if folder:
  1766. # Count files that will be deleted
  1767. file_count_result = await db.execute(
  1768. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id)
  1769. )
  1770. deleted_files += file_count_result.scalar() or 0
  1771. await db.delete(folder)
  1772. deleted_folders += 1
  1773. return BulkDeleteResponse(deleted_files=deleted_files, deleted_folders=deleted_folders)
  1774. # ============ Stats Endpoint ============
  1775. @router.get("/stats")
  1776. async def get_library_stats(db: AsyncSession = Depends(get_db)):
  1777. """Get library statistics."""
  1778. # Total files
  1779. total_files_result = await db.execute(select(func.count(LibraryFile.id)))
  1780. total_files = total_files_result.scalar() or 0
  1781. # Total folders
  1782. total_folders_result = await db.execute(select(func.count(LibraryFolder.id)))
  1783. total_folders = total_folders_result.scalar() or 0
  1784. # Total size
  1785. total_size_result = await db.execute(select(func.sum(LibraryFile.file_size)))
  1786. total_size = total_size_result.scalar() or 0
  1787. # Files by type
  1788. type_result = await db.execute(
  1789. select(LibraryFile.file_type, func.count(LibraryFile.id)).group_by(LibraryFile.file_type)
  1790. )
  1791. files_by_type = dict(type_result.all())
  1792. # Total prints
  1793. total_prints_result = await db.execute(select(func.sum(LibraryFile.print_count)))
  1794. total_prints = total_prints_result.scalar() or 0
  1795. # Disk space info
  1796. library_dir = get_library_dir()
  1797. try:
  1798. disk_stat = shutil.disk_usage(library_dir)
  1799. disk_free_bytes = disk_stat.free
  1800. disk_total_bytes = disk_stat.total
  1801. disk_used_bytes = disk_stat.used
  1802. except Exception:
  1803. disk_free_bytes = 0
  1804. disk_total_bytes = 0
  1805. disk_used_bytes = 0
  1806. return {
  1807. "total_files": total_files,
  1808. "total_folders": total_folders,
  1809. "total_size_bytes": total_size,
  1810. "files_by_type": files_by_type,
  1811. "total_prints": total_prints,
  1812. "disk_free_bytes": disk_free_bytes,
  1813. "disk_total_bytes": disk_total_bytes,
  1814. "disk_used_bytes": disk_used_bytes,
  1815. }