Normalize document export options (#13364)

This commit is contained in:
Tom Moor authored and GitHub committed 2026-08-10 07:43:37 -04:00
1 parent 3afb0517bf
commit a0fcc32622
13 files changed
+300 -273

No files matched your search

+40 -45
View File
@@ -2,7 +2,6 @@ import copy from "copy-to-clipboard";
import invariant from "invariant";
import { capitalize, uniqBy } from "es-toolkit/compat";
import {
DownloadIcon,
DuplicateIcon,
StarredIcon,
PrintIcon,
@@ -36,6 +35,9 @@ import {
EmbedIcon,
OpenIcon,
SplitIcon,
ExportIcon,
CodeIcon,
PDFIcon,
} from "outline-icons";
import { toast } from "sonner";
import Icon from "@shared/components/Icon";
@@ -54,12 +56,12 @@ import DeleteDocumentsInTrash from "~/scenes/Trash/components/DeleteDocumentsInT
import ConfirmationDialog from "~/components/ConfirmationDialog";
import { DialogTitle } from "~/components/DialogTitle";
import DocumentCopy from "~/components/DocumentExplorer/DocumentCopy";
import { DocumentDownload } from "~/components/Export/DocumentDownload";
import MarkdownIcon from "~/components/Icons/MarkdownIcon";
import { ImportDocumentDialog } from "~/components/ImportDocumentDialog";
import { getHeaderExpandedKey } from "~/components/Sidebar/components/Header";
import DocumentTemplatizeDialog from "~/components/TemplatizeDialog";
import {
ActionSeparator,
createAction,
createActionGroup,
createActionWithChildren,
@@ -100,7 +102,7 @@ import type {
Action,
ActionContext,
ActionGroup,
ActionSeparator,
ActionSeparator as TActionSeparator,
} from "~/types";
import lazyWithRetry from "~/utils/lazyWithRetry";
import env from "~/env";
@@ -702,40 +704,13 @@ export const shareDocument = createAction({
},
});
export const downloadDocument = createAction({
name: ({ t, isMenu }) => (isMenu ? t("Download") : t("Download document")),
analyticsName: "Download document",
section: ActiveDocumentSection,
icon: <DownloadIcon />,
keywords: "export md markdown html",
visible: ({ activeDocumentId, stores }) =>
!!activeDocumentId && stores.policies.abilities(activeDocumentId).download,
perform: ({ activeDocumentId, t, stores }) => {
if (!activeDocumentId) {
return;
}
const document = stores.documents.get(activeDocumentId);
invariant(document, "Document must exist");
stores.dialogs.openModal({
title: <DialogTitle title={t("Download document")} model={document} />,
content: (
<DocumentDownload
document={document}
onSubmit={stores.dialogs.closeAllModals}
/>
),
});
},
});
export const downloadDocumentAsMarkdown = createAction({
name: ({ t }) => t("Download as Markdown"),
name: ({ t, isMenu }) => (isMenu ? t("Markdown") : t("Download as Markdown")),
analyticsName: "Download document as Markdown",
section: ActiveDocumentSection,
keywords: "md markdown export",
icon: <DownloadIcon />,
keywords: "md markdown export download",
icon: <MarkdownIcon />,
iconInContextMenu: false,
visible: ({ activeDocumentId, stores }) =>
!!activeDocumentId && stores.policies.abilities(activeDocumentId).download,
perform: async ({ activeDocumentId, stores }) => {
@@ -752,11 +727,12 @@ export const downloadDocumentAsMarkdown = createAction({
});
export const downloadDocumentAsHTML = createAction({
name: ({ t }) => t("Download as HTML"),
name: ({ t, isMenu }) => (isMenu ? t("HTML") : t("Download as HTML")),
analyticsName: "Download document as HTML",
section: ActiveDocumentSection,
keywords: "xml html export",
icon: <DownloadIcon />,
keywords: "xml html export download",
icon: <CodeIcon />,
iconInContextMenu: false,
visible: ({ activeDocumentId, stores }) =>
!!activeDocumentId && stores.policies.abilities(activeDocumentId).download,
perform: async ({ activeDocumentId, stores }) => {
@@ -773,11 +749,13 @@ export const downloadDocumentAsHTML = createAction({
});
export const downloadDocumentAsTextBundle = createAction({
name: ({ t }) => t("Download as TextBundle"),
name: ({ t, isMenu }) =>
isMenu ? t("TextBundle") : t("Download as TextBundle"),
analyticsName: "Download document as TextBundle",
section: ActiveDocumentSection,
keywords: "textbundle textpack bear ulysses export",
icon: <DownloadIcon />,
keywords: "textbundle textpack bear ulysses export download",
icon: <ArchiveIcon />,
iconInContextMenu: false,
visible: ({ activeDocumentId, stores }) =>
!!activeDocumentId && stores.policies.abilities(activeDocumentId).download,
perform: async ({ activeDocumentId, stores }) => {
@@ -794,11 +772,12 @@ export const downloadDocumentAsTextBundle = createAction({
});
export const downloadDocumentAsPDF = createAction({
name: ({ t }) => t("Download as PDF"),
name: ({ t, isMenu }) => (isMenu ? t("PDF") : t("Download as PDF")),
analyticsName: "Download document as PDF",
section: ActiveDocumentSection,
keywords: "pdf export",
icon: <DownloadIcon />,
keywords: "pdf export download",
icon: <PDFIcon />,
iconInContextMenu: false,
visible: ({ activeDocumentId, stores }) =>
!!(
activeDocumentId &&
@@ -1091,12 +1070,29 @@ export const printDocument = createAction({
analyticsName: "Print document",
section: ActiveDocumentSection,
icon: <PrintIcon />,
iconInContextMenu: false,
visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print),
perform: () => {
setTimeout(window.print, 0);
},
});
export const exportDocument = createActionWithChildren({
name: ({ t, isMenu }) => (isMenu ? t("Export") : t("Export document")),
analyticsName: "Export document",
section: ActiveDocumentSection,
icon: <ExportIcon />,
keywords: "download print pdf markdown html",
children: [
downloadDocumentAsMarkdown,
downloadDocumentAsHTML,
downloadDocumentAsTextBundle,
downloadDocumentAsPDF,
ActionSeparator,
printDocument,
],
});
export const openDocumentInDesktop = createAction({
name: ({ t }) => t("Open in desktop app"),
analyticsName: "Open in desktop",
@@ -1753,7 +1749,7 @@ export const leaveDocument = createAction({
export const applyTemplateActionFactory = ({
actions,
}: {
actions: (Action | ActionGroup | ActionSeparator)[];
actions: (Action | ActionGroup | TActionSeparator)[];
}) =>
createActionWithChildren({
name: ({ t }) => t("Apply template"),
@@ -1782,7 +1778,6 @@ export const rootDocumentActions = [
createTemplateFromDocument,
deleteDocument,
importDocument,
downloadDocument,
downloadDocumentAsMarkdown,
downloadDocumentAsHTML,
downloadDocumentAsTextBundle,
+74 -8
View File
@@ -1,12 +1,21 @@
import copy from "copy-to-clipboard";
import { LinkIcon, RestoreIcon, TrashIcon, DownloadIcon } from "outline-icons";
import {
LinkIcon,
RestoreIcon,
TrashIcon,
DownloadIcon,
ExportIcon,
PrintIcon,
} from "outline-icons";
import { matchPath } from "react-router-dom";
import { toast } from "sonner";
import { ExportContentType } from "@shared/types";
import { RevisionHelper } from "@shared/utils/RevisionHelper";
import Revision from "~/models/Revision";
import stores from "~/stores";
import type { ActionContext } from "~/types";
import {
ActionSeparator,
createAction,
createActionWithChildren,
createInternalLinkAction,
@@ -27,6 +36,30 @@ function getActiveRevisionId({ location, getActiveModel }: ActionContext) {
return getActiveModel(Revision)?.id ?? match?.params.revisionId;
}
/**
* Whether the given revision is the one currently displayed, as opposed to
* merely the one a menu was opened from.
*/
function isViewingRevision(
{ location, activeDocumentId }: ActionContext,
revisionId: string
) {
const match = matchPath<{ revisionId: string }>(location.pathname, {
path: matchDocumentHistory,
});
const viewing = match?.params.revisionId;
if (!viewing) {
return false;
}
// The most recent revision is addressed by a placeholder in the url.
return viewing === "latest"
? !!activeDocumentId &&
RevisionHelper.latestId(activeDocumentId) === revisionId
: viewing === revisionId;
}
export const restoreRevision = createInternalLinkAction({
name: ({ t }) => t("Restore"),
analyticsName: "Restore revision",
@@ -169,20 +202,53 @@ export const downloadRevisionAsMarkdownActionFactory = (revisionId: string) =>
},
});
export const downloadRevisionActionFactory = (revisionId: string) =>
createActionWithChildren({
name: ({ t, isMenu }) => (isMenu ? t("Download") : t("Download revision")),
analyticsName: "Download revision",
export const downloadRevisionAsTextBundleActionFactory = (revisionId: string) =>
createAction({
name: ({ t }) => t("TextBundle"),
analyticsName: "Download revision as TextBundle",
section: RevisionSection,
keywords: "textbundle textpack bear ulysses export",
icon: <DownloadIcon />,
keywords: "export",
iconInContextMenu: false,
visible: ({ activeDocumentId }) =>
!!activeDocumentId &&
stores.policies.abilities(activeDocumentId).download,
perform: async () => {
const revision = stores.revisions.get(revisionId);
await revision?.download(ExportContentType.TextBundle);
},
});
export const printRevisionActionFactory = (revisionId: string) =>
createAction({
name: ({ t }) => t("Print"),
analyticsName: "Print revision",
section: RevisionSection,
icon: <PrintIcon />,
iconInContextMenu: false,
// Printing captures whatever is on screen, so it is only offered for the
// revision currently being viewed.
visible: (context) =>
!!window.print && isViewingRevision(context, revisionId),
perform: () => {
setTimeout(window.print, 0);
},
});
export const exportRevisionActionFactory = (revisionId: string) =>
createActionWithChildren({
name: ({ t, isMenu }) => (isMenu ? t("Export") : t("Export revision")),
analyticsName: "Export revision",
section: RevisionSection,
icon: <ExportIcon />,
keywords: "download export",
children: [
downloadRevisionAsHTMLActionFactory(revisionId),
downloadRevisionAsPDFActionFactory(revisionId),
downloadRevisionAsMarkdownActionFactory(revisionId),
downloadRevisionAsHTMLActionFactory(revisionId),
downloadRevisionAsTextBundleActionFactory(revisionId),
downloadRevisionAsPDFActionFactory(revisionId),
ActionSeparator,
printRevisionActionFactory(revisionId),
],
});
-166
View File
@@ -1,166 +0,0 @@
import { observer } from "mobx-react";
import { ArchiveIcon, CodeIcon, PDFIcon } from "outline-icons";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import styled from "styled-components";
import { ExportContentType, NotificationEventType } from "@shared/types";
import type Document from "~/models/Document";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import Flex from "~/components/Flex";
import { FileFormatSelector } from "~/components/Export/FileFormatSelector";
import type { FileFormat } from "~/components/Export/FileFormatSelector";
import MarkdownIcon from "~/components/Icons/MarkdownIcon";
import Text from "~/components/Text";
import env from "~/env";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePersistedState from "~/hooks/usePersistedState";
import useStores from "~/hooks/useStores";
type Props = {
document: Document;
onSubmit: () => void;
};
export const DocumentDownload = observer(({ document, onSubmit }: Props) => {
const { t } = useTranslation();
const { ui } = useStores();
const user = useCurrentUser();
const hasChildDocuments = !!document.childDocuments.length;
const [lastContentType, setContentType] =
usePersistedState<ExportContentType>(
"document-download-format",
ExportContentType.Markdown
);
const [includeChildDocuments, setIncludeChildDocuments] =
useState<boolean>(hasChildDocuments);
const formats = useMemo(() => {
const items: FileFormat<ExportContentType>[] = [
{
title: "Markdown",
extension: ".md",
value: ExportContentType.Markdown,
icon: <MarkdownIcon />,
},
{
title: "HTML",
extension: ".html",
value: ExportContentType.Html,
icon: <CodeIcon />,
},
{
title: "TextBundle",
extension: ".textpack",
value: ExportContentType.TextBundle,
icon: <ArchiveIcon />,
},
];
if (env.PDF_EXPORT_ENABLED) {
items.push({
title: "PDF",
extension: ".pdf",
value: ExportContentType.Pdf,
icon: <PDFIcon />,
});
}
return items;
}, []);
// The last chosen format may no longer be available, fallback to the first.
const contentType = formats.some((format) => format.value === lastContentType)
? lastContentType
: formats[0].value;
const handleIncludeChildDocumentsChange = useCallback(
(ev: React.ChangeEvent<HTMLInputElement>) => {
setIncludeChildDocuments(ev.target.checked);
},
[]
);
const handleSubmit = useCallback(async () => {
const response = await document.download({
contentType,
includeChildDocuments,
});
if (includeChildDocuments && response?.data?.fileOperation) {
const fileOperationId = response.data.fileOperation.id;
const toastId = `export-${fileOperationId}`;
const timeoutId = setTimeout(() => {
toast.success(t("Export started"), {
id: toastId,
description: t("A link to your file will be sent through email soon"),
duration: 3000,
});
ui.exportToasts.delete(fileOperationId);
}, 6000);
ui.registerExportToast(fileOperationId, toastId, timeoutId);
toast.loading(t("Export started"), {
id: toastId,
description: `${t("Preparing your download")}…`,
duration: Infinity,
});
}
onSubmit();
}, [t, ui, document, contentType, includeChildDocuments, onSubmit]);
return (
<ConfirmationDialog onSubmit={handleSubmit} submitText={t("Download")}>
<FileFormatSelector
formats={formats}
value={contentType}
onChange={setContentType}
/>
{hasChildDocuments && (
<>
<hr style={{ margin: "16px 0 " }} />
<Option>
<StyledInput
type="checkbox"
name="includeChildDocuments"
checked={includeChildDocuments}
onChange={handleIncludeChildDocumentsChange}
/>
<Flex column gap={4}>
<Text as="p" size="small" weight="bold">
{t("Include child documents")}
</Text>
<Text as="p" size="small" type="secondary">
{t(
"When selected, exporting the document will take extra time."
)}{" "}
{user.subscribedToEventType(
NotificationEventType.ExportCompleted
) && t("You will receive an email when it's complete.")}
</Text>
</Flex>
</Option>
</>
)}
</ConfirmationDialog>
);
});
const Option = styled.label`
display: flex;
align-items: baseline;
gap: 16px;
p {
margin: 0;
}
`;
const StyledInput = styled.input`
position: relative;
top: 1.5px;
`;
+4 -6
View File
@@ -15,19 +15,17 @@ export default function MarkdownIcon({
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
fill={color}
xmlns="http://www.w3.org/2000/svg"
{...rest}
>
<path
d="M19.2692 7H3.86538C3.38745 7 3 7.38476 3 7.85938V16.2812C3 16.7559 3.38745 17.1406 3.86538 17.1406H19.2692C19.7472 17.1406 20.1346 16.7559 20.1346 16.2812V7.85938C20.1346 7.38476 19.7472 7 19.2692 7Z"
stroke={color}
fill="none"
stroke="currentColor"
strokeWidth="2"
/>
<path
d="M5.16345 14.9922V9.14844H6.89422L8.62499 11.2969L10.3558 9.14844H12.0865V14.9922H10.3558V11.6406L8.62499 13.7891L6.89422 11.6406V14.9922H5.16345ZM15.9808 14.9922L13.3846 12.1562H15.1154V9.14844H16.8461V12.1562H18.5769L15.9808 14.9922Z"
fill={color}
/>
<path d="M5.16345 14.9922V9.14844H6.89422L8.62499 11.2969L10.3558 9.14844H12.0865V14.9922H10.3558V11.6406L8.62499 13.7891L6.89422 11.6406V14.9922H5.16345ZM15.9808 14.9922L13.3846 12.1562H15.1154V9.14844H16.8461V12.1562H18.5769L15.9808 14.9922Z" />
</svg>
);
}
+2 -4
View File
@@ -27,10 +27,9 @@ import {
openDocumentInsights,
openDocumentInDesktop,
openDocumentInSplit,
downloadDocument,
exportDocument,
copyDocument,
presentDocument,
printDocument,
searchInDocument,
deleteDocument,
leaveDocument,
@@ -111,9 +110,8 @@ export function useDocumentMenuAction({
openDocumentInSplit,
openDocumentInDesktop,
presentDocument,
downloadDocument,
exportDocument,
copyDocument,
printDocument,
searchInDocument,
ActionSeparator,
deleteDocument,
+2 -2
View File
@@ -6,7 +6,7 @@ import { OverflowMenuButton } from "~/components/Menu/OverflowMenuButton";
import { ActionSeparator } from "~/actions";
import {
copyLinkToRevisionActionFactory,
downloadRevisionActionFactory,
exportRevisionActionFactory,
restoreRevision,
} from "~/actions/definitions/revisions";
import { useMemo } from "react";
@@ -25,7 +25,7 @@ function RevisionMenu({ document, revisionId }: Props) {
restoreRevision,
ActionSeparator,
copyLinkToRevisionActionFactory(revisionId),
downloadRevisionActionFactory(revisionId),
exportRevisionActionFactory(revisionId),
],
[revisionId]
);
@@ -13,7 +13,7 @@ import type Revision from "~/models/Revision";
import { ActionSeparator } from "~/actions";
import {
copyLinkToRevisionActionFactory,
downloadRevisionActionFactory,
exportRevisionActionFactory,
restoreRevision,
} from "~/actions/definitions/revisions";
import { Avatar, AvatarSize } from "~/components/Avatar";
@@ -51,7 +51,7 @@ const RevisionListItem = ({ item, document, ...rest }: Props) => {
restoreRevision,
ActionSeparator,
copyLinkToRevisionActionFactory(item.id),
downloadRevisionActionFactory(item.id),
exportRevisionActionFactory(item.id),
],
[item.id]
);
+24
View File
@@ -1,6 +1,9 @@
import { addHours } from "date-fns";
import { AttachmentPreset } from "@shared/types";
import { errToString } from "@shared/utils/error";
import env from "@server/env";
import Logger from "@server/logging/Logger";
import type Attachment from "@server/models/Attachment";
import { ValidateKey } from "@server/validation";
import { AttachmentValidation } from "@shared/validations";
@@ -114,4 +117,25 @@ export default class AttachmentHelper {
return env.FILE_STORAGE_UPLOAD_MAX_SIZE;
}
}
/**
* Read the contents of an attachment from storage. An attachment that cannot
* be read is treated as empty so that a single missing file does not fail the
* export it is part of.
*
* @param attachment The attachment to read
* @returns The contents of the attachment.
*/
static async readBuffer(attachment: Attachment): Promise<Buffer> {
try {
return await attachment.buffer;
} catch (err) {
Logger.warn(`Failed to read attachment from storage`, {
attachmentId: attachment.id,
teamId: attachment.teamId,
error: errToString(err),
});
return Buffer.from("");
}
}
}
+8 -2
View File
@@ -32,9 +32,13 @@ export default class TextBundleHelper {
* Builds the metadata entry that identifies a directory as a TextBundle.
*
* @param document The document the bundle was built from.
* @param revisionId The revision the bundle was built from, if not the
* current version of the document.
* @returns The contents of the bundle's info.json.
*/
public static info(document: Document): string {
public static info(document: Document, revisionId?: string): string {
const documentURL = `${env.URL}${document.url}`;
return JSON.stringify(
{
version: 2,
@@ -42,7 +46,9 @@ export default class TextBundleHelper {
transient: false,
creatorIdentifier: "com.getoutline.outline",
creatorURL: env.URL,
sourceURL: `${env.URL}${document.url}`,
sourceURL: revisionId
? `${documentURL}/history/${revisionId}`
: documentURL,
},
null,
2
+1 -13
View File
@@ -9,7 +9,6 @@ import mime from "mime-types";
import type { Order, ScopeOptions, WhereOptions } from "sequelize";
import { Op, Sequelize } from "sequelize";
import { randomUUID } from "node:crypto";
import { errToString } from "@shared/utils/error";
import type { DirectionFilter, SortFilter } from "@shared/types";
import { type NavigationNode } from "@shared/types";
import {
@@ -41,7 +40,6 @@ import {
IncorrectEditionError,
NotFoundError,
} from "@server/errors";
import Logger from "@server/logging/Logger";
import auth from "@server/middlewares/authentication";
import multipart from "@server/middlewares/multipart";
import { rateLimiter } from "@server/middlewares/rateLimiter";
@@ -929,17 +927,7 @@ router.post(
const externalAttachments: { attachment: Attachment; buffer: Buffer }[] =
[];
for (const attachment of attachments) {
let buffer: Buffer;
try {
buffer = await attachment.buffer;
} catch (err) {
Logger.warn(`Failed to read attachment from storage`, {
attachmentId: attachment.id,
teamId: attachment.teamId,
error: errToString(err),
});
buffer = Buffer.from("");
}
const buffer = await AttachmentHelper.readBuffer(attachment);
if (contentType === "text/html") {
const inlined = HTMLHelper.inlineImage(
@@ -1,3 +1,4 @@
import { ExportContentType } from "@shared/types";
import { createContext } from "@server/context";
import { UserMembership, Revision } from "@server/models";
import FileStorage from "@server/storage/files";
@@ -294,6 +295,89 @@ describe("#revisions.export", () => {
expect(entries["export-test.md"]).not.toContain(attachment.redirectUrl);
});
it("should stream a textpack when TextBundle is requested", async () => {
const user = await buildUser();
const attachment = await buildAttachment(
{ teamId: user.teamId, userId: user.id, contentType: "image/png" },
"photo.png"
);
const document = await buildDocument({
title: "Export Test",
userId: user.id,
teamId: user.teamId,
text: `![image](${attachment.redirectUrl})`,
});
const revision = await Revision.createFromDocument(
createContext({ user }),
document
);
vi.spyOn(FileStorage, "getFileBuffer").mockResolvedValue(
Buffer.from("image-data")
);
const res = await server.post("/api/revisions.export", user, {
body: {
id: revision.id,
},
headers: {
accept: ExportContentType.TextBundle,
},
});
expect(res.status).toEqual(200);
expect(res.headers.get("content-disposition")).toContain(
`filename="export-test.textpack"`
);
const bundle = "export-test.textbundle";
const entries = await readZipResponse(res);
expect(Object.keys(entries).sort()).toEqual([
`${bundle}/assets/photo.png`,
`${bundle}/info.json`,
`${bundle}/text.markdown`,
]);
expect(entries[`${bundle}/assets/photo.png`]).toEqual("image-data");
expect(entries[`${bundle}/text.markdown`]).toContain("assets/photo.png");
// The bundle points back at the revision it was built from, rather than the
// current version of the document.
const info = JSON.parse(entries[`${bundle}/info.json`]);
expect(info.type).toEqual("net.daringfireball.markdown");
expect(info.sourceURL).toContain(`/history/${revision.id}`);
});
it("should stream a textpack when TextBundle is requested for a revision with no attachments", async () => {
const user = await buildUser();
const document = await buildDocument({
title: "Plain Export",
userId: user.id,
teamId: user.teamId,
});
const revision = await Revision.createFromDocument(
createContext({ user }),
document
);
const res = await server.post("/api/revisions.export", user, {
body: {
id: revision.id,
},
headers: {
accept: ExportContentType.TextBundle,
},
});
expect(res.status).toEqual(200);
// A bundle is a directory, so there is no self-contained single file form
// to fall back to when nothing is referenced.
const entries = await readZipResponse(res);
expect(Object.keys(entries).sort()).toEqual([
"plain-export.textbundle/info.json",
"plain-export.textbundle/text.markdown",
]);
});
it("should return revision as markdown by default", async () => {
const user = await buildUser();
const document = await buildDocument({
+51 -16
View File
@@ -3,19 +3,19 @@ import Router from "koa-router";
import contentDisposition from "content-disposition";
import { escapeRegExp } from "es-toolkit/compat";
import mime from "mime-types";
import { errToString } from "@shared/utils/error";
import { UserRole } from "@shared/types";
import { ExportContentType, UserRole } from "@shared/types";
import { RevisionHelper } from "@shared/utils/RevisionHelper";
import slugify from "@shared/utils/slugify";
import { ValidationError, IncorrectEditionError } from "@server/errors";
import Logger from "@server/logging/Logger";
import auth from "@server/middlewares/authentication";
import { rateLimiter } from "@server/middlewares/rateLimiter";
import { transaction } from "@server/middlewares/transaction";
import validate from "@server/middlewares/validate";
import { Attachment, Document, Revision } from "@server/models";
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper";
import TextBundleHelper from "@server/models/helpers/TextBundleHelper";
import { authorize } from "@server/policies";
import { presentPolicies, presentRevision } from "@server/presenters";
import type { APIContext } from "@server/types";
@@ -154,6 +154,10 @@ router.post(
let contentType: string;
let content: string;
// A TextBundle is a directory of files, so unlike the other formats it has
// no self-contained single-file form to fall back to.
const isTextBundle = !!accept?.includes(ExportContentType.TextBundle);
if (accept?.includes("text/html")) {
contentType = "text/html";
content = await DocumentHelper.toHTML(revision, {
@@ -164,7 +168,7 @@ router.post(
throw IncorrectEditionError(
"PDF export is not available in the community edition"
);
} else if (accept?.includes("text/markdown")) {
} else if (isTextBundle || accept?.includes("text/markdown")) {
contentType = "text/markdown";
content = await DocumentHelper.toMarkdown(revision);
} else {
@@ -192,6 +196,46 @@ router.post(
})
: [];
if (isTextBundle) {
const root = `${fileName}.${TextBundleHelper.bundleExtension}`;
const usedAssetNames = new Set<string>();
streamZipResponse(
ctx,
`${fileName}.${TextBundleHelper.packExtension}`,
async (zip) => {
for (const attachment of attachments) {
const reference = TextBundleHelper.assetPath(
attachment.name,
usedAssetNames
);
zip.addBuffer(
await AttachmentHelper.readBuffer(attachment),
path.join(root, reference),
{ mtime: attachment.updatedAt }
);
content = content.replace(
new RegExp(escapeRegExp(attachment.redirectUrl), "g"),
encodeURI(reference)
);
}
zip.addBuffer(
Buffer.from(TextBundleHelper.info(document, revision.id)),
path.join(root, TextBundleHelper.infoFileName),
{ mtime: revision.updatedAt }
);
zip.addBuffer(
Buffer.from(content),
path.join(root, TextBundleHelper.textFileName),
{ mtime: revision.updatedAt }
);
}
);
return;
}
if (attachments.length === 0) {
ctx.set("Content-Type", contentType);
ctx.set(
@@ -210,18 +254,9 @@ router.post(
"attachments",
`${attachment.id}.${mime.extension(attachment.contentType)}`
);
let buffer: Buffer;
try {
buffer = await attachment.buffer;
} catch (err) {
Logger.warn(`Failed to read attachment from storage`, {
attachmentId: attachment.id,
teamId: attachment.teamId,
error: errToString(err),
});
buffer = Buffer.from("");
}
zip.addBuffer(buffer, location, { mtime: attachment.updatedAt });
zip.addBuffer(await AttachmentHelper.readBuffer(attachment), location, {
mtime: attachment.updatedAt,
});
content = content.replace(
new RegExp(escapeRegExp(attachment.redirectUrl), "g"),
+8 -9
View File
@@ -77,11 +77,13 @@
"{{ count }} documents unpublished_plural": "{{ count }} documents unpublished",
"Subscription inherited from collection": "Subscription inherited from collection",
"Share document": "Share document",
"Download": "Download",
"Download document": "Download document",
"Markdown": "Markdown",
"Download as Markdown": "Download as Markdown",
"HTML": "HTML",
"Download as HTML": "Download as HTML",
"TextBundle": "TextBundle",
"Download as TextBundle": "Download as TextBundle",
"PDF": "PDF",
"Download as PDF": "Download as PDF",
"Copy as Markdown": "Copy as Markdown",
"Markdown copied to clipboard": "Markdown copied to clipboard",
@@ -103,6 +105,7 @@
"Search in document": "Search in document",
"Print": "Print",
"Print document": "Print document",
"Export document": "Export document",
"Open in desktop app": "Open in desktop app",
"Present": "Present",
"Present document": "Present document",
@@ -196,11 +199,8 @@
"New Application": "New Application",
"Delete app": "Delete app",
"This version of the document was deleted": "This version of the document was deleted",
"HTML": "HTML",
"PDF": "PDF",
"Exporting": "Exporting",
"Markdown": "Markdown",
"Download revision": "Download revision",
"Export revision": "Export revision",
"Dark": "Dark",
"Light": "Light",
"Toggle theme": "Toggle theme",
@@ -411,10 +411,8 @@
"Export started": "Export started",
"A link to your file will be sent through email soon": "A link to your file will be sent through email soon",
"Preparing your download": "Preparing your download",
"Include child documents": "Include child documents",
"When selected, exporting the document will take extra time.": "When selected, exporting the document will take extra time.",
"You will receive an email when it's complete.": "You will receive an email when it's complete.",
"Exporting the collection may take some time.": "Exporting the collection may take some time.",
"You will receive an email when it's complete.": "You will receive an email when it's complete.",
"Include attachments": "Include attachments",
"Including uploaded images and files in the exported data": "Including uploaded images and files in the exported data",
"Include private collections": "Include private collections",
@@ -472,6 +470,7 @@
"View, navigate, or download images in the document": "View, navigate, or download images in the document",
"Zoom in": "Zoom in",
"Zoom out": "Zoom out",
"Download": "Download",
"Edit diagram": "Edit diagram",
"Close": "Close",
"Previous": "Previous",