mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
Compare commits
10
Commits
v0.5.1
...
8446eaba94
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8446eaba94 | ||
|
|
7c264ee447 | ||
|
|
127bd033b3 | ||
|
|
e691acc45b | ||
|
|
380c0854f8 | ||
|
|
ae6cdc88da | ||
|
|
2e24646c8b | ||
|
|
e06409690a | ||
|
|
06ea4eed78 | ||
|
|
4b1b64fe2b |
@@ -8,10 +8,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
* **3d**: Add support for 3D model files (.glb, .gltf, .obj, .fbx, .stl, .dae, .usd, .usda, .usdc, .usdz) with automated turntable video rendering, hover sprite scrubbing, and an interactive 3D turntable viewer featuring 360° ruler scrubbing and degree-based markup comments
|
||||
* **settings**: Add Turntable Renderer settings card with server connection testing and environment variable override support
|
||||
* **kanban**: Related assets on a task are now clickable, taking you directly to that file or folder in its project
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
- **viewer**: Refine the 3D turntable viewer bottom bar into a unified single row with a centered cyclic ruler slider, fixed center indicator, degree tooltip on drag, and ±15° step buttons
|
||||
|
||||
## [0.5.1] - 2026-10-06
|
||||
|
||||
### Added
|
||||
|
||||
@@ -52,6 +52,14 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/turntable/turntable', () => ({
|
||||
turntableService: {
|
||||
getSettings: vi.fn(),
|
||||
updateSettings: vi.fn(),
|
||||
testConnection: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
@@ -638,5 +646,107 @@ describe('team api', () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/turntable-settings returns turntable settings', async () => {
|
||||
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
|
||||
vi.mocked(turntableService.getSettings).mockResolvedValue({
|
||||
url: 'http://localhost:3001',
|
||||
username: 'user',
|
||||
hasPassword: true,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/turntable-settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toEqual({
|
||||
url: 'http://localhost:3001',
|
||||
username: 'user',
|
||||
hasPassword: true,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/turntable-settings updates settings when not env configured', async () => {
|
||||
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
|
||||
vi.mocked(turntableService.updateSettings).mockResolvedValue({
|
||||
url: 'http://custom:3001',
|
||||
username: 'newuser',
|
||||
hasPassword: true,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/turntable-settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
url: 'http://custom:3001',
|
||||
username: 'newuser',
|
||||
password: 'secretpassword',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.url).toBe('http://custom:3001')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/turntable-settings returns 400 when env configured', async () => {
|
||||
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
|
||||
vi.mocked(turntableService.updateSettings).mockRejectedValue(
|
||||
new Error(
|
||||
'Turntable settings are configured via environment variables and cannot be edited',
|
||||
),
|
||||
)
|
||||
|
||||
const res = await app.request('/teams/t1/turntable-settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
url: 'http://custom:3001',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const data = await res.json()
|
||||
expect(data.message).toContain('configured via environment variables')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/turntable-settings/test tests connection', async () => {
|
||||
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
|
||||
vi.mocked(turntableService.testConnection).mockResolvedValue({
|
||||
ok: true,
|
||||
version: '1.0.0',
|
||||
blender: '5.2.0',
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/turntable-settings/test', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
url: 'http://custom:3001',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.ok).toBe(true)
|
||||
expect(data.blender).toBe('5.2.0')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
updateTeamSettingsRequestSchema,
|
||||
listMembersQuerySchema,
|
||||
updateSandboxSettingsRequestSchema,
|
||||
updateTurntableSettingsRequestSchema,
|
||||
updateMeRequestSchema,
|
||||
updateTeamMemberRoleRequestSchema,
|
||||
createApiTokenRequestSchema,
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
import { apiTokenService } from '@shumai/core/src/user/api-token'
|
||||
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
@@ -265,6 +267,63 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(sandbox)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/turntable-settings', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await turntableService.getSettings(teamId)
|
||||
return c.json(settings)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/turntable-settings',
|
||||
zValidator('json', updateTurntableSettingsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
try {
|
||||
const settings = await turntableService.updateSettings(teamId, req)
|
||||
return c.json(settings)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return c.json({ message }, 400)
|
||||
}
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/turntable-settings/test',
|
||||
zValidator('json', updateTurntableSettingsRequestSchema.partial()),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const res = await turntableService.testConnection(req, teamId)
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/user-metadata', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
@@ -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,437 @@
|
||||
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 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: Bun.file(filePath),
|
||||
signal: AbortSignal.timeout(900000),
|
||||
})
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "WorkflowTaskType" ADD VALUE 'transcode_3d';
|
||||
@@ -121,6 +121,7 @@ enum WorkflowTaskType {
|
||||
transcode_screenshot
|
||||
transcode_image_annotation
|
||||
transcode_watermark
|
||||
transcode_3d
|
||||
ai_metadata_autofill
|
||||
chat
|
||||
ai_embedding
|
||||
|
||||
+1
@@ -150,6 +150,7 @@ export const WorkflowTaskType = {
|
||||
transcode_screenshot: 'transcode_screenshot',
|
||||
transcode_image_annotation: 'transcode_image_annotation',
|
||||
transcode_watermark: 'transcode_watermark',
|
||||
transcode_3d: 'transcode_3d',
|
||||
ai_metadata_autofill: 'ai_metadata_autofill',
|
||||
chat: 'chat',
|
||||
ai_embedding: 'ai_embedding',
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -103,8 +103,15 @@ declare global {
|
||||
replyTo?: string
|
||||
}
|
||||
|
||||
export interface TurntableSettings {
|
||||
url?: string
|
||||
username?: string
|
||||
password?: string
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
transcode?: TranscodeSettings
|
||||
turntable?: TurntableSettings
|
||||
mediaGeneration?: MediaGenerationSettings
|
||||
appearance?: AppearanceSettings
|
||||
emailNotification?: EmailNotificationSettings
|
||||
@@ -196,7 +203,7 @@ declare global {
|
||||
duration: number
|
||||
filesize: number
|
||||
frames: number
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf'
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d'
|
||||
imageTranscodes: ImageTranscode[]
|
||||
videoTranscodes: VideoTranscode[]
|
||||
videoPreview?: VideoTranscode
|
||||
@@ -530,7 +537,7 @@ declare global {
|
||||
key: string
|
||||
sizeByte: number
|
||||
contentType?: string | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
}
|
||||
export type KanbanCommentAttachmentList = KanbanCommentAttachment[]
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ export const assetInfoPaginatedListSchema = z.object({
|
||||
export type AssetInfoPaginatedList = z.infer<typeof assetInfoPaginatedListSchema>
|
||||
|
||||
export const previewInfoSchema = z.object({
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
thumbnailUrl: z.string().optional(),
|
||||
originalHeight: z.number().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
@@ -76,7 +76,7 @@ export const assetInfoSchema = z.object({
|
||||
type: z.string(),
|
||||
targetType: z.string().optional().nullable(),
|
||||
status: z.string(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
latestChildren: z.array(childPreviewSchema).optional(),
|
||||
preview: previewInfoSchema.nullable().optional(),
|
||||
createdAt: z.string(),
|
||||
@@ -143,7 +143,7 @@ export const assetInfoSchema = z.object({
|
||||
.optional(),
|
||||
})
|
||||
.optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
metadata: mediaMetadataSchema.optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
@@ -233,7 +233,7 @@ export const attachmentInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
assetId: z.string(),
|
||||
url: z.string(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
})
|
||||
export type AttachmentInfo = z.infer<typeof attachmentInfoSchema>
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ export const kanbanAttachmentPayloadSchema = z.object({
|
||||
key: z.string(),
|
||||
sizeByte: z.number(),
|
||||
contentType: z.string().nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
})
|
||||
export type KanbanAttachmentPayload = z.infer<typeof kanbanAttachmentPayloadSchema>
|
||||
|
||||
@@ -17,7 +17,7 @@ export const kanbanAttachmentInfoSchema = z.object({
|
||||
sizeByte: z.number(),
|
||||
contentType: z.string().nullable().optional(),
|
||||
url: z.string(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
})
|
||||
export type KanbanAttachmentInfo = z.infer<typeof kanbanAttachmentInfoSchema>
|
||||
|
||||
@@ -28,7 +28,7 @@ export const postKanbanAttachmentResponseSchema = z.object({
|
||||
sizeByte: z.number(),
|
||||
contentType: z.string().nullable().optional(),
|
||||
uploadUrl: z.string(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
})
|
||||
export type PostKanbanAttachmentResponse = z.infer<typeof postKanbanAttachmentResponseSchema>
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ export const kanbanTaskAssetInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
type: z.string(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
thumbnailUrl: z.string().nullable().optional(),
|
||||
path: z.string(),
|
||||
creator: kanbanUserInfoSchema.nullable().optional(),
|
||||
|
||||
@@ -18,7 +18,7 @@ export type EntityInfo = z.infer<typeof entityInfoSchema>
|
||||
|
||||
export const assetPreviewSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
|
||||
name: z.string().optional(),
|
||||
preview: z.string().optional(),
|
||||
thumbnailUrl: z.string().optional(),
|
||||
|
||||
@@ -142,6 +142,21 @@ export const updateTeamSettingsRequestSchema = z.union([
|
||||
])
|
||||
export type UpdateTeamSettingsRequest = z.infer<typeof updateTeamSettingsRequestSchema>
|
||||
|
||||
export const turntableSettingsResponseSchema = z.object({
|
||||
url: z.string().optional(),
|
||||
username: z.string().optional(),
|
||||
hasPassword: z.boolean(),
|
||||
isEnvConfigured: z.boolean(),
|
||||
})
|
||||
export type TurntableSettingsResponse = z.infer<typeof turntableSettingsResponseSchema>
|
||||
|
||||
export const updateTurntableSettingsRequestSchema = z.object({
|
||||
url: z.string().optional(),
|
||||
username: z.string().optional(),
|
||||
password: z.string().optional(),
|
||||
})
|
||||
export type UpdateTurntableSettingsRequest = z.infer<typeof updateTurntableSettingsRequestSchema>
|
||||
|
||||
export interface TeamAppearanceSettings {
|
||||
hideAgent?: boolean
|
||||
}
|
||||
@@ -155,6 +170,7 @@ export interface TeamSettingsResponse {
|
||||
hlsEnabled?: boolean
|
||||
hlsResolutions?: HlsResolutionLadder[]
|
||||
}
|
||||
turntable?: TurntableSettingsResponse
|
||||
appearance?: TeamAppearanceSettings
|
||||
semanticSearchEnabled?: boolean
|
||||
[key: string]: unknown
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { prisma, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { fileURLToPath } from 'url'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
|
||||
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||
const fixturesDir = path.resolve(currentDir, '../fixtures')
|
||||
|
||||
describe.each(['local', 'temporal'] as const)(
|
||||
'Workflow E2E - 3D Asset Transcode (executor: %s)',
|
||||
(mode) => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let transcodeWorkerPromise: Promise<void> | null = null
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockTurntableServer: any = null
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-3d'
|
||||
|
||||
const smallPngBuffer = fs.readFileSync(path.join(fixturesDir, 'small.png'))
|
||||
const smallMp4Buffer = fs.readFileSync(path.join(fixturesDir, 'small.mp4'))
|
||||
|
||||
mockTurntableServer = Bun.serve({
|
||||
port: 0,
|
||||
fetch(req) {
|
||||
const url = new URL(req.url)
|
||||
if (url.pathname === '/version') {
|
||||
return Response.json({ version: '1.0.0', runtime: 'bun', blender: '5.2.0' })
|
||||
}
|
||||
if (url.pathname === '/v1/files' && req.method === 'POST') {
|
||||
return Response.json({ id: 'f_input3d', name: 'model.glb', size: 100 }, { status: 201 })
|
||||
}
|
||||
if (url.pathname === '/v1/render' && req.method === 'POST') {
|
||||
return Response.json(
|
||||
{
|
||||
taskId: 't_render3d',
|
||||
status: 'completed',
|
||||
poster: {
|
||||
fileId: 'f_poster3d',
|
||||
size: smallPngBuffer.length,
|
||||
contentType: 'image/png',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
},
|
||||
metadata: { format: 'glb' },
|
||||
},
|
||||
{ status: 201 },
|
||||
)
|
||||
}
|
||||
if (url.pathname === '/v1/render/tasks/t_render3d') {
|
||||
if (req.method === 'DELETE') {
|
||||
return Response.json({ ok: true })
|
||||
}
|
||||
return Response.json({
|
||||
taskId: 't_render3d',
|
||||
status: 'completed',
|
||||
posterFileId: 'f_poster3d',
|
||||
video: {
|
||||
fileId: 'f_video3d',
|
||||
size: smallMp4Buffer.length,
|
||||
contentType: 'video/mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url.pathname === '/v1/files/f_poster3d') {
|
||||
return new Response(smallPngBuffer, {
|
||||
headers: { 'Content-Type': 'image/png' },
|
||||
})
|
||||
}
|
||||
if (url.pathname === '/v1/files/f_video3d') {
|
||||
return new Response(smallMp4Buffer, {
|
||||
headers: { 'Content-Type': 'video/mp4' },
|
||||
})
|
||||
}
|
||||
return new Response('Not Found', { status: 404 })
|
||||
},
|
||||
})
|
||||
|
||||
process.env.TURNTABLE_RENDERER_URL = `http://localhost:${mockTurntableServer.port}`
|
||||
|
||||
workflowService.setExecutorType(mode)
|
||||
initTranscodeWorkflows()
|
||||
|
||||
if (mode === 'temporal') {
|
||||
console.log('Starting background worker for transcode Temporal E2E tests...')
|
||||
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
|
||||
workflowsPath: transcodeWorkflowsPath,
|
||||
})
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||
} else {
|
||||
console.log('Starting local workflow service polling...')
|
||||
workflowService.start()
|
||||
}
|
||||
}, 120000)
|
||||
|
||||
afterAll(async () => {
|
||||
if (mode === 'temporal') {
|
||||
console.log('Shutting down Temporal workers...')
|
||||
await workflowService.shutdownWorkers()
|
||||
await Promise.all([transcodeWorkerPromise].filter(Boolean))
|
||||
}
|
||||
workflowService.close()
|
||||
vi.restoreAllMocks()
|
||||
|
||||
if (mockTurntableServer) {
|
||||
mockTurntableServer.stop()
|
||||
}
|
||||
|
||||
delete process.env.TURNTABLE_RENDERER_URL
|
||||
|
||||
try {
|
||||
console.log('Cleaning up E2E storage files...')
|
||||
await s3Service.deletePrefix('shumai-e2e-test-bucket-3d', '')
|
||||
} catch (err) {
|
||||
console.error('Failed to clean up E2E storage folder:', err)
|
||||
}
|
||||
}, 120000)
|
||||
|
||||
it('should process 3D model transcode workflow task', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E 3D Transcode Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E 3D Transcode Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/model.glb',
|
||||
status: 'active',
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'model.glb',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'model/gltf-binary',
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
const dummyGlbBuffer = Buffer.from('dummy glb content')
|
||||
await s3Service.putObject(
|
||||
'shumai-e2e-test-bucket-3d',
|
||||
'projects/e2e/model.glb',
|
||||
dummyGlbBuffer,
|
||||
dummyGlbBuffer.length,
|
||||
'model/gltf-binary',
|
||||
)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'transcode_3d',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
transcode: {
|
||||
poster: true,
|
||||
sprite: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
console.log(
|
||||
`Submitted E2E 3D Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||
)
|
||||
const completedTask = await workflowService.executeWait(task, 60000)
|
||||
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const updatedAsset = await prisma.asset.findUnique({
|
||||
where: { id: asset.id },
|
||||
})
|
||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||
|
||||
const mediaInfo = updatedAsset?.media as unknown as {
|
||||
proxyType?: string
|
||||
videoPreview?: { key: string }
|
||||
poster?: { key: string }
|
||||
sprite?: { key: string }
|
||||
}
|
||||
expect(mediaInfo).toBeDefined()
|
||||
expect(mediaInfo.proxyType).toBe('3d')
|
||||
expect(mediaInfo.videoPreview?.key).toBe('projects/e2e/turntable.mp4')
|
||||
expect(mediaInfo.poster?.key).toBe('projects/e2e/poster.webp')
|
||||
expect(mediaInfo.sprite?.key).toBe('projects/e2e/sprite.webp')
|
||||
}, 90000)
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render3dModelActivity, generate3dSpriteActivity } from './transcode'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||
import * as fs from 'fs'
|
||||
|
||||
vi.mock('@shumai/core/src/turntable/turntable', () => ({
|
||||
turntableService: {
|
||||
uploadFile: vi.fn(),
|
||||
startRender: vi.fn(),
|
||||
getTaskStatus: vi.fn(),
|
||||
downloadFile: vi.fn(),
|
||||
deleteTask: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
putObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/transcode/transcode', () => ({
|
||||
transcodeService: {
|
||||
convertImageToWebp: vi.fn(),
|
||||
generate3dSprite: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
isAssetPurging: vi.fn().mockResolvedValue(false),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('fs')>()
|
||||
return {
|
||||
...actual,
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('3D Transcode Activities', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(fs.readFileSync).mockReturnValue(Buffer.from('mock-bytes'))
|
||||
vi.mocked(transcodeService.convertImageToWebp).mockResolvedValue(Buffer.from('webp-bytes'))
|
||||
vi.mocked(transcodeService.generate3dSprite).mockResolvedValue()
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue({} as never)
|
||||
vi.mocked(turntableService.deleteTask).mockResolvedValue(true)
|
||||
})
|
||||
|
||||
describe('render3dModelActivity', () => {
|
||||
it('uploads file, starts render, polls until complete, and uploads to S3', async () => {
|
||||
vi.mocked(turntableService.uploadFile).mockResolvedValue({
|
||||
id: 'f_input',
|
||||
name: 'model.glb',
|
||||
size: 1024,
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.startRender).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'queued',
|
||||
poster: {
|
||||
fileId: 'f_poster',
|
||||
contentType: 'image/png',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 5000,
|
||||
},
|
||||
metadata: { format: 'glb', vertices: 120 },
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
|
||||
taskId: 'task_render_1',
|
||||
status: 'completed',
|
||||
createdAt: new Date().toISOString(),
|
||||
video: {
|
||||
fileId: 'f_video',
|
||||
contentType: 'video/mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 1000,
|
||||
},
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('downloaded-data'))
|
||||
|
||||
const res = await render3dModelActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'model.glb',
|
||||
targetVideoKey: 'files/asset-1/turntable.mp4',
|
||||
targetPosterKey: 'files/asset-1/poster.webp',
|
||||
})
|
||||
|
||||
expect(turntableService.uploadFile).toHaveBeenCalledWith(
|
||||
'/tmp/model.glb',
|
||||
'model.glb',
|
||||
'team-1',
|
||||
)
|
||||
expect(turntableService.startRender).toHaveBeenCalledWith('f_input', {}, 'team-1')
|
||||
expect(turntableService.getTaskStatus).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(turntableService.downloadFile).toHaveBeenCalledWith(
|
||||
'f_video',
|
||||
'/tmp/turntable.mp4',
|
||||
'team-1',
|
||||
)
|
||||
expect(turntableService.downloadFile).toHaveBeenCalledWith('f_poster', undefined, 'team-1')
|
||||
expect(transcodeService.convertImageToWebp).toHaveBeenCalledWith(expect.any(Buffer))
|
||||
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/turntable.mp4',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'video/mp4',
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/poster.webp',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(res.modelMetadata).toEqual({ format: 'glb', vertices: 120 })
|
||||
expect(res.videoFilePath).toBe('/tmp/turntable.mp4')
|
||||
expect(res.posterFilePath).toBe('/tmp/poster.webp')
|
||||
})
|
||||
|
||||
it('throws ApplicationFailure when render fails on turntable-renderer', async () => {
|
||||
vi.mocked(turntableService.uploadFile).mockResolvedValue({
|
||||
id: 'f_input',
|
||||
name: 'model.glb',
|
||||
size: 1024,
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.startRender).mockResolvedValue({
|
||||
taskId: 'task_render_2',
|
||||
status: 'queued',
|
||||
poster: {
|
||||
fileId: 'f_poster',
|
||||
contentType: 'image/png',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 5000,
|
||||
},
|
||||
})
|
||||
|
||||
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
|
||||
taskId: 'task_render_2',
|
||||
status: 'failed',
|
||||
createdAt: new Date().toISOString(),
|
||||
error: {
|
||||
code: 'render_failed',
|
||||
message: 'Blender failed to import model',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
render3dModelActivity({
|
||||
taskId: 'wf-task-2',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'model.glb',
|
||||
targetVideoKey: 'files/asset-1/turntable.mp4',
|
||||
targetPosterKey: 'files/asset-1/poster.webp',
|
||||
}),
|
||||
).rejects.toThrow('Blender failed to import model')
|
||||
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_2', 'team-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('generate3dSpriteActivity', () => {
|
||||
it('generates 3d sprite sheet and uploads to S3', async () => {
|
||||
const res = await generate3dSpriteActivity({
|
||||
taskId: 'wf-task-3',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
spriteKey: 'files/asset-1/sprite.webp',
|
||||
})
|
||||
|
||||
expect(transcodeService.generate3dSprite).toHaveBeenCalledWith(
|
||||
'/tmp/turntable.mp4',
|
||||
'/tmp/sprite.webp',
|
||||
undefined,
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/sprite.webp',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'image/webp',
|
||||
)
|
||||
expect(res.spriteKey).toBe('files/asset-1/sprite.webp')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { parseCsvContent } from '@shumai/core/src/transcode/transcode'
|
||||
import { resolutionToDimensions } from '../workflows/transcode-utils'
|
||||
import {
|
||||
@@ -1551,3 +1552,215 @@ export async function deleteS3ObjectActivity(params: { key: string }): Promise<v
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
await s3Service.deleteObject(bucket, params.key)
|
||||
}
|
||||
|
||||
export interface Render3dModelActivityParams {
|
||||
taskId: string
|
||||
teamId: string
|
||||
assetId: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
filename: string
|
||||
targetVideoKey: string
|
||||
targetPosterKey: string
|
||||
}
|
||||
|
||||
export interface Render3dModelActivityResult {
|
||||
videoFilePath: string
|
||||
posterFilePath: string
|
||||
modelMetadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export async function render3dModelActivity(
|
||||
params: Render3dModelActivityParams,
|
||||
): Promise<Render3dModelActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const videoFilePath = path.join(tmpDir, 'turntable.mp4')
|
||||
const posterFilePath = path.join(tmpDir, 'poster.webp')
|
||||
|
||||
let renderTaskId: string | undefined
|
||||
|
||||
try {
|
||||
const uploadResult = await turntableService.uploadFile(
|
||||
params.filePath,
|
||||
params.filename,
|
||||
params.teamId,
|
||||
)
|
||||
const fileId = uploadResult.id
|
||||
|
||||
if (signal?.aborted) {
|
||||
await turntableService.deleteFile(fileId, params.teamId).catch(() => {})
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const startResult = await turntableService.startRender(fileId, {}, params.teamId)
|
||||
renderTaskId = startResult.taskId
|
||||
|
||||
let finishedStatus: 'completed' | 'failed' | null = null
|
||||
let taskRecord: Awaited<ReturnType<typeof turntableService.getTaskStatus>> | null = null
|
||||
|
||||
for (let i = 0; i < 360; i++) {
|
||||
if (signal?.aborted) {
|
||||
if (renderTaskId) {
|
||||
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (i > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 5000))
|
||||
}
|
||||
|
||||
taskRecord = await turntableService.getTaskStatus(renderTaskId, params.teamId)
|
||||
if (taskRecord.status === 'completed') {
|
||||
finishedStatus = 'completed'
|
||||
break
|
||||
}
|
||||
if (taskRecord.status === 'failed') {
|
||||
finishedStatus = 'failed'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (finishedStatus !== 'completed' || !taskRecord) {
|
||||
const errMsg =
|
||||
finishedStatus === 'failed'
|
||||
? taskRecord?.error?.message || '3D render failed on turntable server'
|
||||
: '3D render timed out on turntable server'
|
||||
throw ApplicationFailure.create({
|
||||
message: errMsg,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const videoFileId = taskRecord.video?.fileId
|
||||
if (!videoFileId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video file ID missing from turntable render result',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const posterFileId = startResult.poster?.fileId
|
||||
|
||||
if (!posterFileId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Poster file ID missing from turntable render result',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const videoBuffer = await turntableService.downloadFile(
|
||||
videoFileId,
|
||||
videoFilePath,
|
||||
params.teamId,
|
||||
)
|
||||
const posterBuffer = await turntableService.downloadFile(posterFileId, undefined, params.teamId)
|
||||
|
||||
const posterWebpBuffer = await transcodeService.convertImageToWebp(posterBuffer)
|
||||
fs.writeFileSync(posterFilePath, posterWebpBuffer)
|
||||
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.targetVideoKey,
|
||||
videoBuffer,
|
||||
videoBuffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.targetPosterKey,
|
||||
posterWebpBuffer,
|
||||
posterWebpBuffer.length,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
await turntableService.deleteTask(renderTaskId, params.teamId).catch((err) => {
|
||||
logger.warn({ err, taskId: renderTaskId }, 'Failed to delete turntable task after completion')
|
||||
})
|
||||
renderTaskId = undefined
|
||||
|
||||
return {
|
||||
videoFilePath,
|
||||
posterFilePath,
|
||||
modelMetadata: (startResult.metadata as Record<string, unknown>) || {},
|
||||
}
|
||||
} catch (err) {
|
||||
if (renderTaskId) {
|
||||
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
|
||||
}
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to render 3D model: ${errMsg}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export interface Generate3dSpriteActivityParams {
|
||||
taskId: string
|
||||
assetKey: string
|
||||
videoFilePath: string
|
||||
spriteKey: string
|
||||
}
|
||||
|
||||
export async function generate3dSpriteActivity(
|
||||
params: Generate3dSpriteActivityParams,
|
||||
): Promise<{ spriteKey: string }> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Sprite generation cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = path.dirname(params.videoFilePath)
|
||||
const spriteFilePath = path.join(tmpDir, 'sprite.webp')
|
||||
|
||||
try {
|
||||
await transcodeService.generate3dSprite(params.videoFilePath, spriteFilePath, signal)
|
||||
const spriteBuffer = fs.readFileSync(spriteFilePath)
|
||||
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.spriteKey,
|
||||
spriteBuffer,
|
||||
spriteBuffer.length,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
return { spriteKey: params.spriteKey }
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate 3D sprite: ${errMsg}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { renderPdfPagesWorkflow } from './workflows/render-pdf-pages'
|
||||
import { takeVideoScreenshotsWorkflow } from './workflows/take-video-screenshots'
|
||||
import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annotation'
|
||||
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
|
||||
import { transcode3dWorkflow } from './workflows/transcode-3d'
|
||||
import { transcodeMedia } from './workflows/transcode'
|
||||
|
||||
export function initTranscodeWorkflows() {
|
||||
@@ -16,6 +17,7 @@ export function initTranscodeWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.transcode_video, transcodeVideoWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image, transcodeImageWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_pdf, transcodePdfWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_3d, transcode3dWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_pdf_pages, renderPdfPagesWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
|
||||
@@ -26,6 +28,7 @@ export function initTranscodeWorkflows() {
|
||||
|
||||
export * from './transcoder'
|
||||
export * from './workflows/transcode'
|
||||
export * from './workflows/transcode-3d'
|
||||
export * from './workflows/transcode-watermark'
|
||||
export * from './activities/transcode'
|
||||
export * from './activities/watermark'
|
||||
|
||||
@@ -151,3 +151,41 @@ export class PdfTranscoder {
|
||||
return task.id
|
||||
}
|
||||
}
|
||||
|
||||
export class ModelTranscoder {
|
||||
private spec: PrismaJson.TaskSpec = {}
|
||||
|
||||
constructor(
|
||||
private readonly db: TransactionClient,
|
||||
private readonly assetId: string,
|
||||
private readonly teamId: string,
|
||||
private readonly projectId: string,
|
||||
) {}
|
||||
|
||||
withSprite(): this {
|
||||
this.spec.sprite = true
|
||||
return this
|
||||
}
|
||||
|
||||
withPoster(): this {
|
||||
this.spec.poster = true
|
||||
return this
|
||||
}
|
||||
|
||||
async submit(): Promise<string> {
|
||||
const task = await this.db.workflowTask.create({
|
||||
data: {
|
||||
assetId: this.assetId,
|
||||
teamId: this.teamId,
|
||||
projectId: this.projectId,
|
||||
type: WorkflowTaskType.transcode_3d,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
payload: {
|
||||
projectId: this.projectId,
|
||||
transcode: this.spec,
|
||||
},
|
||||
},
|
||||
})
|
||||
return task.id
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcode3dWorkflow } from './transcode-3d'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('transcode3dWorkflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
updateAssetStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
render3dModelActivity: Object.assign(vi.fn(), { _activityName: 'render3dModelActivity' }),
|
||||
generate3dSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generate3dSpriteActivity' }),
|
||||
updateAssetMediaActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMediaActivity',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
}),
|
||||
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createAutofillTaskIfEnabledActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/model.glb',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should process 3D model transcode successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-3d',
|
||||
assetId: 'asset-3d',
|
||||
type: WorkflowTaskType.transcode_3d,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
transcode: {
|
||||
sprite: true,
|
||||
poster: true,
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-3d',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-3d',
|
||||
name: 'robot.glb',
|
||||
storageKey: { key: 'files/asset-3d/robot.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(1024),
|
||||
})
|
||||
|
||||
mockActivities.render3dModelActivity.mockResolvedValue({
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
posterFilePath: '/tmp/poster.webp',
|
||||
modelMetadata: { format: 'glb' },
|
||||
})
|
||||
|
||||
mockActivities.generate3dSpriteActivity.mockResolvedValue({
|
||||
spriteKey: 'files/asset-3d/sprite.webp',
|
||||
})
|
||||
|
||||
await transcode3dWorkflow(task)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-3d',
|
||||
status: AssetStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.render3dModelActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-3d',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'robot.glb',
|
||||
targetVideoKey: 'files/asset-3d/turntable.mp4',
|
||||
targetPosterKey: 'files/asset-3d/poster.webp',
|
||||
})
|
||||
|
||||
expect(mockActivities.generate3dSpriteActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
spriteKey: 'files/asset-3d/sprite.webp',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'asset-3d',
|
||||
mediaInfo: expect.objectContaining({
|
||||
proxyType: '3d',
|
||||
duration: 4,
|
||||
frames: 24,
|
||||
poster: { key: 'files/asset-3d/poster.webp' },
|
||||
sprite: expect.objectContaining({ key: 'files/asset-3d/sprite.webp' }),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-3d',
|
||||
status: AssetStatus.processed,
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
taskId: 'task-3d',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
}),
|
||||
)
|
||||
|
||||
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should fail task when render activity fails', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-3d-fail',
|
||||
assetId: 'asset-3d-fail',
|
||||
type: WorkflowTaskType.transcode_3d,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
sessionId: null,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-3d-fail',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-3d-fail',
|
||||
name: 'corrupt.glb',
|
||||
storageKey: { key: 'files/corrupt.glb' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
sizeByte: BigInt(512),
|
||||
})
|
||||
|
||||
mockActivities.render3dModelActivity.mockRejectedValue(new Error('Renderer crashed'))
|
||||
|
||||
await expect(transcode3dWorkflow(task)).rejects.toThrow('Renderer crashed')
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
taskId: 'task-3d-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
}),
|
||||
)
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'asset-3d-fail',
|
||||
status: AssetStatus.failed,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { executeActivity, getActivities } from '@shumai/workflow-core'
|
||||
import {
|
||||
getWorkerQueueAndStartTask,
|
||||
fetchAssetWithKey,
|
||||
completeTask,
|
||||
failTask,
|
||||
cleanupTmpDir,
|
||||
} from './common'
|
||||
|
||||
export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
|
||||
let tmpDir: string | undefined
|
||||
let workerQueue = ''
|
||||
let mediaProcessed = false
|
||||
|
||||
try {
|
||||
workerQueue = await getWorkerQueueAndStartTask(task)
|
||||
|
||||
const {
|
||||
updateAssetStatusActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
render3dModelActivity,
|
||||
generate3dSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
createAutofillTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
|
||||
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: key,
|
||||
})
|
||||
const currentFilePath = download.filePath
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const lastSlashIndex = key.lastIndexOf('/')
|
||||
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
|
||||
const videoKey = assetDir ? `${assetDir}/turntable.mp4` : 'turntable.mp4'
|
||||
const posterKey = assetDir ? `${assetDir}/poster.webp` : 'poster.webp'
|
||||
const spriteKey = assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp'
|
||||
|
||||
const renderResult = await executeActivity(workerQueue, render3dModelActivity, {
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
filePath: currentFilePath,
|
||||
filename: asset.name || 'model.glb',
|
||||
targetVideoKey: videoKey,
|
||||
targetPosterKey: posterKey,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, generate3dSpriteActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
videoFilePath: renderResult.videoFilePath,
|
||||
spriteKey,
|
||||
})
|
||||
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration: 4,
|
||||
filesize: 0,
|
||||
frames: 24,
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: videoKey,
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
],
|
||||
videoPreview: {
|
||||
key: videoKey,
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
poster: {
|
||||
key: posterKey,
|
||||
},
|
||||
sprite: {
|
||||
key: spriteKey,
|
||||
frames: 100,
|
||||
tileX: 10,
|
||||
tileY: 10,
|
||||
},
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalHeight: 1080,
|
||||
originalWidth: 1080,
|
||||
hasAudio: false,
|
||||
duration: 4,
|
||||
bitRate: 0,
|
||||
frameRate: 6,
|
||||
totalFrames: 24,
|
||||
startTimecode: '00:00:00:00',
|
||||
format: renderResult.modelMetadata ?? {},
|
||||
},
|
||||
original: {
|
||||
key,
|
||||
filesizeInBytes: Number(asset.sizeByte || 0),
|
||||
codec: '',
|
||||
},
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
assetId: asset.id,
|
||||
status: 'processed',
|
||||
})
|
||||
mediaProcessed = true
|
||||
|
||||
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
|
||||
assetId: asset.id,
|
||||
teamId: task.teamId,
|
||||
projectId: task.projectId,
|
||||
})
|
||||
|
||||
await completeTask(workerQueue, task.id)
|
||||
} catch (err) {
|
||||
console.error(`transcode3dWorkflow failed for task ${task.id}:`, err)
|
||||
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
|
||||
throw err
|
||||
} finally {
|
||||
await cleanupTmpDir(workerQueue, tmpDir)
|
||||
}
|
||||
}
|
||||
@@ -47,5 +47,6 @@ export * from './render-pdf-pages'
|
||||
export * from './take-video-screenshots'
|
||||
export * from './overlay-image-annotation'
|
||||
export * from './transcode-watermark'
|
||||
export * from './transcode-3d'
|
||||
export * from './common'
|
||||
export * from './transcode-utils'
|
||||
|
||||
@@ -60,7 +60,7 @@ interface BreadcrumbNavProps {
|
||||
name?: string
|
||||
type: 'file' | 'folder'
|
||||
version?: number
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
}
|
||||
isRootFolder: boolean
|
||||
customTerminalBreadcrumb?: string
|
||||
|
||||
@@ -4,10 +4,10 @@ import { formatTime } from '../viewers/video/utils'
|
||||
|
||||
type FilePreviewItem = {
|
||||
type?: string | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
preview?: {
|
||||
mediaType?: string | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
spriteUrl?: string
|
||||
thumbnailUrl?: string
|
||||
originalWidth?: number
|
||||
@@ -27,6 +27,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
|
||||
const isVideo = proxyType === 'video'
|
||||
const isAudio = proxyType === 'audio'
|
||||
const isPdf = proxyType === 'pdf'
|
||||
const is3D = proxyType === '3d'
|
||||
const hasDuration = isVideo || isAudio
|
||||
const duration = item.preview?.duration
|
||||
const pageCount = item.preview?.pageCount
|
||||
@@ -43,7 +44,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
|
||||
) : null
|
||||
|
||||
const isMediaWithSprite =
|
||||
(isVideo || isPdf) &&
|
||||
(isVideo || isPdf || is3D) &&
|
||||
item.preview?.spriteUrl &&
|
||||
item.preview.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
|
||||
@@ -445,6 +445,7 @@ export function TaskInfoForm({ teamId, task, canEdit = true }: TaskInfoFormProps
|
||||
onAddAssets={(newAssets) => linkAssets(newAssets)}
|
||||
onRemoveAsset={(assetId) => unlinkAsset(assetId)}
|
||||
disabled={!canEdit}
|
||||
linkable
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -59,6 +59,15 @@ vi.mock('@dnd-kit/react', () => ({
|
||||
KeyboardSensor: {},
|
||||
}))
|
||||
|
||||
// Mock TanStack Router Link as a plain anchor
|
||||
vi.mock('@tanstack/react-router', () => ({
|
||||
Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}))
|
||||
|
||||
// Mock @dnd-kit/dom
|
||||
vi.mock('@dnd-kit/dom', () => ({
|
||||
PointerActivationConstraints: {
|
||||
@@ -690,6 +699,58 @@ describe('Kanban UI Unit & Component Tests', () => {
|
||||
fireEvent.click(removeButtons[0])
|
||||
expect(onRemove).toHaveBeenCalledWith('asset-1')
|
||||
})
|
||||
|
||||
it('does not link asset rows by default', () => {
|
||||
render(
|
||||
<TaskRelatedAssets
|
||||
teamId="team-1"
|
||||
assets={mockAssets}
|
||||
onAddAssets={vi.fn()}
|
||||
onRemoveAsset={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.queryAllByRole('link')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('links files and folders to their project when linkable', () => {
|
||||
const onRemove = vi.fn()
|
||||
render(
|
||||
<TaskRelatedAssets
|
||||
teamId="team-1"
|
||||
projectId="task-proj"
|
||||
assets={[...mockAssets, { ...mockAssets[0], id: 'asset-3', projectId: null }]}
|
||||
onAddAssets={vi.fn()}
|
||||
onRemoveAsset={onRemove}
|
||||
linkable
|
||||
/>,
|
||||
)
|
||||
|
||||
const links = screen.getAllByRole('link')
|
||||
expect(links.map((link) => link.getAttribute('href'))).toEqual([
|
||||
'/projects/proj-1/files/asset-1',
|
||||
'/projects/proj-1/folders/asset-2',
|
||||
// Falls back to the task's project when the asset has none
|
||||
'/projects/task-proj/files/asset-3',
|
||||
])
|
||||
// The remove button stays outside the link
|
||||
fireEvent.click(screen.getAllByTitle(/Unlink Asset|取消关联资产/i)[1])
|
||||
expect(onRemove).toHaveBeenCalledWith('asset-2')
|
||||
})
|
||||
|
||||
it('does not link assets when no project is known', () => {
|
||||
render(
|
||||
<TaskRelatedAssets
|
||||
teamId="team-1"
|
||||
assets={[{ ...mockAssets[0], projectId: null }]}
|
||||
onAddAssets={vi.fn()}
|
||||
onRemoveAsset={vi.fn()}
|
||||
linkable
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.queryAllByRole('link')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('KanbanGoalSidebar component', () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Separator } from '@/ui/components/ui/separator'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
@@ -6,6 +7,7 @@ import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { KanbanTaskAssetInfo } from '@shumai/dtos'
|
||||
import { AssetPickerDialog } from './asset-picker-dialog'
|
||||
import { Plus, X, Folder, File, Files } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface TaskRelatedAssetsProps {
|
||||
teamId: string
|
||||
@@ -14,6 +16,8 @@ interface TaskRelatedAssetsProps {
|
||||
onAddAssets: (newAssets: KanbanTaskAssetInfo[]) => void
|
||||
onRemoveAsset: (assetId: string) => void
|
||||
disabled?: boolean
|
||||
/** Make each row a link to the asset in its project. Off by default so unsaved drafts are not discarded. */
|
||||
linkable?: boolean
|
||||
}
|
||||
|
||||
export function TaskRelatedAssets({
|
||||
@@ -23,6 +27,7 @@ export function TaskRelatedAssets({
|
||||
onAddAssets,
|
||||
onRemoveAsset,
|
||||
disabled = false,
|
||||
linkable = false,
|
||||
}: TaskRelatedAssetsProps) {
|
||||
const [isPickerOpen, setIsPickerOpen] = useState(false)
|
||||
|
||||
@@ -69,39 +74,62 @@ export function TaskRelatedAssets({
|
||||
<div className="space-y-1.5 max-h-48 overflow-y-auto pr-1">
|
||||
{assets.map((asset) => {
|
||||
const isFolder = asset.type === 'folder'
|
||||
const assetProjectId = asset.projectId || projectId
|
||||
const assetHref =
|
||||
linkable && assetProjectId
|
||||
? `/projects/${assetProjectId}/${isFolder ? 'folders' : 'files'}/${asset.id}`
|
||||
: null
|
||||
const body = (
|
||||
<>
|
||||
{/* Thumbnail / Icon */}
|
||||
<div className="w-7 h-7 rounded bg-muted border shrink-0 flex items-center justify-center overflow-hidden">
|
||||
{asset.thumbnailUrl ? (
|
||||
<img
|
||||
src={asset.thumbnailUrl}
|
||||
alt={asset.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : isFolder ? (
|
||||
<Folder className="w-4 h-4 text-primary fill-primary/20" />
|
||||
) : (
|
||||
<File className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Name & Path */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p
|
||||
className={cn(
|
||||
'font-medium truncate text-foreground leading-snug',
|
||||
assetHref && 'group-hover:underline group-hover:text-primary',
|
||||
)}
|
||||
>
|
||||
{asset.name}
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground truncate leading-none mt-0.5">
|
||||
{asset.path || '/'}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={asset.id}
|
||||
className="flex items-center justify-between gap-2 p-1.5 px-2 rounded-md bg-muted/40 hover:bg-muted/70 transition-colors text-xs border border-border/40"
|
||||
>
|
||||
{/* Left: Thumbnail & Names */}
|
||||
<div className="flex items-center gap-2.5 min-w-0 flex-1">
|
||||
{/* Thumbnail / Icon */}
|
||||
<div className="w-7 h-7 rounded bg-muted border shrink-0 flex items-center justify-center overflow-hidden">
|
||||
{asset.thumbnailUrl ? (
|
||||
<img
|
||||
src={asset.thumbnailUrl}
|
||||
alt={asset.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : isFolder ? (
|
||||
<Folder className="w-4 h-4 text-primary fill-primary/20" />
|
||||
) : (
|
||||
<File className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Name & Path */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium truncate text-foreground leading-snug">
|
||||
{asset.name}
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground truncate leading-none mt-0.5">
|
||||
{asset.path || '/'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{/* Left: Thumbnail & Names (links to the asset when linkable) */}
|
||||
{assetHref ? (
|
||||
<Link
|
||||
to={assetHref}
|
||||
title={asset.name}
|
||||
className="group flex items-center gap-2.5 min-w-0 flex-1 rounded-sm cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{body}
|
||||
</Link>
|
||||
) : (
|
||||
<div className="flex items-center gap-2.5 min-w-0 flex-1">{body}</div>
|
||||
)}
|
||||
|
||||
{/* Right: Creator & Remove Button */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
|
||||
@@ -136,14 +136,14 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
|
||||
const hasPreview = asset?.preview && (asset.proxyType === 'image' || asset.proxyType === 'video')
|
||||
|
||||
const handleClick = () => {
|
||||
const handleClick = () => {
|
||||
if (kanbanTask?.id && team?.id) {
|
||||
navigate({
|
||||
to: '/teams/$teamId/kanban',
|
||||
params: { teamId: team.id },
|
||||
search: { taskId: kanbanTask.id },
|
||||
})
|
||||
}else if(project?.id && asset?.id){
|
||||
} else if (project?.id && asset?.id) {
|
||||
//TODO: Perhaps it should be marked as read too when redirecting to it.
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { TurntableSettingsCard } from './TurntableSettingsCard'
|
||||
import type { TurntableSettingsResponse } from '@shumai/dtos'
|
||||
|
||||
const mockGetSettings = vi.fn()
|
||||
const mockPutSettings = vi.fn()
|
||||
const mockTestSettings = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
'turntable-settings': {
|
||||
$get: () => mockGetSettings(),
|
||||
$put: (args: unknown) => mockPutSettings(args),
|
||||
test: {
|
||||
$post: (args: unknown) => mockTestSettings(args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/paraglide/messages.js', () => ({
|
||||
m: {
|
||||
turntable_settings: () => 'Turntable Renderer Settings',
|
||||
turntable_settings_description: () => 'Configure external Blender turntable renderer',
|
||||
turntable_env_configured: () => 'Configured via Environment',
|
||||
turntable_server_url: () => 'Server URL',
|
||||
turntable_server_url_placeholder: () => 'http://localhost:3000',
|
||||
turntable_username: () => 'Username',
|
||||
turntable_password: () => 'Password',
|
||||
turntable_password_placeholder: () => 'Saved password',
|
||||
turntable_test_connection: () => 'Test Connection',
|
||||
turntable_testing: () => 'Testing...',
|
||||
turntable_connection_success: () => 'Connection successful',
|
||||
turntable_connection_failed: () => 'Connection failed',
|
||||
save: () => 'Save',
|
||||
settings_updated: () => 'Settings updated',
|
||||
failed_update_settings: () => 'Failed to update settings',
|
||||
},
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('TurntableSettingsCard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders loaded settings with URL and username', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: 'http://turntable.local:3000',
|
||||
username: 'render-user',
|
||||
hasPassword: true,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByDisplayValue('http://turntable.local:3000')).toBeDefined()
|
||||
expect(screen.getByDisplayValue('render-user')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('disables inputs and displays badge when configured via environment', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: true,
|
||||
url: 'http://env-turntable:3000',
|
||||
username: 'env-user',
|
||||
hasPassword: true,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Configured via Environment')).toBeDefined()
|
||||
const urlInput = screen.getByDisplayValue('http://env-turntable:3000') as HTMLInputElement
|
||||
expect(urlInput.disabled).toBe(true)
|
||||
const saveBtn = screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement
|
||||
expect(saveBtn.disabled).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('saves updated settings', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: '',
|
||||
username: '',
|
||||
hasPassword: false,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
mockPutSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
...settings,
|
||||
url: 'http://new-turntable:3000',
|
||||
username: 'alice',
|
||||
}),
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText('Server URL')).toBeDefined()
|
||||
})
|
||||
|
||||
const urlInput = screen.getByLabelText('Server URL')
|
||||
fireEvent.change(urlInput, { target: { value: 'http://new-turntable:3000' } })
|
||||
|
||||
const usernameInput = screen.getByLabelText('Username')
|
||||
fireEvent.change(usernameInput, { target: { value: 'alice' } })
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: 'Save' })
|
||||
fireEvent.click(saveBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPutSettings).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { teamId: 'team-123' },
|
||||
json: expect.objectContaining({
|
||||
url: 'http://new-turntable:3000',
|
||||
username: 'alice',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('tests connection successfully and displays version info', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: 'http://turntable:3000',
|
||||
username: 'user',
|
||||
hasPassword: false,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
mockTestSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
ok: true,
|
||||
version: '1.0.0',
|
||||
blender: '5.2.0',
|
||||
}),
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByDisplayValue('http://turntable:3000')).toBeDefined()
|
||||
})
|
||||
|
||||
const testBtn = screen.getByRole('button', { name: 'Test Connection' })
|
||||
fireEvent.click(testBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockTestSettings).toHaveBeenCalled()
|
||||
expect(screen.getByText(/Connection successful \(v1\.0\.0, Blender 5\.2\.0\)/)).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('tests connection and displays error when unreachable', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: 'http://invalid-url:3000',
|
||||
username: '',
|
||||
hasPassword: false,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
mockTestSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
ok: false,
|
||||
error: 'ECONNREFUSED',
|
||||
}),
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByDisplayValue('http://invalid-url:3000')).toBeDefined()
|
||||
})
|
||||
|
||||
const testBtn = screen.getByRole('button', { name: 'Test Connection' })
|
||||
fireEvent.click(testBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Connection failed: ECONNREFUSED/)).toBeDefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,243 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
CardFooter,
|
||||
} from '@/ui/components/ui/card'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Loader2, CheckCircle2, XCircle, Info } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface TurntableSettingsCardProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export const TurntableSettingsCard: React.FC<TurntableSettingsCardProps> = ({ teamId }) => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [url, setUrl] = useState('')
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [testResult, setTestResult] = useState<{
|
||||
ok: boolean
|
||||
version?: string
|
||||
blender?: string
|
||||
error?: string
|
||||
} | null>(null)
|
||||
const [isTesting, setIsTesting] = useState(false)
|
||||
|
||||
const { data: turntableSettings, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'turntable-settings'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId']['turntable-settings'].$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to load turntable settings')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (turntableSettings) {
|
||||
setUrl(turntableSettings.url || '')
|
||||
setUsername(turntableSettings.username || '')
|
||||
setPassword('')
|
||||
setTestResult(null)
|
||||
}
|
||||
}, [turntableSettings])
|
||||
|
||||
const { mutateAsync: saveSettings, isPending: isSaving } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId']['turntable-settings'].$put({
|
||||
param: { teamId },
|
||||
json: {
|
||||
url: url || undefined,
|
||||
username: username || undefined,
|
||||
password: password || undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
throw new Error(
|
||||
(err as { message?: string }).message || 'Failed to update turntable settings',
|
||||
)
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'turntable-settings'],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
})
|
||||
toast.success(m.settings_updated())
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message || m.failed_update_settings())
|
||||
},
|
||||
})
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
setIsTesting(true)
|
||||
setTestResult(null)
|
||||
try {
|
||||
const res = await client.api.teams[':teamId']['turntable-settings'].test.$post({
|
||||
param: { teamId },
|
||||
json: {
|
||||
url: url || undefined,
|
||||
username: username || undefined,
|
||||
password: password || undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
const errorMsg = (err as { message?: string }).message || 'Request failed'
|
||||
setTestResult({ ok: false, error: errorMsg })
|
||||
toast.error(m.turntable_connection_failed())
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
setTestResult(data)
|
||||
if (data.ok) {
|
||||
toast.success(m.turntable_connection_success())
|
||||
} else {
|
||||
toast.error(data.error || m.turntable_connection_failed())
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
setTestResult({ ok: false, error: msg })
|
||||
toast.error(m.turntable_connection_failed())
|
||||
} finally {
|
||||
setIsTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const isEnvConfigured = Boolean(turntableSettings?.isEnvConfigured)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>{m.turntable_settings()}</CardTitle>
|
||||
{isEnvConfigured && (
|
||||
<Badge variant="secondary" className="gap-1">
|
||||
<Info className="w-3 h-3" />
|
||||
{m.turntable_env_configured()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardDescription>{m.turntable_settings_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-6">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="turntable-url" className="text-sm font-medium">
|
||||
{m.turntable_server_url()}
|
||||
</label>
|
||||
<Input
|
||||
id="turntable-url"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder={m.turntable_server_url_placeholder()}
|
||||
disabled={isEnvConfigured || isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="turntable-username" className="text-sm font-medium">
|
||||
{m.turntable_username()}
|
||||
</label>
|
||||
<Input
|
||||
id="turntable-username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="admin"
|
||||
disabled={isEnvConfigured || isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="turntable-password" className="text-sm font-medium">
|
||||
{m.turntable_password()}
|
||||
</label>
|
||||
<Input
|
||||
id="turntable-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={
|
||||
turntableSettings?.hasPassword ? m.turntable_password_placeholder() : '••••••••'
|
||||
}
|
||||
disabled={isEnvConfigured || isSaving}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{testResult && (
|
||||
<div
|
||||
className={`flex items-center gap-2 p-3 rounded-lg border text-sm ${
|
||||
testResult.ok
|
||||
? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
|
||||
: 'border-destructive/30 bg-destructive/10 text-destructive'
|
||||
}`}
|
||||
>
|
||||
{testResult.ok ? (
|
||||
<>
|
||||
<CheckCircle2 className="w-4 h-4 shrink-0" />
|
||||
<span>
|
||||
{m.turntable_connection_success()} (v{testResult.version || 'unknown'}
|
||||
{testResult.blender ? `, Blender ${testResult.blender}` : ''})
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<XCircle className="w-4 h-4 shrink-0" />
|
||||
<span>
|
||||
{m.turntable_connection_failed()}: {testResult.error}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-between border-t border-border pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleTestConnection}
|
||||
disabled={isLoading || isTesting || !url.trim()}
|
||||
>
|
||||
{isTesting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
{isTesting ? m.turntable_testing() : m.turntable_test_connection()}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => saveSettings()}
|
||||
disabled={isEnvConfigured || isSaving || isLoading}
|
||||
>
|
||||
{isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
{m.save()}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { FileTypeDefinition } from '../types'
|
||||
import ModelViewer from './model-viewer'
|
||||
|
||||
export function secondToDegree(second: number): number {
|
||||
const frameIndex = Math.min(Math.max(0, Math.round(second * 6)), 23)
|
||||
return (frameIndex * 15) % 360
|
||||
}
|
||||
|
||||
export const modelTypeDefinition: FileTypeDefinition = {
|
||||
id: '3d',
|
||||
name: '3D Model',
|
||||
match: (file) => file.proxyType === '3d',
|
||||
viewer: ModelViewer,
|
||||
commentsConfig: {
|
||||
hasTimestamp: true,
|
||||
hasAnnotations: true,
|
||||
formatTimestamp: (second: number) => {
|
||||
const deg = secondToDegree(second)
|
||||
return `${deg}°`
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import React from 'react'
|
||||
import { Play, Pause, RotateCcw, Maximize, Minimize, Minus, Plus, Download } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { RulerSlider } from './ruler-slider'
|
||||
|
||||
export interface ModelControlBarProps {
|
||||
isPlaying: boolean
|
||||
currentDegree: number
|
||||
zoom: number
|
||||
isFullScreen: boolean
|
||||
allowDownload?: boolean
|
||||
downloadUrl?: string
|
||||
fileName?: string
|
||||
togglePlay: () => void
|
||||
onSeekDegree: (degree: number) => void
|
||||
onResetRotation: () => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
onZoomReset: () => void
|
||||
toggleFullScreen: () => void
|
||||
}
|
||||
|
||||
export const ModelControlBar: React.FC<ModelControlBarProps> = ({
|
||||
isPlaying,
|
||||
currentDegree,
|
||||
zoom,
|
||||
isFullScreen,
|
||||
allowDownload = true,
|
||||
downloadUrl,
|
||||
fileName,
|
||||
togglePlay,
|
||||
onSeekDegree,
|
||||
onResetRotation,
|
||||
onZoomChange,
|
||||
onZoomReset,
|
||||
toggleFullScreen,
|
||||
}) => {
|
||||
const handleDownload = () => {
|
||||
if (!downloadUrl) return
|
||||
const a = document.createElement('a')
|
||||
a.href = downloadUrl
|
||||
a.download = fileName || 'model.glb'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
}
|
||||
|
||||
const handleStepDegree = (delta: number) => {
|
||||
const next = (((currentDegree + delta) % 360) + 360) % 360
|
||||
onSeekDegree(next)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'transition-all duration-300 ease-in-out z-20 text-foreground',
|
||||
isFullScreen
|
||||
? 'absolute bottom-0 left-0 right-0 px-4 py-2.5 bg-card/90 backdrop-blur-md border-t border-border'
|
||||
: 'relative w-full bg-card border-t border-border px-4 py-2.5 z-10 transition-colors duration-200',
|
||||
)}
|
||||
>
|
||||
{/* Unified Single Row Controls */}
|
||||
<div className="flex items-center justify-between text-foreground gap-4">
|
||||
{/* Left Side: Play/Pause, Degree Readout, Reset Rotation */}
|
||||
<div className="flex items-center gap-3 justify-start min-w-0 flex-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={togglePlay}
|
||||
aria-label={isPlaying ? 'Pause' : 'Play'}
|
||||
className="hover:text-primary transition-colors shrink-0"
|
||||
data-testid="play-toggle"
|
||||
data-playing={isPlaying}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="w-5 h-5 fill-current" />
|
||||
) : (
|
||||
<Play className="w-5 h-5 fill-current" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div
|
||||
className="flex items-center text-sm font-medium tabular-nums select-none shrink-0"
|
||||
data-testid="degree-readout"
|
||||
>
|
||||
<span className="text-muted-foreground font-mono">{currentDegree}° / 360°</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResetRotation}
|
||||
title="Reset to 0°"
|
||||
aria-label="Reset rotation to 0°"
|
||||
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Center: RulerSlider with minus & plus buttons */}
|
||||
<div className="flex items-center gap-1.5 w-full max-w-[320px] justify-center mx-auto shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStepDegree(-15)}
|
||||
title="Decrease 15°"
|
||||
aria-label="Decrease 15°"
|
||||
className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
data-testid="ruler-step-minus"
|
||||
>
|
||||
<Minus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
<RulerSlider
|
||||
currentDegree={currentDegree}
|
||||
onChange={onSeekDegree}
|
||||
className="flex-1 min-w-[140px]"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStepDegree(15)}
|
||||
title="Increase 15°"
|
||||
aria-label="Increase 15°"
|
||||
className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
data-testid="ruler-step-plus"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Right Side: Zoom controls, Download, Fullscreen */}
|
||||
<div className="flex items-center gap-2 justify-end min-w-0 flex-1">
|
||||
{/* Zoom controls */}
|
||||
<div className="flex items-center gap-1 bg-muted/60 rounded-lg p-0.5 border border-border/40 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onZoomChange(Math.max(0.2, zoom - 0.2))}
|
||||
aria-label="Zoom out"
|
||||
className="p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Minus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onZoomReset}
|
||||
aria-label="Reset zoom"
|
||||
className="px-1.5 py-0.5 text-[11px] font-mono text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{Math.round(zoom * 100)}%
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onZoomChange(Math.min(5, zoom + 0.2))}
|
||||
aria-label="Zoom in"
|
||||
className="p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Download */}
|
||||
{allowDownload && downloadUrl && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDownload}
|
||||
title="Download asset"
|
||||
aria-label="Download asset"
|
||||
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Fullscreen */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleFullScreen}
|
||||
title={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
|
||||
aria-label={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
|
||||
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
>
|
||||
{isFullScreen ? <Minimize className="w-4 h-4" /> : <Maximize className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import React, { createRef } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ModelViewer } from './model-viewer'
|
||||
import type { MediaController } from '../types'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
vi.mock('@/ui/components/drawing-canvas', () => ({
|
||||
default: () => <div data-testid="drawing-canvas" />,
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/paraglide/messages.js', () => ({
|
||||
m: new Proxy({}, { get: () => () => '' }),
|
||||
}))
|
||||
|
||||
class MockResizeObserver {
|
||||
observe = vi.fn(() => {
|
||||
// Immediate callback with mock size
|
||||
this.callback(
|
||||
[{ contentRect: { width: 800, height: 600 } } as unknown as ResizeObserverEntry],
|
||||
this,
|
||||
)
|
||||
})
|
||||
unobserve = vi.fn()
|
||||
disconnect = vi.fn()
|
||||
constructor(private callback: ResizeObserverCallback) {}
|
||||
}
|
||||
|
||||
const mockAsset: AssetInfo = {
|
||||
id: 'asset-3d-1',
|
||||
name: 'robot.glb',
|
||||
proxyType: '3d',
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
type: 'file',
|
||||
sizeByte: 1024,
|
||||
fileCount: 1,
|
||||
status: 'processed',
|
||||
projectId: 'proj-1',
|
||||
media: {
|
||||
videoPreview: {
|
||||
url: 'https://example.com/robot-turntable.mp4',
|
||||
},
|
||||
original: {
|
||||
key: 'files/robot.glb',
|
||||
},
|
||||
metadata: {
|
||||
originalWidth: 1080,
|
||||
originalHeight: 1080,
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
thumbnailUrl: 'https://example.com/robot-poster.webp',
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
describe('ModelViewer', () => {
|
||||
beforeEach(() => {
|
||||
global.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver
|
||||
vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(() => Promise.resolve())
|
||||
vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('renders model viewer container, surface, video, and control bar', () => {
|
||||
const { getByTestId, getByText } = render(<ModelViewer file={mockAsset} />)
|
||||
|
||||
expect(getByTestId('model-viewer-container')).toBeDefined()
|
||||
expect(getByTestId('model-viewer-surface')).toBeDefined()
|
||||
expect(getByTestId('drawing-canvas')).toBeDefined()
|
||||
// Control bar shows 0° / 360° initially
|
||||
expect(getByText(/0°\s*\/\s*360°/)).toBeDefined()
|
||||
})
|
||||
|
||||
it('toggles play/pause via spacebar hotkey', () => {
|
||||
const onPlay = vi.fn()
|
||||
const onPause = vi.fn()
|
||||
const { container } = render(<ModelViewer file={mockAsset} onPlay={onPlay} onPause={onPause} />)
|
||||
|
||||
const video = container.querySelector('video')
|
||||
expect(video).toBeDefined()
|
||||
|
||||
// Space key triggers togglePlay
|
||||
fireEvent.keyDown(window, { key: ' ' })
|
||||
expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
|
||||
|
||||
// Simulate video playing event
|
||||
if (video) {
|
||||
fireEvent.play(video)
|
||||
expect(onPlay).toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('seeks frames via arrow hotkeys', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
render(<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />)
|
||||
|
||||
// Press ArrowRight -> advance 1 frame (15 deg = 1/6 sec = ~0.1667)
|
||||
fireEvent.keyDown(window, { key: 'ArrowRight' })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
|
||||
|
||||
// Press ArrowRight second time -> advance to frame 2 (30 deg = 2/6 sec)
|
||||
fireEvent.keyDown(window, { key: 'ArrowRight' })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
|
||||
|
||||
// Press ArrowLeft -> back 1 frame (frame 1 = 1/6 sec)
|
||||
fireEvent.keyDown(window, { key: 'ArrowLeft' })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
|
||||
|
||||
// Press ArrowLeft -> back 1 frame (frame 0 = 0 sec)
|
||||
fireEvent.keyDown(window, { key: 'ArrowLeft' })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('handles pointer dragging to rotate 3D asset', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { getByTestId } = render(<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />)
|
||||
|
||||
const surface = getByTestId('model-viewer-surface')
|
||||
// Mock setPointerCapture / releasePointerCapture
|
||||
surface.setPointerCapture = vi.fn()
|
||||
surface.releasePointerCapture = vi.fn()
|
||||
|
||||
// Start drag at x = 100
|
||||
fireEvent.pointerDown(surface, { clientX: 100, button: 0, pointerId: 1 })
|
||||
expect(surface.setPointerCapture).toHaveBeenCalledWith(1)
|
||||
|
||||
// Move right by 24px (+2 frames = +30 deg)
|
||||
fireEvent.pointerMove(surface, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
|
||||
|
||||
// Release drag
|
||||
fireEvent.pointerUp(surface, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(surface.releasePointerCapture).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('exposes imperative media controller via ref', () => {
|
||||
const ref = createRef<MediaController>()
|
||||
render(<ModelViewer ref={ref} file={mockAsset} />)
|
||||
|
||||
expect(ref.current).toBeDefined()
|
||||
expect(ref.current?.getDuration?.()).toBe(4)
|
||||
expect(typeof ref.current?.getCurrentTime?.()).toBe('number')
|
||||
|
||||
ref.current?.play()
|
||||
expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
|
||||
|
||||
ref.current?.pause()
|
||||
expect(HTMLMediaElement.prototype.pause).toHaveBeenCalled()
|
||||
|
||||
ref.current?.seekTo(1) // 1 second -> frame 6 -> 1 second
|
||||
expect(ref.current?.getCurrentTime?.()).toBeDefined()
|
||||
})
|
||||
|
||||
it('resets rotation to 0° when reset button is clicked', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { getByRole } = render(
|
||||
<ModelViewer file={mockAsset} startTime={1} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
|
||||
// Reset rotation button has aria-label 'Reset rotation to 0°'
|
||||
const resetBtn = getByRole('button', { name: /Reset rotation/i })
|
||||
fireEvent.click(resetBtn)
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('renders children alongside viewer surface when provided', () => {
|
||||
const { getByTestId } = render(
|
||||
<ModelViewer file={mockAsset}>
|
||||
<div data-testid="test-sidebar">Sidebar</div>
|
||||
</ModelViewer>,
|
||||
)
|
||||
|
||||
expect(getByTestId('test-sidebar')).toBeDefined()
|
||||
expect(getByTestId('model-viewer-surface')).toBeDefined()
|
||||
})
|
||||
|
||||
it('steps rotation by 15° forward and backward via plus and minus buttons', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { getByTestId } = render(
|
||||
<ModelViewer file={mockAsset} startTime={0} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
|
||||
const plusBtn = getByTestId('ruler-step-plus')
|
||||
const minusBtn = getByTestId('ruler-step-minus')
|
||||
|
||||
// Click plus button at 0° -> seeks to 15° (frame 1, 1/6s)
|
||||
fireEvent.click(plusBtn)
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
|
||||
|
||||
// Click minus button at 0° (or current) -> wraps backward
|
||||
fireEvent.click(minusBtn)
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,400 @@
|
||||
import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
|
||||
import { AlertCircle, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import DrawingCanvas from '@/ui/components/drawing-canvas'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import type { FileViewerProps, MediaController } from '../types'
|
||||
import { centeredPan, fitScale, zoomAtPoint } from '../pan-zoom'
|
||||
import { ModelControlBar } from './model-control-bar'
|
||||
import { secondToDegree } from './index'
|
||||
|
||||
const TOTAL_FRAMES = 24
|
||||
const FPS = 6
|
||||
const FRAME_DURATION = 1 / FPS
|
||||
|
||||
export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
(
|
||||
{
|
||||
file: data,
|
||||
onPlay,
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
children,
|
||||
allowDownload = true,
|
||||
autoPlay = false,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const rootRef = useRef<HTMLDivElement | null>(null)
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null)
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
|
||||
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [currentTime, setCurrentTime] = useState(startTime || 0)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isFullScreen, setIsFullScreen] = useState(false)
|
||||
|
||||
// Pan & Zoom
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [pan, setPan] = useState({ x: 0, y: 0 })
|
||||
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
|
||||
|
||||
// Drag-to-rotate state
|
||||
const [isDraggingRotation, setIsDraggingRotation] = useState(false)
|
||||
const dragStartRef = useRef<{ clientX: number; frame: number }>({ clientX: 0, frame: 0 })
|
||||
|
||||
const videoSrc = data.media?.videoPreview?.url || data.media?.videoTranscodes?.[0]?.url || ''
|
||||
|
||||
const posterUrl = data.preview?.thumbnailUrl || undefined
|
||||
const downloadUrl = data.media?.original?.key ? videoSrc : undefined
|
||||
|
||||
// Drawing Annotation store
|
||||
const {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
addAnnotation,
|
||||
annotations: draftAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
|
||||
const isDrawingMode = isDrawing
|
||||
|
||||
const mediaWidth = data.media?.metadata?.originalWidth || 1080
|
||||
const mediaHeight = data.media?.metadata?.originalHeight || 1080
|
||||
|
||||
// Resize observer
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const entry = entries[0]
|
||||
if (entry) {
|
||||
setContainerSize({
|
||||
width: entry.contentRect.width,
|
||||
height: entry.contentRect.height,
|
||||
})
|
||||
}
|
||||
})
|
||||
observer.observe(containerRef.current)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
// Initial scale and center
|
||||
useEffect(() => {
|
||||
if (containerSize.width > 0 && containerSize.height > 0 && !hasManuallyZoomed) {
|
||||
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
|
||||
setZoom(scale)
|
||||
setPan(
|
||||
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
|
||||
)
|
||||
}
|
||||
}, [containerSize, mediaWidth, mediaHeight, hasManuallyZoomed])
|
||||
|
||||
// Current angle
|
||||
const currentDegree = secondToDegree(currentTime)
|
||||
|
||||
// Seek helper
|
||||
const seekToFrame = useCallback(
|
||||
(frameIndex: number) => {
|
||||
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
|
||||
const targetSec = normalizedFrame * FRAME_DURATION
|
||||
if (videoRef.current) {
|
||||
videoRef.current.currentTime = targetSec
|
||||
}
|
||||
setCurrentTime(targetSec)
|
||||
onTimeUpdate?.(targetSec)
|
||||
},
|
||||
[onTimeUpdate],
|
||||
)
|
||||
|
||||
const seekToDegree = useCallback(
|
||||
(degree: number) => {
|
||||
const frame = Math.round((((degree % 360) + 360) % 360) / 15) % TOTAL_FRAMES
|
||||
seekToFrame(frame)
|
||||
},
|
||||
[seekToFrame],
|
||||
)
|
||||
|
||||
// Play / Pause toggle
|
||||
const togglePlay = useCallback(() => {
|
||||
const video = videoRef.current
|
||||
if (!video) return
|
||||
if (video.paused || video.ended) {
|
||||
video.play().catch(() => {})
|
||||
} else {
|
||||
video.pause()
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Video Imperative Controller
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
play: () => {
|
||||
videoRef.current?.play().catch(() => {})
|
||||
},
|
||||
pause: () => {
|
||||
videoRef.current?.pause()
|
||||
},
|
||||
seekTo: (second: number) => {
|
||||
seekToFrame(Math.floor(second * FPS))
|
||||
},
|
||||
getCurrentTime: () => videoRef.current?.currentTime || 0,
|
||||
getDuration: () => 4,
|
||||
}),
|
||||
[seekToFrame],
|
||||
)
|
||||
|
||||
// Keyboard Hotkeys
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
const active = document.activeElement
|
||||
if (
|
||||
active &&
|
||||
(active.tagName === 'INPUT' ||
|
||||
active.tagName === 'TEXTAREA' ||
|
||||
(active instanceof HTMLElement && active.isContentEditable))
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (e.key === ' ') {
|
||||
e.preventDefault()
|
||||
togglePlay()
|
||||
} else if (e.key === 'ArrowLeft') {
|
||||
e.preventDefault()
|
||||
const currentFrame = Math.round(currentTime * FPS)
|
||||
seekToFrame(currentFrame - 1)
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault()
|
||||
const currentFrame = Math.round(currentTime * FPS)
|
||||
seekToFrame(currentFrame + 1)
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [currentTime, seekToFrame, togglePlay])
|
||||
|
||||
// Pointer events for Drag-to-Rotate
|
||||
const handleViewerPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (isDrawingMode || e.button !== 0) return
|
||||
const target = e.currentTarget
|
||||
target.setPointerCapture(e.pointerId)
|
||||
videoRef.current?.pause()
|
||||
|
||||
const currentFrame = Math.floor(currentTime * FPS)
|
||||
dragStartRef.current = {
|
||||
clientX: e.clientX,
|
||||
frame: currentFrame,
|
||||
}
|
||||
setIsDraggingRotation(true)
|
||||
}
|
||||
|
||||
const handleViewerPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDraggingRotation) return
|
||||
const deltaX = e.clientX - dragStartRef.current.clientX
|
||||
// 12px drag movement corresponds to 1 frame (15°)
|
||||
const deltaFrames = Math.round(deltaX / 12)
|
||||
seekToFrame(dragStartRef.current.frame + deltaFrames)
|
||||
}
|
||||
|
||||
const handleViewerPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDraggingRotation) return
|
||||
setIsDraggingRotation(false)
|
||||
try {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId)
|
||||
} catch {
|
||||
// pointer may already be released
|
||||
}
|
||||
}
|
||||
|
||||
// Fullscreen toggle
|
||||
const toggleFullScreen = () => {
|
||||
if (!rootRef.current) return
|
||||
if (!document.fullscreenElement) {
|
||||
rootRef.current.requestFullscreen().catch(() => {})
|
||||
} else {
|
||||
document.exitFullscreen().catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const onFsChange = () => {
|
||||
setIsFullScreen(Boolean(document.fullscreenElement))
|
||||
}
|
||||
document.addEventListener('fullscreenchange', onFsChange)
|
||||
return () => document.removeEventListener('fullscreenchange', onFsChange)
|
||||
}, [])
|
||||
|
||||
const handleZoomChange = (newZoom: number) => {
|
||||
setHasManuallyZoomed(true)
|
||||
const next = zoomAtPoint(
|
||||
zoom,
|
||||
pan,
|
||||
newZoom / zoom,
|
||||
containerSize.width / 2,
|
||||
containerSize.height / 2,
|
||||
)
|
||||
setZoom(next.zoom)
|
||||
setPan(next.pan)
|
||||
}
|
||||
|
||||
const handleZoomReset = () => {
|
||||
setHasManuallyZoomed(false)
|
||||
if (containerSize.width > 0 && containerSize.height > 0) {
|
||||
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
|
||||
setZoom(scale)
|
||||
setPan(
|
||||
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
data-testid="model-viewer-container"
|
||||
className={cn(
|
||||
'group shadow-2xl font-sans select-none flex flex-col mx-auto relative',
|
||||
isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
|
||||
)}
|
||||
>
|
||||
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
|
||||
{/* Render Carousel/Sidebar here if not fullscreen */}
|
||||
{!isFullScreen && children}
|
||||
|
||||
{/* Interactive Drag Rotation Surface & Model Area */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
data-testid="model-viewer-surface"
|
||||
onPointerDown={handleViewerPointerDown}
|
||||
onPointerMove={handleViewerPointerMove}
|
||||
onPointerUp={handleViewerPointerUp}
|
||||
onPointerCancel={handleViewerPointerUp}
|
||||
className={cn(
|
||||
'flex-1 bg-black relative flex items-center justify-center overflow-hidden min-h-0 touch-none',
|
||||
isDrawingMode
|
||||
? 'cursor-crosshair'
|
||||
: isDraggingRotation
|
||||
? 'cursor-grabbing'
|
||||
: 'cursor-grab',
|
||||
)}
|
||||
>
|
||||
{/* Centered Scaled Media Wrapper */}
|
||||
<div
|
||||
className="absolute pointer-events-none"
|
||||
style={{
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: mediaWidth,
|
||||
height: mediaHeight,
|
||||
transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
|
||||
transformOrigin: '0 0',
|
||||
}}
|
||||
>
|
||||
{videoSrc && (
|
||||
<video
|
||||
ref={videoRef}
|
||||
src={videoSrc}
|
||||
poster={posterUrl}
|
||||
playsInline
|
||||
loop
|
||||
muted
|
||||
autoPlay={autoPlay}
|
||||
preload="auto"
|
||||
onLoadedData={() => {
|
||||
setIsLoading(false)
|
||||
if (startTime && startTime > 0) {
|
||||
seekToFrame(Math.floor(startTime * FPS))
|
||||
}
|
||||
}}
|
||||
onPlay={() => {
|
||||
setIsPlaying(true)
|
||||
onPlay?.()
|
||||
}}
|
||||
onPause={() => {
|
||||
setIsPlaying(false)
|
||||
onPause?.()
|
||||
}}
|
||||
onTimeUpdate={() => {
|
||||
if (videoRef.current && !isDraggingRotation) {
|
||||
setCurrentTime(videoRef.current.currentTime)
|
||||
onTimeUpdate?.(videoRef.current.currentTime)
|
||||
}
|
||||
}}
|
||||
onError={() => {
|
||||
setIsLoading(false)
|
||||
setError('Failed to load turntable video')
|
||||
}}
|
||||
className="w-full h-full block object-contain pointer-events-none"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Drawing Canvas Overlay */}
|
||||
{containerSize.width > 0 && containerSize.height > 0 && (
|
||||
<DrawingCanvas
|
||||
width={containerSize.width}
|
||||
height={containerSize.height}
|
||||
mediaDimensions={{
|
||||
width: mediaWidth,
|
||||
height: mediaHeight,
|
||||
}}
|
||||
annotations={displayAnnotations}
|
||||
scale={zoom}
|
||||
offset={pan}
|
||||
className="absolute inset-0 pointer-events-none"
|
||||
isDrawing={isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={addAnnotation}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Loading Spinner */}
|
||||
{isLoading && !error && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
|
||||
<div className="w-14 h-14 bg-background/80 backdrop-blur-md rounded-full flex items-center justify-center border border-border shadow-lg">
|
||||
<Loader2 className="w-7 h-7 text-primary animate-spin" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 text-destructive z-10 bg-background/90 p-4 text-center">
|
||||
<AlertCircle className="w-10 h-10" />
|
||||
<p className="text-sm font-medium">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Full-width docked bottom control bar */}
|
||||
<ModelControlBar
|
||||
isPlaying={isPlaying}
|
||||
currentDegree={currentDegree}
|
||||
zoom={zoom}
|
||||
isFullScreen={isFullScreen}
|
||||
allowDownload={allowDownload}
|
||||
downloadUrl={downloadUrl}
|
||||
fileName={data.name}
|
||||
togglePlay={togglePlay}
|
||||
onSeekDegree={seekToDegree}
|
||||
onResetRotation={() => seekToDegree(0)}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
ModelViewer.displayName = 'ModelViewer'
|
||||
export default ModelViewer
|
||||
@@ -0,0 +1,141 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RulerSlider } from './ruler-slider'
|
||||
|
||||
describe('RulerSlider', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders slider with fixed center indicator and aria values', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole, getByTestId, queryByTestId } = render(
|
||||
<RulerSlider currentDegree={90} onChange={onChange} />,
|
||||
)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
expect(slider).toBeDefined()
|
||||
expect(slider.getAttribute('aria-valuenow')).toBe('90')
|
||||
expect(slider.getAttribute('aria-valuetext')).toBe('90°')
|
||||
|
||||
// Fixed center indicator exists
|
||||
expect(getByTestId('ruler-center-indicator')).toBeDefined()
|
||||
|
||||
// Tooltip should not be rendered while not dragging
|
||||
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders ticks at 15° intervals, longer at 60° intervals, and no numeric tick labels', () => {
|
||||
const onChange = vi.fn()
|
||||
const { container, getAllByTestId } = render(
|
||||
<RulerSlider currentDegree={0} onChange={onChange} />,
|
||||
)
|
||||
|
||||
// Major ticks at multiples of 60°
|
||||
const ticks0 = getAllByTestId('tick-0')
|
||||
expect(ticks0.length).toBeGreaterThan(0)
|
||||
expect(ticks0[0]?.getAttribute('data-major')).toBe('true')
|
||||
|
||||
const ticks60 = getAllByTestId('tick-60')
|
||||
expect(ticks60.length).toBeGreaterThan(0)
|
||||
expect(ticks60[0]?.getAttribute('data-major')).toBe('true')
|
||||
|
||||
// Regular tick at 15° is not major
|
||||
const ticks15 = getAllByTestId('tick-15')
|
||||
expect(ticks15.length).toBeGreaterThan(0)
|
||||
expect(ticks15[0]?.getAttribute('data-major')).toBe('false')
|
||||
|
||||
// No numeric degree text inside the slider track
|
||||
expect(container.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('shows tooltip displaying degree while dragging and hides on pointer up', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole, getByTestId, queryByTestId } = render(
|
||||
<RulerSlider currentDegree={45} onChange={onChange} />,
|
||||
)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
slider.setPointerCapture = vi.fn()
|
||||
slider.releasePointerCapture = vi.fn()
|
||||
|
||||
// Initially no tooltip
|
||||
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
|
||||
|
||||
// Start dragging
|
||||
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
|
||||
const tooltip = getByTestId('ruler-slider-tooltip')
|
||||
expect(tooltip).toBeDefined()
|
||||
expect(tooltip.textContent).toBe('45°')
|
||||
|
||||
// Release drag
|
||||
fireEvent.pointerUp(slider, { clientX: 100, button: 0, pointerId: 1 })
|
||||
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('handles keyboard navigation with 15 degree stepping and wrapping', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole } = render(<RulerSlider currentDegree={45} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
|
||||
// 45 + 15 = 60
|
||||
fireEvent.keyDown(slider, { key: 'ArrowRight' })
|
||||
expect(onChange).toHaveBeenCalledWith(60)
|
||||
|
||||
// 45 - 15 = 30
|
||||
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
|
||||
expect(onChange).toHaveBeenCalledWith(30)
|
||||
|
||||
// Home -> 0
|
||||
fireEvent.keyDown(slider, { key: 'Home' })
|
||||
expect(onChange).toHaveBeenCalledWith(0)
|
||||
|
||||
// End -> 345
|
||||
fireEvent.keyDown(slider, { key: 'End' })
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
})
|
||||
|
||||
it('wraps around 0° and 360° on keyboard navigation', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole, rerender } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
|
||||
// 0 - 15 wraps to 345
|
||||
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
|
||||
// 345 + 15 wraps to 0
|
||||
rerender(<RulerSlider currentDegree={345} onChange={onChange} />)
|
||||
fireEvent.keyDown(slider, { key: 'ArrowRight' })
|
||||
expect(onChange).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('handles pointer drag interaction with 15 degree snapping and wrapping', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
slider.setPointerCapture = vi.fn()
|
||||
slider.releasePointerCapture = vi.fn()
|
||||
|
||||
// Start drag at x = 100
|
||||
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
|
||||
expect(slider.setPointerCapture).toHaveBeenCalledWith(1)
|
||||
|
||||
// Drag left by 24px (15° forward: deltaX = -24 => deltaDeg = +15)
|
||||
fireEvent.pointerMove(slider, { clientX: 76, button: 0, pointerId: 1 })
|
||||
expect(onChange).toHaveBeenCalledWith(15)
|
||||
|
||||
// Drag right by 24px from origin (x=124 => deltaX = +24 => deltaDeg = -15 => wraps to 345)
|
||||
fireEvent.pointerMove(slider, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
|
||||
// Release pointer
|
||||
fireEvent.pointerUp(slider, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(slider.releasePointerCapture).toHaveBeenCalledWith(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
import React, { useCallback, useRef, useState } from 'react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface RulerSliderProps {
|
||||
currentDegree: number // 0 to 360 (or normalized modulo 360)
|
||||
onChange: (degree: number) => void
|
||||
className?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const PX_PER_DEGREE = 1.6 // 24px per 15° step
|
||||
const STEP = 15
|
||||
const BUFFER_DEGREE = 240 // Render buffer on each side of the active degree
|
||||
|
||||
export const RulerSlider: React.FC<RulerSliderProps> = ({
|
||||
currentDegree,
|
||||
onChange,
|
||||
className,
|
||||
disabled = false,
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [dragDegree, setDragDegree] = useState<number | null>(null)
|
||||
const dragStartRef = useRef<{ clientX: number; startDegree: number }>({
|
||||
clientX: 0,
|
||||
startDegree: 0,
|
||||
})
|
||||
|
||||
const normalizedDegree = (((Math.round(currentDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
const activeDegree = isDragging && dragDegree !== null ? dragDegree : normalizedDegree
|
||||
const displayedDegree = (((Math.round(activeDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (disabled || e.button !== 0) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
const target = containerRef.current
|
||||
if (!target) return
|
||||
target.setPointerCapture(e.pointerId)
|
||||
|
||||
dragStartRef.current = {
|
||||
clientX: e.clientX,
|
||||
startDegree: currentDegree,
|
||||
}
|
||||
setIsDragging(true)
|
||||
setDragDegree(currentDegree)
|
||||
},
|
||||
[disabled, currentDegree],
|
||||
)
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDragging || disabled) return
|
||||
const deltaX = e.clientX - dragStartRef.current.clientX
|
||||
// Dragging left (deltaX < 0) rotates turntable forward (angle increases)
|
||||
const nextRawDegree = dragStartRef.current.startDegree - deltaX / PX_PER_DEGREE
|
||||
const snapped = (((Math.round(nextRawDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
setDragDegree(snapped)
|
||||
onChange(snapped)
|
||||
},
|
||||
[isDragging, disabled, onChange],
|
||||
)
|
||||
|
||||
const handlePointerUp = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDragging) return
|
||||
setIsDragging(false)
|
||||
if (dragDegree !== null) {
|
||||
onChange(dragDegree)
|
||||
}
|
||||
setDragDegree(null)
|
||||
try {
|
||||
containerRef.current?.releasePointerCapture(e.pointerId)
|
||||
} catch {
|
||||
// pointer may have already been released
|
||||
}
|
||||
},
|
||||
[isDragging, dragDegree, onChange],
|
||||
)
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (disabled) return
|
||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange((((normalizedDegree - STEP) % 360) + 360) % 360)
|
||||
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange((normalizedDegree + STEP) % 360)
|
||||
} else if (e.key === 'Home') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange(0)
|
||||
} else if (e.key === 'End') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange(345)
|
||||
}
|
||||
},
|
||||
[disabled, normalizedDegree, onChange],
|
||||
)
|
||||
|
||||
// Compute visible ticks dynamically around activeDegree for seamless cyclic looping
|
||||
const minTickIndex = Math.floor((activeDegree - BUFFER_DEGREE) / STEP)
|
||||
const maxTickIndex = Math.ceil((activeDegree + BUFFER_DEGREE) / STEP)
|
||||
const ticks: number[] = []
|
||||
for (let i = minTickIndex; i <= maxTickIndex; i++) {
|
||||
ticks.push(i * STEP)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
role="slider"
|
||||
aria-label="Turntable angle"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={360}
|
||||
aria-valuenow={displayedDegree}
|
||||
aria-valuetext={`${displayedDegree}°`}
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerUp}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={cn(
|
||||
'relative select-none cursor-ew-resize flex flex-col justify-end h-9 touch-none w-full min-w-[140px] group',
|
||||
disabled && 'opacity-50 cursor-not-allowed',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Tooltip above center indicator (visible only when dragging) */}
|
||||
{isDragging && (
|
||||
<div
|
||||
data-testid="ruler-slider-tooltip"
|
||||
className="absolute -top-6 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-primary text-primary-foreground text-[10px] font-mono font-medium shadow-md whitespace-nowrap pointer-events-none z-30 animate-in fade-in zoom-in-95 duration-100"
|
||||
>
|
||||
{displayedDegree}°
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Moving Track & Ticks with Edge Mask */}
|
||||
<div
|
||||
className="relative w-full h-5 flex items-end overflow-hidden"
|
||||
style={{
|
||||
maskImage:
|
||||
'linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent)',
|
||||
}}
|
||||
>
|
||||
{/* Baseline bar */}
|
||||
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-muted-foreground/20 rounded-full" />
|
||||
|
||||
{/* Cyclic Ticks */}
|
||||
{ticks.map((tickAngle) => {
|
||||
const offsetPx = (tickAngle - activeDegree) * PX_PER_DEGREE
|
||||
const deg = ((tickAngle % 360) + 360) % 360
|
||||
const isMajor = deg % 60 === 0
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`tick-${tickAngle}`}
|
||||
data-testid={`tick-${deg}`}
|
||||
data-major={isMajor}
|
||||
className={cn(
|
||||
'absolute bottom-0 -translate-x-1/2 transition-colors pointer-events-none',
|
||||
isMajor
|
||||
? 'w-0.5 h-4 bg-foreground/75'
|
||||
: 'w-px h-2 bg-muted-foreground/40 group-hover:bg-muted-foreground/60',
|
||||
)}
|
||||
style={{ left: `calc(50% + ${offsetPx}px)` }}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Fixed Center Indicator (Pinned at 50% horizontally) */}
|
||||
<div
|
||||
data-testid="ruler-center-indicator"
|
||||
className="absolute bottom-0 left-1/2 -translate-x-1/2 flex flex-col items-center pointer-events-none z-20"
|
||||
>
|
||||
<div className="w-0.5 h-5 bg-primary rounded-full shadow-xs ring-1 ring-background/50" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,9 +3,15 @@ import { FileTypeDefinition } from './types'
|
||||
import { videoTypeDefinition } from './video'
|
||||
import { imageTypeDefinition } from './image'
|
||||
import { pdfTypeDefinition } from './pdf'
|
||||
import { modelTypeDefinition } from './model'
|
||||
import { defaultTypeDefinition } from './default'
|
||||
|
||||
const registry: FileTypeDefinition[] = [pdfTypeDefinition, videoTypeDefinition, imageTypeDefinition]
|
||||
const registry: FileTypeDefinition[] = [
|
||||
modelTypeDefinition,
|
||||
pdfTypeDefinition,
|
||||
videoTypeDefinition,
|
||||
imageTypeDefinition,
|
||||
]
|
||||
|
||||
export function getViewerForFile(file: AssetInfo | null | undefined): FileTypeDefinition {
|
||||
if (!file) return defaultTypeDefinition
|
||||
|
||||
@@ -257,6 +257,18 @@
|
||||
"transcode_settings": "Transcode Settings",
|
||||
"transcode_description": "Manage your team's video transcoding configurations.",
|
||||
"transcode_strategy_note": "Strategy: We select the best resolution from your list that supports the input quality. Content is never upscaled.",
|
||||
"turntable_settings": "3D Turntable Renderer",
|
||||
"turntable_settings_description": "Configure the external Blender turntable-renderer service for generating 3D asset previews and videos.",
|
||||
"turntable_server_url": "Server URL",
|
||||
"turntable_server_url_placeholder": "e.g. http://localhost:3001",
|
||||
"turntable_username": "Username",
|
||||
"turntable_password": "Password",
|
||||
"turntable_password_placeholder": "Leave blank to keep existing password",
|
||||
"turntable_env_configured": "Configured via environment variables (Read-only)",
|
||||
"turntable_test_connection": "Test Connection",
|
||||
"turntable_connection_success": "Connected successfully",
|
||||
"turntable_connection_failed": "Connection failed",
|
||||
"turntable_testing": "Testing...",
|
||||
"hardware_acceleration_section_description": "Configure hardware-accelerated video encoding to offload workloads to GPUs, or use CPU software encoding.",
|
||||
"mp4_transcoding": "MP4 Transcoding",
|
||||
"mp4_transcoding_description": "Generate web-compatible MP4 files for file downloads and standard video playback.",
|
||||
|
||||
@@ -257,6 +257,18 @@
|
||||
"transcode_settings": "转码设置",
|
||||
"transcode_description": "管理团队的视频转码配置。",
|
||||
"transcode_strategy_note": "策略:我们会从您的列表中选择支持输入质量的最佳分辨率。内容不会被放大。",
|
||||
"turntable_settings": "3D 转盘渲染服务",
|
||||
"turntable_settings_description": "配置用于生成 3D 资产预览图与转盘视频的外部 Blender 渲染服务。",
|
||||
"turntable_server_url": "服务地址",
|
||||
"turntable_server_url_placeholder": "例如 http://localhost:3001",
|
||||
"turntable_username": "用户名",
|
||||
"turntable_password": "密码",
|
||||
"turntable_password_placeholder": "留空以保留当前密码",
|
||||
"turntable_env_configured": "已通过环境变量配置(只读)",
|
||||
"turntable_test_connection": "测试连接",
|
||||
"turntable_connection_success": "连接成功",
|
||||
"turntable_connection_failed": "连接失败",
|
||||
"turntable_testing": "正在测试...",
|
||||
"hardware_acceleration_section_description": "配置硬件加速视频编码以将工作负载分流至 GPU,或使用 CPU 软件编码。",
|
||||
"mp4_transcoding": "MP4 转码",
|
||||
"mp4_transcoding_description": "生成适用于文件下载和标准视频播放的 Web 兼容 MP4 文件。",
|
||||
|
||||
@@ -23,6 +23,7 @@ import { QuotasSettings } from '@/ui/components/settings/QuotasSettings'
|
||||
import { AppearanceSettings } from '@/ui/components/settings/AppearanceSettings'
|
||||
import { EmailNotificationSettings } from '@/ui/components/settings/EmailNotificationSettings'
|
||||
import { ImageVideoGenerationSettings } from '@/ui/components/settings/ImageVideoGenerationSettings'
|
||||
import { TurntableSettingsCard } from '@/ui/components/settings/TurntableSettingsCard'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { Slider } from '@/ui/components/ui/slider'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
@@ -1147,6 +1148,9 @@ export function TeamSettingsPage() {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 3D Turntable Renderer Card */}
|
||||
<TurntableSettingsCard teamId={teamId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ export interface TopNavProjectState {
|
||||
name?: string
|
||||
type: 'file' | 'folder'
|
||||
version?: number
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
}
|
||||
isRootFolder: boolean
|
||||
customTerminalBreadcrumb?: string
|
||||
|
||||
@@ -66,6 +66,10 @@ export class TemporalExecutor implements Executor {
|
||||
workflowName = 'transcodeWatermarkWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
case WorkflowTaskType.transcode_3d:
|
||||
workflowName = 'transcode3dWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
break
|
||||
default:
|
||||
throw new Error(`Unknown task type: ${task.type}`)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user