feat(asset): add move to and copy to functionalities

This commit is contained in:
yiling
2026-05-24 20:15:55 +08:00
parent ffba9940e2
commit c5fba746be
9 changed files with 687 additions and 5 deletions
+93
View File
@@ -11,6 +11,7 @@ vi.mock('@/services/s3/s3', () => ({
putObject: vi.fn().mockResolvedValue(undefined),
deleteObject: vi.fn().mockResolvedValue(1),
deletePrefix: vi.fn().mockResolvedValue(1),
copyObject: vi.fn().mockResolvedValue(undefined),
},
}))
@@ -355,6 +356,98 @@ describe('AssetService', () => {
})
})
it('handles copying assets recursively', async () => {
const { user, assets } = await setupBasicAssets()
await assetService.copyAssets({
assetIds: [assets.folderA.id],
newParentId: assets.root3.id,
creatorId: user.id,
withComments: false,
})
// Verify root3 now has 1 more folder
await verifyAsset(assets.root3.id, {
type: AssetType.folder,
fileCount: 1,
size: 300,
})
// Verify children of folderA were copied
const copiedFolders = await prisma.asset.findMany({
where: { parentId: assets.root3.id, name: 'folderA' },
})
expect(copiedFolders.length).toBe(1)
const newFolderA = copiedFolders[0]
const children = await prisma.asset.findMany({
where: { parentId: newFolderA.id },
})
expect(children.length).toBe(2)
expect(children.map((c) => c.name)).toContain('fileA1')
expect(children.map((c) => c.name)).toContain('fileA2')
})
it('handles copying assets with comments and attachments', async () => {
const { user, assets, project } = await setupBasicAssets()
// Create a comment with attachment on fileA1
const attachmentAsset = await prisma.asset.create({
data: {
name: 'attach.png',
type: AssetType.attachment,
projectId: project.id,
creatorId: user.id,
status: 'uploaded',
sizeByte: 50,
},
})
const comment = await prisma.assetComment.create({
data: {
assetId: assets.fileA1.id,
creatorId: user.id,
message: 'Original Comment',
},
})
await prisma.assetCommentAttachment.create({
data: {
commentId: comment.id,
assetId: attachmentAsset.id,
},
})
await assetService.copyAssets({
assetIds: [assets.fileA1.id],
newParentId: assets.root3.id,
creatorId: user.id,
withComments: true,
})
// Find the copied file
const copiedFiles = await prisma.asset.findMany({
where: { parentId: assets.root3.id, name: 'fileA1' },
})
expect(copiedFiles.length).toBe(1)
const newFileA1 = copiedFiles[0]
// Verify comments were copied
const newComments = await prisma.assetComment.findMany({
where: { assetId: newFileA1.id },
include: { attachments: { include: { asset: true } } },
})
expect(newComments.length).toBe(1)
expect(newComments[0].message).toBe('Original Comment')
expect(newComments[0].attachments.length).toBe(1)
// Verify attachment asset was deep copied
const newAttachmentAsset = newComments[0].attachments[0].asset
expect(newAttachmentAsset.id).not.toBe(attachmentAsset.id)
expect(newAttachmentAsset.name).toBe('attach.png')
expect(newAttachmentAsset.type).toBe(AssetType.attachment)
})
it('handles reparenting - Version Stack: move into stack', async () => {
const { user, assets } = await setupBasicAssets()
await assetService.reparentAssets({
+203
View File
@@ -6,6 +6,7 @@ import {
AttachmentInfo,
ChildPreview,
CommentInfo,
CopyAssetsRequest,
CreateAssetRequest,
CreateCommentRequest,
FieldValueInfo,
@@ -21,6 +22,8 @@ import { Asset, AssetType, Prisma } from '@/generated/prisma/client.ts'
import { PaginatedData, paginateQuery, PaginationParams } from '@/services/pagination'
import { s3Service } from '@/services/s3/s3'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import * as path from 'path'
import { ulid } from 'ulid'
type AssetWithIncludes = Prisma.AssetGetPayload<{
include: {
@@ -266,6 +269,206 @@ export class AssetService {
})
}
async copyAssets(req: CopyAssetsRequest): Promise<void> {
await this.prismaClient.$transaction(async (tx) => {
const newParent = await tx.asset.findUnique({
where: { id: req.newParentId },
include: { project: { include: { team: true } } },
})
if (!newParent) throw new Error('New parent not found')
if (!newParent.project) throw new Error('New parent folder is not associated with a project')
const assetsToCopy = await tx.asset.findMany({
where: { id: { in: req.assetIds } },
include: { project: { include: { team: true } } },
})
if (assetsToCopy.length !== req.assetIds.length) {
throw new Error('Not all assets to be copied were found')
}
for (const a of assetsToCopy) {
if (!a.project || !a.project.team) {
throw new Error(`Asset ${a.id} is not associated with a team`)
}
if (!newParent.project.team) {
throw new Error('New parent folder is not associated with a team')
}
if (a.project.team.id !== newParent.project.team.id) {
throw new Error(`Cannot copy asset ${a.id} to a different team`)
}
}
const firstFile = await tx.asset.findFirst({
where: { parentId: newParent.id },
orderBy: { sortIndex: 'asc' },
})
let firstSortIndex = firstFile?.sortIndex || null
let totalSize = 0
for (let i = req.assetIds.length - 1; i >= 0; i--) {
const assetId = req.assetIds[i]
const asset = assetsToCopy.find((a) => a.id === assetId)!
const newSortIndex = generateSortIndex(firstSortIndex)
const copiedAsset = await this.copyAssetRecursive(
tx,
asset,
newParent.id,
newParent.projectId!,
newSortIndex,
req.creatorId,
req.withComments,
)
totalSize += copiedAsset.sizeByte
firstSortIndex = newSortIndex
}
await tx.asset.update({
where: { id: newParent.id },
data: {
fileCount: { increment: assetsToCopy.length },
},
})
await this.updateAncestorsSize(tx, newParent.id, totalSize)
})
}
private async copyAssetRecursive(
tx: Prisma.TransactionClient,
asset: Asset,
newParentId: string | null,
projectId: string | null,
sortIndex: string | null,
creatorId?: string,
withComments: boolean = false,
): Promise<Asset> {
let newKey = asset.key
if (asset.type === AssetType.file && asset.key) {
// Duplicate S3 object
const bucket = process.env.S3_BUCKET || 'shumai'
const ext = path.extname(asset.key)
newKey = ulid() + ext
await s3Service.copyObject(bucket, asset.key, bucket, newKey)
}
const newAsset = await tx.asset.create({
data: {
name: asset.name,
nameNgram: asset.nameNgram,
key: newKey,
type: asset.type,
mediaType: asset.mediaType,
fileCount: asset.fileCount,
sizeByte: asset.sizeByte,
status: asset.status,
transcodeTaskId: asset.transcodeTaskId,
media: (asset.media as any) || undefined,
isDeleted: asset.isDeleted,
deletedAt: asset.deletedAt,
sortIndex: sortIndex,
parentId: newParentId,
projectId: projectId,
creatorId: creatorId || asset.creatorId,
taskId: asset.taskId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
targetId: asset.targetId as any,
},
})
if (withComments) {
await this.copyComments(tx, asset.id, newAsset.id, creatorId)
}
if (asset.type === AssetType.folder) {
const children = await tx.asset.findMany({
where: { parentId: asset.id },
orderBy: { sortIndex: 'asc' },
})
for (const child of children) {
await this.copyAssetRecursive(
tx,
child,
newAsset.id,
projectId,
child.sortIndex,
creatorId,
withComments,
)
}
}
return newAsset
}
private async copyComments(
tx: Prisma.TransactionClient,
oldAssetId: string,
newAssetId: string,
creatorId?: string,
) {
const comments = await tx.assetComment.findMany({
where: { assetId: oldAssetId, replyToId: null },
include: {
attachments: { include: { asset: true } },
replies: {
include: {
attachments: { include: { asset: true } },
},
},
},
})
for (const comment of comments) {
await this.copyCommentRecursive(tx, comment, newAssetId, null, creatorId)
}
}
private async copyCommentRecursive(
tx: Prisma.TransactionClient,
comment: any, // eslint-disable-line @typescript-eslint/no-explicit-any
newAssetId: string,
newReplyToId: string | null,
creatorId?: string,
) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { id, createdAt, updatedAt, assetId, replyToId, attachments, replies, ...data } = comment
const newComment = await tx.assetComment.create({
data: {
...data,
assetId: newAssetId,
replyToId: newReplyToId,
creatorId: creatorId || comment.creatorId,
},
})
if (attachments) {
for (const attachment of attachments) {
// Deep copy attachment asset
const copiedAttachmentAsset = await this.copyAssetRecursive(
tx,
attachment.asset,
null, // attachment usually has no parent
attachment.asset.projectId,
attachment.asset.sortIndex,
creatorId,
false,
)
await tx.assetCommentAttachment.create({
data: {
commentId: newComment.id,
assetId: copiedAttachmentAsset.id,
},
})
}
}
if (replies) {
for (const reply of replies) {
await this.copyCommentRecursive(tx, reply, newAssetId, newComment.id, creatorId)
}
}
}
private async reparentFileToFile(
tx: Prisma.TransactionClient,
destFile: AssetWithProjectTeam,
+37
View File
@@ -1,5 +1,6 @@
import { ObjectInfo } from '@/dtos/s3'
import {
CopyObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
HeadObjectCommand,
@@ -49,6 +50,12 @@ export interface S3Service {
contentType?: string,
): Promise<void>
getObject(bucket: string, key: string): Promise<S3Object>
copyObject(
sourceBucket: string,
sourceKey: string,
destBucket: string,
destKey: string,
): Promise<void>
downloadToFile(bucket: string, key: string, filePath: string): Promise<void>
deleteObject(bucket: string, key: string): Promise<number>
deletePrefix(bucket: string, prefix: string): Promise<number>
@@ -131,6 +138,21 @@ export class S3StorageService implements S3Service {
}
}
async copyObject(
sourceBucket: string,
sourceKey: string,
destBucket: string,
destKey: string,
): Promise<void> {
const command = new CopyObjectCommand({
Bucket: destBucket,
Key: destKey,
// eslint-disable-next-line @typescript-eslint/naming-convention
CopySource: `${sourceBucket}/${sourceKey}`,
})
await this.client.send(command)
}
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
const command = new GetObjectCommand({
Bucket: bucket,
@@ -331,6 +353,21 @@ export class LocalStorageService implements S3Service {
}
}
async copyObject(
sourceBucket: string,
sourceKey: string,
destBucket: string,
destKey: string,
): Promise<void> {
const srcPath = this.getFilePath(sourceBucket, sourceKey)
const destPath = this.getFilePath(destBucket, destKey)
const dir = path.dirname(destPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
await fs.promises.copyFile(srcPath, destPath)
}
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
const srcPath = this.getFilePath(bucket, key)
await fs.promises.copyFile(srcPath, filePath)