library.py 79 KB

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