diff --git a/README.md b/README.md
index 61d48a2d..1eb6cf6b 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,7 @@ Shumai is an open-source Frame.io alternative built for creative teams to collab
* **Custom Asset Metadata**: Define dynamic metadata fields tailored to your production pipeline.
* **Share Link Watermarking**: Protect shared media with customizable text and image watermarks, and save watermark as reusable templates.
* **Wide File Format Support**: Preview common creative file formats, including images (with PSD support), videos, audio, and documents, while allowing any file type to be uploaded and stored.
+* **Office & Document PDF Proxying via Gotenberg**: Convert Word, PowerPoint, Excel, Markdown, HTML, and CSV documents to high-quality PDF proxies for in-browser previewing using [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg).
But Shumai goes beyond being a Frame.io alternative. With modern models like GPT-Image-2 and Seedance 2.5, AI can already handle a surprising amount of creative work. That means you can create or update videos and images from a simple prompt without having to jump back into Photoshop, Premiere or Houdini. That is why Shumai includes a powerful agent system:
diff --git a/README_CN.md b/README_CN.md
index 0bec3f90..6fa3314a 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -27,6 +27,7 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
* **自定义素材元数据**:可以按你的制作流程,自由定义动态元数据字段。
* **分享链接水印**:通过可自定义的文字和图片水印保护共享媒体,并将水印配置保存为模板以便重复使用。
* **丰富的文件格式支持**:支持预览常见创意文件格式,包括图片(支持 PSD)、视频、音频和文档,同时可上传和存储任意类型的文件。
+* **基于 Gotenberg 的文档 PDF 转码代理**:通过集成 [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg) 支持将 Word、PowerPoint、Excel、Markdown、HTML 和 CSV 文档高质量转换为 PDF 代理文件进行在线预览。
但 Shumai 不仅仅只满足于 Frame.io 的开源替代。随着 GPT-Image-2、Seedance 2.5 这类强大模型的问世,AI已经生成产品级的图片/视频。很多时候,你只要给一句提示词,就能直接生成或修改图片和视频,而不用再打开 Photoshop、Premiere 或者 Houdini。也正因为这样,Shumai 才把 AI Agent 做成了核心能力:
diff --git a/docs/docs.json b/docs/docs.json
index e12f7ffd..6af931a1 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -26,6 +26,7 @@
"group": "Using Shumai",
"pages": [
"using-shumai/asset-management",
+ "using-shumai/gotenberg",
"using-shumai/comments",
"using-shumai/version-stack",
"using-shumai/sort-and-search",
diff --git a/docs/using-shumai/gotenberg.mdx b/docs/using-shumai/gotenberg.mdx
new file mode 100644
index 00000000..38a588d0
--- /dev/null
+++ b/docs/using-shumai/gotenberg.mdx
@@ -0,0 +1,103 @@
+---
+title: Document PDF Conversion with Gotenberg
+description: Convert Office documents, HTML, Markdown, CSV, and TXT files into high-fidelity PDF proxies for in-browser previewing.
+---
+
+Office documents, HTML pages, Markdown files, spreadsheets, and plain-text files cannot be rendered natively in web browsers. Shumai uses [Gotenberg](https://gotenberg.dev) — an open-source, Docker-powered conversion API — to turn these files into PDF proxy assets for seamless in-browser previewing.
+
+Gotenberg performs the conversion using:
+
+- **LibreOffice** for Office documents, spreadsheets, and plain text.
+- **Headless Chromium** for HTML and Markdown files.
+
+---
+
+## Supported File Types
+
+When Gotenberg is configured, Shumai automatically generates a PDF proxy for the following uploads:
+
+| Category | Extensions | Converter |
+| ------------------ | ---------------------- | ----------- |
+| Word | `.doc`, `.docx` | LibreOffice |
+| Excel | `.xls`, `.xlsx` | LibreOffice |
+| PowerPoint | `.ppt`, `.pptx` | LibreOffice |
+| OpenDocument | `.odt`, `.ods`, `.odp` | LibreOffice |
+| Rich Text | `.rtf` | LibreOffice |
+| HTML | `.html`, `.htm` | Chromium |
+| Markdown | `.md`, `.markdown` | Chromium |
+| Spreadsheets / CSV | `.csv` | LibreOffice |
+| Plain text | `.txt` | LibreOffice |
+
+### How It Works
+
+1. The file is uploaded and stored in its original form.
+2. Shumai submits a background `transcode_pdf` task to the workflow engine.
+3. Gotenberg converts the file into a `proxy.pdf` asset.
+4. The PDF proxy is further processed into a **poster** WebP image and a **sprite** WebP image, enabling fast, high-fidelity previews in the asset list and viewer.
+
+**Automatic landscape optimization**: Spreadsheets and CSV files with more than 5 columns are automatically converted in landscape layout so wide tables remain readable.
+
+**Markdown rendering**: Markdown content is rendered by Chromium through an `index.html` wrapper template (`{{ toHTML "file.md" }}`), producing clean, styled PDF output.
+
+---
+
+## Configuration
+
+Gotenberg support is opt-in and controlled by the following environment variables on the machine running the transcode workers:
+
+| Variable | Required | Description |
+| ------------------------------- | --------------- | ---------------------------------------------------------------- |
+| `GOTENBERG_URL` | Yes (to enable) | Base URL of the Gotenberg service, e.g. `http://gotenberg:3000`. |
+| `GOTENBERG_BASIC_AUTH_USERNAME` | No | Username when Basic Authentication is enabled on Gotenberg. |
+| `GOTENBERG_BASIC_AUTH_PASSWORD` | No | Password when Basic Authentication is enabled on Gotenberg. |
+
+### Docker Quickstart
+
+You can start a Gotenberg container with a single command:
+
+```bash
+docker run -d --name gotenberg -p 3000:3000 gotenberg/gotenberg:8
+```
+
+If you wish to enable Basic Authentication:
+
+```bash
+docker run -d --name gotenberg -p 3000:3000 gotenberg/gotenberg:8 gotenberg --gotenberg-basic-auth-username=admin --gotenberg-basic-auth-password=secret
+```
+
+### Docker Compose Setup
+
+Add a Gotenberg service to your `docker-compose.yaml`:
+
+```yaml
+gotenberg:
+ image: gotenberg/gotenberg:8
+ restart: unless-stopped
+ ports:
+ - '3000:3000'
+```
+
+Then point Shumai at it:
+
+```bash
+GOTENBERG_URL=http://localhost:3000
+```
+
+---
+
+## Behavior Without Gotenberg
+
+If Gotenberg is not configured or unreachable, Shumai degrades gracefully:
+
+- **Office documents and HTML**: the upload completes as `processed` without a PDF proxy.
+- **CSV, Markdown, and TXT**: a lightweight built-in PDF generator produces the proxy instead, with reduced fidelity.
+
+---
+
+## Security Considerations
+
+Gotenberg renders user-uploaded HTML and Markdown in a headless Chromium instance, which may fetch referenced remote resources (images, stylesheets, links). If your deployment exposes Gotenberg to untrusted content, we recommend:
+
+- Running Gotenberg in an isolated network segment with restricted egress.
+- Configuring Gotenberg's Chromium allow-list (`--chromium-allow-list`) to constrain which URLs Chromium may access.
+- Applying resource limits (CPU/memory) to the Gotenberg container.
diff --git a/packages/core/src/gotenberg/gotenberg.test.ts b/packages/core/src/gotenberg/gotenberg.test.ts
new file mode 100644
index 00000000..c35dd554
--- /dev/null
+++ b/packages/core/src/gotenberg/gotenberg.test.ts
@@ -0,0 +1,219 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import * as fs from 'fs'
+import * as path from 'path'
+import * as os from 'os'
+import { GotenbergService } from './gotenberg'
+
+describe('GotenbergService', () => {
+ const originalEnv = process.env
+ let tmpDir: string
+ let testFilePath: string
+
+ beforeEach(() => {
+ process.env = { ...originalEnv }
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gotenberg-test-'))
+ testFilePath = path.join(tmpDir, 'test.docx')
+ fs.writeFileSync(testFilePath, 'fake docx content')
+ })
+
+ afterEach(() => {
+ process.env = originalEnv
+ fs.rmSync(tmpDir, { recursive: true, force: true })
+ vi.restoreAllMocks()
+ })
+
+ describe('isAvailable', () => {
+ it('should return false if GOTENBERG_URL is not set', async () => {
+ delete process.env.GOTENBERG_URL
+ const service = new GotenbergService()
+ expect(await service.isAvailable()).toBe(false)
+ })
+
+ it('should return false if GOTENBERG_URL is empty', async () => {
+ process.env.GOTENBERG_URL = ' '
+ const service = new GotenbergService()
+ expect(await service.isAvailable()).toBe(false)
+ })
+
+ it('should return true when health check returns 200 OK', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000'
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ } as Response)
+
+ const service = new GotenbergService()
+ const available = await service.isAvailable()
+
+ expect(available).toBe(true)
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'http://gotenberg:3000/health',
+ expect.objectContaining({
+ method: 'GET',
+ }),
+ )
+ })
+
+ it('should include Basic Auth header if username and password are provided', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000'
+ process.env.GOTENBERG_BASIC_AUTH_USERNAME = 'user'
+ process.env.GOTENBERG_BASIC_AUTH_PASSWORD = 'pass'
+
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ } as Response)
+
+ const service = new GotenbergService()
+ await service.isAvailable()
+
+ const expectedBasic = Buffer.from('user:pass').toString('base64')
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'http://gotenberg:3000/health',
+ expect.objectContaining({
+ headers: {
+ Authorization: `Basic ${expectedBasic}`,
+ },
+ }),
+ )
+ })
+
+ it('should return false when fetch fails', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000'
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Network error'))
+
+ const service = new GotenbergService()
+ expect(await service.isAvailable()).toBe(false)
+ })
+ })
+
+ describe('convertDocumentToPdf', () => {
+ it('should throw error if GOTENBERG_URL is not set', async () => {
+ delete process.env.GOTENBERG_URL
+ const service = new GotenbergService()
+ await expect(service.convertDocumentToPdf(testFilePath, 'test.docx')).rejects.toThrow(
+ 'Gotenberg URL is not configured',
+ )
+ })
+
+ it('should call libreoffice convert endpoint and return buffer', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000/'
+ const mockPdfBuffer = Buffer.from('%PDF-1.7 mock output')
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ arrayBuffer: async () => mockPdfBuffer.buffer,
+ } as unknown as Response)
+
+ const service = new GotenbergService()
+ const result = await service.convertDocumentToPdf(testFilePath, 'test.docx', {
+ landscape: true,
+ })
+
+ expect(result).toBeDefined()
+ expect(result.toString()).toContain('%PDF-1.7')
+
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'http://gotenberg:3000/forms/libreoffice/convert',
+ expect.objectContaining({
+ method: 'POST',
+ body: expect.any(FormData),
+ }),
+ )
+ })
+
+ it('should throw error if gotenberg returns non-200', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000'
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: false,
+ status: 500,
+ statusText: 'Internal Server Error',
+ text: async () => 'Conversion failed',
+ } as unknown as Response)
+
+ const service = new GotenbergService()
+ await expect(service.convertDocumentToPdf(testFilePath, 'test.docx')).rejects.toThrow(
+ 'Gotenberg conversion failed with status 500: Conversion failed',
+ )
+ })
+ })
+
+ describe('convertHtmlToPdf', () => {
+ it('should call chromium html convert endpoint and return buffer', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000'
+ const mockPdfBuffer = Buffer.from('%PDF-1.4 html output')
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ arrayBuffer: async () => mockPdfBuffer.buffer,
+ } as unknown as Response)
+
+ const htmlPath = path.join(tmpDir, 'test.html')
+ fs.writeFileSync(htmlPath, '
Hello
')
+
+ const service = new GotenbergService()
+ const result = await service.convertHtmlToPdf(htmlPath, 'test.html')
+
+ expect(result).toBeDefined()
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'http://gotenberg:3000/forms/chromium/convert/html',
+ expect.objectContaining({
+ method: 'POST',
+ }),
+ )
+ })
+ })
+
+ describe('convertMarkdownToPdf', () => {
+ it('should call chromium markdown convert endpoint with index.html wrapper and return buffer', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000'
+ const mockPdfBuffer = Buffer.from('%PDF-1.4 markdown output')
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ status: 200,
+ arrayBuffer: async () => mockPdfBuffer.buffer,
+ } as unknown as Response)
+
+ const mdPath = path.join(tmpDir, 'test.md')
+ fs.writeFileSync(mdPath, '# Hello Gotenberg')
+
+ const service = new GotenbergService()
+ const result = await service.convertMarkdownToPdf(mdPath, 'test.md')
+
+ expect(result).toBeDefined()
+ expect(fetchSpy).toHaveBeenCalledWith(
+ 'http://gotenberg:3000/forms/chromium/convert/markdown',
+ expect.objectContaining({
+ method: 'POST',
+ body: expect.any(FormData),
+ }),
+ )
+ })
+
+ it('should rename non-.md filenames like README.markdown to file.md for Gotenberg endpoint compatibility', async () => {
+ process.env.GOTENBERG_URL = 'http://gotenberg:3000'
+ const mockPdfBuffer = Buffer.from('%PDF-1.4 markdown output')
+ let capturedFormData: FormData | null = null
+
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, options) => {
+ capturedFormData = options?.body as FormData
+ return {
+ ok: true,
+ status: 200,
+ arrayBuffer: async () => mockPdfBuffer.buffer,
+ } as unknown as Response
+ })
+
+ const mdPath = path.join(tmpDir, 'README.markdown')
+ fs.writeFileSync(mdPath, '# Hello Gotenberg')
+
+ const service = new GotenbergService()
+ await service.convertMarkdownToPdf(mdPath, 'README.markdown')
+
+ expect(capturedFormData).not.toBeNull()
+ const indexBlob = (capturedFormData as unknown as FormData).get('files') as File
+ const indexHtmlText = await indexBlob.text()
+ expect(indexHtmlText).toContain('{{ toHTML "file.md" }}')
+ })
+ })
+})
diff --git a/packages/core/src/gotenberg/gotenberg.ts b/packages/core/src/gotenberg/gotenberg.ts
new file mode 100644
index 00000000..dcd65259
--- /dev/null
+++ b/packages/core/src/gotenberg/gotenberg.ts
@@ -0,0 +1,178 @@
+import * as fs from 'fs'
+
+export interface GotenbergConvertOptions {
+ landscape?: boolean
+}
+
+export class GotenbergService {
+ private getUrl(): string | undefined {
+ const url = process.env.GOTENBERG_URL?.trim()
+ return url ? url.replace(/\/+$/, '') : undefined
+ }
+
+ private getAuthHeader(): string | undefined {
+ const username = process.env.GOTENBERG_BASIC_AUTH_USERNAME
+ const password = process.env.GOTENBERG_BASIC_AUTH_PASSWORD
+
+ if (username && password) {
+ const credentials = Buffer.from(`${username}:${password}`).toString('base64')
+ return `Basic ${credentials}`
+ }
+ return undefined
+ }
+
+ async isAvailable(): Promise {
+ const baseUrl = this.getUrl()
+ if (!baseUrl) {
+ return false
+ }
+
+ try {
+ const headers: Record = {}
+ const authHeader = this.getAuthHeader()
+ if (authHeader) {
+ headers['Authorization'] = authHeader
+ }
+
+ const response = await fetch(`${baseUrl}/health`, {
+ method: 'GET',
+ headers,
+ signal: AbortSignal.timeout(3000),
+ })
+
+ return response.ok
+ } catch {
+ return false
+ }
+ }
+
+ async convertDocumentToPdf(
+ filePath: string,
+ filename: string,
+ options: GotenbergConvertOptions = {},
+ ): Promise {
+ const baseUrl = this.getUrl()
+ if (!baseUrl) {
+ throw new Error('Gotenberg URL is not configured.')
+ }
+
+ const fileBytes = fs.readFileSync(filePath)
+ const formData = new FormData()
+ formData.append('files', new Blob([fileBytes]), filename)
+
+ if (options.landscape) {
+ formData.append('landscape', 'true')
+ }
+
+ const headers: Record = {}
+ const authHeader = this.getAuthHeader()
+ if (authHeader) {
+ headers['Authorization'] = authHeader
+ }
+
+ const response = await fetch(`${baseUrl}/forms/libreoffice/convert`, {
+ method: 'POST',
+ headers,
+ body: formData,
+ signal: AbortSignal.timeout(60000),
+ })
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => '')
+ throw new Error(
+ `Gotenberg conversion failed with status ${response.status}: ${errorText || response.statusText}`,
+ )
+ }
+
+ const arrayBuffer = await response.arrayBuffer()
+ return Buffer.from(arrayBuffer)
+ }
+
+ async convertHtmlToPdf(filePath: string, filename: string): Promise {
+ const baseUrl = this.getUrl()
+ if (!baseUrl) {
+ throw new Error('Gotenberg URL is not configured.')
+ }
+
+ const fileBytes = fs.readFileSync(filePath)
+ const formData = new FormData()
+ const targetFilename =
+ filename.toLowerCase().endsWith('.html') || filename.toLowerCase().endsWith('.htm')
+ ? filename
+ : 'index.html'
+ formData.append('files', new Blob([fileBytes]), targetFilename)
+
+ const headers: Record = {}
+ const authHeader = this.getAuthHeader()
+ if (authHeader) {
+ headers['Authorization'] = authHeader
+ }
+
+ const response = await fetch(`${baseUrl}/forms/chromium/convert/html`, {
+ method: 'POST',
+ headers,
+ body: formData,
+ signal: AbortSignal.timeout(60000),
+ })
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => '')
+ throw new Error(
+ `Gotenberg HTML conversion failed with status ${response.status}: ${errorText || response.statusText}`,
+ )
+ }
+
+ const arrayBuffer = await response.arrayBuffer()
+ return Buffer.from(arrayBuffer)
+ }
+
+ async convertMarkdownToPdf(filePath: string, filename: string): Promise {
+ const baseUrl = this.getUrl()
+ if (!baseUrl) {
+ throw new Error('Gotenberg URL is not configured.')
+ }
+
+ const mdFilename = filename.toLowerCase().endsWith('.md') ? filename : 'file.md'
+
+ const htmlTemplate = `
+
+
+
+ PDF
+
+
+ {{ toHTML "${mdFilename}" }}
+
+`
+
+ const fileBytes = fs.readFileSync(filePath)
+ const formData = new FormData()
+ formData.append('files', new Blob([htmlTemplate], { type: 'text/html' }), 'index.html')
+ formData.append('files', new Blob([fileBytes]), mdFilename)
+
+ const headers: Record = {}
+ const authHeader = this.getAuthHeader()
+ if (authHeader) {
+ headers['Authorization'] = authHeader
+ }
+
+ const response = await fetch(`${baseUrl}/forms/chromium/convert/markdown`, {
+ method: 'POST',
+ headers,
+ body: formData,
+ signal: AbortSignal.timeout(60000),
+ })
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => '')
+ throw new Error(
+ `Gotenberg Markdown conversion failed with status ${response.status}: ${errorText || response.statusText}`,
+ )
+ }
+
+ const arrayBuffer = await response.arrayBuffer()
+ return Buffer.from(arrayBuffer)
+ }
+}
+
+export const gotenbergService = new GotenbergService()
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index ff79b57f..80f36f90 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -24,3 +24,4 @@ export * from './pagination'
export * from './chat/chat'
export * from './ai-usage/ai-usage'
export * from './watermark/watermark'
+export * from './gotenberg/gotenberg'
diff --git a/packages/core/src/upload/upload.test.ts b/packages/core/src/upload/upload.test.ts
index 659c3c54..a3426d14 100644
--- a/packages/core/src/upload/upload.test.ts
+++ b/packages/core/src/upload/upload.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { uploadService } from './upload'
+import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AssetStatus, AssetType, WorkflowTaskType } from '@shumai/db'
@@ -262,6 +263,132 @@ describe('UploadService', () => {
expect(workflowTask).toBeNull()
})
+ it('should confirm file upload and create transcode_pdf for office document when Gotenberg is available', async () => {
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const task = await prisma.task.create({
+ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
+ })
+ const asset = await prisma.asset.create({
+ data: {
+ name: 'document.docx',
+ type: AssetType.file,
+ project: { connect: { id: projectId } },
+ parent: { connect: { id: parentId } },
+ status: AssetStatus.uploading,
+ storageKey: {
+ connectOrCreate: {
+ where: { key: 'test-key' },
+ create: { key: 'test-key' },
+ },
+ },
+ mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ },
+ })
+
+ await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
+
+ const workflowTask = await prisma.workflowTask.findFirst({
+ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
+ })
+ expect(workflowTask).toBeDefined()
+ })
+
+ it('should mark asset processed without creating transcode_pdf for office document when Gotenberg is unavailable', async () => {
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
+ const task = await prisma.task.create({
+ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
+ })
+ const asset = await prisma.asset.create({
+ data: {
+ name: 'document.docx',
+ type: AssetType.file,
+ project: { connect: { id: projectId } },
+ parent: { connect: { id: parentId } },
+ status: AssetStatus.uploading,
+ storageKey: {
+ connectOrCreate: {
+ where: { key: 'test-key' },
+ create: { key: 'test-key' },
+ },
+ },
+ mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ },
+ })
+
+ await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
+
+ const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } })
+ expect(updatedAsset?.status).toBe(AssetStatus.processed)
+
+ const workflowTask = await prisma.workflowTask.findFirst({
+ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
+ })
+ expect(workflowTask).toBeNull()
+ })
+
+ it('should confirm file upload and create transcode_pdf for HTML document when Gotenberg is available', async () => {
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const task = await prisma.task.create({
+ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
+ })
+ const asset = await prisma.asset.create({
+ data: {
+ name: 'index.html',
+ type: AssetType.file,
+ project: { connect: { id: projectId } },
+ parent: { connect: { id: parentId } },
+ status: AssetStatus.uploading,
+ storageKey: {
+ connectOrCreate: {
+ where: { key: 'test-key-html-1' },
+ create: { key: 'test-key-html-1' },
+ },
+ },
+ mediaType: 'text/html',
+ },
+ })
+
+ await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
+
+ const workflowTask = await prisma.workflowTask.findFirst({
+ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
+ })
+ expect(workflowTask).toBeDefined()
+ })
+
+ it('should mark asset processed without creating transcode_pdf for HTML document when Gotenberg is unavailable', async () => {
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
+ const task = await prisma.task.create({
+ data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
+ })
+ const asset = await prisma.asset.create({
+ data: {
+ name: 'index.html',
+ type: AssetType.file,
+ project: { connect: { id: projectId } },
+ parent: { connect: { id: parentId } },
+ status: AssetStatus.uploading,
+ storageKey: {
+ connectOrCreate: {
+ where: { key: 'test-key-html-2' },
+ create: { key: 'test-key-html-2' },
+ },
+ },
+ mediaType: 'text/html',
+ },
+ })
+
+ await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
+
+ const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } })
+ expect(updatedAsset?.status).toBe(AssetStatus.processed)
+
+ const workflowTask = await prisma.workflowTask.findFirst({
+ where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
+ })
+ expect(workflowTask).toBeNull()
+ })
+
it('should confirm file upload and resolve empty mediaType using Bun resolver for audio', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
diff --git a/packages/core/src/upload/upload.ts b/packages/core/src/upload/upload.ts
index 9df9eb86..28f19906 100644
--- a/packages/core/src/upload/upload.ts
+++ b/packages/core/src/upload/upload.ts
@@ -13,8 +13,9 @@ import {
import { ImageTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { ulid } from 'ulid'
+import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
-import { getProxyType } from '@shumai/core/src/utils/mime'
+import { getProxyType, isHtmlDocument, isOfficeDocument } from '@shumai/core/src/utils/mime'
export class UploadService {
constructor(private readonly prismaClient: typeof prisma = prisma) {}
@@ -315,6 +316,20 @@ export class UploadService {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ImageTranscoder(tx as any, asset.id, team.id, projectId).withThumbnail().submit()
} else if (isPdf) {
+ const isOffice = isOfficeDocument(asset.mediaType, asset.name)
+ const isHtml = isHtmlDocument(asset.mediaType, asset.name)
+
+ if (isOffice || isHtml) {
+ const gotenbergAvailable = await gotenbergService.isAvailable()
+ if (!gotenbergAvailable) {
+ await tx.asset.update({
+ where: { id: asset.id },
+ data: { status: AssetStatus.processed },
+ })
+ return
+ }
+ }
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new PdfTranscoder(tx as any, asset.id, team.id, projectId)
.withSprite()
diff --git a/packages/core/src/utils/mime.test.ts b/packages/core/src/utils/mime.test.ts
index 1ca95d5a..674ae0e7 100644
--- a/packages/core/src/utils/mime.test.ts
+++ b/packages/core/src/utils/mime.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest'
-import { detectSupportedMimeType, getProxyType } from './mime'
+import {
+ detectSupportedMimeType,
+ getProxyType,
+ isOfficeDocument,
+ isHtmlDocument,
+ isMarkdownDocument,
+ isCsvDocument,
+} from './mime'
describe('detectSupportedMimeType', () => {
it('should detect JPEG', () => {
@@ -45,6 +52,38 @@ describe('detectSupportedMimeType', () => {
})
})
+describe('document helpers', () => {
+ it('isOfficeDocument should correctly identify office files', () => {
+ expect(isOfficeDocument('application/msword', 'letter.doc')).toBe(true)
+ expect(
+ isOfficeDocument(
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'file.docx',
+ ),
+ ).toBe(true)
+ expect(isOfficeDocument(null, 'sheet.xlsx')).toBe(true)
+ expect(isOfficeDocument(null, 'slides.pptx')).toBe(true)
+ expect(isOfficeDocument(null, 'notes.rtf')).toBe(true)
+ expect(isOfficeDocument('text/plain', 'notes.txt')).toBe(false)
+ })
+
+ it('isHtmlDocument should correctly identify html files', () => {
+ expect(isHtmlDocument('text/html', 'page.html')).toBe(true)
+ expect(isHtmlDocument(null, 'index.htm')).toBe(true)
+ expect(isHtmlDocument('text/plain', 'notes.txt')).toBe(false)
+ })
+
+ it('isMarkdownDocument should correctly identify markdown files', () => {
+ expect(isMarkdownDocument('text/markdown', 'README.md')).toBe(true)
+ expect(isMarkdownDocument(null, 'doc.markdown')).toBe(true)
+ })
+
+ it('isCsvDocument should correctly identify csv files', () => {
+ expect(isCsvDocument('text/csv', 'data.csv')).toBe(true)
+ expect(isCsvDocument(null, 'data.csv')).toBe(true)
+ })
+})
+
describe('getProxyType', () => {
it('should detect image proxyType', () => {
expect(getProxyType('image/png', 'test.png')).toBe('image')
@@ -61,21 +100,20 @@ describe('getProxyType', () => {
expect(getProxyType('audio/mpeg', 'song.mp3')).toBe('audio')
})
- it('should detect pdf proxyType only for pdf, csv, txt, and markdown files', () => {
+ it('should detect pdf proxyType for pdf, csv, txt, markdown, html, and office files', () => {
expect(getProxyType('application/pdf', 'doc.pdf')).toBe('pdf')
expect(getProxyType('text/plain', 'notes.txt')).toBe('pdf')
expect(getProxyType('text/csv', 'data.csv')).toBe('pdf')
expect(getProxyType('text/markdown', 'README.md')).toBe('pdf')
expect(getProxyType('text/x-markdown', 'doc.markdown')).toBe('pdf')
- expect(getProxyType(null, 'file.txt')).toBe('pdf')
- expect(getProxyType(null, 'README.md')).toBe('pdf')
- expect(getProxyType(null, 'doc.markdown')).toBe('pdf')
+ expect(getProxyType('text/html', 'index.html')).toBe('pdf')
+ expect(getProxyType('application/msword', 'letter.doc')).toBe('pdf')
+ expect(getProxyType(null, 'sheet.xlsx')).toBe('pdf')
+ expect(getProxyType(null, 'slides.pptx')).toBe('pdf')
})
- it('should return null for unsupported files including office files', () => {
+ it('should return null for unsupported files', () => {
expect(getProxyType('application/zip', 'archive.zip')).toBeNull()
- expect(getProxyType('application/msword', 'letter.doc')).toBeNull()
- expect(getProxyType(null, 'sheet.xlsx')).toBeNull()
expect(getProxyType(null, 'unknown.bin')).toBeNull()
})
})
diff --git a/packages/core/src/utils/mime.ts b/packages/core/src/utils/mime.ts
index 47b2d955..1120bf2f 100644
--- a/packages/core/src/utils/mime.ts
+++ b/packages/core/src/utils/mime.ts
@@ -1,5 +1,71 @@
export type ProxyType = 'image' | 'video' | 'audio' | 'pdf'
+export function isOfficeDocument(mediaType?: string | null, filename?: string | null): boolean {
+ const lowerMediaType = mediaType?.toLowerCase() || ''
+ const lowerFilename = filename?.toLowerCase() || ''
+
+ if (
+ lowerMediaType === 'application/msword' ||
+ lowerMediaType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
+ lowerMediaType === 'application/vnd.ms-excel' ||
+ lowerMediaType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
+ lowerMediaType === 'application/vnd.ms-powerpoint' ||
+ lowerMediaType ===
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ||
+ lowerMediaType === 'application/vnd.oasis.opendocument.text' ||
+ lowerMediaType === 'application/vnd.oasis.opendocument.spreadsheet' ||
+ lowerMediaType === 'application/vnd.oasis.opendocument.presentation' ||
+ lowerMediaType === 'application/rtf' ||
+ lowerMediaType === 'text/rtf'
+ ) {
+ return true
+ }
+
+ const officeExtensions = [
+ '.doc',
+ '.docx',
+ '.xls',
+ '.xlsx',
+ '.ppt',
+ '.pptx',
+ '.odt',
+ '.ods',
+ '.odp',
+ '.rtf',
+ ]
+ return officeExtensions.some((ext) => lowerFilename.endsWith(ext))
+}
+
+export function isHtmlDocument(mediaType?: string | null, filename?: string | null): boolean {
+ const lowerMediaType = mediaType?.toLowerCase() || ''
+ const lowerFilename = filename?.toLowerCase() || ''
+
+ return (
+ lowerMediaType === 'text/html' ||
+ lowerFilename.endsWith('.html') ||
+ lowerFilename.endsWith('.htm')
+ )
+}
+
+export function isMarkdownDocument(mediaType?: string | null, filename?: string | null): boolean {
+ const lowerMediaType = mediaType?.toLowerCase() || ''
+ const lowerFilename = filename?.toLowerCase() || ''
+
+ return (
+ lowerMediaType === 'text/markdown' ||
+ lowerMediaType === 'text/x-markdown' ||
+ lowerFilename.endsWith('.md') ||
+ lowerFilename.endsWith('.markdown')
+ )
+}
+
+export function isCsvDocument(mediaType?: string | null, filename?: string | null): boolean {
+ const lowerMediaType = mediaType?.toLowerCase() || ''
+ const lowerFilename = filename?.toLowerCase() || ''
+
+ return lowerMediaType === 'text/csv' || lowerFilename.endsWith('.csv')
+}
+
export function getProxyType(
mediaType?: string | null,
filename?: string | null,
@@ -14,14 +80,12 @@ export function getProxyType(
if (
lowerMediaType === 'application/pdf' ||
lowerMediaType === 'text/plain' ||
- lowerMediaType === 'text/csv' ||
- lowerMediaType === 'text/markdown' ||
- lowerMediaType === 'text/x-markdown' ||
lowerFilename.endsWith('.pdf') ||
lowerFilename.endsWith('.txt') ||
- lowerFilename.endsWith('.csv') ||
- lowerFilename.endsWith('.md') ||
- lowerFilename.endsWith('.markdown')
+ isCsvDocument(mediaType, filename) ||
+ isMarkdownDocument(mediaType, filename) ||
+ isHtmlDocument(mediaType, filename) ||
+ isOfficeDocument(mediaType, filename)
) {
return 'pdf'
}
diff --git a/packages/e2e/fixtures/test.docx b/packages/e2e/fixtures/test.docx
new file mode 100644
index 00000000..da545d1c
Binary files /dev/null and b/packages/e2e/fixtures/test.docx differ
diff --git a/packages/e2e/fixtures/test.pptx b/packages/e2e/fixtures/test.pptx
new file mode 100644
index 00000000..7578cd58
Binary files /dev/null and b/packages/e2e/fixtures/test.pptx differ
diff --git a/packages/e2e/fixtures/test.xlsx b/packages/e2e/fixtures/test.xlsx
new file mode 100644
index 00000000..677e9396
Binary files /dev/null and b/packages/e2e/fixtures/test.xlsx differ
diff --git a/packages/e2e/workflow/transcode-gotenberg.test.ts b/packages/e2e/workflow/transcode-gotenberg.test.ts
new file mode 100644
index 00000000..ed5fee5f
--- /dev/null
+++ b/packages/e2e/workflow/transcode-gotenberg.test.ts
@@ -0,0 +1,321 @@
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
+import { prisma, AssetStatus } from '@shumai/db'
+import { setupTestDbHooks } from '@shumai/db/test'
+import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
+import { initTranscodeWorkflows } from '@shumai/transcode'
+import { s3Service } from '@shumai/core/src/s3/s3'
+import { fileURLToPath } from 'url'
+import * as path from 'path'
+import * as fs from 'fs'
+import { GenericContainer, StartedTestContainer } from 'testcontainers'
+
+const currentDir = path.dirname(fileURLToPath(import.meta.url))
+const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
+const fixturesDir = path.resolve(currentDir, '../fixtures')
+
+describe.each(['local', 'temporal'] as const)(
+ 'Workflow E2E - Real Gotenberg Transcode (executor: %s)',
+ (mode) => {
+ setupTestDbHooks()
+
+ let transcodeWorkerPromise: Promise | null = null
+ let gotenbergContainer: StartedTestContainer | null = null
+
+ beforeAll(async () => {
+ process.env.S3_BUCKET = 'shumai-e2e-test-bucket-gotenberg'
+
+ console.log('Starting Gotenberg container via testcontainers...')
+ try {
+ gotenbergContainer = await new GenericContainer('gotenberg/gotenberg:8')
+ .withExposedPorts(3000)
+ .start()
+ const host = gotenbergContainer.getHost()
+ const port = gotenbergContainer.getMappedPort(3000)
+ process.env.GOTENBERG_URL = `http://${host}:${port}`
+ console.log(`Gotenberg container ready at ${process.env.GOTENBERG_URL}`)
+ } catch (err) {
+ console.error('Failed to start Gotenberg container:', err)
+ throw err
+ }
+
+ workflowService.setExecutorType(mode)
+ initTranscodeWorkflows()
+
+ if (mode === 'temporal') {
+ console.log('Starting background worker for transcode Temporal E2E tests...')
+ transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
+ workflowsPath: transcodeWorkflowsPath,
+ })
+ await new Promise((resolve) => setTimeout(resolve, 2000))
+ } else {
+ console.log('Starting local workflow service polling...')
+ workflowService.start()
+ }
+ }, 120000)
+
+ afterAll(async () => {
+ if (mode === 'temporal') {
+ console.log('Shutting down Temporal workers...')
+ await workflowService.shutdownWorkers()
+ await Promise.all([transcodeWorkerPromise].filter(Boolean))
+ }
+ workflowService.close()
+ vi.restoreAllMocks()
+
+ if (gotenbergContainer) {
+ console.log('Stopping Gotenberg container...')
+ await gotenbergContainer.stop()
+ }
+
+ try {
+ console.log('Cleaning up E2E storage files...')
+ await s3Service.deletePrefix('shumai-e2e-test-bucket-gotenberg', '')
+ } catch (err) {
+ console.error('Failed to clean up E2E storage folder:', err)
+ }
+ }, 120000)
+
+ it('should process real office Word document (.docx) transcode PDF task using Gotenberg', async () => {
+ const team = await prisma.team.create({
+ data: { name: 'E2E Gotenberg DOCX Team' },
+ })
+
+ const project = await prisma.project.create({
+ data: { name: 'E2E Gotenberg DOCX Project', teamId: team.id },
+ })
+
+ const storageKey = await prisma.storageKey.create({
+ data: {
+ key: 'projects/e2e/test.docx',
+ status: 'active',
+ },
+ })
+
+ const asset = await prisma.asset.create({
+ data: {
+ name: 'test.docx',
+ type: 'file',
+ status: 'uploaded',
+ mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ projectId: project.id,
+ storageKeyId: storageKey.id,
+ },
+ })
+
+ const docxPath = path.join(fixturesDir, 'test.docx')
+ const docxBuffer = fs.readFileSync(docxPath)
+ await s3Service.putObject(
+ 'shumai-e2e-test-bucket-gotenberg',
+ 'projects/e2e/test.docx',
+ docxBuffer,
+ docxBuffer.length,
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ )
+
+ const task = await prisma.workflowTask.create({
+ data: {
+ type: 'transcode_pdf',
+ status: 'pending',
+ assetId: asset.id,
+ projectId: project.id,
+ teamId: team.id,
+ payload: {
+ projectId: project.id,
+ transcode: {
+ poster: true,
+ sprite: true,
+ },
+ },
+ },
+ })
+
+ console.log(
+ `Submitted E2E Gotenberg DOCX Workflow Task. ID: ${task.id}. Awaiting completion...`,
+ )
+ const completedTask = await workflowService.executeWait(task, 60000)
+
+ expect(completedTask.status).toBe('completed')
+
+ const updatedAsset = await prisma.asset.findUnique({
+ where: { id: asset.id },
+ })
+ expect(updatedAsset?.status).toBe(AssetStatus.processed)
+
+ const mediaInfo = updatedAsset?.media as unknown as {
+ proxyType?: string
+ pdfTranscode?: { key: string }
+ poster?: { key: string }
+ sprite?: { key: string }
+ frames?: number
+ }
+ expect(mediaInfo).toBeDefined()
+ expect(mediaInfo.proxyType).toBe('pdf')
+ expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(mediaInfo.poster?.key).toContain('poster.webp')
+ expect(mediaInfo.sprite?.key).toContain('sprite.webp')
+ expect(mediaInfo.frames).toBeGreaterThan(0)
+ }, 90000)
+
+ it('should process real office PowerPoint presentation (.pptx) transcode PDF task using Gotenberg', async () => {
+ const team = await prisma.team.create({
+ data: { name: 'E2E Gotenberg PPTX Team' },
+ })
+
+ const project = await prisma.project.create({
+ data: { name: 'E2E Gotenberg PPTX Project', teamId: team.id },
+ })
+
+ const storageKey = await prisma.storageKey.create({
+ data: {
+ key: 'projects/e2e/test.pptx',
+ status: 'active',
+ },
+ })
+
+ const asset = await prisma.asset.create({
+ data: {
+ name: 'test.pptx',
+ type: 'file',
+ status: 'uploaded',
+ mediaType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ projectId: project.id,
+ storageKeyId: storageKey.id,
+ },
+ })
+
+ const pptxPath = path.join(fixturesDir, 'test.pptx')
+ const pptxBuffer = fs.readFileSync(pptxPath)
+ await s3Service.putObject(
+ 'shumai-e2e-test-bucket-gotenberg',
+ 'projects/e2e/test.pptx',
+ pptxBuffer,
+ pptxBuffer.length,
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ )
+
+ const task = await prisma.workflowTask.create({
+ data: {
+ type: 'transcode_pdf',
+ status: 'pending',
+ assetId: asset.id,
+ projectId: project.id,
+ teamId: team.id,
+ payload: {
+ projectId: project.id,
+ transcode: {
+ poster: true,
+ sprite: true,
+ },
+ },
+ },
+ })
+
+ console.log(
+ `Submitted E2E Gotenberg PPTX Workflow Task. ID: ${task.id}. Awaiting completion...`,
+ )
+ const completedTask = await workflowService.executeWait(task, 60000)
+
+ expect(completedTask.status).toBe('completed')
+
+ const updatedAsset = await prisma.asset.findUnique({
+ where: { id: asset.id },
+ })
+ expect(updatedAsset?.status).toBe(AssetStatus.processed)
+
+ const mediaInfo = updatedAsset?.media as unknown as {
+ proxyType?: string
+ pdfTranscode?: { key: string }
+ poster?: { key: string }
+ sprite?: { key: string }
+ frames?: number
+ }
+ expect(mediaInfo).toBeDefined()
+ expect(mediaInfo.proxyType).toBe('pdf')
+ expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(mediaInfo.poster?.key).toContain('poster.webp')
+ expect(mediaInfo.sprite?.key).toContain('sprite.webp')
+ expect(mediaInfo.frames).toBeGreaterThan(0)
+ }, 90000)
+
+ it('should process real office Excel spreadsheet (.xlsx) transcode PDF task using Gotenberg', async () => {
+ const team = await prisma.team.create({
+ data: { name: 'E2E Gotenberg XLSX Team' },
+ })
+
+ const project = await prisma.project.create({
+ data: { name: 'E2E Gotenberg XLSX Project', teamId: team.id },
+ })
+
+ const storageKey = await prisma.storageKey.create({
+ data: {
+ key: 'projects/e2e/test.xlsx',
+ status: 'active',
+ },
+ })
+
+ const asset = await prisma.asset.create({
+ data: {
+ name: 'test.xlsx',
+ type: 'file',
+ status: 'uploaded',
+ mediaType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ projectId: project.id,
+ storageKeyId: storageKey.id,
+ },
+ })
+
+ const xlsxPath = path.join(fixturesDir, 'test.xlsx')
+ const xlsxBuffer = fs.readFileSync(xlsxPath)
+ await s3Service.putObject(
+ 'shumai-e2e-test-bucket-gotenberg',
+ 'projects/e2e/test.xlsx',
+ xlsxBuffer,
+ xlsxBuffer.length,
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ )
+
+ const task = await prisma.workflowTask.create({
+ data: {
+ type: 'transcode_pdf',
+ status: 'pending',
+ assetId: asset.id,
+ projectId: project.id,
+ teamId: team.id,
+ payload: {
+ projectId: project.id,
+ transcode: {
+ poster: true,
+ sprite: true,
+ },
+ },
+ },
+ })
+
+ console.log(
+ `Submitted E2E Gotenberg XLSX Workflow Task. ID: ${task.id}. Awaiting completion...`,
+ )
+ const completedTask = await workflowService.executeWait(task, 60000)
+
+ expect(completedTask.status).toBe('completed')
+
+ const updatedAsset = await prisma.asset.findUnique({
+ where: { id: asset.id },
+ })
+ expect(updatedAsset?.status).toBe(AssetStatus.processed)
+
+ const mediaInfo = updatedAsset?.media as unknown as {
+ proxyType?: string
+ pdfTranscode?: { key: string }
+ poster?: { key: string }
+ sprite?: { key: string }
+ frames?: number
+ }
+ expect(mediaInfo).toBeDefined()
+ expect(mediaInfo.proxyType).toBe('pdf')
+ expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(mediaInfo.poster?.key).toContain('poster.webp')
+ expect(mediaInfo.sprite?.key).toContain('sprite.webp')
+ expect(mediaInfo.frames).toBeGreaterThan(0)
+ }, 90000)
+ },
+)
diff --git a/packages/transcode/src/activities/transcode.test.ts b/packages/transcode/src/activities/transcode.test.ts
index e2c36bb3..9f643c0b 100644
--- a/packages/transcode/src/activities/transcode.test.ts
+++ b/packages/transcode/src/activities/transcode.test.ts
@@ -3,6 +3,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import * as child_process from 'child_process'
@@ -37,39 +38,43 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
},
}))
-vi.mock('@shumai/core/src/transcode/transcode', () => ({
- transcodeService: {
- getVideoInfo: vi.fn(),
- getAudioInfo: vi.fn(),
- getImageInfo: vi.fn(),
- getPdfInfo: vi.fn().mockResolvedValue({
- originalWidth: 800,
- originalHeight: 1000,
- duration: 0,
- bitRate: 0,
- frameRate: 0,
- totalFrames: 10,
- hasAudio: false,
- mimeType: 'application/pdf',
- }),
- transcodeVideo: vi.fn(),
- transcodeAudio: vi.fn(),
- transcodeImage: vi.fn(),
- generateSprite: vi.fn(),
- generatePdfSprite: vi.fn().mockResolvedValue({
- pageCount: 10,
- originalWidth: 800,
- originalHeight: 1000,
- }),
- generatePdfFromText: vi.fn(),
- generatePdfFromCsv: vi.fn(),
- createTempDir: vi.fn().mockReturnValue('/tmp'),
- removeDir: vi.fn(),
- takeScreenshots: vi.fn(),
- overlayAnnotations: vi.fn(),
- renderPdfPages: vi.fn(),
- },
-}))
+vi.mock('@shumai/core/src/transcode/transcode', async (importOriginal) => {
+ const actual = await importOriginal()
+ return {
+ ...actual,
+ transcodeService: {
+ getVideoInfo: vi.fn(),
+ getAudioInfo: vi.fn(),
+ getImageInfo: vi.fn(),
+ getPdfInfo: vi.fn().mockResolvedValue({
+ originalWidth: 800,
+ originalHeight: 1000,
+ duration: 0,
+ bitRate: 0,
+ frameRate: 0,
+ totalFrames: 10,
+ hasAudio: false,
+ mimeType: 'application/pdf',
+ }),
+ transcodeVideo: vi.fn(),
+ transcodeAudio: vi.fn(),
+ transcodeImage: vi.fn(),
+ generateSprite: vi.fn(),
+ generatePdfSprite: vi.fn().mockResolvedValue({
+ pageCount: 10,
+ originalWidth: 800,
+ originalHeight: 1000,
+ }),
+ generatePdfFromText: vi.fn(),
+ generatePdfFromCsv: vi.fn(),
+ createTempDir: vi.fn().mockReturnValue('/tmp'),
+ removeDir: vi.fn(),
+ takeScreenshots: vi.fn(),
+ overlayAnnotations: vi.fn(),
+ renderPdfPages: vi.fn(),
+ },
+ }
+})
vi.mock('@shumai/core/src/metadata/metadata', () => ({
metadataService: {
@@ -92,8 +97,70 @@ vi.mock('fs', async (importOriginal) => {
describe('Transcode Activities', () => {
setupTestDbHooks()
- beforeEach(() => {
+ beforeEach(async () => {
vi.clearAllMocks()
+ const fs = await import('fs')
+ vi.mocked(fs.readFileSync).mockImplementation(() => Buffer.from('fake data') as never)
+ })
+
+ it('should convert CSV via Gotenberg in landscape mode when maxCols > 5', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'wide.csv', type: 'file', status: 'uploaded' },
+ })
+
+ const fs = await import('fs')
+ vi.mocked(fs.readFileSync).mockImplementation((_path: unknown, options?: unknown) => {
+ if (options) {
+ return 'c1,c2,c3,c4,c5,c6,c7\n1,2,3,4,5,6,7' as never
+ }
+ return Buffer.from('fake data') as never
+ })
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const convertSpy = vi
+ .spyOn(gotenbergService, 'convertDocumentToPdf')
+ .mockResolvedValue(Buffer.from('fake pdf landscape csv'))
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/wide.csv',
+ filePath: '/tmp/wide.csv',
+ mediaType: 'text/csv',
+ filename: 'wide.csv',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(convertSpy).toHaveBeenCalledWith('/tmp/wide.csv', 'wide.csv', { landscape: true })
+ vi.mocked(fs.readFileSync).mockImplementation(() => Buffer.from('fake data') as never)
+ })
+
+ it('should convert CSV via Gotenberg in portrait mode when maxCols <= 5', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'narrow.csv', type: 'file', status: 'uploaded' },
+ })
+
+ const fs = await import('fs')
+ vi.mocked(fs.readFileSync).mockImplementation((_path: unknown, options?: unknown) => {
+ if (options) {
+ return 'c1,c2,c3\n1,2,3' as never
+ }
+ return Buffer.from('fake data') as never
+ })
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const convertSpy = vi
+ .spyOn(gotenbergService, 'convertDocumentToPdf')
+ .mockResolvedValue(Buffer.from('fake pdf portrait csv'))
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/narrow.csv',
+ filePath: '/tmp/narrow.csv',
+ mediaType: 'text/csv',
+ filename: 'narrow.csv',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(convertSpy).toHaveBeenCalledWith('/tmp/narrow.csv', 'narrow.csv', { landscape: false })
+ vi.mocked(fs.readFileSync).mockImplementation(() => Buffer.from('fake data') as never)
})
it('should call getVideoInfo and set file_type to video', async () => {
@@ -245,6 +312,7 @@ describe('Transcode Activities', () => {
data: { name: 'test.txt', type: 'file', status: 'uploaded' },
})
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
const generatePdfFromTextSpy = vi
.spyOn(transcodeService, 'generatePdfFromText')
.mockImplementation(async (_inPath, outPath) => {
@@ -270,6 +338,7 @@ describe('Transcode Activities', () => {
data: { name: 'README.md', type: 'file', status: 'uploaded' },
})
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
const generatePdfFromTextSpy = vi
.spyOn(transcodeService, 'generatePdfFromText')
.mockImplementation(async (_inPath, outPath) => {
@@ -293,6 +362,188 @@ describe('Transcode Activities', () => {
generatePdfFromTextSpy.mockRestore()
})
+ it('should convert markdown document via Gotenberg Chromium in generatePdfProxyActivity when available', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'README.md', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const convertMdSpy = vi
+ .spyOn(gotenbergService, 'convertMarkdownToPdf')
+ .mockResolvedValue(Buffer.from('fake pdf from gotenberg markdown'))
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/README.md',
+ filePath: '/tmp/README.md',
+ mediaType: 'text/markdown',
+ filename: 'README.md',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(convertMdSpy).toHaveBeenCalledWith('/tmp/README.md', 'README.md')
+ })
+
+ it('should convert office document via Gotenberg in generatePdfProxyActivity when available', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'document.docx', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const convertSpy = vi
+ .spyOn(gotenbergService, 'convertDocumentToPdf')
+ .mockResolvedValue(Buffer.from('fake pdf from gotenberg office'))
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/document.docx',
+ filePath: '/tmp/document.docx',
+ mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ filename: 'document.docx',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(convertSpy).toHaveBeenCalledWith('/tmp/document.docx', 'document.docx')
+ })
+
+ it('should convert html document via Gotenberg Chromium in generatePdfProxyActivity when available', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'index.html', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const convertHtmlSpy = vi
+ .spyOn(gotenbergService, 'convertHtmlToPdf')
+ .mockResolvedValue(Buffer.from('fake pdf from gotenberg html'))
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/index.html',
+ filePath: '/tmp/index.html',
+ mediaType: 'text/html',
+ filename: 'index.html',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(convertHtmlSpy).toHaveBeenCalledWith('/tmp/index.html', 'index.html')
+ })
+
+ it('should throw ApplicationFailure when Office document conversion is attempted but Gotenberg is unavailable', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'sheet.xlsx', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
+
+ await expect(
+ generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/sheet.xlsx',
+ filePath: '/tmp/sheet.xlsx',
+ mediaType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ filename: 'sheet.xlsx',
+ }),
+ ).rejects.toThrow('Gotenberg service is required for Office document conversion')
+ })
+
+ it('should throw ApplicationFailure when HTML document conversion is attempted but Gotenberg is unavailable', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'index.html', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
+
+ await expect(
+ generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/index.html',
+ filePath: '/tmp/index.html',
+ mediaType: 'text/html',
+ filename: 'index.html',
+ }),
+ ).rejects.toThrow('Gotenberg service is required for HTML document conversion')
+ })
+
+ it('should fallback to transcodeService.generatePdfFromCsv for CSV when Gotenberg is unavailable', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'data.csv', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
+ const generatePdfFromCsvSpy = vi
+ .spyOn(transcodeService, 'generatePdfFromCsv')
+ .mockImplementation(async (_inPath, outPath) => {
+ const fs = await import('fs')
+ fs.writeFileSync(outPath, 'fake pdf from csv fallback')
+ })
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/data.csv',
+ filePath: '/tmp/data.csv',
+ mediaType: 'text/csv',
+ filename: 'data.csv',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(generatePdfFromCsvSpy).toHaveBeenCalledWith(
+ '/tmp/data.csv',
+ expect.stringContaining('proxy.pdf'),
+ )
+ generatePdfFromCsvSpy.mockRestore()
+ })
+
+ it('should convert TXT document via Gotenberg when available', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'notes.txt', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(true)
+ const convertSpy = vi
+ .spyOn(gotenbergService, 'convertDocumentToPdf')
+ .mockResolvedValue(Buffer.from('fake pdf from txt gotenberg'))
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/notes.txt',
+ filePath: '/tmp/notes.txt',
+ mediaType: 'text/plain',
+ filename: 'notes.txt',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(convertSpy).toHaveBeenCalledWith('/tmp/notes.txt', 'notes.txt')
+ })
+
+ it('should fallback to transcodeService.generatePdfFromText for TXT when Gotenberg is unavailable', async () => {
+ const asset = await prisma.asset.create({
+ data: { name: 'notes.txt', type: 'file', status: 'uploaded' },
+ })
+
+ vi.spyOn(gotenbergService, 'isAvailable').mockResolvedValue(false)
+ const generatePdfFromTextSpy = vi
+ .spyOn(transcodeService, 'generatePdfFromText')
+ .mockImplementation(async (_inPath, outPath) => {
+ const fs = await import('fs')
+ fs.writeFileSync(outPath, 'fake pdf from txt fallback')
+ })
+
+ const res = await generatePdfProxyActivity({
+ assetId: asset.id,
+ assetKey: 'files/asset1/notes.txt',
+ filePath: '/tmp/notes.txt',
+ mediaType: 'text/plain',
+ filename: 'notes.txt',
+ })
+
+ expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
+ expect(generatePdfFromTextSpy).toHaveBeenCalledWith(
+ '/tmp/notes.txt',
+ expect.stringContaining('proxy.pdf'),
+ )
+ generatePdfFromTextSpy.mockRestore()
+ })
+
it('should set file_type to file for unknown types', async () => {
const asset = await prisma.asset.create({
data: { name: 'u.xyz', type: 'file', status: 'uploaded' },
diff --git a/packages/transcode/src/activities/transcode.ts b/packages/transcode/src/activities/transcode.ts
index df73ad23..f5ac3113 100644
--- a/packages/transcode/src/activities/transcode.ts
+++ b/packages/transcode/src/activities/transcode.ts
@@ -3,7 +3,15 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { stemFromKey } from '@shumai/core/src/utils/filename'
-import { getProxyType } from '@shumai/core/src/utils/mime'
+import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
+import { parseCsvContent } from '@shumai/core/src/transcode/transcode'
+import {
+ getProxyType,
+ isCsvDocument,
+ isHtmlDocument,
+ isMarkdownDocument,
+ isOfficeDocument,
+} from '@shumai/core/src/utils/mime'
import { ApplicationFailure } from '@temporalio/activity'
import * as path from 'path'
import * as fs from 'fs'
@@ -511,16 +519,13 @@ export interface GeneratePdfProxyActivityParams {
export async function generatePdfProxyActivity(
params: GeneratePdfProxyActivityParams,
): Promise<{ pdfProxyKey: string; pdfFilePath: string }> {
- const isTxt =
- params.mediaType === 'text/plain' ||
- params.mediaType === 'text/markdown' ||
- params.mediaType === 'text/x-markdown' ||
- params.filename.toLowerCase().endsWith('.txt') ||
- params.filename.toLowerCase().endsWith('.md') ||
- params.filename.toLowerCase().endsWith('.markdown')
- const isCsv = params.mediaType === 'text/csv' || params.filename.toLowerCase().endsWith('.csv')
+ const isOffice = isOfficeDocument(params.mediaType, params.filename)
+ const isHtml = isHtmlDocument(params.mediaType, params.filename)
+ const isMd = isMarkdownDocument(params.mediaType, params.filename)
+ const isCsv = isCsvDocument(params.mediaType, params.filename)
+ const isTxt = params.mediaType === 'text/plain' || params.filename.toLowerCase().endsWith('.txt')
- if (!isTxt && !isCsv) {
+ if (!isOffice && !isHtml && !isMd && !isCsv && !isTxt) {
return { pdfProxyKey: params.assetKey, pdfFilePath: params.filePath }
}
@@ -530,10 +535,67 @@ export async function generatePdfProxyActivity(
const pdfFilePath = path.join(tmpDir, 'proxy.pdf')
try {
- if (isCsv) {
- await transcodeService.generatePdfFromCsv(params.filePath, pdfFilePath)
- } else {
- await transcodeService.generatePdfFromText(params.filePath, pdfFilePath)
+ const gotenbergAvailable = await gotenbergService.isAvailable()
+
+ if (isOffice) {
+ if (!gotenbergAvailable) {
+ throw new Error(
+ 'Gotenberg service is required for Office document conversion but is unavailable.',
+ )
+ }
+ const pdfBuffer = await gotenbergService.convertDocumentToPdf(
+ params.filePath,
+ params.filename,
+ )
+ fs.writeFileSync(pdfFilePath, pdfBuffer)
+ } else if (isHtml) {
+ if (!gotenbergAvailable) {
+ throw new Error(
+ 'Gotenberg service is required for HTML document conversion but is unavailable.',
+ )
+ }
+ const pdfBuffer = await gotenbergService.convertHtmlToPdf(params.filePath, params.filename)
+ fs.writeFileSync(pdfFilePath, pdfBuffer)
+ } else if (isCsv) {
+ if (gotenbergAvailable) {
+ let isLandscape = false
+ try {
+ const content = String(fs.readFileSync(params.filePath, 'utf-8'))
+ const rows = parseCsvContent(content)
+ const maxCols = Math.max(...rows.map((r) => r.length), 0)
+ isLandscape = maxCols > 5
+ } catch {
+ // Fallback landscape calculation
+ }
+ const pdfBuffer = await gotenbergService.convertDocumentToPdf(
+ params.filePath,
+ params.filename,
+ { landscape: isLandscape },
+ )
+ fs.writeFileSync(pdfFilePath, pdfBuffer)
+ } else {
+ await transcodeService.generatePdfFromCsv(params.filePath, pdfFilePath)
+ }
+ } else if (isMd) {
+ if (gotenbergAvailable) {
+ const pdfBuffer = await gotenbergService.convertMarkdownToPdf(
+ params.filePath,
+ params.filename,
+ )
+ fs.writeFileSync(pdfFilePath, pdfBuffer)
+ } else {
+ await transcodeService.generatePdfFromText(params.filePath, pdfFilePath)
+ }
+ } else if (isTxt) {
+ if (gotenbergAvailable) {
+ const pdfBuffer = await gotenbergService.convertDocumentToPdf(
+ params.filePath,
+ params.filename,
+ )
+ fs.writeFileSync(pdfFilePath, pdfBuffer)
+ } else {
+ await transcodeService.generatePdfFromText(params.filePath, pdfFilePath)
+ }
}
const stat = fs.statSync(pdfFilePath)
@@ -544,7 +606,7 @@ export async function generatePdfProxyActivity(
} catch (err) {
const { message } = getErrorDetails(err)
throw ApplicationFailure.create({
- message: `Failed to generate PDF proxy for text/csv/markdown: ${message}`,
+ message: `Failed to generate PDF proxy: ${message}`,
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})