mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 11:58:20 +00:00
feat(transcode): add 3D asset support and turntable viewer (#454)
* feat(transcode): add 3D asset support and turntable viewer * perf(turntable): stream file via Bun.file and increase upload timeout * feat(turntable): increase upload timeout to 15m to support 5GB uploads * fix(webui): align 3D model viewer layout and full-width control bar with video viewer * feat(webui): unify 3D viewer bottom bar and redesign cyclic ruler slider - Place RulerSlider in single row with playback and zoom controls, centered with max 320px width - Flank RulerSlider with minus and plus buttons to step angle by 15° - Redesign RulerSlider with fixed center indicator and moving cyclic track with continuous 360° wrapping - Render major ticks longer at 60° intervals without numeric text labels on track - Display floating degree tooltip above center indicator only during dragging * fix(webui): prevent RulerSlider from collapsing to 0px width in control bar - Use flex layout with flex-1 on left and right clusters to preserve center cluster width - Enforce min-w-[140px] and w-full on RulerSlider - Fix tooltip positioning and remove outer overflow-hidden * feat(webui): snap RulerSlider track directly to discrete 15° ticks during drag * fix(webui): prevent ruler snap-back caused by floating point second truncation - Use Math.round instead of Math.floor in secondToDegree to avoid 0.999996 dropping to previous frame - Ensure final dragDegree is committed on pointer up * fix(webui): fix arrow key frame rounding and duplicate event bubbling - Use Math.round instead of Math.floor for keyboard arrow frame navigation in ModelViewer - Add e.stopPropagation() to RulerSlider keyboard events to prevent duplicate bubbling to window listener * feat(webui): redesign RulerSlider with encapsulated step buttons and capsule pill track * feat(webui): make RulerSlider responsive on mobile and remove bottom bar reset button * fix(webui): load 3d video directly without poster and invert drag rotation to counterclockwise * fix(webui): fix 3d asset viewer frame seeking and drag jitter * feat(transcode): show 3D asset poster preview immediately after render start * fix(viewer): synchronize 3D turntable playback via frame callback to prevent skipped degrees * fix(viewer): handle touchpad zoom gestures and prevent page zoom in 3D viewer * fix(viewer): eliminate 3D model rotation jitter at 345 degrees * fix(share): watermark 3D asset turntable video on share links * fix(share): preserve video transcode resolution on watermarked share links * fix(viewer): download original 3D model file instead of rendered turntable MP4
This commit is contained in:
@@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
* **3d asset**: 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
|
||||
* **kanban**: Related assets on a task are now clickable, taking you directly to that file or folder in its project
|
||||
|
||||
### Fixed
|
||||
@@ -16,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
## [0.5.1] - 2026-10-06
|
||||
|
||||
### Added
|
||||
|
||||
@@ -42,7 +42,8 @@ async function applyWatermarkToAssetMedia(
|
||||
password?: string,
|
||||
): Promise<AssetInfo> {
|
||||
if (!asset.media) return asset
|
||||
if (asset.proxyType !== 'video' && asset.proxyType !== 'image') return asset
|
||||
if (asset.proxyType !== 'video' && asset.proxyType !== 'image' && asset.proxyType !== '3d')
|
||||
return asset
|
||||
|
||||
const updatedMedia = { ...asset.media }
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
@@ -58,10 +59,27 @@ async function applyWatermarkToAssetMedia(
|
||||
height: vt.height ?? 0,
|
||||
size: 0,
|
||||
hdr: vt.hdr,
|
||||
resolution: vt.resolution,
|
||||
})),
|
||||
)
|
||||
: []
|
||||
|
||||
if (watermarkMedia?.videoTranscodes && watermarkMedia.videoTranscodes.length > 0) {
|
||||
if (updatedMedia.videoPreview) {
|
||||
const watermarkedKey =
|
||||
watermarkMedia.videoPreview?.key || watermarkMedia.videoTranscodes[0]?.key
|
||||
if (watermarkedKey) {
|
||||
updatedMedia.videoPreview = {
|
||||
...updatedMedia.videoPreview,
|
||||
key: watermarkedKey,
|
||||
url: await s3Service.presign(bucket, watermarkedKey, 'GET'),
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
delete updatedMedia.videoPreview
|
||||
}
|
||||
|
||||
updatedMedia.imageTranscodes =
|
||||
watermarkMedia?.imageTranscodes && watermarkMedia.imageTranscodes.length > 0
|
||||
? await Promise.all(
|
||||
@@ -254,11 +272,11 @@ const route = app
|
||||
|
||||
let asset = await assetService.getAsset({ assetId: fileId })
|
||||
|
||||
// Only video/image assets are subject to watermark protection; skip the
|
||||
// Only video/image/3d assets are subject to watermark protection; skip the
|
||||
// watermark lookup entirely for other media types (pdf, audio, ...).
|
||||
if (
|
||||
shareLink.watermarkConfigId &&
|
||||
(asset.proxyType === 'video' || asset.proxyType === 'image')
|
||||
(asset.proxyType === 'video' || asset.proxyType === 'image' || asset.proxyType === '3d')
|
||||
) {
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
|
||||
|
||||
@@ -513,6 +513,121 @@ describe('Share API', () => {
|
||||
expect(body.media.hls).toBeUndefined()
|
||||
})
|
||||
|
||||
test('serves watermarked turntable video for a 3d asset when watermark enabled and completed', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
|
||||
const asset3d = {
|
||||
id: 'file1',
|
||||
name: 'model.glb',
|
||||
sizeByte: 1024,
|
||||
fileCount: 0,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
proxyType: '3d',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoPreview: {
|
||||
url: 'http://s3/unwatermarked-turntable.mp4',
|
||||
key: 'files/turntable.mp4',
|
||||
},
|
||||
videoTranscodes: [
|
||||
{
|
||||
id: 'orig-turntable',
|
||||
url: 'http://s3/unwatermarked-turntable.mp4',
|
||||
key: 'files/turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
},
|
||||
],
|
||||
original: { key: 'files/model.glb' },
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
vi.spyOn(assetService, 'getAsset').mockResolvedValue(asset3d)
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(
|
||||
new Map([
|
||||
[
|
||||
'file1',
|
||||
watermarkMediaInfo({
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: 'files/watermarked-turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
],
|
||||
videoPreview: { key: 'files/watermarked-turntable.mp4', width: 1080, height: 1080 },
|
||||
}),
|
||||
],
|
||||
]),
|
||||
)
|
||||
|
||||
const res = await app.request('/shares/share1/files/file1', {
|
||||
method: 'GET',
|
||||
headers: { 'x-share-password': 'pass' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.media.videoTranscodes).toEqual([
|
||||
{
|
||||
id: 'files/watermarked-turntable.mp4',
|
||||
url: 'http://s3/presigned',
|
||||
key: 'files/watermarked-turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
size: 0,
|
||||
resolution: '1080p',
|
||||
},
|
||||
])
|
||||
expect(body.media.videoPreview?.url).toBe('http://s3/presigned')
|
||||
expect(body.media.videoPreview?.key).toBe('files/watermarked-turntable.mp4')
|
||||
})
|
||||
|
||||
test('strips videoPreview url and serves empty videoTranscodes for a 3d asset while watermark is in flight', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
|
||||
const asset3d = {
|
||||
id: 'file1',
|
||||
name: 'model.glb',
|
||||
sizeByte: 1024,
|
||||
fileCount: 0,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
proxyType: '3d',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoPreview: {
|
||||
url: 'http://s3/unwatermarked-turntable.mp4',
|
||||
key: 'files/turntable.mp4',
|
||||
},
|
||||
videoTranscodes: [
|
||||
{
|
||||
id: 'orig-turntable',
|
||||
url: 'http://s3/unwatermarked-turntable.mp4',
|
||||
key: 'files/turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
},
|
||||
],
|
||||
original: { key: 'files/model.glb' },
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
vi.spyOn(assetService, 'getAsset').mockResolvedValue(asset3d)
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||
|
||||
const res = await app.request('/shares/share1/files/file1', {
|
||||
method: 'GET',
|
||||
headers: { 'x-share-password': 'pass' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.media.videoTranscodes).toEqual([])
|
||||
expect(body.media.videoPreview?.url).toBeUndefined()
|
||||
})
|
||||
|
||||
test('leaves non-video/image media untouched when watermark enabled', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithWatermark)
|
||||
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -3153,6 +3153,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
|
||||
}
|
||||
|
||||
|
||||
@@ -258,6 +258,57 @@ describe('WatermarkService', () => {
|
||||
expect(mediaIds).toContain(mediaFile.id)
|
||||
})
|
||||
|
||||
it('should include 3D assets with turntable video in getMediaAssetIdsInShareLink', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: '3D User', email: '3d-wm@example.com' },
|
||||
})
|
||||
const team = await teamService.createTeam(user, { name: '3D Team' })
|
||||
|
||||
const projectFolder = await prisma.asset.create({
|
||||
data: { name: 'root', type: 'root', status: 'processed' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: '3D Project', teamId: team.id, rootFolderId: projectFolder.id },
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(project.id, { name: '3D Share' }, user.id)
|
||||
|
||||
const modelAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: 'file',
|
||||
mediaType: 'model/gltf-binary',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
media: {
|
||||
duration: 4,
|
||||
filesize: 100,
|
||||
frames: 24,
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [
|
||||
{ key: 'files/asset-3d/turntable.mp4', width: 1080, height: 1080, resolution: '1080p' },
|
||||
],
|
||||
finishedAt: new Date().toISOString(),
|
||||
original: { key: 'files/asset-3d/robot.glb', filesizeInBytes: 100, codec: '' },
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: 'symlink',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: shareLink.rootFolderId,
|
||||
targetId: modelAsset.id,
|
||||
},
|
||||
})
|
||||
|
||||
const mediaIds = await watermarkService.getMediaAssetIdsInShareLink(shareLink.rootFolderId)
|
||||
expect(mediaIds).toContain(modelAsset.id)
|
||||
})
|
||||
|
||||
describe('purgeOrphanWatermarkConfigs', () => {
|
||||
const bucket = 'shumai-gc-test-bucket'
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from '@shumai/core/src/share/errors'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { is3dModel } from '@shumai/core/src/utils/mime'
|
||||
|
||||
// Union of the global client and interactive-transaction client, which share the
|
||||
// same delegate shapes for the models used by this service.
|
||||
@@ -319,8 +320,9 @@ export class WatermarkService {
|
||||
const proxyType = mediaInfo?.proxyType
|
||||
const isVideo = proxyType === 'video' || asset.mediaType?.startsWith('video/')
|
||||
const isImage = proxyType === 'image' || asset.mediaType?.startsWith('image/')
|
||||
const is3d = proxyType === '3d' || is3dModel(asset.mediaType)
|
||||
|
||||
if (isVideo || isImage) {
|
||||
if (isVideo || isImage || is3d) {
|
||||
mediaAssetIds.push(asset.id)
|
||||
}
|
||||
} else if (asset.type === 'folder' || asset.type === 'version_stack') {
|
||||
|
||||
@@ -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)
|
||||
},
|
||||
)
|
||||
@@ -312,6 +312,128 @@ describe.each(['local', 'temporal'] as const)(
|
||||
expect(mediaInfo?.videoTranscodes?.[0].resolution).toBe('360p')
|
||||
})
|
||||
|
||||
it('should generate watermark proxy for a 3d asset from turntable video and update sharelink status to ready', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E Watermark 3D Team' },
|
||||
})
|
||||
const projectFolder = await prisma.asset.create({
|
||||
data: { name: 'root', type: 'root', status: 'processed' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'E2E Watermark 3D Project',
|
||||
teamId: team.id,
|
||||
rootFolderId: projectFolder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/e2e-watermark-3d/model.glb' },
|
||||
})
|
||||
|
||||
const turntableKey = 'files/e2e-watermark-3d/turntable.mp4'
|
||||
const videoPath = path.join(fixturesDir, 'small.mp4')
|
||||
const videoBuffer = fs.readFileSync(videoPath)
|
||||
await s3Service.putObject(
|
||||
'shumai-e2e-test-bucket-watermark',
|
||||
turntableKey,
|
||||
videoBuffer,
|
||||
videoBuffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'model.glb',
|
||||
type: 'file',
|
||||
mediaType: 'model/gltf-binary',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
duration: 1,
|
||||
filesize: videoBuffer.length,
|
||||
frames: 30,
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [{ key: turntableKey, width: 640, height: 360, resolution: '360p' }],
|
||||
videoPreview: { key: turntableKey, width: 640, height: 360, resolution: '360p' },
|
||||
poster: { key: 'files/e2e-watermark-3d/poster.webp' },
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth: 640,
|
||||
originalHeight: 360,
|
||||
duration: 1,
|
||||
bitRate: 0,
|
||||
frameRate: 30,
|
||||
totalFrames: 30,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
},
|
||||
original: {
|
||||
key: storageKey.key,
|
||||
filesizeInBytes: 100,
|
||||
codec: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(project.id, {
|
||||
name: 'Public Watermarked 3D Share',
|
||||
})
|
||||
await shareService.addAssetToShare(shareLink.id, { assetIds: [asset.id] })
|
||||
|
||||
const watermarkConfig: WatermarkConfigSpec = {
|
||||
blocks: [
|
||||
{
|
||||
id: 'b1',
|
||||
type: 'text',
|
||||
x: 0.5,
|
||||
y: 0.5,
|
||||
opacity: 0.5,
|
||||
rotation: 0,
|
||||
text: 'CONFIDENTIAL 3D',
|
||||
size: 0.2,
|
||||
color: '#FF0000',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const updatedShare = await watermarkService.updateShareLinkWatermark(
|
||||
shareLink.id,
|
||||
true,
|
||||
watermarkConfig,
|
||||
)
|
||||
expect(updatedShare.watermarkStatus).toBe('processing')
|
||||
|
||||
let share = await shareService.getShareLink(shareLink.id)
|
||||
const startTime = Date.now()
|
||||
while (share.watermarkStatus === 'processing' && Date.now() - startTime < 60000) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
share = await shareService.getShareLink(shareLink.id)
|
||||
}
|
||||
expect(share.watermarkStatus).toBe('ready')
|
||||
|
||||
const wf = await prisma.watermarkFile.findUnique({
|
||||
where: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
assetId_watermarkConfigId: {
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: updatedShare.watermarkConfigId!,
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(wf).toBeDefined()
|
||||
expect(wf?.status).toBe(WatermarkFileStatus.completed)
|
||||
const media = wf?.media as PrismaJson.MediaInfo
|
||||
expect(media.proxyType).toBe('3d')
|
||||
expect(media.videoTranscodes?.length).toBeGreaterThan(0)
|
||||
expect(media.videoPreview?.key).toBe(media.videoTranscodes?.[0]?.key)
|
||||
})
|
||||
|
||||
it('should watermark a newly added asset after the sharelink is already ready', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
render3dModelActivity,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
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('start3dRenderActivity', () => {
|
||||
it('uploads file, starts render, immediately downloads and uploads poster 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.downloadFile).mockResolvedValue(Buffer.from('poster-raw-data'))
|
||||
|
||||
const res = await start3dRenderActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'model.glb',
|
||||
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.downloadFile).toHaveBeenCalledWith('f_poster', undefined, 'team-1')
|
||||
expect(transcodeService.convertImageToWebp).toHaveBeenCalledWith(
|
||||
Buffer.from('poster-raw-data'),
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/poster.webp',
|
||||
Buffer.from('webp-bytes'),
|
||||
Buffer.from('webp-bytes').length,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
expect(res.renderTaskId).toBe('task_render_1')
|
||||
expect(res.posterFilePath).toBe('/tmp/poster.webp')
|
||||
expect(res.posterWidth).toBe(1080)
|
||||
expect(res.posterHeight).toBe(1080)
|
||||
expect(res.modelMetadata).toEqual({ format: 'glb', vertices: 120 })
|
||||
})
|
||||
|
||||
it('throws ApplicationFailure when poster file ID is missing', 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',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
poster: undefined as any,
|
||||
})
|
||||
|
||||
await expect(
|
||||
start3dRenderActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'model.glb',
|
||||
targetPosterKey: 'files/asset-1/poster.webp',
|
||||
}),
|
||||
).rejects.toThrow('Poster file ID missing from turntable render result')
|
||||
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('waitFor3dVideoRenderActivity', () => {
|
||||
it('polls until complete, downloads video, uploads to S3, and cleans up task', async () => {
|
||||
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('video-data'))
|
||||
|
||||
const res = await waitFor3dVideoRenderActivity({
|
||||
taskId: 'wf-task-1',
|
||||
teamId: 'team-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
renderTaskId: 'task_render_1',
|
||||
targetVideoKey: 'files/asset-1/turntable.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
|
||||
expect(turntableService.getTaskStatus).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(turntableService.downloadFile).toHaveBeenCalledWith(
|
||||
'f_video',
|
||||
'/tmp/turntable.mp4',
|
||||
'team-1',
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/asset-1/turntable.mp4',
|
||||
Buffer.from('video-data'),
|
||||
Buffer.from('video-data').length,
|
||||
'video/mp4',
|
||||
)
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
|
||||
expect(res.videoFilePath).toBe('/tmp/turntable.mp4')
|
||||
})
|
||||
|
||||
it('throws ApplicationFailure when render fails on turntable-renderer', async () => {
|
||||
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(
|
||||
waitFor3dVideoRenderActivity({
|
||||
taskId: 'wf-task-2',
|
||||
teamId: 'team-1',
|
||||
assetKey: 'files/asset-1/model.glb',
|
||||
renderTaskId: 'task_render_2',
|
||||
targetVideoKey: 'files/asset-1/turntable.mp4',
|
||||
tmpDir: '/tmp',
|
||||
}),
|
||||
).rejects.toThrow('Blender failed to import model')
|
||||
|
||||
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_2', 'team-1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('render3dModelActivity (legacy wrapper)', () => {
|
||||
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')
|
||||
})
|
||||
})
|
||||
|
||||
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,316 @@ 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 interface Start3dRenderActivityParams {
|
||||
taskId: string
|
||||
teamId: string
|
||||
assetId: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
filename: string
|
||||
targetPosterKey: string
|
||||
}
|
||||
|
||||
export interface Start3dRenderActivityResult {
|
||||
renderTaskId: string
|
||||
posterFilePath: string
|
||||
posterWidth?: number
|
||||
posterHeight?: number
|
||||
modelMetadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export async function start3dRenderActivity(
|
||||
params: Start3dRenderActivityParams,
|
||||
): Promise<Start3dRenderActivityResult> {
|
||||
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 posterFilePath = path.join(tmpDir, 'poster.webp')
|
||||
|
||||
let fileId: string | undefined
|
||||
let renderTaskId: string | undefined
|
||||
|
||||
try {
|
||||
const uploadResult = await turntableService.uploadFile(
|
||||
params.filePath,
|
||||
params.filename,
|
||||
params.teamId,
|
||||
)
|
||||
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
|
||||
|
||||
const posterFileId = startResult.poster?.fileId
|
||||
if (!posterFileId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Poster file ID missing from turntable render result',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
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.targetPosterKey,
|
||||
posterWebpBuffer,
|
||||
posterWebpBuffer.length,
|
||||
'image/webp',
|
||||
)
|
||||
|
||||
return {
|
||||
renderTaskId,
|
||||
posterFilePath,
|
||||
posterWidth: startResult.poster?.width,
|
||||
posterHeight: startResult.poster?.height,
|
||||
modelMetadata: (startResult.metadata as Record<string, unknown>) || {},
|
||||
}
|
||||
} catch (err) {
|
||||
if (renderTaskId) {
|
||||
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
|
||||
} else if (fileId) {
|
||||
await turntableService.deleteFile(fileId, params.teamId).catch(() => {})
|
||||
}
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to start 3D render: ${errMsg}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export interface WaitFor3dVideoRenderActivityParams {
|
||||
taskId: string
|
||||
teamId: string
|
||||
assetKey: string
|
||||
renderTaskId: string
|
||||
targetVideoKey: string
|
||||
tmpDir: string
|
||||
}
|
||||
|
||||
export interface WaitFor3dVideoRenderActivityResult {
|
||||
videoFilePath: string
|
||||
}
|
||||
|
||||
export async function waitFor3dVideoRenderActivity(
|
||||
params: WaitFor3dVideoRenderActivityParams,
|
||||
): Promise<WaitFor3dVideoRenderActivityResult> {
|
||||
const signal = getActivityCancellationSignal(params.taskId)
|
||||
if (signal?.aborted) {
|
||||
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch(() => {})
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Render cancelled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const videoFilePath = path.join(params.tmpDir, 'turntable.mp4')
|
||||
|
||||
try {
|
||||
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) {
|
||||
await turntableService.deleteTask(params.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(params.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 videoBuffer = await turntableService.downloadFile(
|
||||
videoFileId,
|
||||
videoFilePath,
|
||||
params.teamId,
|
||||
)
|
||||
|
||||
await ensureAssetNotPurging(params.assetKey)
|
||||
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
params.targetVideoKey,
|
||||
videoBuffer,
|
||||
videoBuffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
await turntableService.deleteTask(params.renderTaskId, params.teamId).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, taskId: params.renderTaskId },
|
||||
'Failed to delete turntable task after completion',
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
videoFilePath,
|
||||
}
|
||||
} catch (err) {
|
||||
await turntableService.deleteTask(params.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 video: ${errMsg}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Legacy monolithic 3D render activity. Prefer using `start3dRenderActivity` and `waitFor3dVideoRenderActivity`.
|
||||
*/
|
||||
export async function render3dModelActivity(
|
||||
params: Render3dModelActivityParams,
|
||||
): Promise<Render3dModelActivityResult> {
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const startResult = await start3dRenderActivity({
|
||||
taskId: params.taskId,
|
||||
teamId: params.teamId,
|
||||
assetId: params.assetId,
|
||||
assetKey: params.assetKey,
|
||||
filePath: params.filePath,
|
||||
filename: params.filename,
|
||||
targetPosterKey: params.targetPosterKey,
|
||||
})
|
||||
|
||||
const videoResult = await waitFor3dVideoRenderActivity({
|
||||
taskId: params.taskId,
|
||||
teamId: params.teamId,
|
||||
assetKey: params.assetKey,
|
||||
renderTaskId: startResult.renderTaskId,
|
||||
targetVideoKey: params.targetVideoKey,
|
||||
tmpDir,
|
||||
})
|
||||
|
||||
return {
|
||||
videoFilePath: videoResult.videoFilePath,
|
||||
posterFilePath: startResult.posterFilePath,
|
||||
modelMetadata: startResult.modelMetadata,
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,6 +618,125 @@ describe('Watermark Activities', () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('produces a watermarked mp4 proxy from the turntable video for a 3d asset', async () => {
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/asset-3d/robot.glb' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: 'file',
|
||||
mediaType: 'model/gltf-binary',
|
||||
status: 'processed',
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
duration: 4,
|
||||
filesize: 100,
|
||||
frames: 24,
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: 'files/asset-3d/turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
],
|
||||
videoPreview: {
|
||||
key: 'files/asset-3d/turntable.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
poster: { key: 'files/asset-3d/poster.webp' },
|
||||
sprite: { key: 'files/asset-3d/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth: 1080,
|
||||
originalHeight: 1080,
|
||||
duration: 4,
|
||||
bitRate: 0,
|
||||
frameRate: 6,
|
||||
totalFrames: 24,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: false,
|
||||
format: {},
|
||||
},
|
||||
original: {
|
||||
key: 'files/asset-3d/robot.glb',
|
||||
filesizeInBytes: 100,
|
||||
codec: '',
|
||||
},
|
||||
} as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
const config = await seedConfig()
|
||||
|
||||
vi.mocked(transcodeService.getVideoInfo).mockResolvedValue({
|
||||
originalWidth: 1080,
|
||||
originalHeight: 1080,
|
||||
duration: 4,
|
||||
bitRate: 2000,
|
||||
frameRate: 6,
|
||||
totalFrames: 24,
|
||||
startTimecode: '00:00:00:00',
|
||||
hasAudio: false,
|
||||
mimeType: 'video/mp4',
|
||||
})
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined as never)
|
||||
|
||||
const stem = 'robot'
|
||||
const configId = config.id
|
||||
const outFilePath = path.join('/tmp', `${stem}-watermark-${configId}-1080p.mp4`)
|
||||
fs.writeFileSync(outFilePath, Buffer.from('fake 3d watermarked turntable mp4'))
|
||||
|
||||
const media = await transcodeWatermarkMediaActivity({
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: config.id,
|
||||
})
|
||||
|
||||
expect(media.proxyType).toBe('3d')
|
||||
expect(media.videoTranscodes?.length).toBeGreaterThan(0)
|
||||
expect(media.videoTranscodes?.[0].key).toContain('watermark-')
|
||||
expect(media.videoPreview?.key).toBe(media.videoTranscodes?.[0].key)
|
||||
expect(media.poster?.key).toBe('files/asset-3d/poster.webp')
|
||||
expect(media.sprite?.key).toBe('files/asset-3d/sprite.webp')
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
bucket,
|
||||
'files/asset-3d/turntable.mp4',
|
||||
expect.any(String),
|
||||
)
|
||||
|
||||
fs.rmSync(outFilePath, { force: true })
|
||||
})
|
||||
|
||||
it('throws non-retryable ApplicationFailure when 3d asset has no turntable video transcode', async () => {
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/asset-3d/robot.glb' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: 'file',
|
||||
mediaType: 'model/gltf-binary',
|
||||
status: 'processing',
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [],
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
const config = await seedConfig()
|
||||
|
||||
await expect(
|
||||
transcodeWatermarkMediaActivity({
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: config.id,
|
||||
}),
|
||||
).rejects.toThrow('Turntable video transcode not found for 3D asset')
|
||||
})
|
||||
})
|
||||
|
||||
describe('completeWatermarkFileActivity', () => {
|
||||
|
||||
@@ -163,17 +163,39 @@ export async function transcodeWatermarkMediaActivity(
|
||||
const stem = stemFromKey(assetKey)
|
||||
|
||||
const tmpDir = transcodeService.createTempDir('watermark-')
|
||||
const rawFilePath = path.join(tmpDir, path.basename(assetKey))
|
||||
|
||||
try {
|
||||
await s3Service.downloadToFile(bucket, assetKey, rawFilePath)
|
||||
|
||||
const is3d = (asset.media as PrismaJson.MediaInfo | null)?.proxyType === '3d'
|
||||
const isVideo =
|
||||
asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video'
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('video/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'video')
|
||||
const isImage =
|
||||
asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image'
|
||||
!is3d &&
|
||||
(asset.mediaType?.startsWith('image/') ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.proxyType === 'image')
|
||||
|
||||
if (!isVideo && !isImage && !is3d) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const inputKey = is3d
|
||||
? (asset.media as PrismaJson.MediaInfo | null)?.videoTranscodes?.[0]?.key ||
|
||||
(asset.media as PrismaJson.MediaInfo | null)?.videoPreview?.key
|
||||
: assetKey
|
||||
|
||||
if (is3d && !inputKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Turntable video transcode not found for 3D asset ${params.assetId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const rawFilePath = path.join(tmpDir, path.basename(inputKey!))
|
||||
await s3Service.downloadToFile(bucket, inputKey!, rawFilePath)
|
||||
|
||||
let originalWidth = 1920
|
||||
let originalHeight = 1080
|
||||
@@ -192,7 +214,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
let hdrType: PrismaJson.HdrType | undefined
|
||||
let dvProfile: number | undefined
|
||||
|
||||
if (isVideo) {
|
||||
if (isVideo || is3d) {
|
||||
const info = await transcodeService.getVideoInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
@@ -214,11 +236,6 @@ export async function transcodeWatermarkMediaActivity(
|
||||
const info = await transcodeService.getImageInfo(rawFilePath)
|
||||
originalWidth = info.originalWidth
|
||||
originalHeight = info.originalHeight
|
||||
} else {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Asset ${params.assetId} is neither video nor image`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Process image blocks if any
|
||||
@@ -260,9 +277,11 @@ export async function transcodeWatermarkMediaActivity(
|
||||
duration,
|
||||
filesize: 0,
|
||||
frames: totalFrames,
|
||||
proxyType: isVideo ? 'video' : 'image',
|
||||
proxyType: is3d ? '3d' : isVideo ? 'video' : 'image',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: originalMedia?.poster,
|
||||
sprite: originalMedia?.sprite,
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalWidth,
|
||||
@@ -280,7 +299,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
isHdr: isHdr ?? originalMedia?.metadata?.isHdr,
|
||||
hdrType: hdrType ?? originalMedia?.metadata?.hdrType,
|
||||
dvProfile: dvProfile ?? originalMedia?.metadata?.dvProfile,
|
||||
format: {},
|
||||
format: originalMedia?.metadata?.format ?? {},
|
||||
},
|
||||
original: {
|
||||
key: assetKey,
|
||||
@@ -333,7 +352,7 @@ export async function transcodeWatermarkMediaActivity(
|
||||
})
|
||||
}
|
||||
mediaInfo.filesize = totalSize
|
||||
} else if (isVideo) {
|
||||
} else if (isVideo || is3d) {
|
||||
const originalTranscodes = originalMedia?.videoTranscodes || []
|
||||
let totalSize = 0
|
||||
|
||||
@@ -395,6 +414,15 @@ export async function transcodeWatermarkMediaActivity(
|
||||
})
|
||||
}
|
||||
|
||||
if (is3d && mediaInfo.videoTranscodes.length > 0) {
|
||||
mediaInfo.videoPreview = {
|
||||
key: mediaInfo.videoTranscodes[0].key,
|
||||
width: mediaInfo.videoTranscodes[0].width,
|
||||
height: mediaInfo.videoTranscodes[0].height,
|
||||
resolution: mediaInfo.videoTranscodes[0].resolution,
|
||||
}
|
||||
}
|
||||
|
||||
if (originalMedia?.isHls && originalMedia?.hls?.resolutions?.length) {
|
||||
const hlsWatermarkDirKey = path.posix.join(
|
||||
path.posix.dirname(assetKey),
|
||||
|
||||
@@ -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,253 @@
|
||||
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' }),
|
||||
start3dRenderActivity: Object.assign(vi.fn(), { _activityName: 'start3dRenderActivity' }),
|
||||
waitFor3dVideoRenderActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'waitFor3dVideoRenderActivity',
|
||||
}),
|
||||
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.start3dRenderActivity.mockResolvedValue({
|
||||
renderTaskId: 'task_render_1',
|
||||
posterFilePath: '/tmp/poster.webp',
|
||||
posterWidth: 1080,
|
||||
posterHeight: 1080,
|
||||
modelMetadata: { format: 'glb' },
|
||||
})
|
||||
|
||||
mockActivities.waitFor3dVideoRenderActivity.mockResolvedValue({
|
||||
videoFilePath: '/tmp/turntable.mp4',
|
||||
})
|
||||
|
||||
mockActivities.generate3dSpriteActivity.mockResolvedValue({
|
||||
spriteKey: 'files/asset-3d/sprite.webp',
|
||||
})
|
||||
|
||||
await transcode3dWorkflow(task)
|
||||
|
||||
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-3d',
|
||||
status: AssetStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.start3dRenderActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
teamId: 'team-1',
|
||||
assetId: 'asset-3d',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
filePath: '/tmp/model.glb',
|
||||
filename: 'robot.glb',
|
||||
targetPosterKey: 'files/asset-3d/poster.webp',
|
||||
})
|
||||
|
||||
// Verify initial updateAssetMediaActivity with poster was called before waitFor3dVideoRenderActivity
|
||||
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'asset-3d',
|
||||
mediaInfo: expect.objectContaining({
|
||||
proxyType: '3d',
|
||||
poster: { key: 'files/asset-3d/poster.webp' },
|
||||
metadata: expect.objectContaining({
|
||||
format: { format: 'glb' },
|
||||
originalHeight: 1080,
|
||||
originalWidth: 1080,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
const firstMediaUpdateOrder =
|
||||
mockActivities.updateAssetMediaActivity.mock.invocationCallOrder[0]
|
||||
const waitVideoOrder = mockActivities.waitFor3dVideoRenderActivity.mock.invocationCallOrder[0]
|
||||
expect(firstMediaUpdateOrder).toBeLessThan(waitVideoOrder)
|
||||
|
||||
expect(mockActivities.waitFor3dVideoRenderActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-3d',
|
||||
teamId: 'team-1',
|
||||
assetKey: 'files/asset-3d/robot.glb',
|
||||
renderTaskId: 'task_render_1',
|
||||
targetVideoKey: 'files/asset-3d/turntable.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
|
||||
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.start3dRenderActivity.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,172 @@
|
||||
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,
|
||||
start3dRenderActivity,
|
||||
waitFor3dVideoRenderActivity,
|
||||
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 renderStart = await executeActivity(workerQueue, start3dRenderActivity, {
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
filePath: currentFilePath,
|
||||
filename: asset.name || 'model.glb',
|
||||
targetPosterKey: posterKey,
|
||||
})
|
||||
|
||||
const posterWidth = renderStart.posterWidth || 1080
|
||||
const posterHeight = renderStart.posterHeight || 1080
|
||||
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration: 4,
|
||||
filesize: 0,
|
||||
frames: 24,
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
poster: {
|
||||
key: posterKey,
|
||||
},
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalHeight: posterHeight,
|
||||
originalWidth: posterWidth,
|
||||
hasAudio: false,
|
||||
duration: 4,
|
||||
bitRate: 0,
|
||||
frameRate: 6,
|
||||
totalFrames: 24,
|
||||
startTimecode: '00:00:00:00',
|
||||
format: renderStart.modelMetadata ?? {},
|
||||
},
|
||||
original: {
|
||||
key,
|
||||
filesizeInBytes: Number(asset.sizeByte || 0),
|
||||
codec: '',
|
||||
},
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
const renderVideo = await executeActivity(workerQueue, waitFor3dVideoRenderActivity, {
|
||||
taskId: task.id,
|
||||
teamId: task.teamId,
|
||||
assetKey: key,
|
||||
renderTaskId: renderStart.renderTaskId,
|
||||
targetVideoKey: videoKey,
|
||||
tmpDir,
|
||||
})
|
||||
|
||||
await executeActivity(workerQueue, generate3dSpriteActivity, {
|
||||
taskId: task.id,
|
||||
assetKey: key,
|
||||
videoFilePath: renderVideo.videoFilePath,
|
||||
spriteKey,
|
||||
})
|
||||
|
||||
mediaInfo.sprite = {
|
||||
key: spriteKey,
|
||||
frames: 100,
|
||||
tileX: 10,
|
||||
tileY: 10,
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetMediaActivity, {
|
||||
assetId: asset.id,
|
||||
mediaInfo,
|
||||
})
|
||||
|
||||
mediaInfo.videoTranscodes = [
|
||||
{
|
||||
key: videoKey,
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
},
|
||||
]
|
||||
mediaInfo.videoPreview = {
|
||||
key: videoKey,
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
}
|
||||
mediaInfo.finishedAt = new Date().toISOString()
|
||||
|
||||
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'
|
||||
|
||||
@@ -263,4 +263,45 @@ describe('BreadcrumbNav component', () => {
|
||||
expect(items.some((i) => i.textContent?.includes('1080p'))).toBe(true)
|
||||
expect(items.some((i) => i.textContent?.includes('1920p'))).toBe(false)
|
||||
})
|
||||
|
||||
it('correctly labels 1080p square / 3D turntable transcode in download menu', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav
|
||||
{...baseProps}
|
||||
fileId="file-3d"
|
||||
currentAsset={{
|
||||
id: 'file-3d',
|
||||
name: 'model.glb',
|
||||
type: 'file',
|
||||
version: 1,
|
||||
proxyType: '3d',
|
||||
}}
|
||||
allowDownload={true}
|
||||
downloadInfo={{
|
||||
originalKey: 'model.glb',
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: 'turntable-1080p.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
hdr: false,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const triggerButton = screen.getByRole('button', { name: 'model.glb' })
|
||||
fireEvent.pointerDown(triggerButton, { button: 0, ctrlKey: false })
|
||||
|
||||
const downloadSubTrigger = screen.getByText('Download')
|
||||
fireEvent.click(downloadSubTrigger)
|
||||
|
||||
const items = screen.getAllByRole('menuitem')
|
||||
expect(items.some((i) => i.textContent?.includes('1080p'))).toBe(true)
|
||||
expect(items.some((i) => i.textContent?.includes('480p'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -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,20 @@
|
||||
import { FileTypeDefinition } from '../types'
|
||||
import ModelViewer from './model-viewer'
|
||||
|
||||
import { secondToDegree } from './utils'
|
||||
export { secondToDegree } from './utils'
|
||||
|
||||
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,131 @@
|
||||
import React from 'react'
|
||||
import { Play, Pause, 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
|
||||
onDownload?: () => void
|
||||
togglePlay: () => void
|
||||
onSeekDegree: (degree: number) => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
onZoomReset: () => void
|
||||
toggleFullScreen: () => void
|
||||
}
|
||||
|
||||
export const ModelControlBar: React.FC<ModelControlBarProps> = ({
|
||||
isPlaying,
|
||||
currentDegree,
|
||||
zoom,
|
||||
isFullScreen,
|
||||
allowDownload = true,
|
||||
onDownload,
|
||||
togglePlay,
|
||||
onSeekDegree,
|
||||
onZoomChange,
|
||||
onZoomReset,
|
||||
toggleFullScreen,
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'transition-all duration-300 ease-in-out z-20 text-foreground',
|
||||
isFullScreen
|
||||
? 'absolute bottom-0 left-0 right-0 px-2 py-2 sm:px-4 sm:py-2.5 bg-card/90 backdrop-blur-md border-t border-border'
|
||||
: 'relative w-full bg-card border-t border-border px-2 py-2 sm:px-4 sm:py-2.5 z-10 transition-colors duration-200',
|
||||
)}
|
||||
>
|
||||
{/* Unified Single Row Controls */}
|
||||
<div className="flex items-center justify-between text-foreground gap-1.5 sm:gap-3 md:gap-4">
|
||||
{/* Left Side: Play/Pause, Degree Readout */}
|
||||
<div className="flex items-center gap-1.5 sm: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 p-0.5 sm:p-1"
|
||||
data-testid="play-toggle"
|
||||
data-playing={isPlaying}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="w-4 h-4 sm:w-5 sm:h-5 fill-current" />
|
||||
) : (
|
||||
<Play className="w-4 h-4 sm:w-5 sm:h-5 fill-current" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div
|
||||
className="flex items-center text-xs sm: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>
|
||||
</div>
|
||||
|
||||
{/* Center: RulerSlider with encapsulated minus & plus buttons */}
|
||||
<div className="flex items-center w-full max-w-[130px] sm:max-w-[220px] md:max-w-[320px] justify-center mx-auto shrink min-w-0">
|
||||
<RulerSlider currentDegree={currentDegree} onChange={onSeekDegree} className="w-full" />
|
||||
</div>
|
||||
|
||||
{/* Right Side: Zoom controls, Download, Fullscreen */}
|
||||
<div className="flex items-center gap-1 sm:gap-2 justify-end min-w-0 flex-1">
|
||||
{/* Zoom controls */}
|
||||
<div className="flex items-center gap-0.5 sm: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 sm:px-1.5 py-0.5 text-[10px] sm: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 && onDownload && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDownload}
|
||||
title="Download asset"
|
||||
aria-label="Download asset"
|
||||
className="p-1 sm: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 sm: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,479 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, 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: () => () => '' }),
|
||||
}))
|
||||
|
||||
const mockFileDownloadPost = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://example.com/download-model.glb' }),
|
||||
})
|
||||
const mockShareDownloadPost = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://example.com/share-download-model.glb' }),
|
||||
})
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
files: {
|
||||
'download-url': {
|
||||
$post: (...args: unknown[]) => mockFileDownloadPost(...args),
|
||||
},
|
||||
},
|
||||
shares: {
|
||||
':shareId': {
|
||||
files: {
|
||||
':fileId': {
|
||||
'download-url': {
|
||||
$post: (...args: unknown[]) => mockShareDownloadPost(...args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
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 { container, 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()
|
||||
// Video does not use low-res poster
|
||||
expect(container.querySelector('video')?.getAttribute('poster')).toBeNull()
|
||||
})
|
||||
|
||||
it('prioritizes videoTranscodes URL over videoPreview URL for watermarked share compatibility', () => {
|
||||
const fileWithBoth = {
|
||||
...mockAsset,
|
||||
media: {
|
||||
...mockAsset.media,
|
||||
videoPreview: { url: 'https://example.com/unwatermarked-turntable.mp4' },
|
||||
videoTranscodes: [{ url: 'https://example.com/watermarked-turntable.mp4' }],
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { container } = render(<ModelViewer file={fileWithBoth} />)
|
||||
const video = container.querySelector('video')
|
||||
expect(video?.getAttribute('src')).toBe('https://example.com/watermarked-turntable.mp4')
|
||||
})
|
||||
|
||||
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 (drag right rotates counterclockwise)', () => {
|
||||
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 (drag right rotates counterclockwise: frame 0 - 2 = 22 frames = 22/6s)
|
||||
fireEvent.pointerMove(surface, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(22 / 6, 2))
|
||||
|
||||
// Move left by 24px from origin (frame 0 - (-2) = 2 frames = 2/6s)
|
||||
fireEvent.pointerMove(surface, { clientX: 76, button: 0, pointerId: 1 })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
|
||||
|
||||
// Release drag
|
||||
fireEvent.pointerUp(surface, { clientX: 76, 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('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)
|
||||
})
|
||||
|
||||
it('updates playback smoothly on each frame via requestVideoFrameCallback without skipping degrees', () => {
|
||||
let frameCallback: ((now: number, metadata: { mediaTime: number }) => void) | null = null
|
||||
const rvfcMock = vi.fn().mockImplementation((cb) => {
|
||||
frameCallback = cb
|
||||
return 101
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(HTMLVideoElement.prototype as any).requestVideoFrameCallback = rvfcMock
|
||||
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { container, getByTestId } = render(
|
||||
<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
|
||||
const video = container.querySelector('video')
|
||||
expect(video).toBeDefined()
|
||||
|
||||
// Start playing
|
||||
fireEvent.play(video!)
|
||||
expect(rvfcMock).toHaveBeenCalled()
|
||||
|
||||
// Simulate decoded frames arriving sequentially at 6 FPS (every 1/6 second)
|
||||
const degreeReadout = getByTestId('degree-readout')
|
||||
|
||||
// Frame 0: 0.083s -> 0°
|
||||
act(() => {
|
||||
frameCallback!(100, { mediaTime: 0.083 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('0° / 360°')
|
||||
|
||||
// Frame 1: 0.25s -> 15°
|
||||
act(() => {
|
||||
frameCallback!(267, { mediaTime: 0.25 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('15° / 360°')
|
||||
|
||||
// Frame 2: 0.417s -> 30°
|
||||
act(() => {
|
||||
frameCallback!(433, { mediaTime: 0.417 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('30° / 360°')
|
||||
|
||||
// Frame 3: 0.583s -> 45°
|
||||
act(() => {
|
||||
frameCallback!(600, { mediaTime: 0.583 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('45° / 360°')
|
||||
|
||||
// Frame 4: 0.75s -> 60°
|
||||
act(() => {
|
||||
frameCallback!(767, { mediaTime: 0.75 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('60° / 360°')
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (HTMLVideoElement.prototype as any).requestVideoFrameCallback
|
||||
})
|
||||
|
||||
it('cancels frame callback loop when video is paused', () => {
|
||||
const cancelMock = vi.fn()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(HTMLVideoElement.prototype as any).requestVideoFrameCallback = vi.fn().mockReturnValue(123)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(HTMLVideoElement.prototype as any).cancelVideoFrameCallback = cancelMock
|
||||
|
||||
const { container } = render(<ModelViewer file={mockAsset} />)
|
||||
const video = container.querySelector('video')
|
||||
|
||||
fireEvent.play(video!)
|
||||
fireEvent.pause(video!)
|
||||
|
||||
expect(cancelMock).toHaveBeenCalledWith(123)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (HTMLVideoElement.prototype as any).requestVideoFrameCallback
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (HTMLVideoElement.prototype as any).cancelVideoFrameCallback
|
||||
})
|
||||
|
||||
it('zooms viewer and prevents browser default on touchpad pinch (ctrl+wheel)', () => {
|
||||
const { getByTestId, getByRole } = render(<ModelViewer file={mockAsset} />)
|
||||
const surface = getByTestId('model-viewer-surface')
|
||||
const resetZoomBtn = getByRole('button', { name: 'Reset zoom' })
|
||||
|
||||
const initialZoomText = resetZoomBtn.textContent
|
||||
|
||||
surface.getBoundingClientRect = () =>
|
||||
({
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: 800,
|
||||
height: 600,
|
||||
right: 800,
|
||||
bottom: 600,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => {},
|
||||
}) as DOMRect
|
||||
|
||||
const wheelEvent = new WheelEvent('wheel', {
|
||||
deltaY: -100,
|
||||
deltaMode: 0,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
})
|
||||
Object.defineProperty(wheelEvent, 'ctrlKey', { value: true })
|
||||
Object.defineProperty(wheelEvent, 'clientX', { value: 400 })
|
||||
Object.defineProperty(wheelEvent, 'clientY', { value: 300 })
|
||||
|
||||
let notPrevented = true
|
||||
act(() => {
|
||||
notPrevented = surface.dispatchEvent(wheelEvent)
|
||||
})
|
||||
|
||||
expect(notPrevented).toBe(false)
|
||||
expect(resetZoomBtn.textContent).not.toBe(initialZoomText)
|
||||
})
|
||||
|
||||
it('pans viewer content and prevents scroll on two-finger wheel when zoomed in', () => {
|
||||
const { getByTestId, getByRole } = render(<ModelViewer file={mockAsset} />)
|
||||
const surface = getByTestId('model-viewer-surface')
|
||||
const zoomInBtn = getByRole('button', { name: 'Zoom in' })
|
||||
|
||||
// Zoom in multiple times so zoom exceeds baseScale significantly
|
||||
fireEvent.click(zoomInBtn)
|
||||
fireEvent.click(zoomInBtn)
|
||||
fireEvent.click(zoomInBtn)
|
||||
|
||||
const mediaWrapper = surface.querySelector('div.absolute.pointer-events-none') as HTMLElement
|
||||
const initialTransform = mediaWrapper.style.transform
|
||||
|
||||
const scrollEvent = new WheelEvent('wheel', {
|
||||
deltaX: 20,
|
||||
deltaY: 30,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
})
|
||||
Object.defineProperty(scrollEvent, 'ctrlKey', { value: false })
|
||||
|
||||
let notPrevented = true
|
||||
act(() => {
|
||||
notPrevented = surface.dispatchEvent(scrollEvent)
|
||||
})
|
||||
|
||||
expect(notPrevented).toBe(false)
|
||||
expect(mediaWrapper.style.transform).not.toBe(initialTransform)
|
||||
})
|
||||
|
||||
it('keeps video loop attribute disabled when paused to prevent browser EOF reset, and enables loop when playing', () => {
|
||||
const { container } = render(<ModelViewer file={mockAsset} />)
|
||||
const video = container.querySelector('video') as HTMLVideoElement
|
||||
expect(video).toBeDefined()
|
||||
|
||||
// Paused initially: loop should be false so seeking to final frame does not trigger browser loop-reset
|
||||
expect(video.loop).toBe(false)
|
||||
|
||||
// Play: loop should become true
|
||||
fireEvent.play(video)
|
||||
expect(video.loop).toBe(true)
|
||||
|
||||
// Pause: loop should become false again
|
||||
fireEvent.pause(video)
|
||||
expect(video.loop).toBe(false)
|
||||
})
|
||||
|
||||
it('seeks safely to 345° without touching 4.0s EOF boundary', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { container, getByTestId } = render(
|
||||
<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
const video = container.querySelector('video') as HTMLVideoElement
|
||||
const degreeReadout = getByTestId('degree-readout')
|
||||
|
||||
// At 0°, press ArrowLeft to rotate counterclockwise to 345° (Frame 23)
|
||||
fireEvent.keyDown(window, { key: 'ArrowLeft' })
|
||||
|
||||
// Target time should be 23 / 6s = 3.8333s
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(23 / 6, 2))
|
||||
// Video currentTime should be safely offset from 4.0s EOF (3.875s)
|
||||
expect(video.currentTime).toBeCloseTo(3.875, 3)
|
||||
expect(video.currentTime).toBeLessThan(4.0)
|
||||
expect(degreeReadout.textContent).toContain('345° / 360°')
|
||||
})
|
||||
|
||||
it('downloads the original model via files download-url endpoint when Download asset is clicked', async () => {
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
const { getByTitle } = render(<ModelViewer file={mockAsset} />)
|
||||
const downloadBtn = getByTitle('Download asset')
|
||||
expect(downloadBtn).toBeDefined()
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(downloadBtn)
|
||||
})
|
||||
|
||||
expect(mockFileDownloadPost).toHaveBeenCalledWith({
|
||||
json: { key: 'files/robot.glb', assetId: 'asset-3d-1' },
|
||||
})
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('downloads the model via shares download-url endpoint when shareId is provided', async () => {
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
const { getByTitle } = render(<ModelViewer file={mockAsset} shareId="share-test-123" />)
|
||||
const downloadBtn = getByTitle('Download asset')
|
||||
expect(downloadBtn).toBeDefined()
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(downloadBtn)
|
||||
})
|
||||
|
||||
expect(mockShareDownloadPost).toHaveBeenCalledWith({
|
||||
param: { shareId: 'share-test-123', fileId: 'asset-3d-1' },
|
||||
json: { key: 'files/robot.glb' },
|
||||
})
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('hides the download button when allowDownload is false', () => {
|
||||
const { queryByTitle } = render(<ModelViewer file={mockAsset} allowDownload={false} />)
|
||||
expect(queryByTitle('Download asset')).toBeNull()
|
||||
})
|
||||
|
||||
it('hides the download button when original key is missing', () => {
|
||||
const assetWithoutOriginal = {
|
||||
...mockAsset,
|
||||
media: {
|
||||
...mockAsset.media,
|
||||
original: undefined,
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { queryByTitle } = render(<ModelViewer file={assetWithoutOriginal} />)
|
||||
expect(queryByTitle('Download asset')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,514 @@
|
||||
import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
|
||||
import { AlertCircle, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { client } from '@/ui/api/client'
|
||||
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 { usePanZoomGestures } from '../use-pan-zoom'
|
||||
import { ModelControlBar } from './model-control-bar'
|
||||
import {
|
||||
secondToDegree,
|
||||
secondToFrame,
|
||||
calculateFrameCenterTime,
|
||||
TOTAL_FRAMES,
|
||||
FRAME_DURATION,
|
||||
} from './utils'
|
||||
|
||||
export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
(
|
||||
{
|
||||
file: data,
|
||||
onPlay,
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
shareId,
|
||||
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)
|
||||
|
||||
useEffect(() => {
|
||||
setHasManuallyZoomed(false)
|
||||
}, [data.id])
|
||||
|
||||
// Drag-to-rotate state
|
||||
const [isDraggingRotation, setIsDraggingRotation] = useState(false)
|
||||
const dragStartRef = useRef<{ clientX: number; frame: number }>({ clientX: 0, frame: 0 })
|
||||
|
||||
const videoSrc = data.media?.videoTranscodes?.[0]?.url || data.media?.videoPreview?.url || ''
|
||||
|
||||
const handleDownload = async () => {
|
||||
const key = data.media?.original?.key
|
||||
if (!key || !data.id) return
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: data.id },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: data.id },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = data.name || 'model.glb'
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// fail silently
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
const baseScale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
|
||||
|
||||
// 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) {
|
||||
setZoom(baseScale)
|
||||
setPan(
|
||||
centeredPan(
|
||||
containerSize.width,
|
||||
containerSize.height,
|
||||
mediaWidth,
|
||||
mediaHeight,
|
||||
baseScale,
|
||||
),
|
||||
)
|
||||
}
|
||||
}, [containerSize, mediaWidth, mediaHeight, baseScale, hasManuallyZoomed])
|
||||
|
||||
usePanZoomGestures({
|
||||
containerRef,
|
||||
zoom,
|
||||
pan,
|
||||
baseScale,
|
||||
onZoomChange: (next) => {
|
||||
setHasManuallyZoomed(true)
|
||||
setZoom(next.zoom)
|
||||
setPan(next.pan)
|
||||
},
|
||||
onPanChange: setPan,
|
||||
})
|
||||
|
||||
// Current angle
|
||||
const currentDegree = secondToDegree(currentTime)
|
||||
|
||||
const onTimeUpdateRef = useRef(onTimeUpdate)
|
||||
useEffect(() => {
|
||||
onTimeUpdateRef.current = onTimeUpdate
|
||||
}, [onTimeUpdate])
|
||||
|
||||
// Synchronized playback frame loop (via requestVideoFrameCallback / requestAnimationFrame)
|
||||
useEffect(() => {
|
||||
if (!isPlaying) return
|
||||
const video = videoRef.current
|
||||
if (!video) return
|
||||
|
||||
let animationFrameId: number | null = null
|
||||
let rvfcId: number | null = null
|
||||
let isCancelled = false
|
||||
|
||||
type VideoWithRvfc = HTMLVideoElement & {
|
||||
requestVideoFrameCallback?: (
|
||||
callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void,
|
||||
) => number
|
||||
cancelVideoFrameCallback?: (id: number) => void
|
||||
}
|
||||
|
||||
const videoWithRvfc = video as VideoWithRvfc
|
||||
const rvfcSupported = typeof videoWithRvfc.requestVideoFrameCallback === 'function'
|
||||
|
||||
const updateTime = (time: number) => {
|
||||
if (!isDraggingRotation) {
|
||||
setCurrentTime(time)
|
||||
onTimeUpdateRef.current?.(time)
|
||||
}
|
||||
}
|
||||
|
||||
if (rvfcSupported) {
|
||||
const onFrame = (_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => {
|
||||
if (isCancelled) return
|
||||
updateTime(metadata.mediaTime)
|
||||
rvfcId = videoWithRvfc.requestVideoFrameCallback!(onFrame)
|
||||
}
|
||||
rvfcId = videoWithRvfc.requestVideoFrameCallback!(onFrame)
|
||||
} else {
|
||||
const loop = () => {
|
||||
if (isCancelled) return
|
||||
if (videoRef.current) {
|
||||
updateTime(videoRef.current.currentTime)
|
||||
}
|
||||
animationFrameId = requestAnimationFrame(loop)
|
||||
}
|
||||
animationFrameId = requestAnimationFrame(loop)
|
||||
}
|
||||
|
||||
return () => {
|
||||
isCancelled = true
|
||||
if (rvfcId !== null && typeof videoWithRvfc.cancelVideoFrameCallback === 'function') {
|
||||
videoWithRvfc.cancelVideoFrameCallback(rvfcId)
|
||||
}
|
||||
if (animationFrameId !== null) {
|
||||
cancelAnimationFrame(animationFrameId)
|
||||
}
|
||||
}
|
||||
}, [isPlaying, isDraggingRotation])
|
||||
|
||||
// Seek helper
|
||||
const seekToFrame = useCallback(
|
||||
(frameIndex: number) => {
|
||||
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
|
||||
const targetSec = normalizedFrame * FRAME_DURATION
|
||||
const centerSec = calculateFrameCenterTime(normalizedFrame)
|
||||
if (videoRef.current) {
|
||||
videoRef.current.currentTime = centerSec
|
||||
}
|
||||
setCurrentTime(targetSec)
|
||||
onTimeUpdate?.(targetSec)
|
||||
},
|
||||
[onTimeUpdate],
|
||||
)
|
||||
|
||||
const seekToDegree = useCallback(
|
||||
(degree: number) => {
|
||||
videoRef.current?.pause()
|
||||
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(secondToFrame(second))
|
||||
},
|
||||
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 = secondToFrame(currentTime)
|
||||
seekToFrame(currentFrame - 1)
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault()
|
||||
const currentFrame = secondToFrame(currentTime)
|
||||
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.round(currentDegree / 15) % TOTAL_FRAMES
|
||||
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°)
|
||||
// Dragging right (deltaX > 0) rotates turntable counterclockwise (decreasing frame index)
|
||||
const deltaFrames = Math.round(deltaX / 12)
|
||||
const targetFrame = dragStartRef.current.frame - deltaFrames
|
||||
seekToFrame(targetFrame)
|
||||
}
|
||||
|
||||
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) {
|
||||
setZoom(baseScale)
|
||||
setPan(
|
||||
centeredPan(
|
||||
containerSize.width,
|
||||
containerSize.height,
|
||||
mediaWidth,
|
||||
mediaHeight,
|
||||
baseScale,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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}
|
||||
playsInline
|
||||
loop={isPlaying}
|
||||
muted
|
||||
autoPlay={autoPlay}
|
||||
preload="auto"
|
||||
onLoadedData={() => {
|
||||
setIsLoading(false)
|
||||
if (startTime && startTime > 0) {
|
||||
seekToFrame(secondToFrame(startTime))
|
||||
}
|
||||
}}
|
||||
onPlay={() => {
|
||||
setIsPlaying(true)
|
||||
onPlay?.()
|
||||
}}
|
||||
onPause={() => {
|
||||
setIsPlaying(false)
|
||||
onPause?.()
|
||||
}}
|
||||
onEnded={() => {
|
||||
setIsPlaying(false)
|
||||
}}
|
||||
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}
|
||||
onDownload={data.media?.original?.key ? handleDownload : undefined}
|
||||
togglePlay={togglePlay}
|
||||
onSeekDegree={seekToDegree}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
ModelViewer.displayName = 'ModelViewer'
|
||||
export default ModelViewer
|
||||
@@ -0,0 +1,164 @@
|
||||
// @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)
|
||||
})
|
||||
|
||||
it('steps degree forward and backward via encapsulated plus and minus buttons', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByTestId, rerender } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
|
||||
|
||||
const plusBtn = getByTestId('ruler-step-plus')
|
||||
const minusBtn = getByTestId('ruler-step-minus')
|
||||
|
||||
// 0 + 15 = 15
|
||||
fireEvent.click(plusBtn)
|
||||
expect(onChange).toHaveBeenCalledWith(15)
|
||||
|
||||
// 0 - 15 wraps to 345
|
||||
fireEvent.click(minusBtn)
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
|
||||
// When disabled, clicking should not trigger onChange
|
||||
onChange.mockClear()
|
||||
rerender(<RulerSlider currentDegree={0} onChange={onChange} disabled />)
|
||||
fireEvent.click(plusBtn)
|
||||
fireEvent.click(minusBtn)
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,228 @@
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { Minus, Plus } from 'lucide-react'
|
||||
import React, { useCallback, useRef, useState } from 'react'
|
||||
|
||||
export interface RulerSliderProps {
|
||||
currentDegree: number // 0 to 360 (or normalized modulo 360)
|
||||
onChange: (degree: number) => void
|
||||
className?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const STEP = 15
|
||||
const PX_PER_STEP = 20 // 20px per 15° step
|
||||
const PX_PER_DEGREE = PX_PER_STEP / STEP // ~1.333px per degree
|
||||
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 trackRef = 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 handleStep = useCallback(
|
||||
(delta: number) => {
|
||||
if (disabled) return
|
||||
const next = (((normalizedDegree + delta) % 360) + 360) % 360
|
||||
onChange(next)
|
||||
},
|
||||
[disabled, normalizedDegree, onChange],
|
||||
)
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (disabled || e.button !== 0) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
const target = trackRef.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(nextRawDegree)
|
||||
onChange(snapped)
|
||||
},
|
||||
[isDragging, disabled, onChange],
|
||||
)
|
||||
|
||||
const handlePointerUp = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDragging) return
|
||||
setIsDragging(false)
|
||||
if (dragDegree !== null) {
|
||||
const snapped = (((Math.round(dragDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
onChange(snapped)
|
||||
}
|
||||
setDragDegree(null)
|
||||
try {
|
||||
trackRef.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()
|
||||
handleStep(-STEP)
|
||||
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
handleStep(STEP)
|
||||
} else if (e.key === 'Home') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange(0)
|
||||
} else if (e.key === 'End') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange(345)
|
||||
}
|
||||
},
|
||||
[disabled, handleStep, 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
|
||||
className={cn(
|
||||
'relative select-none flex items-center gap-1 sm:gap-2.5 w-full min-w-0 sm:min-w-[140px]',
|
||||
disabled && 'opacity-50',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Minus button on left */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStep(-STEP)}
|
||||
disabled={disabled}
|
||||
title="Decrease 15°"
|
||||
aria-label="Decrease 15°"
|
||||
data-testid="ruler-step-minus"
|
||||
className="p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<Minus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
{/* Center Capsule Slider Track Container */}
|
||||
<div className="relative flex-1 min-w-0">
|
||||
{/* Tooltip above center indicator (visible only when dragging) */}
|
||||
{isDragging && (
|
||||
<div
|
||||
data-testid="ruler-slider-tooltip"
|
||||
className="absolute -top-7 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>
|
||||
)}
|
||||
|
||||
{/* Capsule track with rounded pill shape, clipping scrolling ticks */}
|
||||
<div
|
||||
ref={trackRef}
|
||||
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 w-full h-7 rounded-full bg-muted border border-border overflow-hidden cursor-ew-resize touch-none select-none group focus:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
disabled && 'cursor-not-allowed',
|
||||
)}
|
||||
>
|
||||
{/* Cyclic Ticks - vertically centered */}
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
{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 top-1/2 -translate-y-1/2 -translate-x-1/2 transition-colors pointer-events-none rounded-[0.5px]',
|
||||
isMajor
|
||||
? 'w-0.5 h-2.5 bg-foreground/75'
|
||||
: 'w-px h-1.5 bg-muted-foreground/45 group-hover:bg-muted-foreground/65',
|
||||
)}
|
||||
style={{ left: `calc(50% + ${offsetPx}px)` }}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Fixed Center Red Indicator (Pinned at 50% horizontally, spans full height) */}
|
||||
<div
|
||||
data-testid="ruler-center-indicator"
|
||||
className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-0.5 flex items-center justify-center pointer-events-none z-20"
|
||||
>
|
||||
<div className="w-full h-full bg-[#ea3349] rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Plus button on right */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStep(STEP)}
|
||||
disabled={disabled}
|
||||
title="Increase 15°"
|
||||
aria-label="Increase 15°"
|
||||
data-testid="ruler-step-plus"
|
||||
className="p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
calculateFrameCenterTime,
|
||||
secondToFrame,
|
||||
secondToDegree,
|
||||
TOTAL_FRAMES,
|
||||
FPS,
|
||||
FRAME_DURATION,
|
||||
} from './utils'
|
||||
|
||||
describe('model viewer utils', () => {
|
||||
describe('calculateFrameCenterTime', () => {
|
||||
it('calculates the center time for frame 0', () => {
|
||||
expect(calculateFrameCenterTime(0)).toBeCloseTo(0.5 / FPS)
|
||||
})
|
||||
|
||||
it('calculates presentation times safely within frame boundaries for all frames 0 to 23', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES - 1; i++) {
|
||||
const center = calculateFrameCenterTime(i)
|
||||
expect(center).toBeCloseTo((i + 0.5) * FRAME_DURATION)
|
||||
}
|
||||
// For the final frame (frame 23, 345°), ensure it is safely offset away from EOF (4.0s)
|
||||
const lastCenter = calculateFrameCenterTime(TOTAL_FRAMES - 1)
|
||||
expect(lastCenter).toBeCloseTo((TOTAL_FRAMES - 1) * FRAME_DURATION + FRAME_DURATION * 0.25)
|
||||
expect(lastCenter).toBeLessThan(TOTAL_FRAMES * FRAME_DURATION)
|
||||
})
|
||||
|
||||
it('handles negative and wrapping frames properly', () => {
|
||||
expect(calculateFrameCenterTime(-1)).toBeCloseTo(calculateFrameCenterTime(23))
|
||||
expect(calculateFrameCenterTime(24)).toBeCloseTo(calculateFrameCenterTime(0))
|
||||
})
|
||||
})
|
||||
|
||||
describe('secondToFrame', () => {
|
||||
it('correctly maps frame start times to frame index without float truncation', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const startSec = i * FRAME_DURATION
|
||||
expect(secondToFrame(startSec)).toBe(i)
|
||||
}
|
||||
})
|
||||
|
||||
it('correctly maps frame center times to frame index', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const centerSec = calculateFrameCenterTime(i)
|
||||
expect(secondToFrame(centerSec)).toBe(i)
|
||||
}
|
||||
})
|
||||
|
||||
it('clamps values below 0 and above total duration', () => {
|
||||
expect(secondToFrame(-1)).toBe(0)
|
||||
expect(secondToFrame(100)).toBe(TOTAL_FRAMES - 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('secondToDegree', () => {
|
||||
it('returns 0 for 0s', () => {
|
||||
expect(secondToDegree(0)).toBe(0)
|
||||
})
|
||||
|
||||
it('returns exact degrees (0..345) for every frame center', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const center = calculateFrameCenterTime(i)
|
||||
expect(secondToDegree(center)).toBe((i * 15) % 360)
|
||||
}
|
||||
})
|
||||
|
||||
it('returns exact degrees for frame start times', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const start = i * FRAME_DURATION
|
||||
expect(secondToDegree(start)).toBe((i * 15) % 360)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
export const TOTAL_FRAMES = 24
|
||||
export const FPS = 6
|
||||
export const FRAME_DURATION = 1 / FPS
|
||||
|
||||
/**
|
||||
* Calculates the presentation time within a frame.
|
||||
* Seeking near the frame center avoids PTS boundary inaccuracies in browser video decoders.
|
||||
* For the final frame (TOTAL_FRAMES - 1), we use a safe offset inside the frame
|
||||
* to avoid grazing the EOF boundary (video duration) which can cause browser decoders
|
||||
* to trigger end-of-stream or loop behavior.
|
||||
*/
|
||||
export function calculateFrameCenterTime(frameIndex: number): number {
|
||||
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
|
||||
if (normalizedFrame === TOTAL_FRAMES - 1) {
|
||||
return normalizedFrame * FRAME_DURATION + FRAME_DURATION * 0.25
|
||||
}
|
||||
return (normalizedFrame + 0.5) * FRAME_DURATION
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a playback second into a frame index (0..23), clamped.
|
||||
* Works with frame start times, frame center times, or continuous playback seconds.
|
||||
*/
|
||||
export function secondToFrame(second: number): number {
|
||||
return Math.min(Math.max(0, Math.floor(second * FPS + 1e-4)), TOTAL_FRAMES - 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a second to turntable degree (0, 15, 30, ..., 345).
|
||||
*/
|
||||
export function secondToDegree(second: number): number {
|
||||
const frameIndex = secondToFrame(second)
|
||||
return (frameIndex * 15) % 360
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Binary file not shown.
@@ -192,3 +192,38 @@ export const sampleAudioAsset: AssetInfo = {
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const TURNTABLE_VIDEO_URL = '/turntable.mp4'
|
||||
export const TURNTABLE_FRAME_RATE = 6
|
||||
export const TURNTABLE_TOTAL_FRAMES = 24
|
||||
export const TURNTABLE_DURATION = 4.0
|
||||
export const TURNTABLE_WIDTH = 1080
|
||||
export const TURNTABLE_HEIGHT = 1080
|
||||
|
||||
export const sampleTurntableAsset: AssetInfo = {
|
||||
id: 'e2e-turntable-asset',
|
||||
name: 'turntable.glb',
|
||||
proxyType: '3d',
|
||||
type: 'file',
|
||||
status: 'ready',
|
||||
sizeByte: 314488,
|
||||
fileCount: 1,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoPreview: {
|
||||
url: TURNTABLE_VIDEO_URL,
|
||||
},
|
||||
original: {
|
||||
key: 'turntable.glb',
|
||||
},
|
||||
metadata: {
|
||||
duration: TURNTABLE_DURATION,
|
||||
originalWidth: TURNTABLE_WIDTH,
|
||||
originalHeight: TURNTABLE_HEIGHT,
|
||||
frameRate: TURNTABLE_FRAME_RATE,
|
||||
totalFrames: TURNTABLE_TOTAL_FRAMES,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { type ReactElement, useCallback, useRef, useState } from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import type { MediaController } from '@/ui/components/viewers/types'
|
||||
import VideoPlayer from '@/ui/components/viewers/video/video-viewer'
|
||||
import ModelViewer from '@/ui/components/viewers/model/model-viewer'
|
||||
import { calculateFrameCenterTime } from '@/ui/components/viewers/video/utils'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import {
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
containerLongerVideoAsset,
|
||||
longAudioVideoAsset,
|
||||
sampleAudioAsset,
|
||||
sampleTurntableAsset,
|
||||
} from './fixture'
|
||||
|
||||
/**
|
||||
@@ -60,6 +62,7 @@ function resolveAsset() {
|
||||
if (variant === 'container-longer') return containerLongerVideoAsset
|
||||
if (variant === 'long-audio') return longAudioVideoAsset
|
||||
if (variant === 'audio') return sampleAudioAsset
|
||||
if (variant === '3d' || variant === 'turntable') return sampleTurntableAsset
|
||||
return sampleVideoAsset
|
||||
}
|
||||
|
||||
@@ -132,12 +135,21 @@ function Harness(): ReactElement {
|
||||
style={{ width: '800px', height: '600px', display: 'flex', overflow: 'hidden' }}
|
||||
>
|
||||
<div className="flex flex-col flex-1 h-full overflow-hidden relative">
|
||||
<VideoPlayer
|
||||
key={playerKey}
|
||||
file={harnessAsset}
|
||||
ref={playerRef}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
/>
|
||||
{harnessAsset.proxyType === '3d' ? (
|
||||
<ModelViewer
|
||||
key={playerKey}
|
||||
file={harnessAsset}
|
||||
ref={playerRef}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
/>
|
||||
) : (
|
||||
<VideoPlayer
|
||||
key={playerKey}
|
||||
file={harnessAsset}
|
||||
ref={playerRef}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -34,6 +34,10 @@ const server = Bun.serve({
|
||||
new Response(Bun.file(join(fixturesDir, 'sample-audio.mp4')), {
|
||||
headers: { 'Content-Type': 'video/mp4' },
|
||||
}),
|
||||
'/turntable.mp4': () =>
|
||||
new Response(Bun.file(join(fixturesDir, 'turntable.mp4')), {
|
||||
headers: { 'Content-Type': 'video/mp4' },
|
||||
}),
|
||||
'/': index,
|
||||
'/*': index,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { Locator, Page } from '@playwright/test'
|
||||
|
||||
const MODEL_VIDEO_SELECTOR = '[data-testid="model-viewer-surface"] video'
|
||||
|
||||
export interface ModelViewerSnapshot {
|
||||
degree: number
|
||||
currentTime: number
|
||||
frameHash: string
|
||||
}
|
||||
|
||||
export class ModelViewerPage {
|
||||
readonly page: Page
|
||||
readonly stage: Locator
|
||||
readonly container: Locator
|
||||
readonly surface: Locator
|
||||
readonly video: Locator
|
||||
readonly playToggle: Locator
|
||||
readonly degreeReadout: Locator
|
||||
readonly rulerSlider: Locator
|
||||
readonly rulerStepMinus: Locator
|
||||
readonly rulerStepPlus: Locator
|
||||
readonly rulerTooltip: Locator
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page
|
||||
this.stage = page.getByTestId('harness-stage')
|
||||
this.container = page.getByTestId('model-viewer-container')
|
||||
this.surface = page.getByTestId('model-viewer-surface')
|
||||
this.video = page.locator(MODEL_VIDEO_SELECTOR).first()
|
||||
this.playToggle = page.getByTestId('play-toggle')
|
||||
this.degreeReadout = page.getByTestId('degree-readout')
|
||||
this.rulerSlider = page.locator('[role="slider"]')
|
||||
this.rulerStepMinus = page.getByTestId('ruler-step-minus')
|
||||
this.rulerStepPlus = page.getByTestId('ruler-step-plus')
|
||||
this.rulerTooltip = page.getByTestId('ruler-slider-tooltip')
|
||||
}
|
||||
|
||||
async goto(): Promise<void> {
|
||||
await this.page.goto('/?variant=3d')
|
||||
await this.waitUntilReady()
|
||||
}
|
||||
|
||||
async waitUntilReady(): Promise<void> {
|
||||
await this.video.waitFor({ state: 'attached' })
|
||||
await this.page.waitForFunction(
|
||||
(selector) => {
|
||||
const el = document.querySelector(selector) as HTMLVideoElement | null
|
||||
return !!el && el.readyState >= 1 && Number.isFinite(el.duration)
|
||||
},
|
||||
MODEL_VIDEO_SELECTOR,
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
await this.page.waitForFunction(
|
||||
() => {
|
||||
const readout = document.querySelector('[data-testid="degree-readout"]')
|
||||
return !!readout && /\d+°\s*\/\s*360°/.test(readout.textContent ?? '')
|
||||
},
|
||||
undefined,
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
}
|
||||
|
||||
async getDegree(): Promise<number> {
|
||||
const text = (await this.degreeReadout.textContent()) ?? ''
|
||||
const match = text.match(/(\d+)°\s*\/\s*360°/)
|
||||
return match ? Number.parseInt(match[1], 10) : Number.NaN
|
||||
}
|
||||
|
||||
async getCurrentTime(): Promise<number> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => el.currentTime)
|
||||
}
|
||||
|
||||
/**
|
||||
* Captures a perceptual pixel hash of the video's current rendered frame.
|
||||
* Two frames displaying identical visuals yield the identical hash.
|
||||
*/
|
||||
async captureFrameHash(): Promise<string> {
|
||||
return this.video.evaluate((el: HTMLVideoElement) => {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = 64
|
||||
canvas.height = 64
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return ''
|
||||
ctx.drawImage(el, 0, 0, 64, 64)
|
||||
const data = ctx.getImageData(0, 0, 64, 64).data
|
||||
let hash = 0
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
hash = ((hash << 5) - hash + data[i]) | 0
|
||||
}
|
||||
return `${hash}_${data[0]}_${data[100]}_${data[500]}_${data[1000]}`
|
||||
})
|
||||
}
|
||||
|
||||
async snapshot(): Promise<ModelViewerSnapshot> {
|
||||
const [degree, currentTime, frameHash] = await Promise.all([
|
||||
this.getDegree(),
|
||||
this.getCurrentTime(),
|
||||
this.captureFrameHash(),
|
||||
])
|
||||
return { degree, currentTime, frameHash }
|
||||
}
|
||||
|
||||
async stepPlus(): Promise<void> {
|
||||
await this.rulerStepPlus.click()
|
||||
}
|
||||
|
||||
async stepMinus(): Promise<void> {
|
||||
await this.rulerStepMinus.click()
|
||||
}
|
||||
|
||||
async pressArrowRight(): Promise<void> {
|
||||
await this.page.keyboard.press('ArrowRight')
|
||||
}
|
||||
|
||||
async pressArrowLeft(): Promise<void> {
|
||||
await this.page.keyboard.press('ArrowLeft')
|
||||
}
|
||||
|
||||
async dragSurface(deltaX: number, steps = 5): Promise<void> {
|
||||
const box = await this.surface.boundingBox()
|
||||
if (!box) throw new Error('Surface bounding box not found')
|
||||
const startX = box.x + box.width / 2
|
||||
const startY = box.y + box.height / 2
|
||||
await this.page.mouse.move(startX, startY)
|
||||
await this.page.mouse.down()
|
||||
await this.page.mouse.move(startX + deltaX, startY, { steps })
|
||||
await this.page.mouse.up()
|
||||
}
|
||||
|
||||
async dragSlider(deltaX: number, steps = 5): Promise<void> {
|
||||
const box = await this.rulerSlider.boundingBox()
|
||||
if (!box) throw new Error('Slider bounding box not found')
|
||||
const startX = box.x + box.width / 2
|
||||
const startY = box.y + box.height / 2
|
||||
await this.page.mouse.move(startX, startY)
|
||||
await this.page.mouse.down()
|
||||
await this.page.mouse.move(startX + deltaX, startY, { steps })
|
||||
await this.page.mouse.up()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { ModelViewerPage } from '../pages/model-viewer.page'
|
||||
|
||||
test.describe('3D Asset Viewer E2E Tests', () => {
|
||||
/**
|
||||
* ISSUE 1 VERIFICATION:
|
||||
* Asserts that all 24 frames across 0° to 345° have completely unique visual scenes.
|
||||
* Specifically, verifies that pairs like [0°, 15°], [45°, 60°], [90°, 105°], etc.
|
||||
* decode distinct frames instead of showing the same scene.
|
||||
*/
|
||||
test('Issue 1: verifies all 24 degree angles render unique visual frames', async ({ page }) => {
|
||||
const viewer = new ModelViewerPage(page)
|
||||
await viewer.goto()
|
||||
|
||||
// Step through each of the 24 angles: 0°, 15°, 30°, 45°, ..., 345°
|
||||
const snapshots: Array<{ degree: number; currentTime: number; frameHash: string }> = []
|
||||
|
||||
for (let i = 0; i < 24; i++) {
|
||||
// Allow video element decoding and frame presentation to settle
|
||||
await page.waitForTimeout(100)
|
||||
const snap = await viewer.snapshot()
|
||||
snapshots.push(snap)
|
||||
|
||||
if (i < 23) {
|
||||
await viewer.stepPlus()
|
||||
}
|
||||
}
|
||||
|
||||
console.log('--- SNAPSHOTS ACROSS ALL 24 STEPS ---')
|
||||
for (const snap of snapshots) {
|
||||
console.log(
|
||||
`Degree: ${snap.degree}°, currentTime: ${snap.currentTime.toFixed(6)}, frameHash: ${snap.frameHash}`,
|
||||
)
|
||||
}
|
||||
|
||||
// Verify all 24 frames have unique hashes
|
||||
const uniqueHashes = new Set(snapshots.map((s) => s.frameHash))
|
||||
expect(uniqueHashes.size).toBe(24)
|
||||
|
||||
// Verify all adjacent pairs have distinct scenes
|
||||
for (let i = 0; i < 23; i++) {
|
||||
const snapA = snapshots[i]
|
||||
const snapB = snapshots[i + 1]
|
||||
expect(snapA.frameHash).not.toBe(snapB.frameHash)
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* ISSUE 2 VERIFICATION (Surface):
|
||||
* Asserts that at 345°, starting a drag or making small drag movements
|
||||
* maintains the 345° position rather than snapping backwards to 330°.
|
||||
*/
|
||||
test('Issue 2: verifies drag-to-rotate on viewer surface at 345 degrees does not jitter', async ({
|
||||
page,
|
||||
}) => {
|
||||
const viewer = new ModelViewerPage(page)
|
||||
await viewer.goto()
|
||||
|
||||
// Step backward from 0° -> wraps to 345°
|
||||
await viewer.stepMinus()
|
||||
await page.waitForTimeout(100)
|
||||
|
||||
const initialSnap = await viewer.snapshot()
|
||||
expect(initialSnap.degree).toBe(345)
|
||||
|
||||
const box = await viewer.surface.boundingBox()
|
||||
if (!box) throw new Error('Surface box not found')
|
||||
const startX = box.x + box.width / 2
|
||||
const startY = box.y + box.height / 2
|
||||
|
||||
// Mouse down at 345°
|
||||
await page.mouse.move(startX, startY)
|
||||
await page.mouse.down()
|
||||
|
||||
// Small drag of -4px (less than 12px / 2 = 6px threshold for 1 frame)
|
||||
await page.mouse.move(startX - 4, startY, { steps: 2 })
|
||||
await page.waitForTimeout(50)
|
||||
const degreeSmallDrag = await viewer.getDegree()
|
||||
// Must remain at 345° (no jitter back to 330°)
|
||||
expect(degreeSmallDrag).toBe(345)
|
||||
|
||||
// Drag left by -12px (rotates counterclockwise by 1 frame: 345° -> 0°)
|
||||
await page.mouse.move(startX - 12, startY, { steps: 2 })
|
||||
await page.waitForTimeout(50)
|
||||
const degreeCcw = await viewer.getDegree()
|
||||
expect(degreeCcw).toBe(0)
|
||||
|
||||
// Drag back to start position (0px delta relative to start)
|
||||
await page.mouse.move(startX, startY, { steps: 2 })
|
||||
await page.waitForTimeout(50)
|
||||
const degreeBack = await viewer.getDegree()
|
||||
expect(degreeBack).toBe(345)
|
||||
|
||||
// Drag right by +12px (rotates clockwise by 1 frame: 345° -> 330°)
|
||||
await page.mouse.move(startX + 12, startY, { steps: 2 })
|
||||
await page.waitForTimeout(50)
|
||||
const degreeCw = await viewer.getDegree()
|
||||
expect(degreeCw).toBe(330)
|
||||
|
||||
await page.mouse.up()
|
||||
})
|
||||
|
||||
/**
|
||||
* ISSUE 2 VERIFICATION (Slider):
|
||||
* Asserts that dragging the ruler slider across 345° and 0° scrolls smoothly
|
||||
* and transitions between angles cleanly.
|
||||
*/
|
||||
test('Issue 2 (slider): verifies dragging ruler slider across 345° and 0° transitions smoothly', async ({
|
||||
page,
|
||||
}) => {
|
||||
const viewer = new ModelViewerPage(page)
|
||||
await viewer.goto()
|
||||
|
||||
// Navigate to 345°
|
||||
await viewer.stepMinus()
|
||||
await page.waitForTimeout(100)
|
||||
expect(await viewer.getDegree()).toBe(345)
|
||||
|
||||
const sliderBox = await viewer.rulerSlider.boundingBox()
|
||||
if (!sliderBox) throw new Error('Slider box not found')
|
||||
const startX = sliderBox.x + sliderBox.width / 2
|
||||
const startY = sliderBox.y + sliderBox.height / 2
|
||||
|
||||
await page.mouse.move(startX, startY)
|
||||
await page.mouse.down()
|
||||
|
||||
// Drag slightly left (-12px) across 345° towards 0°
|
||||
await page.mouse.move(startX - 12, startY, { steps: 2 })
|
||||
await page.waitForTimeout(50)
|
||||
const degCross = await viewer.getDegree()
|
||||
expect(degCross).toBe(0)
|
||||
|
||||
// Drag further left (-32px) to 15°
|
||||
await page.mouse.move(startX - 32, startY, { steps: 2 })
|
||||
await page.waitForTimeout(50)
|
||||
const degFurther = await viewer.getDegree()
|
||||
expect(degFurther).toBe(15)
|
||||
|
||||
// Drag back to 0px
|
||||
await page.mouse.move(startX, startY, { steps: 2 })
|
||||
await page.waitForTimeout(50)
|
||||
const degBack = await viewer.getDegree()
|
||||
expect(degBack).toBe(345)
|
||||
|
||||
await page.mouse.up()
|
||||
})
|
||||
|
||||
/**
|
||||
* ISSUE 3 VERIFICATION (Playback Frame Stepping):
|
||||
* Asserts that auto-rotating via play/pause advances through consecutive 15° steps
|
||||
* (e.g. 0° -> 15° -> 30° -> 45°) without skipping intermediate frames like 30°.
|
||||
*/
|
||||
test('Issue 3: verifies auto-rotation playback updates at consistent 15 degree increments', async ({
|
||||
page,
|
||||
}) => {
|
||||
const viewer = new ModelViewerPage(page)
|
||||
await viewer.goto()
|
||||
|
||||
// Start playback
|
||||
await viewer.playToggle.click()
|
||||
await page.waitForTimeout(100)
|
||||
|
||||
// Collect observed degree values over 1.5 seconds of playback (~9 frames at 6 FPS)
|
||||
const observedDegrees = new Set<number>()
|
||||
const startTime = Date.now()
|
||||
|
||||
while (Date.now() - startTime < 1500) {
|
||||
const deg = await viewer.getDegree()
|
||||
if (!Number.isNaN(deg)) {
|
||||
observedDegrees.add(deg)
|
||||
}
|
||||
await page.waitForTimeout(30)
|
||||
}
|
||||
|
||||
// Pause playback
|
||||
await viewer.playToggle.click()
|
||||
|
||||
// Verify that consecutive 15° frames including 30° and 60° were captured
|
||||
expect(observedDegrees.has(30)).toBe(true)
|
||||
expect(observedDegrees.has(45)).toBe(true)
|
||||
expect(observedDegrees.has(60)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -86,6 +86,19 @@ describe('getVideoResolutionLabel', () => {
|
||||
expect(getVideoResolutionLabel({ width: 320, height: 180 })).toBe('180p')
|
||||
})
|
||||
|
||||
it('derives resolution correctly for square and non-16:9 transcodes without explicit resolution', () => {
|
||||
// 1080p square (e.g. 1080x1080 3D turntable or square video)
|
||||
expect(getVideoResolutionLabel({ width: 1080, height: 1080 })).toBe('1080p')
|
||||
// 720p square
|
||||
expect(getVideoResolutionLabel({ width: 720, height: 720 })).toBe('720p')
|
||||
// 480p square
|
||||
expect(getVideoResolutionLabel({ width: 480, height: 480 })).toBe('480p')
|
||||
// 1080p 4:3
|
||||
expect(getVideoResolutionLabel({ width: 1440, height: 1080 })).toBe('1080p')
|
||||
// 720p 4:3
|
||||
expect(getVideoResolutionLabel({ width: 960, height: 720 })).toBe('720p')
|
||||
})
|
||||
|
||||
it('falls back to short side or single dimension for non-standard sizes', () => {
|
||||
expect(getVideoResolutionLabel({ width: 200, height: 100 })).toBe('100p')
|
||||
expect(getVideoResolutionLabel({ height: 720 })).toBe('720p')
|
||||
|
||||
@@ -59,15 +59,16 @@ export function getVideoResolutionLabel(
|
||||
|
||||
if (width > 0 && height > 0) {
|
||||
const longSide = Math.max(width, height)
|
||||
if (longSide >= 3840) return '2160p'
|
||||
if (longSide >= 2560) return '1440p'
|
||||
if (longSide >= 1920) return '1080p'
|
||||
if (longSide >= 1280) return '720p'
|
||||
if (longSide >= 854) return '480p'
|
||||
if (longSide >= 640) return '360p'
|
||||
if (longSide >= 320) return '180p'
|
||||
|
||||
const shortSide = Math.min(width, height)
|
||||
|
||||
if (longSide >= 3840 || shortSide >= 2160) return '2160p'
|
||||
if (longSide >= 2560 || shortSide >= 1440) return '1440p'
|
||||
if (longSide >= 1920 || shortSide >= 1080) return '1080p'
|
||||
if (longSide >= 1280 || shortSide >= 720) return '720p'
|
||||
if (longSide >= 854 || shortSide >= 480) return '480p'
|
||||
if (longSide >= 640 || shortSide >= 360) return '360p'
|
||||
if (longSide >= 320 || shortSide >= 180) return '180p'
|
||||
|
||||
return `${shortSide}p`
|
||||
}
|
||||
|
||||
|
||||
@@ -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