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:
Yiling-J
2026-11-25 19:53:39 +08:00
committed by GitHub
parent e32445684f
commit 5a1655e4ef
25 changed files with 3428 additions and 51 deletions
+89
View File
@@ -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()
})
})
})
+56
View File
@@ -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),
+123
View File
@@ -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),
})
})
})
+86
View File
@@ -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 })),