library.py 72 KB

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