A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
feat: Add user comment moderation
Luffybec3e355a9ac
diff --git a/cmd/wire_gen.go b/cmd/wire_gen.goindex 947b6605..0379c11a 100644--- a/cmd/wire_gen.go+++ b/cmd/wire_gen.go@@ -192,22 +192,22 @@ func initApplication(debug bool, serverConf *conf.Server, dbConf *data.Database,objService := object_info.NewObjService(answerRepo, questionRepo, commentCommonRepo, tagCommonRepo, tagCommonService)notificationQueueService := notice_queue.NewNotificationQueueService()externalNotificationQueueService := notice_queue.NewNewQuestionNotificationQueueService()- commentService := comment2.NewCommentService(commentRepo, commentCommonRepo, userCommon, objService, voteRepo, emailService, userRepo, notificationQueueService, externalNotificationQueueService, activityQueueService, eventQueueService)rolePowerRelRepo := role.NewRolePowerRelRepo(dataData)rolePowerRelService := role2.NewRolePowerRelService(rolePowerRelRepo, userRoleRelService)rankService := rank2.NewRankService(userCommon, userRankRepo, objService, userRoleRelService, rolePowerRelService, configService)limitRepo := limit.NewRateLimitRepo(dataData)rateLimitMiddleware := middleware.NewRateLimitMiddleware(limitRepo)- commentController := controller.NewCommentController(commentService, rankService, captchaService, rateLimitMiddleware)reportRepo := report.NewReportRepo(dataData, uniqueIDRepo)tagService := tag2.NewTagService(tagRepo, tagCommonService, revisionService, followRepo, siteInfoCommonService, activityQueueService)answerActivityRepo := activity.NewAnswerActivityRepo(dataData, activityRepo, userRankRepo, notificationQueueService)answerActivityService := activity2.NewAnswerActivityService(answerActivityRepo, configService)externalNotificationService := notification.NewExternalNotificationService(dataData, userNotificationConfigRepo, followRepo, emailService, userRepo, externalNotificationQueueService, userExternalLoginRepo, siteInfoCommonService)reviewRepo := review.NewReviewRepo(dataData)- reviewService := review2.NewReviewService(reviewRepo, objService, userCommon, userRepo, questionRepo, answerRepo, userRoleRelService, externalNotificationQueueService, tagCommonService, questionCommon, notificationQueueService, siteInfoCommonService)+ reviewService := review2.NewReviewService(reviewRepo, objService, userCommon, userRepo, questionRepo, answerRepo, userRoleRelService, externalNotificationQueueService, tagCommonService, questionCommon, notificationQueueService, siteInfoCommonService, commentCommonRepo)questionService := content.NewQuestionService(activityRepo, questionRepo, answerRepo, tagCommonService, tagService, questionCommon, userCommon, userRepo, userRoleRelService, revisionService, metaCommonService, collectionCommon, answerActivityService, emailService, notificationQueueService, externalNotificationQueueService, activityQueueService, siteInfoCommonService, externalNotificationService, reviewService, configService, eventQueueService, reviewRepo)answerService := content.NewAnswerService(answerRepo, questionRepo, questionCommon, userCommon, collectionCommon, userRepo, revisionService, answerActivityService, answerCommon, voteRepo, emailService, userRoleRelService, notificationQueueService, externalNotificationQueueService, activityQueueService, reviewService, eventQueueService)+ commentService := comment2.NewCommentService(commentRepo, commentCommonRepo, userCommon, objService, voteRepo, emailService, userRepo, notificationQueueService, externalNotificationQueueService, activityQueueService, eventQueueService, reviewService)+ commentController := controller.NewCommentController(commentService, rankService, captchaService, rateLimitMiddleware)reportHandle := report_handle.NewReportHandle(questionService, answerService, commentService)reportService := report2.NewReportService(reportRepo, objService, userCommon, answerRepo, questionRepo, commentCommonRepo, reportHandle, configService, eventQueueService)reportController := controller.NewReportController(reportService, rankService, captchaService)diff --git a/internal/controller/comment_controller.go b/internal/controller/comment_controller.goindex 288e8aee..5b807d93 100644--- a/internal/controller/comment_controller.go+++ b/internal/controller/comment_controller.go@@ -20,6 +20,8 @@package controllerimport (+ "net/http"+"github.com/apache/answer/internal/base/handler""github.com/apache/answer/internal/base/middleware""github.com/apache/answer/internal/base/reason"@@ -34,7 +36,6 @@ import ("github.com/apache/answer/pkg/uid""github.com/gin-gonic/gin""github.com/segmentfault/pacman/errors"- "net/http")// CommentController comment controller@@ -120,6 +121,9 @@ func (cc *CommentController) AddComment(ctx *gin.Context) {return}+ req.UserAgent = ctx.GetHeader("User-Agent")+ req.IP = ctx.ClientIP()+resp, err := cc.commentService.AddComment(ctx, req)if !isAdmin || !linkUrlLimitUser {cc.actionService.ActionRecordAdd(ctx, entity.CaptchaActionComment, req.UserID)diff --git a/internal/entity/comment_entity.go b/internal/entity/comment_entity.goindex c96f6b3c..248016f8 100644--- a/internal/entity/comment_entity.go+++ b/internal/entity/comment_entity.go@@ -87,3 +87,8 @@ func (c *Comment) SetReplyCommentID(str string) {c.ReplyCommentID = sql.NullInt64{Valid: false}}}++// GetMentionUsernameList get mention username list+func (c *Comment) GetMentionUsernameList() []string {+ return converter.GetMentionUsernameList(c.OriginalText)+}diff --git a/internal/repo/comment/comment_repo.go b/internal/repo/comment/comment_repo.goindex f1794824..10b7b304 100644--- a/internal/repo/comment/comment_repo.go+++ b/internal/repo/comment/comment_repo.go@@ -92,6 +92,17 @@ func (cr *commentRepo) UpdateCommentContent(return}+// UpdateCommentStatus update comment status+func (cr *commentRepo) UpdateCommentStatus(ctx context.Context, commentID string, status int) (err error) {+ _, err = cr.data.DB.Context(ctx).ID(commentID).Update(&entity.Comment{+ Status: status,+ })+ if err != nil {+ err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack()+ }+ return+}+// GetComment get comment onefunc (cr *commentRepo) GetComment(ctx context.Context, commentID string) (comment *entity.Comment, exist bool, err error) {diff --git a/internal/schema/comment_schema.go b/internal/schema/comment_schema.goindex 104e3f33..015da071 100644--- a/internal/schema/comment_schema.go+++ b/internal/schema/comment_schema.go@@ -51,6 +51,9 @@ type AddCommentReq struct {CanEdit bool `json:"-"`// whether user can delete itCanDelete bool `json:"-"`++ IP string `json:"-"`+ UserAgent string `json:"-"`}func (req *AddCommentReq) Check() (errFields []*validator.FormErrorField, err error) {diff --git a/internal/service/comment/comment_service.go b/internal/service/comment/comment_service.goindex ba9bbe1d..3a5b3e6c 100644--- a/internal/service/comment/comment_service.go+++ b/internal/service/comment/comment_service.go@@ -21,7 +21,10 @@ package commentimport ("context"+"github.com/apache/answer/internal/service/event_queue"+ "github.com/apache/answer/internal/service/review"+"time""github.com/apache/answer/internal/base/constant"@@ -50,6 +53,7 @@ type CommentRepo interface {AddComment(ctx context.Context, comment *entity.Comment) (err error)RemoveComment(ctx context.Context, commentID string) (err error)UpdateCommentContent(ctx context.Context, commentID string, original string, parsedText string) (err error)+ UpdateCommentStatus(ctx context.Context, commentID string, status int) (err error)GetComment(ctx context.Context, commentID string) (comment *entity.Comment, exist bool, err error)GetCommentPage(ctx context.Context, commentQuery *CommentQuery) (comments []*entity.Comment, total int64, err error)@@ -88,6 +92,7 @@ type CommentService struct {externalNotificationQueueService notice_queue.ExternalNotificationQueueServiceactivityQueueService activity_queue.ActivityQueueServiceeventQueueService event_queue.EventQueueService+ reviewService *review.ReviewService}// NewCommentService new comment service@@ -103,6 +108,7 @@ func NewCommentService(externalNotificationQueueService notice_queue.ExternalNotificationQueueService,activityQueueService activity_queue.ActivityQueueService,eventQueueService event_queue.EventQueueService,+ reviewService *review.ReviewService,) *CommentService {return &CommentService{commentRepo: commentRepo,@@ -116,6 +122,7 @@ func NewCommentService(externalNotificationQueueService: externalNotificationQueueService,activityQueueService: activityQueueService,eventQueueService: eventQueueService,+ reviewService: reviewService,}}@@ -160,14 +167,21 @@ func (cs *CommentService) AddComment(ctx context.Context, req *schema.AddCommentreturn nil, err}+ comment.Status = cs.reviewService.AddCommentReview(ctx, comment, req.IP, req.UserAgent)+ if err := cs.commentRepo.UpdateCommentStatus(ctx, comment.ID, comment.Status); err != nil {+ return nil, err+ }+resp = &schema.GetCommentResp{}resp.SetFromComment(comment)resp.MemberActions = permission.GetCommentPermission(ctx, req.UserID, resp.UserID,time.Now(), req.CanEdit, req.CanDelete)- commentResp, err := cs.addCommentNotification(ctx, req, resp, comment, objInfo)- if err != nil {- return commentResp, err+ if comment.Status == entity.CommentStatusAvailable {+ commentResp, err := cs.addCommentNotification(ctx, req, resp, comment, objInfo)+ if err != nil {+ return commentResp, err+ }}// get user infodiff --git a/internal/service/comment_common/comment_service.go b/internal/service/comment_common/comment_service.goindex 0b6423a4..623d0081 100644--- a/internal/service/comment_common/comment_service.go+++ b/internal/service/comment_common/comment_service.go@@ -34,6 +34,7 @@ type CommentCommonRepo interface {GetCommentWithoutStatus(ctx context.Context, commentID string) (comment *entity.Comment, exist bool, err error)GetCommentCount(ctx context.Context) (count int64, err error)RemoveAllUserComment(ctx context.Context, userID string) (err error)+ UpdateCommentStatus(ctx context.Context, commentID string, status int) (err error)}// CommentCommonService user servicediff --git a/internal/service/review/review_service.go b/internal/service/review/review_service.goindex 7f934f23..40089fb2 100644--- a/internal/service/review/review_service.go+++ b/internal/service/review/review_service.go@@ -28,6 +28,7 @@ import ("github.com/apache/answer/internal/entity""github.com/apache/answer/internal/schema"answercommon "github.com/apache/answer/internal/service/answer_common"+ commentcommon "github.com/apache/answer/internal/service/comment_common""github.com/apache/answer/internal/service/notice_queue""github.com/apache/answer/internal/service/object_info"questioncommon "github.com/apache/answer/internal/service/question_common"@@ -68,6 +69,7 @@ type ReviewService struct {externalNotificationQueueService notice_queue.ExternalNotificationQueueServicenotificationQueueService notice_queue.NotificationQueueServicesiteInfoService siteinfo_common.SiteInfoCommonService+ commentCommonRepo commentcommon.CommentCommonRepo}// NewReviewService new review service@@ -84,6 +86,7 @@ func NewReviewService(questionCommon *questioncommon.QuestionCommon,notificationQueueService notice_queue.NotificationQueueService,siteInfoService siteinfo_common.SiteInfoCommonService,+ commentCommonRepo commentcommon.CommentCommonRepo,) *ReviewService {return &ReviewService{reviewRepo: reviewRepo,@@ -98,6 +101,7 @@ func NewReviewService(questionCommon: questionCommon,notificationQueueService: notificationQueueService,siteInfoService: siteInfoService,+ commentCommonRepo: commentCommonRepo,}}@@ -153,6 +157,30 @@ func (cs *ReviewService) AddAnswerReview(ctx context.Context,return answerStatus}+// AddCommentReview add review for comment if needed+func (cs *ReviewService) AddCommentReview(ctx context.Context,+ comment *entity.Comment, ip, ua string) (commentStatus int) {+ reviewContent := &plugin.ReviewContent{+ ObjectType: constant.CommentObjectType,+ Content: comment.ParsedText,+ IP: ip,+ UserAgent: ua,+ }+ reviewContent.Author = cs.getReviewContentAuthorInfo(ctx, comment.UserID)+ reviewStatus := cs.callPluginToReview(ctx, comment.UserID, comment.ID, reviewContent)+ switch reviewStatus {+ case plugin.ReviewStatusApproved:+ commentStatus = entity.CommentStatusAvailable+ case plugin.ReviewStatusNeedReview:+ commentStatus = entity.CommentStatusPending+ case plugin.ReviewStatusDeleteDirectly:+ commentStatus = entity.CommentStatusDeleted+ default:+ commentStatus = entity.CommentStatusAvailable+ }+ return commentStatus+}+// get review content author infofunc (cs *ReviewService) getReviewContentAuthorInfo(ctx context.Context, userID string) (author plugin.ReviewContentAuthor) {user, exist, err := cs.userCommon.GetUserBasicInfoByID(ctx, userID)@@ -314,6 +342,32 @@ func (cs *ReviewService) updateObjectStatus(ctx context.Context, review *entity.log.Errorf("update user answer count failed, err: %v", err)}}+ case constant.CommentObjectType:+ commentInfo, exist, err := cs.commentCommonRepo.GetCommentWithoutStatus(ctx, review.ObjectID)+ if err != nil {+ return err+ }+ if !exist {+ return errors.BadRequest(reason.ObjectNotFound)+ }+ if isApprove {+ commentInfo.Status = entity.CommentStatusAvailable+ } else {+ commentInfo.Status = entity.CommentStatusDeleted+ }+ if err := cs.commentCommonRepo.UpdateCommentStatus(ctx, commentInfo.ID, commentInfo.Status); err != nil {+ return err+ }+ _, exist, err = cs.questionRepo.GetQuestion(ctx, commentInfo.QuestionID)+ if err != nil {+ return err+ }+ if !exist {+ return errors.BadRequest(reason.ObjectNotFound)+ }+ if isApprove {+ cs.notificationCommentOnTheQuestion(ctx, commentInfo)+ }}return}@@ -364,6 +418,222 @@ func (cs *ReviewService) notificationAnswerTheQuestion(ctx context.Context,cs.externalNotificationQueueService.Send(ctx, externalNotificationMsg)}+func (cs *ReviewService) notificationCommentOnTheQuestion(ctx context.Context, comment *entity.Comment) {+ objInfo, err := cs.objectInfoService.GetInfo(ctx, comment.ObjectID)+ if err != nil {+ log.Error(err)+ return+ }+ if objInfo.IsDeleted() {+ log.Error("object already deleted")+ return+ }+ objInfo.ObjectID = uid.DeShortID(objInfo.ObjectID)+ objInfo.QuestionID = uid.DeShortID(objInfo.QuestionID)+ objInfo.AnswerID = uid.DeShortID(objInfo.AnswerID)++ // The priority of the notification+ // 1. reply to user+ // 2. comment mention to user+ // 3. answer or question was commented+ alreadyNotifiedUserID := make(map[string]bool)++ // get reply user info+ replyUserID := comment.GetReplyUserID()+ if len(replyUserID) > 0 && replyUserID != comment.UserID {+ replyUser, _, err := cs.userCommon.GetUserBasicInfoByID(ctx, replyUserID)+ if err != nil {+ log.Error(err)+ return+ }+ cs.notificationCommentReply(ctx, replyUser.ID, comment.ID, comment.UserID,+ objInfo.QuestionID, objInfo.Title, htmltext.FetchExcerpt(comment.ParsedText, "...", 240))+ alreadyNotifiedUserID[replyUser.ID] = true+ return+ }++ mentionUsernameList := comment.GetMentionUsernameList()+ if len(mentionUsernameList) > 0 {+ alreadyNotifiedUserIDs := cs.notificationMention(+ ctx, mentionUsernameList, comment.ID, comment.UserID, alreadyNotifiedUserID)+ for _, userID := range alreadyNotifiedUserIDs {+ alreadyNotifiedUserID[userID] = true+ }+ return+ }++ if objInfo.ObjectType == constant.QuestionObjectType && !alreadyNotifiedUserID[objInfo.ObjectCreatorUserID] {+ cs.notificationQuestionComment(ctx, objInfo.ObjectCreatorUserID,+ objInfo.QuestionID, objInfo.Title, comment.ID, comment.UserID, htmltext.FetchExcerpt(comment.ParsedText, "...", 240))+ } else if objInfo.ObjectType == constant.AnswerObjectType && !alreadyNotifiedUserID[objInfo.ObjectCreatorUserID] {+ cs.notificationAnswerComment(ctx, objInfo.QuestionID, objInfo.Title, objInfo.AnswerID,+ objInfo.ObjectCreatorUserID, comment.ID, comment.UserID, htmltext.FetchExcerpt(comment.ParsedText, "...", 240))+ }+ return+}++func (cs *ReviewService) notificationCommentReply(ctx context.Context, replyUserID, commentID, commentUserID,+ questionID, questionTitle, commentSummary string) {+ msg := &schema.NotificationMsg{+ ReceiverUserID: replyUserID,+ TriggerUserID: commentUserID,+ Type: schema.NotificationTypeInbox,+ ObjectID: commentID,+ }+ msg.ObjectType = constant.CommentObjectType+ msg.NotificationAction = constant.NotificationReplyToYou+ cs.notificationQueueService.Send(ctx, msg)++ // Send external notification.+ receiverUserInfo, exist, err := cs.userRepo.GetByUserID(ctx, replyUserID)+ if err != nil {+ log.Error(err)+ return+ }+ if !exist {+ log.Warnf("user %s not found", replyUserID)+ return+ }+ externalNotificationMsg := &schema.ExternalNotificationMsg{+ ReceiverUserID: receiverUserInfo.ID,+ ReceiverEmail: receiverUserInfo.EMail,+ ReceiverLang: receiverUserInfo.Language,+ }+ rawData := &schema.NewCommentTemplateRawData{+ QuestionTitle: questionTitle,+ QuestionID: questionID,+ CommentID: commentID,+ CommentSummary: commentSummary,+ UnsubscribeCode: token.GenerateToken(),+ }+ commentUser, _, _ := cs.userCommon.GetUserBasicInfoByID(ctx, commentUserID)+ if commentUser != nil {+ rawData.CommentUserDisplayName = commentUser.DisplayName+ }+ externalNotificationMsg.NewCommentTemplateRawData = rawData+ cs.externalNotificationQueueService.Send(ctx, externalNotificationMsg)+}++func (cs *ReviewService) notificationMention(+ ctx context.Context, mentionUsernameList []string, commentID, commentUserID string,+ alreadyNotifiedUserID map[string]bool) (alreadyNotifiedUserIDs []string) {+ for _, username := range mentionUsernameList {+ userInfo, exist, err := cs.userCommon.GetUserBasicInfoByUserName(ctx, username)+ if err != nil {+ log.Error(err)+ continue+ }+ if exist && !alreadyNotifiedUserID[userInfo.ID] {+ msg := &schema.NotificationMsg{+ ReceiverUserID: userInfo.ID,+ TriggerUserID: commentUserID,+ Type: schema.NotificationTypeInbox,+ ObjectID: commentID,+ }+ msg.ObjectType = constant.CommentObjectType+ msg.NotificationAction = constant.NotificationMentionYou+ cs.notificationQueueService.Send(ctx, msg)+ alreadyNotifiedUserIDs = append(alreadyNotifiedUserIDs, userInfo.ID)+ }+ }+ return alreadyNotifiedUserIDs+}++func (cs *ReviewService) notificationQuestionComment(ctx context.Context, questionUserID,+ questionID, questionTitle, commentID, commentUserID, commentSummary string) {+ if questionUserID == commentUserID {+ return+ }+ // send internal notification+ msg := &schema.NotificationMsg{+ ReceiverUserID: questionUserID,+ TriggerUserID: commentUserID,+ Type: schema.NotificationTypeInbox,+ ObjectID: commentID,+ }+ msg.ObjectType = constant.CommentObjectType+ msg.NotificationAction = constant.NotificationCommentQuestion+ cs.notificationQueueService.Send(ctx, msg)++ // send external notification+ receiverUserInfo, exist, err := cs.userRepo.GetByUserID(ctx, questionUserID)+ if err != nil {+ log.Error(err)+ return+ }+ if !exist {+ log.Warnf("user %s not found", questionUserID)+ return+ }++ externalNotificationMsg := &schema.ExternalNotificationMsg{+ ReceiverUserID: receiverUserInfo.ID,+ ReceiverEmail: receiverUserInfo.EMail,+ ReceiverLang: receiverUserInfo.Language,+ }+ rawData := &schema.NewCommentTemplateRawData{+ QuestionTitle: questionTitle,+ QuestionID: questionID,+ CommentID: commentID,+ CommentSummary: commentSummary,+ UnsubscribeCode: token.GenerateToken(),+ }+ commentUser, _, _ := cs.userCommon.GetUserBasicInfoByID(ctx, commentUserID)+ if commentUser != nil {+ rawData.CommentUserDisplayName = commentUser.DisplayName+ }+ externalNotificationMsg.NewCommentTemplateRawData = rawData+ cs.externalNotificationQueueService.Send(ctx, externalNotificationMsg)+}++func (cs *ReviewService) notificationAnswerComment(ctx context.Context,+ questionID, questionTitle, answerID, answerUserID, commentID, commentUserID, commentSummary string) {+ if answerUserID == commentUserID {+ return+ }++ // Send internal notification.+ msg := &schema.NotificationMsg{+ ReceiverUserID: answerUserID,+ TriggerUserID: commentUserID,+ Type: schema.NotificationTypeInbox,+ ObjectID: commentID,+ }+ msg.ObjectType = constant.CommentObjectType+ msg.NotificationAction = constant.NotificationCommentAnswer+ cs.notificationQueueService.Send(ctx, msg)++ // Send external notification.+ receiverUserInfo, exist, err := cs.userRepo.GetByUserID(ctx, answerUserID)+ if err != nil {+ log.Error(err)+ return+ }+ if !exist {+ log.Warnf("user %s not found", answerUserID)+ return+ }+ externalNotificationMsg := &schema.ExternalNotificationMsg{+ ReceiverUserID: receiverUserInfo.ID,+ ReceiverEmail: receiverUserInfo.EMail,+ ReceiverLang: receiverUserInfo.Language,+ }+ rawData := &schema.NewCommentTemplateRawData{+ QuestionTitle: questionTitle,+ QuestionID: questionID,+ AnswerID: answerID,+ CommentID: commentID,+ CommentSummary: commentSummary,+ UnsubscribeCode: token.GenerateToken(),+ }+ commentUser, _, _ := cs.userCommon.GetUserBasicInfoByID(ctx, commentUserID)+ if commentUser != nil {+ rawData.CommentUserDisplayName = commentUser.DisplayName+ }+ externalNotificationMsg.NewCommentTemplateRawData = rawData+ cs.externalNotificationQueueService.Send(ctx, externalNotificationMsg)+}+// GetReviewPendingCount get review pending countfunc (cs *ReviewService) GetReviewPendingCount(ctx context.Context) (count int64, err error) {return cs.reviewRepo.GetReviewCount(ctx, entity.ReviewStatusPending)diff --git a/pkg/converter/user.go b/pkg/converter/user.goindex b5c5042d..b55b7449 100644--- a/pkg/converter/user.go+++ b/pkg/converter/user.go@@ -19,8 +19,25 @@package converter-import "github.com/segmentfault/pacman/utils"+import (+ "regexp"++ "github.com/segmentfault/pacman/utils"+)func DeleteUserDisplay(userID string) string {return utils.EnShortID(StringToInt64(userID), 100)}++func GetMentionUsernameList(text string) []string {+ re := regexp.MustCompile(`\[@([^\]]+)\]\(/users/[^\)]+\)`)+ matches := re.FindAllStringSubmatch(text, -1)++ var usernames []string+ for _, match := range matches {+ if len(match) > 1 {+ usernames = append(usernames, match[1])+ }+ }+ return usernames+}