#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Fix Convert batch routing, ebook settings and email recipients (#8766)
Anthony Stirling12fe2fa01e85
diff --git a/app/common/src/main/java/stirling/software/common/util/EmlProcessingUtils.java b/app/common/src/main/java/stirling/software/common/util/EmlProcessingUtils.javaindex 25af604c8c..d72d9ed352 100644--- a/app/common/src/main/java/stirling/software/common/util/EmlProcessingUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/EmlProcessingUtils.java@@ -170,7 +170,9 @@ public class EmlProcessingUtils {sanitizeText(content.getFrom(), customHtmlSanitizer),sanitizeText(content.getTo(), customHtmlSanitizer)));- if (content.getCc() != null && !content.getCc().trim().isEmpty()) {+ if ((request == null || request.isIncludeAllRecipients())+ && content.getCc() != null+ && !content.getCc().trim().isEmpty()) {html.append(String.format(Locale.ROOT,@@ -178,7 +180,9 @@ public class EmlProcessingUtils {sanitizeText(content.getCc(), customHtmlSanitizer)));}- if (content.getBcc() != null && !content.getBcc().trim().isEmpty()) {+ if ((request == null || request.isIncludeAllRecipients())+ && content.getBcc() != null+ && !content.getBcc().trim().isEmpty()) {html.append(String.format(Locale.ROOT,diff --git a/app/common/src/test/java/stirling/software/common/util/EmlRecipientFixturesTest.java b/app/common/src/test/java/stirling/software/common/util/EmlRecipientFixturesTest.javanew file mode 100644index 0000000000..a78414bfcd--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/util/EmlRecipientFixturesTest.java@@ -0,0 +1,106 @@+package stirling.software.common.util;++import static org.assertj.core.api.Assertions.assertThat;++import java.io.IOException;+import java.util.stream.Stream;++import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.Arguments;+import org.junit.jupiter.params.provider.MethodSource;++import stirling.software.common.model.api.converters.EmlToPdfRequest;++class EmlRecipientFixturesTest {++ @ParameterizedTest(name = "{0}: includeAllRecipients={1}")+ @MethodSource("recipientChoices")+ void respectsRecipientChoiceFromEmailFile(String fixture, boolean includeAllRecipients)+ throws IOException {+ var request = new EmlToPdfRequest();+ request.setIncludeAllRecipients(includeAllRecipients);++ String html = convertFixture(fixture, request);++ assertMessageContentPreserved(html);+ if (includeAllRecipients) {+ assertCopyRecipientsPresent(html);+ } else {+ assertThat(html)+ .doesNotContain(+ "<strong>CC:</strong>",+ "<strong>BCC:</strong>",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "René Copy",+ "Second Copy",+ "Søren Blind");+ }+ }++ @ParameterizedTest+ @MethodSource("recipientFixtures")+ void includesCopyRecipientsByDefault(String fixture) throws IOException {+ String html = convertFixture(fixture, new EmlToPdfRequest());++ assertMessageContentPreserved(html);+ assertCopyRecipientsPresent(html);+ }++ @ParameterizedTest+ @MethodSource("recipientFixtures")+ void includesCopyRecipientsWithoutRequestOptions(String fixture) throws IOException {+ String html = convertFixture(fixture, null);++ assertMessageContentPreserved(html);+ assertCopyRecipientsPresent(html);+ }++ private static Stream<String> recipientFixtures() {+ return Stream.of("recipients.eml", "recipients-unicode.msg", "recipients-ansi.msg");+ }++ private static Stream<Arguments> recipientChoices() {+ return recipientFixtures()+ .flatMap(+ fixture ->+ Stream.of(+ Arguments.of(fixture, false), Arguments.of(fixture, true)));+ }++ private static String convertFixture(String fixture, EmlToPdfRequest request)+ throws IOException {+ try (var input =+ EmlRecipientFixturesTest.class.getResourceAsStream("/eml/recipients/" + fixture)) {+ assertThat(input).as("email fixture %s", fixture).isNotNull();+ return EmlToPdf.convertEmlToHtml(input.readAllBytes(), request);+ }+ }++ private static void assertMessageContentPreserved(String html) {+ assertThat(html)+ .contains(+ "<strong>From:</strong>",+ "<strong>To:</strong>",+ "[email protected]",+ "[email protected]",+ "Élodie Sender",+ "Zoë Primary",+ "Recipient options café",+ "Fixture email body with café.");+ }++ private static void assertCopyRecipientsPresent(String html) {+ assertThat(html)+ .contains(+ "<strong>CC:</strong>",+ "<strong>BCC:</strong>",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "René Copy",+ "Second Copy",+ "Søren Blind");+ }+}diff --git a/app/common/src/test/java/stirling/software/common/util/EmlRecipientOptionsTest.java b/app/common/src/test/java/stirling/software/common/util/EmlRecipientOptionsTest.javanew file mode 100644index 0000000000..9824797afb--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/util/EmlRecipientOptionsTest.java@@ -0,0 +1,40 @@+package stirling.software.common.util;++import static org.assertj.core.api.Assertions.assertThat;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import stirling.software.common.model.api.converters.EmlToPdfRequest;+import stirling.software.common.util.EmlParser.EmailContent;++class EmlRecipientOptionsTest {+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void respectsRecipientChoice(boolean includeAllRecipients) {+ var request = new EmlToPdfRequest();+ request.setIncludeAllRecipients(includeAllRecipients);+ String html = EmlProcessingUtils.generateEnhancedEmailHtml(email(), request, null);+ assertThat(html).contains("[email protected]", "[email protected]", "Email body");+ assertThat(html.contains("[email protected]")).isEqualTo(includeAllRecipients);+ assertThat(html.contains("[email protected]")).isEqualTo(includeAllRecipients);+ }++ @Test+ void retainsRecipientsWithoutRequestOptions() {+ String html = EmlProcessingUtils.generateEnhancedEmailHtml(email(), null, null);+ assertThat(html).contains("[email protected]", "[email protected]");+ }++ private static EmailContent email() {+ var content = new EmailContent();+ content.setSubject("Subject");+ content.setFrom("[email protected]");+ content.setTo("[email protected]");+ content.setCc("[email protected]");+ content.setBcc("[email protected]");+ content.setTextBody("Email body");+ return content;+ }+}diff --git a/app/common/src/test/resources/eml/recipients/README.md b/app/common/src/test/resources/eml/recipients/README.mdnew file mode 100644index 0000000000..7bb15b447b--- /dev/null+++ b/app/common/src/test/resources/eml/recipients/README.md@@ -0,0 +1,19 @@+# Email recipient fixtures++These synthetic messages contain the same sender, To recipient, two CC recipients,+one BCC recipient, subject and body. All addresses use `example.com`; there is no+personal email data.++- `recipients.eml`: UTF-8 text with MIME-encoded display names and a folded CC header.+- `recipients-unicode.msg`: Outlook compound-file message with UTF-16LE MAPI strings.+- `recipients-ansi.msg`: Outlook compound-file message with Windows-1252 MAPI strings.++The MSG fixtures were constructed with Apache POI's `POIFSFileSystem`. Recipients+are stored in MAPI recipient directories with explicit To/CC/BCC types, including+multiple CC entries. They have no transport headers, so recipient parsing must+read the MSG recipient data. Accented names, subject and body exercise decoding+in both MSG string formats.++`EmlRecipientFixturesTest` reads these files through the real EML/MSG parser and+HTML generator. It checks recipient inclusion, exclusion and defaults while+preserving From, To, subject and body. No PDF renderer or network is required.diff --git a/app/common/src/test/resources/eml/recipients/recipients-ansi.msg b/app/common/src/test/resources/eml/recipients/recipients-ansi.msgnew file mode 100644index 0000000000..a06ed9a630Binary files /dev/null and b/app/common/src/test/resources/eml/recipients/recipients-ansi.msg differdiff --git a/app/common/src/test/resources/eml/recipients/recipients-unicode.msg b/app/common/src/test/resources/eml/recipients/recipients-unicode.msgnew file mode 100644index 0000000000..8aee97e70aBinary files /dev/null and b/app/common/src/test/resources/eml/recipients/recipients-unicode.msg differdiff --git a/app/common/src/test/resources/eml/recipients/recipients.eml b/app/common/src/test/resources/eml/recipients/recipients.emlnew file mode 100644index 0000000000..92a267e9c8--- /dev/null+++ b/app/common/src/test/resources/eml/recipients/recipients.eml@@ -0,0 +1,13 @@+From: =?utf-8?q?=C3=89lodie_Sender?= <[email protected]>+To: =?utf-8?q?Zo=C3=AB_Primary?= <[email protected]>+Cc: =?utf-8?q?Ren=C3=A9_Copy?= <[email protected]>,+ Second Copy <[email protected]>+Bcc: =?utf-8?q?S=C3=B8ren_Blind?= <[email protected]>+Subject: =?utf-8?q?Recipient_options_caf=C3=A9?=+Date: Mon, 01 Jan 2024 12:00:00 +0000+Message-ID: <[email protected]>+MIME-Version: 1.0+Content-Type: text/plain; charset=UTF-8+Content-Transfer-Encoding: 8bit++Fixture email body with café.diff --git a/frontend/src/editor/core/components/tools/convert/ConvertToEpubSettings.test.tsx b/frontend/src/editor/core/components/tools/convert/ConvertToEpubSettings.test.tsxnew file mode 100644index 0000000000..9c8ec82c0c--- /dev/null+++ b/frontend/src/editor/core/components/tools/convert/ConvertToEpubSettings.test.tsx@@ -0,0 +1,83 @@+import { MantineProvider } from "@mantine/core";+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import ConvertToEpubSettings from "@editor/components/tools/convert/ConvertToEpubSettings";+import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));++describe("ebook output settings", () => {+ test.each(["epub", "azw3"])(+ "%s stays selected when chapter and device settings change",+ (toExtension) => {+ const onParameterChange = vi.fn();+ const outputFormat = toExtension === "azw3" ? "AZW3" : "EPUB";+ render(+ <MantineProvider>+ <ConvertToEpubSettings+ parameters={{+ ...defaultParameters,+ fromExtension: "pdf",+ toExtension,+ epubOptions: {+ detectChapters: true,+ targetDevice: "TABLET_PHONE_IMAGES",+ outputFormat: "EPUB",+ },+ }}+ onParameterChange={onParameterChange}+ />+ </MantineProvider>,+ );+ expect(onParameterChange).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole("checkbox", { name: "Detect chapters" }),+ );+ expect(onParameterChange).toHaveBeenLastCalledWith("epubOptions", {+ detectChapters: false,+ targetDevice: "TABLET_PHONE_IMAGES",+ outputFormat,+ });+ fireEvent.click(screen.getByRole("textbox", { name: "Target device" }));+ fireEvent.click(+ screen.getByRole("option", { name: "Kindle e-Ink (text optimized)" }),+ );+ expect(onParameterChange).toHaveBeenLastCalledWith("epubOptions", {+ detectChapters: true,+ targetDevice: "KINDLE_EINK_TEXT",+ outputFormat,+ });+ },+ );++ test("the ebook format picker changes the tool target without losing other options", () => {+ const onParameterChange = vi.fn();+ render(+ <MantineProvider>+ <ConvertToEpubSettings+ parameters={{+ ...defaultParameters,+ fromExtension: "pdf",+ toExtension: "epub",+ epubOptions: {+ detectChapters: false,+ targetDevice: "KINDLE_EINK_TEXT",+ outputFormat: "EPUB",+ },+ }}+ onParameterChange={onParameterChange}+ />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("textbox", { name: "Output format" }));+ fireEvent.click(screen.getByRole("option", { name: "AZW3" }));+ expect(onParameterChange).toHaveBeenCalledWith("toExtension", "azw3");+ expect(onParameterChange).toHaveBeenCalledWith("epubOptions", {+ detectChapters: false,+ targetDevice: "KINDLE_EINK_TEXT",+ outputFormat: "AZW3",+ });+ });+});diff --git a/frontend/src/editor/core/components/tools/convert/ConvertToEpubSettings.tsx b/frontend/src/editor/core/components/tools/convert/ConvertToEpubSettings.tsxindex a1996372ef..6969740d32 100644--- a/frontend/src/editor/core/components/tools/convert/ConvertToEpubSettings.tsx+++ b/frontend/src/editor/core/components/tools/convert/ConvertToEpubSettings.tsx@@ -19,64 +19,38 @@ const ConvertToEpubSettings = ({}: ConvertToEpubSettingsProps) => {const { t } = useTranslation();+ const epubOptions = {+ detectChapters: parameters.epubOptions?.detectChapters ?? true,+ targetDevice: parameters.epubOptions?.targetDevice ?? "TABLET_PHONE_IMAGES",+ outputFormat: parameters.toExtension === "azw3" ? "AZW3" : "EPUB",+ };+const handleDetectChaptersChange = (value: boolean) => {onParameterChange("epubOptions", {+ ...epubOptions,detectChapters: value,- targetDevice:- parameters.epubOptions?.targetDevice ?? "TABLET_PHONE_IMAGES",- outputFormat:- (parameters.epubOptions?.outputFormat ??- parameters.toExtension === "azw3")- ? "AZW3"- : "EPUB",});};const handleTargetDeviceChange = (value: string | null) => {if (value) {onParameterChange("epubOptions", {- detectChapters: parameters.epubOptions?.detectChapters ?? true,+ ...epubOptions,targetDevice: value,- outputFormat:- (parameters.epubOptions?.outputFormat ??- parameters.toExtension === "azw3")- ? "AZW3"- : "EPUB",});}};const handleOutputFormatChange = (value: string | null) => {- if (value) {+ if (value === "EPUB" || value === "AZW3") {+ onParameterChange("toExtension", value === "AZW3" ? "azw3" : "epub");onParameterChange("epubOptions", {- detectChapters: parameters.epubOptions?.detectChapters ?? true,- targetDevice:- parameters.epubOptions?.targetDevice ?? "TABLET_PHONE_IMAGES",+ ...epubOptions,outputFormat: value,});}};- // Initialize epubOptions if not present, set output format based on toExtension- const epubOptions = parameters.epubOptions || {- detectChapters: true,- targetDevice: "TABLET_PHONE_IMAGES",- outputFormat: parameters.toExtension === "azw3" ? "AZW3" : "EPUB",- };-- // Sync output format with selected target extension if not manually set- if (- parameters.toExtension === "azw3" &&- epubOptions.outputFormat !== "AZW3"- ) {- handleOutputFormatChange("AZW3");- } else if (- parameters.toExtension === "epub" &&- epubOptions.outputFormat !== "EPUB"- ) {- handleOutputFormatChange("EPUB");- }-return (<Stack gap="sm" data-testid="epub-settings"><Checkboxdiff --git a/frontend/src/editor/core/hooks/tools/convert/convertBatchRouting.test.ts b/frontend/src/editor/core/hooks/tools/convert/convertBatchRouting.test.tsnew file mode 100644index 0000000000..0077671dc5--- /dev/null+++ b/frontend/src/editor/core/hooks/tools/convert/convertBatchRouting.test.ts@@ -0,0 +1,227 @@+import { beforeEach, describe, expect, test, vi } from "vitest";+import {+ buildConvertFormData,+ convertProcessor,+} from "@editor/hooks/tools/convert/useConvertOperation";+import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";++const api = vi.hoisted(() => ({ post: vi.fn() }));+vi.mock("@editor/services/apiClient", () => ({+ default: {+ post: api.post,+ get: vi.fn(),+ put: vi.fn(),+ delete: vi.fn(),+ interceptors: { response: { use: vi.fn() } },+ },+}));++const CONVERSION_ROUTES = [+ ["pdf", "docx", "pdf/word", "pdf-to-word"],+ ["pdf", "odt", "pdf/word", "pdf-to-word"],+ ["pdf", "pptx", "pdf/presentation", "pdf-to-presentation"],+ ["pdf", "odp", "pdf/presentation", "pdf-to-presentation"],+ ["pdf", "txt", "pdf/text", "pdf-to-text"],+ ["pdf", "rtf", "pdf/text", "pdf-to-rtf"],+ ["pdf", "xlsx", "pdf/xlsx", "pdf-to-xlsx"],+ ["pdf", "html", "pdf/html", "pdf-to-html"],+ ["pdf", "md", "pdf/markdown", "pdf-to-markdown"],+ ["pdf", "xml", "pdf/xml", "pdf-to-xml"],+ ["pdf", "pdfa", "pdf/pdfa", "pdf-to-pdfa"],+ ["pdf", "epub", "pdf/epub", "pdf-to-epub"],+ ["pdf", "azw3", "pdf/epub", "pdf-to-epub"],+ ["docx", "pdf", "file/pdf", "file-to-pdf"],+ ["doc", "pdf", "file/pdf", "file-to-pdf"],+ ["odt", "pdf", "file/pdf", "file-to-pdf"],+ ["xlsx", "pdf", "file/pdf", "file-to-pdf"],+ ["xls", "pdf", "file/pdf", "file-to-pdf"],+ ["ods", "pdf", "file/pdf", "file-to-pdf"],+ ["pptx", "pdf", "file/pdf", "file-to-pdf"],+ ["ppt", "pdf", "file/pdf", "file-to-pdf"],+ ["odp", "pdf", "file/pdf", "file-to-pdf"],+ ["rtf", "pdf", "file/pdf", "file-to-pdf"],+ ["txt", "pdf", "file/pdf", "file-to-pdf"],+ ["file-vsdx", "pdf", "file/pdf", "file-to-pdf"],+ ["html", "pdf", "html/pdf", "html-to-pdf"],+ ["zip", "pdf", "html/pdf", "html-to-pdf"],+ ["md", "pdf", "markdown/pdf", "markdown-to-pdf"],+ ["eml", "pdf", "eml/pdf", "eml-to-pdf"],+ ["msg", "pdf", "eml/pdf", "eml-to-pdf"],+ ["epub", "pdf", "ebook/pdf", "ebook-to-pdf"],+ ["mobi", "pdf", "ebook/pdf", "ebook-to-pdf"],+ ["azw3", "pdf", "ebook/pdf", "ebook-to-pdf"],+ ["fb2", "pdf", "ebook/pdf", "ebook-to-pdf"],+];++beforeEach(() => {+ api.post+ .mockReset()+ .mockResolvedValue({ data: new Blob(["converted"]), headers: {} });+});++describe("conversion batch routing", () => {+ test.each(CONVERSION_ROUTES)(+ "%s to %s processes each input through %s",+ async (fromExtension, toExtension, path, endpointName) => {+ const parameters = {+ ...defaultParameters,+ fromExtension,+ toExtension,+ };+ const files = ["first", "second"].map(+ (name) =>+ new File([name], `${name}.${fromExtension.replace("file-", "")}`),+ );++ const result = await convertProcessor(parameters, files);++ expect(result.files).toHaveLength(2);+ expect(api.post).toHaveBeenCalledTimes(2);+ for (let index = 0; index < files.length; index++) {+ const [url, form, config] = api.post.mock.calls[index];+ expect(url).toBe(`/api/v1/convert/${path}`);+ expect(config.endpointName).toBe(endpointName);+ expect(form.getAll("fileInput")).toEqual([files[index]]);+ }+ },+ );+});++test("mixed uploads use their own endpoint and retain existing PDFs", async () => {+ const types = ["docx", "eml", "html", "png", "epub", "md", "vsdx", "pdf"];+ const files = types.map((type) => new File([type], `input.${type}`));+ const result = await convertProcessor(+ {+ ...defaultParameters,+ fromExtension: "any",+ toExtension: "pdf",+ isSmartDetection: true,+ smartDetectionType: "mixed",+ },+ files,+ );++ expect(result.files).toHaveLength(files.length);+ expect(result.files.at(-1)).toBe(files.at(-1));+ const routes = [+ ["file/pdf", "file-to-pdf"],+ ["eml/pdf", "eml-to-pdf"],+ ["html/pdf", "html-to-pdf"],+ ["img/pdf", "img-to-pdf"],+ ["ebook/pdf", "ebook-to-pdf"],+ ["markdown/pdf", "markdown-to-pdf"],+ ["file/pdf", "file-to-pdf"],+ ];+ expect(api.post).toHaveBeenCalledTimes(routes.length);+ routes.forEach(([route, name], index) => {+ const [url, form, config] = api.post.mock.calls[index];+ expect(url).toBe(`/api/v1/convert/${route}`);+ expect(form.getAll("fileInput")).toEqual([files[index]]);+ expect(config.endpointName).toBe(name);+ });+ expect(api.post.mock.calls[1][1].get("includeAttachments")).not.toBeNull();+ expect(api.post.mock.calls[2][1].get("zoom")).not.toBeNull();+ expect(+ api.post.mock.calls[4][1].get("includeTableOfContents"),+ ).not.toBeNull();+});++test.each([+ ["pdf", "png"],+ ["pdf", "csv"],+ ["pdf", "pdfx"],+ ["pdf", "pdfua"],+ ["pdf", "cbz"],+ ["pdf", "cbr"],+ ["svg", "pdf"],+ ["cbz", "pdf"],+ ["cbr", "pdf"],+])("%s to %s processes every upload", async (fromExtension, toExtension) => {+ await convertProcessor(+ {+ ...defaultParameters,+ fromExtension,+ toExtension,+ imageOptions: { ...defaultParameters.imageOptions, combineImages: false },+ },+ [+ new File(["x"], `one.${fromExtension}`),+ new File(["y"], `two.${fromExtension}`),+ ],+ );+ expect(api.post).toHaveBeenCalledTimes(2);+ for (const [, form] of api.post.mock.calls) {+ expect(form.getAll("fileInput")).toHaveLength(1);+ }+});++test.each(["png", "image", "svg"])(+ "%s keeps combined-image requests",+ async (fromExtension) => {+ const files = [new File(["one"], "one.png"), new File(["two"], "two.png")];+ await convertProcessor(+ {+ ...defaultParameters,+ fromExtension,+ toExtension: "pdf",+ imageOptions: {+ ...defaultParameters.imageOptions,+ combineImages: true,+ },+ },+ files,+ );+ expect(api.post).toHaveBeenCalledTimes(1);+ expect(api.post.mock.calls[0][1].getAll("fileInput")).toEqual(files);+ },+);++test.each(["epub", "azw3"])(+ "%s output follows the selected target despite stale saved options",+ (toExtension) => {+ const data = buildConvertFormData(+ {+ ...defaultParameters,+ fromExtension: "pdf",+ toExtension,+ epubOptions: {+ detectChapters: false,+ targetDevice: "KINDLE_EINK_TEXT",+ outputFormat: toExtension === "azw3" ? "EPUB" : "AZW3",+ },+ },+ [new File(["pdf"], "one.pdf")],+ );+ expect(data.get("outputFormat")).toBe(+ toExtension === "azw3" ? "AZW3" : "EPUB",+ );+ expect(data.get("detectChapters")).toBe("false");+ expect(data.get("targetDevice")).toBe("KINDLE_EINK_TEXT");+ },+);++test.each([false, true])(+ "generic single uploads route by filename with smart detection %s",+ async (isSmartDetection) => {+ const file = new File(["email"], "message.eml");+ await convertProcessor(+ {+ ...defaultParameters,+ fromExtension: "any",+ toExtension: "pdf",+ isSmartDetection,+ smartDetectionType: isSmartDetection ? "mixed" : "none",+ emailOptions: {+ ...defaultParameters.emailOptions,+ includeAllRecipients: false,+ },+ },+ [file],+ );+ expect(api.post).toHaveBeenCalledTimes(1);+ const [url, form, config] = api.post.mock.calls[0];+ expect(url).toBe("/api/v1/convert/eml/pdf");+ expect(config.endpointName).toBe("eml-to-pdf");+ expect(form.get("includeAllRecipients")).toBe("false");+ },+);diff --git a/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts b/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.tsindex af6add70ae..fe5c6f5a0a 100644--- a/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts+++ b/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts@@ -18,8 +18,6 @@ import {getEndpointUrl,getEndpointName,isImageFormat,- isWebFormat,- isOfficeFormat,usesOfficeEngine,parseOfficeEngineChoice,} from "@editor/utils/convertUtils";@@ -35,65 +33,46 @@ import {FIT_OPTIONS,} from "@editor/constants/convertConstants";import { useToolCloudStatus } from "@editor/hooks/useToolCloudStatus";+import { detectFileExtension } from "@editor/utils/fileUtils";-// Static function that can be used by both the hook and automation executor+/** Only the image and SVG endpoints can combine several uploads in one request. */export const shouldProcessFilesSeparately = (selectedFiles: File[],parameters: ConvertParameters,): boolean => {return (selectedFiles.length > 1 &&- // Image to PDF with combineImages = false- (((isImageFormat(parameters.fromExtension) ||- parameters.fromExtension === "image") &&+ !(parameters.toExtension === "pdf" &&- !parameters.imageOptions.combineImages) ||- // SVG to PDF with combineIntoSinglePdf = false- (parameters.fromExtension === "svg" &&- parameters.toExtension === "pdf" &&- !parameters.imageOptions.combineImages) ||- // PDF to image conversions (each PDF should generate its own image file)- (parameters.fromExtension === "pdf" &&- isImageFormat(parameters.toExtension)) ||- // PDF to PDF/A, PDF/X and PDF/UA conversions (each PDF should be processed separately)- (parameters.fromExtension === "pdf" &&- ["pdfa", "pdfx", "pdfua"].includes(parameters.toExtension)) ||- // PDF to text-like/spreadsheet formats should be one output per input- (parameters.fromExtension === "pdf" &&- ["txt", "rtf", "csv", "xlsx"].includes(parameters.toExtension)) ||- // PDF to CBR conversions (each PDF should generate its own archive)- (parameters.fromExtension === "pdf" &&- parameters.toExtension === "cbr") ||- // PDF to EPUB/AZW3 conversions (each PDF should generate its own ebook)- (parameters.fromExtension === "pdf" &&- ["epub", "azw3"].includes(parameters.toExtension)) ||- // PDF to office format conversions (each PDF should generate its own office file)- (parameters.fromExtension === "pdf" &&- isOfficeFormat(parameters.toExtension)) ||- // Office files to PDF conversions (each file should be processed separately via LibreOffice)- (isOfficeFormat(parameters.fromExtension) &&- parameters.toExtension === "pdf") ||- // Web files to PDF conversions (each web file should generate its own PDF)- ((isWebFormat(parameters.fromExtension) ||- parameters.fromExtension === "web") &&- parameters.toExtension === "pdf") ||- // eBook files to PDF conversions (each file should be processed separately via Calibre)- (["epub", "mobi", "azw3", "fb2"].includes(parameters.fromExtension) &&- parameters.toExtension === "pdf") ||- // Web files smart detection- (parameters.isSmartDetection &&- parameters.smartDetectionType === "web") ||- // Mixed file types (smart detection)- (parameters.isSmartDetection &&- parameters.smartDetectionType === "mixed"))+ (isImageFormat(parameters.fromExtension) ||+ ["image", "svg"].includes(parameters.fromExtension)) &&+ parameters.imageOptions.combineImages+ ));};+const parametersForFile = (+ parameters: ConvertParameters,+ file: File,+): ConvertParameters =>+ parameters.fromExtension === "any" && parameters.toExtension === "pdf"+ ? {+ ...parameters,+ fromExtension: detectFileExtension(file.name) || "any",+ isSmartDetection: false,+ smartDetectionType: "none",+ }+ : parameters;+// Static function that can be used by both the hook and automation executorexport const buildConvertFormData = (parameters: ConvertParameters,selectedFiles: File[],): FormData => {+ const requestParameters =+ selectedFiles.length === 1+ ? parametersForFile(parameters, selectedFiles[0])+ : parameters;const formData = new FormData();const {fromExtension,@@ -110,7 +89,7 @@ export const buildConvertFormData = (cbzOutputOptions,ebookOptions,epubOptions,- } = parameters;+ } = requestParameters;selectedFiles.forEach((file) => {formData.append("fileInput", file);@@ -241,10 +220,7 @@ export const buildConvertFormData = ("targetDevice",epubOptions?.targetDevice ?? "TABLET_PHONE_IMAGES",);- formData.append(- "outputFormat",- epubOptions?.outputFormat ?? (toExtension === "azw3" ? "AZW3" : "EPUB"),- );+ formData.append("outputFormat", toExtension === "azw3" ? "AZW3" : "EPUB");}return formData;@@ -309,13 +285,13 @@ export const convertProcessor = async (// Map PDF/X to use PDF/A endpointconst actualToExtension =parameters.toExtension === "pdfx" ? "pdfa" : parameters.toExtension;- const endpoint = getEndpointUrl(parameters.fromExtension, actualToExtension);+ let endpoint = getEndpointUrl(parameters.fromExtension, actualToExtension);if (!endpoint) {throw new Error("Unsupported conversion format");}// PDF to text and to RTF share a URL, so desktop routing needs the key itself.- const requestConfig = {+ let requestConfig = {responseType: "blob" as const,endpointName: getEndpointName(parameters.fromExtension, actualToExtension),};@@ -327,10 +303,29 @@ export const convertProcessor = async (toExtension: actualToExtension, // Use the mapped extension for decision logic});- if (isSeparateProcessing) {+ if (isSeparateProcessing || parameters.fromExtension === "any") {// Individual processing for complex cases (PDF→image, smart detection, etc.)for (const file of selectedFiles) {try {+ const fileParameters = parametersForFile(parameters, file);+ if (+ fileParameters.fromExtension === "pdf" &&+ actualToExtension === "pdf"+ ) {+ processedFiles.push(file);+ continue;+ }+ endpoint = getEndpointUrl(+ fileParameters.fromExtension,+ actualToExtension,+ );+ requestConfig = {+ ...requestConfig,+ endpointName: getEndpointName(+ fileParameters.fromExtension,+ actualToExtension,+ ),+ };const formData = buildConvertFormData(parameters, [file]);const response = await apiClient.post(endpoint, formData, requestConfig)diff --git a/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx b/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsxindex 48e07792c0..087188aa21 100644--- a/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx+++ b/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx@@ -106,6 +106,23 @@ vi.mock("../../services/thumbnailGenerationService", () => ({},}));+vi.mock("@editor/utils/thumbnailUtils", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@editor/utils/thumbnailUtils")>()),+ generateThumbnailForFile: vi+ .fn()+ .mockResolvedValue("data:image/png;base64,fake-thumbnail"),+ generateThumbnailPairWithMetadata: vi.fn().mockResolvedValue({+ unrotated: {+ thumbnail: "data:image/png;base64,fake-thumbnail",+ pageCount: 1,+ },+ rotated: {+ thumbnail: "data:image/png;base64,fake-thumbnail",+ pageCount: 1,+ },+ }),+}));+const TestWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (<MantineProvider><I18nextProvider i18n={i18n}>@@ -304,7 +321,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {expect(files).toHaveLength(3);});- test("should detect mixed file types and use file-to-pdf endpoint", async () => {+ test("converts mixed Office uploads individually and keeps the existing PDF", async () => {const { result: paramsResult } = renderHook(() => useConvertParameters(),{@@ -361,6 +378,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {});expect(onToolRunComplete).toHaveBeenCalledTimes(1);+ expect(mockedApiClient.post).toHaveBeenCalledTimes(2);expect(mockedApiClient.post).toHaveBeenCalledWith("/api/v1/convert/file/pdf",expect.any(FormData),diff --git a/frontend/src/editor/core/tests/stubbed/convert-batches.spec.ts b/frontend/src/editor/core/tests/stubbed/convert-batches.spec.tsnew file mode 100644index 0000000000..f7456d5a7a--- /dev/null+++ b/frontend/src/editor/core/tests/stubbed/convert-batches.spec.ts@@ -0,0 +1,147 @@+import { test, expect, type Page } from "@playwright/test";+import path from "path";+import { readFileSync } from "node:fs";+import { mockAppApis } from "@editor/tests/helpers/api-stubs";+import {+ suppressNativeFilePicker,+ revealPickerTool,+} from "@editor/tests/helpers/ui-helpers";++const SAMPLE_PDF = path.join(+ import.meta.dirname,+ "../test-fixtures/sample.pdf",+);++async function dismissTourTooltip(page: Page) {+ const closeBtn = page.getByRole("button", { name: /close tooltip/i }).first();+ if (await closeBtn.isVisible({ timeout: 500 }).catch(() => false)) {+ await closeBtn.click();+ }+}++async function navigateToConvert(page: Page) {+ const tile = await revealPickerTool(page, "convert");+ await tile.click();+ await page.waitForSelector('[data-testid="convert-from-dropdown"]', {+ timeout: 5000,+ });+}++async function selectToFormat(page: Page, toValue: string) {+ await page.getByTestId("convert-to-dropdown").click();+ await page.getByTestId(`format-option-${toValue}`).click();+}++test.describe("Convert batches", () => {+ test.beforeEach(async ({ page }) => {+ suppressNativeFilePicker(page);+ await mockAppApis(page);+ await page.goto("/?bypassOnboarding=true");+ await expect(page.getByTestId("files-button")).toBeVisible();+ });++ for (const format of ["eml", "msg"]) {+ test(`converts every ${format.toUpperCase()} upload with its email settings`, async ({+ page,+ }) => {+ const payloads: string[] = [];+ await page.route("**/api/v1/convert/eml/pdf", (route) => {+ payloads.push(route.request().postData() ?? "");+ return route.fulfill({+ status: 200,+ contentType: "application/pdf",+ headers: {+ "Content-Disposition": `attachment; filename="email-${payloads.length}.pdf"`,+ },+ path: SAMPLE_PDF,+ });+ });+ await page.getByTestId("files-button").click();+ const buffer =+ format === "msg"+ ? readFileSync(+ path.resolve("../app/common/src/test/resources/eml/example.msg"),+ )+ : Buffer.from(+ "From: [email protected]\r\nSubject: Email\r\n\r\nEmail content",+ );+ await page.getByTestId("file-input").setInputFiles(+ ["first", "second"].map((name) => ({+ name: `${name}.${format}`,+ mimeType:+ format === "msg" ? "application/vnd.ms-outlook" : "message/rfc822",+ buffer,+ })),+ );+ await navigateToConvert(page);+ await selectToFormat(page, "pdf");+ await expect(page.getByTestId("email-settings")).toBeVisible();+ await page.getByTestId("include-attachments-checkbox").check();+ await page.getByTestId("include-all-recipients-checkbox").uncheck();+ await dismissTourTooltip(page);+ const request = page.waitForRequest("**/api/v1/convert/eml/pdf");+ await page.getByTestId("convert-button").click();+ const payload = (await request).postData() ?? "";+ expect(payload).toMatch(/name="includeAttachments"\r\n\r\ntrue/);+ expect(payload).toMatch(/name="includeAllRecipients"\r\n\r\nfalse/);+ await expect(page.getByTestId("download-result-button")).toBeVisible();+ await expect.poll(() => payloads.length).toBe(2);+ for (const body of payloads) {+ expect(body).toMatch(/name="includeAttachments"\r\n\r\ntrue/);+ expect(body).toMatch(/name="includeAllRecipients"\r\n\r\nfalse/);+ }+ });+ }++ test("mixed Office, email and HTML uploads use their own conversion endpoints", async ({+ page,+ }) => {+ const requests: string[] = [];+ await page.route("**/api/v1/convert/**", (route) => {+ requests.push(new URL(route.request().url()).pathname);+ return route.fulfill({+ status: 200,+ contentType: "application/pdf",+ path: SAMPLE_PDF,+ headers: {+ "Content-Disposition": `attachment; filename="converted-${requests.length}.pdf"`,+ },+ });+ });+ await page.getByTestId("files-button").click();+ await page.getByTestId("file-input").setInputFiles([+ {+ name: "letter.docx",+ mimeType:+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ buffer: Buffer.from("document"),+ },+ {+ name: "mail.eml",+ mimeType: "message/rfc822",+ buffer: Buffer.from(+ "From: [email protected]\r\nSubject: Email\r\n\r\nEmail",+ ),+ },+ {+ name: "page.html",+ mimeType: "text/html",+ buffer: Buffer.from("<html><body>HTML</body></html>"),+ },+ {+ name: "existing.pdf",+ mimeType: "application/pdf",+ buffer: readFileSync(SAMPLE_PDF),+ },+ ]);+ await navigateToConvert(page);+ await dismissTourTooltip(page);+ await page.getByTestId("convert-button").click();+ await expect(page.getByTestId("download-result-button")).toBeVisible();+ expect(requests).toEqual([+ "/api/v1/convert/file/pdf",+ "/api/v1/convert/eml/pdf",+ "/api/v1/convert/html/pdf",+ ]);+ });+});