mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-01 13:34:33 +00:00
feat(sharelink): add sharelink watermark support (#270)
* feat(sharelink): add sharelink watermark support
* fix(sharelink): harden watermark feature against races, crashes, and tenant leaks
Addresses review findings on the sharelink watermark feature:
- fix(watermark): read back sharelink via transaction client so the
updateShareLinkWatermark response reflects the just-committed state
(global-client reads on a pooled connection miss uncommitted changes)
- fix(watermark): use prisma upsert on the config hash instead of
find-then-create to avoid P2002 races on concurrent enables
- fix(watermark): resolve nested symlinks when walking the share tree and
batch the walk level-by-level instead of one query per node
- fix(watermark): keep watermark tasks in flight from being purged by
orphan-config GC (avoids FK violations in completing activities)
- fix(transcode): re-transcode stale 'processing' watermark rows instead
of silently skipping (crash recovery); downscale embedded block images;
use pino structured logging; drop unused any casts
- fix(api): scope watermark-template list/create to the caller's teams,
reject teamless template creation, and make teamless templates
read-only; validate watermark config required when enabling (400);
map sharelink-not-found to 404
- fix(api): resolve symlink target ids once in public share children
endpoint instead of twice per item
- refactor(db): dedicated WatermarkFileStatus enum (migration included)
- test: activity unit tests (init crash recovery, image + video transcode
paths), concurrent upsert, nested-symlink resolution, API scoping and
validation, e2e video watermark path
* refactor(transcode): move sharp usage out of watermark activity into transcodeService
The transcode package does not declare sharp as a dependency (only
@shumai/core does), so importing it directly in the watermark activity
broke CI typecheck for the transcode package.
- add transcodeService.renderSvgToPng, downscaleImageToPng and
compositeOverlayToWebpFile encapsulating the sharp logic
- watermark activity now calls these methods instead of importing sharp
- activity tests mock the new methods (no sharp/real fixture needed)
- add unit tests for the new transcodeService helpers
* feat(watermark): restrict watermark transcode to existing image and video transcodes
* refactor(transcode): reuse transcodeVideo in watermark activity
* refactor(watermark): use Bun.hash instead of node crypto for watermark config hash
* refactor(watermark): move computeWatermarkConfigHash from dtos to core watermark-hash module
* refactor(api): delegate watermark DB queries from public-share route to watermarkService
* refactor(share): replace dynamic watermarkService import with static import
* feat(watermark): add waitForWatermarkFileActivity for in-flight watermark transcoding tasks
* refactor(asset): replace dynamic watermarkService import with static import
* test(watermark): harden purgeOrphanWatermarkConfigs coverage
Replace the single happy-path GC test with a dedicated suite covering:
- orphan config with proxies: purged, watermarkFiles removed, all four
proxy keys deleted from S3 while the original key is preserved
- config still referenced by a share link is not purged
- config with pending/processing transcode_watermark tasks is not purged
(in-flight guard), but completed tasks do not block purging
- pending tasks of other types (transcode_video) do not protect a config
- an S3 delete failure is non-fatal: remaining keys still deleted and the
config is still purged
- mixed run: only the orphan config is purged while a referenced one
survives (exact count assertion)
* feat(webui): add sharelink watermark editor and sidebar controls
* style(webui): enlarge watermark editor dialog and allocate 2/3 width to preview column
* fix(webui): override sm:max-w-lg in DialogContent to allow full 1400px width
* fix(webui): stop block click propagation and remove preview mode toggles
* fix(webui): store watermark block size as fraction of canvas width
The editor stored block.size in pixels (slider 10-120px, preview
fontSize: `${block.size}px`) while the SVG generator
(generateWatermarkSvg) interprets size as a fraction (0..1) of canvas
width. A 36px block therefore rendered as a ~36x-canvas glyph covering
the entire image.
- Keep backend fraction semantics (canvasWidth * size) so watermarks
scale proportionally with output resolution across proxies
- Editor: defaults (text 5%, image 15%), slider ranges (1-12% / 2-50%)
and number input now work in percent, storing a fraction
- Preview: scales blocks by the measured canvas width so WYSIWYG
- DTO schema: size constrained to (0..1) to enforce the contract
- Update DTO/editor tests to fraction sizes
* feat(webui): add single-row aspect ratio selector and 5 predefined background colors to watermark editor preview
* feat(webui): update aspect ratio to multi-toggle group and enable dot-grid pattern for all background colors
* fix(webui): update background swatches to distinct colors and share PRESET_BACKGROUND_OPTIONS array
* fix(webui): hide redundant absolute close button on watermark editor dialog header
* fix(transcode): skip raw video transcode when generating watermark proxies
The raw marker entry (isRaw: true) in videoTranscodes points at the
original source file and is only used to offer the 'Original' playback
option. It is not a transcoded proxy, so watermarking it produced a
redundant full-resolution transcode (the most expensive pass) plus an
unneeded S3 upload.
Skip entries with isRaw: true in transcodeWatermarkMediaActivity, and
cover the behavior with a unit regression test plus an e2e assertion
that exactly one watermark proxy is produced for a video asset.
* feat(webui): replace watermark image asset ID with 1MB file uploader
* fix(webui): correct watermark editor preview block sizing
The preview canvas width was measured in a useEffect([open]) that ran
before the Radix Dialog had mounted its content, so canvasRef.current was
still null, canvasWidthPx stayed 0, and every block silently fell back to
the hardcoded 640px width (block.size * (canvasWidthPx || 640)). A 100%
size therefore rendered at ~640px on an ~876px canvas (~72%), making the
preview smaller than the real watermarked output for both image and text
blocks.
- Measure the canvas via a ref callback (fires exactly when the node
mounts, regardless of dialog mount timing) and keep a ResizeObserver
attached for aspect-ratio/window changes.
- Use clientWidth (padding-box width) instead of getBoundingClientRect(),
which includes the dialog's zoom-in-95 animation transform.
- Drop max-w-full/max-h-full on the preview <img> so logos scale up to
the block size like the backend SVG rendering does, instead of being
capped at their natural pixel size.
* fix(webui): keep watermark editor preview aspect ratio and restore config scroll
- Compute the preview canvas size with a JS contain-fit (ResizeObserver on the
frame) instead of relying on CSS aspect-ratio + w-full/max-h-full, which
broke the selected ratio on wide-and-short (or tall-and-narrow) windows.
- Add min-h-0 to the config ScrollArea so it shrinks to the column's remaining
height instead of growing to its content height, restoring the scroll range.
* fix(webui): remove toast notification on template load
* fix(share): serve per-file watermark proxies in public share APIs
Stop gating watermark replacement on the share-link-wide watermarkStatus.
Public share endpoints now resolve each asset's own completed watermark
proxy and:
- replace videoTranscodes/imageTranscodes with the watermarked entries
when the watermark file is completed;
- empty those arrays when no completed proxy exists yet (still
transcoding or failed) so original, unwatermarked media is never
exposed while a newly added file is being processed;
- leave non-video/image media (pdf, audio, ...) untouched, since they
never receive watermark transcodes.
This removes the previous behavior where adding a file to a ready
watermark share flipped the whole share link to processing and served
original media for every file until the new transcode finished.
Adds API tests for detail/children endpoints (ready, in-flight, pdf, and
watermark-disabled cases) and a workflow E2E test for adding an asset to
an already-ready watermark sharelink.
This commit is contained in:
@@ -22,6 +22,7 @@ import { HTTPException } from 'hono/http-exception'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
|
||||
@@ -1104,6 +1105,7 @@ export class AssetService {
|
||||
await this.expireTrashedAssets()
|
||||
await this.purgePendingAssets()
|
||||
await this.purgeUnreferencedStorageKeys()
|
||||
await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
} catch (e: unknown) {
|
||||
console.error('Error in asset cleanup job:', e)
|
||||
}
|
||||
|
||||
@@ -23,3 +23,4 @@ export * from './hyrumtoken'
|
||||
export * from './pagination'
|
||||
export * from './chat/chat'
|
||||
export * from './ai-usage/ai-usage'
|
||||
export * from './watermark/watermark'
|
||||
|
||||
@@ -29,3 +29,11 @@ export class ShareLinkPasswordInvalidError extends Error {
|
||||
Object.setPrototypeOf(this, ShareLinkPasswordInvalidError.prototype)
|
||||
}
|
||||
}
|
||||
|
||||
export class ShareLinkWatermarkProcessingError extends Error {
|
||||
constructor(message = 'Watermark transcoding is currently in progress') {
|
||||
super(message)
|
||||
this.name = 'ShareLinkWatermarkProcessingError'
|
||||
Object.setPrototypeOf(this, ShareLinkWatermarkProcessingError.prototype)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,11 @@ import {
|
||||
UpdateShareLinkRequest,
|
||||
ListShareLinksRequest,
|
||||
AddAssetToShareRequest,
|
||||
WatermarkConfigSpec,
|
||||
} from '@shumai/dtos'
|
||||
import { PaginatedData, paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import {
|
||||
ShareLinkNotFoundError,
|
||||
ShareLinkDisabledError,
|
||||
@@ -144,13 +146,16 @@ export class ShareService {
|
||||
)
|
||||
}
|
||||
|
||||
async getShareLink(shareLinkId: string): Promise<ShareLinkInfo> {
|
||||
const shareLink = await prisma.shareLink.findUnique({
|
||||
async getShareLink(
|
||||
shareLinkId: string,
|
||||
client: Prisma.TransactionClient | typeof prisma = prisma,
|
||||
): Promise<ShareLinkInfo> {
|
||||
const shareLink = await client.shareLink.findUnique({
|
||||
where: { id: shareLinkId },
|
||||
include: { creator: true },
|
||||
})
|
||||
if (!shareLink) throw new ShareLinkNotFoundError('Share link not found')
|
||||
return await this.toShareLinkInfo(shareLink)
|
||||
return await this.toShareLinkInfo(shareLink, client)
|
||||
}
|
||||
|
||||
async addAssetToShare(shareLinkId: string, req: AddAssetToShareRequest): Promise<number> {
|
||||
@@ -202,6 +207,17 @@ export class ShareService {
|
||||
})
|
||||
})
|
||||
|
||||
if (shareLink.watermarkConfigId) {
|
||||
await prisma.shareLink.update({
|
||||
where: { id: shareLinkId },
|
||||
data: { watermarkStatus: 'processing' },
|
||||
})
|
||||
await watermarkService.triggerWatermarkTranscodeForShareLink(
|
||||
shareLinkId,
|
||||
shareLink.watermarkConfigId,
|
||||
)
|
||||
}
|
||||
|
||||
return idsToAdd.length
|
||||
}
|
||||
|
||||
@@ -297,10 +313,18 @@ export class ShareService {
|
||||
return shareLink
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private async toShareLinkInfo(l: any): Promise<ShareLinkInfo> {
|
||||
private async toShareLinkInfo(
|
||||
l: Prisma.ShareLinkGetPayload<{ include: { creator: true } }>,
|
||||
client: Prisma.TransactionClient | typeof prisma = prisma,
|
||||
): Promise<ShareLinkInfo> {
|
||||
const isExpired = l.expireAt ? new Date(l.expireAt) < new Date() : false
|
||||
const avatarUrl = l.creator ? await getAvatarUrl(l.creator.image) : undefined
|
||||
let watermarkConfig: Prisma.WatermarkConfigGetPayload<Record<string, never>> | null = null
|
||||
if (l.watermarkConfigId) {
|
||||
watermarkConfig = await client.watermarkConfig.findUnique({
|
||||
where: { id: l.watermarkConfigId },
|
||||
})
|
||||
}
|
||||
return {
|
||||
id: l.id,
|
||||
name: l.name,
|
||||
@@ -308,12 +332,23 @@ export class ShareService {
|
||||
isDisabled: l.isDisabled,
|
||||
hasPassword: !!l.password,
|
||||
password: l.password,
|
||||
defaultSortOrder: l.defaultSortOrder,
|
||||
viewMode: l.viewMode,
|
||||
defaultSortOrder: l.defaultSortOrder ?? undefined,
|
||||
viewMode: l.viewMode ?? undefined,
|
||||
fieldVisibility: l.fieldVisibility as Record<string, boolean> | undefined,
|
||||
rootFolderId: l.rootFolderId,
|
||||
projectId: l.projectId,
|
||||
isExpired,
|
||||
watermarkConfigId: l.watermarkConfigId,
|
||||
watermarkStatus: l.watermarkStatus || 'disabled',
|
||||
watermarkConfig: watermarkConfig
|
||||
? {
|
||||
id: watermarkConfig.id,
|
||||
config: await watermarkService.enrichWatermarkConfigWithPresignedUrls(
|
||||
watermarkConfig.config as WatermarkConfigSpec,
|
||||
),
|
||||
hash: watermarkConfig.hash,
|
||||
}
|
||||
: null,
|
||||
createdAt: l.createdAt.toISOString(),
|
||||
updatedAt: l.updatedAt.toISOString(),
|
||||
creator: l.creator ? { id: l.creator.id, name: l.creator.name, image: avatarUrl } : null,
|
||||
|
||||
@@ -28,6 +28,7 @@ vi.mock('sharp', () => {
|
||||
toColorspace: vi.fn().mockReturnThis(),
|
||||
webp: vi.fn().mockReturnThis(),
|
||||
composite: vi.fn().mockReturnThis(),
|
||||
png: vi.fn().mockReturnThis(),
|
||||
toBuffer: vi.fn().mockResolvedValue(Buffer.from('fake-webp-buffer')),
|
||||
toFile: vi.fn().mockImplementation(async (filePath: string) => {
|
||||
fs.writeFileSync(filePath, 'fake-webp-data')
|
||||
@@ -763,5 +764,55 @@ describe('TranscodeService', () => {
|
||||
const stat = fs.statSync(pdfFile)
|
||||
expect(stat.size).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
describe('watermark overlay helpers', () => {
|
||||
it('renderSvgToPng should rasterize the SVG to a PNG buffer', async () => {
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg"><text>WM</text></svg>'
|
||||
const result = await transcodeService.renderSvgToPng(svg)
|
||||
expect(Buffer.isBuffer(result)).toBe(true)
|
||||
// sharp was invoked with the SVG bytes
|
||||
expect(sharp).toHaveBeenCalledWith(Buffer.from(svg))
|
||||
})
|
||||
|
||||
it('downscaleImageToPng should resize, normalize to PNG and return dimensions', async () => {
|
||||
const result = await transcodeService.downscaleImageToPng(Buffer.from('raw-image'), 1024)
|
||||
expect(result.buffer).toBeDefined()
|
||||
expect(result.width).toBe(800)
|
||||
expect(result.height).toBe(600)
|
||||
// resize limited to the max dimension without enlargement
|
||||
const resizeCall = vi.mocked(sharp().resize).mock.calls[0] as unknown[]
|
||||
expect(resizeCall[0]).toBe(1024)
|
||||
expect(resizeCall[1]).toBe(1024)
|
||||
expect(resizeCall[2]).toEqual({
|
||||
fit: 'inside',
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
expect(vi.mocked(sharp().png)).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('compositeOverlayToWebpFile should composite the overlay and write a webp file', async () => {
|
||||
const inputPath = path.join(tempDir, 'input.png')
|
||||
const outputPath = path.join(tempDir, 'output.webp')
|
||||
fs.writeFileSync(inputPath, 'fake-input')
|
||||
|
||||
await transcodeService.compositeOverlayToWebpFile(
|
||||
inputPath,
|
||||
Buffer.from('overlay-png'),
|
||||
outputPath,
|
||||
1920,
|
||||
1080,
|
||||
)
|
||||
|
||||
expect(fs.existsSync(outputPath)).toBe(true)
|
||||
expect(vi.mocked(sharp().resize)).toHaveBeenCalledWith(1920, 1080, {
|
||||
fit: 'inside',
|
||||
})
|
||||
expect(vi.mocked(sharp().composite)).toHaveBeenCalledWith([
|
||||
{ input: Buffer.from('overlay-png') },
|
||||
])
|
||||
expect(vi.mocked(sharp().webp)).toHaveBeenCalledWith({ quality: 90 })
|
||||
expect(vi.mocked(sharp().toFile)).toHaveBeenCalledWith(outputPath)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -110,6 +110,7 @@ export interface TranscodeVideoParams {
|
||||
height: number
|
||||
frameRate?: number | string
|
||||
disableAudio?: boolean
|
||||
overlayFile?: string
|
||||
}
|
||||
|
||||
export interface ExtractVideoFramesParams {
|
||||
@@ -339,13 +340,22 @@ export class TranscodeService {
|
||||
}
|
||||
|
||||
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
|
||||
let filterComplex = `[0:v]scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
|
||||
let filterComplex: string
|
||||
const args: string[] = ['-i', params.inputFile]
|
||||
|
||||
if (params.overlayFile) {
|
||||
args.push('-i', params.overlayFile)
|
||||
filterComplex = `[0:v]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0`
|
||||
} else {
|
||||
filterComplex = `[0:v]scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
|
||||
}
|
||||
|
||||
if (params.frameRate) {
|
||||
filterComplex += `,fps=${params.frameRate}`
|
||||
}
|
||||
filterComplex += '[vout]'
|
||||
|
||||
const args = ['-i', params.inputFile, '-filter_complex', filterComplex, '-map', '[vout]']
|
||||
args.push('-filter_complex', filterComplex, '-map', '[vout]')
|
||||
|
||||
if (params.frameRate) {
|
||||
let calculatedFps: number
|
||||
@@ -1148,6 +1158,55 @@ export class TranscodeService {
|
||||
this.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders an SVG string to a PNG buffer. Used by the watermark workflow to
|
||||
* rasterize the overlay before compositing it onto images or feeding it to
|
||||
* ffmpeg for video overlays.
|
||||
*/
|
||||
async renderSvgToPng(svgString: string): Promise<Buffer> {
|
||||
return sharp(Buffer.from(svgString)).png().toBuffer()
|
||||
}
|
||||
|
||||
/**
|
||||
* Downscales an image buffer to a bounded size and normalizes it to PNG.
|
||||
* Used for watermark block images embedded into the SVG overlay, so large
|
||||
* logo assets don't balloon the SVG/base64 payload.
|
||||
*/
|
||||
async downscaleImageToPng(
|
||||
buffer: Buffer,
|
||||
maxDimension: number,
|
||||
): Promise<{ buffer: Buffer; width: number; height: number }> {
|
||||
const processed = await sharp(buffer, { limitInputPixels: false })
|
||||
.resize(maxDimension, maxDimension, { fit: 'inside', withoutEnlargement: true })
|
||||
.png()
|
||||
.toBuffer()
|
||||
const meta = await sharp(processed).metadata()
|
||||
return {
|
||||
buffer: processed,
|
||||
width: meta.width || 100,
|
||||
height: meta.height || 100,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composites an overlay PNG onto an image file and writes a WebP file.
|
||||
* Used by the watermark workflow to produce watermarked image proxies.
|
||||
*/
|
||||
async compositeOverlayToWebpFile(
|
||||
inputPath: string,
|
||||
overlayPngBuffer: Buffer,
|
||||
outputPath: string,
|
||||
width: number,
|
||||
height: number,
|
||||
): Promise<void> {
|
||||
await sharp(inputPath, { limitInputPixels: false })
|
||||
.toColorspace('srgb')
|
||||
.resize(width, height, { fit: 'inside' })
|
||||
.composite([{ input: overlayPngBuffer }])
|
||||
.webp({ quality: 90 })
|
||||
.toFile(outputPath)
|
||||
}
|
||||
}
|
||||
|
||||
function renderAnnotationsToSvg(
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { WatermarkConfigSpec } from '@shumai/dtos'
|
||||
|
||||
export function computeWatermarkConfigHash(config: WatermarkConfigSpec): string {
|
||||
const blockStrings = config.blocks.map((block) => {
|
||||
if (block.type === 'text') {
|
||||
return `text|x:${block.x.toFixed(4)}|y:${block.y.toFixed(4)}|op:${block.opacity.toFixed(2)}|rot:${block.rotation.toFixed(2)}|sz:${block.size.toFixed(4)}|col:${block.color.toLowerCase()}|txt:${block.text}`
|
||||
} else {
|
||||
return `image|x:${block.x.toFixed(4)}|y:${block.y.toFixed(4)}|op:${block.opacity.toFixed(2)}|rot:${block.rotation.toFixed(2)}|sz:${block.size.toFixed(4)}|img:${block.imageAssetKey}`
|
||||
}
|
||||
})
|
||||
blockStrings.sort()
|
||||
const str = blockStrings.join(';')
|
||||
return Bun.hash(str).toString(16)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { WatermarkConfigSpec } from '@shumai/dtos'
|
||||
|
||||
export interface RenderBlockImageData {
|
||||
imageAssetKey: string
|
||||
base64Data: string
|
||||
mimeType: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
function escapeXml(unsafe: string): string {
|
||||
return unsafe
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
export function generateWatermarkSvg(
|
||||
config: WatermarkConfigSpec,
|
||||
canvasWidth: number,
|
||||
canvasHeight: number,
|
||||
blockImagesMap: Map<string, RenderBlockImageData> = new Map(),
|
||||
): string {
|
||||
const elements: string[] = []
|
||||
|
||||
for (const block of config.blocks) {
|
||||
const cx = canvasWidth * block.x
|
||||
const cy = canvasHeight * block.y
|
||||
const opacity = Math.max(0, Math.min(1, block.opacity))
|
||||
const rotation = block.rotation || 0
|
||||
|
||||
if (block.type === 'text') {
|
||||
// block.size is a FRACTION of the canvas width (0..1), so the watermark
|
||||
// scales proportionally with the output resolution. The editor must store
|
||||
// size as a fraction too (it converts from its %/px UI controls).
|
||||
const fontSize = Math.max(1, Math.round(canvasWidth * block.size))
|
||||
const textContent = escapeXml(block.text || '')
|
||||
const fill = escapeXml(block.color || '#FFFFFF')
|
||||
|
||||
elements.push(
|
||||
`<text x="${cx}" y="${cy}" text-anchor="middle" dominant-baseline="central" font-family="sans-serif" font-size="${fontSize}" font-weight="bold" fill="${fill}" opacity="${opacity}" transform="rotate(${rotation}, ${cx}, ${cy})">${textContent}</text>`,
|
||||
)
|
||||
} else if (block.type === 'image') {
|
||||
const imageData = blockImagesMap.get(block.imageAssetKey)
|
||||
if (!imageData) continue
|
||||
|
||||
// Fraction of canvas width, same as the text blocks above.
|
||||
const targetWidth = Math.max(1, Math.round(canvasWidth * block.size))
|
||||
const aspectRatio = imageData.height > 0 ? imageData.width / imageData.height : 1
|
||||
const targetHeight = Math.max(1, Math.round(targetWidth / aspectRatio))
|
||||
|
||||
const x = cx - targetWidth / 2
|
||||
const y = cy - targetHeight / 2
|
||||
|
||||
elements.push(
|
||||
`<image x="${x}" y="${y}" width="${targetWidth}" height="${targetHeight}" href="data:${imageData.mimeType};base64,${imageData.base64Data}" opacity="${opacity}" transform="rotate(${rotation}, ${cx}, ${cy})"/>`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="${canvasWidth}" height="${canvasHeight}">${elements.join(
|
||||
'\n',
|
||||
)}</svg>`
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateWatermarkSvg } from '@shumai/core/src/watermark/watermark-svg'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { computeWatermarkConfigHash } from '@shumai/core/src/watermark/watermark-hash'
|
||||
import type { WatermarkConfigSpec } from '@shumai/dtos'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
describe('WatermarkService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const sampleConfig: WatermarkConfigSpec = {
|
||||
blocks: [
|
||||
{
|
||||
id: 'block-1',
|
||||
type: 'text',
|
||||
x: 0.5,
|
||||
y: 0.5,
|
||||
opacity: 0.8,
|
||||
rotation: -30,
|
||||
text: 'CONFIDENTIAL',
|
||||
size: 0.2,
|
||||
color: '#FF0000',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
it('should compute deterministic hash ignoring block id and block order', () => {
|
||||
const config1: WatermarkConfigSpec = {
|
||||
blocks: [
|
||||
{
|
||||
id: 'b1',
|
||||
type: 'text',
|
||||
x: 0.5,
|
||||
y: 0.5,
|
||||
opacity: 0.5,
|
||||
rotation: 0,
|
||||
text: 'A',
|
||||
size: 0.1,
|
||||
color: '#FFFFFF',
|
||||
},
|
||||
{
|
||||
id: 'b2',
|
||||
type: 'text',
|
||||
x: 0.1,
|
||||
y: 0.1,
|
||||
opacity: 0.9,
|
||||
rotation: 15,
|
||||
text: 'B',
|
||||
size: 0.2,
|
||||
color: '#000000',
|
||||
},
|
||||
],
|
||||
}
|
||||
const config2: WatermarkConfigSpec = {
|
||||
blocks: [
|
||||
{
|
||||
id: 'other-id-2',
|
||||
type: 'text',
|
||||
x: 0.1,
|
||||
y: 0.1,
|
||||
opacity: 0.9,
|
||||
rotation: 15,
|
||||
text: 'B',
|
||||
size: 0.2,
|
||||
color: '#000000',
|
||||
},
|
||||
{
|
||||
id: 'other-id-1',
|
||||
type: 'text',
|
||||
x: 0.5,
|
||||
y: 0.5,
|
||||
opacity: 0.5,
|
||||
rotation: 0,
|
||||
text: 'A',
|
||||
size: 0.1,
|
||||
color: '#FFFFFF',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const hash1 = computeWatermarkConfigHash(config1)
|
||||
const hash2 = computeWatermarkConfigHash(config2)
|
||||
expect(hash1).toBe(hash2)
|
||||
})
|
||||
|
||||
it('should generate SVG overlay XML', () => {
|
||||
const svg = generateWatermarkSvg(sampleConfig, 1000, 500)
|
||||
expect(svg).toContain('<svg')
|
||||
expect(svg).toContain('CONFIDENTIAL')
|
||||
expect(svg).toContain('fill="#FF0000"')
|
||||
})
|
||||
|
||||
it('should upsert watermark config by hash', async () => {
|
||||
const config1 = await watermarkService.upsertConfig(sampleConfig)
|
||||
expect(config1.id).toBeDefined()
|
||||
|
||||
const config2 = await watermarkService.upsertConfig(sampleConfig)
|
||||
expect(config2.id).toBe(config1.id)
|
||||
})
|
||||
|
||||
it('should not race when upserting the same config concurrently', async () => {
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 10 }, () => watermarkService.upsertConfig(sampleConfig)),
|
||||
)
|
||||
const ids = new Set(results.map((r) => r.id))
|
||||
expect(ids.size).toBe(1)
|
||||
})
|
||||
|
||||
it('should manage watermark templates (CRUD)', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User', email: 'test-wm-tpl@example.com' },
|
||||
})
|
||||
const team = await teamService.createTeam(user, { name: 'Watermark Team' })
|
||||
|
||||
const created = await watermarkService.createTemplate(team.id, 'Draft Preset', sampleConfig)
|
||||
expect(created.id).toBeDefined()
|
||||
expect(created.name).toBe('Draft Preset')
|
||||
|
||||
const list = await watermarkService.listTemplates(team.id)
|
||||
expect(list.length).toBe(1)
|
||||
|
||||
const updated = await watermarkService.updateTemplate(created.id, 'Final Preset')
|
||||
expect(updated.name).toBe('Final Preset')
|
||||
|
||||
const fetched = await watermarkService.getTemplate(created.id)
|
||||
expect(fetched.name).toBe('Final Preset')
|
||||
|
||||
await watermarkService.deleteTemplate(created.id)
|
||||
const emptyList = await watermarkService.listTemplates(team.id)
|
||||
expect(emptyList.length).toBe(0)
|
||||
})
|
||||
|
||||
it('should update sharelink watermark and dispatch transcode tasks', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Share User', email: 'share-wm@example.com' },
|
||||
})
|
||||
const team = await teamService.createTeam(user, { name: 'Share Team' })
|
||||
|
||||
const projectFolder = await prisma.asset.create({
|
||||
data: { name: 'root', type: 'root', status: 'processed' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project', teamId: team.id, rootFolderId: projectFolder.id },
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(project.id, { name: 'My Share' }, user.id)
|
||||
|
||||
// Add a file asset to project and share link
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'sample.mp4',
|
||||
type: 'file',
|
||||
mediaType: 'video/mp4',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
await shareService.addAssetToShare(shareLink.id, { assetIds: [asset.id] })
|
||||
|
||||
// Update sharelink watermark -> enable
|
||||
const updated = await watermarkService.updateShareLinkWatermark(
|
||||
shareLink.id,
|
||||
true,
|
||||
sampleConfig,
|
||||
)
|
||||
expect(updated.watermarkStatus).toBe('processing')
|
||||
expect(updated.watermarkConfigId).toBeDefined()
|
||||
|
||||
// Verify WorkflowTask was created
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: { assetId: asset.id, type: 'transcode_watermark' },
|
||||
})
|
||||
expect(tasks.length).toBeGreaterThan(0)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((tasks[0].payload as any)?.watermark?.watermarkConfigId).toBe(updated.watermarkConfigId)
|
||||
|
||||
// Attempting update while status is processing should throw conflict error
|
||||
await expect(
|
||||
watermarkService.updateShareLinkWatermark(shareLink.id, true, sampleConfig),
|
||||
).rejects.toThrow('Watermark transcoding is currently in progress')
|
||||
|
||||
// Simulate completion of transcoding
|
||||
await prisma.shareLink.update({
|
||||
where: { id: shareLink.id },
|
||||
data: { watermarkStatus: 'ready' },
|
||||
})
|
||||
|
||||
// Disable watermark after ready
|
||||
const disabled = await watermarkService.updateShareLinkWatermark(shareLink.id, false)
|
||||
expect(disabled.watermarkStatus).toBe('disabled')
|
||||
expect(disabled.watermarkConfigId).toBeNull()
|
||||
})
|
||||
|
||||
it('should resolve media assets including nested symlinks in shared folders', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Nested User', email: 'nested-wm@example.com' },
|
||||
})
|
||||
const team = await teamService.createTeam(user, { name: 'Nested Team' })
|
||||
|
||||
const projectFolder = await prisma.asset.create({
|
||||
data: { name: 'root', type: 'root', status: 'processed' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Nested Project', teamId: team.id, rootFolderId: projectFolder.id },
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(
|
||||
project.id,
|
||||
{ name: 'Nested Share' },
|
||||
user.id,
|
||||
)
|
||||
|
||||
// Shared folder -> inner folder -> symlink -> media file
|
||||
const sharedFolder = await prisma.asset.create({
|
||||
data: { name: 'shared', type: 'folder', status: 'processed', projectId: project.id },
|
||||
})
|
||||
const innerFolder = await prisma.asset.create({
|
||||
data: { name: 'inner', type: 'folder', status: 'processed', projectId: project.id },
|
||||
})
|
||||
const mediaFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'clip.mp4',
|
||||
type: 'file',
|
||||
mediaType: 'video/mp4',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: innerFolder.id,
|
||||
},
|
||||
})
|
||||
// symlink inside the shared folder points at the inner folder
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'inner-link',
|
||||
type: 'symlink',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: sharedFolder.id,
|
||||
targetId: innerFolder.id,
|
||||
},
|
||||
})
|
||||
// root symlink for the share points at the shared folder
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'shared-link',
|
||||
type: 'symlink',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
parentId: shareLink.rootFolderId,
|
||||
targetId: sharedFolder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const mediaIds = await watermarkService.getMediaAssetIdsInShareLink(shareLink.rootFolderId)
|
||||
expect(mediaIds).toContain(mediaFile.id)
|
||||
})
|
||||
|
||||
describe('purgeOrphanWatermarkConfigs', () => {
|
||||
const bucket = 'shumai-gc-test-bucket'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
process.env.S3_BUCKET = bucket
|
||||
})
|
||||
|
||||
// Media with every proxy slot the GC should delete from S3 (plus an
|
||||
// `original` key that must survive).
|
||||
function proxyMedia(): PrismaJson.MediaInfo {
|
||||
return {
|
||||
duration: 0,
|
||||
filesize: 100,
|
||||
frames: 0,
|
||||
proxyType: 'video',
|
||||
videoTranscodes: [
|
||||
{ key: 'files/gc/wm.mp4', width: 1920, height: 1080, resolution: '1080p' },
|
||||
],
|
||||
imageTranscodes: [
|
||||
{ key: 'files/gc/wm.webp', width: 1280, height: 720, quality: 90, format: 'webp' },
|
||||
],
|
||||
videoPreview: { key: 'files/gc/preview.mp4', width: 1280, height: 720 },
|
||||
thumbnail: {
|
||||
key: 'files/gc/thumb.webp',
|
||||
width: 320,
|
||||
height: 180,
|
||||
quality: 90,
|
||||
format: 'webp',
|
||||
},
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: { key: 'files/gc/original.mp4', downloadUrl: '', filesizeInBytes: 0, codec: '' },
|
||||
}
|
||||
}
|
||||
|
||||
async function seedProject() {
|
||||
const team = await prisma.team.create({ data: { name: 'GC Team' } })
|
||||
const projectFolder = await prisma.asset.create({
|
||||
data: { name: 'root', type: 'root', status: 'processed' },
|
||||
})
|
||||
return prisma.project.create({
|
||||
data: { name: 'GC Project', teamId: team.id, rootFolderId: projectFolder.id },
|
||||
})
|
||||
}
|
||||
|
||||
async function seedConfigWithWatermarkFile(config: WatermarkConfigSpec = sampleConfig) {
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'gc-asset.mp4', type: 'file', mediaType: 'video/mp4', status: 'processed' },
|
||||
})
|
||||
const wmConfig = await watermarkService.upsertConfig(config)
|
||||
const watermarkFile = await prisma.watermarkFile.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
watermarkConfigId: wmConfig.id,
|
||||
status: 'completed',
|
||||
media: proxyMedia(),
|
||||
},
|
||||
})
|
||||
return { asset, config: wmConfig, watermarkFile }
|
||||
}
|
||||
|
||||
async function seedWatermarkTask(
|
||||
assetId: string,
|
||||
projectId: string,
|
||||
configId: string,
|
||||
status: 'pending' | 'processing' | 'completed',
|
||||
type: 'transcode_watermark' | 'transcode_video' = 'transcode_watermark',
|
||||
) {
|
||||
return prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId,
|
||||
projectId,
|
||||
type,
|
||||
status,
|
||||
payload: {
|
||||
projectId,
|
||||
watermark: { watermarkConfigId: configId },
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('should purge an orphan config, delete its S3 proxies and keep the original key', async () => {
|
||||
const { config, watermarkFile } = await seedConfigWithWatermarkFile()
|
||||
const deleteSpy = vi.spyOn(s3Service, 'deleteObject').mockResolvedValue(0)
|
||||
|
||||
const purgedCount = await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
|
||||
expect(purgedCount).toBe(1)
|
||||
expect(await prisma.watermarkConfig.findUnique({ where: { id: config.id } })).toBeNull()
|
||||
expect(await prisma.watermarkFile.findUnique({ where: { id: watermarkFile.id } })).toBeNull()
|
||||
|
||||
// All proxy slots deleted, but the original file is never touched
|
||||
for (const key of [
|
||||
'files/gc/wm.mp4',
|
||||
'files/gc/wm.webp',
|
||||
'files/gc/preview.mp4',
|
||||
'files/gc/thumb.webp',
|
||||
]) {
|
||||
expect(deleteSpy).toHaveBeenCalledWith(bucket, key)
|
||||
}
|
||||
expect(deleteSpy).not.toHaveBeenCalledWith(bucket, 'files/gc/original.mp4')
|
||||
expect(deleteSpy).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('should NOT purge a config still referenced by a share link', async () => {
|
||||
const { config } = await seedConfigWithWatermarkFile()
|
||||
const project = await seedProject()
|
||||
const shareFolder = await prisma.asset.create({
|
||||
data: { name: 'share-folder', type: 'share', status: 'processed', projectId: project.id },
|
||||
})
|
||||
await prisma.shareLink.create({
|
||||
data: {
|
||||
name: 'GC Share',
|
||||
projectId: project.id,
|
||||
rootFolderId: shareFolder.id,
|
||||
watermarkConfigId: config.id,
|
||||
},
|
||||
})
|
||||
const deleteSpy = vi.spyOn(s3Service, 'deleteObject').mockResolvedValue(0)
|
||||
|
||||
const purgedCount = await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
|
||||
expect(purgedCount).toBe(0)
|
||||
expect(await prisma.watermarkConfig.findUnique({ where: { id: config.id } })).not.toBeNull()
|
||||
expect(deleteSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['pending', 'processing'] as const)(
|
||||
'should NOT purge a config with an in-flight %s watermark task',
|
||||
async (status) => {
|
||||
const { asset, config } = await seedConfigWithWatermarkFile()
|
||||
const project = await seedProject()
|
||||
await seedWatermarkTask(asset.id, project.id, config.id, status)
|
||||
const deleteSpy = vi.spyOn(s3Service, 'deleteObject').mockResolvedValue(0)
|
||||
|
||||
const purgedCount = await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
|
||||
expect(purgedCount).toBe(0)
|
||||
expect(await prisma.watermarkConfig.findUnique({ where: { id: config.id } })).not.toBeNull()
|
||||
expect(deleteSpy).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('should purge a config once its watermark tasks are all completed', async () => {
|
||||
const { asset, config } = await seedConfigWithWatermarkFile()
|
||||
const project = await seedProject()
|
||||
await seedWatermarkTask(asset.id, project.id, config.id, 'completed')
|
||||
vi.spyOn(s3Service, 'deleteObject').mockResolvedValue(0)
|
||||
|
||||
const purgedCount = await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
|
||||
expect(purgedCount).toBe(1)
|
||||
expect(await prisma.watermarkConfig.findUnique({ where: { id: config.id } })).toBeNull()
|
||||
})
|
||||
|
||||
it('should ignore pending tasks of other types when deciding to purge', async () => {
|
||||
const { asset, config } = await seedConfigWithWatermarkFile()
|
||||
const project = await seedProject()
|
||||
// A pending transcode_video task must not protect the watermark config
|
||||
await seedWatermarkTask(asset.id, project.id, config.id, 'pending', 'transcode_video')
|
||||
vi.spyOn(s3Service, 'deleteObject').mockResolvedValue(0)
|
||||
|
||||
const purgedCount = await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
|
||||
expect(purgedCount).toBe(1)
|
||||
expect(await prisma.watermarkConfig.findUnique({ where: { id: config.id } })).toBeNull()
|
||||
})
|
||||
|
||||
it('should keep purging other configs and S3 keys when one S3 delete fails', async () => {
|
||||
const { config } = await seedConfigWithWatermarkFile()
|
||||
const deleteSpy = vi
|
||||
.spyOn(s3Service, 'deleteObject')
|
||||
.mockRejectedValueOnce(new Error('s3 down'))
|
||||
.mockResolvedValue(0)
|
||||
|
||||
const purgedCount = await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
|
||||
expect(purgedCount).toBe(1)
|
||||
expect(await prisma.watermarkConfig.findUnique({ where: { id: config.id } })).toBeNull()
|
||||
// All 4 proxy keys were attempted even though the first one failed
|
||||
expect(deleteSpy).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('should purge only the orphan config when another config is still referenced', async () => {
|
||||
const otherConfig: WatermarkConfigSpec = {
|
||||
blocks: [
|
||||
{
|
||||
id: 'other-block',
|
||||
type: 'text',
|
||||
x: 0.3,
|
||||
y: 0.3,
|
||||
opacity: 0.4,
|
||||
rotation: 10,
|
||||
text: 'OTHER TEAM',
|
||||
size: 0.1,
|
||||
color: '#00FF00',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const orphan = await seedConfigWithWatermarkFile()
|
||||
const referenced = await seedConfigWithWatermarkFile(otherConfig)
|
||||
|
||||
const project = await seedProject()
|
||||
const shareFolder = await prisma.asset.create({
|
||||
data: { name: 'share-folder', type: 'share', status: 'processed', projectId: project.id },
|
||||
})
|
||||
await prisma.shareLink.create({
|
||||
data: {
|
||||
name: 'GC Share',
|
||||
projectId: project.id,
|
||||
rootFolderId: shareFolder.id,
|
||||
watermarkConfigId: referenced.config.id,
|
||||
},
|
||||
})
|
||||
vi.spyOn(s3Service, 'deleteObject').mockResolvedValue(0)
|
||||
|
||||
const purgedCount = await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
|
||||
expect(purgedCount).toBe(1)
|
||||
expect(
|
||||
await prisma.watermarkConfig.findUnique({ where: { id: orphan.config.id } }),
|
||||
).toBeNull()
|
||||
expect(
|
||||
await prisma.watermarkConfig.findUnique({ where: { id: referenced.config.id } }),
|
||||
).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('should fetch completed watermark media map for asset IDs', async () => {
|
||||
const config = await watermarkService.upsertConfig(sampleConfig)
|
||||
const asset1 = await prisma.asset.create({
|
||||
data: { name: 'asset1.png', type: 'file', status: 'processed' },
|
||||
})
|
||||
const asset2 = await prisma.asset.create({
|
||||
data: { name: 'asset2.png', type: 'file', status: 'processed' },
|
||||
})
|
||||
|
||||
const sampleMedia: PrismaJson.MediaInfo = {
|
||||
duration: 0,
|
||||
filesize: 100,
|
||||
frames: 0,
|
||||
proxyType: 'image',
|
||||
imageTranscodes: [
|
||||
{ key: 'watermarked.webp', width: 100, height: 100, quality: 90, format: 'webp' },
|
||||
],
|
||||
videoTranscodes: [],
|
||||
finishedAt: new Date().toISOString(),
|
||||
metadata: null,
|
||||
original: null,
|
||||
}
|
||||
|
||||
await prisma.watermarkFile.create({
|
||||
data: {
|
||||
assetId: asset1.id,
|
||||
watermarkConfigId: config.id,
|
||||
status: 'completed',
|
||||
media: sampleMedia,
|
||||
},
|
||||
})
|
||||
|
||||
// asset2 has pending status
|
||||
await prisma.watermarkFile.create({
|
||||
data: {
|
||||
assetId: asset2.id,
|
||||
watermarkConfigId: config.id,
|
||||
status: 'pending',
|
||||
},
|
||||
})
|
||||
|
||||
const map = await watermarkService.getCompletedWatermarkMediaMap(
|
||||
[asset1.id, asset2.id],
|
||||
config.id,
|
||||
)
|
||||
|
||||
expect(map.size).toBe(1)
|
||||
expect(map.get(asset1.id)).toBeDefined()
|
||||
expect(map.get(asset1.id)?.imageTranscodes[0].key).toBe('watermarked.webp')
|
||||
expect(map.get(asset2.id)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,584 @@
|
||||
import {
|
||||
prisma,
|
||||
WorkflowTaskStatus,
|
||||
WorkflowTaskType,
|
||||
WatermarkStatus,
|
||||
WatermarkFileStatus,
|
||||
WatermarkConfig,
|
||||
WatermarkTemplate,
|
||||
} from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import {
|
||||
WatermarkConfigSpec,
|
||||
WatermarkConfigInfo,
|
||||
WatermarkTemplateInfo,
|
||||
ShareLinkInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { computeWatermarkConfigHash } from '@shumai/core/src/watermark/watermark-hash'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
ShareLinkNotFoundError,
|
||||
ShareLinkWatermarkProcessingError,
|
||||
} from '@shumai/core/src/share/errors'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
// Union of the global client and interactive-transaction client, which share the
|
||||
// same delegate shapes for the models used by this service.
|
||||
type WatermarkDbClient = Prisma.TransactionClient | typeof prisma
|
||||
|
||||
export class WatermarkService {
|
||||
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
||||
|
||||
async upsertConfig(config: WatermarkConfigSpec) {
|
||||
return this.upsertConfigWithClient(this.prismaClient, config)
|
||||
}
|
||||
|
||||
private async upsertConfigWithClient(client: WatermarkDbClient, config: WatermarkConfigSpec) {
|
||||
const hash = computeWatermarkConfigHash(config)
|
||||
// Upsert keyed on the unique hash so concurrent enables of the same config
|
||||
// cannot race into a unique-constraint violation.
|
||||
return client.watermarkConfig.upsert({
|
||||
where: { hash },
|
||||
update: {},
|
||||
create: {
|
||||
hash,
|
||||
config: config as PrismaJson.WatermarkConfigSpec,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Watermark Template CRUD
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
async createTemplate(
|
||||
teamId: string | null,
|
||||
name: string,
|
||||
config: WatermarkConfigSpec,
|
||||
): Promise<WatermarkTemplateInfo> {
|
||||
const tpl = await this.prismaClient.watermarkTemplate.create({
|
||||
data: {
|
||||
name,
|
||||
config: config as PrismaJson.WatermarkConfigSpec,
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
return await this.toWatermarkTemplateInfo(tpl)
|
||||
}
|
||||
|
||||
async updateTemplate(
|
||||
templateId: string,
|
||||
name?: string,
|
||||
config?: WatermarkConfigSpec,
|
||||
): Promise<WatermarkTemplateInfo> {
|
||||
const existing = await this.prismaClient.watermarkTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
})
|
||||
if (!existing) {
|
||||
throw new Error('Watermark template not found')
|
||||
}
|
||||
|
||||
const tpl = await this.prismaClient.watermarkTemplate.update({
|
||||
where: { id: templateId },
|
||||
data: {
|
||||
name: name ?? undefined,
|
||||
config: config ? (config as PrismaJson.WatermarkConfigSpec) : undefined,
|
||||
},
|
||||
})
|
||||
return await this.toWatermarkTemplateInfo(tpl)
|
||||
}
|
||||
|
||||
async deleteTemplate(templateId: string): Promise<void> {
|
||||
const existing = await this.prismaClient.watermarkTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
})
|
||||
if (!existing) {
|
||||
throw new Error('Watermark template not found')
|
||||
}
|
||||
await this.prismaClient.watermarkTemplate.delete({
|
||||
where: { id: templateId },
|
||||
})
|
||||
}
|
||||
|
||||
async listTemplates(teamIds?: string | string[] | null): Promise<WatermarkTemplateInfo[]> {
|
||||
const where = teamIds
|
||||
? Array.isArray(teamIds)
|
||||
? { teamId: { in: teamIds } }
|
||||
: { teamId: teamIds }
|
||||
: undefined
|
||||
const tpls = await this.prismaClient.watermarkTemplate.findMany({
|
||||
where,
|
||||
// ULIDs are time-sortable; ordering by id desc is the project convention
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
return await Promise.all(tpls.map((t) => this.toWatermarkTemplateInfo(t)))
|
||||
}
|
||||
|
||||
async getTemplate(templateId: string): Promise<WatermarkTemplateInfo> {
|
||||
const tpl = await this.prismaClient.watermarkTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
})
|
||||
if (!tpl) {
|
||||
throw new Error('Watermark template not found')
|
||||
}
|
||||
return await this.toWatermarkTemplateInfo(tpl)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// ShareLink Watermark Management
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
async updateShareLinkWatermark(
|
||||
shareLinkId: string,
|
||||
enabled: boolean,
|
||||
config?: WatermarkConfigSpec,
|
||||
): Promise<ShareLinkInfo> {
|
||||
return await this.prismaClient.$transaction(async (tx) => {
|
||||
// Lock the sharelink record SELECT FOR UPDATE
|
||||
const lockedRows = await tx.$queryRaw<
|
||||
{
|
||||
id: string
|
||||
watermarkStatus: WatermarkStatus
|
||||
watermarkConfigId: string | null
|
||||
}[]
|
||||
>`SELECT id, watermark_status AS "watermarkStatus", watermark_config_id AS "watermarkConfigId" FROM share_links WHERE id = ${shareLinkId} FOR UPDATE`
|
||||
|
||||
if (lockedRows.length === 0) {
|
||||
throw new ShareLinkNotFoundError('Share link not found')
|
||||
}
|
||||
|
||||
const currentStatus = lockedRows[0].watermarkStatus
|
||||
|
||||
if (currentStatus === WatermarkStatus.processing) {
|
||||
throw new ShareLinkWatermarkProcessingError(
|
||||
'Watermark transcoding is currently in progress',
|
||||
)
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
await tx.shareLink.update({
|
||||
where: { id: shareLinkId },
|
||||
data: {
|
||||
watermarkConfigId: null,
|
||||
watermarkStatus: WatermarkStatus.disabled,
|
||||
},
|
||||
})
|
||||
// Read back through the transaction client: the global client runs on a
|
||||
// different pooled connection and cannot see uncommitted changes.
|
||||
return await shareService.getShareLink(shareLinkId, tx)
|
||||
}
|
||||
|
||||
if (!config || !config.blocks || config.blocks.length === 0) {
|
||||
throw new Error('Watermark configuration is required when enabling watermark')
|
||||
}
|
||||
|
||||
// Upsert watermark config based on hash
|
||||
const watermarkConfig = await this.upsertConfigWithClient(tx, config)
|
||||
|
||||
await tx.shareLink.update({
|
||||
where: { id: shareLinkId },
|
||||
data: {
|
||||
watermarkConfigId: watermarkConfig.id,
|
||||
watermarkStatus: WatermarkStatus.processing,
|
||||
},
|
||||
})
|
||||
|
||||
// Dispatch transcode tasks for all video/image assets in the sharelink
|
||||
await this.triggerWatermarkTranscodeForShareLink(shareLinkId, watermarkConfig.id, tx)
|
||||
|
||||
return await shareService.getShareLink(shareLinkId, tx)
|
||||
})
|
||||
}
|
||||
|
||||
async getShareLinkWatermark(shareLinkId: string): Promise<{
|
||||
watermarkStatus: WatermarkStatus
|
||||
watermarkConfig: WatermarkConfigInfo | null
|
||||
}> {
|
||||
const shareLink = await this.prismaClient.shareLink.findUnique({
|
||||
where: { id: shareLinkId },
|
||||
include: { watermarkConfig: true },
|
||||
})
|
||||
|
||||
if (!shareLink) {
|
||||
throw new ShareLinkNotFoundError('Share link not found')
|
||||
}
|
||||
|
||||
return {
|
||||
watermarkStatus: shareLink.watermarkStatus,
|
||||
watermarkConfig: shareLink.watermarkConfig
|
||||
? await this.toWatermarkConfigInfo(shareLink.watermarkConfig)
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all media file asset IDs (videos and images) contained in the sharelink,
|
||||
* including files within symlinked folders, and enqueues transcode workflow tasks.
|
||||
*/
|
||||
async triggerWatermarkTranscodeForShareLink(
|
||||
shareLinkId: string,
|
||||
watermarkConfigId: string,
|
||||
txClient?: WatermarkDbClient,
|
||||
): Promise<number> {
|
||||
const client = txClient || this.prismaClient
|
||||
const shareLink = await client.shareLink.findUnique({
|
||||
where: { id: shareLinkId },
|
||||
})
|
||||
if (!shareLink) return 0
|
||||
|
||||
const targetMediaAssets = await this.getMediaAssetIdsInShareLink(shareLink.rootFolderId, client)
|
||||
|
||||
if (targetMediaAssets.length === 0) {
|
||||
// If no media assets in sharelink, mark sharelink watermark as ready immediately
|
||||
await client.shareLink.update({
|
||||
where: { id: shareLinkId },
|
||||
data: { watermarkStatus: WatermarkStatus.ready },
|
||||
})
|
||||
return 0
|
||||
}
|
||||
|
||||
let dispatchedCount = 0
|
||||
for (const assetId of targetMediaAssets) {
|
||||
// Deliberately one create() per task: the @shumai/db client extension that
|
||||
// submits tasks to the workflow engine only hooks `workflowTask.create`,
|
||||
// not `createMany`.
|
||||
await client.workflowTask.create({
|
||||
data: {
|
||||
assetId,
|
||||
type: WorkflowTaskType.transcode_watermark,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
projectId: shareLink.projectId,
|
||||
payload: {
|
||||
projectId: shareLink.projectId,
|
||||
watermark: {
|
||||
watermarkConfigId,
|
||||
shareLinkId,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
dispatchedCount++
|
||||
}
|
||||
|
||||
return dispatchedCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively resolves real media file asset IDs (video and image) under a sharelink root folder.
|
||||
* Walks the tree level-by-level (batched queries) and follows symlinks at any depth.
|
||||
*/
|
||||
async getMediaAssetIdsInShareLink(
|
||||
rootFolderId: string,
|
||||
txClient?: WatermarkDbClient,
|
||||
): Promise<string[]> {
|
||||
const client = txClient || this.prismaClient
|
||||
|
||||
// Fetch symlinks directly under root folder; these point to the shared targets
|
||||
const symlinks = await client.asset.findMany({
|
||||
where: {
|
||||
parentId: rootFolderId,
|
||||
type: 'symlink',
|
||||
isDeleted: false,
|
||||
},
|
||||
select: { targetId: true },
|
||||
})
|
||||
|
||||
const queue = symlinks.map((s) => s.targetId).filter((id): id is string => !!id)
|
||||
|
||||
if (queue.length === 0) return []
|
||||
|
||||
const mediaAssetIds: string[] = []
|
||||
const visited = new Set<string>()
|
||||
|
||||
while (queue.length > 0) {
|
||||
const frontier = queue.splice(0)
|
||||
const assets = await client.asset.findMany({
|
||||
where: { id: { in: frontier } },
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
mediaType: true,
|
||||
media: true,
|
||||
isDeleted: true,
|
||||
targetId: true,
|
||||
},
|
||||
})
|
||||
|
||||
const folderIds: string[] = []
|
||||
const next: string[] = []
|
||||
|
||||
for (const asset of assets) {
|
||||
if (visited.has(asset.id)) continue
|
||||
visited.add(asset.id)
|
||||
if (asset.isDeleted) continue
|
||||
|
||||
if (asset.type === 'file') {
|
||||
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
|
||||
const proxyType = mediaInfo?.proxyType
|
||||
const isVideo = proxyType === 'video' || asset.mediaType?.startsWith('video/')
|
||||
const isImage = proxyType === 'image' || asset.mediaType?.startsWith('image/')
|
||||
|
||||
if (isVideo || isImage) {
|
||||
mediaAssetIds.push(asset.id)
|
||||
}
|
||||
} else if (asset.type === 'folder') {
|
||||
folderIds.push(asset.id)
|
||||
} else if (asset.type === 'symlink' && asset.targetId) {
|
||||
// Resolve nested symlinks (e.g. folders that contain their own symlinks)
|
||||
next.push(asset.targetId)
|
||||
}
|
||||
}
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
const children = await client.asset.findMany({
|
||||
where: { parentId: { in: folderIds }, isDeleted: false },
|
||||
select: { id: true },
|
||||
})
|
||||
next.push(...children.map((c) => c.id))
|
||||
}
|
||||
|
||||
queue.push(...next)
|
||||
}
|
||||
|
||||
return mediaAssetIds
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all required media assets in a sharelink have completed watermark transcodes.
|
||||
* If all are completed, sets ShareLink.watermarkStatus to 'ready'.
|
||||
* If any failed, sets ShareLink.watermarkStatus to 'failed'.
|
||||
*/
|
||||
async checkAndUpdateShareLinkStatus(shareLinkId: string): Promise<WatermarkStatus> {
|
||||
const shareLink = await this.prismaClient.shareLink.findUnique({
|
||||
where: { id: shareLinkId },
|
||||
})
|
||||
if (!shareLink || !shareLink.watermarkConfigId) {
|
||||
return WatermarkStatus.disabled
|
||||
}
|
||||
|
||||
const watermarkConfigId = shareLink.watermarkConfigId
|
||||
const mediaAssetIds = await this.getMediaAssetIdsInShareLink(shareLink.rootFolderId)
|
||||
|
||||
if (mediaAssetIds.length === 0) {
|
||||
await this.prismaClient.shareLink.update({
|
||||
where: { id: shareLinkId },
|
||||
data: { watermarkStatus: WatermarkStatus.ready },
|
||||
})
|
||||
return WatermarkStatus.ready
|
||||
}
|
||||
|
||||
const watermarkFiles = await this.prismaClient.watermarkFile.findMany({
|
||||
where: {
|
||||
assetId: { in: mediaAssetIds },
|
||||
watermarkConfigId,
|
||||
},
|
||||
})
|
||||
|
||||
const statusMap = new Map(watermarkFiles.map((wf) => [wf.assetId, wf.status]))
|
||||
|
||||
let allCompleted = true
|
||||
let anyFailed = false
|
||||
|
||||
for (const assetId of mediaAssetIds) {
|
||||
const status = statusMap.get(assetId)
|
||||
if (status === WatermarkFileStatus.failed) {
|
||||
anyFailed = true
|
||||
allCompleted = false
|
||||
break
|
||||
}
|
||||
if (status !== WatermarkFileStatus.completed) {
|
||||
allCompleted = false
|
||||
}
|
||||
}
|
||||
|
||||
let newStatus: WatermarkStatus
|
||||
if (anyFailed) {
|
||||
newStatus = WatermarkStatus.failed
|
||||
} else if (allCompleted) {
|
||||
newStatus = WatermarkStatus.ready
|
||||
} else {
|
||||
newStatus = WatermarkStatus.processing
|
||||
}
|
||||
|
||||
if (newStatus !== shareLink.watermarkStatus) {
|
||||
await this.prismaClient.shareLink.update({
|
||||
where: { id: shareLinkId },
|
||||
data: { watermarkStatus: newStatus },
|
||||
})
|
||||
}
|
||||
|
||||
return newStatus
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Background Async Garbage Collection
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Background task to prune orphan WatermarkConfig records and delete their storage files.
|
||||
* Runs as part of background cleanup.
|
||||
*/
|
||||
async purgeOrphanWatermarkConfigs(): Promise<number> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
// 1. Find orphan configs with 0 sharelinks attached and no in-flight watermark
|
||||
// tasks, using FOR UPDATE SKIP LOCKED. Configs with pending/processing tasks
|
||||
// must not be purged, or the running activities would fail with FK violations.
|
||||
const orphanConfigs = await this.prismaClient.$queryRaw<{ id: string }[]>`
|
||||
SELECT wc.id FROM watermark_configs wc
|
||||
WHERE NOT EXISTS (SELECT 1 FROM share_links sl WHERE sl.watermark_config_id = wc.id)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM workflow_tasks wt
|
||||
WHERE wt.type = 'transcode_watermark'
|
||||
AND wt.status IN ('pending', 'processing')
|
||||
AND wt.payload->'watermark'->>'watermarkConfigId' = wc.id
|
||||
)
|
||||
LIMIT 20
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`
|
||||
|
||||
if (orphanConfigs.length === 0) return 0
|
||||
|
||||
let purgedCount = 0
|
||||
|
||||
for (const config of orphanConfigs) {
|
||||
try {
|
||||
// Fetch all watermark files for this config
|
||||
const watermarkFiles = await this.prismaClient.watermarkFile.findMany({
|
||||
where: { watermarkConfigId: config.id },
|
||||
})
|
||||
|
||||
// Delete proxy files from S3
|
||||
for (const wf of watermarkFiles) {
|
||||
const media = wf.media
|
||||
if (media) {
|
||||
const keysToDelete: string[] = []
|
||||
if (Array.isArray(media.videoTranscodes)) {
|
||||
for (const vt of media.videoTranscodes) {
|
||||
if (vt.key) keysToDelete.push(vt.key)
|
||||
}
|
||||
}
|
||||
if (Array.isArray(media.imageTranscodes)) {
|
||||
for (const it of media.imageTranscodes) {
|
||||
if (it.key) keysToDelete.push(it.key)
|
||||
}
|
||||
}
|
||||
if (media.videoPreview?.key) keysToDelete.push(media.videoPreview.key)
|
||||
if (media.thumbnail?.key) keysToDelete.push(media.thumbnail.key)
|
||||
|
||||
for (const key of keysToDelete) {
|
||||
try {
|
||||
await s3Service.deleteObject(bucket, key)
|
||||
} catch (s3Err) {
|
||||
logger.warn({ key, err: s3Err }, 'Failed to delete watermark proxy file from S3')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete WatermarkFiles and WatermarkConfig in DB
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
await tx.watermarkFile.deleteMany({
|
||||
where: { watermarkConfigId: config.id },
|
||||
})
|
||||
await tx.watermarkConfig.delete({
|
||||
where: { id: config.id },
|
||||
})
|
||||
})
|
||||
|
||||
purgedCount++
|
||||
logger.info({ configId: config.id }, 'Purged orphan watermark config and proxy files')
|
||||
} catch (err) {
|
||||
logger.error({ configId: config.id, err }, 'Failed to purge orphan watermark config')
|
||||
}
|
||||
}
|
||||
|
||||
return purgedCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches completed watermark media entries for a list of asset IDs under a specific watermark config.
|
||||
* Returns a map of assetId -> PrismaJson.MediaInfo.
|
||||
*/
|
||||
async getCompletedWatermarkMediaMap(
|
||||
assetIds: string[],
|
||||
watermarkConfigId: string,
|
||||
): Promise<Map<string, PrismaJson.MediaInfo>> {
|
||||
if (assetIds.length === 0) return new Map()
|
||||
|
||||
const watermarkFiles = await prisma.watermarkFile.findMany({
|
||||
where: {
|
||||
assetId: { in: assetIds },
|
||||
watermarkConfigId,
|
||||
status: 'completed',
|
||||
},
|
||||
})
|
||||
|
||||
const map = new Map<string, PrismaJson.MediaInfo>()
|
||||
for (const wf of watermarkFiles) {
|
||||
if (wf.media) {
|
||||
map.set(wf.assetId, wf.media as PrismaJson.MediaInfo)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
/**
|
||||
* Enriches image blocks in a watermark config with accessible presigned URLs for WebUI rendering.
|
||||
*/
|
||||
async enrichWatermarkConfigWithPresignedUrls(
|
||||
config: WatermarkConfigSpec,
|
||||
): Promise<WatermarkConfigSpec> {
|
||||
if (!config || !config.blocks || config.blocks.length === 0) return config
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const enrichedBlocks = await Promise.all(
|
||||
config.blocks.map(async (block) => {
|
||||
if (block.type === 'image' && block.imageAssetKey) {
|
||||
try {
|
||||
const url = await s3Service.presign(bucket, block.imageAssetKey, 'GET')
|
||||
return { ...block, imageAssetUrl: url }
|
||||
} catch (err) {
|
||||
logger.warn({ key: block.imageAssetKey, err }, 'Failed to presign watermark image key')
|
||||
}
|
||||
}
|
||||
return block
|
||||
}),
|
||||
)
|
||||
return { ...config, blocks: enrichedBlocks }
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// DTO Mappers
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
private async toWatermarkTemplateInfo(t: WatermarkTemplate): Promise<WatermarkTemplateInfo> {
|
||||
const config = await this.enrichWatermarkConfigWithPresignedUrls(
|
||||
t.config as WatermarkConfigSpec,
|
||||
)
|
||||
return {
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
config,
|
||||
teamId: t.teamId,
|
||||
createdAt: t.createdAt.toISOString(),
|
||||
updatedAt: t.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
private async toWatermarkConfigInfo(c: WatermarkConfig): Promise<WatermarkConfigInfo> {
|
||||
const config = await this.enrichWatermarkConfigWithPresignedUrls(
|
||||
c.config as WatermarkConfigSpec,
|
||||
)
|
||||
return {
|
||||
id: c.id,
|
||||
config,
|
||||
hash: c.hash,
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const watermarkService = new WatermarkService()
|
||||
Reference in New Issue
Block a user