library.py 87 KB

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