library.py 60 KB

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