diff --git a/CHANGELOG.md b/CHANGELOG.md index b0708e26..5d7374eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/apps/web/e2e/README.md b/apps/web/e2e/README.md index f7d4683f..fcbecb25 100644 --- a/apps/web/e2e/README.md +++ b/apps/web/e2e/README.md @@ -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` | diff --git a/apps/web/e2e/tests/project/share-password.spec.ts b/apps/web/e2e/tests/project/share-password.spec.ts index ca30231b..2378cb57 100644 --- a/apps/web/e2e/tests/project/share-password.spec.ts +++ b/apps/web/e2e/tests/project/share-password.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() + } +}) diff --git a/packages/api/src/file.test.ts b/packages/api/src/file.test.ts index f6e2cd08..59e6e143 100644 --- a/packages/api/src/file.test.ts +++ b/packages/api/src/file.test.ts @@ -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>) 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() + }) + }) }) diff --git a/packages/api/src/file.ts b/packages/api/src/file.ts index a1cb26f3..e0741acf 100644 --- a/packages/api/src/file.ts +++ b/packages/api/src/file.ts @@ -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), diff --git a/packages/api/src/public-share.print.test.ts b/packages/api/src/public-share.print.test.ts new file mode 100644 index 00000000..53a0c960 --- /dev/null +++ b/packages/api/src/public-share.print.test.ts @@ -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), + }) + }) +}) diff --git a/packages/api/src/public-share.ts b/packages/api/src/public-share.ts index 495da79b..4f5af64e 100644 --- a/packages/api/src/public-share.ts +++ b/packages/api/src/public-share.ts @@ -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 })), diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index a1b283eb..bd3bac07 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -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 { + 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 { + 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, diff --git a/packages/core/src/comment/comment-frame.test.ts b/packages/core/src/comment/comment-frame.test.ts new file mode 100644 index 00000000..763f9169 --- /dev/null +++ b/packages/core/src/comment/comment-frame.test.ts @@ -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 { + return sharp({ + create: { + width: 32, + height: 18, + channels: 3, + background: { r: 20, g: 120, b: 220 }, + }, + }) + .png() + .toBuffer() +} + +async function createSampleWebpBuffer(): Promise { + 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((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((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().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(async (_file, args) => { + await new Promise((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(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(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 = { + '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 }) + } + }) +}) diff --git a/packages/core/src/comment/comment-frame.ts b/packages/core/src/comment/comment-frame.ts new file mode 100644 index 00000000..b0ec83e8 --- /dev/null +++ b/packages/core/src/comment/comment-frame.ts @@ -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 { + run: () => Promise + 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[] = [] + + constructor(private readonly maxConcurrency: number) {} + + get activeCount(): number { + return this.running + } + + get queuedCount(): number { + return this.pending.length + } + + enqueue(run: () => Promise, signal?: AbortSignal): Promise { + if (signal?.aborted) { + return Promise.reject(new DOMException('Frame extraction aborted', 'AbortError')) + } + + return new Promise((resolve, reject) => { + const task: QueuedTask = { run, resolve, reject, signal } + + if (signal) { + const onAbort = () => { + const idx = this.pending.indexOf(task as QueuedTask) + 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) + 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 + 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 { + 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((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 { + 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 { + 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() diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index dccd6ff0..6a8bb63a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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' diff --git a/packages/dtos/src/asset.ts b/packages/dtos/src/asset.ts index 3383231c..f343b1cf 100644 --- a/packages/dtos/src/asset.ts +++ b/packages/dtos/src/asset.ts @@ -485,3 +485,18 @@ export type ExportCommentsRequest = z.infer 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 + +export const printCommentsResponseSchema = z.object({ + asset: assetInfoSchema, + breadcrumbs: z.array(z.string()), + comments: z.array(commentInfoSchema), +}) +export type PrintCommentsResponse = z.infer diff --git a/packages/webui/components/file-viewer-right-sidebar.test.tsx b/packages/webui/components/file-viewer-right-sidebar.test.tsx index f8ff930b..cdb8efc9 100644 --- a/packages/webui/components/file-viewer-right-sidebar.test.tsx +++ b/packages/webui/components/file-viewer-right-sidebar.test.tsx @@ -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( { , ) - 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( + + + , + ) + + 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 () => { diff --git a/packages/webui/components/file-viewer-right-sidebar.tsx b/packages/webui/components/file-viewer-right-sidebar.tsx index 98fc231c..6bf84c85 100644 --- a/packages/webui/components/file-viewer-right-sidebar.tsx +++ b/packages/webui/components/file-viewer-right-sidebar.tsx @@ -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({ - {!isPublic && ( -
- {m.all_comments()} - - - - - +
+ {m.all_comments()} + + + + + + {!isPublic && ( {m.export_comments()} @@ -396,10 +405,13 @@ export function FileViewerRightSidebar({ ))} - - -
- )} + )} + + {m.print_comments()} + +
+
+
{comments.map((comment) => ( diff --git a/packages/webui/components/print-comments/annotation-overlay-svg.tsx b/packages/webui/components/print-comments/annotation-overlay-svg.tsx new file mode 100644 index 00000000..0e10a003 --- /dev/null +++ b/packages/webui/components/print-comments/annotation-overlay-svg.tsx @@ -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 + 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 = ({ + 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 ( + + ) +} diff --git a/packages/webui/components/print-comments/comment-frame-thumbnail.tsx b/packages/webui/components/print-comments/comment-frame-thumbnail.tsx new file mode 100644 index 00000000..179c42df --- /dev/null +++ b/packages/webui/components/print-comments/comment-frame-thumbnail.tsx @@ -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 = ({ + 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(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) => { + 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 ( +
+ {status === 'loading' && ( +
+ + {m.print_comments_frame_loading()} +
+ )} + + {status === 'error' ? ( +
+ + {m.print_comments_frame_unavailable()} +
+ ) : ( +
+ {alt} + {status === 'loaded' && annotations.length > 0 && ( + + )} +
+ )} +
+ ) +} diff --git a/packages/webui/components/print-comments/print-comments-view.test.tsx b/packages/webui/components/print-comments/print-comments-view.test.tsx new file mode 100644 index 00000000..553de2ca --- /dev/null +++ b/packages/webui/components/print-comments/print-comments-view.test.tsx @@ -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 { + 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 + 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( + , + ) + + // 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( + , + ) + + 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( + , + ) + + 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('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( + , + ) + + 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( + , + ) + 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( + , + ) + 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( + , + ) + expect(screen.queryByTestId('print-comment-frame')).toBeNull() + }) + + it('shows friendly fallback when a frame fails to load', () => { + const { container } = render( + , + ) + + 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() + }) +}) diff --git a/packages/webui/components/print-comments/print-comments-view.tsx b/packages/webui/components/print-comments/print-comments-view.tsx new file mode 100644 index 00000000..c9985be1 --- /dev/null +++ b/packages/webui/components/print-comments/print-comments-view.tsx @@ -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 ( + + @{mentionedUser?.name || 'Unknown'} + + ) + } + return {part} + }) +} + +export const PrintCommentsView: React.FC = ({ + 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(hasPositionSort ? 'position' : 'oldest') + const [settledFrameUrls, setSettledFrameUrls] = useState>({}) + + 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() + 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) => { + const url = frameUrls.get(commentId) + if (!url) return null + + return ( + + 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 ( +
+ {/* Avatar + vertical thread connector matching Frame.io / Shumai threads */} +
+ {options.isReply && ( +
+ )} + {((options.hasReplies && !options.isReply) || + (options.isReply && !options.isLastReply)) && ( +
+ )} + + {comment.creator?.image && ( + + )} + + {creatorName[0]?.toUpperCase() || 'U'} + + +
+ + {/* Entry content */} +
+ {/* Author + timestamp + #index + completed status */} +
+
+ {creatorName} + + {formatCommentDateTime(comment.createdAt)} + +
+
+ {comment.isCompleted && ( + + + {m.print_comments_completed()} + + )} + {options.indexNumber !== undefined && ( + + # + {options.indexNumber} + + )} +
+
+ + {/* Prefix (timecode / page / angle + annotation indicator) + Comment text */} +
+ {(timestamp || hasAnnotations) && ( + + {timestamp && ( + + {timestamp} + + )} + {hasAnnotations && ( + + + + )} + + )} + + {comment.sessionId && comment.message ? ( +
+ {preprocessMarkdown(comment.message)} +
+ ) : ( + + {renderPlainCommentText(comment)} + + )} +
+ + {options.isReply && frameUrls.has(comment.id) && ( +
{renderFrame(comment.id, annotations)}
+ )} + + {/* Attachments */} + {comment.attachments && comment.attachments.length > 0 && ( +
+ {comment.attachments.map((att) => { + const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file' + const name = decodeURIComponent(rawName) + const isImage = isImageFileName(name) + return ( +
+ {isImage ? ( + {name} + ) : ( + + )} + + {name} + +
+ ) + })} +
+ )} + + {/* Emoji reactions */} + {comment.reactionCounts && comment.reactionCounts.length > 0 && ( +
+ {comment.reactionCounts.map((reaction) => ( + + {reaction.code} + {reaction.count} + + ))} +
+ )} +
+
+ ) + } + + return ( +
+ {/* Non-printable action toolbar */} +
+
+
+ {isLoadingFrames ? ( + + + + {m.print_comments_loading_frames({ + loaded: String(settledFrameCount), + total: String(frameUrls.size), + })} + + + ) : ( + {commentCountLabel} + )} +
+ +
+
+ {hasPositionSort && ( + + )} + + +
+ + +
+
+
+ + {/* Printable document body */} +
+ {/* Document Header */} +
+
+ {headerThumbUrl ? ( + + ) : proxyType === 'audio' ? ( + + ) : proxyType === 'pdf' ? ( + + ) : ( + + )} +
+ +
+ {/* Top row: Breadcrumbs + Shumai Logo */} +
+ + +
+ + {/* Bottom row: Filename + Creator & Date */} +
+

+ {nameHead} + {nameTail && {nameTail}} +

+ {creatorAndDate && ( + + {creatorAndDate} + + )} +
+
+
+ +
+ + {/* Sort Indicator */} +
+ + {sortIndicatorLabel} +
+ + {/* Comments List */} + {sortedComments.length === 0 ? ( +
+ {m.print_comments_empty()} +
+ ) : ( +
+ {sortedComments.map((comment, idx) => { + const annotations = parseAnnotations(comment.annotations) + const replies = comment.replies ?? [] + + return ( +
+ {hasVisualThumbnailColumn && ( +
{renderFrame(comment.id, annotations)}
+ )} + +
+ {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, + }), + )} +
+
+ ) + })} +
+ )} +
+
+ ) +} diff --git a/packages/webui/globals.css b/packages/webui/globals.css index 1fa812c1..4aad28e4 100644 --- a/packages/webui/globals.css +++ b/packages/webui/globals.css @@ -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; + } +} diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index 983316cc..49a7d62b 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -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" } diff --git a/packages/webui/messages/ko.json b/packages/webui/messages/ko.json index 89a44130..aacd33bf 100644 --- a/packages/webui/messages/ko.json +++ b/packages/webui/messages/ko.json @@ -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": "์ฃผ์„์ด ํฌํ•จ๋œ ๋Œ“๊ธ€" } diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index d85c21c7..d1eddf45 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -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": "่ฏ„่ฎบๅŒ…ๅซๆ ‡ๆณจ" } diff --git a/packages/webui/routeTree.gen.ts b/packages/webui/routeTree.gen.ts index 5b46126c..62dca9af 100644 --- a/packages/webui/routeTree.gen.ts +++ b/packages/webui/routeTree.gen.ts @@ -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, diff --git a/packages/webui/routes/print/comments/$assetId.lazy.tsx b/packages/webui/routes/print/comments/$assetId.lazy.tsx new file mode 100644 index 00000000..f77cc034 --- /dev/null +++ b/packages/webui/routes/print/comments/$assetId.lazy.tsx @@ -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({ + 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 ( +
+ +

{m.print_comments_loading()}

+
+ ) + } + + if (shareId && error instanceof PrintAuthError && error.status === 401) { + return ( +
+ + + + + {m.password_protected()} + + + +
+ setPasswordInput(e.target.value)} + placeholder={m.enter_password()} + autoFocus + /> + {sharePassword && ( +

+ {m.incorrect_password()} +

+ )} + +
+
+
+
+ ) + } + + if (error || !data) { + return ( +
+ +

{m.print_comments_error()}

+
+ ) + } + + return ( + + ) +} + +export const Route = createLazyFileRoute('/print/comments/$assetId')({ + component: PrintCommentsPage, +}) diff --git a/packages/webui/routes/print/comments/$assetId.tsx b/packages/webui/routes/print/comments/$assetId.tsx new file mode 100644 index 00000000..9cff7fce --- /dev/null +++ b/packages/webui/routes/print/comments/$assetId.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/print/comments/$assetId')({ + validateSearch: (search: Record) => { + return { + shareId: typeof search.shareId === 'string' && search.shareId ? search.shareId : undefined, + } as { + shareId?: string + } + }, +})