mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 20:34:28 +00:00
feat(premiere-uxp): introduce Adobe Premiere Pro UXP plugin for Shumai (#407)
* feat(premiere-uxp): use native Bun bundler and build script instead of Vite * feat(premiere-uxp): switch FileListView to use Search API consistent with WebUI * feat(premiere-uxp): add on-demand jpeg preview conversion for uxp compatibility * feat(premiere-uxp): integrate spectrum web components (swc) * fix(premiere-uxp): align swc packages with 0.37.0 and fix auth layout * feat(premiere-uxp): use horizontal 2-column card view for projects and files * style(premiere-uxp): enlarge file preview by 20% and add row padding * fix(premiere-uxp): prevent card squishing and overflow with large item counts * fix(premiere-uxp): change host in manifest to single object * docs(premiere-uxp): add AGENTS.md with SWC preferences and UXP layout rules * feat(premiere-uxp): integrate spectrum web components across plugin views * fix(premiere-uxp): remove breadcrumb icons and use slash separator * feat(premiere-uxp): add collapsible folder and file sections with infinite scroll * feat(premiere-uxp): update file card layout with right column info and clean preview * fix(premiere-uxp): use raw text for file card details and fix black icons * style(premiere-uxp): use contain object-fit and black background for file card preview * fix(premiere-uxp): refine header logo, sticky title bars, circular badges, and controls * fix(premiere-uxp): replace stroke icons with spectrum workflow icons * fix(premiere-uxp): switch icon buttons to swc sp-button with icon-only and slot=icon * fix(premiere-uxp): vertically center endpoint text in header * feat(premiere-uxp): add asset and proxy import support into Premiere Pro - Implement context menu on file cards with left-click, right-click, and more action button triggers - Support raw file import for non-video assets and video assets - Support video proxy submenu listing ready transcode resolutions - Add UXP native file picker save dialog and binary download orchestration - Call Premiere Pro project.importFiles API to import downloaded assets into active project - Add non-blocking toast notification banner for progress and status reporting - Add unit tests for premiere host service and import orchestration * fix(premiere-uxp): anchor import menu directly to file card using sp-action-menu - Replace custom fixed-position ContextMenu with native SWC sp-action-menu - Anchor menu directly to the triggered file card rather than the top-left window corner - Support programmatic opening on file card click/contextmenu via imperative handle - Support video submenu with Original and ready proxy options inside sp-action-menu - Lazy load video proxies on menu open or hover - Clean up obsolete fixed-position styles and unused backdrop overlays * fix(premiere-uxp): align SWC packages to 0.37.0 and guard custom element registry - Downgrade action-menu and menu SWC packages to 0.37.0 to match the rest of the workspace - Eliminate duplicate icons-ui and sp-icon-chevron100 customElements.define calls - Add polyfill guard to customElements.define to prevent duplicate registration errors during UXP reload * fix(premiere-uxp): polyfill window.matchMedia for Adobe UXP - Add window.matchMedia polyfill in polyfills.ts - Satisfies SWC MatchMediaController used by ActionMenu and PickerBase in UXP - Prevents TypeError when opening files page * feat(premiere-uxp): replace context menu with card download action and video import dialog * fix(premiere-uxp): resolve download url before save, pass null targetBin, and center download icon * fix(premiere-uxp): resolve raw download url via download-url endpoint with fallback * feat(premiere-uxp): use native folder picker and auto-increment conflict suffixes * feat(premiere-uxp): add sequence linking, comment-marker sync, and navigation tabs - Add sequence-to-asset linking with persistent project metadata storage - Support one-way comment-to-marker timeline synchronization - Add two-tab navigation (Sequences and Browse) using Spectrum buttons - Add LinkSequenceDialog, SequencesView, and autoSyncService background engine - Enforce Spectrum Workflow Icons and UXP layout rules * feat(premiere-uxp): refine UI layouts, card interactions, and search box activation * fix(premiere-uxp): set compact fixed width for file list search box * fix(premiere-uxp): ensure search box click activation across full width in UXP * fix(premiere-uxp): revert search box hacks and restore simple default sp-search layout * feat(premiere-uxp): sync non-timestamped comments as markers at time 0 * feat(premiere-uxp): change link icon to unlink when asset is linked in file card * fix(premiere-uxp): sync linked sequences between host project and browse view * feat(premiere-uxp): remove synced markers on sequence unlink matching Frame.io * fix(premiere-uxp): ensure reliable marker GUID capture, normalization, and fallback on unlink * fix(premiere-uxp): use official Shumai logo for plugin manifest icons * fix(premiere-uxp): use official PNG icons for manifest and plugin entrypoints * refactor(premiere-uxp): use single 114x114 icon for plugin and panel * feat(premiere-uxp): show file version in file list page file card * build(premiere-uxp): check in built ccx package and update packaging configuration * fix(premiere-uxp): address code review findings for media conversion, marker sync, and link scoping - Reset hasJpegCover on project cover update and hasJpegPreview on asset media transcode - Only advance synced comment metadata after confirmed marker transaction - Normalize GUID keys and lookups in AutoSyncService map - Restrict cached sequence link lookups to project-specific keys and prevent cross-project leakage on empty sequences - Update built CCX distribution package
This commit is contained in:
@@ -9,6 +9,8 @@ import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { AssetService } from './asset'
|
||||
|
||||
import { ensureJpegInStorage } from '@shumai/core/src/s3/preview-converter'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
|
||||
@@ -19,6 +21,14 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/s3/preview-converter', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/core/src/s3/preview-converter')>()
|
||||
return {
|
||||
...actual,
|
||||
ensureJpegInStorage: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AssetService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
@@ -1918,6 +1928,146 @@ describe('AssetService', () => {
|
||||
expect(info.preview).toBeDefined()
|
||||
expect(info.preview?.duration).toBeUndefined()
|
||||
})
|
||||
|
||||
it('converts webp thumbnail to jpeg on demand when hasJpegPreview is false', async () => {
|
||||
vi.mocked(ensureJpegInStorage).mockClear()
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
const image = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'photo.webp',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
sizeByte: 2000,
|
||||
mediaType: 'image/webp',
|
||||
status: 'processed',
|
||||
hasJpegPreview: false,
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
thumbnail: { key: 'shumai/files/1/thumb.webp' },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const preview = await assetService.toPreviewInfo(image, 'jpeg')
|
||||
|
||||
expect(preview).toBeDefined()
|
||||
expect(ensureJpegInStorage).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'shumai/files/1/thumb.webp',
|
||||
'shumai/files/1/thumb.jpeg',
|
||||
)
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'shumai/files/1/thumb.jpeg',
|
||||
'GET',
|
||||
)
|
||||
|
||||
const updated = await prisma.asset.findUnique({ where: { id: image.id } })
|
||||
expect(updated?.hasJpegPreview).toBe(true)
|
||||
})
|
||||
|
||||
it('skips conversion when hasJpegPreview is already true', async () => {
|
||||
vi.mocked(ensureJpegInStorage).mockClear()
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
const image = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'photo-converted.webp',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
sizeByte: 2000,
|
||||
mediaType: 'image/webp',
|
||||
status: 'processed',
|
||||
hasJpegPreview: true,
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
thumbnail: { key: 'shumai/files/2/thumb.webp' },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const preview = await assetService.toPreviewInfo(image, 'jpeg')
|
||||
|
||||
expect(preview).toBeDefined()
|
||||
expect(ensureJpegInStorage).not.toHaveBeenCalled()
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'shumai/files/2/thumb.jpeg',
|
||||
'GET',
|
||||
)
|
||||
})
|
||||
|
||||
it('gracefully falls back to webp when conversion fails', async () => {
|
||||
vi.mocked(ensureJpegInStorage).mockRejectedValueOnce(new Error('Sharp conversion failed'))
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
const image = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'failing.webp',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
sizeByte: 2000,
|
||||
mediaType: 'image/webp',
|
||||
status: 'processed',
|
||||
hasJpegPreview: false,
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
thumbnail: { key: 'shumai/files/3/thumb.webp' },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const preview = await assetService.toPreviewInfo(image, 'jpeg')
|
||||
|
||||
expect(preview).toBeDefined()
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'shumai/files/3/thumb.webp',
|
||||
'GET',
|
||||
)
|
||||
|
||||
const updated = await prisma.asset.findUnique({ where: { id: image.id } })
|
||||
expect(updated?.hasJpegPreview).toBe(false)
|
||||
})
|
||||
|
||||
it('listAssetsByIds forwards previewFormat and converts preview', async () => {
|
||||
vi.mocked(ensureJpegInStorage).mockClear()
|
||||
const { project, user } = await setupBasicAssets()
|
||||
|
||||
const image = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'list-photo.webp',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
sizeByte: 2000,
|
||||
mediaType: 'image/webp',
|
||||
status: 'processed',
|
||||
hasJpegPreview: false,
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
thumbnail: { key: 'shumai/files/4/thumb.webp' },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
},
|
||||
})
|
||||
|
||||
const list = await assetService.listAssetsByIds([image.id], 'jpeg')
|
||||
|
||||
expect(list).toHaveLength(1)
|
||||
expect(ensureJpegInStorage).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'shumai/files/4/thumb.webp',
|
||||
'shumai/files/4/thumb.jpeg',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Symlinks', () => {
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
AssetUserInfo,
|
||||
ListRecentsRequest,
|
||||
CommentExportFormat,
|
||||
PreviewFormat,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
exportCommentsToFormat,
|
||||
@@ -32,6 +33,11 @@ import { HTTPException } from 'hono/http-exception'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
ensureJpegInStorage,
|
||||
getJpegKeyForWebp,
|
||||
isWebpKey,
|
||||
} from '@shumai/core/src/s3/preview-converter'
|
||||
import { dedupeSymlinksToTarget } from './symlink'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
@@ -133,7 +139,7 @@ export class AssetService {
|
||||
return [folderId, ...ids]
|
||||
}
|
||||
|
||||
async listAssetsByIds(ids: string[]): Promise<AssetInfo[]> {
|
||||
async listAssetsByIds(ids: string[], previewFormat?: PreviewFormat): Promise<AssetInfo[]> {
|
||||
if (ids.length === 0) return []
|
||||
|
||||
const assets = await this.prismaClient.asset.findMany({
|
||||
@@ -145,7 +151,7 @@ export class AssetService {
|
||||
const orderedAssets = ids
|
||||
.map((id) => assetMap.get(id))
|
||||
.filter((a): a is AssetWithIncludes => !!a)
|
||||
const orderedInfos = await this.toAssetInfos(orderedAssets)
|
||||
const orderedInfos = await this.toAssetInfos(orderedAssets, previewFormat)
|
||||
|
||||
return orderedInfos
|
||||
}
|
||||
@@ -2036,7 +2042,10 @@ export class AssetService {
|
||||
return exportCommentsToFormat(metadata, comments, format, options)
|
||||
}
|
||||
|
||||
async toAssetInfos(assets: AssetWithIncludes[]): Promise<AssetInfo[]> {
|
||||
async toAssetInfos(
|
||||
assets: AssetWithIncludes[],
|
||||
previewFormat?: PreviewFormat,
|
||||
): Promise<AssetInfo[]> {
|
||||
const stackIds = new Set<string>()
|
||||
|
||||
for (const a of assets) {
|
||||
@@ -2150,7 +2159,7 @@ export class AssetService {
|
||||
id: stackId,
|
||||
versions: await Promise.all(
|
||||
versions.map(async (v, i) => {
|
||||
const preview = await this.toPreviewInfo(v as Asset)
|
||||
const preview = await this.toPreviewInfo(v as Asset, previewFormat)
|
||||
return {
|
||||
version: versions.length - i,
|
||||
current: i === 0,
|
||||
@@ -2208,12 +2217,12 @@ export class AssetService {
|
||||
|
||||
latestChildren.push({
|
||||
type: mediaType,
|
||||
preview: await this.toPreviewInfo(previewAsset),
|
||||
preview: await this.toPreviewInfo(previewAsset, previewFormat),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const preview = await this.toPreviewInfo(latestVersion as Asset)
|
||||
const preview = await this.toPreviewInfo(latestVersion as Asset, previewFormat)
|
||||
|
||||
const creator = latestVersion.creator
|
||||
? {
|
||||
@@ -2374,6 +2383,7 @@ export class AssetService {
|
||||
const assets = await this.prismaClient.asset.findMany({
|
||||
where: { id: { in: assetIds }, isDeleted: false },
|
||||
select: {
|
||||
id: true,
|
||||
projectId: true,
|
||||
type: true,
|
||||
target: { select: { projectId: true } },
|
||||
@@ -2386,6 +2396,16 @@ export class AssetService {
|
||||
if (asset.type === 'symlink' && asset.target?.projectId) {
|
||||
projId = asset.target.projectId
|
||||
}
|
||||
if (!projId) {
|
||||
try {
|
||||
const ctx = await this.getAssetContext(asset.id)
|
||||
if (ctx.projectId) {
|
||||
projId = ctx.projectId
|
||||
}
|
||||
} catch {
|
||||
// ignore if no team/project context
|
||||
}
|
||||
}
|
||||
if (projId) {
|
||||
projectIds.add(projId)
|
||||
}
|
||||
@@ -2604,24 +2624,48 @@ export class AssetService {
|
||||
)
|
||||
}
|
||||
|
||||
async toPreviewInfo(asset: Asset | AssetWithIncludes): Promise<PreviewInfo | null> {
|
||||
async toPreviewInfo(
|
||||
asset: Asset | AssetWithIncludes,
|
||||
previewFormat?: PreviewFormat,
|
||||
): Promise<PreviewInfo | null> {
|
||||
if (!asset.media) return null
|
||||
|
||||
const proxyType = (asset.media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
|
||||
let thumbnailUrl = undefined
|
||||
let rawThumbKey: string | undefined
|
||||
if (proxyType === 'image' && asset.media.thumbnail?.key) {
|
||||
thumbnailUrl = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
asset.media.thumbnail.key,
|
||||
'GET',
|
||||
)
|
||||
rawThumbKey = asset.media.thumbnail.key
|
||||
} else if (asset.media.poster?.key) {
|
||||
thumbnailUrl = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
asset.media.poster.key,
|
||||
'GET',
|
||||
)
|
||||
rawThumbKey = asset.media.poster.key
|
||||
}
|
||||
|
||||
let thumbnailUrl = undefined
|
||||
if (rawThumbKey) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
let finalKey = rawThumbKey
|
||||
if (previewFormat === 'jpeg' && isWebpKey(rawThumbKey)) {
|
||||
const targetJpegKey = getJpegKeyForWebp(rawThumbKey)
|
||||
if (asset.hasJpegPreview) {
|
||||
finalKey = targetJpegKey
|
||||
} else {
|
||||
try {
|
||||
await ensureJpegInStorage(bucket, rawThumbKey, targetJpegKey)
|
||||
await this.prismaClient.asset.update({
|
||||
where: { id: asset.id },
|
||||
data: { hasJpegPreview: true },
|
||||
})
|
||||
asset.hasJpegPreview = true
|
||||
finalKey = targetJpegKey
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, assetId: asset.id, rawThumbKey },
|
||||
'Failed to ensure JPEG preview for asset, falling back to WebP',
|
||||
)
|
||||
finalKey = rawThumbKey
|
||||
}
|
||||
}
|
||||
}
|
||||
thumbnailUrl = await s3Service.presign(bucket, finalKey, 'GET')
|
||||
}
|
||||
|
||||
let spriteUrl = undefined
|
||||
|
||||
@@ -5,6 +5,8 @@ import { ProjectService } from './project'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
|
||||
import { ensureJpegInStorage } from '@shumai/core/src/s3/preview-converter'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
presign: vi.fn(),
|
||||
@@ -13,6 +15,14 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/s3/preview-converter', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/core/src/s3/preview-converter')>()
|
||||
return {
|
||||
...actual,
|
||||
ensureJpegInStorage: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
})
|
||||
|
||||
describe('ProjectService', () => {
|
||||
setupTestDbHooks()
|
||||
let projectService: ProjectService
|
||||
@@ -562,4 +572,116 @@ describe('ProjectService', () => {
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('previewFormat handling', () => {
|
||||
it('converts webp cover to jpeg on demand and updates hasJpegCover in listProjects', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Preview Team' } })
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'preview-u1', email: 'preview-u1@example.com' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'Proj WebP',
|
||||
teamId: team.id,
|
||||
coverImageKey: 'projects/p1/cover.webp',
|
||||
hasJpegCover: false,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await projectService.listProjects({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
previewFormat: 'jpeg',
|
||||
pagination: {},
|
||||
})
|
||||
|
||||
expect(res.data).toHaveLength(1)
|
||||
expect(ensureJpegInStorage).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'projects/p1/cover.webp',
|
||||
'projects/p1/cover.jpeg',
|
||||
)
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'projects/p1/cover.jpeg',
|
||||
'GET',
|
||||
)
|
||||
|
||||
const updated = await prisma.project.findUnique({ where: { id: project.id } })
|
||||
expect(updated?.hasJpegCover).toBe(true)
|
||||
})
|
||||
|
||||
it('skips conversion if hasJpegCover is already true in getUserProjects', async () => {
|
||||
vi.mocked(ensureJpegInStorage).mockClear()
|
||||
const team = await prisma.team.create({ data: { name: 'Preview Team 2' } })
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'preview-u2', email: 'preview-u2@example.com' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
|
||||
await prisma.project.create({
|
||||
data: {
|
||||
name: 'Proj JPEG',
|
||||
teamId: team.id,
|
||||
coverImageKey: 'projects/p2/cover.webp',
|
||||
hasJpegCover: true,
|
||||
},
|
||||
})
|
||||
|
||||
const result = await projectService.getUserProjects(user.id, 10, 'jpeg')
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(ensureJpegInStorage).not.toHaveBeenCalled()
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'projects/p2/cover.jpeg',
|
||||
'GET',
|
||||
)
|
||||
})
|
||||
|
||||
it('resets hasJpegCover to false when coverImageKey changes during updateProject and reconverts', async () => {
|
||||
vi.mocked(ensureJpegInStorage).mockClear()
|
||||
const team = await prisma.team.create({ data: { name: 'Preview Team 3' } })
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'preview-u3', email: 'preview-u3@example.com' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'Proj Original',
|
||||
teamId: team.id,
|
||||
coverImageKey: 'projects/p3/original.webp',
|
||||
hasJpegCover: true,
|
||||
},
|
||||
})
|
||||
|
||||
await projectService.updateProject({
|
||||
projectId: project.id,
|
||||
coverImageKey: 'projects/p3/replacement.webp',
|
||||
})
|
||||
|
||||
const afterUpdate = await prisma.project.findUnique({ where: { id: project.id } })
|
||||
expect(afterUpdate?.coverImageKey).toBe('projects/p3/replacement.webp')
|
||||
expect(afterUpdate?.hasJpegCover).toBe(false)
|
||||
|
||||
const fetched = await projectService.getUserProjects(user.id, 10, 'jpeg')
|
||||
expect(fetched).toHaveLength(1)
|
||||
expect(ensureJpegInStorage).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'projects/p3/replacement.webp',
|
||||
'projects/p3/replacement.jpeg',
|
||||
)
|
||||
const afterFetch = await prisma.project.findUnique({ where: { id: project.id } })
|
||||
expect(afterFetch?.hasJpegCover).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,6 +5,12 @@ import { paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import {
|
||||
ensureJpegInStorage,
|
||||
getJpegKeyForWebp,
|
||||
isWebpKey,
|
||||
} from '@shumai/core/src/s3/preview-converter'
|
||||
import {
|
||||
ServiceCreateProjectRequest,
|
||||
ServiceUpdateProjectRequest,
|
||||
@@ -14,6 +20,7 @@ import {
|
||||
ServiceUpdateProjectMemberRoleRequest,
|
||||
ProjectInfo,
|
||||
ProjectUserInfo,
|
||||
PreviewFormat,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
export class ProjectService {
|
||||
@@ -99,11 +106,15 @@ export class ProjectService {
|
||||
if (!project) throw new Error('Project not found')
|
||||
if (!project.team) throw new Error('Project has no team')
|
||||
|
||||
const isCoverChanged =
|
||||
req.coverImageKey !== undefined && req.coverImageKey !== project.coverImageKey
|
||||
|
||||
const updatedProject = await prisma.project.update({
|
||||
where: { id: req.projectId },
|
||||
data: {
|
||||
name: req.name,
|
||||
coverImageKey: req.coverImageKey,
|
||||
...(isCoverChanged ? { hasJpegCover: false } : {}),
|
||||
enableNotification: req.enableNotification,
|
||||
},
|
||||
include: { rootFolder: true },
|
||||
@@ -153,7 +164,9 @@ export class ProjectService {
|
||||
take,
|
||||
include: { rootFolder: true },
|
||||
})
|
||||
const infos = await Promise.all(projects.map((p) => this.toProjectInfo(p)))
|
||||
const infos = await Promise.all(
|
||||
projects.map((p) => this.toProjectInfo(p, req.previewFormat)),
|
||||
)
|
||||
return infos
|
||||
},
|
||||
null,
|
||||
@@ -162,7 +175,11 @@ export class ProjectService {
|
||||
return res
|
||||
}
|
||||
|
||||
async getUserProjects(userId: string, limit = 200): Promise<ProjectInfo[]> {
|
||||
async getUserProjects(
|
||||
userId: string,
|
||||
limit = 200,
|
||||
previewFormat?: PreviewFormat,
|
||||
): Promise<ProjectInfo[]> {
|
||||
const teamMembers = await prisma.teamMember.findMany({
|
||||
where: { userId },
|
||||
})
|
||||
@@ -184,7 +201,7 @@ export class ProjectService {
|
||||
take: limit - allProjects.length,
|
||||
include: { rootFolder: true },
|
||||
})
|
||||
const infos = await Promise.all(teamProjects.map((p) => this.toProjectInfo(p)))
|
||||
const infos = await Promise.all(teamProjects.map((p) => this.toProjectInfo(p, previewFormat)))
|
||||
allProjects.push(...infos)
|
||||
if (allProjects.length >= limit) {
|
||||
break
|
||||
@@ -503,7 +520,7 @@ export class ProjectService {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private async toProjectInfo(p: any): Promise<ProjectInfo> {
|
||||
private async toProjectInfo(p: any, previewFormat?: PreviewFormat): Promise<ProjectInfo> {
|
||||
const pi: ProjectInfo = {
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
@@ -522,7 +539,30 @@ export class ProjectService {
|
||||
if (p.coverImageKey) {
|
||||
try {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const url = await s3Service.presign(bucket, p.coverImageKey, 'GET')
|
||||
let finalKey = p.coverImageKey
|
||||
if (previewFormat === 'jpeg' && isWebpKey(p.coverImageKey)) {
|
||||
const targetJpegKey = getJpegKeyForWebp(p.coverImageKey)
|
||||
if (p.hasJpegCover) {
|
||||
finalKey = targetJpegKey
|
||||
} else {
|
||||
try {
|
||||
await ensureJpegInStorage(bucket, p.coverImageKey, targetJpegKey)
|
||||
await prisma.project.update({
|
||||
where: { id: p.id },
|
||||
data: { hasJpegCover: true },
|
||||
})
|
||||
p.hasJpegCover = true
|
||||
finalKey = targetJpegKey
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, projectId: p.id, coverImageKey: p.coverImageKey },
|
||||
'Failed to ensure JPEG cover for project, falling back to WebP',
|
||||
)
|
||||
finalKey = p.coverImageKey
|
||||
}
|
||||
}
|
||||
}
|
||||
const url = await s3Service.presign(bucket, finalKey, 'GET')
|
||||
pi.coverImage = url
|
||||
} catch (e: unknown) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ensureJpegInStorage, getJpegKeyForWebp, isWebpKey } from './preview-converter'
|
||||
import { s3Service } from './s3'
|
||||
|
||||
vi.mock('./s3', () => ({
|
||||
s3Service: {
|
||||
getObject: vi.fn(),
|
||||
putObject: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('sharp', () => {
|
||||
return {
|
||||
default: vi.fn(() => ({
|
||||
jpeg: vi.fn().mockReturnThis(),
|
||||
toBuffer: vi.fn().mockResolvedValue(Buffer.from('converted-jpeg-data')),
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
describe('preview-converter', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('isWebpKey', () => {
|
||||
it('returns true for .webp files case-insensitively', () => {
|
||||
expect(isWebpKey('thumb.webp')).toBe(true)
|
||||
expect(isWebpKey('folder/IMAGE.WEBP')).toBe(true)
|
||||
expect(isWebpKey('a/b/c/file.WebP')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for non-webp files or empty inputs', () => {
|
||||
expect(isWebpKey('thumb.jpeg')).toBe(false)
|
||||
expect(isWebpKey('thumb.png')).toBe(false)
|
||||
expect(isWebpKey('')).toBe(false)
|
||||
expect(isWebpKey(null)).toBe(false)
|
||||
expect(isWebpKey(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getJpegKeyForWebp', () => {
|
||||
it('replaces .webp extension with .jpeg', () => {
|
||||
expect(getJpegKeyForWebp('path/to/thumb.webp')).toBe('path/to/thumb.jpeg')
|
||||
expect(getJpegKeyForWebp('path/to/thumb.WEBP')).toBe('path/to/thumb.jpeg')
|
||||
})
|
||||
|
||||
it('appends .jpeg if not ending with .webp', () => {
|
||||
expect(getJpegKeyForWebp('path/to/thumb')).toBe('path/to/thumb.jpeg')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureJpegInStorage', () => {
|
||||
it('converts webp to jpeg and puts it into storage', async () => {
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('fake-webp-buffer'),
|
||||
contentType: 'image/webp',
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.getObject>>)
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined)
|
||||
|
||||
await ensureJpegInStorage('my-bucket', 'path/thumb.webp', 'path/thumb.jpeg')
|
||||
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith('my-bucket', 'path/thumb.webp')
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'my-bucket',
|
||||
'path/thumb.jpeg',
|
||||
Buffer.from('converted-jpeg-data'),
|
||||
19,
|
||||
'image/jpeg',
|
||||
)
|
||||
})
|
||||
|
||||
it('throws error when object buffer is empty or missing', async () => {
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.alloc(0),
|
||||
} as unknown as Awaited<ReturnType<typeof s3Service.getObject>>)
|
||||
|
||||
await expect(
|
||||
ensureJpegInStorage('my-bucket', 'path/empty.webp', 'path/empty.jpeg'),
|
||||
).rejects.toThrow('Empty or missing buffer')
|
||||
})
|
||||
|
||||
it('deduplicates concurrent requests for the same image', async () => {
|
||||
let resolveGetObject: ((val: unknown) => void) | undefined
|
||||
const getObjectPromise = new Promise<unknown>((resolve) => {
|
||||
resolveGetObject = resolve
|
||||
})
|
||||
vi.mocked(s3Service.getObject).mockImplementation(
|
||||
() => getObjectPromise as ReturnType<typeof s3Service.getObject>,
|
||||
)
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined)
|
||||
|
||||
const p1 = ensureJpegInStorage('bucket', 'race.webp', 'race.jpeg')
|
||||
const p2 = ensureJpegInStorage('bucket', 'race.webp', 'race.jpeg')
|
||||
|
||||
// Resolve the object fetch
|
||||
resolveGetObject!({
|
||||
buffer: Buffer.from('race-webp-buffer'),
|
||||
})
|
||||
|
||||
await Promise.all([p1, p2])
|
||||
|
||||
// Only one getObject and putObject should have occurred
|
||||
expect(s3Service.getObject).toHaveBeenCalledTimes(1)
|
||||
expect(s3Service.putObject).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import sharp from 'sharp'
|
||||
import { s3Service } from './s3'
|
||||
import { logger } from '../logger'
|
||||
|
||||
const inFlightConversions = new Map<string, Promise<void>>()
|
||||
|
||||
/**
|
||||
* Checks if a key represents a WebP image.
|
||||
*/
|
||||
export function isWebpKey(key?: string | null): boolean {
|
||||
if (!key) return false
|
||||
return key.toLowerCase().endsWith('.webp')
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministically derives the target JPEG storage key for a WebP key.
|
||||
* e.g. "shumai/files/123/image-300p.webp" -> "shumai/files/123/image-300p.jpeg"
|
||||
*/
|
||||
export function getJpegKeyForWebp(key: string): string {
|
||||
if (key.toLowerCase().endsWith('.webp')) {
|
||||
return `${key.slice(0, -5)}.jpeg`
|
||||
}
|
||||
return `${key}.jpeg`
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that a JPEG version of the given WebP object exists in S3/storage.
|
||||
* Uses an in-flight Promise map to deduplicate concurrent requests for the same image.
|
||||
*/
|
||||
export async function ensureJpegInStorage(
|
||||
bucket: string,
|
||||
webpKey: string,
|
||||
jpegKey: string,
|
||||
): Promise<void> {
|
||||
const dedupeKey = `${bucket}:${webpKey}:${jpegKey}`
|
||||
const existing = inFlightConversions.get(dedupeKey)
|
||||
if (existing) {
|
||||
return await existing
|
||||
}
|
||||
|
||||
const conversionPromise = (async () => {
|
||||
const obj = await s3Service.getObject(bucket, webpKey)
|
||||
if (!obj.buffer || obj.buffer.length === 0) {
|
||||
throw new Error(`Empty or missing buffer for WebP object at ${bucket}/${webpKey}`)
|
||||
}
|
||||
|
||||
const jpegBuffer = await sharp(obj.buffer).jpeg({ quality: 85 }).toBuffer()
|
||||
await s3Service.putObject(bucket, jpegKey, jpegBuffer, jpegBuffer.length, 'image/jpeg')
|
||||
logger.debug({ bucket, webpKey, jpegKey }, 'Converted and saved JPEG preview to storage')
|
||||
})()
|
||||
|
||||
inFlightConversions.set(dedupeKey, conversionPromise)
|
||||
try {
|
||||
await conversionPromise
|
||||
} catch (err) {
|
||||
logger.warn({ err, bucket, webpKey, jpegKey }, 'Failed to convert WebP preview to JPEG')
|
||||
throw err
|
||||
} finally {
|
||||
inFlightConversions.delete(dedupeKey)
|
||||
}
|
||||
}
|
||||
@@ -1027,4 +1027,21 @@ describe('SearchService — natural sort by name', () => {
|
||||
|
||||
expect(result.data.map((a) => a.name)).toEqual(['scene 2', 'scene 9', 'scene 10', 'scene 100'])
|
||||
})
|
||||
|
||||
it('forwards previewFormat to listAssetsByIds during search', async () => {
|
||||
const { root } = await setupSearchNaturalSortAssets(['file1'])
|
||||
const spy = vi.spyOn(assetService, 'listAssetsByIds')
|
||||
|
||||
await searchService.search(root.id, {
|
||||
recursively: true,
|
||||
assetType: 'file',
|
||||
operator: 'AND',
|
||||
conditions: [],
|
||||
isSemantic: false,
|
||||
previewFormat: 'jpeg',
|
||||
})
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(expect.any(Array), 'jpeg')
|
||||
spy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -135,7 +135,7 @@ export class SearchService {
|
||||
|
||||
// 6. Map back to full rich metadata and return time-based duplicate segments
|
||||
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
|
||||
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds)
|
||||
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds, req.previewFormat)
|
||||
const assetInfosMap = new Map<string, AssetInfo>()
|
||||
for (const info of fetchedInfos) {
|
||||
assetInfosMap.set(info.id, info)
|
||||
@@ -334,7 +334,7 @@ export class SearchService {
|
||||
|
||||
// Map back to full rich metadata
|
||||
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
|
||||
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds)
|
||||
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds, req.previewFormat)
|
||||
const assetInfosMap = new Map<string, AssetInfo>()
|
||||
for (const info of fetchedInfos) {
|
||||
assetInfosMap.set(info.id, info)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { mapConcurrent } from '../utils/async'
|
||||
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { execFile } from 'child_process'
|
||||
@@ -12,6 +11,7 @@ import PDFDocument from 'pdfkit'
|
||||
import sharp from 'sharp'
|
||||
import { ulid } from 'ulid'
|
||||
import { promisify } from 'util'
|
||||
import { mapConcurrent } from '../utils/async'
|
||||
import { dataFormatNames } from './dataFormatNames'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
Reference in New Issue
Block a user