diff --git a/app/scenes/Settings/components/ImportNotionDialog.tsx b/app/scenes/Settings/components/ImportNotionDialog.tsx deleted file mode 100644 index b0bc119f6c..0000000000 --- a/app/scenes/Settings/components/ImportNotionDialog.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import * as React from "react"; -import { Trans, useTranslation } from "react-i18next"; -import { FileOperationFormat } from "@shared/types"; -import useStores from "~/hooks/useStores"; -import DropToImport from "./DropToImport"; -import HelpDisclosure from "./HelpDisclosure"; - -function ImportNotionDialog() { - const { t } = useTranslation(); - const { dialogs } = useStores(); - - return ( - <> - Where do I find the file?}> - , - }} - /> - - - <> - {t( - `Drag and drop the zip file from Notion's HTML export option, or click to upload` - )} - - - - ); -} - -export default ImportNotionDialog; diff --git a/plugins/notion/server/tasks/NotionAPIImportTask.ts b/plugins/notion/server/tasks/NotionAPIImportTask.ts index 2ade378ce6..5198563ab4 100644 --- a/plugins/notion/server/tasks/NotionAPIImportTask.ts +++ b/plugins/notion/server/tasks/NotionAPIImportTask.ts @@ -1,6 +1,8 @@ +import { APIResponseError, APIErrorCode } from "@notionhq/client"; import { ImportTaskInput, ImportTaskOutput } from "@shared/schema"; import { IntegrationService, ProsemirrorDoc } from "@shared/types"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; +import Logger from "@server/logging/Logger"; import { Integration } from "@server/models"; import ImportTask from "@server/models/ImportTask"; import APIImportTask, { @@ -39,7 +41,10 @@ export default class NotionAPIImportTask extends APIImportTask this.processPage({ item, client })) ); - const taskOutput: ImportTaskOutput = parsedPages.map((parsedPage) => ({ + // Filter out any null results (from pages/databases that couldn't be accessed) + const validParsedPages = parsedPages.filter(Boolean) as ParsePageOutput[]; + + const taskOutput: ImportTaskOutput = validParsedPages.map((parsedPage) => ({ externalId: parsedPage.externalId, title: parsedPage.title, emoji: parsedPage.emoji, @@ -50,7 +55,7 @@ export default class NotionAPIImportTask extends APIImportTask = - parsedPages.flatMap((parsedPage) => + validParsedPages.flatMap((parsedPage) => parsedPage.children.map((childPage) => ({ type: childPage.type, externalId: childPage.externalId, @@ -88,36 +93,55 @@ export default class NotionAPIImportTask extends APIImportTask[number]; client: NotionClient; - }): Promise { + }): Promise { const collectionExternalId = item.collectionExternalId ?? item.externalId; - // Convert Notion database to an empty page with "pages in database" as its children. - if (item.type === PageType.Database) { - const { pages, ...databaseInfo } = await client.fetchDatabase( - item.externalId - ); + try { + // Convert Notion database to an empty page with "pages in database" as its children. + if (item.type === PageType.Database) { + const { pages, ...databaseInfo } = await client.fetchDatabase( + item.externalId + ); + + return { + ...databaseInfo, + externalId: item.externalId, + content: ProsemirrorHelper.getEmptyDocument() as ProsemirrorDoc, + collectionExternalId, + children: pages.map((page) => ({ + type: page.type, + externalId: page.id, + })), + }; + } + + const { blocks, ...pageInfo } = await client.fetchPage(item.externalId); return { - ...databaseInfo, + ...pageInfo, externalId: item.externalId, - content: ProsemirrorHelper.getEmptyDocument() as ProsemirrorDoc, + content: NotionConverter.page({ children: blocks } as NotionPage), collectionExternalId, - children: pages.map((page) => ({ - type: page.type, - externalId: page.id, - })), + children: this.parseChildPages(blocks), }; + } catch (error) { + if (error instanceof APIResponseError) { + // Skip this page/database if it's not found or not accessible + if ( + error.code === APIErrorCode.ObjectNotFound || + error.code === APIErrorCode.Unauthorized + ) { + Logger.warn( + `Skipping Notion ${ + item.type === PageType.Database ? "database" : "page" + } ${item.externalId} - Error code: ${error.code} - ${error.message}` + ); + return null; + } + } + // Re-throw other errors to be handled by the parent try/catch + throw error; } - - const { blocks, ...pageInfo } = await client.fetchPage(item.externalId); - - return { - ...pageInfo, - externalId: item.externalId, - content: NotionConverter.page({ children: blocks } as NotionPage), - collectionExternalId, - children: this.parseChildPages(blocks), - }; } /** diff --git a/server/collaboration/ConnectionLimitExtension.test.ts b/server/collaboration/ConnectionLimitExtension.test.ts new file mode 100644 index 0000000000..e3027acb48 --- /dev/null +++ b/server/collaboration/ConnectionLimitExtension.test.ts @@ -0,0 +1,109 @@ +import { Server } from "@hocuspocus/server"; +import WebSocket from "ws"; +import EDITOR_VERSION from "@shared/editor/version"; +import { sleep } from "@server/utils/timers"; +import { ConnectionLimitExtension } from "./ConnectionLimitExtension"; +import { EditorVersionExtension } from "./EditorVersionExtension"; + +jest.mock("@server/env", () => ({ + COLLABORATION_MAX_CLIENTS_PER_DOCUMENT: 2, +})); + +describe("ConnectionLimitExtension", () => { + let server: typeof Server; + let extension: ConnectionLimitExtension; + const port = 12345; + const url = `ws://localhost:${port}`; + const documentName = "test"; + + beforeEach(async () => { + extension = new ConnectionLimitExtension(); + server = Server.configure({ + port, + extensions: [extension, new EditorVersionExtension()], + }); + await server.listen(); + }); + + afterEach(async () => { + await server.destroy(); + }); + + const getConnections = () => + extension.connectionsByDocument.get(documentName)?.size ?? 0; + + const createWebSocket = (editorVersion = EDITOR_VERSION) => + new Promise((resolve, reject) => { + const ws = new WebSocket( + `${url}/${documentName}?editorVersion=${editorVersion}` + ); + ws.on("open", () => resolve(ws)); + ws.on("error", reject); + }); + + it("should allow connections within limit", async () => { + const ws1 = await createWebSocket(); + const ws2 = await createWebSocket(); + + expect(ws1.readyState).toBe(WebSocket.OPEN); + expect(ws2.readyState).toBe(WebSocket.OPEN); + expect(getConnections()).toBe(2); + + ws1.close(); + ws2.close(); + + await sleep(250); + expect(getConnections()).toBe(0); + }); + + it("should close connections exceeding limit", async () => { + const ws1 = await createWebSocket(); + const ws2 = await createWebSocket(); + + const ws3 = await createWebSocket(); + await sleep(250); + + expect(ws3.readyState).toBe(WebSocket.CLOSED); + expect(ws2.readyState).toBe(WebSocket.OPEN); + expect(ws1.readyState).toBe(WebSocket.OPEN); + expect(getConnections()).toBe(2); + + ws1.close(); + ws2.close(); + + await sleep(250); + expect(getConnections()).toBe(0); + }); + + it("should handle connections closed by other extensions", async () => { + const ws1 = await createWebSocket(); + + // Create a connection that will be closed by the EditorVersionExtension + const ws2 = await createWebSocket("1.0.0"); + + ws1.close(); + ws2.close(); + + await sleep(250); + expect(getConnections()).toBe(0); + }); + + it("should allow new connection after disconnect", async () => { + const ws1 = await createWebSocket(); + const ws2 = await createWebSocket(); + + ws1.close(); + await sleep(250); + expect(getConnections()).toBe(1); + + const ws3 = await createWebSocket(); + expect(ws3.readyState).toBe(WebSocket.OPEN); + expect(getConnections()).toBe(2); + + ws2.close(); + ws3.close(); + + await sleep(250); + expect(getConnections()).toBe(0); + }); +}); diff --git a/server/collaboration/ConnectionLimitExtension.ts b/server/collaboration/ConnectionLimitExtension.ts index b4628e42bf..a86a2dc3a8 100644 --- a/server/collaboration/ConnectionLimitExtension.ts +++ b/server/collaboration/ConnectionLimitExtension.ts @@ -1,8 +1,10 @@ import { Extension, + connectedPayload, onConnectPayload, onDisconnectPayload, } from "@hocuspocus/server"; +import pluralize from "pluralize"; import { TooManyConnections } from "@shared/collaboration/CloseEvents"; import env from "@server/env"; import Logger from "@server/logging/Logger"; @@ -14,7 +16,7 @@ export class ConnectionLimitExtension implements Extension { /** * Map of documentId -> connection count */ - connectionsByDocument: Map> = new Map(); + public connectionsByDocument: Map> = new Map(); /** * On disconnect hook @@ -34,23 +36,30 @@ export class ConnectionLimitExtension implements Extension { } } + const connectionCount = connections?.size ?? 0; Logger.debug( "multiplayer", - `${connections?.size} connections to "${documentName}"` + `${connectionCount} ${pluralize( + "connection", + connectionCount + )} to "${documentName}"` ); return Promise.resolve(); } /** - * On connect hook + * onConnect hook is called when a new connection has been established. + * This is where we can check if the document has reached the maximum number of + * connections and reject the connection if it has. * - * @param data The connect payload - * @returns Promise, resolving will allow the connection, rejecting will drop it + * @param data The onConnect payload + * @returns Promise, resolving will allow the connection, rejecting will drop. */ - onConnect({ documentName, socketId }: withContext) { + onConnect({ documentName }: withContext) { const connections = this.connectionsByDocument.get(documentName) || new Set(); + if (connections?.size >= env.COLLABORATION_MAX_CLIENTS_PER_DOCUMENT) { Logger.info( "multiplayer", @@ -61,12 +70,30 @@ export class ConnectionLimitExtension implements Extension { return Promise.reject(TooManyConnections); } + return Promise.resolve(); + } + + /** + * Connected hook is called after a new connection has been established. + * We can safely update the connection count for the document. + * + * @param data The onConnect payload + * @returns Promise + */ + connected({ documentName, socketId }: withContext) { + const connections = + this.connectionsByDocument.get(documentName) || new Set(); + connections.add(socketId); this.connectionsByDocument.set(documentName, connections); + const connectionCount = connections.size ?? 0; Logger.debug( "multiplayer", - `${connections.size} connections to "${documentName}"` + `${connectionCount} ${pluralize( + "connection", + connectionCount + )} to "${documentName}"` ); return Promise.resolve(); diff --git a/server/commands/teamCreator.ts b/server/commands/teamCreator.ts index f78f984ac6..ac8804ea12 100644 --- a/server/commands/teamCreator.ts +++ b/server/commands/teamCreator.ts @@ -3,7 +3,6 @@ import slugify from "slugify"; import { RESERVED_SUBDOMAINS } from "@shared/utils/domains"; import { traceFunction } from "@server/logging/tracing"; import { Team, Event } from "@server/models"; -import { generateAvatarUrl } from "@server/utils/avatars"; type Props = { /** The displayed name of the team */ @@ -29,20 +28,14 @@ type Props = { async function teamCreator({ name, - domain, subdomain, avatarUrl, authenticationProviders, ip, transaction, }: Props): Promise { - // If the service did not provide a logo/avatar then we attempt to generate - // one via ClearBit, or fallback to colored initials in worst case scenario - if (!avatarUrl || !avatarUrl.startsWith("http")) { - avatarUrl = await generateAvatarUrl({ - domain, - id: subdomain, - }); + if (!avatarUrl?.startsWith("http")) { + avatarUrl = null; } const team = await Team.create( diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index a57beebbc6..e8704c9214 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -3,14 +3,13 @@ import compact from "lodash/compact"; import flatten from "lodash/flatten"; import isEqual from "lodash/isEqual"; import uniq from "lodash/uniq"; -import { Node, DOMSerializer, Fragment, Mark } from "prosemirror-model"; +import { Node, DOMSerializer, Fragment } from "prosemirror-model"; import * as React from "react"; import { renderToString } from "react-dom/server"; import styled, { ServerStyleSheet, ThemeProvider } from "styled-components"; import { prosemirrorToYDoc } from "y-prosemirror"; import * as Y from "yjs"; import EditorContainer from "@shared/editor/components/Styles"; -import embeds from "@shared/editor/embeds"; import GlobalStyles from "@shared/styles/globals"; import light from "@shared/styles/theme"; import { MentionType, ProsemirrorData } from "@shared/types"; @@ -61,47 +60,7 @@ export class ProsemirrorHelper { ); } - let node = parser.parse(input); - - // in the editor embeds are created at runtime by converting links into - // embeds where they match.Because we're converting to a CRDT structure on - // the server we need to mimic this behavior. - function urlsToEmbeds(node: Node): Node { - if (node.type.name === "paragraph") { - for (const textNode of node.content.content) { - for (const embed of embeds) { - if ( - textNode.text && - textNode.marks.some( - (m: Mark) => - m.type.name === "link" && m.attrs.href === textNode.text - ) && - embed.matcher(textNode.text) - ) { - return schema.nodes.embed.createAndFill({ - href: textNode.text, - }) as Node; - } - } - } - } - - if (node.content) { - const contentAsArray = - node.content instanceof Fragment - ? node.content.content - : node.content; - // @ts-expect-error content - node.content = Fragment.fromArray(contentAsArray.map(urlsToEmbeds)); - } - - return node; - } - - if (node) { - node = urlsToEmbeds(node); - } - + const node = parser.parse(input); return node ? prosemirrorToYDoc(node, fieldName) : new Y.Doc(); } diff --git a/server/queues/processors/FileOperationCreatedProcessor.ts b/server/queues/processors/FileOperationCreatedProcessor.ts index f88ed8011b..ed0ef08871 100644 --- a/server/queues/processors/FileOperationCreatedProcessor.ts +++ b/server/queues/processors/FileOperationCreatedProcessor.ts @@ -6,7 +6,6 @@ import ExportJSONTask from "../tasks/ExportJSONTask"; import ExportMarkdownZipTask from "../tasks/ExportMarkdownZipTask"; import ImportJSONTask from "../tasks/ImportJSONTask"; import ImportMarkdownZipTask from "../tasks/ImportMarkdownZipTask"; -import ImportNotionTask from "../tasks/ImportNotionTask"; import BaseProcessor from "./BaseProcessor"; export default class FileOperationCreatedProcessor extends BaseProcessor { @@ -25,11 +24,6 @@ export default class FileOperationCreatedProcessor extends BaseProcessor { fileOperationId: event.modelId, }); break; - case FileOperationFormat.Notion: - await ImportNotionTask.schedule({ - fileOperationId: event.modelId, - }); - break; case FileOperationFormat.JSON: await ImportJSONTask.schedule({ fileOperationId: event.modelId, diff --git a/server/queues/processors/ImportsProcessor.ts b/server/queues/processors/ImportsProcessor.ts index 15e585d070..4aa617148b 100644 --- a/server/queues/processors/ImportsProcessor.ts +++ b/server/queues/processors/ImportsProcessor.ts @@ -3,7 +3,12 @@ import chunk from "lodash/chunk"; import keyBy from "lodash/keyBy"; import truncate from "lodash/truncate"; import { Fragment, Node } from "prosemirror-model"; -import { CreateOptions, CreationAttributes, Transaction } from "sequelize"; +import { + CreateOptions, + CreationAttributes, + Transaction, + UniqueConstraintError, +} from "sequelize"; import { v4 as uuidv4 } from "uuid"; import { randomElement } from "@shared/random"; import { ImportInput, ImportTaskInput } from "@shared/schema"; @@ -154,45 +159,59 @@ export default abstract class ImportsProcessor< * @returns Promise that resolves when mapping and persistence is completed. */ private async onProcessed(importModel: Import, transaction: Transaction) { - const { collections } = await this.createCollectionsAndDocuments({ - importModel, - transaction, - }); - - // Once all collections and documents are created, update collection's document structure. - // This ensures the root documents have the whole subtree available in the structure. - for (const collection of collections) { - await Document.unscoped().findAllInBatches( - { - where: { parentDocumentId: null, collectionId: collection.id }, - order: [ - ["createdAt", "DESC"], - ["id", "ASC"], - ], - transaction, - }, - async (documents) => { - for (const document of documents) { - await collection.addDocumentToStructure(document, 0, { - save: false, - silent: true, - transaction, - }); - } - } - ); - - await collection.save({ silent: true, transaction }); - } - - importModel.state = ImportState.Completed; - importModel.error = null; // unset any error from previous attempts. - await importModel.saveWithCtx( - createContext({ - user: importModel.createdBy, + try { + const { collections } = await this.createCollectionsAndDocuments({ + importModel, transaction, - }) - ); + }); + + // Once all collections and documents are created, update collection's document structure. + // This ensures the root documents have the whole subtree available in the structure. + for (const collection of collections) { + await Document.unscoped().findAllInBatches( + { + where: { parentDocumentId: null, collectionId: collection.id }, + order: [ + ["createdAt", "DESC"], + ["id", "ASC"], + ], + transaction, + }, + async (documents) => { + for (const document of documents) { + await collection.addDocumentToStructure(document, 0, { + save: false, + silent: true, + transaction, + }); + } + } + ); + + await collection.save({ silent: true, transaction }); + } + + importModel.state = ImportState.Completed; + importModel.error = null; // unset any error from previous attempts. + await importModel.saveWithCtx( + createContext({ + user: importModel.createdBy, + transaction, + }) + ); + } catch (err) { + if (err instanceof UniqueConstraintError) { + Logger.error( + "ImportsProcessor persistence failed due to unique constraint error", + err, + { + fields: err.fields, + } + ); + } + + throw err; + } } /** @@ -304,6 +323,15 @@ export default abstract class ImportsProcessor< const output = outputMap[externalId]; + // Skip this item if it has no output (likely due to an error during processing) + if (!output) { + Logger.debug( + "processor", + `Skipping item with no output: ${externalId}` + ); + continue; + } + const collectionItem = importInput[externalId]; const attachments = await Attachment.findAll({ @@ -444,7 +472,7 @@ export default abstract class ImportsProcessor< importInput: Record[number]>; actorId: string; }): ProsemirrorDoc { - // special case when the doc content is empty + // special case when the doc content is empty. if (!content.content.length) { return content; } diff --git a/server/queues/tasks/APIImportTask.ts b/server/queues/tasks/APIImportTask.ts index 7c1fa338ae..54856a8d69 100644 --- a/server/queues/tasks/APIImportTask.ts +++ b/server/queues/tasks/APIImportTask.ts @@ -170,7 +170,7 @@ export default abstract class APIImportTask< await importTask.save({ transaction }); const associatedImport = importTask.import; - associatedImport.documentCount += importTask.input.length; + associatedImport.documentCount += taskOutputWithReplacements.length; await associatedImport.saveWithCtx( createContext({ user: associatedImport.createdBy, diff --git a/server/queues/tasks/ImportNotionTask.test.ts b/server/queues/tasks/ImportNotionTask.test.ts deleted file mode 100644 index 01181bfa9a..0000000000 --- a/server/queues/tasks/ImportNotionTask.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* eslint-disable @typescript-eslint/no-empty-function */ -import path from "path"; -import { FileOperation } from "@server/models"; -import { buildFileOperation } from "@server/test/factories"; -import ImportNotionTask from "./ImportNotionTask"; - -describe("ImportNotionTask", () => { - it("should import successfully from a Markdown export", async () => { - const fileOperation = await buildFileOperation(); - Object.defineProperty(fileOperation, "handle", { - get() { - return { - path: path.resolve( - __dirname, - "..", - "..", - "test", - "fixtures", - "notion-markdown.zip" - ), - cleanup: async () => {}, - }; - }, - }); - jest.spyOn(FileOperation, "findByPk").mockResolvedValue(fileOperation); - - const props = { - fileOperationId: fileOperation.id, - }; - - const task = new ImportNotionTask(); - const response = await task.perform(props); - - expect(response.collections.size).toEqual(2); - expect(response.documents.size).toEqual(6); - expect(response.attachments.size).toEqual(1); - - // Check that the image url was replaced in the text with a redirect - const attachments = Array.from(response.attachments.values()); - const documents = Array.from(response.documents.values()); - expect(documents.map((d) => d.text).join("")).toContain( - attachments[0].redirectUrl - ); - }); - - it("should import successfully from a HTML export", async () => { - const fileOperation = await buildFileOperation(); - Object.defineProperty(fileOperation, "handle", { - get() { - return { - path: path.resolve( - __dirname, - "..", - "..", - "test", - "fixtures", - "notion-html.zip" - ), - cleanup: async () => {}, - }; - }, - }); - jest.spyOn(FileOperation, "findByPk").mockResolvedValue(fileOperation); - - const props = { - fileOperationId: fileOperation.id, - }; - - const task = new ImportNotionTask(); - const response = await task.perform(props); - - expect(response.collections.size).toEqual(2); - expect(response.documents.size).toEqual(6); - expect(response.attachments.size).toEqual(4); - - // Check that the image url was replaced in the text with a redirect - const attachments = Array.from(response.attachments.values()); - const attachment = attachments.find((att) => - att.key.endsWith("Screen_Shot_2022-04-21_at_2.23.26_PM.png") - ); - - const documents = Array.from(response.documents.values()); - expect(documents.map((d) => d.text).join("")).toContain( - attachment?.redirectUrl - ); - }); -}); diff --git a/server/queues/tasks/ImportNotionTask.ts b/server/queues/tasks/ImportNotionTask.ts deleted file mode 100644 index 36ccd640ee..0000000000 --- a/server/queues/tasks/ImportNotionTask.ts +++ /dev/null @@ -1,354 +0,0 @@ -import path from "path"; -import fs from "fs-extra"; -import compact from "lodash/compact"; -import escapeRegExp from "lodash/escapeRegExp"; -import mime from "mime-types"; -import { v4 as uuidv4 } from "uuid"; -import documentImporter from "@server/commands/documentImporter"; -import { createContext } from "@server/context"; -import Logger from "@server/logging/Logger"; -import { FileOperation, User } from "@server/models"; -import { sequelize } from "@server/storage/database"; -import ImportHelper, { FileTreeNode } from "@server/utils/ImportHelper"; -import ImportTask, { StructuredImportData } from "./ImportTask"; - -export default class ImportNotionTask extends ImportTask { - public async parseData( - dirPath: string, - fileOperation: FileOperation - ): Promise { - const tree = await ImportHelper.toFileTree(dirPath); - if (!tree) { - throw new Error("Could not find valid content in zip file"); - } - - // New Notion exports have a single folder with the name of the export, we must skip this - // folder and go directly to the children. - let parsed; - if ( - tree.children.length === 1 && - tree.children[0].children.find((child) => child.title === "index") - ) { - parsed = await this.parseFileTree( - fileOperation, - tree.children[0].children.filter((child) => child.title !== "index") - ); - } else { - parsed = await this.parseFileTree(fileOperation, tree.children); - } - - if (parsed.documents.length === 0 && parsed.collections.length === 1) { - const collection = parsed.collections[0]; - const collectionId = uuidv4(); - if (collection.description) { - parsed.documents.push({ - title: collection.name, - icon: collection.icon, - color: collection.color, - path: "", - text: String(collection.description), - id: collection.id, - externalId: collection.externalId, - mimeType: "text/html", - collectionId, - }); - } - - collection.name = "Notion"; - collection.icon = undefined; - collection.color = undefined; - collection.externalId = undefined; - collection.description = undefined; - collection.id = collectionId; - } - - return parsed; - } - - /** - * Converts the file structure from zipAsFileTree into documents, - * collections, and attachments. - * - * @param fileOperation The file operation - * @param tree An array of FileTreeNode representing root files in the zip - * @returns A StructuredImportData object - */ - private async parseFileTree( - fileOperation: FileOperation, - tree: FileTreeNode[] - ): Promise { - const user = await User.findByPk(fileOperation.userId, { - rejectOnEmpty: true, - }); - - const output: StructuredImportData = { - collections: [], - documents: [], - attachments: [], - }; - - const parseNodeChildren = async ( - children: FileTreeNode[], - collectionId: string, - parentDocumentId?: string - ): Promise => { - await Promise.all( - children.map(async (child) => { - // Ignore the CSV's for databases upfront - if (child.path.endsWith(".csv")) { - return; - } - - const id = uuidv4(); - const match = child.title.match(this.NotionUUIDRegex); - const name = child.title.replace(this.NotionUUIDRegex, ""); - const externalId = match ? match[0].trim() : undefined; - - // If it's not a text file we're going to treat it as an attachment. - const mimeType = mime.lookup(child.name); - const isDocument = - mimeType === "text/markdown" || - mimeType === "text/plain" || - mimeType === "text/html"; - - // If it's not a document and not a folder, treat it as an attachment - if (!isDocument && mimeType) { - output.attachments.push({ - id, - name: child.name, - path: child.path, - mimeType, - buffer: () => fs.readFile(child.path), - externalId, - }); - return; - } - - Logger.debug("task", `Processing ${name} as ${mimeType}`); - - const { title, icon, text } = await sequelize.transaction( - async (transaction) => - documentImporter({ - mimeType: mimeType || "text/markdown", - fileName: name, - content: - child.children.length > 0 - ? "" - : await fs.readFile(child.path, "utf8"), - user, - ctx: createContext({ user, transaction }), - }) - ); - - const existingDocumentIndex = output.documents.findIndex( - (doc) => doc.externalId === externalId - ); - - const existingDocument = output.documents[existingDocumentIndex]; - - // If there is an existing document with the same externalId that means - // we've already parsed either a folder or a file referencing the same - // document, as such we should merge. - if (existingDocument) { - if (existingDocument.text === "") { - output.documents[existingDocumentIndex].text = text; - } - - await parseNodeChildren( - child.children, - collectionId, - existingDocument.id - ); - } else { - output.documents.push({ - id, - title, - icon, - text, - collectionId, - parentDocumentId, - path: child.path, - mimeType: mimeType || "text/markdown", - externalId, - }); - await parseNodeChildren(child.children, collectionId, id); - } - }) - ); - }; - - const replaceInternalLinksAndImages = (text: string) => { - // Find if there are any images in this document - const imagesInText = this.parseImages(text); - - for (const image of imagesInText) { - const name = path.basename(image.src); - const attachment = output.attachments.find( - (att) => - att.path.endsWith(image.src) || - encodeURI(att.path).endsWith(image.src) - ); - - if (!attachment) { - if (!image.src.startsWith("http")) { - Logger.info( - "task", - `Could not find referenced attachment with name ${name} and src ${image.src}` - ); - } - } else { - text = text.replace( - new RegExp(escapeRegExp(image.src), "g"), - `<<${attachment.id}>>` - ); - } - } - - // With Notion's HTML import, images sometimes come wrapped in anchor tags - // This isn't supported in Outline's editor, so we need to strip them. - text = text.replace(/\[!\[([^[]+)]/g, "![]"); - - // Find if there are any links in this document pointing to other documents - const internalLinksInText = this.parseInternalLinks(text); - - // For each link update to the standardized format of <> - // instead of a relative or absolute URL within the original zip file. - for (const link of internalLinksInText) { - const doc = output.documents.find( - (doc) => doc.externalId === link.externalId - ); - - if (!doc) { - Logger.info( - "task", - `Could not find referenced document with externalId ${link.externalId}` - ); - } else { - text = text.replace(link.href, `<<${doc.id}>>`); - } - } - - return text; - }; - - // All nodes in the root level should become collections - for (const node of tree) { - const match = node.title.match(this.NotionUUIDRegex); - const name = node.title.replace(this.NotionUUIDRegex, ""); - const externalId = match ? match[0].trim() : undefined; - const mimeType = mime.lookup(node.name); - - const existingCollectionIndex = output.collections.findIndex( - (collection) => collection.externalId === externalId - ); - const existingCollection = output.collections[existingCollectionIndex]; - const collectionId = existingCollection?.id || uuidv4(); - let description; - - // Root level docs become the descriptions of collections - if ( - mimeType === "text/markdown" || - mimeType === "text/plain" || - mimeType === "text/html" - ) { - const { text } = await sequelize.transaction(async (transaction) => - documentImporter({ - mimeType, - fileName: name, - content: await fs.readFile(node.path, "utf8"), - user, - ctx: createContext({ user, transaction }), - }) - ); - - description = text; - } else if (node.children.length > 0) { - await parseNodeChildren(node.children, collectionId); - } else { - Logger.debug("task", `Unhandled file in zip: ${node.path}`, { - fileOperationId: fileOperation.id, - }); - continue; - } - - if (existingCollectionIndex !== -1) { - if (description) { - output.collections[existingCollectionIndex].description = description; - } - } else { - output.collections.push({ - id: collectionId, - name, - description, - externalId, - }); - } - } - - for (const document of output.documents) { - document.text = replaceInternalLinksAndImages(document.text); - } - - for (const collection of output.collections) { - if (typeof collection.description === "string") { - collection.description = replaceInternalLinksAndImages( - collection.description - ); - } - } - - return output; - } - - /** - * Extracts internal links from a markdown document, taking into account the - * externalId of the document, which is part of the link title. - * - * @param text The markdown text to parse - * @returns An array of internal links - */ - private parseInternalLinks( - text: string - ): { title: string; href: string; externalId: string }[] { - return compact( - [...text.matchAll(this.NotionLinkRegex)].map((match) => ({ - title: match[1], - href: match[2], - externalId: match[3], - })) - ); - } - - /** - * Extracts images from the markdown document - * - * @param text The markdown text to parse - * @returns An array of internal links - */ - private parseImages(text: string): { alt: string; src: string }[] { - return compact( - [...text.matchAll(this.ImageRegex)].map((match) => ({ - alt: match[1], - src: match[2], - })) - ); - } - - /** - * Regex to find markdown images of all types - */ - private ImageRegex = - /!\[(?[^\][]*?)]\((?[^\][]*?)(?=“|\))“?(?[^\][”]+)?”?\)/g; - - /** - * Regex to find markdown links containing ID's that look like UUID's with the - * "-"'s removed, Notion's externalId format. - */ - private NotionLinkRegex = /\[([^[]+)]\((.*?([0-9a-fA-F]{32})\..*?)\)/g; - - /** - * Regex to find Notion document UUID's in the title of a document. - */ - private NotionUUIDRegex = - /\s([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}|[0-9a-fA-F]{32})$/; -} diff --git a/server/test/fixtures/notion-html.zip b/server/test/fixtures/notion-html.zip deleted file mode 100644 index 7ad29a287b..0000000000 Binary files a/server/test/fixtures/notion-html.zip and /dev/null differ diff --git a/server/test/fixtures/notion-markdown.zip b/server/test/fixtures/notion-markdown.zip deleted file mode 100644 index aaa6daa175..0000000000 Binary files a/server/test/fixtures/notion-markdown.zip and /dev/null differ diff --git a/server/utils/avatars.test.ts b/server/utils/avatars.test.ts deleted file mode 100644 index 9bffe6c891..0000000000 --- a/server/utils/avatars.test.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { generateAvatarUrl } from "./avatars"; - -it("should return clearbit url if available", async () => { - const url = await generateAvatarUrl({ - id: "google", - domain: "google.com", - }); - expect(url).toBe("https://logo.clearbit.com/google.com"); -}); diff --git a/server/utils/avatars.ts b/server/utils/avatars.ts deleted file mode 100644 index fee5a372b1..0000000000 --- a/server/utils/avatars.ts +++ /dev/null @@ -1,28 +0,0 @@ -import crypto from "crypto"; -import fetch from "./fetch"; - -export async function generateAvatarUrl({ - id, - domain, -}: { - id: string; - domain?: string; -}) { - // attempt to get logo from Clearbit API. If one doesn't exist then - // fall back to using tiley to generate a placeholder logo - const hash = crypto.createHash("sha256"); - hash.update(id); - let cbResponse, cbUrl; - - if (domain) { - cbUrl = `https://logo.clearbit.com/${domain}`; - - try { - cbResponse = await fetch(cbUrl); - } catch (err) { - // okay - } - } - - return cbUrl && cbResponse && cbResponse.status === 200 ? cbUrl : null; -} diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index c26e736bfd..383d56e123 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -957,9 +957,6 @@ "{{ count }} document imported_plural": "{{ count }} documents imported", "You can import a zip file that was previously exported from an Outline installation – collections, documents, and images will be imported. In Outline, open <em>Export</em> in the Settings sidebar and click on <em>Export Data</em>.": "You can import a zip file that was previously exported from an Outline installation – collections, documents, and images will be imported. In Outline, open <em>Export</em> in the Settings sidebar and click on <em>Export Data</em>.", "Drag and drop the zip file from the Markdown export option in {{appName}}, or click to upload": "Drag and drop the zip file from the Markdown export option in {{appName}}, or click to upload", - "Where do I find the file?": "Where do I find the file?", - "In Notion, click <em>Settings & Members</em> in the left sidebar and open Settings. Look for the Export section, and click <em>Export all workspace content</em>. Choose <em>HTML</em> as the format for the best data compatability.": "In Notion, click <em>Settings & Members</em> in the left sidebar and open Settings. Look for the Export section, and click <em>Export all workspace content</em>. Choose <em>HTML</em> as the format for the best data compatability.", - "Drag and drop the zip file from Notion's HTML export option, or click to upload": "Drag and drop the zip file from Notion's HTML export option, or click to upload", "Last active": "Last active", "Guest": "Guest", "Are you sure you want to delete the {{ appName }} application? This cannot be undone.": "Are you sure you want to delete the {{ appName }} application? This cannot be undone.",