library.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. """API routes for File Manager (Library) functionality."""
  2. import base64
  3. import hashlib
  4. import logging
  5. import os
  6. import re
  7. import shutil
  8. import uuid
  9. from pathlib import Path
  10. from fastapi import APIRouter, Depends, File, HTTPException, Response, UploadFile
  11. from fastapi.responses import FileResponse as FastAPIFileResponse
  12. from sqlalchemy import func, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.config import settings as app_settings
  15. from backend.app.core.database import get_db
  16. from backend.app.models.archive import PrintArchive
  17. from backend.app.models.library import LibraryFile, LibraryFolder
  18. from backend.app.models.print_queue import PrintQueueItem
  19. from backend.app.models.project import Project
  20. from backend.app.schemas.library import (
  21. AddToQueueError,
  22. AddToQueueRequest,
  23. AddToQueueResponse,
  24. AddToQueueResult,
  25. BulkDeleteRequest,
  26. BulkDeleteResponse,
  27. FileDuplicate,
  28. FileListResponse,
  29. FileMoveRequest,
  30. FilePrintRequest,
  31. FileResponse as FileResponseSchema,
  32. FileUpdate,
  33. FileUploadResponse,
  34. FolderCreate,
  35. FolderResponse,
  36. FolderTreeItem,
  37. FolderUpdate,
  38. 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 = None,
  631. preserve_structure: bool = True,
  632. db: AsyncSession = Depends(get_db),
  633. ):
  634. """Upload and extract a ZIP file to the library.
  635. Args:
  636. file: The ZIP file to extract
  637. folder_id: Target folder ID (None = root)
  638. preserve_structure: If True, recreate folder structure from ZIP; if False, extract all files flat
  639. """
  640. import tempfile
  641. import zipfile
  642. if not file.filename or not file.filename.lower().endswith(".zip"):
  643. raise HTTPException(status_code=400, detail="Only ZIP files are supported")
  644. # Verify target folder exists if specified
  645. if folder_id is not None:
  646. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  647. if not folder_result.scalar_one_or_none():
  648. raise HTTPException(status_code=404, detail="Target folder not found")
  649. # Save ZIP to temp file
  650. try:
  651. with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp:
  652. content = await file.read()
  653. tmp.write(content)
  654. tmp_path = tmp.name
  655. except Exception as e:
  656. raise HTTPException(status_code=500, detail=f"Failed to save ZIP file: {str(e)}")
  657. extracted_files: list[ZipExtractResult] = []
  658. errors: list[ZipExtractError] = []
  659. folders_created = 0
  660. folder_cache: dict[str, int] = {} # path -> folder_id
  661. try:
  662. with zipfile.ZipFile(tmp_path, "r") as zf:
  663. # Filter out directories and hidden/system files
  664. file_list = [
  665. name
  666. for name in zf.namelist()
  667. if not name.endswith("/")
  668. and not name.startswith("__MACOSX")
  669. and not os.path.basename(name).startswith(".")
  670. ]
  671. for zip_path in file_list:
  672. try:
  673. # Determine target folder
  674. target_folder_id = folder_id
  675. if preserve_structure:
  676. # Get directory path from ZIP
  677. dir_path = os.path.dirname(zip_path)
  678. if dir_path:
  679. # Create folder structure
  680. parts = dir_path.split("/")
  681. current_parent = folder_id
  682. current_path = ""
  683. for part in parts:
  684. if not part:
  685. continue
  686. current_path = f"{current_path}/{part}" if current_path else part
  687. if current_path in folder_cache:
  688. current_parent = folder_cache[current_path]
  689. else:
  690. # Check if folder exists
  691. existing = await db.execute(
  692. select(LibraryFolder).where(
  693. LibraryFolder.name == part,
  694. LibraryFolder.parent_id == current_parent
  695. if current_parent
  696. else LibraryFolder.parent_id.is_(None),
  697. )
  698. )
  699. existing_folder = existing.scalar_one_or_none()
  700. if existing_folder:
  701. current_parent = existing_folder.id
  702. else:
  703. # Create folder
  704. new_folder = LibraryFolder(name=part, parent_id=current_parent)
  705. db.add(new_folder)
  706. await db.flush()
  707. current_parent = new_folder.id
  708. folders_created += 1
  709. folder_cache[current_path] = current_parent
  710. target_folder_id = current_parent
  711. # Extract file
  712. filename = os.path.basename(zip_path)
  713. ext = os.path.splitext(filename)[1].lower()
  714. file_type = ext[1:] if ext else "unknown"
  715. # Generate unique filename for storage
  716. unique_filename = f"{uuid.uuid4().hex}{ext}"
  717. file_path = get_library_files_dir() / unique_filename
  718. # Extract and save file
  719. file_content = zf.read(zip_path)
  720. with open(file_path, "wb") as f:
  721. f.write(file_content)
  722. # Calculate hash
  723. file_hash = calculate_file_hash(file_path)
  724. # Extract metadata and thumbnail for 3MF files
  725. metadata = {}
  726. thumbnail_path = None
  727. thumbnails_dir = get_library_thumbnails_dir()
  728. if ext == ".3mf":
  729. try:
  730. parser = ThreeMFParser(str(file_path))
  731. raw_metadata = parser.parse()
  732. thumbnail_data = raw_metadata.get("_thumbnail_data")
  733. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  734. if thumbnail_data:
  735. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  736. thumb_path = thumbnails_dir / thumb_filename
  737. with open(thumb_path, "wb") as f:
  738. f.write(thumbnail_data)
  739. thumbnail_path = str(thumb_path)
  740. def clean_metadata(obj):
  741. if isinstance(obj, dict):
  742. return {
  743. k: clean_metadata(v)
  744. for k, v in obj.items()
  745. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  746. }
  747. elif isinstance(obj, list):
  748. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  749. elif isinstance(obj, bytes):
  750. return None
  751. return obj
  752. metadata = clean_metadata(raw_metadata)
  753. except Exception as e:
  754. logger.warning(f"Failed to parse 3MF from ZIP: {e}")
  755. elif ext == ".gcode":
  756. try:
  757. thumbnail_data = extract_gcode_thumbnail(file_path)
  758. if thumbnail_data:
  759. thumb_filename = f"{uuid.uuid4().hex}.png"
  760. thumb_path = thumbnails_dir / thumb_filename
  761. with open(thumb_path, "wb") as f:
  762. f.write(thumbnail_data)
  763. thumbnail_path = str(thumb_path)
  764. except Exception as e:
  765. logger.warning(f"Failed to extract gcode thumbnail from ZIP: {e}")
  766. elif ext.lower() in IMAGE_EXTENSIONS:
  767. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  768. # Create database entry
  769. library_file = LibraryFile(
  770. folder_id=target_folder_id,
  771. filename=filename,
  772. file_path=str(file_path),
  773. file_type=file_type,
  774. file_size=len(file_content),
  775. file_hash=file_hash,
  776. thumbnail_path=thumbnail_path,
  777. file_metadata=metadata if metadata else None,
  778. )
  779. db.add(library_file)
  780. await db.flush()
  781. await db.refresh(library_file)
  782. extracted_files.append(
  783. ZipExtractResult(
  784. filename=filename,
  785. file_id=library_file.id,
  786. folder_id=target_folder_id,
  787. )
  788. )
  789. # Commit after each file to release database lock
  790. # This prevents long-running transactions from blocking other requests
  791. await db.commit()
  792. except Exception as e:
  793. logger.error(f"Failed to extract {zip_path}: {e}")
  794. errors.append(ZipExtractError(filename=os.path.basename(zip_path), error=str(e)))
  795. # Rollback the failed file but continue with others
  796. await db.rollback()
  797. return ZipExtractResponse(
  798. extracted=len(extracted_files),
  799. folders_created=folders_created,
  800. files=extracted_files,
  801. errors=errors,
  802. )
  803. except zipfile.BadZipFile:
  804. raise HTTPException(status_code=400, detail="Invalid or corrupted ZIP file")
  805. except Exception as e:
  806. logger.error(f"ZIP extraction failed: {e}", exc_info=True)
  807. raise HTTPException(status_code=500, detail=f"ZIP extraction failed: {str(e)}")
  808. finally:
  809. # Clean up temp file
  810. try:
  811. os.unlink(tmp_path)
  812. except Exception:
  813. pass
  814. # ============ Queue Operations ============
  815. # NOTE: These routes must be defined BEFORE /files/{file_id} to avoid path parameter conflicts
  816. def is_sliced_file(filename: str) -> bool:
  817. """Check if a file is a sliced (printable) file.
  818. Sliced files are:
  819. - .gcode files
  820. - .3mf files that contain '.gcode.' in the name (e.g., filename.gcode.3mf)
  821. """
  822. lower = filename.lower()
  823. return lower.endswith(".gcode") or ".gcode." in lower
  824. @router.post("/files/add-to-queue", response_model=AddToQueueResponse)
  825. async def add_files_to_queue(
  826. request: AddToQueueRequest,
  827. db: AsyncSession = Depends(get_db),
  828. ):
  829. """Add library files to the print queue.
  830. Only sliced files (.gcode or .gcode.3mf) can be added to the queue.
  831. The archive will be created automatically when the print starts.
  832. """
  833. added: list[AddToQueueResult] = []
  834. errors: list[AddToQueueError] = []
  835. # Get all requested files
  836. result = await db.execute(select(LibraryFile).where(LibraryFile.id.in_(request.file_ids)))
  837. files = {f.id: f for f in result.scalars().all()}
  838. # Get max position for queue ordering
  839. pos_result = await db.execute(select(func.coalesce(func.max(PrintQueueItem.position), 0)))
  840. max_position = pos_result.scalar() or 0
  841. for file_id in request.file_ids:
  842. lib_file = files.get(file_id)
  843. if not lib_file:
  844. errors.append(AddToQueueError(file_id=file_id, filename="(not found)", error="File not found"))
  845. continue
  846. # Validate file is sliced
  847. if not is_sliced_file(lib_file.filename):
  848. errors.append(
  849. AddToQueueError(
  850. file_id=file_id,
  851. filename=lib_file.filename,
  852. error="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  853. )
  854. )
  855. continue
  856. try:
  857. # Verify file exists on disk
  858. file_path = Path(app_settings.base_dir) / lib_file.file_path
  859. if not file_path.exists():
  860. errors.append(
  861. AddToQueueError(file_id=file_id, filename=lib_file.filename, error="File not found on disk")
  862. )
  863. continue
  864. # Create queue item referencing library file (archive created at print start)
  865. max_position += 1
  866. queue_item = PrintQueueItem(
  867. printer_id=None, # Unassigned
  868. library_file_id=file_id,
  869. position=max_position,
  870. status="pending",
  871. )
  872. db.add(queue_item)
  873. await db.flush() # Get queue_item.id
  874. added.append(
  875. AddToQueueResult(
  876. file_id=file_id,
  877. filename=lib_file.filename,
  878. queue_item_id=queue_item.id,
  879. )
  880. )
  881. except Exception as e:
  882. logger.exception(f"Error adding file {file_id} to queue")
  883. errors.append(AddToQueueError(file_id=file_id, filename=lib_file.filename, error=str(e)))
  884. await db.commit()
  885. return AddToQueueResponse(added=added, errors=errors)
  886. @router.get("/files/{file_id}/plates")
  887. async def get_library_file_plates(
  888. file_id: int,
  889. db: AsyncSession = Depends(get_db),
  890. ):
  891. """Get available plates from a multi-plate 3MF library file.
  892. Returns a list of plates with their index, name, thumbnail availability,
  893. and filament requirements. For single-plate exports, returns a single plate.
  894. """
  895. import xml.etree.ElementTree as ET
  896. import zipfile
  897. # Get the library file
  898. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  899. lib_file = result.scalar_one_or_none()
  900. if not lib_file:
  901. raise HTTPException(status_code=404, detail="File not found")
  902. file_path = Path(app_settings.base_dir) / lib_file.file_path
  903. if not file_path.exists():
  904. raise HTTPException(status_code=404, detail="File not found on disk")
  905. # Only 3MF files have plates
  906. if not lib_file.filename.lower().endswith(".3mf"):
  907. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  908. plates = []
  909. try:
  910. with zipfile.ZipFile(file_path, "r") as zf:
  911. namelist = zf.namelist()
  912. # Find all plate gcode files to determine available plates
  913. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  914. if not gcode_files:
  915. # No sliced plates found
  916. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  917. # Extract plate indices from gcode filenames
  918. plate_indices = []
  919. for gf in gcode_files:
  920. try:
  921. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  922. plate_indices.append(int(plate_str))
  923. except ValueError:
  924. pass
  925. plate_indices.sort()
  926. # Parse model_settings.config for plate names
  927. plate_names = {}
  928. if "Metadata/model_settings.config" in namelist:
  929. try:
  930. model_content = zf.read("Metadata/model_settings.config").decode()
  931. model_root = ET.fromstring(model_content)
  932. for plate_elem in model_root.findall(".//plate"):
  933. plater_id = None
  934. plater_name = None
  935. for meta in plate_elem.findall("metadata"):
  936. key = meta.get("key")
  937. value = meta.get("value")
  938. if key == "plater_id" and value:
  939. try:
  940. plater_id = int(value)
  941. except ValueError:
  942. pass
  943. elif key == "plater_name" and value:
  944. plater_name = value.strip()
  945. if plater_id is not None and plater_name:
  946. plate_names[plater_id] = plater_name
  947. except Exception:
  948. pass
  949. # Parse slice_info.config for plate metadata
  950. plate_metadata = {}
  951. if "Metadata/slice_info.config" in namelist:
  952. content = zf.read("Metadata/slice_info.config").decode()
  953. root = ET.fromstring(content)
  954. for plate_elem in root.findall(".//plate"):
  955. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  956. plate_index = None
  957. for meta in plate_elem.findall("metadata"):
  958. key = meta.get("key")
  959. value = meta.get("value")
  960. if key == "index" and value:
  961. try:
  962. plate_index = int(value)
  963. except ValueError:
  964. pass
  965. elif key == "prediction" and value:
  966. try:
  967. plate_info["prediction"] = int(value)
  968. except ValueError:
  969. pass
  970. elif key == "weight" and value:
  971. try:
  972. plate_info["weight"] = float(value)
  973. except ValueError:
  974. pass
  975. # Get filaments used in this plate
  976. for filament_elem in plate_elem.findall("filament"):
  977. filament_id = filament_elem.get("id")
  978. filament_type = filament_elem.get("type", "")
  979. filament_color = filament_elem.get("color", "")
  980. used_g = filament_elem.get("used_g", "0")
  981. used_m = filament_elem.get("used_m", "0")
  982. try:
  983. used_grams = float(used_g)
  984. except (ValueError, TypeError):
  985. used_grams = 0
  986. if used_grams > 0 and filament_id:
  987. plate_info["filaments"].append(
  988. {
  989. "slot_id": int(filament_id),
  990. "type": filament_type,
  991. "color": filament_color,
  992. "used_grams": round(used_grams, 1),
  993. "used_meters": float(used_m) if used_m else 0,
  994. }
  995. )
  996. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  997. # Collect object names
  998. for obj_elem in plate_elem.findall("object"):
  999. obj_name = obj_elem.get("name")
  1000. if obj_name and obj_name not in plate_info["objects"]:
  1001. plate_info["objects"].append(obj_name)
  1002. # Set plate name
  1003. if plate_index is not None:
  1004. custom_name = plate_names.get(plate_index)
  1005. if custom_name:
  1006. plate_info["name"] = custom_name
  1007. elif plate_info["objects"]:
  1008. plate_info["name"] = plate_info["objects"][0]
  1009. plate_metadata[plate_index] = plate_info
  1010. # Build plate list
  1011. for idx in plate_indices:
  1012. meta = plate_metadata.get(idx, {})
  1013. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1014. plates.append(
  1015. {
  1016. "index": idx,
  1017. "name": meta.get("name"),
  1018. "objects": meta.get("objects", []),
  1019. "has_thumbnail": has_thumbnail,
  1020. "thumbnail_url": f"/api/v1/library/files/{file_id}/plate-thumbnail/{idx}"
  1021. if has_thumbnail
  1022. else None,
  1023. "print_time_seconds": meta.get("prediction"),
  1024. "filament_used_grams": meta.get("weight"),
  1025. "filaments": meta.get("filaments", []),
  1026. }
  1027. )
  1028. except Exception as e:
  1029. logger.warning(f"Failed to parse plates from library file {file_id}: {e}")
  1030. return {
  1031. "file_id": file_id,
  1032. "filename": lib_file.filename,
  1033. "plates": plates,
  1034. "is_multi_plate": len(plates) > 1,
  1035. }
  1036. @router.get("/files/{file_id}/plate-thumbnail/{plate_index}")
  1037. async def get_library_file_plate_thumbnail(
  1038. file_id: int,
  1039. plate_index: int,
  1040. db: AsyncSession = Depends(get_db),
  1041. ):
  1042. """Get the thumbnail image for a specific plate from a library file."""
  1043. import zipfile
  1044. from starlette.responses import Response
  1045. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1046. lib_file = result.scalar_one_or_none()
  1047. if not lib_file:
  1048. raise HTTPException(status_code=404, detail="File not found")
  1049. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1050. if not file_path.exists():
  1051. raise HTTPException(status_code=404, detail="File not found on disk")
  1052. try:
  1053. with zipfile.ZipFile(file_path, "r") as zf:
  1054. thumb_path = f"Metadata/plate_{plate_index}.png"
  1055. if thumb_path in zf.namelist():
  1056. data = zf.read(thumb_path)
  1057. return Response(content=data, media_type="image/png")
  1058. except Exception:
  1059. pass
  1060. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1061. @router.get("/files/{file_id}/filament-requirements")
  1062. async def get_library_file_filament_requirements(
  1063. file_id: int,
  1064. plate_id: int | None = None,
  1065. db: AsyncSession = Depends(get_db),
  1066. ):
  1067. """Get filament requirements from a library file.
  1068. Parses the 3MF file to extract filament slot IDs, types, colors, and usage.
  1069. This enables AMS slot assignment when printing from the file manager.
  1070. Args:
  1071. file_id: The library file ID
  1072. plate_id: Optional plate index to get filaments for a specific plate
  1073. """
  1074. import xml.etree.ElementTree as ET
  1075. import zipfile
  1076. # Get the library file
  1077. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1078. lib_file = result.scalar_one_or_none()
  1079. if not lib_file:
  1080. raise HTTPException(status_code=404, detail="File not found")
  1081. # Get the full file path
  1082. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1083. if not file_path.exists():
  1084. raise HTTPException(status_code=404, detail="File not found on disk")
  1085. # Only 3MF files have parseable filament info
  1086. if not lib_file.filename.lower().endswith(".3mf"):
  1087. return {"file_id": file_id, "filename": lib_file.filename, "plate_id": plate_id, "filaments": []}
  1088. filaments = []
  1089. try:
  1090. with zipfile.ZipFile(file_path, "r") as zf:
  1091. # Parse slice_info.config for filament requirements
  1092. if "Metadata/slice_info.config" in zf.namelist():
  1093. content = zf.read("Metadata/slice_info.config").decode()
  1094. root = ET.fromstring(content)
  1095. if plate_id is not None:
  1096. # Find filaments for specific plate
  1097. for plate_elem in root.findall(".//plate"):
  1098. # Check if this is the requested plate
  1099. plate_index = None
  1100. for meta in plate_elem.findall("metadata"):
  1101. if meta.get("key") == "index":
  1102. try:
  1103. plate_index = int(meta.get("value", ""))
  1104. except ValueError:
  1105. pass
  1106. break
  1107. if plate_index == plate_id:
  1108. # Extract filaments from this plate
  1109. for filament_elem in plate_elem.findall("filament"):
  1110. filament_id = filament_elem.get("id")
  1111. filament_type = filament_elem.get("type", "")
  1112. filament_color = filament_elem.get("color", "")
  1113. used_g = filament_elem.get("used_g", "0")
  1114. used_m = filament_elem.get("used_m", "0")
  1115. try:
  1116. used_grams = float(used_g)
  1117. except (ValueError, TypeError):
  1118. used_grams = 0
  1119. if used_grams > 0 and filament_id:
  1120. filaments.append(
  1121. {
  1122. "slot_id": int(filament_id),
  1123. "type": filament_type,
  1124. "color": filament_color,
  1125. "used_grams": round(used_grams, 1),
  1126. "used_meters": float(used_m) if used_m else 0,
  1127. }
  1128. )
  1129. break
  1130. else:
  1131. # Extract all filaments with used_g > 0 (for single-plate or overview)
  1132. for filament_elem in root.findall(".//filament"):
  1133. filament_id = filament_elem.get("id")
  1134. filament_type = filament_elem.get("type", "")
  1135. filament_color = filament_elem.get("color", "")
  1136. used_g = filament_elem.get("used_g", "0")
  1137. used_m = filament_elem.get("used_m", "0")
  1138. try:
  1139. used_grams = float(used_g)
  1140. except (ValueError, TypeError):
  1141. used_grams = 0
  1142. if used_grams > 0 and filament_id:
  1143. filaments.append(
  1144. {
  1145. "slot_id": int(filament_id),
  1146. "type": filament_type,
  1147. "color": filament_color,
  1148. "used_grams": round(used_grams, 1),
  1149. "used_meters": float(used_m) if used_m else 0,
  1150. }
  1151. )
  1152. # Sort by slot ID
  1153. filaments.sort(key=lambda x: x["slot_id"])
  1154. except Exception as e:
  1155. logger.warning(f"Failed to parse filament requirements from library file {file_id}: {e}")
  1156. return {
  1157. "file_id": file_id,
  1158. "filename": lib_file.filename,
  1159. "plate_id": plate_id,
  1160. "filaments": filaments,
  1161. }
  1162. @router.post("/files/{file_id}/print")
  1163. async def print_library_file(
  1164. file_id: int,
  1165. printer_id: int,
  1166. body: FilePrintRequest | None = None,
  1167. db: AsyncSession = Depends(get_db),
  1168. ):
  1169. """Print a library file directly.
  1170. This endpoint:
  1171. 1. Creates an archive from the library file
  1172. 2. Uploads the file to the printer
  1173. 3. Starts the print
  1174. Only sliced files (.gcode or .gcode.3mf) can be printed.
  1175. """
  1176. import zipfile
  1177. from backend.app.main import register_expected_print
  1178. from backend.app.models.printer import Printer
  1179. from backend.app.services.bambu_ftp import (
  1180. delete_file_async,
  1181. get_ftp_retry_settings,
  1182. upload_file_async,
  1183. with_ftp_retry,
  1184. )
  1185. from backend.app.services.printer_manager import printer_manager
  1186. # Use defaults if no body provided
  1187. if body is None:
  1188. body = FilePrintRequest()
  1189. # Get the library file
  1190. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1191. lib_file = result.scalar_one_or_none()
  1192. if not lib_file:
  1193. raise HTTPException(status_code=404, detail="File not found")
  1194. # Validate file is sliced
  1195. if not is_sliced_file(lib_file.filename):
  1196. raise HTTPException(
  1197. status_code=400,
  1198. detail="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1199. )
  1200. # Get the full file path
  1201. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1202. if not file_path.exists():
  1203. raise HTTPException(status_code=404, detail="File not found on disk")
  1204. # Get printer
  1205. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1206. printer = result.scalar_one_or_none()
  1207. if not printer:
  1208. raise HTTPException(status_code=404, detail="Printer not found")
  1209. # Check printer is connected
  1210. if not printer_manager.is_connected(printer_id):
  1211. raise HTTPException(status_code=400, detail="Printer is not connected")
  1212. # Create archive from the library file
  1213. archive_service = ArchiveService(db)
  1214. archive = await archive_service.archive_print(
  1215. printer_id=printer_id,
  1216. source_file=file_path,
  1217. )
  1218. if not archive:
  1219. raise HTTPException(status_code=500, detail="Failed to create archive")
  1220. await db.flush()
  1221. # Prepare remote filename
  1222. base_name = lib_file.filename
  1223. if base_name.endswith(".gcode.3mf"):
  1224. base_name = base_name[:-10]
  1225. elif base_name.endswith(".3mf"):
  1226. base_name = base_name[:-4]
  1227. remote_filename = f"{base_name}.3mf"
  1228. remote_path = f"/{remote_filename}"
  1229. # Get FTP retry settings
  1230. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1231. # Delete existing file if present (avoids 553 error)
  1232. await delete_file_async(
  1233. printer.ip_address,
  1234. printer.access_code,
  1235. remote_path,
  1236. socket_timeout=ftp_timeout,
  1237. printer_model=printer.model,
  1238. )
  1239. # Upload file to printer
  1240. if ftp_retry_enabled:
  1241. uploaded = await with_ftp_retry(
  1242. upload_file_async,
  1243. printer.ip_address,
  1244. printer.access_code,
  1245. file_path,
  1246. remote_path,
  1247. socket_timeout=ftp_timeout,
  1248. printer_model=printer.model,
  1249. max_retries=ftp_retry_count,
  1250. retry_delay=ftp_retry_delay,
  1251. operation_name=f"Upload for print to {printer.name}",
  1252. )
  1253. else:
  1254. uploaded = await upload_file_async(
  1255. printer.ip_address,
  1256. printer.access_code,
  1257. file_path,
  1258. remote_path,
  1259. socket_timeout=ftp_timeout,
  1260. printer_model=printer.model,
  1261. )
  1262. if not uploaded:
  1263. raise HTTPException(status_code=500, detail="Failed to upload file to printer")
  1264. # Register this as an expected print so we don't create a duplicate archive
  1265. register_expected_print(printer_id, remote_filename, archive.id)
  1266. # Determine plate ID
  1267. if body.plate_id is not None:
  1268. plate_id = body.plate_id
  1269. else:
  1270. plate_id = 1
  1271. try:
  1272. with zipfile.ZipFile(file_path, "r") as zf:
  1273. for name in zf.namelist():
  1274. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1275. plate_str = name[15:-6]
  1276. plate_id = int(plate_str)
  1277. break
  1278. except Exception:
  1279. pass
  1280. logger.info(
  1281. f"Print library file {file_id}: archive_id={archive.id}, plate_id={plate_id}, "
  1282. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}"
  1283. )
  1284. # Start the print
  1285. started = printer_manager.start_print(
  1286. printer_id,
  1287. remote_filename,
  1288. plate_id,
  1289. ams_mapping=body.ams_mapping,
  1290. timelapse=body.timelapse,
  1291. bed_levelling=body.bed_levelling,
  1292. flow_cali=body.flow_cali,
  1293. vibration_cali=body.vibration_cali,
  1294. layer_inspect=body.layer_inspect,
  1295. use_ams=body.use_ams,
  1296. )
  1297. if not started:
  1298. raise HTTPException(status_code=500, detail="Failed to start print")
  1299. await db.commit()
  1300. return {
  1301. "status": "printing",
  1302. "printer_id": printer_id,
  1303. "archive_id": archive.id,
  1304. "filename": lib_file.filename,
  1305. }
  1306. # ============ File Detail Endpoints ============
  1307. @router.get("/files/{file_id}", response_model=FileResponseSchema)
  1308. async def get_file(file_id: int, db: AsyncSession = Depends(get_db)):
  1309. """Get a file by ID with full details."""
  1310. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1311. file = result.scalar_one_or_none()
  1312. if not file:
  1313. raise HTTPException(status_code=404, detail="File not found")
  1314. # Get folder name
  1315. folder_name = None
  1316. if file.folder_id:
  1317. folder_result = await db.execute(select(LibraryFolder.name).where(LibraryFolder.id == file.folder_id))
  1318. folder_name = folder_result.scalar()
  1319. # Get project name
  1320. project_name = None
  1321. if file.project_id:
  1322. project_result = await db.execute(select(Project.name).where(Project.id == file.project_id))
  1323. project_name = project_result.scalar()
  1324. # Get duplicates
  1325. duplicates = []
  1326. duplicate_count = 0
  1327. if file.file_hash:
  1328. dup_result = await db.execute(
  1329. select(LibraryFile, LibraryFolder.name)
  1330. .outerjoin(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  1331. .where(LibraryFile.file_hash == file.file_hash, LibraryFile.id != file.id)
  1332. )
  1333. for dup_file, dup_folder_name in dup_result.all():
  1334. duplicates.append(
  1335. FileDuplicate(
  1336. id=dup_file.id,
  1337. filename=dup_file.filename,
  1338. folder_id=dup_file.folder_id,
  1339. folder_name=dup_folder_name,
  1340. created_at=dup_file.created_at,
  1341. )
  1342. )
  1343. duplicate_count = len(duplicates)
  1344. return FileResponseSchema(
  1345. id=file.id,
  1346. folder_id=file.folder_id,
  1347. folder_name=folder_name,
  1348. project_id=file.project_id,
  1349. project_name=project_name,
  1350. filename=file.filename,
  1351. file_path=file.file_path,
  1352. file_type=file.file_type,
  1353. file_size=file.file_size,
  1354. file_hash=file.file_hash,
  1355. thumbnail_path=file.thumbnail_path,
  1356. metadata=file.file_metadata,
  1357. print_count=file.print_count,
  1358. last_printed_at=file.last_printed_at,
  1359. notes=file.notes,
  1360. duplicates=duplicates if duplicates else None,
  1361. duplicate_count=duplicate_count,
  1362. created_at=file.created_at,
  1363. updated_at=file.updated_at,
  1364. )
  1365. @router.put("/files/{file_id}", response_model=FileResponseSchema)
  1366. async def update_file(file_id: int, data: FileUpdate, db: AsyncSession = Depends(get_db)):
  1367. """Update a file's metadata."""
  1368. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1369. file = result.scalar_one_or_none()
  1370. if not file:
  1371. raise HTTPException(status_code=404, detail="File not found")
  1372. if data.filename is not None:
  1373. # Validate filename doesn't contain path separators
  1374. if "/" in data.filename or "\\" in data.filename:
  1375. raise HTTPException(status_code=400, detail="Filename cannot contain path separators")
  1376. file.filename = data.filename
  1377. if data.folder_id is not None:
  1378. if data.folder_id == 0:
  1379. file.folder_id = None
  1380. else:
  1381. # Verify folder exists
  1382. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  1383. if not folder_result.scalar_one_or_none():
  1384. raise HTTPException(status_code=404, detail="Folder not found")
  1385. file.folder_id = data.folder_id
  1386. if data.project_id is not None:
  1387. if data.project_id == 0:
  1388. file.project_id = None
  1389. else:
  1390. # Verify project exists
  1391. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  1392. if not project_result.scalar_one_or_none():
  1393. raise HTTPException(status_code=404, detail="Project not found")
  1394. file.project_id = data.project_id
  1395. if data.notes is not None:
  1396. file.notes = data.notes if data.notes else None
  1397. await db.flush()
  1398. await db.refresh(file)
  1399. # Return full response (reuse get_file logic)
  1400. return await get_file(file_id, db)
  1401. @router.delete("/files/{file_id}")
  1402. async def delete_file(file_id: int, db: AsyncSession = Depends(get_db)):
  1403. """Delete a file."""
  1404. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1405. file = result.scalar_one_or_none()
  1406. if not file:
  1407. raise HTTPException(status_code=404, detail="File not found")
  1408. # Delete actual files
  1409. try:
  1410. if file.file_path and os.path.exists(file.file_path):
  1411. os.remove(file.file_path)
  1412. if file.thumbnail_path and os.path.exists(file.thumbnail_path):
  1413. os.remove(file.thumbnail_path)
  1414. except Exception as e:
  1415. logger.warning(f"Failed to delete file from disk: {e}")
  1416. await db.delete(file)
  1417. return {"status": "success", "message": "File deleted"}
  1418. # ============ File Content Endpoints ============
  1419. @router.get("/files/{file_id}/download")
  1420. async def download_file(file_id: int, db: AsyncSession = Depends(get_db)):
  1421. """Download a file."""
  1422. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1423. file = result.scalar_one_or_none()
  1424. if not file:
  1425. raise HTTPException(status_code=404, detail="File not found")
  1426. if not file.file_path or not os.path.exists(file.file_path):
  1427. raise HTTPException(status_code=404, detail="File not found on disk")
  1428. return FastAPIFileResponse(
  1429. file.file_path,
  1430. filename=file.filename,
  1431. media_type="application/octet-stream",
  1432. )
  1433. @router.get("/files/{file_id}/thumbnail")
  1434. async def get_thumbnail(file_id: int, db: AsyncSession = Depends(get_db)):
  1435. """Get a file's thumbnail."""
  1436. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1437. file = result.scalar_one_or_none()
  1438. if not file:
  1439. raise HTTPException(status_code=404, detail="File not found")
  1440. if not file.thumbnail_path or not os.path.exists(file.thumbnail_path):
  1441. raise HTTPException(status_code=404, detail="Thumbnail not found")
  1442. # Detect media type from extension
  1443. thumb_ext = os.path.splitext(file.thumbnail_path)[1].lower()
  1444. media_types = {
  1445. ".png": "image/png",
  1446. ".jpg": "image/jpeg",
  1447. ".jpeg": "image/jpeg",
  1448. ".gif": "image/gif",
  1449. ".webp": "image/webp",
  1450. }
  1451. media_type = media_types.get(thumb_ext, "image/png")
  1452. return FastAPIFileResponse(file.thumbnail_path, media_type=media_type)
  1453. @router.get("/files/{file_id}/gcode")
  1454. async def get_gcode(file_id: int, db: AsyncSession = Depends(get_db)):
  1455. """Get gcode for a file (for preview)."""
  1456. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1457. file = result.scalar_one_or_none()
  1458. if not file:
  1459. raise HTTPException(status_code=404, detail="File not found")
  1460. if not file.file_path or not os.path.exists(file.file_path):
  1461. raise HTTPException(status_code=404, detail="File not found on disk")
  1462. if file.file_type == "gcode":
  1463. return FastAPIFileResponse(file.file_path, media_type="text/plain")
  1464. elif file.file_type == "3mf":
  1465. # Extract gcode from 3mf
  1466. import zipfile
  1467. try:
  1468. with zipfile.ZipFile(file.file_path, "r") as zf:
  1469. # Find gcode file
  1470. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  1471. if not gcode_files:
  1472. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  1473. gcode_content = zf.read(gcode_files[0])
  1474. from fastapi.responses import Response
  1475. return Response(content=gcode_content, media_type="text/plain")
  1476. except zipfile.BadZipFile:
  1477. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  1478. else:
  1479. raise HTTPException(status_code=400, detail="Unsupported file type")
  1480. # ============ Bulk Operations ============
  1481. @router.post("/files/move")
  1482. async def move_files(data: FileMoveRequest, db: AsyncSession = Depends(get_db)):
  1483. """Move multiple files to a folder."""
  1484. # Verify folder exists if specified
  1485. if data.folder_id is not None:
  1486. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  1487. if not folder_result.scalar_one_or_none():
  1488. raise HTTPException(status_code=404, detail="Folder not found")
  1489. # Update files
  1490. moved = 0
  1491. for file_id in data.file_ids:
  1492. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1493. file = result.scalar_one_or_none()
  1494. if file:
  1495. file.folder_id = data.folder_id
  1496. moved += 1
  1497. return {"status": "success", "moved": moved}
  1498. @router.post("/bulk-delete", response_model=BulkDeleteResponse)
  1499. async def bulk_delete(data: BulkDeleteRequest, db: AsyncSession = Depends(get_db)):
  1500. """Delete multiple files and/or folders."""
  1501. deleted_files = 0
  1502. deleted_folders = 0
  1503. # Delete files first
  1504. for file_id in data.file_ids:
  1505. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1506. file = result.scalar_one_or_none()
  1507. if file:
  1508. try:
  1509. if file.file_path and os.path.exists(file.file_path):
  1510. os.remove(file.file_path)
  1511. if file.thumbnail_path and os.path.exists(file.thumbnail_path):
  1512. os.remove(file.thumbnail_path)
  1513. except Exception as e:
  1514. logger.warning(f"Failed to delete file from disk: {e}")
  1515. await db.delete(file)
  1516. deleted_files += 1
  1517. # Delete folders (cascade will handle contents)
  1518. for folder_id in data.folder_ids:
  1519. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  1520. folder = result.scalar_one_or_none()
  1521. if folder:
  1522. # Count files that will be deleted
  1523. file_count_result = await db.execute(
  1524. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id)
  1525. )
  1526. deleted_files += file_count_result.scalar() or 0
  1527. await db.delete(folder)
  1528. deleted_folders += 1
  1529. return BulkDeleteResponse(deleted_files=deleted_files, deleted_folders=deleted_folders)
  1530. # ============ Stats Endpoint ============
  1531. @router.get("/stats")
  1532. async def get_library_stats(db: AsyncSession = Depends(get_db)):
  1533. """Get library statistics."""
  1534. # Total files
  1535. total_files_result = await db.execute(select(func.count(LibraryFile.id)))
  1536. total_files = total_files_result.scalar() or 0
  1537. # Total folders
  1538. total_folders_result = await db.execute(select(func.count(LibraryFolder.id)))
  1539. total_folders = total_folders_result.scalar() or 0
  1540. # Total size
  1541. total_size_result = await db.execute(select(func.sum(LibraryFile.file_size)))
  1542. total_size = total_size_result.scalar() or 0
  1543. # Files by type
  1544. type_result = await db.execute(
  1545. select(LibraryFile.file_type, func.count(LibraryFile.id)).group_by(LibraryFile.file_type)
  1546. )
  1547. files_by_type = dict(type_result.all())
  1548. # Total prints
  1549. total_prints_result = await db.execute(select(func.sum(LibraryFile.print_count)))
  1550. total_prints = total_prints_result.scalar() or 0
  1551. # Disk space info
  1552. library_dir = get_library_dir()
  1553. try:
  1554. disk_stat = shutil.disk_usage(library_dir)
  1555. disk_free_bytes = disk_stat.free
  1556. disk_total_bytes = disk_stat.total
  1557. disk_used_bytes = disk_stat.used
  1558. except Exception:
  1559. disk_free_bytes = 0
  1560. disk_total_bytes = 0
  1561. disk_used_bytes = 0
  1562. return {
  1563. "total_files": total_files,
  1564. "total_folders": total_folders,
  1565. "total_size_bytes": total_size,
  1566. "files_by_type": files_by_type,
  1567. "total_prints": total_prints,
  1568. "disk_free_bytes": disk_free_bytes,
  1569. "disk_total_bytes": disk_total_bytes,
  1570. "disk_used_bytes": disk_used_bytes,
  1571. }