library.py 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365
  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. sliced_for_model = None
  565. if f.file_metadata:
  566. print_name = f.file_metadata.get("print_name")
  567. print_time = f.file_metadata.get("print_time_seconds")
  568. filament_grams = f.file_metadata.get("filament_used_grams")
  569. sliced_for_model = f.file_metadata.get("sliced_for_model")
  570. file_list.append(
  571. FileListResponse(
  572. id=f.id,
  573. folder_id=f.folder_id,
  574. filename=f.filename,
  575. file_type=f.file_type,
  576. file_size=f.file_size,
  577. thumbnail_path=f.thumbnail_path,
  578. print_count=f.print_count,
  579. duplicate_count=hash_counts.get(f.file_hash, 0) if f.file_hash else 0,
  580. created_by_id=f.created_by_id,
  581. created_by_username=f.created_by.username if f.created_by else None,
  582. created_at=f.created_at,
  583. print_name=print_name,
  584. print_time_seconds=print_time,
  585. filament_used_grams=filament_grams,
  586. sliced_for_model=sliced_for_model,
  587. )
  588. )
  589. return file_list
  590. @router.post("/files", response_model=FileUploadResponse)
  591. @router.post("/files/", response_model=FileUploadResponse)
  592. async def upload_file(
  593. file: UploadFile = File(...),
  594. folder_id: int | None = None,
  595. generate_stl_thumbnails: bool = Query(default=True),
  596. db: AsyncSession = Depends(get_db),
  597. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  598. ):
  599. """Upload a file to the library."""
  600. try:
  601. if not file.filename:
  602. raise HTTPException(status_code=400, detail="Filename is required")
  603. filename = file.filename
  604. ext = os.path.splitext(filename)[1].lower()
  605. # Handle files without extension
  606. file_type = ext[1:] if ext else "unknown"
  607. # Verify folder exists if specified
  608. if folder_id is not None:
  609. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  610. if not folder_result.scalar_one_or_none():
  611. raise HTTPException(status_code=404, detail="Folder not found")
  612. # Generate unique filename for storage
  613. unique_filename = f"{uuid.uuid4().hex}{ext}"
  614. file_path = get_library_files_dir() / unique_filename
  615. # Save file
  616. content = await file.read()
  617. with open(file_path, "wb") as f:
  618. f.write(content)
  619. # Calculate hash
  620. file_hash = calculate_file_hash(file_path)
  621. # Check for duplicates
  622. dup_result = await db.execute(select(LibraryFile.id).where(LibraryFile.file_hash == file_hash).limit(1))
  623. duplicate_of = dup_result.scalar()
  624. # Extract metadata and thumbnail
  625. metadata = {}
  626. thumbnail_path = None
  627. thumbnails_dir = get_library_thumbnails_dir()
  628. if ext == ".3mf":
  629. try:
  630. parser = ThreeMFParser(str(file_path))
  631. raw_metadata = parser.parse()
  632. # Extract thumbnail before cleaning metadata
  633. thumbnail_data = raw_metadata.get("_thumbnail_data")
  634. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  635. # Save thumbnail if extracted
  636. if thumbnail_data:
  637. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  638. thumb_path = thumbnails_dir / thumb_filename
  639. with open(thumb_path, "wb") as f:
  640. f.write(thumbnail_data)
  641. thumbnail_path = str(thumb_path)
  642. # Clean metadata - remove non-JSON-serializable data (bytes, etc.)
  643. def clean_metadata(obj):
  644. if isinstance(obj, dict):
  645. return {
  646. k: clean_metadata(v)
  647. for k, v in obj.items()
  648. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  649. }
  650. elif isinstance(obj, list):
  651. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  652. elif isinstance(obj, bytes):
  653. return None
  654. return obj
  655. metadata = clean_metadata(raw_metadata)
  656. except Exception as e:
  657. logger.warning(f"Failed to parse 3MF: {e}")
  658. elif ext == ".gcode":
  659. # Extract embedded thumbnail from gcode
  660. try:
  661. thumbnail_data = extract_gcode_thumbnail(file_path)
  662. if thumbnail_data:
  663. thumb_filename = f"{uuid.uuid4().hex}.png"
  664. thumb_path = thumbnails_dir / thumb_filename
  665. with open(thumb_path, "wb") as f:
  666. f.write(thumbnail_data)
  667. thumbnail_path = str(thumb_path)
  668. except Exception as e:
  669. logger.warning(f"Failed to extract gcode thumbnail: {e}")
  670. elif ext.lower() in IMAGE_EXTENSIONS:
  671. # For image files, create a thumbnail from the image itself
  672. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  673. elif ext == ".stl":
  674. # Generate STL thumbnail if enabled
  675. if generate_stl_thumbnails:
  676. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  677. # Create database entry (store relative paths for portability)
  678. library_file = LibraryFile(
  679. folder_id=folder_id,
  680. filename=filename,
  681. file_path=to_relative_path(file_path),
  682. file_type=file_type,
  683. file_size=len(content),
  684. file_hash=file_hash,
  685. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  686. file_metadata=metadata if metadata else None,
  687. created_by_id=current_user.id if current_user else None,
  688. )
  689. db.add(library_file)
  690. await db.flush()
  691. await db.refresh(library_file)
  692. return FileUploadResponse(
  693. id=library_file.id,
  694. filename=library_file.filename,
  695. file_type=library_file.file_type,
  696. file_size=library_file.file_size,
  697. thumbnail_path=library_file.thumbnail_path,
  698. duplicate_of=duplicate_of,
  699. metadata=library_file.file_metadata,
  700. )
  701. except HTTPException:
  702. raise
  703. except Exception as e:
  704. logger.error(f"Upload failed for {file.filename}: {e}", exc_info=True)
  705. raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
  706. @router.post("/files/extract-zip", response_model=ZipExtractResponse)
  707. async def extract_zip_file(
  708. file: UploadFile = File(...),
  709. folder_id: int | None = Query(default=None),
  710. preserve_structure: bool = Query(default=True),
  711. create_folder_from_zip: bool = Query(default=False),
  712. generate_stl_thumbnails: bool = Query(default=True),
  713. db: AsyncSession = Depends(get_db),
  714. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  715. ):
  716. """Upload and extract a ZIP file to the library.
  717. Args:
  718. file: The ZIP file to extract
  719. folder_id: Target folder ID (None = root)
  720. preserve_structure: If True, recreate folder structure from ZIP; if False, extract all files flat
  721. create_folder_from_zip: If True, create a folder named after the ZIP file and extract into it
  722. generate_stl_thumbnails: If True, generate thumbnails for STL files
  723. """
  724. import tempfile
  725. import zipfile
  726. if not file.filename or not file.filename.lower().endswith(".zip"):
  727. raise HTTPException(status_code=400, detail="Only ZIP files are supported")
  728. # Verify target folder exists if specified
  729. if folder_id is not None:
  730. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  731. if not folder_result.scalar_one_or_none():
  732. raise HTTPException(status_code=404, detail="Target folder not found")
  733. # Save ZIP to temp file
  734. try:
  735. with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp:
  736. content = await file.read()
  737. tmp.write(content)
  738. tmp_path = tmp.name
  739. except Exception as e:
  740. raise HTTPException(status_code=500, detail=f"Failed to save ZIP file: {str(e)}")
  741. extracted_files: list[ZipExtractResult] = []
  742. errors: list[ZipExtractError] = []
  743. folders_created = 0
  744. folder_cache: dict[str, int] = {} # path -> folder_id
  745. # If create_folder_from_zip is True, create a folder named after the ZIP file
  746. zip_folder_id = folder_id
  747. logger.info(
  748. f"ZIP extraction: create_folder_from_zip={create_folder_from_zip}, folder_id={folder_id}, filename={file.filename}"
  749. )
  750. if create_folder_from_zip and file.filename:
  751. # Remove .zip extension to get folder name
  752. zip_folder_name = file.filename[:-4] if file.filename.lower().endswith(".zip") else file.filename
  753. # Check if folder already exists
  754. existing = await db.execute(
  755. select(LibraryFolder).where(
  756. LibraryFolder.name == zip_folder_name,
  757. LibraryFolder.parent_id == folder_id if folder_id else LibraryFolder.parent_id.is_(None),
  758. )
  759. )
  760. existing_folder = existing.scalar_one_or_none()
  761. if existing_folder:
  762. zip_folder_id = existing_folder.id
  763. logger.info(f"Reusing existing folder '{zip_folder_name}' with id={zip_folder_id}")
  764. else:
  765. # Create folder
  766. new_folder = LibraryFolder(name=zip_folder_name, parent_id=folder_id)
  767. db.add(new_folder)
  768. await db.flush()
  769. await db.commit() # Commit folder creation immediately
  770. zip_folder_id = new_folder.id
  771. folders_created += 1
  772. logger.info(f"Created new folder '{zip_folder_name}' with id={zip_folder_id}")
  773. try:
  774. with zipfile.ZipFile(tmp_path, "r") as zf:
  775. # Filter out directories and hidden/system files
  776. file_list = [
  777. name
  778. for name in zf.namelist()
  779. if not name.endswith("/")
  780. and not name.startswith("__MACOSX")
  781. and not os.path.basename(name).startswith(".")
  782. ]
  783. for zip_path in file_list:
  784. try:
  785. # Determine target folder (use zip_folder_id as base if create_folder_from_zip was used)
  786. target_folder_id = zip_folder_id
  787. if preserve_structure:
  788. # Get directory path from ZIP
  789. dir_path = os.path.dirname(zip_path)
  790. if dir_path:
  791. # Create folder structure
  792. parts = dir_path.split("/")
  793. current_parent = zip_folder_id
  794. current_path = ""
  795. for part in parts:
  796. if not part:
  797. continue
  798. current_path = f"{current_path}/{part}" if current_path else part
  799. if current_path in folder_cache:
  800. current_parent = folder_cache[current_path]
  801. else:
  802. # Check if folder exists
  803. existing = await db.execute(
  804. select(LibraryFolder).where(
  805. LibraryFolder.name == part,
  806. LibraryFolder.parent_id == current_parent
  807. if current_parent
  808. else LibraryFolder.parent_id.is_(None),
  809. )
  810. )
  811. existing_folder = existing.scalar_one_or_none()
  812. if existing_folder:
  813. current_parent = existing_folder.id
  814. else:
  815. # Create folder
  816. new_folder = LibraryFolder(name=part, parent_id=current_parent)
  817. db.add(new_folder)
  818. await db.flush()
  819. current_parent = new_folder.id
  820. folders_created += 1
  821. folder_cache[current_path] = current_parent
  822. target_folder_id = current_parent
  823. # Extract file
  824. filename = os.path.basename(zip_path)
  825. ext = os.path.splitext(filename)[1].lower()
  826. file_type = ext[1:] if ext else "unknown"
  827. # Generate unique filename for storage
  828. unique_filename = f"{uuid.uuid4().hex}{ext}"
  829. file_path = get_library_files_dir() / unique_filename
  830. # Extract and save file
  831. file_content = zf.read(zip_path)
  832. with open(file_path, "wb") as f:
  833. f.write(file_content)
  834. # Calculate hash
  835. file_hash = calculate_file_hash(file_path)
  836. # Extract metadata and thumbnail for 3MF files
  837. metadata = {}
  838. thumbnail_path = None
  839. thumbnails_dir = get_library_thumbnails_dir()
  840. if ext == ".3mf":
  841. try:
  842. parser = ThreeMFParser(str(file_path))
  843. raw_metadata = parser.parse()
  844. thumbnail_data = raw_metadata.get("_thumbnail_data")
  845. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  846. if thumbnail_data:
  847. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  848. thumb_path = thumbnails_dir / thumb_filename
  849. with open(thumb_path, "wb") as f:
  850. f.write(thumbnail_data)
  851. thumbnail_path = str(thumb_path)
  852. def clean_metadata(obj):
  853. if isinstance(obj, dict):
  854. return {
  855. k: clean_metadata(v)
  856. for k, v in obj.items()
  857. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  858. }
  859. elif isinstance(obj, list):
  860. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  861. elif isinstance(obj, bytes):
  862. return None
  863. return obj
  864. metadata = clean_metadata(raw_metadata)
  865. except Exception as e:
  866. logger.warning(f"Failed to parse 3MF from ZIP: {e}")
  867. elif ext == ".gcode":
  868. try:
  869. thumbnail_data = extract_gcode_thumbnail(file_path)
  870. if thumbnail_data:
  871. thumb_filename = f"{uuid.uuid4().hex}.png"
  872. thumb_path = thumbnails_dir / thumb_filename
  873. with open(thumb_path, "wb") as f:
  874. f.write(thumbnail_data)
  875. thumbnail_path = str(thumb_path)
  876. except Exception as e:
  877. logger.warning(f"Failed to extract gcode thumbnail from ZIP: {e}")
  878. elif ext.lower() in IMAGE_EXTENSIONS:
  879. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  880. elif ext == ".stl":
  881. # Generate STL thumbnail if enabled
  882. if generate_stl_thumbnails:
  883. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  884. # Create database entry (store relative paths for portability)
  885. library_file = LibraryFile(
  886. folder_id=target_folder_id,
  887. filename=filename,
  888. file_path=to_relative_path(file_path),
  889. file_type=file_type,
  890. file_size=len(file_content),
  891. file_hash=file_hash,
  892. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  893. file_metadata=metadata if metadata else None,
  894. created_by_id=current_user.id if current_user else None,
  895. )
  896. db.add(library_file)
  897. await db.flush()
  898. await db.refresh(library_file)
  899. extracted_files.append(
  900. ZipExtractResult(
  901. filename=filename,
  902. file_id=library_file.id,
  903. folder_id=target_folder_id,
  904. )
  905. )
  906. # Commit after each file to release database lock
  907. # This prevents long-running transactions from blocking other requests
  908. await db.commit()
  909. except Exception as e:
  910. logger.error(f"Failed to extract {zip_path}: {e}")
  911. errors.append(ZipExtractError(filename=os.path.basename(zip_path), error=str(e)))
  912. # Rollback the failed file but continue with others
  913. await db.rollback()
  914. return ZipExtractResponse(
  915. extracted=len(extracted_files),
  916. folders_created=folders_created,
  917. files=extracted_files,
  918. errors=errors,
  919. )
  920. except zipfile.BadZipFile:
  921. raise HTTPException(status_code=400, detail="Invalid or corrupted ZIP file")
  922. except Exception as e:
  923. logger.error(f"ZIP extraction failed: {e}", exc_info=True)
  924. raise HTTPException(status_code=500, detail=f"ZIP extraction failed: {str(e)}")
  925. finally:
  926. # Clean up temp file
  927. try:
  928. os.unlink(tmp_path)
  929. except Exception:
  930. pass
  931. # ============ STL Thumbnail Batch Generation ============
  932. @router.post("/generate-stl-thumbnails", response_model=BatchThumbnailResponse)
  933. async def batch_generate_stl_thumbnails(
  934. request: BatchThumbnailRequest,
  935. db: AsyncSession = Depends(get_db),
  936. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPDATE_ALL)),
  937. ):
  938. """Generate thumbnails for STL files in batch.
  939. Note: Requires library:update_all permission since this is a batch operation
  940. that may affect files owned by different users.
  941. Can generate thumbnails for:
  942. - Specific file IDs (file_ids)
  943. - All STL files in a folder (folder_id)
  944. - All STL files missing thumbnails (all_missing=True)
  945. """
  946. thumbnails_dir = get_library_thumbnails_dir()
  947. results: list[BatchThumbnailResult] = []
  948. # Build query based on request
  949. query = select(LibraryFile).where(LibraryFile.file_type == "stl")
  950. if request.file_ids:
  951. # Specific files
  952. query = query.where(LibraryFile.id.in_(request.file_ids))
  953. elif request.folder_id is not None:
  954. # All STL files in a specific folder
  955. query = query.where(LibraryFile.folder_id == request.folder_id)
  956. if not request.all_missing:
  957. # If not specifically asking for missing thumbnails, get all
  958. pass
  959. else:
  960. query = query.where(LibraryFile.thumbnail_path.is_(None))
  961. elif request.all_missing:
  962. # All STL files without thumbnails
  963. query = query.where(LibraryFile.thumbnail_path.is_(None))
  964. else:
  965. # No criteria specified - return empty
  966. return BatchThumbnailResponse(
  967. processed=0,
  968. succeeded=0,
  969. failed=0,
  970. results=[],
  971. )
  972. result = await db.execute(query)
  973. stl_files = result.scalars().all()
  974. succeeded = 0
  975. failed = 0
  976. for stl_file in stl_files:
  977. file_path = to_absolute_path(stl_file.file_path)
  978. if not file_path or not file_path.exists():
  979. results.append(
  980. BatchThumbnailResult(
  981. file_id=stl_file.id,
  982. filename=stl_file.filename,
  983. success=False,
  984. error="File not found on disk",
  985. )
  986. )
  987. failed += 1
  988. continue
  989. try:
  990. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  991. if thumbnail_path:
  992. # Update database with relative path
  993. stl_file.thumbnail_path = to_relative_path(thumbnail_path)
  994. await db.flush()
  995. results.append(
  996. BatchThumbnailResult(
  997. file_id=stl_file.id,
  998. filename=stl_file.filename,
  999. success=True,
  1000. )
  1001. )
  1002. succeeded += 1
  1003. else:
  1004. results.append(
  1005. BatchThumbnailResult(
  1006. file_id=stl_file.id,
  1007. filename=stl_file.filename,
  1008. success=False,
  1009. error="Thumbnail generation failed",
  1010. )
  1011. )
  1012. failed += 1
  1013. except Exception as e:
  1014. logger.error(f"Failed to generate thumbnail for {stl_file.filename}: {e}")
  1015. results.append(
  1016. BatchThumbnailResult(
  1017. file_id=stl_file.id,
  1018. filename=stl_file.filename,
  1019. success=False,
  1020. error=str(e),
  1021. )
  1022. )
  1023. failed += 1
  1024. await db.commit()
  1025. return BatchThumbnailResponse(
  1026. processed=len(stl_files),
  1027. succeeded=succeeded,
  1028. failed=failed,
  1029. results=results,
  1030. )
  1031. # ============ Queue Operations ============
  1032. # NOTE: These routes must be defined BEFORE /files/{file_id} to avoid path parameter conflicts
  1033. def is_sliced_file(filename: str) -> bool:
  1034. """Check if a file is a sliced (printable) file.
  1035. Sliced files are:
  1036. - .gcode files
  1037. - .3mf files that contain '.gcode.' in the name (e.g., filename.gcode.3mf)
  1038. """
  1039. lower = filename.lower()
  1040. return lower.endswith(".gcode") or ".gcode." in lower
  1041. @router.post("/files/add-to-queue", response_model=AddToQueueResponse)
  1042. async def add_files_to_queue(
  1043. request: AddToQueueRequest,
  1044. db: AsyncSession = Depends(get_db),
  1045. _: User | None = Depends(require_permission_if_auth_enabled(Permission.QUEUE_CREATE)),
  1046. ):
  1047. """Add library files to the print queue.
  1048. Only sliced files (.gcode or .gcode.3mf) can be added to the queue.
  1049. The archive will be created automatically when the print starts.
  1050. """
  1051. added: list[AddToQueueResult] = []
  1052. errors: list[AddToQueueError] = []
  1053. # Get all requested files
  1054. result = await db.execute(select(LibraryFile).where(LibraryFile.id.in_(request.file_ids)))
  1055. files = {f.id: f for f in result.scalars().all()}
  1056. # Get max position for queue ordering
  1057. pos_result = await db.execute(select(func.coalesce(func.max(PrintQueueItem.position), 0)))
  1058. max_position = pos_result.scalar() or 0
  1059. for file_id in request.file_ids:
  1060. lib_file = files.get(file_id)
  1061. if not lib_file:
  1062. errors.append(AddToQueueError(file_id=file_id, filename="(not found)", error="File not found"))
  1063. continue
  1064. # Validate file is sliced
  1065. if not is_sliced_file(lib_file.filename):
  1066. errors.append(
  1067. AddToQueueError(
  1068. file_id=file_id,
  1069. filename=lib_file.filename,
  1070. error="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1071. )
  1072. )
  1073. continue
  1074. try:
  1075. # Verify file exists on disk
  1076. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1077. if not file_path.exists():
  1078. errors.append(
  1079. AddToQueueError(file_id=file_id, filename=lib_file.filename, error="File not found on disk")
  1080. )
  1081. continue
  1082. # Create queue item referencing library file (archive created at print start)
  1083. max_position += 1
  1084. queue_item = PrintQueueItem(
  1085. printer_id=None, # Unassigned
  1086. library_file_id=file_id,
  1087. position=max_position,
  1088. status="pending",
  1089. )
  1090. db.add(queue_item)
  1091. await db.flush() # Get queue_item.id
  1092. added.append(
  1093. AddToQueueResult(
  1094. file_id=file_id,
  1095. filename=lib_file.filename,
  1096. queue_item_id=queue_item.id,
  1097. )
  1098. )
  1099. except Exception as e:
  1100. logger.exception(f"Error adding file {file_id} to queue")
  1101. errors.append(AddToQueueError(file_id=file_id, filename=lib_file.filename, error=str(e)))
  1102. await db.commit()
  1103. return AddToQueueResponse(added=added, errors=errors)
  1104. @router.get("/files/{file_id}/plates")
  1105. async def get_library_file_plates(
  1106. file_id: int,
  1107. db: AsyncSession = Depends(get_db),
  1108. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1109. ):
  1110. """Get available plates from a multi-plate 3MF library file.
  1111. Returns a list of plates with their index, name, thumbnail availability,
  1112. and filament requirements. For single-plate exports, returns a single plate.
  1113. """
  1114. import json
  1115. import re
  1116. import zipfile
  1117. import defusedxml.ElementTree as ET
  1118. # Get the library file
  1119. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1120. lib_file = result.scalar_one_or_none()
  1121. if not lib_file:
  1122. raise HTTPException(status_code=404, detail="File not found")
  1123. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1124. if not file_path.exists():
  1125. raise HTTPException(status_code=404, detail="File not found on disk")
  1126. # Only 3MF files have plates
  1127. if not lib_file.filename.lower().endswith(".3mf"):
  1128. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1129. plates = []
  1130. try:
  1131. with zipfile.ZipFile(file_path, "r") as zf:
  1132. namelist = zf.namelist()
  1133. # Find all plate gcode files to determine available plates
  1134. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1135. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  1136. plate_indices: list[int] = []
  1137. if gcode_files:
  1138. # Extract plate indices from gcode filenames
  1139. for gf in gcode_files:
  1140. try:
  1141. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1142. plate_indices.append(int(plate_str))
  1143. except ValueError:
  1144. pass
  1145. else:
  1146. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  1147. plate_png_files = [
  1148. n
  1149. for n in namelist
  1150. if n.startswith("Metadata/plate_")
  1151. and n.endswith(".png")
  1152. and "_small" not in n
  1153. and "no_light" not in n
  1154. ]
  1155. plate_name_candidates = plate_json_files + plate_png_files
  1156. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  1157. seen_indices: set[int] = set()
  1158. for name in plate_name_candidates:
  1159. match = plate_re.match(name)
  1160. if match:
  1161. try:
  1162. index = int(match.group(1))
  1163. except ValueError:
  1164. continue
  1165. if index in seen_indices:
  1166. continue
  1167. seen_indices.add(index)
  1168. plate_indices.append(index)
  1169. if not plate_indices:
  1170. # No plate metadata found
  1171. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1172. plate_indices.sort()
  1173. # Parse model_settings.config for plate names + object assignments
  1174. plate_names = {}
  1175. plate_object_ids: dict[int, list[str]] = {}
  1176. object_names_by_id: dict[str, str] = {}
  1177. if "Metadata/model_settings.config" in namelist:
  1178. try:
  1179. model_content = zf.read("Metadata/model_settings.config").decode()
  1180. model_root = ET.fromstring(model_content)
  1181. for obj_elem in model_root.findall(".//object"):
  1182. obj_id = obj_elem.get("id")
  1183. if not obj_id:
  1184. continue
  1185. name_meta = obj_elem.find("metadata[@key='name']")
  1186. obj_name = name_meta.get("value") if name_meta is not None else None
  1187. if obj_name:
  1188. object_names_by_id[obj_id] = obj_name
  1189. for plate_elem in model_root.findall(".//plate"):
  1190. plater_id = None
  1191. plater_name = None
  1192. for meta in plate_elem.findall("metadata"):
  1193. key = meta.get("key")
  1194. value = meta.get("value")
  1195. if key == "plater_id" and value:
  1196. try:
  1197. plater_id = int(value)
  1198. except ValueError:
  1199. pass
  1200. elif key == "plater_name" and value:
  1201. plater_name = value.strip()
  1202. if plater_id is not None and plater_name:
  1203. plate_names[plater_id] = plater_name
  1204. if plater_id is not None:
  1205. for instance_elem in plate_elem.findall("model_instance"):
  1206. for inst_meta in instance_elem.findall("metadata"):
  1207. if inst_meta.get("key") == "object_id":
  1208. obj_id = inst_meta.get("value")
  1209. if not obj_id:
  1210. continue
  1211. plate_object_ids.setdefault(plater_id, [])
  1212. if obj_id not in plate_object_ids[plater_id]:
  1213. plate_object_ids[plater_id].append(obj_id)
  1214. except Exception:
  1215. pass
  1216. # Parse slice_info.config for plate metadata
  1217. plate_metadata = {}
  1218. if "Metadata/slice_info.config" in namelist:
  1219. content = zf.read("Metadata/slice_info.config").decode()
  1220. root = ET.fromstring(content)
  1221. for plate_elem in root.findall(".//plate"):
  1222. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1223. plate_index = None
  1224. for meta in plate_elem.findall("metadata"):
  1225. key = meta.get("key")
  1226. value = meta.get("value")
  1227. if key == "index" and value:
  1228. try:
  1229. plate_index = int(value)
  1230. except ValueError:
  1231. pass
  1232. elif key == "prediction" and value:
  1233. try:
  1234. plate_info["prediction"] = int(value)
  1235. except ValueError:
  1236. pass
  1237. elif key == "weight" and value:
  1238. try:
  1239. plate_info["weight"] = float(value)
  1240. except ValueError:
  1241. pass
  1242. # Get filaments used in this plate
  1243. for filament_elem in plate_elem.findall("filament"):
  1244. filament_id = filament_elem.get("id")
  1245. filament_type = filament_elem.get("type", "")
  1246. filament_color = filament_elem.get("color", "")
  1247. used_g = filament_elem.get("used_g", "0")
  1248. used_m = filament_elem.get("used_m", "0")
  1249. try:
  1250. used_grams = float(used_g)
  1251. except (ValueError, TypeError):
  1252. used_grams = 0
  1253. if used_grams > 0 and filament_id:
  1254. plate_info["filaments"].append(
  1255. {
  1256. "slot_id": int(filament_id),
  1257. "type": filament_type,
  1258. "color": filament_color,
  1259. "used_grams": round(used_grams, 1),
  1260. "used_meters": float(used_m) if used_m else 0,
  1261. }
  1262. )
  1263. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1264. # Collect object names
  1265. for obj_elem in plate_elem.findall("object"):
  1266. obj_name = obj_elem.get("name")
  1267. if obj_name and obj_name not in plate_info["objects"]:
  1268. plate_info["objects"].append(obj_name)
  1269. # Set plate name
  1270. if plate_index is not None:
  1271. custom_name = plate_names.get(plate_index)
  1272. if custom_name:
  1273. plate_info["name"] = custom_name
  1274. elif plate_info["objects"]:
  1275. plate_info["name"] = plate_info["objects"][0]
  1276. plate_metadata[plate_index] = plate_info
  1277. # Parse plate_*.json for object lists when slice_info is missing
  1278. plate_json_objects: dict[int, list[str]] = {}
  1279. for name in namelist:
  1280. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  1281. if not match:
  1282. continue
  1283. try:
  1284. plate_index = int(match.group(1))
  1285. except ValueError:
  1286. continue
  1287. try:
  1288. payload = json.loads(zf.read(name).decode())
  1289. bbox_objects = payload.get("bbox_objects", [])
  1290. names: list[str] = []
  1291. for obj in bbox_objects:
  1292. obj_name = obj.get("name") if isinstance(obj, dict) else None
  1293. if obj_name and obj_name not in names:
  1294. names.append(obj_name)
  1295. if names:
  1296. plate_json_objects[plate_index] = names
  1297. except Exception:
  1298. continue
  1299. # Build plate list
  1300. for idx in plate_indices:
  1301. meta = plate_metadata.get(idx, {})
  1302. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1303. objects = meta.get("objects", [])
  1304. if not objects:
  1305. objects = plate_json_objects.get(idx, [])
  1306. if not objects and plate_object_ids.get(idx):
  1307. objects = [
  1308. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  1309. ]
  1310. plate_name = meta.get("name")
  1311. if not plate_name:
  1312. plate_name = plate_names.get(idx)
  1313. if not plate_name and objects:
  1314. plate_name = objects[0]
  1315. plates.append(
  1316. {
  1317. "index": idx,
  1318. "name": plate_name,
  1319. "objects": objects,
  1320. "object_count": len(objects),
  1321. "has_thumbnail": has_thumbnail,
  1322. "thumbnail_url": f"/api/v1/library/files/{file_id}/plate-thumbnail/{idx}"
  1323. if has_thumbnail
  1324. else None,
  1325. "print_time_seconds": meta.get("prediction"),
  1326. "filament_used_grams": meta.get("weight"),
  1327. "filaments": meta.get("filaments", []),
  1328. }
  1329. )
  1330. except Exception as e:
  1331. logger.warning(f"Failed to parse plates from library file {file_id}: {e}")
  1332. return {
  1333. "file_id": file_id,
  1334. "filename": lib_file.filename,
  1335. "plates": plates,
  1336. "is_multi_plate": len(plates) > 1,
  1337. }
  1338. @router.get("/files/{file_id}/plate-thumbnail/{plate_index}")
  1339. async def get_library_file_plate_thumbnail(
  1340. file_id: int,
  1341. plate_index: int,
  1342. db: AsyncSession = Depends(get_db),
  1343. ):
  1344. """Get the thumbnail image for a specific plate from a library file."""
  1345. import zipfile
  1346. from starlette.responses import Response
  1347. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1348. lib_file = result.scalar_one_or_none()
  1349. if not lib_file:
  1350. raise HTTPException(status_code=404, detail="File not found")
  1351. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1352. if not file_path.exists():
  1353. raise HTTPException(status_code=404, detail="File not found on disk")
  1354. try:
  1355. with zipfile.ZipFile(file_path, "r") as zf:
  1356. thumb_path = f"Metadata/plate_{plate_index}.png"
  1357. if thumb_path in zf.namelist():
  1358. data = zf.read(thumb_path)
  1359. return Response(content=data, media_type="image/png")
  1360. except Exception:
  1361. pass
  1362. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1363. @router.get("/files/{file_id}/filament-requirements")
  1364. async def get_library_file_filament_requirements(
  1365. file_id: int,
  1366. plate_id: int | None = None,
  1367. db: AsyncSession = Depends(get_db),
  1368. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1369. ):
  1370. """Get filament requirements from a library file.
  1371. Parses the 3MF file to extract filament slot IDs, types, colors, and usage.
  1372. This enables AMS slot assignment when printing from the file manager.
  1373. Args:
  1374. file_id: The library file ID
  1375. plate_id: Optional plate index to get filaments for a specific plate
  1376. """
  1377. import zipfile
  1378. import defusedxml.ElementTree as ET
  1379. # Get the library file
  1380. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1381. lib_file = result.scalar_one_or_none()
  1382. if not lib_file:
  1383. raise HTTPException(status_code=404, detail="File not found")
  1384. # Get the full file path
  1385. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1386. if not file_path.exists():
  1387. raise HTTPException(status_code=404, detail="File not found on disk")
  1388. # Only 3MF files have parseable filament info
  1389. if not lib_file.filename.lower().endswith(".3mf"):
  1390. return {"file_id": file_id, "filename": lib_file.filename, "plate_id": plate_id, "filaments": []}
  1391. filaments = []
  1392. try:
  1393. with zipfile.ZipFile(file_path, "r") as zf:
  1394. # Parse slice_info.config for filament requirements
  1395. if "Metadata/slice_info.config" in zf.namelist():
  1396. content = zf.read("Metadata/slice_info.config").decode()
  1397. root = ET.fromstring(content)
  1398. if plate_id is not None:
  1399. # Find filaments for specific plate
  1400. for plate_elem in root.findall(".//plate"):
  1401. # Check if this is the requested plate
  1402. plate_index = None
  1403. for meta in plate_elem.findall("metadata"):
  1404. if meta.get("key") == "index":
  1405. try:
  1406. plate_index = int(meta.get("value", ""))
  1407. except ValueError:
  1408. pass
  1409. break
  1410. if plate_index == plate_id:
  1411. # Extract filaments from this plate
  1412. for filament_elem in plate_elem.findall("filament"):
  1413. filament_id = filament_elem.get("id")
  1414. filament_type = filament_elem.get("type", "")
  1415. filament_color = filament_elem.get("color", "")
  1416. used_g = filament_elem.get("used_g", "0")
  1417. used_m = filament_elem.get("used_m", "0")
  1418. tray_info_idx = filament_elem.get("tray_info_idx", "")
  1419. try:
  1420. used_grams = float(used_g)
  1421. except (ValueError, TypeError):
  1422. used_grams = 0
  1423. if used_grams > 0 and filament_id:
  1424. filaments.append(
  1425. {
  1426. "slot_id": int(filament_id),
  1427. "type": filament_type,
  1428. "color": filament_color,
  1429. "used_grams": round(used_grams, 1),
  1430. "used_meters": float(used_m) if used_m else 0,
  1431. "tray_info_idx": tray_info_idx,
  1432. }
  1433. )
  1434. break
  1435. else:
  1436. # Extract all filaments with used_g > 0 (for single-plate or overview)
  1437. for filament_elem in root.findall(".//filament"):
  1438. filament_id = filament_elem.get("id")
  1439. filament_type = filament_elem.get("type", "")
  1440. filament_color = filament_elem.get("color", "")
  1441. used_g = filament_elem.get("used_g", "0")
  1442. used_m = filament_elem.get("used_m", "0")
  1443. tray_info_idx = filament_elem.get("tray_info_idx", "")
  1444. try:
  1445. used_grams = float(used_g)
  1446. except (ValueError, TypeError):
  1447. used_grams = 0
  1448. if used_grams > 0 and filament_id:
  1449. filaments.append(
  1450. {
  1451. "slot_id": int(filament_id),
  1452. "type": filament_type,
  1453. "color": filament_color,
  1454. "used_grams": round(used_grams, 1),
  1455. "used_meters": float(used_m) if used_m else 0,
  1456. "tray_info_idx": tray_info_idx,
  1457. }
  1458. )
  1459. # Sort by slot ID
  1460. filaments.sort(key=lambda x: x["slot_id"])
  1461. except Exception as e:
  1462. logger.warning(f"Failed to parse filament requirements from library file {file_id}: {e}")
  1463. return {
  1464. "file_id": file_id,
  1465. "filename": lib_file.filename,
  1466. "plate_id": plate_id,
  1467. "filaments": filaments,
  1468. }
  1469. @router.post("/files/{file_id}/print")
  1470. async def print_library_file(
  1471. file_id: int,
  1472. printer_id: int,
  1473. body: FilePrintRequest | None = None,
  1474. db: AsyncSession = Depends(get_db),
  1475. _: User | None = Depends(require_permission_if_auth_enabled(Permission.PRINTERS_CONTROL)),
  1476. ):
  1477. """Print a library file directly.
  1478. This endpoint:
  1479. 1. Creates an archive from the library file
  1480. 2. Uploads the file to the printer
  1481. 3. Starts the print
  1482. Only sliced files (.gcode or .gcode.3mf) can be printed.
  1483. """
  1484. import zipfile
  1485. from backend.app.main import register_expected_print
  1486. from backend.app.models.printer import Printer
  1487. from backend.app.services.bambu_ftp import (
  1488. delete_file_async,
  1489. get_ftp_retry_settings,
  1490. upload_file_async,
  1491. with_ftp_retry,
  1492. )
  1493. from backend.app.services.printer_manager import printer_manager
  1494. # Use defaults if no body provided
  1495. if body is None:
  1496. body = FilePrintRequest()
  1497. # Get the library file
  1498. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1499. lib_file = result.scalar_one_or_none()
  1500. if not lib_file:
  1501. raise HTTPException(status_code=404, detail="File not found")
  1502. # Validate file is sliced
  1503. if not is_sliced_file(lib_file.filename):
  1504. raise HTTPException(
  1505. status_code=400,
  1506. detail="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1507. )
  1508. # Get the full file path
  1509. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1510. if not file_path.exists():
  1511. raise HTTPException(status_code=404, detail="File not found on disk")
  1512. # Get printer
  1513. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1514. printer = result.scalar_one_or_none()
  1515. if not printer:
  1516. raise HTTPException(status_code=404, detail="Printer not found")
  1517. # Check printer is connected
  1518. if not printer_manager.is_connected(printer_id):
  1519. raise HTTPException(status_code=400, detail="Printer is not connected")
  1520. # Create archive from the library file
  1521. archive_service = ArchiveService(db)
  1522. archive = await archive_service.archive_print(
  1523. printer_id=printer_id,
  1524. source_file=file_path,
  1525. )
  1526. if not archive:
  1527. raise HTTPException(status_code=500, detail="Failed to create archive")
  1528. await db.flush()
  1529. # Prepare remote filename
  1530. base_name = lib_file.filename
  1531. if base_name.endswith(".gcode.3mf"):
  1532. base_name = base_name[:-10]
  1533. elif base_name.endswith(".3mf"):
  1534. base_name = base_name[:-4]
  1535. remote_filename = f"{base_name}.3mf"
  1536. remote_path = f"/{remote_filename}"
  1537. # Get FTP retry settings
  1538. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1539. logger.info(
  1540. f"Library print FTP upload starting: printer={printer.name} ({printer.model}), "
  1541. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  1542. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  1543. )
  1544. # Delete existing file if present (avoids 553 error)
  1545. logger.debug(f"Deleting existing file {remote_path} if present...")
  1546. delete_result = await delete_file_async(
  1547. printer.ip_address,
  1548. printer.access_code,
  1549. remote_path,
  1550. socket_timeout=ftp_timeout,
  1551. printer_model=printer.model,
  1552. )
  1553. logger.debug(f"Delete result: {delete_result}")
  1554. # Upload file to printer
  1555. if ftp_retry_enabled:
  1556. uploaded = await with_ftp_retry(
  1557. upload_file_async,
  1558. printer.ip_address,
  1559. printer.access_code,
  1560. file_path,
  1561. remote_path,
  1562. socket_timeout=ftp_timeout,
  1563. printer_model=printer.model,
  1564. max_retries=ftp_retry_count,
  1565. retry_delay=ftp_retry_delay,
  1566. operation_name=f"Upload for print to {printer.name}",
  1567. )
  1568. else:
  1569. uploaded = await upload_file_async(
  1570. printer.ip_address,
  1571. printer.access_code,
  1572. file_path,
  1573. remote_path,
  1574. socket_timeout=ftp_timeout,
  1575. printer_model=printer.model,
  1576. )
  1577. if not uploaded:
  1578. logger.error(
  1579. f"FTP upload failed for library print: printer={printer.name}, model={printer.model}, "
  1580. f"ip={printer.ip_address}, file={remote_filename}. "
  1581. "Check logs above for storage diagnostics and specific error codes."
  1582. )
  1583. raise HTTPException(
  1584. status_code=500,
  1585. detail="Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  1586. "See server logs for detailed diagnostics.",
  1587. )
  1588. # Register this as an expected print so we don't create a duplicate archive
  1589. register_expected_print(printer_id, remote_filename, archive.id)
  1590. # Determine plate ID
  1591. if body.plate_id is not None:
  1592. plate_id = body.plate_id
  1593. else:
  1594. plate_id = 1
  1595. try:
  1596. with zipfile.ZipFile(file_path, "r") as zf:
  1597. for name in zf.namelist():
  1598. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1599. plate_str = name[15:-6]
  1600. plate_id = int(plate_str)
  1601. break
  1602. except Exception:
  1603. pass
  1604. logger.info(
  1605. f"Print library file {file_id}: archive_id={archive.id}, plate_id={plate_id}, "
  1606. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}"
  1607. )
  1608. # Start the print
  1609. started = printer_manager.start_print(
  1610. printer_id,
  1611. remote_filename,
  1612. plate_id,
  1613. ams_mapping=body.ams_mapping,
  1614. timelapse=body.timelapse,
  1615. bed_levelling=body.bed_levelling,
  1616. flow_cali=body.flow_cali,
  1617. vibration_cali=body.vibration_cali,
  1618. layer_inspect=body.layer_inspect,
  1619. use_ams=body.use_ams,
  1620. )
  1621. if not started:
  1622. raise HTTPException(status_code=500, detail="Failed to start print")
  1623. await db.commit()
  1624. return {
  1625. "status": "printing",
  1626. "printer_id": printer_id,
  1627. "archive_id": archive.id,
  1628. "filename": lib_file.filename,
  1629. }
  1630. # ============ File Detail Endpoints ============
  1631. @router.get("/files/{file_id}", response_model=FileResponseSchema)
  1632. async def get_file(
  1633. file_id: int,
  1634. db: AsyncSession = Depends(get_db),
  1635. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1636. ):
  1637. """Get a file by ID with full details."""
  1638. result = await db.execute(
  1639. select(LibraryFile).options(selectinload(LibraryFile.created_by)).where(LibraryFile.id == file_id)
  1640. )
  1641. file = result.scalar_one_or_none()
  1642. if not file:
  1643. raise HTTPException(status_code=404, detail="File not found")
  1644. # Get folder name
  1645. folder_name = None
  1646. if file.folder_id:
  1647. folder_result = await db.execute(select(LibraryFolder.name).where(LibraryFolder.id == file.folder_id))
  1648. folder_name = folder_result.scalar()
  1649. # Get project name
  1650. project_name = None
  1651. if file.project_id:
  1652. project_result = await db.execute(select(Project.name).where(Project.id == file.project_id))
  1653. project_name = project_result.scalar()
  1654. # Get duplicates
  1655. duplicates = []
  1656. duplicate_count = 0
  1657. if file.file_hash:
  1658. dup_result = await db.execute(
  1659. select(LibraryFile, LibraryFolder.name)
  1660. .outerjoin(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  1661. .where(LibraryFile.file_hash == file.file_hash, LibraryFile.id != file.id)
  1662. )
  1663. for dup_file, dup_folder_name in dup_result.all():
  1664. duplicates.append(
  1665. FileDuplicate(
  1666. id=dup_file.id,
  1667. filename=dup_file.filename,
  1668. folder_id=dup_file.folder_id,
  1669. folder_name=dup_folder_name,
  1670. created_at=dup_file.created_at,
  1671. )
  1672. )
  1673. duplicate_count = len(duplicates)
  1674. # Extract key metadata fields
  1675. print_name = None
  1676. print_time = None
  1677. filament_grams = None
  1678. sliced_for_model = None
  1679. if file.file_metadata:
  1680. print_name = file.file_metadata.get("print_name")
  1681. print_time = file.file_metadata.get("print_time_seconds")
  1682. filament_grams = file.file_metadata.get("filament_used_grams")
  1683. sliced_for_model = file.file_metadata.get("sliced_for_model")
  1684. return FileResponseSchema(
  1685. id=file.id,
  1686. folder_id=file.folder_id,
  1687. folder_name=folder_name,
  1688. project_id=file.project_id,
  1689. project_name=project_name,
  1690. filename=file.filename,
  1691. file_path=file.file_path,
  1692. file_type=file.file_type,
  1693. file_size=file.file_size,
  1694. file_hash=file.file_hash,
  1695. thumbnail_path=file.thumbnail_path,
  1696. metadata=file.file_metadata,
  1697. print_count=file.print_count,
  1698. last_printed_at=file.last_printed_at,
  1699. notes=file.notes,
  1700. duplicates=duplicates if duplicates else None,
  1701. duplicate_count=duplicate_count,
  1702. created_by_id=file.created_by_id,
  1703. created_by_username=file.created_by.username if file.created_by else None,
  1704. created_at=file.created_at,
  1705. updated_at=file.updated_at,
  1706. print_name=print_name,
  1707. print_time_seconds=print_time,
  1708. filament_used_grams=filament_grams,
  1709. sliced_for_model=sliced_for_model,
  1710. )
  1711. @router.put("/files/{file_id}", response_model=FileResponseSchema)
  1712. async def update_file(
  1713. file_id: int,
  1714. data: FileUpdate,
  1715. db: AsyncSession = Depends(get_db),
  1716. auth_result: tuple[User | None, bool] = Depends(
  1717. require_ownership_permission(
  1718. Permission.LIBRARY_UPDATE_ALL,
  1719. Permission.LIBRARY_UPDATE_OWN,
  1720. )
  1721. ),
  1722. ):
  1723. """Update a file's metadata."""
  1724. user, can_modify_all = auth_result
  1725. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1726. file = result.scalar_one_or_none()
  1727. if not file:
  1728. raise HTTPException(status_code=404, detail="File not found")
  1729. # Ownership check
  1730. if not can_modify_all:
  1731. if file.created_by_id != user.id:
  1732. raise HTTPException(status_code=403, detail="You can only update your own files")
  1733. if data.filename is not None:
  1734. # Validate filename doesn't contain path separators
  1735. if "/" in data.filename or "\\" in data.filename:
  1736. raise HTTPException(status_code=400, detail="Filename cannot contain path separators")
  1737. file.filename = data.filename
  1738. if data.folder_id is not None:
  1739. if data.folder_id == 0:
  1740. file.folder_id = None
  1741. else:
  1742. # Verify folder exists
  1743. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  1744. if not folder_result.scalar_one_or_none():
  1745. raise HTTPException(status_code=404, detail="Folder not found")
  1746. file.folder_id = data.folder_id
  1747. if data.project_id is not None:
  1748. if data.project_id == 0:
  1749. file.project_id = None
  1750. else:
  1751. # Verify project exists
  1752. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  1753. if not project_result.scalar_one_or_none():
  1754. raise HTTPException(status_code=404, detail="Project not found")
  1755. file.project_id = data.project_id
  1756. if data.notes is not None:
  1757. file.notes = data.notes if data.notes else None
  1758. await db.flush()
  1759. await db.refresh(file)
  1760. # Return full response (reuse get_file logic)
  1761. return await get_file(file_id, db)
  1762. @router.delete("/files/{file_id}")
  1763. async def delete_file(
  1764. file_id: int,
  1765. db: AsyncSession = Depends(get_db),
  1766. auth_result: tuple[User | None, bool] = Depends(
  1767. require_ownership_permission(
  1768. Permission.LIBRARY_DELETE_ALL,
  1769. Permission.LIBRARY_DELETE_OWN,
  1770. )
  1771. ),
  1772. ):
  1773. """Delete a file."""
  1774. user, can_modify_all = auth_result
  1775. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1776. file = result.scalar_one_or_none()
  1777. if not file:
  1778. raise HTTPException(status_code=404, detail="File not found")
  1779. # Ownership check
  1780. if not can_modify_all:
  1781. if file.created_by_id != user.id:
  1782. raise HTTPException(status_code=403, detail="You can only delete your own files")
  1783. # Delete actual files
  1784. try:
  1785. abs_file_path = to_absolute_path(file.file_path)
  1786. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  1787. if abs_file_path and abs_file_path.exists():
  1788. abs_file_path.unlink()
  1789. if abs_thumb_path and abs_thumb_path.exists():
  1790. abs_thumb_path.unlink()
  1791. except Exception as e:
  1792. logger.warning(f"Failed to delete file from disk: {e}")
  1793. await db.delete(file)
  1794. return {"status": "success", "message": "File deleted"}
  1795. # ============ File Content Endpoints ============
  1796. @router.get("/files/{file_id}/download")
  1797. async def download_file(
  1798. file_id: int,
  1799. db: AsyncSession = Depends(get_db),
  1800. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1801. ):
  1802. """Download a file."""
  1803. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1804. file = result.scalar_one_or_none()
  1805. if not file:
  1806. raise HTTPException(status_code=404, detail="File not found")
  1807. abs_path = to_absolute_path(file.file_path)
  1808. if not abs_path or not abs_path.exists():
  1809. raise HTTPException(status_code=404, detail="File not found on disk")
  1810. return FastAPIFileResponse(
  1811. str(abs_path),
  1812. filename=file.filename,
  1813. media_type="application/octet-stream",
  1814. )
  1815. @router.get("/files/{file_id}/thumbnail")
  1816. async def get_thumbnail(file_id: int, db: AsyncSession = Depends(get_db)):
  1817. """Get a file's thumbnail."""
  1818. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1819. file = result.scalar_one_or_none()
  1820. if not file:
  1821. raise HTTPException(status_code=404, detail="File not found")
  1822. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  1823. if not abs_thumb_path or not abs_thumb_path.exists():
  1824. raise HTTPException(status_code=404, detail="Thumbnail not found")
  1825. # Detect media type from extension
  1826. thumb_ext = abs_thumb_path.suffix.lower()
  1827. media_types = {
  1828. ".png": "image/png",
  1829. ".jpg": "image/jpeg",
  1830. ".jpeg": "image/jpeg",
  1831. ".gif": "image/gif",
  1832. ".webp": "image/webp",
  1833. }
  1834. media_type = media_types.get(thumb_ext, "image/png")
  1835. return FastAPIFileResponse(str(abs_thumb_path), media_type=media_type)
  1836. @router.get("/files/{file_id}/gcode")
  1837. async def get_gcode(
  1838. file_id: int,
  1839. db: AsyncSession = Depends(get_db),
  1840. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1841. ):
  1842. """Get gcode for a file (for preview)."""
  1843. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1844. file = result.scalar_one_or_none()
  1845. if not file:
  1846. raise HTTPException(status_code=404, detail="File not found")
  1847. abs_path = to_absolute_path(file.file_path)
  1848. if not abs_path or not abs_path.exists():
  1849. raise HTTPException(status_code=404, detail="File not found on disk")
  1850. if file.file_type == "gcode":
  1851. return FastAPIFileResponse(str(abs_path), media_type="text/plain")
  1852. elif file.file_type == "3mf":
  1853. # Extract gcode from 3mf
  1854. import zipfile
  1855. try:
  1856. with zipfile.ZipFile(str(abs_path), "r") as zf:
  1857. # Find gcode file
  1858. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  1859. if not gcode_files:
  1860. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  1861. gcode_content = zf.read(gcode_files[0])
  1862. from fastapi.responses import Response
  1863. return Response(content=gcode_content, media_type="text/plain")
  1864. except zipfile.BadZipFile:
  1865. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  1866. else:
  1867. raise HTTPException(status_code=400, detail="Unsupported file type")
  1868. # ============ Bulk Operations ============
  1869. @router.post("/files/move")
  1870. async def move_files(
  1871. data: FileMoveRequest,
  1872. db: AsyncSession = Depends(get_db),
  1873. auth_result: tuple[User | None, bool] = Depends(
  1874. require_ownership_permission(
  1875. Permission.LIBRARY_UPDATE_ALL,
  1876. Permission.LIBRARY_UPDATE_OWN,
  1877. )
  1878. ),
  1879. ):
  1880. """Move multiple files to a folder.
  1881. Files not owned by the user are skipped (unless user has *_all permission).
  1882. """
  1883. user, can_modify_all = auth_result
  1884. # Verify folder exists if specified
  1885. if data.folder_id is not None:
  1886. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  1887. if not folder_result.scalar_one_or_none():
  1888. raise HTTPException(status_code=404, detail="Folder not found")
  1889. # Update files
  1890. moved = 0
  1891. skipped = 0
  1892. for file_id in data.file_ids:
  1893. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1894. file = result.scalar_one_or_none()
  1895. if file:
  1896. # Ownership check
  1897. if not can_modify_all and file.created_by_id != user.id:
  1898. skipped += 1
  1899. continue
  1900. file.folder_id = data.folder_id
  1901. moved += 1
  1902. return {"status": "success", "moved": moved, "skipped": skipped}
  1903. @router.post("/bulk-delete", response_model=BulkDeleteResponse)
  1904. async def bulk_delete(
  1905. data: BulkDeleteRequest,
  1906. db: AsyncSession = Depends(get_db),
  1907. auth_result: tuple[User | None, bool] = Depends(
  1908. require_ownership_permission(
  1909. Permission.LIBRARY_DELETE_ALL,
  1910. Permission.LIBRARY_DELETE_OWN,
  1911. )
  1912. ),
  1913. ):
  1914. """Delete multiple files and/or folders.
  1915. Files not owned by the user are skipped (unless user has *_all permission).
  1916. """
  1917. user, can_modify_all = auth_result
  1918. deleted_files = 0
  1919. deleted_folders = 0
  1920. skipped_files = 0
  1921. # Delete files first
  1922. for file_id in data.file_ids:
  1923. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1924. file = result.scalar_one_or_none()
  1925. if file:
  1926. # Ownership check
  1927. if not can_modify_all and file.created_by_id != user.id:
  1928. skipped_files += 1
  1929. continue
  1930. try:
  1931. abs_file_path = to_absolute_path(file.file_path)
  1932. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  1933. if abs_file_path and abs_file_path.exists():
  1934. abs_file_path.unlink()
  1935. if abs_thumb_path and abs_thumb_path.exists():
  1936. abs_thumb_path.unlink()
  1937. except Exception as e:
  1938. logger.warning(f"Failed to delete file from disk: {e}")
  1939. await db.delete(file)
  1940. deleted_files += 1
  1941. # Delete folders (cascade will handle contents)
  1942. # Note: Folders don't have ownership tracking currently, require *_all permission
  1943. for folder_id in data.folder_ids:
  1944. if not can_modify_all:
  1945. # Users without *_all permission cannot delete folders
  1946. continue
  1947. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  1948. folder = result.scalar_one_or_none()
  1949. if folder:
  1950. # Count files that will be deleted
  1951. file_count_result = await db.execute(
  1952. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id)
  1953. )
  1954. deleted_files += file_count_result.scalar() or 0
  1955. await db.delete(folder)
  1956. deleted_folders += 1
  1957. return BulkDeleteResponse(deleted_files=deleted_files, deleted_folders=deleted_folders)
  1958. # ============ Stats Endpoint ============
  1959. @router.get("/stats")
  1960. async def get_library_stats(
  1961. db: AsyncSession = Depends(get_db),
  1962. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1963. ):
  1964. """Get library statistics."""
  1965. # Total files
  1966. total_files_result = await db.execute(select(func.count(LibraryFile.id)))
  1967. total_files = total_files_result.scalar() or 0
  1968. # Total folders
  1969. total_folders_result = await db.execute(select(func.count(LibraryFolder.id)))
  1970. total_folders = total_folders_result.scalar() or 0
  1971. # Total size
  1972. total_size_result = await db.execute(select(func.sum(LibraryFile.file_size)))
  1973. total_size = total_size_result.scalar() or 0
  1974. # Files by type
  1975. type_result = await db.execute(
  1976. select(LibraryFile.file_type, func.count(LibraryFile.id)).group_by(LibraryFile.file_type)
  1977. )
  1978. files_by_type = dict(type_result.all())
  1979. # Total prints
  1980. total_prints_result = await db.execute(select(func.sum(LibraryFile.print_count)))
  1981. total_prints = total_prints_result.scalar() or 0
  1982. # Disk space info
  1983. library_dir = get_library_dir()
  1984. try:
  1985. disk_stat = shutil.disk_usage(library_dir)
  1986. disk_free_bytes = disk_stat.free
  1987. disk_total_bytes = disk_stat.total
  1988. disk_used_bytes = disk_stat.used
  1989. except Exception:
  1990. disk_free_bytes = 0
  1991. disk_total_bytes = 0
  1992. disk_used_bytes = 0
  1993. return {
  1994. "total_files": total_files,
  1995. "total_folders": total_folders,
  1996. "total_size_bytes": total_size,
  1997. "files_by_type": files_by_type,
  1998. "total_prints": total_prints,
  1999. "disk_free_bytes": disk_free_bytes,
  2000. "disk_total_bytes": disk_total_bytes,
  2001. "disk_used_bytes": disk_used_bytes,
  2002. }