mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(comments): add printable comments page with frame thumbnails and markup overlays (#550)
* feat(comments): add printable comments page with frame thumbnails and markup overlays * fix(comments): guarantee frame-accurate ffmpeg seeking for printable comment thumbnails * fix(comments): address printable comments review findings
This commit is contained in:
@@ -8,12 +8,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
- **comments**: Add a "Print Comments" option in the comments menu (available in both project file views and public share links) that opens a dedicated print-friendly page with asset metadata, comment thumbnails, visual markup overlays, replies, completion status, emoji reactions, and attachments.
|
||||
|
||||
- **share**: See view counts, last viewed times, and activity for public share links, including file and folder views, downloads, and comments.
|
||||
|
||||
- **share**: Add options to create a share link or add to existing share links directly from the media view dropdown menu, and open a quick share dialog with inline renaming, one-click link copying, and security settings upon creation.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing.
|
||||
|
||||
### Changed
|
||||
|
||||
## [0.7.1] - 2026-11-23
|
||||
|
||||
@@ -80,6 +80,7 @@ apps/web/e2e/
|
||||
| Owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings | `tests/project/create-share-link.spec.ts` |
|
||||
| Owner creates a share link and adds to an existing share link from media view | `tests/project/create-share-link.spec.ts` |
|
||||
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
|
||||
| Guests can unlock a protected printable comments link directly | `tests/project/share-password.spec.ts` |
|
||||
| Public page views and share activity appear in both management sidebars | `tests/project/share-activity.spec.ts` |
|
||||
| Opening a direct historical version link records the selected version | `tests/project/share-activity.spec.ts` |
|
||||
| Concurrent public opens count every view and deduplicate matching activity | `tests/project/share-activity.spec.ts` |
|
||||
|
||||
@@ -49,3 +49,33 @@ test('owner protects a share with a password and guests must enter it to view',
|
||||
await guestContext.close()
|
||||
}
|
||||
})
|
||||
|
||||
test('a guest can unlock a protected printable comments link directly', async ({
|
||||
file,
|
||||
browser,
|
||||
}) => {
|
||||
const { context, projectId, fileName, fileId } = file
|
||||
const share = await apiCreateShare(context.request, projectId, 'Shared Print')
|
||||
await apiAddAssetsToShare(context.request, share.id, [fileId])
|
||||
const res = await context.request.put(`/api/shares/${share.id}`, {
|
||||
data: { password: 'secret123' },
|
||||
})
|
||||
expect(res.ok()).toBe(true)
|
||||
|
||||
const guestContext = await browser.newContext()
|
||||
const page = await guestContext.newPage()
|
||||
try {
|
||||
await page.goto(`/print/comments/${fileId}?shareId=${share.id}`)
|
||||
const passwordInput = page.getByPlaceholder('Enter password')
|
||||
await expect(passwordInput).toBeVisible()
|
||||
await passwordInput.fill('wrong-password')
|
||||
await page.getByRole('button', { name: 'Confirm' }).click()
|
||||
await expect(page.getByText('Incorrect password. Please try again.')).toBeVisible()
|
||||
await passwordInput.fill('secret123')
|
||||
await page.getByRole('button', { name: 'Confirm' }).click()
|
||||
await expect(page.getByTitle(fileName)).toBeVisible()
|
||||
await expect(page).toHaveURL(`/print/comments/${fileId}?shareId=${share.id}`)
|
||||
} finally {
|
||||
await guestContext.close()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Hono, type Context, type Next } from 'hono'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import fileRoute from './file'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
@@ -90,7 +91,10 @@ describe('file api', () => {
|
||||
assetId: 'file1',
|
||||
} as unknown as Awaited<ReturnType<typeof assetService.getComment>>)
|
||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listAllComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'getProjectNameForAsset').mockResolvedValue('Demo Project')
|
||||
vi.spyOn(assetService, 'exportComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(commentFrameService, 'extractFrame').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
@@ -1095,4 +1099,89 @@ describe('file api', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /files/:fileId/comments/print and /frame routes', () => {
|
||||
it('returns asset, top-down breadcrumbs, and all comments for printing', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'file-1',
|
||||
name: 'demo.mp4',
|
||||
sizeByte: 100,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
proxyType: 'video',
|
||||
ancestorFolders: [
|
||||
{ id: 'f2', name: 'Inner' },
|
||||
{ id: 'f1', name: 'Outer' },
|
||||
],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.mocked(assetService.getProjectNameForAsset).mockResolvedValue('My Project')
|
||||
vi.mocked(assetService.listAllComments).mockResolvedValue([
|
||||
{
|
||||
id: 'c1',
|
||||
assetId: 'file-1',
|
||||
message: 'Looks great',
|
||||
annotations: null,
|
||||
second: 1.5,
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
},
|
||||
])
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/file-1/comments/print')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.breadcrumbs).toEqual(['My Project', 'Outer', 'Inner'])
|
||||
expect(body.comments).toHaveLength(1)
|
||||
expect(body.asset.id).toBe('file-1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'file-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('streams extracted frame image with cache headers', async () => {
|
||||
const buf = Buffer.from('mock-webp-bytes')
|
||||
vi.mocked(commentFrameService.extractFrame).mockResolvedValue({
|
||||
buffer: buf,
|
||||
mimeType: 'image/webp',
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/file-1/comments/frame?second=2.5&width=400')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('image/webp')
|
||||
expect(res.headers.get('cache-control')).toBe('private, max-age=300')
|
||||
const arr = new Uint8Array(await res.arrayBuffer())
|
||||
expect(Buffer.from(arr).toString()).toBe('mock-webp-bytes')
|
||||
expect(commentFrameService.extractFrame).toHaveBeenCalledWith({
|
||||
assetId: 'file-1',
|
||||
second: 2.5,
|
||||
width: 400,
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects invalid second query parameter with 400', async () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/file-1/comments/frame?second=-5')
|
||||
expect(res.status).toBe(400)
|
||||
expect(commentFrameService.extractFrame).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { commentService } from '@shumai/core/src/comment/comment'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
getDownloadLinksRequestSchema,
|
||||
getStoragePathsRequestSchema,
|
||||
completeCommentRequestSchema,
|
||||
commentFrameQuerySchema,
|
||||
exportCommentsRequestSchema,
|
||||
addCommentReactionRequestSchema,
|
||||
removeCommentReactionRequestSchema,
|
||||
@@ -248,6 +250,60 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.body(result.content)
|
||||
},
|
||||
)
|
||||
.get('/files/:fileId/comments/print', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const [asset, projectName, comments] = await Promise.all([
|
||||
assetService.getAsset({ assetId: fileId }),
|
||||
assetService.getProjectNameForAsset(fileId),
|
||||
assetService.listAllComments(fileId, user.id),
|
||||
])
|
||||
|
||||
const folderNames = (asset.ancestorFolders ?? [])
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((f) => f.name)
|
||||
.filter((name): name is string => Boolean(name))
|
||||
const breadcrumbs = projectName ? [projectName, ...folderNames] : folderNames
|
||||
|
||||
return c.json({
|
||||
asset,
|
||||
breadcrumbs,
|
||||
comments,
|
||||
})
|
||||
})
|
||||
.get('/files/:fileId/comments/frame', zValidator('query', commentFrameQuerySchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const { second, width } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const result = await commentFrameService.extractFrame({
|
||||
assetId: fileId,
|
||||
second,
|
||||
width,
|
||||
signal: c.req.raw.signal,
|
||||
})
|
||||
|
||||
return c.body(new Uint8Array(result.buffer), 200, {
|
||||
'Content-Type': result.mimeType,
|
||||
'Cache-Control': 'private, max-age=300',
|
||||
})
|
||||
})
|
||||
.post(
|
||||
'/comments/:commentId/reactions',
|
||||
zValidator('json', addCommentReactionRequestSchema),
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import publicShareRoute from './public-share'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { ShareLinkPasswordInvalidError } from '@shumai/core/src/share/errors'
|
||||
|
||||
describe('public share print comments and frame api', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(auth.api, 'getSession').mockResolvedValue(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /shares/:shareId/files/:fileId/comments/print returns share-scoped breadcrumbs and comments', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share-1',
|
||||
name: 'Client Review',
|
||||
rootFolderId: 'share-root',
|
||||
projectId: 'proj-1',
|
||||
watermarkConfigId: null,
|
||||
} as never)
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockResolvedValue({
|
||||
id: 'file-1',
|
||||
name: 'spot.mp4',
|
||||
sizeByte: 100,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
proxyType: 'video',
|
||||
ancestorFolders: [
|
||||
{ id: 'inner', name: 'Inner Folder' },
|
||||
{ id: 'share-root', name: 'Share Root' },
|
||||
{ id: 'private-parent', name: 'Secret Project Folder' },
|
||||
],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file-1')
|
||||
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file-1')
|
||||
vi.spyOn(assetService, 'listAllComments').mockResolvedValue([
|
||||
{
|
||||
id: 'c1',
|
||||
assetId: 'file-1',
|
||||
message: 'Great cut!',
|
||||
annotations: null,
|
||||
second: 3,
|
||||
creator: { id: 'u1', name: 'Guest' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
},
|
||||
])
|
||||
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request('/shares/share-1/files/file-1/comments/print', {
|
||||
headers: { 'x-share-password': 'secret' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.breadcrumbs).toEqual(['Client Review', 'Inner Folder'])
|
||||
expect(body.asset.ancestorFolders).toEqual([{ id: 'inner', name: 'Inner Folder' }])
|
||||
expect(JSON.stringify(body)).not.toContain('Secret Project Folder')
|
||||
expect(JSON.stringify(body)).not.toContain('private-parent')
|
||||
expect(body.comments).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('GET /shares/:shareId/files/:fileId/comments/print returns 401 on invalid password', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockRejectedValue(
|
||||
new ShareLinkPasswordInvalidError('Invalid password'),
|
||||
)
|
||||
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request('/shares/share-1/files/file-1/comments/print')
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET /shares/:shareId/files/:fileId/comments/frame passes watermarkConfigId and password query param', async () => {
|
||||
const verifySpy = vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share-1',
|
||||
name: 'Watermarked Review',
|
||||
rootFolderId: 'share-root',
|
||||
projectId: 'proj-1',
|
||||
watermarkConfigId: 'wm-1',
|
||||
} as never)
|
||||
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('target-file-1')
|
||||
const extractSpy = vi.spyOn(commentFrameService, 'extractFrame').mockResolvedValue({
|
||||
buffer: Buffer.from('wm-webp'),
|
||||
mimeType: 'image/webp',
|
||||
})
|
||||
vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map())
|
||||
|
||||
const app = new Hono().route('/', publicShareRoute)
|
||||
const res = await app.request(
|
||||
'/shares/share-1/files/file-1/comments/frame?second=4.2&width=400&p=pw123',
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('image/webp')
|
||||
expect(verifySpy).toHaveBeenCalledWith('share-1', 'file-1', 'pw123')
|
||||
expect(extractSpy).toHaveBeenCalledWith({
|
||||
assetId: 'target-file-1',
|
||||
second: 4.2,
|
||||
width: 400,
|
||||
watermarkConfigId: 'wm-1',
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,14 +1,17 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getCookie } from 'hono/cookie'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { commentFrameService } from '@shumai/core/src/comment/comment-frame'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import {
|
||||
paginationParamsSchema,
|
||||
assetTypeFilterSchema,
|
||||
commentFrameQuerySchema,
|
||||
recordShareViewRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
@@ -400,6 +403,89 @@ const route = app
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId/comments/print', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
let asset = await assetService.getAsset({ assetId: fileId })
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
|
||||
|
||||
if (
|
||||
shareLink.watermarkConfigId &&
|
||||
(asset.proxyType === 'video' || asset.proxyType === 'image' || asset.proxyType === '3d')
|
||||
) {
|
||||
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
|
||||
[targetAssetId],
|
||||
shareLink.watermarkConfigId,
|
||||
)
|
||||
asset = await applyWatermarkToAssetMedia(
|
||||
asset,
|
||||
wfMap.get(targetAssetId) ?? null,
|
||||
shareLink.id,
|
||||
password,
|
||||
)
|
||||
}
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const userId = await getPublicShareUserId(c, shareId)
|
||||
const comments = await assetService.listAllComments(targetFileId, userId)
|
||||
|
||||
// Scope breadcrumbs strictly to folders inside the share link root so private
|
||||
// project and parent folder names are never leaked.
|
||||
const ancestors = asset.ancestorFolders ?? []
|
||||
const rootIndex = ancestors.findIndex((f) => f.id === shareLink.rootFolderId)
|
||||
const scopedAncestors = rootIndex !== -1 ? ancestors.slice(0, rootIndex) : []
|
||||
const scopedFolders = [...scopedAncestors]
|
||||
.reverse()
|
||||
.map((f) => f.name)
|
||||
.filter((name): name is string => Boolean(name))
|
||||
const breadcrumbs = shareLink.name ? [shareLink.name, ...scopedFolders] : scopedFolders
|
||||
|
||||
return c.json({
|
||||
asset: { ...asset, ancestorFolders: scopedAncestors },
|
||||
breadcrumbs,
|
||||
comments,
|
||||
})
|
||||
} catch (err) {
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments/frame',
|
||||
zValidator('query', commentFrameQuerySchema),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password =
|
||||
c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
|
||||
const { second, width } = c.req.valid('query')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const result = await commentFrameService.extractFrame({
|
||||
assetId: targetFileId,
|
||||
second,
|
||||
width,
|
||||
watermarkConfigId: shareLink.watermarkConfigId,
|
||||
signal: c.req.raw.signal,
|
||||
})
|
||||
|
||||
return c.body(new Uint8Array(result.buffer), 200, {
|
||||
'Content-Type': result.mimeType,
|
||||
'Cache-Control': 'private, max-age=300',
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof HTTPException) {
|
||||
throw err
|
||||
}
|
||||
return handlePublicShareError(c, err)
|
||||
}
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
|
||||
@@ -2289,6 +2289,35 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
private getCommentInclude() {
|
||||
return {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
asset: { include: { storageKey: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' as const },
|
||||
},
|
||||
replies: {
|
||||
include: {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' as const },
|
||||
},
|
||||
},
|
||||
orderBy: { id: 'asc' as const },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async listComments(
|
||||
assetId: string,
|
||||
params: PaginationParams,
|
||||
@@ -2300,32 +2329,7 @@ export class AssetService {
|
||||
async (skip, take) => {
|
||||
return this.prismaClient.assetComment.findMany({
|
||||
where: { assetId: resolvedAssetId, replyToId: null },
|
||||
include: {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
asset: { include: { storageKey: true } },
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
replies: {
|
||||
include: {
|
||||
creator: true,
|
||||
completionLastChangedBy: true,
|
||||
attachments: { include: { asset: { include: { storageKey: true } } } },
|
||||
reactions: {
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
},
|
||||
},
|
||||
include: this.getCommentInclude(),
|
||||
skip,
|
||||
take,
|
||||
orderBy: { id: 'asc' },
|
||||
@@ -2343,6 +2347,28 @@ export class AssetService {
|
||||
return { data: infos, pageInfo }
|
||||
}
|
||||
|
||||
async listAllComments(assetId: string, requestingUserId?: string): Promise<CommentInfo[]> {
|
||||
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
|
||||
|
||||
const comments = await this.prismaClient.assetComment.findMany({
|
||||
where: { assetId: resolvedAssetId, replyToId: null },
|
||||
include: this.getCommentInclude(),
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
return Promise.all(comments.map((c) => this.toCommentInfo(c, requestingUserId)))
|
||||
}
|
||||
|
||||
async getProjectNameForAsset(assetId: string): Promise<string | null> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: {
|
||||
project: { select: { name: true } },
|
||||
},
|
||||
})
|
||||
return asset?.project?.name ?? null
|
||||
}
|
||||
|
||||
async exportComments(
|
||||
assetId: string,
|
||||
format: CommentExportFormat,
|
||||
|
||||
@@ -0,0 +1,738 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import {
|
||||
CommentFrameService,
|
||||
FrameExtractionQueue,
|
||||
selectBestVideoProxyKey,
|
||||
type ExecFileFn,
|
||||
} from './comment-frame'
|
||||
import { execFileSync } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import sharp from 'sharp'
|
||||
|
||||
async function createSamplePngBuffer(): Promise<Buffer> {
|
||||
return sharp({
|
||||
create: {
|
||||
width: 32,
|
||||
height: 18,
|
||||
channels: 3,
|
||||
background: { r: 20, g: 120, b: 220 },
|
||||
},
|
||||
})
|
||||
.png()
|
||||
.toBuffer()
|
||||
}
|
||||
|
||||
async function createSampleWebpBuffer(): Promise<Buffer> {
|
||||
return sharp({
|
||||
create: {
|
||||
width: 32,
|
||||
height: 18,
|
||||
channels: 3,
|
||||
background: { r: 220, g: 80, b: 40 },
|
||||
},
|
||||
})
|
||||
.webp()
|
||||
.toBuffer()
|
||||
}
|
||||
|
||||
describe('FrameExtractionQueue', () => {
|
||||
it('enforces maxConcurrency and processes queued tasks in FIFO order', async () => {
|
||||
const queue = new FrameExtractionQueue(2)
|
||||
let active = 0
|
||||
let maxObserved = 0
|
||||
const order: number[] = []
|
||||
const resolvers: Array<() => void> = []
|
||||
|
||||
const makeTask = (id: number) =>
|
||||
queue.enqueue(async () => {
|
||||
active++
|
||||
maxObserved = Math.max(maxObserved, active)
|
||||
order.push(id)
|
||||
await new Promise<void>((resolve) => resolvers.push(resolve))
|
||||
active--
|
||||
return id
|
||||
})
|
||||
|
||||
const p1 = makeTask(1)
|
||||
const p2 = makeTask(2)
|
||||
const p3 = makeTask(3)
|
||||
const p4 = makeTask(4)
|
||||
|
||||
expect(queue.activeCount).toBe(2)
|
||||
expect(queue.queuedCount).toBe(2)
|
||||
expect(maxObserved).toBe(2)
|
||||
|
||||
resolvers.shift()?.()
|
||||
await p1
|
||||
expect(queue.activeCount).toBe(2)
|
||||
expect(queue.queuedCount).toBe(1)
|
||||
|
||||
resolvers.shift()?.()
|
||||
await p2
|
||||
expect(queue.activeCount).toBe(2)
|
||||
expect(queue.queuedCount).toBe(0)
|
||||
|
||||
resolvers.shift()?.()
|
||||
await p3
|
||||
resolvers.shift()?.()
|
||||
await p4
|
||||
|
||||
expect(order).toEqual([1, 2, 3, 4])
|
||||
expect(maxObserved).toBe(2)
|
||||
expect(queue.activeCount).toBe(0)
|
||||
expect(queue.queuedCount).toBe(0)
|
||||
})
|
||||
|
||||
it('cancels queued tasks when their AbortSignal fires before execution', async () => {
|
||||
const queue = new FrameExtractionQueue(1)
|
||||
let releaseFirst!: () => void
|
||||
const first = queue.enqueue(
|
||||
() =>
|
||||
new Promise<string>((resolve) => {
|
||||
releaseFirst = () => resolve('first')
|
||||
}),
|
||||
)
|
||||
|
||||
const controller = new AbortController()
|
||||
const runSecond = vi.fn().mockResolvedValue('second')
|
||||
const second = queue.enqueue(runSecond, controller.signal)
|
||||
|
||||
expect(queue.queuedCount).toBe(1)
|
||||
controller.abort()
|
||||
|
||||
await expect(second).rejects.toThrow('Frame extraction aborted')
|
||||
expect(queue.queuedCount).toBe(0)
|
||||
expect(runSecond).not.toHaveBeenCalled()
|
||||
|
||||
releaseFirst()
|
||||
await expect(first).resolves.toBe('first')
|
||||
})
|
||||
})
|
||||
|
||||
describe('selectBestVideoProxyKey', () => {
|
||||
it('prefers SDR proxies over HDR and chooses lowest adequate resolution >= 360p', () => {
|
||||
const key = selectBestVideoProxyKey([
|
||||
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
|
||||
{ key: 'sdr-1080.mp4', width: 1920, height: 1080, hdr: false, resolution: '1080p' },
|
||||
{ key: 'sdr-540.mp4', width: 960, height: 540, hdr: false, resolution: '540p' },
|
||||
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
|
||||
])
|
||||
expect(key).toBe('sdr-540.mp4')
|
||||
})
|
||||
|
||||
it('falls back to highest available SDR proxy if all are below 360p', () => {
|
||||
const key = selectBestVideoProxyKey([
|
||||
{ key: 'sdr-180.mp4', width: 320, height: 180, hdr: false, resolution: '180p' },
|
||||
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
|
||||
])
|
||||
expect(key).toBe('sdr-240.mp4')
|
||||
})
|
||||
|
||||
it('falls back to HDR proxy if no SDR proxy exists', () => {
|
||||
const key = selectBestVideoProxyKey([
|
||||
{ key: 'hdr-1080.mp4', width: 1920, height: 1080, hdr: true, resolution: '1080p' },
|
||||
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
|
||||
])
|
||||
expect(key).toBe('hdr-720.mp4')
|
||||
})
|
||||
|
||||
it('returns null when no valid keys exist', () => {
|
||||
expect(selectBestVideoProxyKey([])).toBeNull()
|
||||
expect(selectBestVideoProxyKey(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('CommentFrameService & AssetService print helpers', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let userId: string
|
||||
let teamId: string
|
||||
let projectId: string
|
||||
let rootFolderId: string
|
||||
let subFolderId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Alice',
|
||||
email: `alice-${Date.now()}-${Math.random()}@example.com`,
|
||||
},
|
||||
})
|
||||
userId = user.id
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Studio Team',
|
||||
},
|
||||
})
|
||||
teamId = team.id
|
||||
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root',
|
||||
type: AssetType.root,
|
||||
status: AssetStatus.processed,
|
||||
creatorId: userId,
|
||||
},
|
||||
})
|
||||
rootFolderId = rootFolder.id
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'Commercial Cut',
|
||||
teamId,
|
||||
rootFolderId,
|
||||
},
|
||||
})
|
||||
projectId = project.id
|
||||
|
||||
await prisma.asset.update({
|
||||
where: { id: rootFolderId },
|
||||
data: { projectId },
|
||||
})
|
||||
|
||||
const subFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Dailies',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.processed,
|
||||
projectId,
|
||||
parentId: rootFolderId,
|
||||
creatorId: userId,
|
||||
},
|
||||
})
|
||||
subFolderId = subFolder.id
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('skips extraction when the request is aborted during asset lookup', async () => {
|
||||
const storageKey = await prisma.storageKey.create({ data: { key: 'files/clip.mp4' } })
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
const controller = new AbortController()
|
||||
const resolveLatestVersionId = assetService.resolveLatestVersionId.bind(assetService)
|
||||
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementationOnce(async (assetId) => {
|
||||
const resolvedId = await resolveLatestVersionId(assetId)
|
||||
controller.abort()
|
||||
return resolvedId
|
||||
})
|
||||
const resolveInput = vi.spyOn(s3Service, 'resolveInput').mockResolvedValue('/local/clip.mp4')
|
||||
const execFileFn = vi.fn<ExecFileFn>().mockResolvedValue({ stdout: '', stderr: '' })
|
||||
const service = new CommentFrameService({ execFileFn })
|
||||
|
||||
await expect(
|
||||
service.extractFrame({ assetId: asset.id, second: 0, signal: controller.signal }),
|
||||
).rejects.toMatchObject({ name: 'AbortError' })
|
||||
expect(resolveInput).not.toHaveBeenCalled()
|
||||
expect(execFileFn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('extracts a video frame using the lowest adequate SDR proxy and deduplicates concurrent requests', async () => {
|
||||
const webpBuffer = await createSampleWebpBuffer()
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/video-original.mp4' },
|
||||
})
|
||||
const videoAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'scene1.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: 'video',
|
||||
duration: 10,
|
||||
filesize: 1000,
|
||||
frames: 240,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [
|
||||
{ key: 'files/proxies/1080p.mp4', width: 1920, height: 1080, hdr: false },
|
||||
{ key: 'files/proxies/540p.mp4', width: 960, height: 540, hdr: false },
|
||||
{ key: 'files/proxies/720p-hdr.mp4', width: 1280, height: 720, hdr: true },
|
||||
],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const resolveInputSpy = vi
|
||||
.spyOn(s3Service, 'resolveInput')
|
||||
.mockResolvedValue('/local/files/proxies/540p.mp4')
|
||||
|
||||
let releaseExec!: () => void
|
||||
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseExec = resolve
|
||||
})
|
||||
const outPath = args[args.length - 1]
|
||||
fs.writeFileSync(outPath, webpBuffer)
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const service = new CommentFrameService({ maxConcurrency: 2, execFileFn: execFileMock })
|
||||
|
||||
const p1 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
|
||||
const p2 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
|
||||
|
||||
// Let async DB lookup finish before releasing exec
|
||||
await vi.waitFor(() => expect(execFileMock).toHaveBeenCalledTimes(1))
|
||||
releaseExec()
|
||||
|
||||
const [r1, r2] = await Promise.all([p1, p2])
|
||||
expect(r1.mimeType).toBe('image/webp')
|
||||
expect(r1.buffer.equals(webpBuffer)).toBe(true)
|
||||
expect(r2.buffer.equals(webpBuffer)).toBe(true)
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/proxies/540p.mp4')
|
||||
})
|
||||
|
||||
it('extracts a 3D model turntable frame and enforces watermark-only proxies when watermarkConfigId is set', async () => {
|
||||
const webpBuffer = await createSampleWebpBuffer()
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/chair.glb' },
|
||||
})
|
||||
const modelAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'chair.glb',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'model/gltf-binary',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
duration: 24,
|
||||
filesize: 2000,
|
||||
frames: 24,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [{ key: 'files/proxies/turntable.mp4', width: 1024, height: 1024 }],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const watermarkSpy = vi
|
||||
.spyOn(watermarkService, 'getCompletedWatermarkMediaMap')
|
||||
.mockResolvedValueOnce(
|
||||
new Map([
|
||||
[
|
||||
modelAsset.id,
|
||||
{
|
||||
proxyType: '3d',
|
||||
duration: 24,
|
||||
filesize: 2000,
|
||||
frames: 24,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [{ key: 'files/wm/turntable-wm.mp4', width: 1024, height: 1024 }],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
],
|
||||
]),
|
||||
)
|
||||
.mockResolvedValueOnce(new Map())
|
||||
|
||||
const resolveInputSpy = vi
|
||||
.spyOn(s3Service, 'resolveInput')
|
||||
.mockResolvedValue('/local/files/wm/turntable-wm.mp4')
|
||||
|
||||
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
|
||||
const outPath = args[args.length - 1]
|
||||
fs.writeFileSync(outPath, webpBuffer)
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const service = new CommentFrameService({ execFileFn: execFileMock })
|
||||
|
||||
const res = await service.extractFrame({
|
||||
assetId: modelAsset.id,
|
||||
second: 3,
|
||||
width: 400,
|
||||
watermarkConfigId: 'wm-cfg-1',
|
||||
})
|
||||
expect(res.mimeType).toBe('image/webp')
|
||||
expect(watermarkSpy).toHaveBeenCalledWith([modelAsset.id], 'wm-cfg-1')
|
||||
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/wm/turntable-wm.mp4')
|
||||
|
||||
// Missing watermark proxy must reject with 422 rather than leaking unwatermarked media
|
||||
await expect(
|
||||
service.extractFrame({
|
||||
assetId: modelAsset.id,
|
||||
second: 3,
|
||||
width: 400,
|
||||
watermarkConfigId: 'wm-cfg-2',
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 422 })
|
||||
})
|
||||
|
||||
it('renders a PDF page frame via pdftoppm and sharp', async () => {
|
||||
const samplePng = await createSamplePngBuffer()
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/deck.pdf' },
|
||||
})
|
||||
const pdfAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'deck.pdf',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'application/pdf',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
media: {
|
||||
proxyType: 'pdf',
|
||||
duration: 0,
|
||||
filesize: 5000,
|
||||
frames: 5,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
pdfTranscode: { key: 'files/proxies/deck.pdf' },
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const downloadSpy = vi
|
||||
.spyOn(s3Service, 'downloadToFile')
|
||||
.mockImplementation(async (_bucket, _key, dest) => {
|
||||
fs.writeFileSync(dest, '%PDF-1.4 mock')
|
||||
})
|
||||
|
||||
const execFileMock = vi.fn<ExecFileFn>(async (file, args) => {
|
||||
expect(file).toBe('pdftoppm')
|
||||
expect(args[args.indexOf('-scale-to') + 1]).toBe('400')
|
||||
expect(args).toContain('-f')
|
||||
expect(args).toContain('3')
|
||||
const prefix = args[args.length - 1]
|
||||
fs.writeFileSync(`${prefix}-3.png`, samplePng)
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
|
||||
const service = new CommentFrameService({ execFileFn: execFileMock })
|
||||
const res = await service.extractFrame({ assetId: pdfAsset.id, second: 3, width: 400 })
|
||||
expect(downloadSpy).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'files/proxies/deck.pdf',
|
||||
expect.stringContaining(path.sep),
|
||||
)
|
||||
expect(res.mimeType).toBe('image/webp')
|
||||
expect(res.buffer.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('rejects unsupported asset types with 400 and archived assets without proxy with 422', async () => {
|
||||
const imgKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/photo.png' },
|
||||
})
|
||||
const imageAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'photo.png',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'image/png',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: imgKey.id,
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
duration: 0,
|
||||
filesize: 100,
|
||||
frames: 1,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const archivedKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/archived.mp4', isArchived: true },
|
||||
})
|
||||
const archivedVideo = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'archived.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.archived,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: archivedKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
const service = new CommentFrameService()
|
||||
await expect(service.extractFrame({ assetId: imageAsset.id, second: 0 })).rejects.toMatchObject(
|
||||
{ status: 400 },
|
||||
)
|
||||
await expect(
|
||||
service.extractFrame({ assetId: archivedVideo.id, second: 1 }),
|
||||
).rejects.toMatchObject({ status: 422 })
|
||||
await expect(
|
||||
service.extractFrame({ assetId: 'non-existent-id', second: 0 }),
|
||||
).rejects.toMatchObject({ status: 404 })
|
||||
})
|
||||
|
||||
it('lists all comments with replies, reactions, completion status, and fetches project name', async () => {
|
||||
vi.spyOn(s3Service, 'presign').mockResolvedValue('http://mock-s3/file')
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: { key: 'files/cut.mp4' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'cut.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
const parent = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
creatorId: userId,
|
||||
message: 'Check lighting',
|
||||
second: 1.5,
|
||||
isCompleted: true,
|
||||
completionLastChangedById: userId,
|
||||
},
|
||||
})
|
||||
await prisma.assetCommentReaction.create({
|
||||
data: { commentId: parent.id, userId, code: '👍' },
|
||||
})
|
||||
await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
creatorId: userId,
|
||||
replyToId: parent.id,
|
||||
message: 'Fixed in v2',
|
||||
},
|
||||
})
|
||||
|
||||
const allComments = await assetService.listAllComments(asset.id, userId)
|
||||
expect(allComments).toHaveLength(1)
|
||||
expect(allComments[0].message).toBe('Check lighting')
|
||||
expect(allComments[0].isCompleted).toBe(true)
|
||||
expect(allComments[0].reactionCounts).toEqual([
|
||||
expect.objectContaining({ code: '👍', count: 1, requestingUserReacted: true }),
|
||||
])
|
||||
expect(allComments[0].replies).toHaveLength(1)
|
||||
expect(allComments[0].replies[0].message).toBe('Fixed in v2')
|
||||
|
||||
const projectName = await assetService.getProjectNameForAsset(asset.id)
|
||||
expect(projectName).toBe('Commercial Cut')
|
||||
})
|
||||
|
||||
it('extracts exact frames with real ffmpeg for 30fps video, 23.976fps video, and 6fps 3D turntable', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-frame-acc-'))
|
||||
const w = 64
|
||||
const h = 64
|
||||
|
||||
const createColorCodedVideo = (filename: string, rateArg: string, totalFrames: number) => {
|
||||
const raw = Buffer.alloc(w * h * 3 * totalFrames)
|
||||
for (let n = 0; n < totalFrames; n++) {
|
||||
const r = (n * 9) & 255
|
||||
const g = (n * 15) & 255
|
||||
const off = n * w * h * 3
|
||||
for (let i = 0; i < w * h; i++) {
|
||||
raw[off + i * 3] = r
|
||||
raw[off + i * 3 + 1] = g
|
||||
raw[off + i * 3 + 2] = 120
|
||||
}
|
||||
}
|
||||
const rawPath = path.join(tmpDir, `${filename}.rgb`)
|
||||
const mp4Path = path.join(tmpDir, `${filename}.mp4`)
|
||||
fs.writeFileSync(rawPath, raw)
|
||||
execFileSync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-f',
|
||||
'rawvideo',
|
||||
'-pix_fmt',
|
||||
'rgb24',
|
||||
'-s',
|
||||
`${w}x${h}`,
|
||||
'-r',
|
||||
rateArg,
|
||||
'-i',
|
||||
rawPath,
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
'-g',
|
||||
'12',
|
||||
'-bf',
|
||||
'2',
|
||||
'-movflags',
|
||||
'+faststart',
|
||||
mp4Path,
|
||||
])
|
||||
return mp4Path
|
||||
}
|
||||
|
||||
const identifyExtractedFrame = async (webpBuffer: Buffer, totalFrames: number) => {
|
||||
const { data, info } = await sharp(webpBuffer).raw().toBuffer({ resolveWithObject: true })
|
||||
const cx = Math.floor(info.width / 2)
|
||||
const cy = Math.floor(info.height / 2)
|
||||
const idx = (cy * info.width + cx) * info.channels
|
||||
const r = data[idx]
|
||||
const g = data[idx + 1]
|
||||
let best = -1
|
||||
let bestDist = Infinity
|
||||
for (let n = 0; n < totalFrames; n++) {
|
||||
const dr = r - ((n * 9) & 255)
|
||||
const dg = g - ((n * 15) & 255)
|
||||
const dist = dr * dr + dg * dg
|
||||
if (dist < bestDist) {
|
||||
bestDist = dist
|
||||
best = n
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
try {
|
||||
const mp4Fps30 = createColorCodedVideo('v30', '30', 24)
|
||||
const mp4Fps23976 = createColorCodedVideo('v23976', '24000/1001', 24)
|
||||
const mp4Turntable = createColorCodedVideo('turntable', '6', 24)
|
||||
|
||||
const keyMap: Record<string, string> = {
|
||||
'files/proxies/v30.mp4': mp4Fps30,
|
||||
'files/proxies/v23976.mp4': mp4Fps23976,
|
||||
'files/proxies/turntable.mp4': mp4Turntable,
|
||||
}
|
||||
vi.spyOn(s3Service, 'resolveInput').mockImplementation(async (_bucket, key) => keyMap[key])
|
||||
|
||||
const createAsset = async (
|
||||
name: string,
|
||||
proxyType: 'video' | '3d',
|
||||
proxyKey: string,
|
||||
fps: number,
|
||||
totalFrames: number,
|
||||
) => {
|
||||
const sk = await prisma.storageKey.create({ data: { key: `files/${name}` } })
|
||||
return prisma.asset.create({
|
||||
data: {
|
||||
name,
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.processed,
|
||||
mediaType: proxyType === '3d' ? 'model/gltf-binary' : 'video/mp4',
|
||||
projectId,
|
||||
parentId: subFolderId,
|
||||
creatorId: userId,
|
||||
storageKeyId: sk.id,
|
||||
media: {
|
||||
proxyType,
|
||||
duration: totalFrames / fps,
|
||||
filesize: 1000,
|
||||
frames: totalFrames,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [{ key: proxyKey, width: 64, height: 64, hdr: false }],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: {
|
||||
originalHeight: h,
|
||||
originalWidth: w,
|
||||
hasAudio: false,
|
||||
bitRate: 100000,
|
||||
frameRate: fps,
|
||||
totalFrames,
|
||||
duration: totalFrames / fps,
|
||||
startTimecode: '00:00:00:00',
|
||||
format: {},
|
||||
},
|
||||
original: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const asset30 = await createAsset('v30.mp4', 'video', 'files/proxies/v30.mp4', 30, 24)
|
||||
const asset23976 = await createAsset(
|
||||
'v23976.mp4',
|
||||
'video',
|
||||
'files/proxies/v23976.mp4',
|
||||
24000 / 1001,
|
||||
24,
|
||||
)
|
||||
const asset3d = await createAsset('chair.glb', '3d', 'files/proxies/turntable.mp4', 6, 24)
|
||||
|
||||
const realService = new CommentFrameService({ maxConcurrency: 2 })
|
||||
|
||||
// Frames where .toFixed(4) previously rounded UP and skipped to N+1:
|
||||
// 30fps: frame 2 (0.06666... -> 0.0667), frame 5 (0.16666... -> 0.1667), frame 23 (last frame)
|
||||
for (const frame of [0, 2, 5, 8, 17, 23]) {
|
||||
const res = await realService.extractFrame({
|
||||
assetId: asset30.id,
|
||||
second: frame / 30,
|
||||
width: 64,
|
||||
})
|
||||
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||
}
|
||||
|
||||
// 23.976fps: frame 7 (0.291958 -> 0.2920), frame 8, frame 19, frame 23
|
||||
for (const frame of [0, 7, 8, 19, 23]) {
|
||||
const res = await realService.extractFrame({
|
||||
assetId: asset23976.id,
|
||||
second: frame / (24000 / 1001),
|
||||
width: 64,
|
||||
})
|
||||
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||
}
|
||||
|
||||
// 3D 6fps turntable where model-viewer stores center times ((N + 0.5) / 6, last = (23 + 0.25) / 6)
|
||||
for (const frame of [0, 1, 6, 12, 23]) {
|
||||
const centerSec = frame === 23 ? (frame + 0.25) / 6 : (frame + 0.5) / 6
|
||||
const res = await realService.extractFrame({
|
||||
assetId: asset3d.id,
|
||||
second: centerSec,
|
||||
width: 64,
|
||||
})
|
||||
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,557 @@
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { secondToTurntableFrame, TURNTABLE_FPS } from '@shumai/core/src/utils/model3d'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { prisma } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { execFile } from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import sharp from 'sharp'
|
||||
import { ulid } from 'ulid'
|
||||
import { promisify } from 'util'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const DEFAULT_CONCURRENCY = 4
|
||||
const DEFAULT_FRAME_TIMEOUT_MS = 30_000
|
||||
const MIN_PREFERRED_PROXY_HEIGHT = 360
|
||||
|
||||
export interface ExtractCommentFrameParams {
|
||||
assetId: string
|
||||
second: number
|
||||
width?: number
|
||||
watermarkConfigId?: string | null
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface ExtractCommentFrameResult {
|
||||
buffer: Buffer
|
||||
mimeType: string
|
||||
}
|
||||
|
||||
export type ExecFileFn = (
|
||||
file: string,
|
||||
args: string[],
|
||||
options?: { signal?: AbortSignal; timeout?: number },
|
||||
) => Promise<{ stdout: string | Buffer; stderr: string | Buffer }>
|
||||
|
||||
interface QueuedTask<T> {
|
||||
run: () => Promise<T>
|
||||
resolve: (value: T) => void
|
||||
reject: (err: unknown) => void
|
||||
signal?: AbortSignal
|
||||
onAbort?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded FIFO concurrency queue dedicated to on-demand comment frame extraction,
|
||||
* isolated from background transcode workers so print requests stay fast without
|
||||
* overloading the main API server.
|
||||
*/
|
||||
export class FrameExtractionQueue {
|
||||
private running = 0
|
||||
private readonly pending: QueuedTask<unknown>[] = []
|
||||
|
||||
constructor(private readonly maxConcurrency: number) {}
|
||||
|
||||
get activeCount(): number {
|
||||
return this.running
|
||||
}
|
||||
|
||||
get queuedCount(): number {
|
||||
return this.pending.length
|
||||
}
|
||||
|
||||
enqueue<T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
||||
if (signal?.aborted) {
|
||||
return Promise.reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
}
|
||||
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const task: QueuedTask<T> = { run, resolve, reject, signal }
|
||||
|
||||
if (signal) {
|
||||
const onAbort = () => {
|
||||
const idx = this.pending.indexOf(task as QueuedTask<unknown>)
|
||||
if (idx !== -1) {
|
||||
this.pending.splice(idx, 1)
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
}
|
||||
}
|
||||
task.onAbort = onAbort
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
}
|
||||
|
||||
this.pending.push(task as QueuedTask<unknown>)
|
||||
this.drain()
|
||||
})
|
||||
}
|
||||
|
||||
private drain(): void {
|
||||
while (this.running < this.maxConcurrency && this.pending.length > 0) {
|
||||
const task = this.pending.shift()
|
||||
if (!task) break
|
||||
|
||||
if (task.signal && task.onAbort) {
|
||||
task.signal.removeEventListener('abort', task.onAbort)
|
||||
}
|
||||
if (task.signal?.aborted) {
|
||||
task.reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
continue
|
||||
}
|
||||
|
||||
this.running++
|
||||
task.run().then(
|
||||
(result) => {
|
||||
this.running--
|
||||
this.drain()
|
||||
task.resolve(result)
|
||||
},
|
||||
(err) => {
|
||||
this.running--
|
||||
this.drain()
|
||||
task.reject(err)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the fastest video proxy suitable for thumbnail extraction:
|
||||
* 1. Prefer SDR proxies over HDR to avoid washed-out colors.
|
||||
* 2. Among SDR proxies, pick the lowest resolution that is still >= 360p (fast seek + decode
|
||||
* for a ~400px thumbnail). If none are >= 360p, pick the highest available SDR proxy.
|
||||
*/
|
||||
export function selectBestVideoProxyKey(
|
||||
videoTranscodes?: PrismaJson.VideoTranscode[] | null,
|
||||
): string | null {
|
||||
if (!videoTranscodes || videoTranscodes.length === 0) return null
|
||||
|
||||
const valid = videoTranscodes.filter((t) => Boolean(t.key))
|
||||
if (valid.length === 0) return null
|
||||
|
||||
const sdr = valid.filter((t) => !t.hdr)
|
||||
const pool = sdr.length > 0 ? sdr : valid
|
||||
|
||||
const adequate = pool
|
||||
.filter((t) => (t.height || 0) >= MIN_PREFERRED_PROXY_HEIGHT)
|
||||
.sort((a, b) => (a.height || 0) - (b.height || 0))
|
||||
if (adequate.length > 0) {
|
||||
return adequate[0].key ?? null
|
||||
}
|
||||
|
||||
const fallback = [...pool].sort((a, b) => (b.height || 0) - (a.height || 0))
|
||||
return fallback[0]?.key ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an ffmpeg `-ss` input seek timestamp that lands squarely on the exact
|
||||
* target frame displayed by Shumai's video and 3D turntable players.
|
||||
*
|
||||
* `ffmpeg -ss T -i input -vframes 1` outputs the first frame with `PTS >= T`.
|
||||
* Passing `N / fps` directly (especially after decimal rounding) or a frame center
|
||||
* `(N + 0.5) / fps` causes ffmpeg to skip frame `N` and emit frame `N + 1` whenever
|
||||
* `T` exceeds `PTS(N)` by even 1µs.
|
||||
*
|
||||
* Instead, we recover integer frame `N` with the exact player formula
|
||||
* (`Math.floor(second * fps + 0.45)` for video, `secondToTurntableFrame` for 3D)
|
||||
* and seek to the midpoint between frame `N - 1` and frame `N`: `(N - 0.5) / fps`,
|
||||
* leaving a full ±0.5 frame tolerance margin on both sides.
|
||||
*/
|
||||
export function resolveFrameAccurateSeek(params: {
|
||||
second: number
|
||||
proxyType: 'video' | '3d'
|
||||
frameRate?: number | null
|
||||
totalFrames?: number | null
|
||||
duration?: number | null
|
||||
}): { seekTime: number; frameIndex: number | null } {
|
||||
const safeSecond = Math.max(0, params.second)
|
||||
|
||||
if (params.proxyType === '3d') {
|
||||
const frameIndex = secondToTurntableFrame(safeSecond)
|
||||
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / TURNTABLE_FPS
|
||||
return { seekTime, frameIndex }
|
||||
}
|
||||
|
||||
const fps = params.frameRate && params.frameRate > 0 ? params.frameRate : null
|
||||
if (fps) {
|
||||
let frameIndex = Math.max(0, Math.floor(safeSecond * fps + 0.45))
|
||||
if (params.totalFrames && params.totalFrames > 0) {
|
||||
frameIndex = Math.min(frameIndex, params.totalFrames - 1)
|
||||
} else if (params.duration && params.duration > 0) {
|
||||
const maxFrame = Math.max(0, Math.round(params.duration * fps) - 1)
|
||||
frameIndex = Math.min(frameIndex, maxFrame)
|
||||
}
|
||||
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / fps
|
||||
return { seekTime, frameIndex }
|
||||
}
|
||||
|
||||
const seekTime =
|
||||
params.duration && params.duration > 0 && safeSecond >= params.duration
|
||||
? Math.max(0, params.duration - 0.05)
|
||||
: safeSecond
|
||||
return { seekTime, frameIndex: null }
|
||||
}
|
||||
|
||||
export class CommentFrameService {
|
||||
private readonly queue: FrameExtractionQueue
|
||||
private readonly inFlight = new Map<
|
||||
string,
|
||||
{
|
||||
promise: Promise<ExtractCommentFrameResult>
|
||||
controller: AbortController
|
||||
waiters: number
|
||||
}
|
||||
>()
|
||||
private readonly execFileFn: ExecFileFn
|
||||
private readonly timeoutMs: number
|
||||
|
||||
constructor(options?: { maxConcurrency?: number; timeoutMs?: number; execFileFn?: ExecFileFn }) {
|
||||
const envConcurrency = Number(process.env.PRINT_FRAME_CONCURRENCY)
|
||||
const maxConcurrency =
|
||||
options?.maxConcurrency ??
|
||||
(Number.isInteger(envConcurrency) && envConcurrency > 0
|
||||
? envConcurrency
|
||||
: DEFAULT_CONCURRENCY)
|
||||
this.queue = new FrameExtractionQueue(maxConcurrency)
|
||||
this.timeoutMs = options?.timeoutMs ?? DEFAULT_FRAME_TIMEOUT_MS
|
||||
this.execFileFn =
|
||||
options?.execFileFn ??
|
||||
((file, args, opts) =>
|
||||
execFileAsync(file, args, {
|
||||
signal: opts?.signal,
|
||||
timeout: opts?.timeout,
|
||||
maxBuffer: 10 * 1024 * 1024,
|
||||
}))
|
||||
}
|
||||
|
||||
async extractFrame(params: ExtractCommentFrameParams): Promise<ExtractCommentFrameResult> {
|
||||
if (params.signal?.aborted) {
|
||||
throw new DOMException('Frame extraction aborted', 'AbortError')
|
||||
}
|
||||
|
||||
const width = Math.max(64, Math.min(1280, Math.round(params.width ?? 400)))
|
||||
const second = Math.max(0, params.second)
|
||||
|
||||
const targetAssetId = await assetService.resolveLatestVersionId(params.assetId)
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
params.signal?.throwIfAborted()
|
||||
|
||||
if (!asset || asset.isDeleted) {
|
||||
throw new HTTPException(404, { message: 'Asset not found' })
|
||||
}
|
||||
|
||||
const media = asset.media as PrismaJson.MediaInfo | null
|
||||
const proxyType = media?.proxyType ?? this.inferProxyType(asset.mediaType)
|
||||
|
||||
if (proxyType !== 'video' && proxyType !== '3d' && proxyType !== 'pdf') {
|
||||
throw new HTTPException(400, {
|
||||
message: 'Frame extraction is only supported for video, 3D model, and PDF assets',
|
||||
})
|
||||
}
|
||||
|
||||
const frameTarget =
|
||||
proxyType === 'pdf'
|
||||
? null
|
||||
: resolveFrameAccurateSeek({
|
||||
second,
|
||||
proxyType,
|
||||
frameRate: media?.metadata?.frameRate,
|
||||
totalFrames: media?.metadata?.totalFrames ?? media?.frames,
|
||||
duration: media?.duration ?? media?.metadata?.duration,
|
||||
})
|
||||
|
||||
const normalizedKeyTime =
|
||||
proxyType === 'pdf'
|
||||
? `p${Math.max(1, Math.round(second))}`
|
||||
: frameTarget!.frameIndex !== null
|
||||
? `f${frameTarget!.frameIndex}`
|
||||
: frameTarget!.seekTime.toFixed(6)
|
||||
const dedupeKey = `${targetAssetId}:${params.watermarkConfigId ?? ''}:${normalizedKeyTime}:${width}`
|
||||
|
||||
let entry = this.inFlight.get(dedupeKey)
|
||||
if (!entry) {
|
||||
const controller = new AbortController()
|
||||
const promise = this.queue
|
||||
.enqueue(async () => {
|
||||
if (proxyType === 'pdf') {
|
||||
return this.extractPdfPageFrame({
|
||||
asset,
|
||||
media,
|
||||
page: Math.max(1, Math.round(second)),
|
||||
width,
|
||||
signal: controller.signal,
|
||||
})
|
||||
}
|
||||
return this.extractVideoFrame({
|
||||
asset,
|
||||
media,
|
||||
second,
|
||||
seekTime: frameTarget!.seekTime,
|
||||
frameRate: proxyType === '3d' ? TURNTABLE_FPS : media?.metadata?.frameRate,
|
||||
width,
|
||||
watermarkConfigId: params.watermarkConfigId,
|
||||
signal: controller.signal,
|
||||
})
|
||||
}, controller.signal)
|
||||
.finally(() => {
|
||||
if (this.inFlight.get(dedupeKey)?.promise === promise) {
|
||||
this.inFlight.delete(dedupeKey)
|
||||
}
|
||||
})
|
||||
|
||||
entry = { promise, controller, waiters: 0 }
|
||||
this.inFlight.set(dedupeKey, entry)
|
||||
}
|
||||
|
||||
entry.waiters++
|
||||
const currentEntry = entry
|
||||
|
||||
if (!params.signal) {
|
||||
return currentEntry.promise.finally(() => {
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
})
|
||||
}
|
||||
|
||||
return new Promise<ExtractCommentFrameResult>((resolve, reject) => {
|
||||
let settled = false
|
||||
const cleanup = () => {
|
||||
params.signal?.removeEventListener('abort', onAbort)
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
if (currentEntry.waiters === 0) {
|
||||
currentEntry.controller.abort()
|
||||
}
|
||||
}
|
||||
const onAbort = () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
cleanup()
|
||||
reject(new DOMException('Frame extraction aborted', 'AbortError'))
|
||||
}
|
||||
|
||||
params.signal!.addEventListener('abort', onAbort, { once: true })
|
||||
|
||||
currentEntry.promise.then(
|
||||
(res) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
params.signal?.removeEventListener('abort', onAbort)
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
resolve(res)
|
||||
},
|
||||
(err) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
params.signal?.removeEventListener('abort', onAbort)
|
||||
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
|
||||
reject(err)
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
private inferProxyType(mediaType: string | null): PrismaJson.MediaInfo['proxyType'] | undefined {
|
||||
const lower = (mediaType || '').toLowerCase()
|
||||
if (lower.startsWith('video/')) return 'video'
|
||||
if (lower === 'application/pdf') return 'pdf'
|
||||
if (lower.startsWith('image/')) return 'image'
|
||||
if (lower.startsWith('audio/')) return 'audio'
|
||||
return undefined
|
||||
}
|
||||
|
||||
private async extractVideoFrame(params: {
|
||||
asset: {
|
||||
id: string
|
||||
status: string
|
||||
storageKey: { key: string; isArchived: boolean } | null
|
||||
}
|
||||
media: PrismaJson.MediaInfo | null
|
||||
second: number
|
||||
seekTime: number
|
||||
frameRate?: number | null
|
||||
width: number
|
||||
watermarkConfigId?: string | null
|
||||
signal?: AbortSignal
|
||||
}): Promise<ExtractCommentFrameResult> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
let targetKey: string | null
|
||||
|
||||
if (params.watermarkConfigId) {
|
||||
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
|
||||
[params.asset.id],
|
||||
params.watermarkConfigId,
|
||||
)
|
||||
const watermarkMedia = wfMap.get(params.asset.id) ?? null
|
||||
targetKey = selectBestVideoProxyKey(watermarkMedia?.videoTranscodes)
|
||||
if (!targetKey) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Watermarked proxy is not ready for this asset',
|
||||
})
|
||||
}
|
||||
} else {
|
||||
targetKey = selectBestVideoProxyKey(params.media?.videoTranscodes)
|
||||
if (!targetKey) {
|
||||
const originalKey = params.asset.storageKey?.key
|
||||
const isArchived =
|
||||
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
|
||||
if (!originalKey || isArchived) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Original video file is archived and no proxy is available',
|
||||
})
|
||||
}
|
||||
targetKey = originalKey
|
||||
}
|
||||
}
|
||||
|
||||
const inputSource = await s3Service.resolveInput(bucket, targetKey)
|
||||
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-frame-'))
|
||||
|
||||
try {
|
||||
const outPath = path.join(tmpDir, `frame-${ulid()}.webp`)
|
||||
const runFfmpeg = async (timestamp: number) => {
|
||||
const args = [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
...(isRemote
|
||||
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
|
||||
: []),
|
||||
'-ss',
|
||||
timestamp.toFixed(6),
|
||||
'-i',
|
||||
inputSource,
|
||||
'-map',
|
||||
'0:V:0',
|
||||
'-vframes',
|
||||
'1',
|
||||
'-vf',
|
||||
`scale=${params.width}:-2:force_original_aspect_ratio=decrease`,
|
||||
'-c:v',
|
||||
'libwebp',
|
||||
'-q:v',
|
||||
'80',
|
||||
outPath,
|
||||
]
|
||||
await this.execFileFn('ffmpeg', args, {
|
||||
signal: params.signal,
|
||||
timeout: this.timeoutMs,
|
||||
})
|
||||
}
|
||||
|
||||
await runFfmpeg(params.seekTime)
|
||||
|
||||
// If container metadata overestimated totalFrames at EOF, step back one frame and retry.
|
||||
if ((!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) && params.seekTime > 0) {
|
||||
const stepBack = params.frameRate && params.frameRate > 0 ? 1 / params.frameRate : 0.1
|
||||
await runFfmpeg(Math.max(0, params.seekTime - stepBack))
|
||||
}
|
||||
|
||||
if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) {
|
||||
throw new HTTPException(404, { message: 'Could not extract frame at requested timestamp' })
|
||||
}
|
||||
|
||||
const buffer = fs.readFileSync(outPath)
|
||||
return { buffer, mimeType: 'image/webp' }
|
||||
} catch (err) {
|
||||
if (err instanceof HTTPException) throw err
|
||||
if ((err as { name?: string })?.name === 'AbortError') throw err
|
||||
logger.error(
|
||||
{ assetId: params.asset.id, second: params.second, err },
|
||||
'Failed to extract video comment frame',
|
||||
)
|
||||
throw new HTTPException(500, { message: 'Failed to extract video frame' })
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async extractPdfPageFrame(params: {
|
||||
asset: {
|
||||
id: string
|
||||
status: string
|
||||
storageKey: { key: string; isArchived: boolean } | null
|
||||
}
|
||||
media: PrismaJson.MediaInfo | null
|
||||
page: number
|
||||
width: number
|
||||
signal?: AbortSignal
|
||||
}): Promise<ExtractCommentFrameResult> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const proxyKey = params.media?.pdfTranscode?.key
|
||||
const originalKey = params.asset.storageKey?.key
|
||||
const isArchived =
|
||||
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
|
||||
|
||||
let targetKey: string | null = proxyKey || null
|
||||
if (!targetKey) {
|
||||
if (!originalKey || isArchived) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Original PDF file is archived and no proxy is available',
|
||||
})
|
||||
}
|
||||
targetKey = originalKey
|
||||
}
|
||||
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-pdf-'))
|
||||
try {
|
||||
const pdfPath = path.join(tmpDir, 'source.pdf')
|
||||
await s3Service.downloadToFile(bucket, targetKey, pdfPath)
|
||||
|
||||
const pagePrefix = path.join(tmpDir, 'page')
|
||||
await this.execFileFn(
|
||||
'pdftoppm',
|
||||
[
|
||||
'-png',
|
||||
'-scale-to',
|
||||
String(params.width),
|
||||
'-f',
|
||||
String(params.page),
|
||||
'-l',
|
||||
String(params.page),
|
||||
pdfPath,
|
||||
pagePrefix,
|
||||
],
|
||||
{
|
||||
signal: params.signal,
|
||||
timeout: this.timeoutMs,
|
||||
},
|
||||
)
|
||||
|
||||
const pngFile = fs.readdirSync(tmpDir).find((f) => f.endsWith('.png'))
|
||||
if (!pngFile) {
|
||||
throw new HTTPException(404, { message: `PDF page ${params.page} not found` })
|
||||
}
|
||||
|
||||
const buffer = await sharp(path.join(tmpDir, pngFile), {
|
||||
limitInputPixels: (params.width + 1) ** 2,
|
||||
})
|
||||
.toColorspace('srgb')
|
||||
.webp({ quality: 82 })
|
||||
.toBuffer()
|
||||
|
||||
return { buffer, mimeType: 'image/webp' }
|
||||
} catch (err) {
|
||||
if (err instanceof HTTPException) throw err
|
||||
if ((err as { name?: string })?.name === 'AbortError') throw err
|
||||
logger.error(
|
||||
{ assetId: params.asset.id, page: params.page, err },
|
||||
'Failed to render PDF comment page frame',
|
||||
)
|
||||
throw new HTTPException(500, { message: 'Failed to render PDF page' })
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const commentFrameService = new CommentFrameService()
|
||||
@@ -5,6 +5,7 @@ export * from './asset/auto-archive-job'
|
||||
export * from './auth/auth'
|
||||
export * from './authz/authz'
|
||||
export * from './collection/collection'
|
||||
export * from './comment/comment-frame'
|
||||
export * from './invite/invite'
|
||||
export * from './metadata/metadata'
|
||||
export * from './notification/index'
|
||||
|
||||
@@ -485,3 +485,18 @@ export type ExportCommentsRequest = z.infer<typeof exportCommentsRequestSchema>
|
||||
export const exportCommentsQuerySchema = exportCommentsRequestSchema
|
||||
/** @deprecated Use ExportCommentsRequest */
|
||||
export type ExportCommentsQuery = ExportCommentsRequest
|
||||
|
||||
export const commentFrameQuerySchema = z.object({
|
||||
second: z.coerce.number().refine((val) => Number.isFinite(val) && val >= 0, {
|
||||
message: 'second must be a non-negative finite number',
|
||||
}),
|
||||
width: z.coerce.number().int().min(64).max(1280).optional().default(400),
|
||||
})
|
||||
export type CommentFrameQuery = z.infer<typeof commentFrameQuerySchema>
|
||||
|
||||
export const printCommentsResponseSchema = z.object({
|
||||
asset: assetInfoSchema,
|
||||
breadcrumbs: z.array(z.string()),
|
||||
comments: z.array(commentInfoSchema),
|
||||
})
|
||||
export type PrintCommentsResponse = z.infer<typeof printCommentsResponseSchema>
|
||||
|
||||
@@ -154,7 +154,8 @@ describe('FileViewerRightSidebar - Comments Export', () => {
|
||||
expect(screen.getByRole('button', { name: 'More options' })).toBeDefined()
|
||||
})
|
||||
|
||||
it('does NOT render "All comments" header row in public share view', async () => {
|
||||
it('renders "All comments" header with Print Comments (and without Export Comments) in public share view', async () => {
|
||||
const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<FileViewerRightSidebar
|
||||
@@ -169,8 +170,49 @@ describe('FileViewerRightSidebar - Comments Export', () => {
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.queryByText('All comments')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'More options' })).toBeNull()
|
||||
expect(screen.getByText('All comments')).toBeDefined()
|
||||
const moreButton = screen.getByRole('button', { name: 'More options' })
|
||||
fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false })
|
||||
|
||||
const printItem = await screen.findByText('Print Comments')
|
||||
expect(printItem).toBeDefined()
|
||||
expect(screen.queryByText('Export Comments')).toBeNull()
|
||||
|
||||
fireEvent.click(printItem)
|
||||
expect(windowOpenSpy).toHaveBeenCalledWith(
|
||||
'/print/comments/file-123?shareId=share-123',
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
)
|
||||
windowOpenSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('opens printable comments page from authenticated sidebar menu', async () => {
|
||||
const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<FileViewerRightSidebar
|
||||
teamId="team-1"
|
||||
projectId="proj-1"
|
||||
file={mockFile}
|
||||
onSaveField={vi.fn()}
|
||||
members={[{ id: 'user-1', name: 'User One', role: 'owner' }]}
|
||||
isPublic={false}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const moreButton = screen.getByRole('button', { name: 'More options' })
|
||||
fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false })
|
||||
|
||||
const printItem = await screen.findByText('Print Comments')
|
||||
fireEvent.click(printItem)
|
||||
expect(windowOpenSpy).toHaveBeenCalledWith(
|
||||
'/print/comments/file-123',
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
)
|
||||
windowOpenSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('opens dropdown menu with Export Comments and the 4 NLE options', async () => {
|
||||
|
||||
@@ -88,6 +88,15 @@ export function FileViewerRightSidebar({
|
||||
second?: number | null
|
||||
} | null>(null)
|
||||
|
||||
const handlePrintComments = () => {
|
||||
if (!file?.id) return
|
||||
const url =
|
||||
isPublic && shareId
|
||||
? `/print/comments/${encodeURIComponent(file.id)}?shareId=${encodeURIComponent(shareId)}`
|
||||
: `/print/comments/${encodeURIComponent(file.id)}`
|
||||
window.open(url, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
const handleExportComments = async (format: CommentExportFormat) => {
|
||||
if (!file?.id || isExporting) return
|
||||
try {
|
||||
@@ -361,21 +370,21 @@ export function FileViewerRightSidebar({
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
|
||||
{!isPublic && (
|
||||
<div className="flex items-center justify-between px-1 py-1.5 shrink-0 border-b border-border/50">
|
||||
<span className="text-xs font-semibold text-foreground">{m.all_comments()}</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
aria-label={m.more_options()}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<div className="flex items-center justify-between px-1 py-1.5 shrink-0 border-b border-border/50">
|
||||
<span className="text-xs font-semibold text-foreground">{m.all_comments()}</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
aria-label={m.more_options()}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
{!isPublic && (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="cursor-pointer">
|
||||
<span>{m.export_comments()}</span>
|
||||
@@ -396,10 +405,13 @@ export function FileViewerRightSidebar({
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
<DropdownMenuItem className="cursor-pointer" onClick={handlePrintComments}>
|
||||
<span>{m.print_comments()}</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
||||
<div className="space-y-4 pt-2">
|
||||
{comments.map((comment) => (
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import React from 'react'
|
||||
|
||||
export function parseAnnotations(raw: unknown): Annotation[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const valid: Annotation[] = []
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
const rec = item as Record<string, unknown>
|
||||
const type = rec.type
|
||||
const color = rec.color
|
||||
const points = rec.points
|
||||
if (
|
||||
(type === 'box' || type === 'line' || type === 'arrow' || type === 'freehand') &&
|
||||
typeof color === 'string' &&
|
||||
Array.isArray(points) &&
|
||||
points.length >= 2 &&
|
||||
points.every(
|
||||
(pt) =>
|
||||
Array.isArray(pt) &&
|
||||
pt.length >= 2 &&
|
||||
typeof pt[0] === 'number' &&
|
||||
typeof pt[1] === 'number',
|
||||
)
|
||||
) {
|
||||
valid.push({
|
||||
type,
|
||||
color,
|
||||
points: points as [number, number][],
|
||||
} as Annotation)
|
||||
}
|
||||
}
|
||||
return valid
|
||||
}
|
||||
|
||||
interface AnnotationOverlaySvgProps {
|
||||
annotations: Annotation[]
|
||||
width: number
|
||||
height: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
function buildFreehandPath(points: [number, number][], w: number, h: number): string {
|
||||
if (points.length === 0) return ''
|
||||
const scaled = points.map(([nx, ny]) => [nx * w, ny * h] as const)
|
||||
if (scaled.length === 2) {
|
||||
return `M ${scaled[0][0]} ${scaled[0][1]} L ${scaled[1][0]} ${scaled[1][1]}`
|
||||
}
|
||||
|
||||
// Smooth quadratic path matching Konva's tension ~0.5 appearance
|
||||
let d = `M ${scaled[0][0]} ${scaled[0][1]}`
|
||||
for (let i = 1; i < scaled.length - 1; i++) {
|
||||
const midX = (scaled[i][0] + scaled[i + 1][0]) / 2
|
||||
const midY = (scaled[i][1] + scaled[i + 1][1]) / 2
|
||||
d += ` Q ${scaled[i][0]} ${scaled[i][1]} ${midX} ${midY}`
|
||||
}
|
||||
const last = scaled[scaled.length - 1]
|
||||
d += ` L ${last[0]} ${last[1]}`
|
||||
return d
|
||||
}
|
||||
|
||||
/**
|
||||
* Vector SVG overlay for normalized [0..1] comment annotations.
|
||||
* Using inline SVG instead of rasterized canvas ensures sharp markups when
|
||||
* printing or exporting to PDF and avoids browser canvas limits on long lists.
|
||||
*/
|
||||
export const AnnotationOverlaySvg: React.FC<AnnotationOverlaySvgProps> = ({
|
||||
annotations,
|
||||
width,
|
||||
height,
|
||||
className,
|
||||
}) => {
|
||||
if (annotations.length === 0 || width <= 0 || height <= 0) return null
|
||||
|
||||
// Keep stroke visually consistent with DrawingCanvas regardless of image dimensions
|
||||
const baseDim = Math.max(width, height)
|
||||
const strokeWidth = Math.max(1.5, baseDim * 0.014)
|
||||
const headLength = strokeWidth * 3.8
|
||||
const headHalfWidth = strokeWidth * 2.1
|
||||
|
||||
return (
|
||||
<svg
|
||||
viewBox={`0 0 ${width} ${height}`}
|
||||
preserveAspectRatio="none"
|
||||
className={className}
|
||||
data-testid="print-annotation-overlay"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{annotations.map((ann, idx) => {
|
||||
if (ann.type === 'box') {
|
||||
const [start, end] = ann.points
|
||||
const x = Math.min(start[0], end[0]) * width
|
||||
const y = Math.min(start[1], end[1]) * height
|
||||
const boxW = Math.abs(end[0] - start[0]) * width
|
||||
const boxH = Math.abs(end[1] - start[1]) * height
|
||||
return (
|
||||
<rect
|
||||
key={idx}
|
||||
x={x}
|
||||
y={y}
|
||||
width={boxW}
|
||||
height={boxH}
|
||||
fill="none"
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (ann.type === 'line') {
|
||||
const [start, end] = ann.points
|
||||
return (
|
||||
<line
|
||||
key={idx}
|
||||
x1={start[0] * width}
|
||||
y1={start[1] * height}
|
||||
x2={end[0] * width}
|
||||
y2={end[1] * height}
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (ann.type === 'arrow') {
|
||||
const [start, end] = ann.points
|
||||
const x1 = start[0] * width
|
||||
const y1 = start[1] * height
|
||||
const x2 = end[0] * width
|
||||
const y2 = end[1] * height
|
||||
const angle = Math.atan2(y2 - y1, x2 - x1)
|
||||
const lineLen = Math.hypot(x2 - x1, y2 - y1)
|
||||
const clampedHeadLen = Math.min(headLength, lineLen * 0.65)
|
||||
const clampedHalfW = (clampedHeadLen / headLength) * headHalfWidth
|
||||
const baseX = x2 - clampedHeadLen * Math.cos(angle)
|
||||
const baseY = y2 - clampedHeadLen * Math.sin(angle)
|
||||
const leftX = baseX - clampedHalfW * Math.sin(angle)
|
||||
const leftY = baseY + clampedHalfW * Math.cos(angle)
|
||||
const rightX = baseX + clampedHalfW * Math.sin(angle)
|
||||
const rightY = baseY - clampedHalfW * Math.cos(angle)
|
||||
|
||||
return (
|
||||
<g key={idx}>
|
||||
<line
|
||||
x1={x1}
|
||||
y1={y1}
|
||||
x2={baseX}
|
||||
y2={baseY}
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<polygon
|
||||
points={`${x2},${y2} ${leftX},${leftY} ${rightX},${rightY}`}
|
||||
fill={ann.color}
|
||||
/>
|
||||
</g>
|
||||
)
|
||||
}
|
||||
|
||||
if (ann.type === 'freehand') {
|
||||
const d = buildFreehandPath(ann.points, width, height)
|
||||
return (
|
||||
<path
|
||||
key={idx}
|
||||
d={d}
|
||||
fill="none"
|
||||
stroke={ann.color}
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
})}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { ImageOff, Loader2 } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { AnnotationOverlaySvg } from './annotation-overlay-svg'
|
||||
|
||||
const BOX_WIDTH = 200
|
||||
const BOX_HEIGHT = 112
|
||||
|
||||
interface CommentFrameThumbnailProps {
|
||||
src: string
|
||||
annotations: Annotation[]
|
||||
alt?: string
|
||||
onStatusChange?: (status: 'loaded' | 'error') => void
|
||||
}
|
||||
|
||||
export const CommentFrameThumbnail: React.FC<CommentFrameThumbnailProps> = ({
|
||||
src,
|
||||
annotations,
|
||||
alt = '',
|
||||
onStatusChange,
|
||||
}) => {
|
||||
const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading')
|
||||
const [naturalSize, setNaturalSize] = useState<{ width: number; height: number }>({
|
||||
width: BOX_WIDTH,
|
||||
height: BOX_HEIGHT,
|
||||
})
|
||||
const imgRef = useRef<HTMLImageElement>(null)
|
||||
const onStatusChangeRef = useRef(onStatusChange)
|
||||
onStatusChangeRef.current = onStatusChange
|
||||
|
||||
useEffect(() => {
|
||||
setStatus('loading')
|
||||
const img = imgRef.current
|
||||
if (img && img.complete && img.naturalWidth > 0) {
|
||||
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||
setStatus('loaded')
|
||||
onStatusChangeRef.current?.('loaded')
|
||||
}
|
||||
}, [src])
|
||||
|
||||
const handleLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
|
||||
const img = e.currentTarget
|
||||
const nw = img.naturalWidth || BOX_WIDTH
|
||||
const nh = img.naturalHeight || BOX_HEIGHT
|
||||
setNaturalSize({ width: nw, height: nh })
|
||||
setStatus('loaded')
|
||||
onStatusChangeRef.current?.('loaded')
|
||||
}
|
||||
|
||||
const handleError = () => {
|
||||
setStatus('error')
|
||||
onStatusChangeRef.current?.('error')
|
||||
}
|
||||
|
||||
// Fit the actual image rect inside 200x112 while preserving aspect ratio so the
|
||||
// SVG markup overlay aligns accurately for portrait, square, PDF, and ultrawide media.
|
||||
const scale = Math.min(BOX_WIDTH / naturalSize.width, BOX_HEIGHT / naturalSize.height)
|
||||
const fittedWidth = Math.max(1, Math.round(naturalSize.width * scale))
|
||||
const fittedHeight = Math.max(1, Math.round(naturalSize.height * scale))
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative flex items-center justify-center overflow-hidden rounded-sm border border-border transparency-checkerboard shrink-0"
|
||||
style={{ width: BOX_WIDTH, height: BOX_HEIGHT }}
|
||||
data-testid="print-comment-frame"
|
||||
>
|
||||
{status === 'loading' && (
|
||||
<div
|
||||
className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-1.5 bg-muted/95 text-muted-foreground"
|
||||
data-testid="print-frame-loading"
|
||||
>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-[11px] leading-none">{m.print_comments_frame_loading()}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status === 'error' ? (
|
||||
<div
|
||||
className="flex flex-col items-center justify-center gap-1.5 px-2 text-center text-muted-foreground"
|
||||
data-testid="print-frame-error"
|
||||
>
|
||||
<ImageOff className="h-4 w-4" />
|
||||
<span className="text-[11px] leading-tight">{m.print_comments_frame_unavailable()}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="relative"
|
||||
style={{
|
||||
width: status === 'loaded' ? fittedWidth : BOX_WIDTH,
|
||||
height: status === 'loaded' ? fittedHeight : BOX_HEIGHT,
|
||||
}}
|
||||
>
|
||||
<img
|
||||
ref={imgRef}
|
||||
src={src}
|
||||
alt={alt}
|
||||
onLoad={handleLoad}
|
||||
onError={handleError}
|
||||
className={`block h-full w-full object-contain ${
|
||||
status === 'loaded' ? 'opacity-100' : 'opacity-0'
|
||||
}`}
|
||||
/>
|
||||
{status === 'loaded' && annotations.length > 0 && (
|
||||
<AnnotationOverlaySvg
|
||||
annotations={annotations}
|
||||
width={fittedWidth}
|
||||
height={fittedHeight}
|
||||
className="pointer-events-none absolute inset-0 h-full w-full z-10"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AssetInfo, CommentInfo } from '@shumai/dtos'
|
||||
import { PrintCommentsView } from './print-comments-view'
|
||||
|
||||
function makeComment(overrides: Partial<CommentInfo> = {}): CommentInfo {
|
||||
return {
|
||||
id: 'c-1',
|
||||
assetId: 'asset-1',
|
||||
message: 'Check the color grade here',
|
||||
annotations: null,
|
||||
second: 1.5,
|
||||
creator: { id: 'u-1', name: 'Alice' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: '2026-11-25T14:53:00.000Z',
|
||||
updatedAt: '2026-11-25T14:53:00.000Z',
|
||||
sessionId: null,
|
||||
isCompleted: false,
|
||||
completionLastChangedBy: null,
|
||||
reactionCounts: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('PrintCommentsView', () => {
|
||||
let printMock: ReturnType<typeof vi.fn>
|
||||
const originalPrint = window.print
|
||||
|
||||
beforeEach(() => {
|
||||
printMock = vi.fn()
|
||||
Object.defineProperty(window, 'print', {
|
||||
value: printMock,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
Object.defineProperty(window, 'print', {
|
||||
value: originalPrint,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
|
||||
const videoAsset: AssetInfo = {
|
||||
id: 'asset-video-1',
|
||||
name: '3D_printer_building_model_20261017121617.mp4',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
sizeByte: 1024,
|
||||
fileCount: 1,
|
||||
proxyType: 'video',
|
||||
preview: { thumbnailUrl: 'https://example.com/thumb.jpg' },
|
||||
creator: { id: 'u-1', name: 'Alice' },
|
||||
createdAt: '2026-11-06T10:00:00.000Z',
|
||||
updatedAt: '2026-11-06T10:00:00.000Z',
|
||||
media: {
|
||||
proxyType: 'video',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
metadata: { frameRate: 24 },
|
||||
},
|
||||
}
|
||||
|
||||
it('renders video comments sorted by timecode with frames, SVG annotations, replies, completed status, reactions, and attachments without auto-printing', () => {
|
||||
const comments: CommentInfo[] = [
|
||||
makeComment({
|
||||
id: 'c-2',
|
||||
second: 5,
|
||||
message: 'Second comment later in timeline',
|
||||
}),
|
||||
makeComment({
|
||||
id: 'c-1',
|
||||
second: 1.5,
|
||||
message: 'First comment <@u-2>',
|
||||
mentions: [{ id: 'u-2', name: 'Bob' }],
|
||||
isCompleted: true,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ef4444',
|
||||
points: [
|
||||
[0.1, 0.1],
|
||||
[0.5, 0.5],
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'arrow',
|
||||
color: '#22c55e',
|
||||
points: [
|
||||
[0.2, 0.2],
|
||||
[0.8, 0.8],
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'line',
|
||||
color: '#3b82f6',
|
||||
points: [
|
||||
[0.1, 0.9],
|
||||
[0.9, 0.1],
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'freehand',
|
||||
color: '#eab308',
|
||||
points: [
|
||||
[0.1, 0.2],
|
||||
[0.2, 0.3],
|
||||
[0.4, 0.35],
|
||||
],
|
||||
},
|
||||
],
|
||||
attachments: [
|
||||
{ id: 'att-1', assetId: 'a-1', url: 'https://example.com/ref-frame.png' },
|
||||
{ id: 'att-2', assetId: 'a-2', url: 'https://example.com/notes.pdf' },
|
||||
],
|
||||
reactionCounts: [
|
||||
{ code: '👍', count: 2, requestingUserReacted: true, creatorNames: ['Bob'] },
|
||||
],
|
||||
replies: [
|
||||
makeComment({
|
||||
id: 'r-1',
|
||||
second: null,
|
||||
message: 'Updated in v2!',
|
||||
creator: { id: 'u-2', name: 'Bob' },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]
|
||||
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={['Untitled Project', 'Dailies']}
|
||||
comments={comments}
|
||||
/>,
|
||||
)
|
||||
|
||||
// Never auto-trigger print
|
||||
expect(printMock).not.toHaveBeenCalled()
|
||||
|
||||
// Header breadcrumbs & creator
|
||||
expect(screen.getByText('Untitled Project')).toBeDefined()
|
||||
expect(screen.getByText('Dailies')).toBeDefined()
|
||||
expect(screen.getByText('Sorted by timecode')).toBeDefined()
|
||||
|
||||
// Progress indicator while thumbnails are loading
|
||||
expect(screen.getByTestId('print-frames-progress')).toBeDefined()
|
||||
expect(screen.getAllByTestId('print-frame-loading')).toHaveLength(2)
|
||||
|
||||
// Sorted by timecode: c-1 (1.5s) appears before c-2 (5s)
|
||||
const threads = screen.getAllByTestId('print-comment-thread')
|
||||
expect(threads).toHaveLength(2)
|
||||
expect(threads[0].textContent).toContain('First comment')
|
||||
expect(threads[0].textContent).toContain('@Bob')
|
||||
expect(threads[0].textContent).toContain('Updated in v2!')
|
||||
expect(threads[1].textContent).toContain('Second comment later in timeline')
|
||||
|
||||
// Completed badge, reactions, and attachments
|
||||
expect(screen.getByTestId('print-comment-completed').textContent).toContain('Completed')
|
||||
expect(screen.getByTestId('print-comment-reactions').textContent).toContain('👍')
|
||||
expect(screen.getByTestId('print-comment-reactions').textContent).toContain('2')
|
||||
expect(screen.getByTestId('print-comment-attachments').textContent).toContain('ref-frame.png')
|
||||
expect(screen.getByTestId('print-comment-attachments').textContent).toContain('notes.pdf')
|
||||
|
||||
// Frame image requests point to backend frame endpoint
|
||||
const frameImgs = container.querySelectorAll('[data-testid="print-comment-frame"] img')
|
||||
expect(frameImgs).toHaveLength(2)
|
||||
expect(frameImgs[0].getAttribute('src')).toBe(
|
||||
'/api/files/asset-video-1/comments/frame?second=1.5&width=400',
|
||||
)
|
||||
|
||||
// Simulate frame image load -> SVG overlay renders all 4 annotation shapes
|
||||
Object.defineProperty(frameImgs[0], 'naturalWidth', { value: 400, configurable: true })
|
||||
Object.defineProperty(frameImgs[0], 'naturalHeight', { value: 225, configurable: true })
|
||||
fireEvent.load(frameImgs[0])
|
||||
fireEvent.load(frameImgs[1])
|
||||
|
||||
expect(screen.queryByTestId('print-frames-progress')).toBeNull()
|
||||
const overlay = screen.getByTestId('print-annotation-overlay')
|
||||
expect(overlay.querySelector('rect')).not.toBeNull()
|
||||
expect(overlay.querySelector('polygon')).not.toBeNull()
|
||||
expect(overlay.querySelector('path')).not.toBeNull()
|
||||
|
||||
// Clicking Print button invokes window.print()
|
||||
fireEvent.click(screen.getByTestId('print-comments-button'))
|
||||
expect(printMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('uses public share frame endpoint with password query param when shareId is set', () => {
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={['Client Share']}
|
||||
comments={[makeComment({ id: 'c-1', second: 3.25 })]}
|
||||
shareId="share-99"
|
||||
sharePassword="pw!"
|
||||
/>,
|
||||
)
|
||||
|
||||
const img = container.querySelector('[data-testid="print-comment-frame"] img')
|
||||
expect(img?.getAttribute('src')).toBe(
|
||||
'/api/shares/share-99/files/asset-video-1/comments/frame?second=3.25&width=400&p=pw%21',
|
||||
)
|
||||
})
|
||||
|
||||
it('renders an annotated reply at its own timestamp and waits for it before printing', () => {
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={[]}
|
||||
comments={[
|
||||
makeComment({
|
||||
second: 1,
|
||||
replies: [
|
||||
makeComment({
|
||||
id: 'reply',
|
||||
message: '',
|
||||
second: 2,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: 'red',
|
||||
points: [
|
||||
[0.1, 0.1],
|
||||
[0.5, 0.5],
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>,
|
||||
)
|
||||
|
||||
const [commentFrame, replyFrame] = container.querySelectorAll(
|
||||
'[data-testid="print-comment-frame"] img',
|
||||
)
|
||||
expect(replyFrame?.getAttribute('src')).toContain('second=2&')
|
||||
fireEvent.load(commentFrame)
|
||||
|
||||
const printButton = screen.getByRole<HTMLButtonElement>('button', { name: 'Print' })
|
||||
expect(printButton.disabled).toBe(true)
|
||||
expect(screen.getByTestId('print-frames-progress').textContent).toContain('1/2')
|
||||
fireEvent.load(replyFrame)
|
||||
|
||||
expect(screen.getByTestId('print-reply-item').querySelector('svg rect')).not.toBeNull()
|
||||
expect(printButton.disabled).toBe(false)
|
||||
fireEvent.click(printButton)
|
||||
expect(printMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reuses image proxy URL directly for image assets without calling frame API', () => {
|
||||
const imageAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-img-1',
|
||||
name: 'poster.png',
|
||||
proxyType: 'image',
|
||||
media: {
|
||||
proxyType: 'image',
|
||||
imageTranscodes: [
|
||||
{
|
||||
id: 't1',
|
||||
key: 'k1',
|
||||
url: 'https://cdn.example.com/poster-600.webp',
|
||||
width: 600,
|
||||
height: 400,
|
||||
size: 100,
|
||||
},
|
||||
],
|
||||
videoTranscodes: [],
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={imageAsset}
|
||||
breadcrumbs={['Design']}
|
||||
comments={[makeComment({ id: 'c-img', second: null, message: 'Adjust logo spacing' })]}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Sorted by oldest')).toBeDefined()
|
||||
const img = container.querySelector('[data-testid="print-comment-frame"] img')
|
||||
expect(img?.getAttribute('src')).toBe('https://cdn.example.com/poster-600.webp')
|
||||
})
|
||||
|
||||
it('supports PDF page formatting, 3D angle formatting, and audio without frame column', () => {
|
||||
const pdfAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-pdf-1',
|
||||
name: 'script.pdf',
|
||||
proxyType: 'pdf',
|
||||
media: { proxyType: 'pdf', imageTranscodes: [], videoTranscodes: [] },
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { rerender } = render(
|
||||
<PrintCommentsView
|
||||
asset={pdfAsset}
|
||||
breadcrumbs={['Docs']}
|
||||
comments={[makeComment({ id: 'c-pdf', second: 3, message: 'Fix typo on page 3' })]}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Sorted by page')).toBeDefined()
|
||||
expect(screen.getByTestId('print-comment-timestamp').textContent).toBe('P3')
|
||||
|
||||
const modelAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-3d-1',
|
||||
name: 'chair.glb',
|
||||
proxyType: '3d',
|
||||
media: { proxyType: '3d', imageTranscodes: [], videoTranscodes: [] },
|
||||
} as unknown as AssetInfo
|
||||
|
||||
rerender(
|
||||
<PrintCommentsView
|
||||
asset={modelAsset}
|
||||
breadcrumbs={['Models']}
|
||||
comments={[makeComment({ id: 'c-3d', second: 3, message: 'Smooth bevel' })]}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Sorted by angle')).toBeDefined()
|
||||
expect(screen.getByTestId('print-comment-timestamp').textContent).toBe('270°')
|
||||
|
||||
const audioAsset = {
|
||||
...videoAsset,
|
||||
id: 'asset-audio-1',
|
||||
name: 'mix.wav',
|
||||
proxyType: 'audio',
|
||||
preview: null,
|
||||
media: {
|
||||
proxyType: 'audio',
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
metadata: { frameRate: 30 },
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
rerender(
|
||||
<PrintCommentsView
|
||||
asset={audioAsset}
|
||||
breadcrumbs={['Audio']}
|
||||
comments={[makeComment({ id: 'c-aud', second: 2, message: 'Reduce reverb' })]}
|
||||
/>,
|
||||
)
|
||||
expect(screen.queryByTestId('print-comment-frame')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows friendly fallback when a frame fails to load', () => {
|
||||
const { container } = render(
|
||||
<PrintCommentsView
|
||||
asset={videoAsset}
|
||||
breadcrumbs={['Project']}
|
||||
comments={[makeComment({ id: 'c-err', second: 2 })]}
|
||||
/>,
|
||||
)
|
||||
|
||||
const img = container.querySelector('[data-testid="print-comment-frame"] img')!
|
||||
fireEvent.error(img)
|
||||
|
||||
expect(screen.getByTestId('print-frame-error').textContent).toContain('Frame unavailable')
|
||||
expect(screen.queryByTestId('print-frames-progress')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,629 @@
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { DrawAnnotation, ShumaiLogo } from '@/ui/components/ui/icons'
|
||||
import { getViewerForFile } from '@/ui/components/viewers/registry'
|
||||
import { formatFrame, formatTimecode } from '@/ui/components/viewers/video/utils'
|
||||
import { isImageFileName } from '@/ui/lib/media'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import type { AssetInfo, CommentInfo } from '@shumai/dtos'
|
||||
import {
|
||||
ArrowDownWideNarrow,
|
||||
CheckCircle2,
|
||||
FileAudio,
|
||||
FileIcon,
|
||||
FileText,
|
||||
Loader2,
|
||||
Printer,
|
||||
} from 'lucide-react'
|
||||
import React, { useCallback, useMemo, useState } from 'react'
|
||||
import Markdown from 'react-markdown'
|
||||
import { parseAnnotations } from './annotation-overlay-svg'
|
||||
import { CommentFrameThumbnail } from './comment-frame-thumbnail'
|
||||
|
||||
export type PrintSortMode = 'position' | 'oldest' | 'newest'
|
||||
|
||||
export interface PrintCommentsViewProps {
|
||||
asset: AssetInfo
|
||||
breadcrumbs: string[]
|
||||
comments: CommentInfo[]
|
||||
shareId?: string
|
||||
sharePassword?: string
|
||||
}
|
||||
|
||||
function getHeaderThumbnailUrl(asset: AssetInfo): string | null {
|
||||
if (asset.preview?.thumbnailUrl) return asset.preview.thumbnailUrl
|
||||
if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) {
|
||||
const sorted = [...asset.media.imageTranscodes]
|
||||
.filter((t) => Boolean(t.url))
|
||||
.sort((a, b) => (a.width || 0) - (b.width || 0))
|
||||
if (sorted[0]?.url) return sorted[0].url
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function getImageCommentThumbnailUrl(asset: AssetInfo): string | null {
|
||||
if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) {
|
||||
const valid = asset.media.imageTranscodes.filter((t) => Boolean(t.url))
|
||||
const adequate = valid
|
||||
.filter((t) => (t.width || 0) >= 400)
|
||||
.sort((a, b) => (a.width || 0) - (b.width || 0))
|
||||
if (adequate[0]?.url) return adequate[0].url
|
||||
const largest = [...valid].sort((a, b) => (b.width || 0) - (a.width || 0))
|
||||
if (largest[0]?.url) return largest[0].url
|
||||
}
|
||||
return asset.preview?.thumbnailUrl || null
|
||||
}
|
||||
|
||||
function buildFrameEndpointUrl(params: {
|
||||
assetId: string
|
||||
second: number
|
||||
width?: number
|
||||
shareId?: string
|
||||
sharePassword?: string
|
||||
}): string {
|
||||
const qs = new URLSearchParams({
|
||||
second: String(params.second),
|
||||
width: String(params.width ?? 400),
|
||||
})
|
||||
if (params.shareId) {
|
||||
if (params.sharePassword) {
|
||||
qs.set('p', params.sharePassword)
|
||||
}
|
||||
return `/api/shares/${encodeURIComponent(params.shareId)}/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}`
|
||||
}
|
||||
return `/api/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}`
|
||||
}
|
||||
|
||||
function formatShortDate(iso?: string | null): string {
|
||||
if (!iso) return ''
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
month: 'numeric',
|
||||
day: 'numeric',
|
||||
year: '2-digit',
|
||||
}).format(date)
|
||||
}
|
||||
|
||||
function formatCommentDateTime(iso?: string | null): string {
|
||||
if (!iso) return ''
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
const datePart = new Intl.DateTimeFormat(undefined, {
|
||||
month: 'numeric',
|
||||
day: 'numeric',
|
||||
year: '2-digit',
|
||||
}).format(date)
|
||||
const timePart = new Intl.DateTimeFormat(undefined, {
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
}).format(date)
|
||||
return `${datePart} · ${timePart}`
|
||||
}
|
||||
|
||||
function splitMiddleTruncate(name: string): { head: string; tail: string } {
|
||||
if (name.length <= 16) return { head: name, tail: '' }
|
||||
const tailLen = 10
|
||||
return {
|
||||
head: name.slice(0, name.length - tailLen),
|
||||
tail: name.slice(name.length - tailLen),
|
||||
}
|
||||
}
|
||||
|
||||
function preprocessMarkdown(text: string): string {
|
||||
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
|
||||
}
|
||||
|
||||
function renderPlainCommentText(comment: CommentInfo): React.ReactNode {
|
||||
const text = comment.message ?? ''
|
||||
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
|
||||
return parts.map((part, index) => {
|
||||
if (part.match(/^<@[a-zA-Z0-9_-]+>$/)) {
|
||||
const userId = part.slice(2, -1)
|
||||
const mentionedUser = comment.mentions?.find((u) => u.id === userId)
|
||||
return (
|
||||
<span key={index} className="font-medium text-primary">
|
||||
@{mentionedUser?.name || 'Unknown'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return <React.Fragment key={index}>{part}</React.Fragment>
|
||||
})
|
||||
}
|
||||
|
||||
export const PrintCommentsView: React.FC<PrintCommentsViewProps> = ({
|
||||
asset,
|
||||
breadcrumbs,
|
||||
comments,
|
||||
shareId,
|
||||
sharePassword,
|
||||
}) => {
|
||||
const { videoTimeDisplayMode } = useUiStore()
|
||||
const viewerDef = useMemo(() => getViewerForFile(asset), [asset])
|
||||
const proxyType = asset.proxyType ?? asset.media?.proxyType ?? null
|
||||
|
||||
const hasPositionSort = Boolean(viewerDef.commentsConfig?.hasTimestamp)
|
||||
const [sortMode, setSortMode] = useState<PrintSortMode>(hasPositionSort ? 'position' : 'oldest')
|
||||
const [settledFrameUrls, setSettledFrameUrls] = useState<Record<string, string>>({})
|
||||
|
||||
const frameRate = viewerDef.commentsConfig?.hasTimestamp
|
||||
? asset.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
const startTimecode = viewerDef.commentsConfig?.hasTimestamp
|
||||
? asset.media?.metadata?.startTimecode
|
||||
: undefined
|
||||
|
||||
const formatCommentTimestamp = useCallback(
|
||||
(second: number | null | undefined): string => {
|
||||
if (second === null || second === undefined) return ''
|
||||
if (viewerDef.commentsConfig?.formatTimestamp) {
|
||||
return viewerDef.commentsConfig.formatTimestamp(second)
|
||||
}
|
||||
if (!frameRate) return ''
|
||||
const frameIndex = formatFrame(second, frameRate)
|
||||
return formatTimecode(frameIndex, frameRate, videoTimeDisplayMode, startTimecode)
|
||||
},
|
||||
[viewerDef, frameRate, videoTimeDisplayMode, startTimecode],
|
||||
)
|
||||
|
||||
const sortedComments = useMemo(() => {
|
||||
const list = [...comments]
|
||||
if (sortMode === 'position') {
|
||||
list.sort((a, b) => {
|
||||
const aHas = a.second !== null && a.second !== undefined
|
||||
const bHas = b.second !== null && b.second !== undefined
|
||||
if (aHas && bHas) {
|
||||
if (a.second! !== b.second!) return a.second! - b.second!
|
||||
return a.id.localeCompare(b.id)
|
||||
}
|
||||
if (aHas) return -1
|
||||
if (bHas) return 1
|
||||
return a.id.localeCompare(b.id)
|
||||
})
|
||||
} else if (sortMode === 'newest') {
|
||||
list.sort((a, b) => b.id.localeCompare(a.id))
|
||||
} else {
|
||||
list.sort((a, b) => a.id.localeCompare(b.id))
|
||||
}
|
||||
return list
|
||||
}, [comments, sortMode])
|
||||
|
||||
const hasVisualThumbnailColumn =
|
||||
proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf' || proxyType === 'image'
|
||||
|
||||
const getCommentFrameUrl = useCallback(
|
||||
(comment: CommentInfo): string | null => {
|
||||
if (!hasVisualThumbnailColumn) return null
|
||||
if (proxyType === 'image') {
|
||||
return getImageCommentThumbnailUrl(asset)
|
||||
}
|
||||
if (proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf') {
|
||||
if (comment.second !== null && comment.second !== undefined) {
|
||||
return buildFrameEndpointUrl({
|
||||
assetId: asset.id,
|
||||
second: comment.second,
|
||||
width: 400,
|
||||
shareId,
|
||||
sharePassword,
|
||||
})
|
||||
}
|
||||
// If an untimestamped comment still carries visual annotations, show the asset poster/thumbnail
|
||||
const anns = parseAnnotations(comment.annotations)
|
||||
if (anns.length > 0) {
|
||||
return getHeaderThumbnailUrl(asset)
|
||||
}
|
||||
return null
|
||||
}
|
||||
return null
|
||||
},
|
||||
[hasVisualThumbnailColumn, proxyType, asset, shareId, sharePassword],
|
||||
)
|
||||
|
||||
const frameUrls = useMemo(() => {
|
||||
const urls = new Map<string, string>()
|
||||
for (const comment of comments) {
|
||||
const url = getCommentFrameUrl(comment)
|
||||
if (url) urls.set(comment.id, url)
|
||||
|
||||
for (const reply of comment.replies ?? []) {
|
||||
if (parseAnnotations(reply.annotations).length === 0) continue
|
||||
const replyUrl = getCommentFrameUrl(reply)
|
||||
if (replyUrl) urls.set(reply.id, replyUrl)
|
||||
}
|
||||
}
|
||||
return urls
|
||||
}, [comments, getCommentFrameUrl])
|
||||
|
||||
const settledFrameCount = Array.from(frameUrls).filter(
|
||||
([id, url]) => settledFrameUrls[id] === url,
|
||||
).length
|
||||
const isLoadingFrames = settledFrameCount < frameUrls.size
|
||||
|
||||
const sortIndicatorLabel = useMemo(() => {
|
||||
if (sortMode === 'oldest') return m.print_comments_sorted_by_oldest()
|
||||
if (sortMode === 'newest') return m.print_comments_sorted_by_newest()
|
||||
if (proxyType === 'pdf') return m.print_comments_sorted_by_page()
|
||||
if (proxyType === '3d') return m.print_comments_sorted_by_angle()
|
||||
return m.print_comments_sorted_by_timecode()
|
||||
}, [sortMode, proxyType])
|
||||
|
||||
const positionSortOptionLabel = useMemo(() => {
|
||||
if (proxyType === 'pdf') return m.print_comments_sort_page()
|
||||
if (proxyType === '3d') return m.print_comments_sort_angle()
|
||||
return m.print_comments_sort_timecode()
|
||||
}, [proxyType])
|
||||
|
||||
const headerThumbUrl = useMemo(() => getHeaderThumbnailUrl(asset), [asset])
|
||||
const { head: nameHead, tail: nameTail } = splitMiddleTruncate(asset.name || '')
|
||||
const creatorAndDate = [asset.creator?.name, formatShortDate(asset.createdAt)]
|
||||
.filter(Boolean)
|
||||
.join(', ')
|
||||
|
||||
const commentCountLabel =
|
||||
comments.length === 1
|
||||
? m.print_comments_count_one()
|
||||
: m.print_comments_count({ count: String(comments.length) })
|
||||
|
||||
const renderFrame = (commentId: string, annotations: ReturnType<typeof parseAnnotations>) => {
|
||||
const url = frameUrls.get(commentId)
|
||||
if (!url) return null
|
||||
|
||||
return (
|
||||
<CommentFrameThumbnail
|
||||
key={url}
|
||||
src={url}
|
||||
annotations={annotations}
|
||||
onStatusChange={() =>
|
||||
setSettledFrameUrls((prev) =>
|
||||
prev[commentId] === url ? prev : { ...prev, [commentId]: url },
|
||||
)
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const renderCommentEntry = (
|
||||
comment: CommentInfo,
|
||||
options: {
|
||||
indexNumber?: number
|
||||
isReply: boolean
|
||||
hasReplies: boolean
|
||||
isLastReply: boolean
|
||||
},
|
||||
) => {
|
||||
const timestamp = formatCommentTimestamp(comment.second)
|
||||
const annotations = parseAnnotations(comment.annotations)
|
||||
const hasAnnotations = annotations.length > 0
|
||||
const creatorName = comment.creator?.name || 'Unknown'
|
||||
|
||||
return (
|
||||
<div
|
||||
key={comment.id}
|
||||
className={`relative flex gap-2.5 ${options.isReply ? 'pt-3' : ''}`}
|
||||
data-testid={options.isReply ? 'print-reply-item' : 'print-comment-item'}
|
||||
>
|
||||
{/* Avatar + vertical thread connector matching Frame.io / Shumai threads */}
|
||||
<div className="relative flex w-6 shrink-0 flex-col items-center">
|
||||
{options.isReply && (
|
||||
<div className="absolute -top-3 left-1/2 h-3.5 w-px -translate-x-1/2 bg-border" />
|
||||
)}
|
||||
{((options.hasReplies && !options.isReply) ||
|
||||
(options.isReply && !options.isLastReply)) && (
|
||||
<div className="absolute top-6 bottom-[-12px] left-1/2 w-px -translate-x-1/2 bg-border" />
|
||||
)}
|
||||
<Avatar className="relative z-10 h-6 w-6">
|
||||
{comment.creator?.image && (
|
||||
<AvatarImage src={comment.creator.image} alt={creatorName} className="object-cover" />
|
||||
)}
|
||||
<AvatarFallback className="bg-muted text-[10px] font-semibold text-foreground">
|
||||
{creatorName[0]?.toUpperCase() || 'U'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
|
||||
{/* Entry content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
{/* Author + timestamp + #index + completed status */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate text-sm font-semibold text-foreground">{creatorName}</span>
|
||||
<span className="whitespace-nowrap text-xs text-muted-foreground">
|
||||
{formatCommentDateTime(comment.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{comment.isCompleted && (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700"
|
||||
data-testid="print-comment-completed"
|
||||
>
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
<span>{m.print_comments_completed()}</span>
|
||||
</span>
|
||||
)}
|
||||
{options.indexNumber !== undefined && (
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
<span className="opacity-70">#</span>
|
||||
{options.indexNumber}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Prefix (timecode / page / angle + annotation indicator) + Comment text */}
|
||||
<div className="mt-1 text-sm leading-relaxed text-foreground">
|
||||
{(timestamp || hasAnnotations) && (
|
||||
<span className="mr-2 inline-flex items-center gap-1.5 align-middle">
|
||||
{timestamp && (
|
||||
<span
|
||||
className="inline-block rounded bg-muted px-1.5 py-0.5 font-mono text-xs font-semibold leading-none text-foreground"
|
||||
data-testid="print-comment-timestamp"
|
||||
>
|
||||
{timestamp}
|
||||
</span>
|
||||
)}
|
||||
{hasAnnotations && (
|
||||
<span
|
||||
className="inline-flex items-center text-muted-foreground"
|
||||
title={m.print_comments_has_annotations()}
|
||||
aria-label={m.print_comments_has_annotations()}
|
||||
>
|
||||
<DrawAnnotation className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{comment.sessionId && comment.message ? (
|
||||
<div className="prose prose-sm mt-0.5 max-w-none break-words text-foreground">
|
||||
<Markdown>{preprocessMarkdown(comment.message)}</Markdown>
|
||||
</div>
|
||||
) : (
|
||||
<span className="whitespace-pre-wrap break-words">
|
||||
{renderPlainCommentText(comment)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{options.isReply && frameUrls.has(comment.id) && (
|
||||
<div className="mt-2">{renderFrame(comment.id, annotations)}</div>
|
||||
)}
|
||||
|
||||
{/* Attachments */}
|
||||
{comment.attachments && comment.attachments.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-2" data-testid="print-comment-attachments">
|
||||
{comment.attachments.map((att) => {
|
||||
const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file'
|
||||
const name = decodeURIComponent(rawName)
|
||||
const isImage = isImageFileName(name)
|
||||
return (
|
||||
<div
|
||||
key={att.id}
|
||||
className="inline-flex max-w-full items-center gap-2 rounded-md border border-border bg-card px-2 py-1"
|
||||
>
|
||||
{isImage ? (
|
||||
<img
|
||||
src={att.url}
|
||||
alt={name}
|
||||
className="h-10 w-10 shrink-0 rounded object-cover"
|
||||
/>
|
||||
) : (
|
||||
<FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="max-w-[220px] truncate text-xs font-medium text-foreground">
|
||||
{name}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Emoji reactions */}
|
||||
{comment.reactionCounts && comment.reactionCounts.length > 0 && (
|
||||
<div
|
||||
className="mt-2 flex flex-wrap items-center gap-1.5"
|
||||
data-testid="print-comment-reactions"
|
||||
>
|
||||
{comment.reactionCounts.map((reaction) => (
|
||||
<span
|
||||
key={reaction.code}
|
||||
className="inline-flex items-center gap-1 rounded-full border border-border bg-card px-2 py-0.5 text-xs text-foreground"
|
||||
>
|
||||
<span className="leading-none">{reaction.code}</span>
|
||||
<span className="font-semibold">{reaction.count}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="print-sheet min-h-screen bg-background text-foreground">
|
||||
{/* Non-printable action toolbar */}
|
||||
<div className="sticky top-0 z-20 border-b border-border bg-background/95 backdrop-blur-sm print:hidden">
|
||||
<div className="mx-auto flex max-w-[860px] flex-wrap items-center justify-between gap-3 px-6 py-3">
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
{isLoadingFrames ? (
|
||||
<span
|
||||
className="inline-flex items-center gap-2 font-medium text-foreground"
|
||||
data-testid="print-frames-progress"
|
||||
>
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin text-primary" />
|
||||
<span>
|
||||
{m.print_comments_loading_frames({
|
||||
loaded: String(settledFrameCount),
|
||||
total: String(frameUrls.size),
|
||||
})}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span>{commentCountLabel}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="inline-flex items-center rounded-md border border-border bg-card p-0.5 text-xs">
|
||||
{hasPositionSort && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSortMode('position')}
|
||||
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||
sortMode === 'position'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{positionSortOptionLabel}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSortMode('oldest')}
|
||||
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||
sortMode === 'oldest'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{m.print_comments_sort_oldest()}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSortMode('newest')}
|
||||
className={`rounded px-2.5 py-1 font-medium transition-colors cursor-pointer ${
|
||||
sortMode === 'newest'
|
||||
? 'bg-background text-foreground shadow-xs'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{m.print_comments_sort_newest()}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={isLoadingFrames}
|
||||
onClick={() => window.print()}
|
||||
className="gap-1.5 cursor-pointer"
|
||||
data-testid="print-comments-button"
|
||||
>
|
||||
<Printer className="h-3.5 w-3.5" />
|
||||
<span>{m.print()}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Printable document body */}
|
||||
<div className="mx-auto max-w-[860px] px-6 py-8 print:max-w-none print:px-0 print:py-0">
|
||||
{/* Document Header */}
|
||||
<header className="flex items-center gap-4 pb-5">
|
||||
<div
|
||||
className="flex shrink-0 items-center justify-center overflow-hidden rounded-sm border border-border transparency-checkerboard"
|
||||
style={{ width: 96, height: 54 }}
|
||||
>
|
||||
{headerThumbUrl ? (
|
||||
<img src={headerThumbUrl} alt="" className="h-full w-full object-contain" />
|
||||
) : proxyType === 'audio' ? (
|
||||
<FileAudio className="h-5 w-5 text-muted-foreground" />
|
||||
) : proxyType === 'pdf' ? (
|
||||
<FileText className="h-5 w-5 text-muted-foreground" />
|
||||
) : (
|
||||
<FileIcon className="h-5 w-5 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col justify-between gap-1.5">
|
||||
{/* Top row: Breadcrumbs + Shumai Logo */}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<nav
|
||||
aria-label="Breadcrumb"
|
||||
className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
|
||||
>
|
||||
{breadcrumbs.map((segment, i) => (
|
||||
<React.Fragment key={`${segment}-${i}`}>
|
||||
{i > 0 && <span className="shrink-0 opacity-60">/</span>}
|
||||
<span className="truncate">{segment}</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</nav>
|
||||
<ShumaiLogo className="h-4 w-4 shrink-0 text-foreground" aria-label="Shumai" />
|
||||
</div>
|
||||
|
||||
{/* Bottom row: Filename + Creator & Date */}
|
||||
<div className="flex items-baseline justify-between gap-4">
|
||||
<h1
|
||||
className="flex min-w-0 text-base font-semibold leading-tight text-foreground"
|
||||
title={asset.name}
|
||||
>
|
||||
<span className="truncate">{nameHead}</span>
|
||||
{nameTail && <span className="shrink-0">{nameTail}</span>}
|
||||
</h1>
|
||||
{creatorAndDate && (
|
||||
<span className="shrink-0 whitespace-nowrap text-xs text-muted-foreground">
|
||||
{creatorAndDate}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="border-b border-border" />
|
||||
|
||||
{/* Sort Indicator */}
|
||||
<div className="flex items-center gap-1.5 py-4 text-xs font-medium text-muted-foreground">
|
||||
<ArrowDownWideNarrow className="h-4 w-4" />
|
||||
<span>{sortIndicatorLabel}</span>
|
||||
</div>
|
||||
|
||||
{/* Comments List */}
|
||||
{sortedComments.length === 0 ? (
|
||||
<div className="py-12 text-center text-sm text-muted-foreground">
|
||||
{m.print_comments_empty()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{sortedComments.map((comment, idx) => {
|
||||
const annotations = parseAnnotations(comment.annotations)
|
||||
const replies = comment.replies ?? []
|
||||
|
||||
return (
|
||||
<article
|
||||
key={comment.id}
|
||||
className="flex gap-5 py-5 break-inside-avoid"
|
||||
data-testid="print-comment-thread"
|
||||
>
|
||||
{hasVisualThumbnailColumn && (
|
||||
<div className="w-[200px] shrink-0">{renderFrame(comment.id, annotations)}</div>
|
||||
)}
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
{renderCommentEntry(comment, {
|
||||
indexNumber: idx + 1,
|
||||
isReply: false,
|
||||
hasReplies: replies.length > 0,
|
||||
isLastReply: false,
|
||||
})}
|
||||
{replies.map((reply, replyIdx) =>
|
||||
renderCommentEntry(reply, {
|
||||
isReply: true,
|
||||
hasReplies: false,
|
||||
isLastReply: replyIdx === replies.length - 1,
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -203,3 +203,48 @@
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
/* Always render printable comment sheets with light paper tokens, even when the app is in dark mode */
|
||||
.print-sheet {
|
||||
color-scheme: light;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.153 0.006 107.1);
|
||||
--card: oklch(0.988 0.003 106.5);
|
||||
--card-foreground: oklch(0.153 0.006 107.1);
|
||||
--muted: oklch(0.966 0.005 106.5);
|
||||
--muted-foreground: oklch(0.5 0.02 107.3);
|
||||
--border: oklch(0.91 0.007 106.5);
|
||||
--accent: oklch(0.966 0.005 106.5);
|
||||
--accent-foreground: oklch(0.228 0.013 107.4);
|
||||
--primary: oklch(0.553 0.195 38.402);
|
||||
--primary-foreground: oklch(0.98 0.016 73.684);
|
||||
}
|
||||
|
||||
.transparency-checkerboard {
|
||||
background-color: #f5f5f5;
|
||||
background-image:
|
||||
linear-gradient(45deg, #e5e5e5 25%, transparent 25%),
|
||||
linear-gradient(-45deg, #e5e5e5 25%, transparent 25%),
|
||||
linear-gradient(45deg, transparent 75%, #e5e5e5 75%),
|
||||
linear-gradient(-45deg, transparent 75%, #e5e5e5 75%);
|
||||
background-size: 16px 16px;
|
||||
background-position:
|
||||
0 0,
|
||||
0 8px,
|
||||
8px -8px,
|
||||
-8px 0;
|
||||
}
|
||||
|
||||
@media print {
|
||||
@page {
|
||||
margin: 12mm;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
background: #ffffff !important;
|
||||
color: #171717 !important;
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1771,5 +1771,27 @@
|
||||
"agent_runner_team_default_with_name": "Team Default ({name})",
|
||||
"agent_runner_none_configured_warning": "No runners are configured for this team yet. The bash and download_asset tools will remain unavailable until you register a runner in Team Settings → Agent Runners.",
|
||||
"advanced_settings": "Advanced settings",
|
||||
"failed_add_to_share_link": "Failed to add to share link"
|
||||
"failed_add_to_share_link": "Failed to add to share link",
|
||||
"print_comments": "Print Comments",
|
||||
"print": "Print",
|
||||
"print_comments_loading": "Loading comments...",
|
||||
"print_comments_loading_frames": "Loading thumbnails ({loaded}/{total})...",
|
||||
"print_comments_frame_loading": "Loading frame...",
|
||||
"print_comments_frame_unavailable": "Frame unavailable",
|
||||
"print_comments_sorted_by_timecode": "Sorted by timecode",
|
||||
"print_comments_sorted_by_page": "Sorted by page",
|
||||
"print_comments_sorted_by_angle": "Sorted by angle",
|
||||
"print_comments_sorted_by_oldest": "Sorted by oldest",
|
||||
"print_comments_sorted_by_newest": "Sorted by newest",
|
||||
"print_comments_sort_timecode": "Timecode",
|
||||
"print_comments_sort_page": "Page",
|
||||
"print_comments_sort_angle": "Angle",
|
||||
"print_comments_sort_oldest": "Oldest",
|
||||
"print_comments_sort_newest": "Newest",
|
||||
"print_comments_completed": "Completed",
|
||||
"print_comments_empty": "No comments on this file.",
|
||||
"print_comments_error": "Failed to load printable comments.",
|
||||
"print_comments_count": "{count} comments",
|
||||
"print_comments_count_one": "1 comment",
|
||||
"print_comments_has_annotations": "Comment has annotations"
|
||||
}
|
||||
|
||||
@@ -1701,5 +1701,27 @@
|
||||
"agent_runner_team_default_with_name": "팀 기본({name})",
|
||||
"agent_runner_none_configured_warning": "이 팀에 아직 구성된 러너가 없습니다. 팀 설정 → 에이전트 러너에서 러너를 등록할 때까지 bash 및 download_asset 도구를 사용할 수 없습니다.",
|
||||
"advanced_settings": "고급 설정",
|
||||
"failed_add_to_share_link": "공유 링크에 추가하지 못했습니다"
|
||||
"failed_add_to_share_link": "공유 링크에 추가하지 못했습니다",
|
||||
"print_comments": "댓글 인쇄",
|
||||
"print": "인쇄",
|
||||
"print_comments_loading": "댓글을 불러오는 중...",
|
||||
"print_comments_loading_frames": "썸네일 불러오는 중 ({loaded}/{total})...",
|
||||
"print_comments_frame_loading": "프레임 불러오는 중...",
|
||||
"print_comments_frame_unavailable": "프레임을 불러올 수 없음",
|
||||
"print_comments_sorted_by_timecode": "타임코드순 정렬",
|
||||
"print_comments_sorted_by_page": "페이지순 정렬",
|
||||
"print_comments_sorted_by_angle": "각도순 정렬",
|
||||
"print_comments_sorted_by_oldest": "오래된순 정렬",
|
||||
"print_comments_sorted_by_newest": "최신순 정렬",
|
||||
"print_comments_sort_timecode": "타임코드",
|
||||
"print_comments_sort_page": "페이지",
|
||||
"print_comments_sort_angle": "각도",
|
||||
"print_comments_sort_oldest": "오래된순",
|
||||
"print_comments_sort_newest": "최신순",
|
||||
"print_comments_completed": "완료됨",
|
||||
"print_comments_empty": "이 파일에 댓글이 없습니다.",
|
||||
"print_comments_error": "인쇄용 댓글을 불러오지 못했습니다.",
|
||||
"print_comments_count": "댓글 {count}개",
|
||||
"print_comments_count_one": "댓글 1개",
|
||||
"print_comments_has_annotations": "주석이 포함된 댓글"
|
||||
}
|
||||
|
||||
@@ -1771,5 +1771,27 @@
|
||||
"agent_runner_team_default_with_name": "团队默认({name})",
|
||||
"agent_runner_none_configured_warning": "当前团队尚未配置任何运行器。在“团队设置 → Agent 运行器”中注册运行器之前,bash 和 download_asset 工具将不可用。",
|
||||
"advanced_settings": "高级设置",
|
||||
"failed_add_to_share_link": "添加到分享链接失败"
|
||||
"failed_add_to_share_link": "添加到分享链接失败",
|
||||
"print_comments": "打印评论",
|
||||
"print": "打印",
|
||||
"print_comments_loading": "正在加载评论...",
|
||||
"print_comments_loading_frames": "正在加载缩略图 ({loaded}/{total})...",
|
||||
"print_comments_frame_loading": "正在生成预览...",
|
||||
"print_comments_frame_unavailable": "无法加载预览",
|
||||
"print_comments_sorted_by_timecode": "按时间码排序",
|
||||
"print_comments_sorted_by_page": "按页码排序",
|
||||
"print_comments_sorted_by_angle": "按角度排序",
|
||||
"print_comments_sorted_by_oldest": "按最早排序",
|
||||
"print_comments_sorted_by_newest": "按最新排序",
|
||||
"print_comments_sort_timecode": "时间码",
|
||||
"print_comments_sort_page": "页码",
|
||||
"print_comments_sort_angle": "角度",
|
||||
"print_comments_sort_oldest": "最早",
|
||||
"print_comments_sort_newest": "最新",
|
||||
"print_comments_completed": "已完成",
|
||||
"print_comments_empty": "此文件暂无评论。",
|
||||
"print_comments_error": "加载可打印评论失败。",
|
||||
"print_comments_count": "{count} 条评论",
|
||||
"print_comments_count_one": "1 条评论",
|
||||
"print_comments_has_annotations": "评论包含标注"
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { Route as TeamsTeamIdDashboardRouteImport } from './routes/teams/$teamId
|
||||
import { Route as ProjectsProjectIdRecentsRouteImport } from './routes/projects/$projectId/recents'
|
||||
import { Route as ProjectsProjectIdRecentlyDeletedRouteImport } from './routes/projects/$projectId/recently-deleted'
|
||||
import { Route as ProjectsProjectIdAgentsmdRouteImport } from './routes/projects/$projectId/agentsmd'
|
||||
import { Route as PrintCommentsAssetIdRouteImport } from './routes/print/comments/$assetId'
|
||||
import { Route as ProjectsProjectIdSharesIndexRouteImport } from './routes/projects/$projectId/shares/index'
|
||||
import { Route as ProjectsProjectIdCollectionsIndexRouteImport } from './routes/projects/$projectId/collections/index'
|
||||
import { Route as ShareShareIdFoldersFolderIdRouteImport } from './routes/share/$shareId/folders/$folderId'
|
||||
@@ -111,6 +112,11 @@ const ProjectsProjectIdAgentsmdRoute = ProjectsProjectIdAgentsmdRouteImport.upda
|
||||
path: '/projects/$projectId/agentsmd',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any).lazy(() => import('./routes/projects/$projectId/agentsmd.lazy').then((d) => d.Route))
|
||||
const PrintCommentsAssetIdRoute = PrintCommentsAssetIdRouteImport.update({
|
||||
id: '/print/comments/$assetId',
|
||||
path: '/print/comments/$assetId',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any).lazy(() => import('./routes/print/comments/$assetId.lazy').then((d) => d.Route))
|
||||
const ProjectsProjectIdSharesIndexRoute = ProjectsProjectIdSharesIndexRouteImport.update({
|
||||
id: '/projects/$projectId/shares/',
|
||||
path: '/projects/$projectId/shares/',
|
||||
@@ -176,6 +182,7 @@ export interface FileRoutesByFullPath {
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
'/share/$shareId': typeof ShareShareIdRouteWithChildren
|
||||
'/print/comments/$assetId': typeof PrintCommentsAssetIdRoute
|
||||
'/projects/$projectId/agentsmd': typeof ProjectsProjectIdAgentsmdRoute
|
||||
'/projects/$projectId/recently-deleted': typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
'/projects/$projectId/recents': typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -201,6 +208,7 @@ export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
'/print/comments/$assetId': typeof PrintCommentsAssetIdRoute
|
||||
'/projects/$projectId/agentsmd': typeof ProjectsProjectIdAgentsmdRoute
|
||||
'/projects/$projectId/recently-deleted': typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
'/projects/$projectId/recents': typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -228,6 +236,7 @@ export interface FileRoutesById {
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/signup': typeof SignupRoute
|
||||
'/share/$shareId': typeof ShareShareIdRouteWithChildren
|
||||
'/print/comments/$assetId': typeof PrintCommentsAssetIdRoute
|
||||
'/projects/$projectId/agentsmd': typeof ProjectsProjectIdAgentsmdRoute
|
||||
'/projects/$projectId/recently-deleted': typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
'/projects/$projectId/recents': typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -256,6 +265,7 @@ export interface FileRouteTypes {
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
| '/share/$shareId'
|
||||
| '/print/comments/$assetId'
|
||||
| '/projects/$projectId/agentsmd'
|
||||
| '/projects/$projectId/recently-deleted'
|
||||
| '/projects/$projectId/recents'
|
||||
@@ -281,6 +291,7 @@ export interface FileRouteTypes {
|
||||
| '/login'
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
| '/print/comments/$assetId'
|
||||
| '/projects/$projectId/agentsmd'
|
||||
| '/projects/$projectId/recently-deleted'
|
||||
| '/projects/$projectId/recents'
|
||||
@@ -307,6 +318,7 @@ export interface FileRouteTypes {
|
||||
| '/reset-password'
|
||||
| '/signup'
|
||||
| '/share/$shareId'
|
||||
| '/print/comments/$assetId'
|
||||
| '/projects/$projectId/agentsmd'
|
||||
| '/projects/$projectId/recently-deleted'
|
||||
| '/projects/$projectId/recents'
|
||||
@@ -334,6 +346,7 @@ export interface RootRouteChildren {
|
||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||
SignupRoute: typeof SignupRoute
|
||||
ShareShareIdRoute: typeof ShareShareIdRouteWithChildren
|
||||
PrintCommentsAssetIdRoute: typeof PrintCommentsAssetIdRoute
|
||||
ProjectsProjectIdAgentsmdRoute: typeof ProjectsProjectIdAgentsmdRoute
|
||||
ProjectsProjectIdRecentlyDeletedRoute: typeof ProjectsProjectIdRecentlyDeletedRoute
|
||||
ProjectsProjectIdRecentsRoute: typeof ProjectsProjectIdRecentsRoute
|
||||
@@ -458,6 +471,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof ProjectsProjectIdAgentsmdRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/print/comments/$assetId': {
|
||||
id: '/print/comments/$assetId'
|
||||
path: '/print/comments/$assetId'
|
||||
fullPath: '/print/comments/$assetId'
|
||||
preLoaderRoute: typeof PrintCommentsAssetIdRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/projects/$projectId/shares/': {
|
||||
id: '/projects/$projectId/shares/'
|
||||
path: '/projects/$projectId/shares'
|
||||
@@ -545,6 +565,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
ResetPasswordRoute: ResetPasswordRoute,
|
||||
SignupRoute: SignupRoute,
|
||||
ShareShareIdRoute: ShareShareIdRouteWithChildren,
|
||||
PrintCommentsAssetIdRoute: PrintCommentsAssetIdRoute,
|
||||
ProjectsProjectIdAgentsmdRoute: ProjectsProjectIdAgentsmdRoute,
|
||||
ProjectsProjectIdRecentlyDeletedRoute: ProjectsProjectIdRecentlyDeletedRoute,
|
||||
ProjectsProjectIdRecentsRoute: ProjectsProjectIdRecentsRoute,
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { PrintCommentsView } from '@/ui/components/print-comments/print-comments-view'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { PrintCommentsResponse } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { createLazyFileRoute } from '@tanstack/react-router'
|
||||
import { AlertCircle, Loader2, Lock } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
|
||||
class PrintAuthError extends Error {
|
||||
status: number
|
||||
constructor(status: number, message: string) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
function PrintCommentsPage() {
|
||||
const { assetId } = Route.useParams()
|
||||
const { shareId } = Route.useSearch()
|
||||
|
||||
const [sharePassword, setSharePassword] = useState(() => {
|
||||
if (!shareId || typeof window === 'undefined') return ''
|
||||
return localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
})
|
||||
const [passwordInput, setPasswordInput] = useState('')
|
||||
|
||||
const { data, isLoading, error } = useQuery<PrintCommentsResponse>({
|
||||
queryKey: shareId
|
||||
? ['print-comments', 'share', shareId, assetId, sharePassword]
|
||||
: ['print-comments', 'file', assetId],
|
||||
queryFn: async () => {
|
||||
if (shareId) {
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].comments.print.$get(
|
||||
{
|
||||
param: { shareId, fileId: assetId },
|
||||
},
|
||||
{
|
||||
// A 401 here is a share-password challenge handled by this page.
|
||||
fetch,
|
||||
headers: sharePassword ? { 'x-share-password': sharePassword } : undefined,
|
||||
},
|
||||
)
|
||||
if (res.status === 401) {
|
||||
throw new PrintAuthError(401, 'Unauthorized')
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new PrintAuthError(res.status, 'Failed to fetch printable comments')
|
||||
}
|
||||
return (await res.json()) as unknown as PrintCommentsResponse
|
||||
}
|
||||
|
||||
const res = await client.api.files[':fileId'].comments.print.$get({
|
||||
param: { fileId: assetId },
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new PrintAuthError(res.status, 'Failed to fetch printable comments')
|
||||
}
|
||||
return (await res.json()) as unknown as PrintCommentsResponse
|
||||
},
|
||||
retry: false,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.asset?.name) {
|
||||
document.title = `${data.asset.name} - ${m.print_comments()}`
|
||||
}
|
||||
}, [data?.asset?.name])
|
||||
|
||||
useEffect(() => {
|
||||
if (data && shareId && sharePassword) {
|
||||
localStorage.setItem(`share_pwd_${shareId}`, sharePassword)
|
||||
}
|
||||
}, [data, shareId, sharePassword])
|
||||
|
||||
const handlePasswordSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!shareId) return
|
||||
setSharePassword(passwordInput)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div
|
||||
className="print-sheet flex min-h-screen flex-col items-center justify-center gap-3 bg-background text-foreground"
|
||||
data-testid="print-comments-loading"
|
||||
>
|
||||
<Loader2 className="h-6 w-6 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground">{m.print_comments_loading()}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (shareId && error instanceof PrintAuthError && error.status === 401) {
|
||||
return (
|
||||
<div className="print-sheet flex min-h-screen items-center justify-center bg-background p-4 text-foreground">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Lock className="h-4 w-4" />
|
||||
<span>{m.password_protected()}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handlePasswordSubmit} className="space-y-3">
|
||||
<Input
|
||||
type="password"
|
||||
value={passwordInput}
|
||||
onChange={(e) => setPasswordInput(e.target.value)}
|
||||
placeholder={m.enter_password()}
|
||||
autoFocus
|
||||
/>
|
||||
{sharePassword && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{m.incorrect_password()}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" className="w-full cursor-pointer">
|
||||
{m.confirm()}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error || !data) {
|
||||
return (
|
||||
<div
|
||||
className="print-sheet flex min-h-screen flex-col items-center justify-center gap-3 bg-background p-6 text-center text-foreground"
|
||||
data-testid="print-comments-error"
|
||||
>
|
||||
<AlertCircle className="h-6 w-6 text-destructive" />
|
||||
<p className="text-sm font-medium">{m.print_comments_error()}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PrintCommentsView
|
||||
asset={data.asset}
|
||||
breadcrumbs={data.breadcrumbs}
|
||||
comments={data.comments}
|
||||
shareId={shareId}
|
||||
sharePassword={sharePassword || undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const Route = createLazyFileRoute('/print/comments/$assetId')({
|
||||
component: PrintCommentsPage,
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/print/comments/$assetId')({
|
||||
validateSearch: (search: Record<string, unknown>) => {
|
||||
return {
|
||||
shareId: typeof search.shareId === 'string' && search.shareId ? search.shareId : undefined,
|
||||
} as {
|
||||
shareId?: string
|
||||
}
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user