library.py 78 KB

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