Sfoglia il codice sorgente

Merge pull request #5901 from weseek/feat/gw7812-get-mentioned-users-from-comment-and-send-notification

feat: gw7812 get mentioned users from comment and send notification
Mudana-Grune 3 anni fa
parent
commit
d22597a00c
1 ha cambiato i file con 25 aggiunte e 8 eliminazioni
  1. 25 8
      packages/app/src/server/service/comment.ts

+ 25 - 8
packages/app/src/server/service/comment.ts

@@ -7,6 +7,8 @@ import { stringifySnapshot } from '~/models/serializers/in-app-notification-snap
 import loggerFactory from '../../utils/logger';
 import loggerFactory from '../../utils/logger';
 import Crowi from '../crowi';
 import Crowi from '../crowi';
 
 
+// https://regex101.com/r/Ztxj2j/1
+const USERNAME_PATTERN = new RegExp(/\B@[\w@.-]+/g);
 
 
 const logger = loggerFactory('growi:service:CommentService');
 const logger = loggerFactory('growi:service:CommentService');
 
 
@@ -99,19 +101,34 @@ class CommentService {
     let targetUsers: Types.ObjectId[] = [];
     let targetUsers: Types.ObjectId[] = [];
     targetUsers = await activity.getNotificationTargetUsers();
     targetUsers = await activity.getNotificationTargetUsers();
 
 
-    // TODO get mentioned users from comment
-    // const mentionedUsers = await this.getMentionedUsers(page.event);
-    // targetUsers = targetUsers.concat(mentionedUsers);
-    // Create and send notifications
+    // Add mentioned users to targetUsers
+    const mentionedUsers = await this.getMentionedUsers(activity.event);
+    targetUsers = targetUsers.concat(mentionedUsers);
+
     await this.inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
     await this.inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
     await this.inAppNotificationService.emitSocketIo(targetUsers);
     await this.inAppNotificationService.emitSocketIo(targetUsers);
   };
   };
 
 
-  private getMentionedUsers = async(comment: Types.ObjectId) => {
-    // TODO extract users from comment model
-    // Implement User model to find users ID
+  getMentionedUsers = async(commentId: Types.ObjectId): Promise<Types.ObjectId[]> => {
+    const Comment = getModelSafely('Comment') || require('../models/comment')(this.crowi);
+    const User = getModelSafely('User') || require('../models/user')(this.crowi);
+
+    // Get comment by comment ID
+    const commentData = await Comment.findOne({ _id: commentId });
+    const { comment } = commentData;
+
+    const usernamesFromComment = comment.match(USERNAME_PATTERN);
 
 
-    // return User ObjectID array
+    // Get username from comment and remove duplicate username
+    const mentionedUsernames = [...new Set(usernamesFromComment?.map((username) => {
+      return username.slice(1);
+    }))];
+
+    // Get mentioned users ID
+    const mentionedUserIDs = await User.find({ username: { $in: mentionedUsernames } });
+    return mentionedUserIDs?.map((user) => {
+      return user._id;
+    });
   }
   }
 
 
 }
 }