library.py 77 KB

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