Simplify email references determination (#8189)

* Simplify email references determination

* individual thread for comments

* use toPlainText
This commit is contained in:
Hemachandar authored and GitHub committed 2025-01-07 05:29:04 -08:00
1 parent 48feaf9bc0
commit 4afa225967
6 files changed
+142 -457

No files matched your search

+1 -2
View File
@@ -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
+22 -10
View File
@@ -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 {
+83 -339
View File
@@ -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);
});
});
});
+34 -57
View File
@@ -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<string[] | undefined> {
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<Notification>(
{
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;
}
}
+2 -2
View File
@@ -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);
-47
View File
@@ -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}>`;
};