mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 20:34:28 +00:00
Merge branch 'main' into feat/virtualize-file-list
This commit is contained in:
@@ -559,6 +559,63 @@ describe('AssetService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('fileCount verification', () => {
|
||||
it('createAsset should increment parent fileCount', async () => {
|
||||
const { user, assets, project } = await setupBasicAssets()
|
||||
|
||||
const parent = assets.folderA
|
||||
const initialCount = parent.fileCount // should be 2 from setup (fileA1, fileA2)
|
||||
|
||||
// Create a new folder inside folderA
|
||||
await assetService.createAsset({
|
||||
name: 'newFolder',
|
||||
type: 'folder',
|
||||
parentId: parent.id,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const updatedParent = await prisma.asset.findUnique({ where: { id: parent.id } })
|
||||
expect(updatedParent?.fileCount).toBe(initialCount + 1)
|
||||
|
||||
// Create a new file inside folderA
|
||||
await assetService.createAsset({
|
||||
name: 'newFile',
|
||||
type: 'file',
|
||||
parentId: parent.id,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const updatedParent2 = await prisma.asset.findUnique({ where: { id: parent.id } })
|
||||
expect(updatedParent2?.fileCount).toBe(initialCount + 2)
|
||||
})
|
||||
|
||||
it('reparentAssets should update fileCount when moving folders', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
|
||||
const sourceParent = assets.root
|
||||
const targetParent = assets.folderB
|
||||
const folderToMove = assets.folderA
|
||||
|
||||
// folderA is a child of root.
|
||||
// root children: folderA, folderB, fileRoot1. count=3.
|
||||
// folderB children: stackB, fileB2. count=2.
|
||||
|
||||
await assetService.reparentAssets({
|
||||
assetIds: [folderToMove.id],
|
||||
newParentId: targetParent.id,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const updatedSourceParent = await prisma.asset.findUnique({ where: { id: sourceParent.id } })
|
||||
expect(updatedSourceParent?.fileCount).toBe(2)
|
||||
|
||||
const updatedTargetParent = await prisma.asset.findUnique({ where: { id: targetParent.id } })
|
||||
expect(updatedTargetParent?.fileCount).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
it('handles reparenting - Version Stack: dissolve with 1 remaining', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
await assetService.reparentAssets({
|
||||
|
||||
@@ -172,8 +172,8 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
async reparentAssets(req: ReparentAssetsRequest): Promise<void> {
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
async reparentAssets(req: ReparentAssetsRequest, tx?: Prisma.TransactionClient): Promise<void> {
|
||||
const runInTx = async (tx: Prisma.TransactionClient) => {
|
||||
const newParent = await tx.asset.findUnique({
|
||||
where: { id: req.newParentId },
|
||||
include: { project: { include: { team: true } } },
|
||||
@@ -269,7 +269,13 @@ export class AssetService {
|
||||
if (oldParent) {
|
||||
await this.dissolveStackIfEmpty(tx, oldParent)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (tx) {
|
||||
await runInTx(tx)
|
||||
} else {
|
||||
await this.prismaClient.$transaction(runInTx)
|
||||
}
|
||||
}
|
||||
|
||||
async copyAssets(req: CopyAssetsRequest): Promise<void> {
|
||||
@@ -722,30 +728,41 @@ export class AssetService {
|
||||
if (req.contentType) data.mediaType = req.contentType
|
||||
if (req.creatorId) data.creator = { connect: { id: req.creatorId } }
|
||||
|
||||
const asset = await this.prismaClient.asset.create({
|
||||
data,
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
const asset = await this.prismaClient.$transaction(async (tx) => {
|
||||
const createdAsset = await tx.asset.create({
|
||||
data,
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
target: {
|
||||
include: {
|
||||
creator: true,
|
||||
metadataValues: true,
|
||||
storageKey: true,
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: { creator: true, metadataValues: true, storageKey: true },
|
||||
take: 3,
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (parent) {
|
||||
await tx.asset.update({
|
||||
where: { id: parent.id },
|
||||
data: { fileCount: { increment: 1 } },
|
||||
})
|
||||
}
|
||||
|
||||
return createdAsset
|
||||
})
|
||||
|
||||
const infos = await this.toAssetInfos([asset])
|
||||
@@ -824,6 +841,7 @@ export class AssetService {
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
info.media.original.key,
|
||||
'GET',
|
||||
a.name,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1548,9 +1566,18 @@ export class AssetService {
|
||||
|
||||
const key = latestVersion.storageKey?.key
|
||||
if (media && key) {
|
||||
const fileName =
|
||||
a.type === AssetType.version_stack && (a.name === '' || !a.name)
|
||||
? latestVersion.name
|
||||
: a.name
|
||||
media.original = {
|
||||
key,
|
||||
downloadUrl: await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET'),
|
||||
downloadUrl: await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
fileName,
|
||||
),
|
||||
filesizeInBytes: latestVersion.sizeByte,
|
||||
codec: '', // TODO: extract from metadata if needed
|
||||
}
|
||||
|
||||
@@ -225,6 +225,7 @@ export class ProjectService {
|
||||
name: pm.teamMember.user.name,
|
||||
role: pm.role,
|
||||
image: await getAvatarUrl(pm.teamMember.user.image),
|
||||
scope: pm.teamMember.scope,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,36 +3,41 @@ import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { LocalStorageService, S3StorageService } from './s3'
|
||||
|
||||
// Mock the AWS SDK
|
||||
// Mock Bun S3Client
|
||||
const s3ClientConstructorSpy = vi.fn()
|
||||
vi.mock('@aws-sdk/client-s3', () => {
|
||||
const s3FileSpy = vi.fn()
|
||||
const s3WriteSpy = vi.fn()
|
||||
const s3DeleteSpy = vi.fn()
|
||||
const s3ListSpy = vi.fn()
|
||||
const s3ExistsSpy = vi.fn()
|
||||
const s3PresignSpy = vi.fn()
|
||||
|
||||
vi.mock('bun', () => {
|
||||
return {
|
||||
S3Client: class {
|
||||
constructor(params: unknown) {
|
||||
s3ClientConstructorSpy(params)
|
||||
}
|
||||
send = vi.fn().mockResolvedValue({})
|
||||
file = s3FileSpy.mockReturnValue({
|
||||
size: Promise.resolve(123),
|
||||
exists: vi.fn().mockResolvedValue(true),
|
||||
arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(10)),
|
||||
type: 'text/plain',
|
||||
})
|
||||
write = s3WriteSpy.mockResolvedValue({})
|
||||
delete = s3DeleteSpy.mockResolvedValue({})
|
||||
list = s3ListSpy.mockResolvedValue({ contents: [], isTruncated: false })
|
||||
exists = s3ExistsSpy.mockResolvedValue(true)
|
||||
presign = s3PresignSpy.mockReturnValue('http://presigned-url')
|
||||
},
|
||||
HeadObjectCommand: class {},
|
||||
PutObjectCommand: class {},
|
||||
GetObjectCommand: class {},
|
||||
ListObjectsV2Command: class {},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@aws-sdk/s3-request-presigner', () => {
|
||||
return {
|
||||
getSignedUrl: vi.fn().mockResolvedValue('http://presigned-url'),
|
||||
}
|
||||
})
|
||||
|
||||
describe('S3Service implementations', () => {
|
||||
beforeEach(async () => {
|
||||
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
|
||||
vi.mocked(getSignedUrl).mockReset()
|
||||
vi.mocked(getSignedUrl).mockResolvedValue('http://presigned-url')
|
||||
vi.clearAllMocks()
|
||||
delete process.env.PRESIGNED_URL_EXPIRES_IN
|
||||
s3PresignSpy.mockReturnValue('http://presigned-url')
|
||||
})
|
||||
|
||||
describe('S3StorageService', () => {
|
||||
@@ -64,56 +69,65 @@ describe('S3Service implementations', () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
const url = await s3.presign('bucket', 'key', 'GET')
|
||||
expect(url).toBe('http://presigned-url')
|
||||
expect(s3PresignSpy).toHaveBeenCalledWith('key', expect.objectContaining({ method: 'GET' }))
|
||||
})
|
||||
|
||||
it('should cache GET presign URLs', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
|
||||
|
||||
vi.mocked(getSignedUrl).mockClear()
|
||||
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://presigned-url-1')
|
||||
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://presigned-url-2')
|
||||
s3PresignSpy.mockClear()
|
||||
s3PresignSpy.mockReturnValueOnce('http://presigned-url-1')
|
||||
s3PresignSpy.mockReturnValueOnce('http://presigned-url-2')
|
||||
|
||||
const url1 = await s3.presign('bucket', 'key', 'GET')
|
||||
const url2 = await s3.presign('bucket', 'key', 'GET')
|
||||
|
||||
expect(url1).toBe('http://presigned-url-1')
|
||||
expect(url2).toBe('http://presigned-url-1')
|
||||
expect(vi.mocked(getSignedUrl)).toHaveBeenCalledTimes(1)
|
||||
expect(s3PresignSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should NOT cache PUT presign URLs', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
|
||||
|
||||
vi.mocked(getSignedUrl).mockClear()
|
||||
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://put-url-1')
|
||||
vi.mocked(getSignedUrl).mockResolvedValueOnce('http://put-url-2')
|
||||
s3PresignSpy.mockReset()
|
||||
s3PresignSpy.mockReturnValueOnce('http://unique-put-url-1')
|
||||
s3PresignSpy.mockReturnValueOnce('http://unique-put-url-2')
|
||||
|
||||
const url1 = await s3.presign('bucket', 'key', 'PUT')
|
||||
const url2 = await s3.presign('bucket', 'key', 'PUT')
|
||||
|
||||
expect(url1).toBe('http://put-url-1')
|
||||
expect(url2).toBe('http://put-url-2')
|
||||
expect(vi.mocked(getSignedUrl)).toHaveBeenCalledTimes(2)
|
||||
expect(url1).toBe('http://unique-put-url-1')
|
||||
expect(url2).toBe('http://unique-put-url-2')
|
||||
expect(s3PresignSpy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should respect PRESIGNED_URL_EXPIRES_IN env', async () => {
|
||||
process.env.PRESIGNED_URL_EXPIRES_IN = '10'
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner')
|
||||
|
||||
vi.mocked(getSignedUrl).mockClear()
|
||||
s3PresignSpy.mockClear()
|
||||
await s3.presign('bucket', 'key', 'GET')
|
||||
|
||||
expect(vi.mocked(getSignedUrl)).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
expect(s3PresignSpy).toHaveBeenCalledWith(
|
||||
'key',
|
||||
expect.objectContaining({ expiresIn: 10 * 3600 }),
|
||||
)
|
||||
|
||||
delete process.env.PRESIGNED_URL_EXPIRES_IN
|
||||
})
|
||||
|
||||
it('should pass filename to presign', async () => {
|
||||
const s3 = new S3StorageService('localhost:9000', 'key', 'secret', 'test-bucket', false)
|
||||
await s3.presign('bucket', 'key', 'GET', 'test.txt')
|
||||
|
||||
expect(s3PresignSpy).toHaveBeenCalledWith(
|
||||
'key',
|
||||
expect.objectContaining({
|
||||
contentDisposition: 'attachment; filename="test.txt"',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('LocalStorageService', () => {
|
||||
@@ -168,6 +182,11 @@ describe('S3Service implementations', () => {
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt')
|
||||
})
|
||||
|
||||
it('should generate a local presign URL with filename', async () => {
|
||||
const url = await localS3.presign('my-bucket', 'dir/file.txt', 'GET', 'original.txt')
|
||||
expect(url).toBe('http://localhost:3000/files/my-bucket/dir/file.txt?filename=original.txt')
|
||||
})
|
||||
|
||||
it('should throw an error for unsupported presign methods', async () => {
|
||||
await expect(localS3.presign('b', 'k', 'POST')).rejects.toThrow()
|
||||
})
|
||||
|
||||
+64
-130
@@ -1,17 +1,7 @@
|
||||
import { ObjectInfo } from '@shumai/dtos'
|
||||
import {
|
||||
CopyObjectCommand,
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
HeadObjectCommand,
|
||||
ListObjectsV2Command,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3'
|
||||
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
|
||||
import { S3Client } from 'bun'
|
||||
import * as crypto from 'crypto'
|
||||
import * as fs from 'fs'
|
||||
import { readFileSync, statSync } from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
import { LruTtlCache } from '../cache/lru-ttl-cache'
|
||||
@@ -64,7 +54,7 @@ export interface S3Service {
|
||||
listObjects(bucket: string, prefix: string): Promise<string[]>
|
||||
uploadFile(filePath: string, contentType: string): Promise<string>
|
||||
uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void>
|
||||
presign(bucket: string, key: string, method: string): Promise<string>
|
||||
presign(bucket: string, key: string, method: string, filename?: string): Promise<string>
|
||||
}
|
||||
|
||||
export class S3StorageService implements S3Service {
|
||||
@@ -89,54 +79,36 @@ export class S3StorageService implements S3Service {
|
||||
this.client = new S3Client({
|
||||
region,
|
||||
endpoint: fullEndpoint,
|
||||
credentials: {
|
||||
accessKeyId,
|
||||
secretAccessKey,
|
||||
},
|
||||
forcePathStyle: false,
|
||||
accessKeyId,
|
||||
secretAccessKey,
|
||||
bucket,
|
||||
})
|
||||
this.bucket = bucket
|
||||
}
|
||||
|
||||
async getObjectSize(bucket: string, key: string): Promise<number> {
|
||||
const command = new HeadObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
const response = await this.client.send(command)
|
||||
return response.ContentLength || 0
|
||||
return await this.client.size(key, { bucket })
|
||||
}
|
||||
|
||||
async putObject(
|
||||
bucket: string,
|
||||
key: string,
|
||||
body: Buffer | Uint8Array | string,
|
||||
size: number,
|
||||
_size: number,
|
||||
contentType?: string,
|
||||
): Promise<void> {
|
||||
const command = new PutObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
Body: body,
|
||||
ContentLength: size,
|
||||
ContentType: contentType,
|
||||
await this.client.write(key, body, {
|
||||
bucket,
|
||||
type: contentType,
|
||||
})
|
||||
await this.client.send(command)
|
||||
}
|
||||
|
||||
async getObject(bucket: string, key: string): Promise<S3Object> {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
const response = await this.client.send(command)
|
||||
if (!response.Body) {
|
||||
throw new Error('Empty response body')
|
||||
}
|
||||
const byteArray = await response.Body.transformToByteArray()
|
||||
const file = this.client.file(key, { bucket })
|
||||
const arrayBuffer = await file.arrayBuffer()
|
||||
return {
|
||||
buffer: Buffer.from(byteArray),
|
||||
contentType: response.ContentType || 'application/octet-stream',
|
||||
buffer: Buffer.from(arrayBuffer),
|
||||
contentType: file.type || 'application/octet-stream',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,54 +118,22 @@ export class S3StorageService implements S3Service {
|
||||
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)
|
||||
const sourceFile = this.client.file(sourceKey, { bucket: sourceBucket })
|
||||
await this.client.write(destKey, sourceFile, { bucket: destBucket })
|
||||
}
|
||||
|
||||
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
const response = await this.client.send(command)
|
||||
if (!response.Body) {
|
||||
throw new Error('Empty response body')
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const stream = response.Body as any
|
||||
const writeStream = fs.createWriteStream(filePath)
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
stream
|
||||
.pipe(writeStream)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
.on('error', (err: any) => {
|
||||
writeStream.close()
|
||||
reject(err)
|
||||
})
|
||||
.on('finish', () => {
|
||||
writeStream.close()
|
||||
resolve(null)
|
||||
})
|
||||
})
|
||||
const file = this.client.file(key, { bucket })
|
||||
await Bun.write(filePath, file)
|
||||
}
|
||||
|
||||
async deleteObject(bucket: string, key: string): Promise<number> {
|
||||
const command = new DeleteObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
try {
|
||||
await this.client.send(command)
|
||||
const exists = await this.client.exists(key, { bucket })
|
||||
if (!exists) return 0
|
||||
await this.client.delete(key, { bucket })
|
||||
return 1
|
||||
} catch {
|
||||
// If object doesn't exist, we return 0
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -207,17 +147,20 @@ export class S3StorageService implements S3Service {
|
||||
}
|
||||
|
||||
async headObject(bucket: string, key: string): Promise<ObjectInfo> {
|
||||
const command = new HeadObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
const response = await this.client.send(command)
|
||||
const file = this.client.file(key, { bucket })
|
||||
const exists = await file.exists()
|
||||
if (!exists) {
|
||||
throw new Error(`NoSuchKey: The specified key does not exist.`)
|
||||
}
|
||||
|
||||
// Bun.S3File doesn't expose lastModified or eTag directly in a way that matches ObjectInfo easily
|
||||
// but we can try to get them if available. For now, using defaults for fields not provided.
|
||||
return {
|
||||
key,
|
||||
size: response.ContentLength || 0,
|
||||
lastModified: response.LastModified || new Date(),
|
||||
contentType: response.ContentType || 'application/octet-stream',
|
||||
eTag: response.ETag || '',
|
||||
size: await file.size,
|
||||
lastModified: new Date(), // Bun doesn't expose this yet via S3File
|
||||
contentType: file.type || 'application/octet-stream',
|
||||
eTag: '',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,23 +170,21 @@ export class S3StorageService implements S3Service {
|
||||
let continuationToken: string | undefined = undefined
|
||||
|
||||
while (isTruncated) {
|
||||
const command: ListObjectsV2Command = new ListObjectsV2Command({
|
||||
Bucket: bucket,
|
||||
Prefix: prefix,
|
||||
ContinuationToken: continuationToken,
|
||||
const response = await this.client.list({
|
||||
prefix,
|
||||
continuationToken,
|
||||
})
|
||||
const response = await this.client.send(command)
|
||||
|
||||
if (response.Contents) {
|
||||
for (const item of response.Contents) {
|
||||
if (item.Key) {
|
||||
keys.push(item.Key)
|
||||
if (response.contents) {
|
||||
for (const item of response.contents) {
|
||||
if (item.key) {
|
||||
keys.push(item.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isTruncated = response.IsTruncated || false
|
||||
continuationToken = response.NextContinuationToken
|
||||
isTruncated = response.isTruncated || false
|
||||
continuationToken = response.nextContinuationToken
|
||||
}
|
||||
|
||||
return keys
|
||||
@@ -256,50 +197,39 @@ export class S3StorageService implements S3Service {
|
||||
}
|
||||
|
||||
async uploadFileToKey(filePath: string, key: string, contentType: string): Promise<void> {
|
||||
const fileStats = statSync(filePath)
|
||||
const fileContent = readFileSync(filePath)
|
||||
|
||||
const command = new PutObjectCommand({
|
||||
Bucket: this.bucket,
|
||||
Key: key,
|
||||
Body: fileContent,
|
||||
ContentLength: fileStats.size,
|
||||
ContentType: contentType,
|
||||
await this.client.write(key, Bun.file(filePath), {
|
||||
bucket: this.bucket,
|
||||
type: contentType,
|
||||
})
|
||||
|
||||
await this.client.send(command)
|
||||
}
|
||||
|
||||
async presign(bucket: string, key: string, method: string): Promise<string> {
|
||||
async presign(bucket: string, key: string, method: string, filename?: string): Promise<string> {
|
||||
const expireHours = parseInt(process.env.PRESIGNED_URL_EXPIRES_IN || '5', 10)
|
||||
const expiresInSeconds = expireHours * 3600
|
||||
// Cache time is 2/3 of expire time, rounded to minute
|
||||
const cacheMinutes = Math.round((expireHours * 60 * 2) / 3)
|
||||
const cacheTtlMs = cacheMinutes * 60 * 1000
|
||||
|
||||
const cacheKey = `${bucket}:${key}`
|
||||
const cacheKey = `${bucket}:${key}:${filename || ''}`
|
||||
|
||||
if (method === 'GET') {
|
||||
const cached = this.presignCache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
}
|
||||
|
||||
let command: GetObjectCommand | PutObjectCommand
|
||||
if (method === 'GET') {
|
||||
command = new GetObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
} else if (method === 'PUT') {
|
||||
command = new PutObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
})
|
||||
} else {
|
||||
throw new Error(`Invalid method: ${method}`)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const options: any = {
|
||||
bucket,
|
||||
expiresIn: expiresInSeconds,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
method: method as any,
|
||||
}
|
||||
|
||||
const url = await getSignedUrl(this.client, command, { expiresIn: expiresInSeconds })
|
||||
if (filename) {
|
||||
options.contentDisposition = `attachment; filename="${filename}"`
|
||||
}
|
||||
|
||||
const url = this.client.presign(key, options)
|
||||
|
||||
if (method === 'GET') {
|
||||
this.presignCache.set(cacheKey, url, cacheTtlMs)
|
||||
@@ -505,14 +435,18 @@ export class LocalStorageService implements S3Service {
|
||||
await fs.promises.copyFile(filePath, destPath)
|
||||
}
|
||||
|
||||
async presign(bucket: string, key: string, method: string): Promise<string> {
|
||||
async presign(bucket: string, key: string, method: string, filename?: string): Promise<string> {
|
||||
if (method !== 'GET' && method !== 'PUT') {
|
||||
throw new Error(`Invalid method: ${method}`)
|
||||
}
|
||||
if (method === 'PUT') {
|
||||
return `${this.endpoint}${signLocalUrl(bucket, key)}`
|
||||
}
|
||||
return `${this.endpoint}/files/${bucket}/${key}`
|
||||
let url = `${this.endpoint}/files/${bucket}/${key}`
|
||||
if (filename) {
|
||||
url += `?filename=${encodeURIComponent(filename)}`
|
||||
}
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -127,6 +127,7 @@ describe('TeamService', () => {
|
||||
|
||||
const members = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: user1.id,
|
||||
})
|
||||
|
||||
expect(members).toHaveLength(2)
|
||||
@@ -169,6 +170,7 @@ describe('TeamService', () => {
|
||||
// Should hide bots by default
|
||||
const members = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
})
|
||||
expect(members).toHaveLength(1)
|
||||
expect(members[0].id).toBe(user.id)
|
||||
@@ -176,11 +178,73 @@ describe('TeamService', () => {
|
||||
// Should include bots if requested
|
||||
const allMembers = await teamService.getTeamMembers({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
includeAgents: true,
|
||||
})
|
||||
expect(allMembers).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('should filter members for project-scoped members', async () => {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: `owner-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'Test Team' })
|
||||
|
||||
const teamMember = await prisma.user.create({
|
||||
data: { name: 'Team Member', email: `tm-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await teamService.joinTeam({ teamId: team.id, userId: teamMember.id })
|
||||
|
||||
const projectMember1 = await prisma.user.create({
|
||||
data: { name: 'Proj Member 1', email: `pm1-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
const tm1 = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: projectMember1.id, scope: 'project', role: 'editor' },
|
||||
})
|
||||
|
||||
const projectMember2 = await prisma.user.create({
|
||||
data: { name: 'Proj Member 2', email: `pm2-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
const tm2 = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: projectMember2.id, scope: 'project', role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Shared Project', teamId: team.id },
|
||||
})
|
||||
|
||||
await prisma.projectMember.createMany({
|
||||
data: [
|
||||
{ projectId: project.id, teamMemberId: tm1.id, role: 'editor' },
|
||||
{ projectId: project.id, teamMemberId: tm2.id, role: 'editor' },
|
||||
],
|
||||
})
|
||||
|
||||
const projectMember3 = await prisma.user.create({
|
||||
data: { name: 'Proj Member 3', email: `pm3-${Date.now()}@example.com`, password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: projectMember3.id, scope: 'project', role: 'editor' },
|
||||
})
|
||||
|
||||
// Owner (team scope) should see everyone (4 users)
|
||||
const ownerView = await teamService.getTeamMembers({ teamId: team.id, userId: owner.id })
|
||||
expect(ownerView).toHaveLength(5) // Owner, Team Member, PM1, PM2, PM3
|
||||
|
||||
// PM1 (project scope) should see: Owner, Team Member, PM2 (shares project), but NOT PM3
|
||||
const pm1View = await teamService.getTeamMembers({ teamId: team.id, userId: projectMember1.id })
|
||||
const pm1ViewIds = pm1View.map((m) => m.id)
|
||||
expect(pm1View).toHaveLength(4)
|
||||
expect(pm1ViewIds).toContain(owner.id)
|
||||
expect(pm1ViewIds).toContain(teamMember.id)
|
||||
expect(pm1ViewIds).toContain(projectMember2.id)
|
||||
expect(pm1ViewIds).not.toContain(projectMember3.id)
|
||||
|
||||
// Check scopes are returned
|
||||
expect(pm1View.find((m) => m.id === owner.id)?.scope).toBe('team')
|
||||
expect(pm1View.find((m) => m.id === projectMember2.id)?.scope).toBe('project')
|
||||
})
|
||||
|
||||
it('should get and update settings', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User', email: `test-${Date.now()}@example.com`, password: 'pw' },
|
||||
|
||||
@@ -174,6 +174,19 @@ export class TeamService {
|
||||
}
|
||||
|
||||
async getTeamMembers(req: ServiceGetTeamMembersRequest): Promise<UserInfo[]> {
|
||||
const requester = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: req.teamId,
|
||||
userId: req.userId,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!requester) {
|
||||
throw new HTTPException(403, { message: 'Requester is not a team member' })
|
||||
}
|
||||
|
||||
const members = await prisma.teamMember.findMany({
|
||||
where: {
|
||||
teamId: req.teamId,
|
||||
@@ -194,17 +207,39 @@ export class TeamService {
|
||||
}
|
||||
: { user: { type: { not: 'agent' } } }),
|
||||
},
|
||||
include: { user: true },
|
||||
include: {
|
||||
user: true,
|
||||
projectMembers: true,
|
||||
},
|
||||
})
|
||||
|
||||
let filteredMembers = members
|
||||
|
||||
if (requester.scope === 'project') {
|
||||
const requesterProjectIds = await prisma.projectMember
|
||||
.findMany({
|
||||
where: { teamMemberId: requester.id },
|
||||
select: { projectId: true },
|
||||
})
|
||||
.then((pms) => pms.map((pm) => pm.projectId))
|
||||
|
||||
filteredMembers = members.filter((m) => {
|
||||
// Team-scoped members are always visible
|
||||
if (m.scope === 'team') return true
|
||||
// Project-scoped members are visible if they share a project
|
||||
return m.projectMembers.some((pm) => requesterProjectIds.includes(pm.projectId))
|
||||
})
|
||||
}
|
||||
|
||||
return Promise.all(
|
||||
members.map(async (m) => ({
|
||||
filteredMembers.map(async (m) => ({
|
||||
id: m.user.id,
|
||||
name: m.user.name,
|
||||
email: undefined,
|
||||
role: m.role,
|
||||
type: m.user.type || undefined,
|
||||
image: await getAvatarUrl(m.user.image),
|
||||
scope: m.scope,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -93,6 +93,67 @@ describe('UploadService', () => {
|
||||
expect(hidden).toBeNull()
|
||||
})
|
||||
|
||||
it('should correctly increment fileCount for parent folders when uploading folders', async () => {
|
||||
const req = {
|
||||
parentId: parentId,
|
||||
files: [
|
||||
{
|
||||
name: 'folder1',
|
||||
id: '1',
|
||||
type: 'folder' as const,
|
||||
size: 0,
|
||||
children: [
|
||||
{
|
||||
name: 'folder2',
|
||||
id: '2',
|
||||
type: 'folder' as const,
|
||||
size: 0,
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
name: 'file1.txt',
|
||||
id: '3',
|
||||
type: 'file' as const,
|
||||
size: 100,
|
||||
mediaType: 'text/plain',
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
await uploadService.createUploadTask(userId, req)
|
||||
|
||||
// parentId folder should have folder1 as a direct child
|
||||
const parent = await prisma.asset.findUnique({ where: { id: parentId } })
|
||||
expect(parent?.fileCount).toBe(1)
|
||||
|
||||
// folder1 should have folder2 and file1.txt as direct children
|
||||
// folder2 is a folder, so it is counted immediately.
|
||||
// file1.txt is a file, so it is counted after confirmFileUpload.
|
||||
const folder1 = await prisma.asset.findFirst({ where: { name: 'folder1' } })
|
||||
expect(folder1?.parentId).toBe(parentId)
|
||||
expect(folder1?.fileCount).toBe(1)
|
||||
|
||||
const folder2 = await prisma.asset.findFirst({ where: { name: 'folder2' } })
|
||||
expect(folder2?.parentId).toBe(folder1?.id)
|
||||
expect(folder2?.fileCount).toBe(0)
|
||||
|
||||
const file1 = await prisma.asset.findFirst({ where: { name: 'file1.txt' } })
|
||||
expect(file1?.parentId).toBe(folder1?.id)
|
||||
expect(file1?.status).toBe(AssetStatus.uploading)
|
||||
|
||||
// Confirm upload for file1.txt
|
||||
const task = await prisma.task.findFirst({ where: { total: 1 } })
|
||||
await uploadService.confirmFileUpload(userId, task!.id, {
|
||||
fileId: file1!.id,
|
||||
})
|
||||
|
||||
const folder1After = await prisma.asset.findUnique({ where: { id: folder1!.id } })
|
||||
expect(folder1After?.fileCount).toBe(2)
|
||||
})
|
||||
|
||||
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' },
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { ulid } from 'ulid'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { PaginatedData, PaginationParams, paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
AssetStatus,
|
||||
AssetType,
|
||||
Prisma,
|
||||
TaskStatus,
|
||||
WorkflowTaskStatus,
|
||||
WorkflowTaskType,
|
||||
prisma,
|
||||
} from '@shumai/db'
|
||||
import {
|
||||
ConfirmFileUploadRequest,
|
||||
CreateUploadTaskRequest,
|
||||
@@ -11,16 +18,9 @@ import {
|
||||
PresignedUrl,
|
||||
TaskInfo,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
AssetStatus,
|
||||
AssetType,
|
||||
Prisma,
|
||||
TaskStatus,
|
||||
WorkflowTaskStatus,
|
||||
WorkflowTaskType,
|
||||
} from '@shumai/db'
|
||||
import { PaginationParams, paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
|
||||
import { VideoTranscoder, ImageTranscoder } from '@shumai/transcode'
|
||||
import { ImageTranscoder, VideoTranscoder } from '@shumai/transcode'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
export class UploadService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
@@ -67,24 +67,32 @@ export class UploadService {
|
||||
const isParentFile = parentAsset.type === AssetType.file
|
||||
const targetParentId = isParentFile ? parentAsset.parentId! : parentAsset.id
|
||||
|
||||
const createdAssetIds = await this.createAssetsRecursively(
|
||||
userId,
|
||||
task.id,
|
||||
parentAsset.projectId,
|
||||
targetParentId,
|
||||
req.files,
|
||||
presignedUrls,
|
||||
)
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const ids = await this.createAssetsRecursively(
|
||||
tx,
|
||||
userId,
|
||||
task.id,
|
||||
parentAsset.projectId!,
|
||||
targetParentId,
|
||||
req.files,
|
||||
presignedUrls,
|
||||
)
|
||||
|
||||
if (isParentFile && createdAssetIds.length > 0) {
|
||||
for (const assetId of createdAssetIds) {
|
||||
await assetService.reparentAssets({
|
||||
assetIds: [assetId],
|
||||
newParentId: parentAsset.id,
|
||||
creatorId: userId,
|
||||
})
|
||||
if (isParentFile && ids.length > 0) {
|
||||
for (const assetId of ids) {
|
||||
await assetService.reparentAssets(
|
||||
{
|
||||
assetIds: [assetId],
|
||||
newParentId: parentAsset.id,
|
||||
creatorId: userId,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ids
|
||||
})
|
||||
|
||||
return {
|
||||
taskId: task.id,
|
||||
@@ -93,6 +101,7 @@ export class UploadService {
|
||||
}
|
||||
|
||||
private async createAssetsRecursively(
|
||||
tx: Prisma.TransactionClient,
|
||||
userId: string,
|
||||
taskId: string,
|
||||
projectId: string,
|
||||
@@ -100,7 +109,7 @@ export class UploadService {
|
||||
files: FileNode[],
|
||||
presignedUrls: PresignedUrl[],
|
||||
): Promise<string[]> {
|
||||
const firstFile = await this.prismaClient.asset.findFirst({
|
||||
const firstFile = await tx.asset.findFirst({
|
||||
where: { parentId },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
@@ -119,14 +128,14 @@ export class UploadService {
|
||||
key = `files/${ulid()}/raw`
|
||||
}
|
||||
|
||||
const newAsset = await this.prismaClient.asset.create({
|
||||
const newAsset = await tx.asset.create({
|
||||
data: {
|
||||
name: file.name,
|
||||
type: assetType,
|
||||
storageKey: key ? { create: { key } } : undefined,
|
||||
sortIndex: newSortIndex,
|
||||
mediaType: file.mediaType,
|
||||
status: AssetStatus.uploading,
|
||||
status: assetType === AssetType.folder ? AssetStatus.uploaded : AssetStatus.uploading,
|
||||
sizeByte: file.size,
|
||||
creator: userId ? { connect: { id: userId } } : undefined,
|
||||
parent: parentId ? { connect: { id: parentId } } : undefined,
|
||||
@@ -136,8 +145,16 @@ export class UploadService {
|
||||
})
|
||||
createdIds.push(newAsset.id)
|
||||
|
||||
if (assetType === AssetType.folder && parentId) {
|
||||
await tx.asset.update({
|
||||
where: { id: parentId },
|
||||
data: { fileCount: { increment: 1 } },
|
||||
})
|
||||
}
|
||||
|
||||
if (file.children && file.children.length > 0) {
|
||||
await this.createAssetsRecursively(
|
||||
tx,
|
||||
userId,
|
||||
taskId,
|
||||
projectId,
|
||||
@@ -212,9 +229,8 @@ export class UploadService {
|
||||
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)
|
||||
|
||||
await assetService.updateAncestorsSize(tx, asset.parentId, updatedAsset.sizeByte)
|
||||
}
|
||||
|
||||
// Update task
|
||||
|
||||
Reference in New Issue
Block a user