mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(transcode): add 3D asset support and turntable viewer
This commit is contained in:
@@ -1931,6 +1931,36 @@ describe('AssetService', () => {
|
||||
expect(info.preview?.duration).toBeUndefined()
|
||||
})
|
||||
|
||||
it('toPreviewInfo handles 3d asset with proxyType 3d and omits duration', async () => {
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
const model = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'model.glb',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
sizeByte: 8000,
|
||||
mediaType: 'model/gltf-binary',
|
||||
status: 'processed',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
poster: { key: 'poster-key' },
|
||||
sprite: { key: 'sprite-key', frames: 100, tileX: 10, tileY: 10 },
|
||||
metadata: { originalWidth: 1080, originalHeight: 1080, duration: 4 },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const info = await assetService.getAsset({ assetId: model.id })
|
||||
|
||||
expect(info.preview).toBeDefined()
|
||||
expect(info.preview?.proxyType).toBe('3d')
|
||||
expect(info.preview?.duration).toBeUndefined()
|
||||
expect(info.preview?.spriteUrl).toBeDefined()
|
||||
})
|
||||
|
||||
it('converts webp thumbnail to jpeg on demand when hasJpegPreview is false', async () => {
|
||||
vi.mocked(ensureJpegInStorage).mockClear()
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
@@ -2407,7 +2407,13 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
const proxyType = (media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
const proxyType = (media?.proxyType || null) as
|
||||
| 'image'
|
||||
| 'video'
|
||||
| 'audio'
|
||||
| 'pdf'
|
||||
| '3d'
|
||||
| null
|
||||
|
||||
result.push({
|
||||
id: a.id,
|
||||
@@ -2773,7 +2779,13 @@ export class AssetService {
|
||||
): Promise<PreviewInfo | null> {
|
||||
if (!asset.media) return null
|
||||
|
||||
const proxyType = (asset.media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
const proxyType = (asset.media?.proxyType || null) as
|
||||
| 'image'
|
||||
| 'video'
|
||||
| 'audio'
|
||||
| 'pdf'
|
||||
| '3d'
|
||||
| null
|
||||
|
||||
let rawThumbKey: string | undefined
|
||||
if (proxyType === 'image' && asset.media.thumbnail?.key) {
|
||||
@@ -2826,7 +2838,7 @@ export class AssetService {
|
||||
originalHeight: asset.media.metadata?.originalHeight,
|
||||
originalWidth: asset.media.metadata?.originalWidth,
|
||||
spriteUrl,
|
||||
duration: asset.media.metadata?.duration,
|
||||
duration: proxyType === '3d' ? undefined : asset.media.metadata?.duration,
|
||||
pageCount: asset.media.metadata?.totalFrames,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,3 +31,4 @@ export * from './kanban/kanban'
|
||||
export * from './media-generation/media-generation'
|
||||
export * from './sandbox'
|
||||
export * from './asset/comments-export'
|
||||
export * from './turntable/turntable'
|
||||
|
||||
@@ -375,6 +375,12 @@ describe('TeamService', () => {
|
||||
hlsEnabled: false,
|
||||
hlsResolutions: ['480p', '720p', '1080p'],
|
||||
},
|
||||
turntable: {
|
||||
hasPassword: false,
|
||||
isEnvConfigured: false,
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
|
||||
@@ -392,6 +398,12 @@ describe('TeamService', () => {
|
||||
hlsEnabled: false,
|
||||
hlsResolutions: ['480p', '720p', '1080p'],
|
||||
},
|
||||
turntable: {
|
||||
hasPassword: false,
|
||||
isEnvConfigured: false,
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
|
||||
@@ -418,6 +430,12 @@ describe('TeamService', () => {
|
||||
hlsEnabled: true,
|
||||
hlsResolutions: ['720p', '1080p', '2160p'],
|
||||
},
|
||||
turntable: {
|
||||
hasPassword: false,
|
||||
isEnvConfigured: false,
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: true },
|
||||
semanticSearchEnabled: false,
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
|
||||
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import {
|
||||
ServiceCreateTeamRequest,
|
||||
ServiceGetUserTeamsRequest,
|
||||
@@ -343,6 +344,8 @@ export class TeamService {
|
||||
settings.appearance.hideAgent = false
|
||||
}
|
||||
|
||||
settings.turntable = await turntableService.getSettings(teamId)
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
|
||||
@@ -3118,6 +3118,45 @@ export class TranscodeService {
|
||||
.webp({ quality: 90 })
|
||||
.toFile(outputPath)
|
||||
}
|
||||
|
||||
async convertImageToWebp(imageBuffer: Buffer, quality = 85): Promise<Buffer> {
|
||||
return await sharp(imageBuffer, { limitInputPixels: false })
|
||||
.toColorspace('srgb')
|
||||
.webp({ quality })
|
||||
.toBuffer()
|
||||
}
|
||||
|
||||
async generate3dSprite(
|
||||
inputFile: string,
|
||||
outputSprite: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
if (signal?.aborted) {
|
||||
throw new Error('Sprite generation cancelled')
|
||||
}
|
||||
const spriteFps = 100 / 4
|
||||
const filterComplex = `[0:v]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out]`
|
||||
const args = [
|
||||
'-i',
|
||||
inputFile,
|
||||
'-filter_complex',
|
||||
filterComplex,
|
||||
'-map',
|
||||
'[sprite_out]',
|
||||
'-frames:v',
|
||||
'1',
|
||||
'-c:v',
|
||||
'libwebp',
|
||||
'-q:v',
|
||||
'75',
|
||||
outputSprite,
|
||||
]
|
||||
if (signal) {
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal })
|
||||
} else {
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderAnnotationsToSvg(
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as os from 'os'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { TurntableService } from './turntable'
|
||||
|
||||
describe('TurntableService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const originalEnv = process.env
|
||||
let tmpDir: string
|
||||
let testFilePath: string
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...originalEnv }
|
||||
delete process.env.TURNTABLE_RENDERER_URL
|
||||
delete process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME
|
||||
delete process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD
|
||||
delete process.env.TURNTABLE_RENDERER_USERNAME
|
||||
delete process.env.TURNTABLE_RENDERER_PASSWORD
|
||||
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'turntable-test-'))
|
||||
testFilePath = path.join(tmpDir, 'model.glb')
|
||||
fs.writeFileSync(testFilePath, 'fake glb content')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('resolveConfig', () => {
|
||||
it('returns isEnv: false when neither env nor team settings are present', async () => {
|
||||
const service = new TurntableService()
|
||||
const config = await service.resolveConfig()
|
||||
expect(config.url).toBeUndefined()
|
||||
expect(config.isEnv).toBe(false)
|
||||
})
|
||||
|
||||
it('resolves env configuration with highest priority', async () => {
|
||||
process.env.TURNTABLE_RENDERER_URL = 'http://localhost:3000/'
|
||||
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME = 'admin'
|
||||
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD = 'secret'
|
||||
|
||||
const service = new TurntableService()
|
||||
const config = await service.resolveConfig('any-team-id')
|
||||
|
||||
expect(config.url).toBe('http://localhost:3000')
|
||||
expect(config.username).toBe('admin')
|
||||
expect(config.password).toBe('secret')
|
||||
expect(config.isEnv).toBe(true)
|
||||
})
|
||||
|
||||
it('falls back to team DB settings when env is not set', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team 3D',
|
||||
settings: {
|
||||
turntable: {
|
||||
url: 'http://custom-turntable:4000',
|
||||
username: 'teamUser',
|
||||
password: 'teamPassword',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const service = new TurntableService()
|
||||
const config = await service.resolveConfig(team.id)
|
||||
|
||||
expect(config.url).toBe('http://custom-turntable:4000')
|
||||
expect(config.username).toBe('teamUser')
|
||||
expect(config.password).toBe('teamPassword')
|
||||
expect(config.isEnv).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isAvailable', () => {
|
||||
it('returns false if URL is not configured', async () => {
|
||||
const service = new TurntableService()
|
||||
expect(await service.isAvailable()).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when health check returns 200', async () => {
|
||||
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
} as Response)
|
||||
|
||||
const service = new TurntableService()
|
||||
expect(await service.isAvailable()).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when health check fails or throws', async () => {
|
||||
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
|
||||
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Connection refused'))
|
||||
|
||||
const service = new TurntableService()
|
||||
expect(await service.isAvailable()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('testConnection', () => {
|
||||
it('returns error when url is empty', async () => {
|
||||
const service = new TurntableService()
|
||||
const result = await service.testConnection({})
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toBe('URL is required')
|
||||
})
|
||||
|
||||
it('returns version information upon successful connection', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ version: '0.1.0', blender: '5.2.2' }),
|
||||
} as Response)
|
||||
|
||||
const service = new TurntableService()
|
||||
const result = await service.testConnection({ url: 'http://localhost:3000' })
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.version).toBe('0.1.0')
|
||||
expect(result.blender).toBe('5.2.2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('uploadFile', () => {
|
||||
it('posts file buffer to /v1/files and returns file info', async () => {
|
||||
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 201,
|
||||
json: async () => ({ id: 'f_test123', name: 'model.glb', size: 100 }),
|
||||
} as Response)
|
||||
|
||||
const service = new TurntableService()
|
||||
const res = await service.uploadFile(testFilePath, 'model.glb')
|
||||
|
||||
expect(res.id).toBe('f_test123')
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'http://turntable:3000/v1/files',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('startRender & getTaskStatus & downloadFile & deleteTask', () => {
|
||||
beforeEach(() => {
|
||||
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
|
||||
})
|
||||
|
||||
it('startRender calls /v1/render and returns sync response', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
taskId: 't_test456',
|
||||
status: 'queued',
|
||||
poster: {
|
||||
fileId: 'f_poster',
|
||||
size: 200,
|
||||
contentType: 'image/png',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
},
|
||||
}),
|
||||
} as Response)
|
||||
|
||||
const service = new TurntableService()
|
||||
const res = await service.startRender('f_input')
|
||||
expect(res.taskId).toBe('t_test456')
|
||||
expect(res.poster.fileId).toBe('f_poster')
|
||||
})
|
||||
|
||||
it('getTaskStatus queries /v1/render/tasks/:id', async () => {
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
taskId: 't_test456',
|
||||
status: 'completed',
|
||||
video: {
|
||||
fileId: 'f_video',
|
||||
size: 1000,
|
||||
contentType: 'video/mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
},
|
||||
}),
|
||||
} as Response)
|
||||
|
||||
const service = new TurntableService()
|
||||
const res = await service.getTaskStatus('t_test456')
|
||||
expect(res.status).toBe('completed')
|
||||
expect(res.video?.fileId).toBe('f_video')
|
||||
})
|
||||
|
||||
it('downloadFile fetches /v1/files/:id and writes to destination', async () => {
|
||||
const destPath = path.join(tmpDir, 'downloaded.mp4')
|
||||
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
arrayBuffer: async () => Buffer.from('video data').buffer,
|
||||
} as Response)
|
||||
|
||||
const service = new TurntableService()
|
||||
await service.downloadFile('f_video', destPath)
|
||||
|
||||
expect(fs.existsSync(destPath)).toBe(true)
|
||||
expect(fs.readFileSync(destPath, 'utf8')).toBe('video data')
|
||||
})
|
||||
|
||||
it('deleteTask calls DELETE /v1/render/tasks/:id and returns boolean', async () => {
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
} as Response)
|
||||
|
||||
const service = new TurntableService()
|
||||
const deleted = await service.deleteTask('t_test456')
|
||||
|
||||
expect(deleted).toBe(true)
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'http://turntable:3000/v1/render/tasks/t_test456',
|
||||
expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,438 @@
|
||||
import * as fs from 'fs'
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { TurntableSettingsResponse, UpdateTurntableSettingsRequest } from '@shumai/dtos'
|
||||
import { logger } from '../logger'
|
||||
|
||||
export interface TurntableConfig {
|
||||
url?: string
|
||||
username?: string
|
||||
password?: string
|
||||
isEnv: boolean
|
||||
}
|
||||
|
||||
export interface TurntablePosterOutput {
|
||||
fileId: string
|
||||
size: number
|
||||
contentType: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface TurntableRenderSyncResponse {
|
||||
taskId: string
|
||||
status: 'queued' | 'rendering'
|
||||
positionInQueue?: number
|
||||
metadata?: Record<string, unknown>
|
||||
poster: TurntablePosterOutput
|
||||
}
|
||||
|
||||
export interface TurntableVideoOutput {
|
||||
fileId: string
|
||||
size: number
|
||||
contentType: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface TurntableRenderStats {
|
||||
width: number
|
||||
height: number
|
||||
frames: number
|
||||
fps: number
|
||||
durationSeconds: number
|
||||
degreesPerFrame: number
|
||||
startAngle: number
|
||||
direction: string
|
||||
includeEndFrame: boolean
|
||||
engine: string
|
||||
elapsedMs: number
|
||||
}
|
||||
|
||||
export interface TurntableTaskResponse {
|
||||
taskId: string
|
||||
status: 'queued' | 'rendering' | 'completed' | 'failed'
|
||||
positionInQueue?: number
|
||||
createdAt: string
|
||||
startedAt?: string
|
||||
completedAt?: string
|
||||
failedAt?: string
|
||||
render?: TurntableRenderStats
|
||||
video?: TurntableVideoOutput
|
||||
error?: {
|
||||
code: string
|
||||
message: string
|
||||
details?: Record<string, unknown>
|
||||
}
|
||||
}
|
||||
|
||||
export class TurntableService {
|
||||
async resolveConfig(teamId?: string): Promise<TurntableConfig> {
|
||||
const envUrl = process.env.TURNTABLE_RENDERER_URL?.trim()
|
||||
const envUsername =
|
||||
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME?.trim() ||
|
||||
process.env.TURNTABLE_RENDERER_USERNAME?.trim()
|
||||
const envPassword =
|
||||
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD?.trim() ||
|
||||
process.env.TURNTABLE_RENDERER_PASSWORD?.trim()
|
||||
|
||||
if (envUrl) {
|
||||
return {
|
||||
url: envUrl.replace(/\/+$/, ''),
|
||||
username: envUsername || undefined,
|
||||
password: envPassword || undefined,
|
||||
isEnv: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (teamId) {
|
||||
try {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
const teamSettings = team?.settings as PrismaJson.Settings | null
|
||||
const turntable = teamSettings?.turntable
|
||||
if (turntable?.url?.trim()) {
|
||||
return {
|
||||
url: turntable.url.trim().replace(/\/+$/, ''),
|
||||
username: turntable.username?.trim() || undefined,
|
||||
password: turntable.password?.trim() || undefined,
|
||||
isEnv: false,
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err, teamId }, 'Failed to load team turntable settings')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isEnv: false,
|
||||
}
|
||||
}
|
||||
|
||||
private getAuthHeader(config: TurntableConfig): string | undefined {
|
||||
if (config.username && config.password) {
|
||||
const credentials = Buffer.from(`${config.username}:${config.password}`).toString('base64')
|
||||
return `Basic ${credentials}`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
async isAvailable(teamId?: string): Promise<boolean> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${config.url}/health`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(3000),
|
||||
})
|
||||
|
||||
return response.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async getSettings(teamId: string): Promise<TurntableSettingsResponse> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
return {
|
||||
url: config.url,
|
||||
username: config.username,
|
||||
hasPassword: Boolean(config.password),
|
||||
isEnvConfigured: config.isEnv,
|
||||
}
|
||||
}
|
||||
|
||||
async updateSettings(
|
||||
teamId: string,
|
||||
req: UpdateTurntableSettingsRequest,
|
||||
): Promise<TurntableSettingsResponse> {
|
||||
const currentConfig = await this.resolveConfig(teamId)
|
||||
if (currentConfig.isEnv) {
|
||||
throw new Error(
|
||||
'Turntable settings are configured via environment variables and cannot be edited',
|
||||
)
|
||||
}
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
const settings = (team?.settings || {}) as PrismaJson.Settings
|
||||
const prevTurntable = settings.turntable || {}
|
||||
|
||||
settings.turntable = {
|
||||
url: req.url !== undefined ? req.url : prevTurntable.url,
|
||||
username: req.username !== undefined ? req.username : prevTurntable.username,
|
||||
password: req.password !== undefined ? req.password : prevTurntable.password,
|
||||
}
|
||||
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: { settings },
|
||||
})
|
||||
|
||||
return this.getSettings(teamId)
|
||||
}
|
||||
|
||||
async testConnection(
|
||||
config?: {
|
||||
url?: string
|
||||
username?: string
|
||||
password?: string
|
||||
},
|
||||
teamId?: string,
|
||||
): Promise<{ ok: boolean; version?: string; blender?: string; error?: string }> {
|
||||
let resolvedUrl = config?.url?.trim()
|
||||
let resolvedUsername = config?.username?.trim()
|
||||
let resolvedPassword = config?.password
|
||||
|
||||
if (teamId && (!resolvedUrl || resolvedPassword === undefined)) {
|
||||
const savedConfig = await this.resolveConfig(teamId)
|
||||
if (!resolvedUrl) {
|
||||
resolvedUrl = savedConfig.url
|
||||
}
|
||||
if (!resolvedUsername && savedConfig.username) {
|
||||
resolvedUsername = savedConfig.username
|
||||
}
|
||||
if (resolvedPassword === undefined) {
|
||||
resolvedPassword = savedConfig.password
|
||||
}
|
||||
}
|
||||
|
||||
if (!resolvedUrl) {
|
||||
return { ok: false, error: 'URL is required' }
|
||||
}
|
||||
const cleanUrl = resolvedUrl.replace(/\/+$/, '')
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
if (resolvedUsername && resolvedPassword) {
|
||||
const credentials = Buffer.from(`${resolvedUsername}:${resolvedPassword}`).toString(
|
||||
'base64',
|
||||
)
|
||||
headers['Authorization'] = `Basic ${credentials}`
|
||||
}
|
||||
|
||||
const response = await fetch(`${cleanUrl}/version`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text().catch(() => '')
|
||||
return {
|
||||
ok: false,
|
||||
error: `Server returned status ${response.status}: ${errText || response.statusText}`,
|
||||
}
|
||||
}
|
||||
|
||||
const body = (await response.json()) as { version?: string; blender?: string }
|
||||
return {
|
||||
ok: true,
|
||||
version: body.version,
|
||||
blender: body.blender,
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return { ok: false, error: message }
|
||||
}
|
||||
}
|
||||
|
||||
async uploadFile(
|
||||
filePath: string,
|
||||
filename: string,
|
||||
teamId?: string,
|
||||
): Promise<{ id: string; name: string; size: number }> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
throw new Error('Turntable renderer URL is not configured.')
|
||||
}
|
||||
|
||||
const fileBytes = fs.readFileSync(filePath)
|
||||
const headers: Record<string, string> = {
|
||||
'content-type': 'application/octet-stream',
|
||||
'x-filename': encodeURIComponent(filename),
|
||||
}
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${config.url}/v1/files`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: fileBytes,
|
||||
signal: AbortSignal.timeout(120000),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => '')
|
||||
throw new Error(
|
||||
`Turntable upload failed with status ${response.status}: ${errorText || response.statusText}`,
|
||||
)
|
||||
}
|
||||
|
||||
return (await response.json()) as { id: string; name: string; size: number }
|
||||
}
|
||||
|
||||
async startRender(
|
||||
fileId: string,
|
||||
options: Record<string, unknown> = {},
|
||||
teamId?: string,
|
||||
): Promise<TurntableRenderSyncResponse> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
throw new Error('Turntable renderer URL is not configured.')
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'content-type': 'application/json',
|
||||
}
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${config.url}/v1/render`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
input: { fileId },
|
||||
options,
|
||||
}),
|
||||
signal: AbortSignal.timeout(60000),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => '')
|
||||
throw new Error(
|
||||
`Turntable render request failed with status ${response.status}: ${errorText || response.statusText}`,
|
||||
)
|
||||
}
|
||||
|
||||
return (await response.json()) as TurntableRenderSyncResponse
|
||||
}
|
||||
|
||||
async getTaskStatus(taskId: string, teamId?: string): Promise<TurntableTaskResponse> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
throw new Error('Turntable renderer URL is not configured.')
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${config.url}/v1/render/tasks/${taskId}`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => '')
|
||||
throw new Error(
|
||||
`Failed to fetch task status (${response.status}): ${errorText || response.statusText}`,
|
||||
)
|
||||
}
|
||||
|
||||
return (await response.json()) as TurntableTaskResponse
|
||||
}
|
||||
|
||||
async downloadFile(fileId: string, targetPath?: string, teamId?: string): Promise<Buffer> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
throw new Error('Turntable renderer URL is not configured.')
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${config.url}/v1/files/${fileId}`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(120000),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => '')
|
||||
throw new Error(
|
||||
`Failed to download file ${fileId} (${response.status}): ${errorText || response.statusText}`,
|
||||
)
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer()
|
||||
const buffer = Buffer.from(arrayBuffer)
|
||||
if (targetPath) {
|
||||
fs.writeFileSync(targetPath, buffer)
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
|
||||
async deleteTask(taskId: string, teamId?: string): Promise<boolean> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
return false
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${config.url}/v1/render/tasks/${taskId}`, {
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
return response.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async deleteFile(fileId: string, teamId?: string): Promise<boolean> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
return false
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${config.url}/v1/files/${fileId}`, {
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
return response.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const turntableService = new TurntableService()
|
||||
@@ -3,6 +3,7 @@ import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { uploadService } from './upload'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { AssetStatus, AssetType, TaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
|
||||
@@ -450,6 +451,76 @@ describe('UploadService', () => {
|
||||
expect(workflowTask).toBeNull()
|
||||
})
|
||||
|
||||
it('should confirm file upload and create transcode_3d for 3D model when turntable is available', async () => {
|
||||
vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(true)
|
||||
const task = await prisma.task.create({
|
||||
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key-3d-1' },
|
||||
create: { key: 'test-key-3d-1' },
|
||||
},
|
||||
},
|
||||
mediaType: 'model/gltf-binary',
|
||||
},
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
|
||||
|
||||
const workflowTask = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: asset.id, type: WorkflowTaskType.transcode_3d },
|
||||
})
|
||||
expect(workflowTask).toBeDefined()
|
||||
expect(workflowTask?.payload).toEqual({
|
||||
projectId: projectId,
|
||||
transcode: {
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should mark asset processed without creating transcode_3d for 3D model when turntable is unavailable', async () => {
|
||||
vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(false)
|
||||
const task = await prisma.task.create({
|
||||
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key-3d-2' },
|
||||
create: { key: 'test-key-3d-2' },
|
||||
},
|
||||
},
|
||||
mediaType: 'model/gltf-binary',
|
||||
},
|
||||
})
|
||||
|
||||
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_3d },
|
||||
})
|
||||
expect(workflowTask).toBeNull()
|
||||
})
|
||||
|
||||
it('should confirm file upload and resolve empty mediaType using Bun resolver for audio', async () => {
|
||||
const task = await prisma.task.create({
|
||||
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
|
||||
|
||||
@@ -14,10 +14,11 @@ import {
|
||||
S3SignResponse,
|
||||
TaskInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { ImageTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
|
||||
import { ImageTranscoder, ModelTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { ulid } from 'ulid'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { getProxyType, isHtmlDocument, isOfficeDocument } from '@shumai/core/src/utils/mime'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
@@ -323,6 +324,7 @@ export class UploadService {
|
||||
const isImage = proxyType === 'image'
|
||||
const isAudio = proxyType === 'audio'
|
||||
const isPdf = proxyType === 'pdf'
|
||||
const is3D = proxyType === '3d'
|
||||
|
||||
if (!proxyType) {
|
||||
await tx.asset.update({
|
||||
@@ -376,6 +378,21 @@ export class UploadService {
|
||||
.withSprite()
|
||||
.withPoster()
|
||||
.submit()
|
||||
} else if (is3D) {
|
||||
const turntableAvailable = await turntableService.isAvailable(team.id)
|
||||
if (!turntableAvailable) {
|
||||
await tx.asset.update({
|
||||
where: { id: asset.id },
|
||||
data: { status: AssetStatus.processed },
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await new ModelTranscoder(tx as any, asset.id, team.id, projectId)
|
||||
.withSprite()
|
||||
.withPoster()
|
||||
.submit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +126,24 @@ describe('getProxyType', () => {
|
||||
expect(getProxyType(null, 'slides.pptx')).toBe('pdf')
|
||||
})
|
||||
|
||||
it('should detect 3d proxyType for supported 3D models', () => {
|
||||
expect(getProxyType('model/gltf-binary', 'model.glb')).toBe('3d')
|
||||
expect(getProxyType('model/gltf+json', 'model.gltf')).toBe('3d')
|
||||
expect(getProxyType(null, 'model.glb')).toBe('3d')
|
||||
expect(getProxyType(null, 'model.gltf')).toBe('3d')
|
||||
expect(getProxyType(null, 'character.fbx')).toBe('3d')
|
||||
expect(getProxyType('model/obj', 'mesh.obj')).toBe('3d')
|
||||
expect(getProxyType(null, 'mesh.obj')).toBe('3d')
|
||||
expect(getProxyType('model/stl', 'part.stl')).toBe('3d')
|
||||
expect(getProxyType(null, 'part.stl')).toBe('3d')
|
||||
expect(getProxyType(null, 'scene.usd')).toBe('3d')
|
||||
expect(getProxyType(null, 'scene.usda')).toBe('3d')
|
||||
expect(getProxyType(null, 'scene.usdc')).toBe('3d')
|
||||
expect(getProxyType('model/vnd.usdz+zip', 'scene.usdz')).toBe('3d')
|
||||
expect(getProxyType('model/vnd.collada+xml', 'model.dae')).toBe('3d')
|
||||
expect(getProxyType(null, 'MODEL.GLB')).toBe('3d')
|
||||
})
|
||||
|
||||
it('should return null for unsupported files', () => {
|
||||
expect(getProxyType('application/zip', 'archive.zip')).toBeNull()
|
||||
expect(getProxyType(null, 'unknown.bin')).toBeNull()
|
||||
|
||||
@@ -1,6 +1,41 @@
|
||||
import { isRawImage } from './raw'
|
||||
|
||||
export type ProxyType = 'image' | 'video' | 'audio' | 'pdf'
|
||||
export type ProxyType = 'image' | 'video' | 'audio' | 'pdf' | '3d'
|
||||
|
||||
export function is3dModel(mediaType?: string | null, filename?: string | null): boolean {
|
||||
const lowerMediaType = mediaType?.toLowerCase() || ''
|
||||
const lowerFilename = filename?.toLowerCase() || ''
|
||||
|
||||
const modelExtensions = [
|
||||
'.glb',
|
||||
'.gltf',
|
||||
'.usd',
|
||||
'.usda',
|
||||
'.usdc',
|
||||
'.usdz',
|
||||
'.fbx',
|
||||
'.obj',
|
||||
'.stl',
|
||||
'.dae',
|
||||
]
|
||||
if (modelExtensions.some((ext) => lowerFilename.endsWith(ext))) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (
|
||||
lowerMediaType.startsWith('model/') ||
|
||||
lowerMediaType === 'model/gltf-binary' ||
|
||||
lowerMediaType === 'model/gltf+json' ||
|
||||
lowerMediaType === 'model/obj' ||
|
||||
lowerMediaType === 'model/stl' ||
|
||||
lowerMediaType === 'model/vnd.usdz+zip' ||
|
||||
lowerMediaType === 'model/vnd.collada+xml'
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export function isOfficeDocument(mediaType?: string | null, filename?: string | null): boolean {
|
||||
const lowerMediaType = mediaType?.toLowerCase() || ''
|
||||
@@ -97,6 +132,10 @@ export function getProxyType(
|
||||
return 'pdf'
|
||||
}
|
||||
|
||||
if (is3dModel(mediaType, filename)) {
|
||||
return '3d'
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user