From aa6d5ed6264f8c405a5043836476c1f1592a3f44 Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Sun, 9 Aug 2026 14:44:13 +0800 Subject: [PATCH] feat(transcode): add Gotenberg support for Office, HTML, CSV, and Markdown PDF proxies (#283) * feat(transcode): add Gotenberg support for Office, HTML, CSV, and Markdown PDF proxies * fix(transcode): use Gotenberg chromium markdown endpoint with index.html wrapper for markdown conversion * test(transcode): add complete unit test coverage for HTML, CSV landscape/portrait, TXT, and Gotenberg fallback branches * fix(gotenberg): force .md extension for Gotenberg markdown conversion endpoint compatibility * refactor(gotenberg): standardize basic auth environment variables on GOTENBERG_BASIC_AUTH_USERNAME and GOTENBERG_BASIC_AUTH_PASSWORD * test(e2e): add real Gotenberg testcontainers workflow E2E test for docx, pptx, and xlsx * docs: add Gotenberg document PDF conversion documentation and update features in README * docs(gotenberg): add Docker quickstart commands and remove obsolete GOTENBERG_USERNAME note --- README.md | 1 + README_CN.md | 1 + docs/docs.json | 1 + docs/using-shumai/gotenberg.mdx | 103 ++++++ packages/core/src/gotenberg/gotenberg.test.ts | 219 ++++++++++++ packages/core/src/gotenberg/gotenberg.ts | 178 ++++++++++ packages/core/src/index.ts | 1 + packages/core/src/upload/upload.test.ts | 127 +++++++ packages/core/src/upload/upload.ts | 17 +- packages/core/src/utils/mime.test.ts | 54 ++- packages/core/src/utils/mime.ts | 76 ++++- packages/e2e/fixtures/test.docx | Bin 0 -> 6521 bytes packages/e2e/fixtures/test.pptx | Bin 0 -> 32127 bytes packages/e2e/fixtures/test.xlsx | Bin 0 -> 5067 bytes .../e2e/workflow/transcode-gotenberg.test.ts | 321 ++++++++++++++++++ .../src/activities/transcode.test.ts | 319 +++++++++++++++-- .../transcode/src/activities/transcode.ts | 92 ++++- 17 files changed, 1446 insertions(+), 64 deletions(-) create mode 100644 docs/using-shumai/gotenberg.mdx create mode 100644 packages/core/src/gotenberg/gotenberg.test.ts create mode 100644 packages/core/src/gotenberg/gotenberg.ts create mode 100644 packages/e2e/fixtures/test.docx create mode 100644 packages/e2e/fixtures/test.pptx create mode 100644 packages/e2e/fixtures/test.xlsx create mode 100644 packages/e2e/workflow/transcode-gotenberg.test.ts 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 0000000000000000000000000000000000000000..da545d1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^L7Sp;jws4A8$k*+m!43dcHicHQP5dScPt!A(U7H&>@9Vne*+uo4328rk-+&mqoI#aG#gc-fTL9sV9f1Hey zqML6`+se8-t}_MKv{lr($%J%D-;m48EXh-Vxbf%1&u@t)-br zOw2}ycB4;hEhut6VQ5o0Cja@qA2+ zkjzZ9BkuKH{_HZUn7D+9FluLMf$AGPMf6%PLN0kuXNloHLcH5H=-%D~iCRJg%3G@bCCikx|O&u%QF0D%^0k3QDf#{{dU|pG*?`=P5IlKr$JL{EL z;Ps83JkE`tTFY)im<{mTr1en!Ze^i1t97AN7Q#-lFsYLHV;cUlN2)!Kk$PI_jju0Mr#jkq&&oUpVD*A_8s_3&;7isxG zRrICqAeeB8%QL^v+oJ36K{V&2PHEnrBx39MlJUykm)fX3+p&#+VDe1I}j@ty%?Ga1TxE}A*m zc7xTRqAm@Dn~eEL*@g&~%i{!@-b#u~(ibZ=UoFL|z=`_cd4el7(o#u$(wiC-Z0m2gf!5m7uEs(s+H zH}AP!A&v~QvJ5|3P$Buu{;S6?4L+Y3t3WE`<&qJ(iha<<@Ke;0;{q2~HnSJ5hM5d*J@4(cdy?cacG*ZEh3Ap}q$h zgy@Zs&0V;^6HTGN2ksA|ztwT>B7>?#+$LJca1SyF(Hl*OyKsLe`jh1zxIc*g7Mi$= z44Qa+nuA_Z_mzOg4AcGKPx`|1QGQ17**pfM)5sZJ{00}V>`rXTt5Q>|3J2k%d+fA5_@7nE*){q1TX(EltV-B1Nt zKDx^kbm`=FH)^YQ4;%rfBby0iAKWeS4SDuiI};G~T@()a|`J9PKsv{dCYts=ElF z&fe`&o}c+IgkRNgud{p?4Ah;v_78uTVT)Vd;@ulT2kqD1*6&hpd9Uv!FZBTW`XUP8 N&ouB+;nvq@{|}GOFn9m} literal 0 HcmV?d00001 diff --git a/packages/e2e/fixtures/test.xlsx b/packages/e2e/fixtures/test.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..677e93963ffa0564c724ae3ac11c103bbcb3dc2c GIT binary patch liter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`8zGADJdj?Dq+=d*flLGj|)aFH@&Hfs03v^YhKd*+Cuq zX5&};r}rFS(63(3j(ER%0b%|Z { + 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, })