diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 74d7fc4ead..ebf4c9a5f0 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -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: , - 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: , - content: ( - - ), - }); - }, -}); - 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: , + keywords: "md markdown export download", + icon: , + 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: , + keywords: "xml html export download", + icon: , + 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: , + keywords: "textbundle textpack bear ulysses export download", + icon: , + 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: , + keywords: "pdf export download", + icon: , + iconInContextMenu: false, visible: ({ activeDocumentId, stores }) => !!( activeDocumentId && @@ -1091,12 +1070,29 @@ export const printDocument = createAction({ analyticsName: "Print document", section: ActiveDocumentSection, icon: , + 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: , + 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, diff --git a/app/actions/definitions/revisions.tsx b/app/actions/definitions/revisions.tsx index 300efeaa5a..96bff4050a 100644 --- a/app/actions/definitions/revisions.tsx +++ b/app/actions/definitions/revisions.tsx @@ -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: , - 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: , + 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: , + keywords: "download export", children: [ - downloadRevisionAsHTMLActionFactory(revisionId), - downloadRevisionAsPDFActionFactory(revisionId), downloadRevisionAsMarkdownActionFactory(revisionId), + downloadRevisionAsHTMLActionFactory(revisionId), + downloadRevisionAsTextBundleActionFactory(revisionId), + downloadRevisionAsPDFActionFactory(revisionId), + ActionSeparator, + printRevisionActionFactory(revisionId), ], }); diff --git a/app/components/Export/DocumentDownload.tsx b/app/components/Export/DocumentDownload.tsx deleted file mode 100644 index 66621745df..0000000000 --- a/app/components/Export/DocumentDownload.tsx +++ /dev/null @@ -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( - "document-download-format", - ExportContentType.Markdown - ); - const [includeChildDocuments, setIncludeChildDocuments] = - useState(hasChildDocuments); - - const formats = useMemo(() => { - const items: FileFormat[] = [ - { - title: "Markdown", - extension: ".md", - value: ExportContentType.Markdown, - icon: , - }, - { - title: "HTML", - extension: ".html", - value: ExportContentType.Html, - icon: , - }, - { - title: "TextBundle", - extension: ".textpack", - value: ExportContentType.TextBundle, - icon: , - }, - ]; - - if (env.PDF_EXPORT_ENABLED) { - items.push({ - title: "PDF", - extension: ".pdf", - value: ExportContentType.Pdf, - icon: , - }); - } - - 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) => { - 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 ( - - - {hasChildDocuments && ( - <> -
- - - )} -
- ); -}); - -const Option = styled.label` - display: flex; - align-items: baseline; - gap: 16px; - - p { - margin: 0; - } -`; - -const StyledInput = styled.input` - position: relative; - top: 1.5px; -`; diff --git a/app/components/Icons/MarkdownIcon.tsx b/app/components/Icons/MarkdownIcon.tsx index 1b0d28490f..060f57b884 100644 --- a/app/components/Icons/MarkdownIcon.tsx +++ b/app/components/Icons/MarkdownIcon.tsx @@ -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} > - + ); } diff --git a/app/hooks/useDocumentMenuAction.tsx b/app/hooks/useDocumentMenuAction.tsx index 375df62b60..831b4e21df 100644 --- a/app/hooks/useDocumentMenuAction.tsx +++ b/app/hooks/useDocumentMenuAction.tsx @@ -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, diff --git a/app/menus/RevisionMenu.tsx b/app/menus/RevisionMenu.tsx index 116343313d..7939ac4adb 100644 --- a/app/menus/RevisionMenu.tsx +++ b/app/menus/RevisionMenu.tsx @@ -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] ); diff --git a/app/scenes/Document/components/History/RevisionListItem.tsx b/app/scenes/Document/components/History/RevisionListItem.tsx index 87576d3343..7155a45cfd 100644 --- a/app/scenes/Document/components/History/RevisionListItem.tsx +++ b/app/scenes/Document/components/History/RevisionListItem.tsx @@ -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] ); diff --git a/server/models/helpers/AttachmentHelper.ts b/server/models/helpers/AttachmentHelper.ts index ced41f6606..49c61fb008 100644 --- a/server/models/helpers/AttachmentHelper.ts +++ b/server/models/helpers/AttachmentHelper.ts @@ -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 { + 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(""); + } + } } diff --git a/server/models/helpers/TextBundleHelper.ts b/server/models/helpers/TextBundleHelper.ts index 9d4ea97088..b6affae559 100644 --- a/server/models/helpers/TextBundleHelper.ts +++ b/server/models/helpers/TextBundleHelper.ts @@ -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 diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 8938914b08..a565090e58 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -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( diff --git a/server/routes/api/revisions/revisions.test.ts b/server/routes/api/revisions/revisions.test.ts index 407d3b3584..e8107d6fe2 100644 --- a/server/routes/api/revisions/revisions.test.ts +++ b/server/routes/api/revisions/revisions.test.ts @@ -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({ diff --git a/server/routes/api/revisions/revisions.ts b/server/routes/api/revisions/revisions.ts index b31cf58f78..bb8e798929 100644 --- a/server/routes/api/revisions/revisions.ts +++ b/server/routes/api/revisions/revisions.ts @@ -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(); + + 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"), diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index bc3c15acd5..940caa2d76 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -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",