From ec42c4e9ffb9c5f70b9bb87f97332411c6f72800 Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 11 Jun 2026 11:44:26 +0800 Subject: [PATCH] feat(file): add bulk download links API and frontend batch download dialog --- packages/api/src/api/file.test.ts | 81 +++++++++ packages/api/src/api/file.ts | 63 +++++++ packages/core/src/asset/asset.test.ts | 157 ++++++++++++++++++ packages/core/src/asset/asset.ts | 140 ++++++++++++++++ packages/dtos/src/asset.ts | 17 ++ .../components/file-browser/file-browser.tsx | 90 +++++++++- .../file-browser/use-file-actions.ts | 84 +++++++++- packages/webui/components/members-dialog.tsx | 26 +-- 8 files changed, 639 insertions(+), 19 deletions(-) diff --git a/packages/api/src/api/file.test.ts b/packages/api/src/api/file.test.ts index c2f5968b..66ec2efb 100644 --- a/packages/api/src/api/file.test.ts +++ b/packages/api/src/api/file.test.ts @@ -36,6 +36,7 @@ vi.mock('@shumai/core/src/authz/authz', () => ({ ResourceType: { Asset: 'asset', Team: 'team', + Project: 'project', }, })) @@ -452,4 +453,84 @@ describe('file api', () => { beforeIndex: 'index-1', }) }) + + it('POST /files/download-links generates links if assets belong to the same project', async () => { + const mockFindMany = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([ + { + id: 'asset1', + projectId: 'project-id-1', + type: 'file', + targetId: null, + }, + { + id: 'asset2', + projectId: 'project-id-1', + type: 'folder', + targetId: null, + }, + // Mocking only the required subset of Prisma Asset properties for the test + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ] as any) + + const mockGetDownloadLinks = vi.spyOn(assetService, 'getDownloadLinks').mockResolvedValue([ + { id: 'file1', name: 'file1.txt', url: 'http://link1' }, + { id: 'file2', name: 'file2.txt', url: 'http://link2' }, + ]) + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/download-links', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: ['asset1', 'asset2'] }), + }) + + expect(res.status).toBe(200) + const json = await res.json() + expect(json.files).toHaveLength(2) + expect(json.files[0].name).toBe('file1.txt') + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user1', name: 'Test User' }, + permission: Permission.Read, + type: 'project', + id: 'project-id-1', + }) + + expect(assetService.getDownloadLinks).toHaveBeenCalledWith(['asset1', 'asset2']) + + mockFindMany.mockRestore() + mockGetDownloadLinks.mockRestore() + }) + + it('POST /files/download-links rejects if assets belong to different projects', async () => { + const mockFindMany = vi.spyOn(prisma.asset, 'findMany').mockResolvedValue([ + { + id: 'asset1', + projectId: 'project-id-1', + type: 'file', + targetId: null, + }, + { + id: 'asset2', + projectId: 'project-id-2', + type: 'file', + targetId: null, + }, + // Mocking only the required subset of Prisma Asset properties for the test + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ] as any) + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/download-links', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: ['asset1', 'asset2'] }), + }) + + expect(res.status).toBe(400) + const json = await res.json() + expect(json.error).toBe('All selected items must belong to the same project') + + mockFindMany.mockRestore() + }) }) diff --git a/packages/api/src/api/file.ts b/packages/api/src/api/file.ts index b7c7b00c..63f151ca 100644 --- a/packages/api/src/api/file.ts +++ b/packages/api/src/api/file.ts @@ -15,6 +15,7 @@ import { updateAssetOrderRequestSchema, updateFileRequestSchema, uploadFileRequestSchema, + getDownloadLinksRequestSchema, } from '@shumai/dtos' import { transcodeService } from '@shumai/transcode/src/transcode' import fs from 'fs' @@ -264,5 +265,67 @@ const route = new Hono<{ Variables: { user: User } }>() return c.json({ key }) }) + .post('/files/download-links', zValidator('json', getDownloadLinksRequestSchema), async (c) => { + const user = c.get('user') + const req = c.req.valid('json') + + if (req.ids.length === 0) { + return c.json({ files: [] }) + } + + // 1. Fetch input assets to verify project grouping + const assets = await prisma.asset.findMany({ + where: { id: { in: req.ids }, isDeleted: false }, + select: { + id: true, + projectId: true, + type: true, + targetId: true, + target: { select: { projectId: true } }, + }, + }) + + if (assets.length === 0) { + return c.json({ files: [] }) + } + + const projectIds = new Set() + for (const asset of assets) { + let projId = asset.projectId + if (asset.type === 'symlink' && asset.target?.projectId) { + projId = asset.target.projectId + } + if (projId) { + projectIds.add(projId) + } + } + + // 2. Validate same-project constraint + if (projectIds.size !== 1) { + return c.json({ error: 'All selected items must belong to the same project' }, 400) + } + + const projectId = Array.from(projectIds)[0] + + // 3. Verify user has READ permission on this project + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Project, + id: projectId, + }) + + // 4. Resolve starting IDs (dereference top-level symlinks) + const startingIds = assets.map((asset) => { + if (asset.type === 'symlink' && asset.targetId) { + return asset.targetId + } + return asset.id + }) + + // 5. Generate download links + const files = await assetService.getDownloadLinks(startingIds) + return c.json({ files }) + }) export default route diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 75e977d4..5a820b09 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -1647,4 +1647,161 @@ describe('AssetService — natural sort by name', () => { expect(result.data.map((a) => a.name)).toEqual(['apple', 'apricot', 'banana', 'cherry']) }) + + describe('getDownloadLinks', () => { + it('resolves folders, version stacks, and symlinks to correct latest files and urls', async () => { + const user = await prisma.user.create({ + data: { + name: 'DownloadUser', + email: `download-${Date.now()}@example.com`, + }, + }) + const team = await prisma.team.create({ data: { name: 'DownloadTeam' } }) + const project = await prisma.project.create({ + data: { name: 'DownloadProject', teamId: team.id }, + }) + + // Create folder structure: + // - rootFolder (folder) + // - file1.txt (file) + // - subFolder (folder) + // - file2.txt (file) + // - stack (version_stack) + // - version1.txt (file, sortIndex = 'a1') + // - version2.txt (file, sortIndex = 'a0') -> latest + // - symlinkToFile (symlink -> file1.txt) + // - symlinkToStack (symlink -> stack) + + const rootFolder = await prisma.asset.create({ + data: { + name: 'rootFolder', + type: AssetType.folder, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + }, + }) + + const file1 = await prisma.asset.create({ + data: { + name: 'file1.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + storageKey: { create: { key: 'keys/file1' } }, + }, + }) + + const subFolder = await prisma.asset.create({ + data: { + name: 'subFolder', + type: AssetType.folder, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + }, + }) + + await prisma.asset.create({ + data: { + name: 'file2.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: subFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + storageKey: { create: { key: 'keys/file2' } }, + }, + }) + + const stack = await prisma.asset.create({ + data: { + name: 'stack', + type: AssetType.version_stack, + project: { connect: { id: project.id } }, + parent: { connect: { id: subFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + }, + }) + + await prisma.asset.create({ + data: { + name: 'version1.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: stack.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + sortIndex: 'a1', + storageKey: { create: { key: 'keys/v1' } }, + }, + }) + + await prisma.asset.create({ + data: { + name: 'version2.txt', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: stack.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + sortIndex: 'a0', // smaller sortIndex means latest + storageKey: { create: { key: 'keys/v2' } }, + }, + }) + + await prisma.asset.create({ + data: { + name: 'symlinkToFile', + type: AssetType.symlink, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + target: { connect: { id: file1.id } }, + }, + }) + + await prisma.asset.create({ + data: { + name: 'symlinkToStack', + type: AssetType.symlink, + project: { connect: { id: project.id } }, + parent: { connect: { id: rootFolder.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + target: { connect: { id: stack.id } }, + }, + }) + + // Run download links request on rootFolder + const result = await assetService.getDownloadLinks([rootFolder.id]) + + // We expect: + // 1. file1.txt + // 2. file2.txt + // 3. version2.txt (latest version of the stack) + // 4. file1.txt (from symlinkToFile target resolution, deduplicated) + // 5. version2.txt (from symlinkToStack target resolution, deduplicated) + + const fileNames = result.map((r) => r.name) + expect(fileNames).toHaveLength(3) // 3 unique files + expect(fileNames).toContain('file1.txt') + expect(fileNames).toContain('file2.txt') + expect(fileNames).toContain('version2.txt') + expect(fileNames).not.toContain('version1.txt') // older version should not be downloaded + expect(fileNames).not.toContain('rootFolder') + expect(fileNames).not.toContain('subFolder') + expect(fileNames).not.toContain('stack') + + // Check urls are returned correctly (mock s3 presign resolves to 'http://mock-s3-url') + for (const item of result) { + expect(item.url).toBe('http://mock-s3-url') + } + }) + }) }) diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index b28b50a6..6bf85adf 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -1649,6 +1649,146 @@ export class AssetService { ) } + async getDownloadLinks( + startingIds: string[], + ): Promise> { + if (startingIds.length === 0) return [] + + const descendants = await this.prismaClient.$queryRaw< + Array<{ + id: string + name: string + type: string + parentId: string | null + storageKeyId: string | null + sortIndex: string | null + targetId: string | null + }> + >` + WITH RECURSIVE descendant AS ( + SELECT id, name, type, parent_id, storage_key_id, sort_index, target_id, is_deleted + FROM assets + WHERE id IN (${Prisma.join(startingIds)}) AND is_deleted = false + UNION ALL + SELECT a.id, a.name, a.type, a.parent_id, a.storage_key_id, a.sort_index, a.target_id, a.is_deleted + FROM assets a + INNER JOIN descendant d ON a.parent_id = d.id + WHERE a.is_deleted = false + ) + SELECT id, name, type, parent_id AS "parentId", storage_key_id AS "storageKeyId", sort_index AS "sortIndex", target_id AS "targetId" FROM descendant; + ` + + // Find any symlink in the descendants and resolve its target. + const symlinks = descendants.filter((d) => d.type === 'symlink') + let resolvedTargets: Array<{ + id: string + name: string + type: string + parentId: string | null + storageKeyId: string | null + sortIndex: string | null + targetId: string | null + }> = [] + + if (symlinks.length > 0) { + const targetIds = symlinks.map((s) => s.targetId).filter((id): id is string => !!id) + if (targetIds.length > 0) { + const dbTargets = await this.prismaClient.asset.findMany({ + where: { id: { in: targetIds }, isDeleted: false }, + }) + resolvedTargets = dbTargets.map((t) => ({ + id: t.id, + name: t.name, + type: t.type, + parentId: t.parentId, + storageKeyId: t.storageKeyId, + sortIndex: t.sortIndex, + targetId: t.targetId, + })) + } + } + + const allAssets = [...descendants.filter((d) => d.type !== 'symlink'), ...resolvedTargets] + + const nonFolderAssets = allAssets.filter( + (a) => + a.type !== 'folder' && a.type !== 'root' && a.type !== 'share_root' && a.type !== 'share', + ) + + // Separate version stacks and other files + const versionStackIds = new Set( + nonFolderAssets.filter((a) => a.type === 'version_stack').map((a) => a.id), + ) + + const versionAssetsByStack = new Map() + const otherAssets: typeof nonFolderAssets = [] + + for (const asset of nonFolderAssets) { + if (asset.type === 'version_stack') { + continue + } + if (asset.parentId && versionStackIds.has(asset.parentId)) { + const list = versionAssetsByStack.get(asset.parentId) || [] + list.push(asset) + versionAssetsByStack.set(asset.parentId, list) + } else { + otherAssets.push(asset) + } + } + + // Pick the latest version for each version stack (ascending sortIndex: 'asc' means first version is latest) + const latestVersions: typeof nonFolderAssets = [] + for (const versions of versionAssetsByStack.values()) { + versions.sort((x, y) => { + if (!x.sortIndex || !y.sortIndex) return 0 + return x.sortIndex < y.sortIndex ? -1 : x.sortIndex > y.sortIndex ? 1 : 0 + }) + if (versions.length > 0) { + latestVersions.push(versions[0]) + } + } + + const finalFiles = [...otherAssets, ...latestVersions] + + // Deduplicate files by id + const uniqueFilesMap = new Map() + for (const file of finalFiles) { + uniqueFilesMap.set(file.id, file) + } + const deduplicatedFiles = Array.from(uniqueFilesMap.values()) + + // Fetch storage keys + const storageKeyIds = deduplicatedFiles + .map((f) => f.storageKeyId) + .filter((id): id is string => !!id) + const storageKeys = await this.prismaClient.storageKey.findMany({ + where: { id: { in: storageKeyIds } }, + }) + const storageKeyMap = new Map(storageKeys.map((k) => [k.id, k.key])) + + const downloadLinks = await Promise.all( + deduplicatedFiles.map(async (file) => { + const key = file.storageKeyId ? storageKeyMap.get(file.storageKeyId) : null + if (!key) return null + + const url = await s3Service.presign( + process.env.S3_BUCKET || 'shumai', + key, + 'GET', + file.name, + ) + + return { + id: file.id, + name: file.name, + url, + } + }), + ) + + return downloadLinks.filter((link): link is { id: string; name: string; url: string } => !!link) + } + private async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise { if (!asset.media) return null diff --git a/packages/dtos/src/asset.ts b/packages/dtos/src/asset.ts index 1b81ec2d..4855fbbb 100644 --- a/packages/dtos/src/asset.ts +++ b/packages/dtos/src/asset.ts @@ -294,3 +294,20 @@ export const postAttachmentResponseSchema = z.object({ uploadUrl: z.string(), }) export type PostAttachmentResponse = z.infer + +export const getDownloadLinksRequestSchema = z.object({ + ids: z.array(z.string()), +}) +export type GetDownloadLinksRequest = z.infer + +export const downloadLinkItemSchema = z.object({ + id: z.string(), + name: z.string(), + url: z.string(), +}) +export type DownloadLinkItem = z.infer + +export const getDownloadLinksResponseSchema = z.object({ + files: z.array(downloadLinkItemSchema), +}) +export type GetDownloadLinksResponse = z.infer diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index a11c1fd1..fd5a77ef 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -13,7 +13,7 @@ import { useFieldStore } from '@/ui/stores/fields' import { useUploadStore } from '@/ui/stores/upload' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' -import { Download } from 'lucide-react' +import { Download, AlertTriangle, Loader2 } from 'lucide-react' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { toast } from 'sonner' import type { DragState } from '../dnd-types' @@ -30,6 +30,15 @@ import { AlertDialogHeader, AlertDialogTitle, } from '../ui/alert-dialog' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '../ui/dialog' +import { Progress } from '../ui/progress' import { Button } from '../ui/button' import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu' import { FileCard } from './file-card' @@ -327,6 +336,12 @@ export function FileBrowser({ isDeleteDialogOpen, setIsDeleteDialogOpen, confirmDelete, + isDownloadDialogOpen, + setIsDownloadDialogOpen, + itemsToDownload, + isDownloading, + downloadProgress, + startDownload, } = useFileActions({ teamId, projectId, @@ -1007,6 +1022,79 @@ export function FileBrowser({ + + + + + {isDownloading ? 'Downloading Files' : 'Prepare Download'} + + {isDownloading + ? 'Please wait while we queue your downloads. Do not close this dialog.' + : 'Selected files and folders will be prepared for download.'} + + + + {!isDownloading ? ( +
+
+ You have selected{' '} + {itemsToDownload.length}{' '} + item(s). +
+
+ +
+

No Folder Structure

+

+ Folder hierarchy will be flattened. All nested files will be downloaded directly + into your default download folder. +

+
+
+
+ ) : ( +
+
+ + + {downloadProgress.total === 0 + ? 'Preparing download links...' + : `Downloading file ${downloadProgress.current} of ${downloadProgress.total}...`} + +
+ {downloadProgress.total > 0 && ( +
+ +

+ Current file: {downloadProgress.currentName} +

+
+ )} +
+ )} + + + {!isDownloading ? ( + <> + + + + ) : ( + + )} + +
+
) } diff --git a/packages/webui/components/file-browser/use-file-actions.ts b/packages/webui/components/file-browser/use-file-actions.ts index 24f26dcb..3b45c4c3 100644 --- a/packages/webui/components/file-browser/use-file-actions.ts +++ b/packages/webui/components/file-browser/use-file-actions.ts @@ -5,6 +5,7 @@ import type { AssetInfo } from '@shumai/dtos' import { useMutation, useQueryClient } from '@tanstack/react-query' import type { InferRequestType, InferResponseType } from 'hono/client' import { useState } from 'react' +import { toast } from 'sonner' interface UseFileActionsProps { teamId: string @@ -26,6 +27,14 @@ export function useFileActions({ const [editingItemId, setEditingItemId] = useState(null) const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false) const [itemsToDelete, setItemsToDelete] = useState([]) + const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false) + const [itemsToDownload, setItemsToDownload] = useState([]) + const [isDownloading, setIsDownloading] = useState(false) + const [downloadProgress, setDownloadProgress] = useState<{ + current: number + total: number + currentName: string + }>({ current: 0, total: 0, currentName: '' }) const queryClient = useQueryClient() const $createFolder = client.api.folders.$post @@ -111,6 +120,19 @@ export function useFileActions({ }, }) + const $getDownloadLinks = client.api.files['download-links'].$post + const { mutateAsync: getDownloadLinks } = useMutation< + InferResponseType, + Error, + InferRequestType + >({ + mutationFn: async (request) => { + const res = await $getDownloadLinks(request) + if (!res.ok) throw new Error('Failed to get download links') + return (await res.json()) as unknown as InferResponseType + }, + }) + const handleRename = (item: AssetInfo) => { setEditingItemId(item.id!) } @@ -186,11 +208,57 @@ export function useFileActions({ } const handleDownload = (items: AssetInfo[]) => { - alert( - `Download functionality - Would download ${ - items.length - } item(s): ${items.map((i) => i.name).join(', ')}`, - ) + if (items.length === 0) return + setItemsToDownload(items) + setDownloadProgress({ current: 0, total: 0, currentName: '' }) + setIsDownloadDialogOpen(true) + } + + const startDownload = async () => { + setIsDownloading(true) + try { + const res = await getDownloadLinks({ + json: { ids: itemsToDownload.map((i) => i.id!) }, + }) + const files = res.files + + const chunkSize = 5 + const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + + for (let i = 0; i < files.length; i += chunkSize) { + const chunk = files.slice(i, i + chunkSize) + + // Trigger downloads for this batch in parallel by creating/clicking links + for (const file of chunk) { + const absoluteIndex = i + chunk.indexOf(file) + 1 + setDownloadProgress({ + current: absoluteIndex, + total: files.length, + currentName: file.name, + }) + + const a = document.createElement('a') + a.href = file.url + a.download = file.name + a.target = '_blank' + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + } + + // If we have more chunks to process, wait 1 second before triggering the next batch + if (i + chunkSize < files.length) { + await delay(1000) + } + } + toast.success('Downloads started successfully') + } catch (error) { + toast.error('Download failed') + console.error(error) + } finally { + setIsDownloading(false) + setIsDownloadDialogOpen(false) + } } const handleNewFolder = (name: string) => { @@ -283,5 +351,11 @@ export function useFileActions({ setIsDeleteDialogOpen, itemsToDelete, confirmDelete, + isDownloadDialogOpen, + setIsDownloadDialogOpen, + itemsToDownload, + isDownloading, + downloadProgress, + startDownload, } } diff --git a/packages/webui/components/members-dialog.tsx b/packages/webui/components/members-dialog.tsx index 1c7fffa0..73bbcffa 100644 --- a/packages/webui/components/members-dialog.tsx +++ b/packages/webui/components/members-dialog.tsx @@ -1,22 +1,22 @@ import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar' import { Button } from '@/ui/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog' import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, - DropdownMenuTrigger, + DropdownMenu, + DropdownMenuContent, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Input } from '@/ui/components/ui/input' import { ChevronDown, Copy, Loader2, Trash2 } from 'lucide-react'