From 4afa2259672f3ed8cfc3a7cd53221bbe37374df2 Mon Sep 17 00:00:00 2001 From: Hemachandar <132386067+hmacr@users.noreply.github.com> Date: Tue, 7 Jan 2025 18:59:04 +0530 Subject: [PATCH] Simplify email references determination (#8189) * Simplify email references determination * individual thread for comments * use toPlainText --- server/emails/templates/BaseEmail.tsx | 3 +- .../emails/templates/CommentCreatedEmail.tsx | 32 +- server/models/Notification.test.ts | 422 ++++-------------- server/models/Notification.ts | 91 ++-- server/models/helpers/DocumentHelper.tsx | 4 +- server/utils/emails.ts | 47 -- 6 files changed, 142 insertions(+), 457 deletions(-) delete mode 100644 server/utils/emails.ts diff --git a/server/emails/templates/BaseEmail.tsx b/server/emails/templates/BaseEmail.tsx index 0744bfb51f..8a2176bd4d 100644 --- a/server/emails/templates/BaseEmail.tsx +++ b/server/emails/templates/BaseEmail.tsx @@ -18,7 +18,6 @@ import { TextHelper } from "@server/models/helpers/TextHelper"; import { taskQueue } from "@server/queues"; import { TaskPriority } from "@server/queues/tasks/BaseTask"; import { NotificationMetadata } from "@server/types"; -import { getEmailMessageId } from "@server/utils/emails"; export enum EmailMessageCategory { Authentication = "authentication", @@ -138,7 +137,7 @@ export default abstract class BaseEmail< } const messageId = notification - ? getEmailMessageId(notification.id) + ? Notification.emailMessageId(notification.id) : undefined; const references = notification diff --git a/server/emails/templates/CommentCreatedEmail.tsx b/server/emails/templates/CommentCreatedEmail.tsx index 3396caa272..67615e56d5 100644 --- a/server/emails/templates/CommentCreatedEmail.tsx +++ b/server/emails/templates/CommentCreatedEmail.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { NotificationEventType } from "@shared/types"; import { Collection, Comment, Document } from "@server/models"; +import { DocumentHelper } from "@server/models/helpers/DocumentHelper"; import NotificationSettingsHelper from "@server/models/helpers/NotificationSettingsHelper"; import { ProsemirrorHelper } from "@server/models/helpers/ProsemirrorHelper"; import { can } from "@server/policies"; @@ -14,6 +15,8 @@ import Footer from "./components/Footer"; import Header from "./components/Header"; import Heading from "./components/Heading"; +const MAX_SUBJECT_CONTENT = 50; + type InputProps = EmailProps & { userId: string; documentId: string; @@ -23,10 +26,11 @@ type InputProps = EmailProps & { }; type BeforeSend = { + comment: Comment; + parentComment?: Comment; document: Document; collection: Collection | null; body: string | undefined; - isFirstComment: boolean; isReply: boolean; unsubscribeUrl: string; }; @@ -61,24 +65,22 @@ export default class CommentCreatedEmail extends BaseEmail< return false; } - const firstComment = await Comment.findOne({ - attributes: ["id"], - where: { documentId }, - order: [["createdAt", "ASC"]], - }); + const parentComment = comment.parentCommentId + ? (await comment.$get("parentComment")) ?? undefined + : undefined; const body = await this.htmlForData( team, ProsemirrorHelper.toProsemirror(comment.data) ); const isReply = !!comment.parentCommentId; - const isFirstComment = firstComment?.id === commentId; return { + comment, + parentComment, document, collection, isReply, - isFirstComment, body, unsubscribeUrl: this.unsubscribeUrl(props), }; @@ -91,8 +93,18 @@ export default class CommentCreatedEmail extends BaseEmail< ); } - protected subject({ isFirstComment, document }: Props) { - return `${isFirstComment ? "" : "Re: "}New comment on “${document.title}”`; + protected subject({ comment, parentComment, document }: Props) { + const commentText = DocumentHelper.toPlainText( + parentComment?.data ?? comment.data + ); + const trimmedText = + commentText.length <= MAX_SUBJECT_CONTENT + ? commentText + : `${commentText.slice(0, MAX_SUBJECT_CONTENT)}...`; + + return `${parentComment ? "Re: " : ""}New comment on “${ + document.title + }” - ${trimmedText}`; } protected preview({ isReply, actorName }: Props): string { diff --git a/server/models/Notification.test.ts b/server/models/Notification.test.ts index 89fe47223c..61a5b31def 100644 --- a/server/models/Notification.test.ts +++ b/server/models/Notification.test.ts @@ -1,396 +1,140 @@ import { NotificationEventType } from "@shared/types"; import { - buildCollection, buildComment, buildDocument, buildNotification, - buildTeam, buildUser, } from "@server/test/factories"; -import { - getEmailMessageId, - MaxMessagesInEmailThread, -} from "@server/utils/emails"; import Notification from "./Notification"; describe("Notification", () => { describe("emailReferences", () => { - it("should return no references for an unsupported notification", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, - }); - const document = await buildDocument({ - collectionId: collection.id, - userId: user.id, - teamId: team.id, - }); - + it("should return no reference for an unsupported notification", async () => { const notification = await buildNotification({ event: NotificationEventType.AddUserToDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, }); const references = await Notification.emailReferences(notification); - expect(references).toBeUndefined(); }); - it("should return no references for a new notification", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, - }); - const document = await buildDocument({ - collectionId: collection.id, - userId: user.id, - teamId: team.id, - }); - - const notification = await buildNotification({ - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }); - const references = await Notification.emailReferences(notification); - - expect(references).toBeUndefined(); - }); - - describe("should return references from last thread for current notification", () => { - it("only one thread available", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, + describe("should return document update reference", () => { + it("document published", async () => { + const document = await buildDocument(); + const notification = await buildNotification({ + event: NotificationEventType.PublishDocument, + documentId: document.id, }); - const document = await buildDocument({ - collectionId: collection.id, - userId: user.id, - teamId: team.id, - }); - const pastNotifications = await Notification.bulkCreate( - [...Array(2)].map(() => ({ - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - })) + + const references = await Notification.emailReferences(notification); + + const expectedReference = Notification.emailMessageId( + `${document.id}-updates` ); + expect(references![0]).toBe(expectedReference); + }); + it("document updated", async () => { + const document = await buildDocument(); const notification = await buildNotification({ event: NotificationEventType.UpdateDocument, documentId: document.id, - userId: user.id, - teamId: team.id, }); + const references = await Notification.emailReferences(notification); - expect(references?.length).toEqual(2); - - const expectedReferences = pastNotifications.map((notif) => - getEmailMessageId(notif.id) + const expectedReference = Notification.emailMessageId( + `${document.id}-updates` ); - - expect(references).toEqual(expectedReferences); - }); - - it("multiple threads available", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, - }); - const document = await buildDocument({ - collectionId: collection.id, - userId: user.id, - teamId: team.id, - }); - const pastNotifications = await Notification.bulkCreate( - [...Array(105)].map(() => ({ - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - })) - ); - - const notification = await buildNotification({ - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }); - const references = await Notification.emailReferences(notification); - - expect(references?.length).toEqual(5); - - const expectedReferences = pastNotifications - .slice(MaxMessagesInEmailThread) - .map((notif) => getEmailMessageId(notif.id)); - - expect(references).toEqual(expectedReferences); + expect(references![0]).toBe(expectedReference); }); }); - describe("should return references from consolidated events", () => { - it("document edits", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, - }); - const document = await buildDocument({ - collectionId: collection.id, - userId: user.id, - teamId: team.id, - }); - const pastNotifications = await Notification.bulkCreate([ - { - event: NotificationEventType.PublishDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - ...[...Array(2)].map(() => ({ - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - })), - ...[...Array(2)].map(() => ({ - event: NotificationEventType.CreateComment, - documentId: document.id, - userId: user.id, - teamId: team.id, - })), - ]); - - const notification = await buildNotification({ - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }); - const references = await Notification.emailReferences(notification); - - expect(references?.length).toEqual(3); - - const expectedReferences = pastNotifications - .filter( - (notif) => - notif.event === NotificationEventType.PublishDocument || - notif.event === NotificationEventType.UpdateDocument - ) - .map((notif) => getEmailMessageId(notif.id)); - - expect(references).toEqual(expectedReferences); - }); - - it("comment creation", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, - }); - const document = await buildDocument({ - collectionId: collection.id, - userId: user.id, - teamId: team.id, - }); - const pastNotifications = await Notification.bulkCreate([ - { - event: NotificationEventType.PublishDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - ...[...Array(2)].map(() => ({ - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - })), - ...[...Array(2)].map(() => ({ - event: NotificationEventType.CreateComment, - documentId: document.id, - userId: user.id, - teamId: team.id, - })), - ]); - - const notification = await buildNotification({ - event: NotificationEventType.CreateComment, - documentId: document.id, - userId: user.id, - teamId: team.id, - }); - const references = await Notification.emailReferences(notification); - - expect(references?.length).toEqual(2); - - const expectedReferences = pastNotifications - .filter( - (notif) => notif.event === NotificationEventType.CreateComment - ) - .map((notif) => getEmailMessageId(notif.id)); - - expect(references).toEqual(expectedReferences); - }); - - it("document mentions", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, - }); - const document = await buildDocument({ - collectionId: collection.id, - userId: user.id, - teamId: team.id, - }); - const comment = await buildComment({ - documentId: document.id, - userId: user.id, - }); - const pastNotifications = await Notification.bulkCreate([ - { - event: NotificationEventType.PublishDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.CreateComment, - commentId: comment.id, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.MentionedInComment, - commentId: comment.id, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.MentionedInDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - ]); - + describe("should return mention reference", () => { + it("mentioned in document", async () => { + const document = await buildDocument(); const notification = await buildNotification({ event: NotificationEventType.MentionedInDocument, documentId: document.id, - userId: user.id, - teamId: team.id, }); const references = await Notification.emailReferences(notification); - expect(references?.length).toEqual(2); - - const expectedReferences = pastNotifications - .filter( - (notif) => - notif.event === NotificationEventType.MentionedInDocument || - notif.event === NotificationEventType.MentionedInComment - ) - .map((notif) => getEmailMessageId(notif.id)); - - expect(references).toEqual(expectedReferences); + const expectedReference = Notification.emailMessageId( + `${document.id}-mentions` + ); + expect(references?.length).toBe(1); + expect(references![0]).toBe(expectedReference); }); - it("comment mentions", async () => { - const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); - const collection = await buildCollection({ - userId: user.id, - teamId: team.id, + it("mentioned in comment", async () => { + const document = await buildDocument(); + const notification = await buildNotification({ + event: NotificationEventType.MentionedInComment, + documentId: document.id, }); + + const references = await Notification.emailReferences(notification); + + const expectedReference = Notification.emailMessageId( + `${document.id}-mentions` + ); + expect(references?.length).toBe(1); + expect(references![0]).toBe(expectedReference); + }); + }); + + describe("should return comment reference", () => { + it("first comment in a thread", async () => { + const user = await buildUser(); const document = await buildDocument({ - collectionId: collection.id, userId: user.id, - teamId: team.id, + teamId: user.teamId, }); const comment = await buildComment({ documentId: document.id, userId: user.id, }); - const pastNotifications = await Notification.bulkCreate([ - { - event: NotificationEventType.PublishDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.UpdateDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.CreateComment, - commentId: comment.id, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.MentionedInComment, - commentId: comment.id, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - { - event: NotificationEventType.MentionedInDocument, - documentId: document.id, - userId: user.id, - teamId: team.id, - }, - ]); - const notification = await buildNotification({ - event: NotificationEventType.MentionedInComment, - documentId: document.id, - userId: user.id, - teamId: team.id, + event: NotificationEventType.CreateComment, + commentId: comment.id, }); + const references = await Notification.emailReferences(notification); - expect(references?.length).toEqual(2); + const expectedReference = Notification.emailMessageId( + `${comment.id}-comments` + ); + expect(references?.length).toBe(1); + expect(references![0]).toBe(expectedReference); + }); - const expectedReferences = pastNotifications - .filter( - (notif) => - notif.event === NotificationEventType.MentionedInComment || - notif.event === NotificationEventType.MentionedInDocument - ) - .map((notif) => getEmailMessageId(notif.id)); + it("child comments in a thread", async () => { + const user = await buildUser(); + const document = await buildDocument({ + userId: user.id, + teamId: user.teamId, + }); + const parentComment = await buildComment({ + documentId: document.id, + userId: user.id, + }); + const childComment = await buildComment({ + documentId: document.id, + userId: user.id, + parentCommentId: parentComment.id, + }); + const notification = await buildNotification({ + event: NotificationEventType.CreateComment, + commentId: childComment.id, + }); - expect(references).toEqual(expectedReferences); + const references = await Notification.emailReferences(notification); + + const expectedReference = Notification.emailMessageId( + `${parentComment.id}-comments` + ); + expect(references?.length).toBe(1); + expect(references![0]).toBe(expectedReference); }); }); }); diff --git a/server/models/Notification.ts b/server/models/Notification.ts index 2f31f8bd4e..ee6007705b 100644 --- a/server/models/Notification.ts +++ b/server/models/Notification.ts @@ -1,11 +1,9 @@ import crypto from "crypto"; -import chunk from "lodash/chunk"; import type { InferAttributes, InferCreationAttributes, SaveOptions, } from "sequelize"; -import { Op } from "sequelize"; import { Table, ForeignKey, @@ -22,14 +20,9 @@ import { DefaultScope, } from "sequelize-typescript"; import { NotificationEventType } from "@shared/types"; +import { getBaseDomain } from "@shared/utils/domains"; import env from "@server/env"; import Model from "@server/models/base/Model"; -import { - getEmailMessageId, - getEmailThreadEventGroup, - isEmailThreadSupportedNotification, - MaxMessagesInEmailThread, -} from "@server/utils/emails"; import Collection from "./Collection"; import Comment from "./Comment"; import Document from "./Document"; @@ -39,6 +32,8 @@ import Team from "./Team"; import User from "./User"; import Fix from "./decorators/Fix"; +let baseDomain; + @Scopes(() => ({ withTeam: { include: [ @@ -228,62 +223,44 @@ class Notification extends Model< } /** - * Returns the past message ids which are used to setup the thread chain in email clients. + * Returns the message id for the email. * - * @param notification Notification for which the past notifications are fetched - used for determining the properties that form a thread. - * @returns An array of email message ids that form a thread. + * @param name Username part of the email address. + * @returns Email message id. + */ + public static emailMessageId(name: string) { + baseDomain ||= getBaseDomain(); + return `<${name}@${baseDomain}>`; + } + + /** + * Returns the message reference id which will be used to setup the thread chain in email clients. + * + * @param notification Notification for which to determine the reference id. + * @returns Reference id as an array. */ public static async emailReferences( notification: Notification ): Promise { - if (!isEmailThreadSupportedNotification(notification.event)) { - return; + let name: string | undefined; + + switch (notification.event) { + case NotificationEventType.PublishDocument: + case NotificationEventType.UpdateDocument: + name = `${notification.documentId}-updates`; + break; + case NotificationEventType.MentionedInDocument: + case NotificationEventType.MentionedInComment: + name = `${notification.documentId}-mentions`; + break; + case NotificationEventType.CreateComment: { + const comment = await Comment.findByPk(notification.commentId); + name = `${comment?.parentCommentId ?? comment?.id}-comments`; + break; + } } - const events = getEmailThreadEventGroup(notification.event); - - if (!events) { - return; - } - - const prevNotifications: Notification[] = []; - - await this.findAllInBatches( - { - attributes: ["id"], - where: { - id: { - [Op.ne]: notification.id, - }, - event: { - [Op.in]: events, - }, - documentId: notification.documentId, - userId: notification.userId, - }, - order: [["createdAt", "ASC"]], - offset: 0, - batchLimit: 100, - }, - async (notifications) => void prevNotifications.push(...notifications) - ); - - const emailThreads = chunk(prevNotifications, MaxMessagesInEmailThread); - const lastThread = emailThreads.at(-1); - - // Don't return anything if there are no past notifications (or) the limit is reached. - // This will start a new thread in the email clients. - // Also ensures we don't face header limit errors. - if ( - !lastThread || - lastThread.length === 0 || - lastThread.length === MaxMessagesInEmailThread - ) { - return; - } - - // Return references from the last thread. - return lastThread.map((notif) => getEmailMessageId(notif.id)); + return name ? [this.emailMessageId(name)] : undefined; } } diff --git a/server/models/helpers/DocumentHelper.tsx b/server/models/helpers/DocumentHelper.tsx index d25a0e30e7..ae4eab013d 100644 --- a/server/models/helpers/DocumentHelper.tsx +++ b/server/models/helpers/DocumentHelper.tsx @@ -132,10 +132,10 @@ export class DocumentHelper { * Returns the document as plain text. This method uses the * collaborative state if available, otherwise it falls back to Markdown. * - * @param document The document or revision to convert + * @param document The document or revision or prosemirror data to convert * @returns The document content as plain text without formatting. */ - static toPlainText(document: Document | Revision) { + static toPlainText(document: Document | Revision | ProsemirrorData) { const node = DocumentHelper.toProsemirror(document); return textBetween(node, 0, node.content.size, this.textSerializers); diff --git a/server/utils/emails.ts b/server/utils/emails.ts deleted file mode 100644 index 9e2af126b8..0000000000 --- a/server/utils/emails.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { NotificationEventType } from "@shared/types"; -import { getBaseDomain } from "@shared/utils/domains"; - -const EmailThreadSupportedNotifications = [ - NotificationEventType.PublishDocument, - NotificationEventType.UpdateDocument, - NotificationEventType.MentionedInDocument, - NotificationEventType.CreateComment, - NotificationEventType.MentionedInComment, -]; - -// Gmail creates a new thread for every 100 messages. -export const MaxMessagesInEmailThread = 100; - -export const isEmailThreadSupportedNotification = ( - event: NotificationEventType -) => EmailThreadSupportedNotifications.includes(event); - -export const getEmailThreadEventGroup = ( - event: NotificationEventType -): NotificationEventType[] | undefined => { - switch (event) { - case NotificationEventType.PublishDocument: - case NotificationEventType.UpdateDocument: - return [ - NotificationEventType.PublishDocument, - NotificationEventType.UpdateDocument, - ]; - case NotificationEventType.MentionedInDocument: - case NotificationEventType.MentionedInComment: - return [ - NotificationEventType.MentionedInDocument, - NotificationEventType.MentionedInComment, - ]; - case NotificationEventType.CreateComment: - return [NotificationEventType.CreateComment]; - default: - return; - } -}; - -let baseDomain; - -export const getEmailMessageId = (notificationId: string) => { - baseDomain ||= getBaseDomain(); - return `<${notificationId}@${baseDomain}>`; -};