library.py 60 KB

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