library.py 76 KB

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