feat(file): add bulk download links API and frontend batch download dialog

This commit is contained in:
yiling
2026-06-11 11:44:26 +08:00
parent 81ccc803db
commit ec42c4e9ff
8 changed files with 639 additions and 19 deletions
+81
View File
@@ -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()
})
})
+63
View File
@@ -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<string>()
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
+157
View File
@@ -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')
}
})
})
})
+140
View File
@@ -1649,6 +1649,146 @@ export class AssetService {
)
}
async getDownloadLinks(
startingIds: string[],
): Promise<Array<{ id: string; name: string; url: string }>> {
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<string, typeof nonFolderAssets>()
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<string, (typeof finalFiles)[0]>()
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<PreviewInfo | null> {
if (!asset.media) return null
+17
View File
@@ -294,3 +294,20 @@ export const postAttachmentResponseSchema = z.object({
uploadUrl: z.string(),
})
export type PostAttachmentResponse = z.infer<typeof postAttachmentResponseSchema>
export const getDownloadLinksRequestSchema = z.object({
ids: z.array(z.string()),
})
export type GetDownloadLinksRequest = z.infer<typeof getDownloadLinksRequestSchema>
export const downloadLinkItemSchema = z.object({
id: z.string(),
name: z.string(),
url: z.string(),
})
export type DownloadLinkItem = z.infer<typeof downloadLinkItemSchema>
export const getDownloadLinksResponseSchema = z.object({
files: z.array(downloadLinkItemSchema),
})
export type GetDownloadLinksResponse = z.infer<typeof getDownloadLinksResponseSchema>
@@ -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({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Dialog open={isDownloadDialogOpen} onOpenChange={setIsDownloadDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{isDownloading ? 'Downloading Files' : 'Prepare Download'}</DialogTitle>
<DialogDescription>
{isDownloading
? 'Please wait while we queue your downloads. Do not close this dialog.'
: 'Selected files and folders will be prepared for download.'}
</DialogDescription>
</DialogHeader>
{!isDownloading ? (
<div className="space-y-4 py-2">
<div className="text-sm text-muted-foreground">
You have selected{' '}
<span className="font-medium text-foreground">{itemsToDownload.length}</span>{' '}
item(s).
</div>
<div className="flex items-start gap-3 p-3 text-sm rounded-lg bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-900/30">
<AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
<div>
<p className="font-semibold">No Folder Structure</p>
<p className="mt-0.5 text-xs text-amber-700/90 dark:text-amber-400/90">
Folder hierarchy will be flattened. All nested files will be downloaded directly
into your default download folder.
</p>
</div>
</div>
</div>
) : (
<div className="space-y-4 py-4">
<div className="flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<span className="text-sm font-medium text-foreground">
{downloadProgress.total === 0
? 'Preparing download links...'
: `Downloading file ${downloadProgress.current} of ${downloadProgress.total}...`}
</span>
</div>
{downloadProgress.total > 0 && (
<div className="space-y-2">
<Progress
value={Math.round((downloadProgress.current / downloadProgress.total) * 100)}
className="h-2"
/>
<p className="text-xs text-muted-foreground truncate">
Current file: {downloadProgress.currentName}
</p>
</div>
)}
</div>
)}
<DialogFooter>
{!isDownloading ? (
<>
<Button variant="outline" onClick={() => setIsDownloadDialogOpen(false)}>
Cancel
</Button>
<Button onClick={startDownload} className="gap-2">
<Download className="h-4 w-4" />
Start Download
</Button>
</>
) : (
<Button disabled variant="outline">
Downloading...
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
@@ -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<string | null>(null)
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false)
const [itemsToDownload, setItemsToDownload] = useState<AssetInfo[]>([])
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<typeof $getDownloadLinks, 200>,
Error,
InferRequestType<typeof $getDownloadLinks>
>({
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<typeof $getDownloadLinks, 200>
},
})
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,
}
}
+13 -13
View File
@@ -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'