initial commit

This commit is contained in:
yiling
2026-05-19 16:05:09 +08:00
commit 9cad96210c
370 changed files with 131609 additions and 0 deletions
+182
View File
@@ -0,0 +1,182 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { uploadService } from './upload'
import { AssetStatus, AssetType, WorkflowTaskType } from '@/generated/prisma/client'
vi.mock('@/services/s3/s3', () => ({
s3Service: {
presign: vi.fn().mockResolvedValue('http://presigned-url.com'),
getObjectSize: vi.fn().mockResolvedValue(100),
},
}))
describe('UploadService', () => {
setupTestDbHooks()
let userId: string
let teamId: string
let projectId: string
let parentId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: { name: 'test', email: 'test-upload@example.com' },
})
userId = user.id
const team = await prisma.team.create({ data: { name: 'team' } })
teamId = team.id
const project = await prisma.project.create({
data: { name: 'project', teamId },
})
projectId = project.id
const parent = await prisma.asset.create({
data: {
name: 'parent',
type: AssetType.folder,
projectId,
status: AssetStatus.uploaded,
},
})
parentId = parent.id
})
it('should create an upload task', async () => {
const req = {
parentId: parentId,
files: [
{
name: 'file1.txt',
id: '1',
size: 100,
type: 'file',
mediaType: 'video/mp4',
children: [],
},
{
name: 'folder1',
id: '2',
type: 'folder',
size: 0,
children: [
{
name: 'file2.txt',
id: '3',
size: 200,
type: 'file',
mediaType: 'image/png',
children: [],
},
],
},
{ name: '.hidden', id: '4', size: 100, type: 'file', children: [] },
],
}
const resp = await uploadService.createUploadTask(userId, req)
expect(resp.taskId).toBeDefined()
expect(resp.presignedUrls).toHaveLength(2)
const task = await prisma.task.findUnique({ where: { id: resp.taskId } })
expect(task?.name).toBe('2 Items')
expect(task?.total).toBe(2)
const file1 = await prisma.asset.findFirst({ where: { name: 'file1.txt' } })
expect(file1?.mediaType).toBe('video/mp4')
const file2 = await prisma.asset.findFirst({ where: { name: 'file2.txt' } })
expect(file2?.mediaType).toBe('image/png')
const hidden = await prisma.asset.findFirst({ where: { name: '.hidden' } })
expect(hidden).toBeNull()
})
it('should confirm file upload and create transcode tasks for video', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'video.mp4',
type: AssetType.file,
projectId,
parentId,
status: AssetStatus.uploading,
key: 'test-key',
mediaType: 'video/mp4',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } })
// For video/image, status remains 'uploaded' while transcoding is pending
expect(updatedAsset?.status).toBe(AssetStatus.uploaded)
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode },
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
videoStrategy: 'single',
sprite: true,
poster: true,
})
})
it('should confirm file upload and create transcode tasks for image', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'image.png',
type: AssetType.file,
projectId,
parentId,
status: AssetStatus.uploading,
key: 'test-key',
mediaType: 'image/png',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode },
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
imageStrategy: 'single',
thumbnail: true,
})
})
it('should confirm file upload for non-media files', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'file.txt',
type: AssetType.file,
projectId,
parentId,
status: AssetStatus.uploading,
key: 'test-key',
mediaType: 'text/plain',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } })
expect(updatedAsset?.status).toBe(AssetStatus.processed)
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode },
})
expect(workflowTask).toBeNull()
})
})
+350
View File
@@ -0,0 +1,350 @@
import { prisma } from '@/db'
import { ulid } from 'ulid'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { s3Service } from '@/services/s3/s3'
import { assetService } from '@/services/asset/asset'
import {
ConfirmFileUploadRequest,
CreateUploadTaskRequest,
CreateUploadTaskResponse,
FileNode,
PresignedUrl,
TaskInfo,
} from '@/dtos/upload'
import {
AssetStatus,
AssetType,
Prisma,
TaskStatus,
WorkflowTaskStatus,
WorkflowTaskType,
} from '@/generated/prisma/client'
import { PaginationParams, paginateQuery, PaginatedData } from '@/services/pagination'
import { VideoTranscoder, ImageTranscoder } from '@/transcode/transcoder'
export class UploadService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async createUploadTask(
userId: string,
req: CreateUploadTaskRequest,
): Promise<CreateUploadTaskResponse> {
const visibleFiles = req.files.filter((f) => !f.name.startsWith('.'))
let taskName = ''
if (visibleFiles.length === 1) {
taskName = visibleFiles[0].name
} else {
taskName = `${visibleFiles.length} Items`
}
let total = 0
const countTotalFiles = (nodes: FileNode[]) => {
for (const node of nodes) {
if (node.name.startsWith('.')) continue
if (node.type === 'file') {
total++
} else {
countTotalFiles(node.children)
}
}
}
countTotalFiles(req.files)
const task = await this.prismaClient.task.create({
data: {
creatorId: userId,
type: 'upload',
name: taskName,
total,
status: TaskStatus.pending,
},
})
const parentAsset = await this.prismaClient.asset.findUnique({
where: { id: req.parentId },
include: { project: true },
})
if (!parentAsset) throw new Error('Parent asset not found')
if (!parentAsset.projectId) throw new Error('Parent asset has no project')
const presignedUrls: PresignedUrl[] = []
await this.createAssetsRecursively(
userId,
task.id,
parentAsset.projectId,
parentAsset.id,
req.files,
presignedUrls,
)
return {
taskId: task.id,
presignedUrls: presignedUrls,
}
}
private async createAssetsRecursively(
userId: string,
taskId: string,
projectId: string,
parentId: string,
files: FileNode[],
presignedUrls: PresignedUrl[],
): Promise<void> {
const firstFile = await this.prismaClient.asset.findFirst({
where: { parentId },
orderBy: { sortIndex: 'asc' },
})
let currentSortIndex = firstFile?.sortIndex || undefined
for (const file of files) {
if (file.name.startsWith('.')) continue
const newSortIndex = generateKeyBetween(null, currentSortIndex || null)
currentSortIndex = newSortIndex
const assetType = file.type === 'folder' ? AssetType.folder : AssetType.file
let key: string | null = null
if (assetType === AssetType.file) {
key = `file/${ulid()}/raw`
}
const newAsset = await this.prismaClient.asset.create({
data: {
name: file.name,
type: assetType,
key,
sortIndex: newSortIndex,
mediaType: file.mediaType,
status: AssetStatus.uploading,
sizeByte: file.size,
creatorId: userId,
parentId,
projectId,
taskId,
},
})
if (file.children && file.children.length > 0) {
await this.createAssetsRecursively(
userId,
taskId,
projectId,
newAsset.id,
file.children,
presignedUrls,
)
} else if (assetType === AssetType.file && key) {
const url = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
presignedUrls.push({
id: file.id,
fileId: newAsset.id,
url,
})
}
}
}
async confirmFileUpload(
userId: string,
taskId: string,
req: ConfirmFileUploadRequest,
): Promise<void> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: req.fileId },
include: { project: { include: { team: true } } },
})
if (!asset) throw new Error('Asset not found')
if (!asset.project) throw new Error('Project not found for asset')
if (!asset.key) throw new Error('Asset has no key')
if (req.errorMessage) {
await this.prismaClient.asset.delete({ where: { id: asset.id } })
const t = await this.prismaClient.task.findUnique({ where: { id: taskId } })
if (t) {
const updatedTask = await this.prismaClient.task.update({
where: { id: taskId },
data: { uploaded: { increment: 1 } },
})
if (updatedTask.uploaded === updatedTask.total) {
await this.prismaClient.task.update({
where: { id: taskId },
data: { status: TaskStatus.completed },
})
}
}
return
}
const size = await s3Service.getObjectSize(process.env.S3_BUCKET || 'shumai', asset.key)
const project = asset.project
await this.prismaClient.$transaction(async (tx) => {
// Update asset
const updatedAsset = await tx.asset.update({
where: { id: asset.id },
data: {
status: AssetStatus.uploaded,
sizeByte: size,
},
})
// Update parent and ancestors
if (asset.parentId) {
await tx.asset.update({
where: { id: asset.parentId },
data: { fileCount: { increment: 1 } },
})
// The transaction context is compatible with the asset service's requirements
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await assetService.updateAncestorsSize(tx as any, asset.parentId, updatedAsset.sizeByte)
}
// Update task
const updatedTask = await tx.task.update({
where: { id: taskId },
data: { uploaded: { increment: 1 } },
})
if (updatedTask.uploaded === (updatedTask.total || 0)) {
await tx.task.update({
where: { id: taskId },
data: { status: TaskStatus.completed },
})
}
const team = project.team
if (!team) return
if (!asset.projectId) throw new Error('Asset project ID is missing')
// Ai Tasks
const autofillAgent = await tx.agent.findFirst({
where: {
type: 'autofill',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (autofillAgent) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId: asset.projectId,
payload: { projectId: asset.projectId, agentId: autofillAgent.id },
},
})
}
const transcriptionAgent = await tx.agent.findFirst({
where: {
type: 'transcription',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (transcriptionAgent) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_transcription,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId: asset.projectId,
payload: { projectId: asset.projectId, agentId: transcriptionAgent.id },
},
})
}
// Ai Embedding if enabled via agent
const embeddingAgent = await tx.agent.findFirst({
where: {
type: 'embedding',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (embeddingAgent) {
if (asset.mediaType?.startsWith('video/') || asset.mediaType?.startsWith('image/')) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId: asset.projectId,
payload: { projectId: asset.projectId, agentId: embeddingAgent.id },
},
})
}
}
const isVideo = asset.mediaType?.startsWith('video/')
const isImage = asset.mediaType?.startsWith('image/')
if (!isVideo && !isImage) {
await tx.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
} else {
const settings = team.settings as PrismaJson.Settings | null
if (isVideo) {
const strategy = settings?.transcode?.videoStrategy || 'single'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new VideoTranscoder(tx as any, asset.id, team.id, asset.projectId)
.setStrategy(strategy)
.withSprite()
.withPoster()
.submit()
} else if (isImage) {
const strategy = settings?.transcode?.imageStrategy || 'single'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ImageTranscoder(tx as any, asset.id, team.id, asset.projectId)
.setStrategy(strategy)
.withThumbnail()
.submit()
}
}
})
}
async listUploadTasks(
userId: string,
params: PaginationParams,
): Promise<PaginatedData<TaskInfo[]>> {
const where: Prisma.TaskWhereInput = {
creatorId: userId,
type: 'upload',
}
const { data: tasks, pageInfo } = await paginateQuery(
async (skip, take) => {
return this.prismaClient.task.findMany({
where,
orderBy: { id: 'desc' },
skip,
take,
})
},
async () => this.prismaClient.task.count({ where }),
params,
)
const infos: TaskInfo[] = tasks.map((t) => ({
id: t.id,
name: t.name || '',
total: t.total || 0,
uploaded: t.uploaded,
createdAt: t.createdAt.toISOString(),
}))
return { data: infos, pageInfo }
}
}
export const uploadService = new UploadService()