Open platform to collect and prioritize feedback
Total re-implementation of mentions
Matt Roberts53a9758fad3a
diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.goindex 52479dabd..74412629d 100644--- a/app/handlers/apiv1/post.go+++ b/app/handlers/apiv1/post.go@@ -1,8 +1,6 @@package apiv1import (- "fmt"-"github.com/getfider/fider/app/actions""github.com/getfider/fider/app/metrics""github.com/getfider/fider/app/models/cmd"@@ -11,7 +9,6 @@ import ("github.com/getfider/fider/app/models/query""github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/env"- "github.com/getfider/fider/app/pkg/markdown""github.com/getfider/fider/app/pkg/web""github.com/getfider/fider/app/tasks")@@ -215,9 +212,9 @@ func ListComments() web.HandlerFunc {return c.Failure(err)}- // the content of the comment needs to be sanitized before it is returnedfor _, comment := range getComments.Result {- comment.Content = markdown.StripMentionMetaData(comment.Content)+ commentString := entity.CommentString(comment.Content)+ comment.Content = commentString.SanitizeMentions()}return c.Ok(getComments.Result)@@ -237,7 +234,8 @@ func GetComment() web.HandlerFunc {return c.Failure(err)}- commentByID.Result.Content = markdown.StripMentionMetaData(commentByID.Result.Content)+ commentString := entity.CommentString(commentByID.Result.Content)+ commentByID.Result.Content = commentString.SanitizeMentions()return c.Ok(commentByID.Result)}@@ -289,10 +287,8 @@ func PostComment() web.HandlerFunc {}addNewComment := &cmd.AddNewComment{- Post: getPost.Result,- Content: entity.CommentString(action.Content).FormatMentionJson(func(mention entity.Mention) string {- return fmt.Sprintf(`{"id":%d,"name":"%s"}`, mention.ID, mention.Name)- }),+ Post: getPost.Result,+ Content: action.Content,}if err := bus.Dispatch(c, addNewComment); err != nil {return c.Failure(err)@@ -331,9 +327,10 @@ func UpdateComment() web.HandlerFunc {return c.Failure(err)}- contentToSave := entity.CommentString(action.Content).FormatMentionJson(func(mention entity.Mention) string {- return fmt.Sprintf(`{"id":%d,"name":"%s"}`, mention.ID, mention.Name)- })+ comment := &entity.Comment{+ ID: action.ID,+ Content: action.Content,+ }err := bus.Dispatch(c,&cmd.UploadImages{@@ -342,7 +339,7 @@ func UpdateComment() web.HandlerFunc {},&cmd.UpdateComment{CommentID: action.ID,- Content: contentToSave,+ Content: action.Content,},&cmd.SetAttachments{Post: action.Post,@@ -356,7 +353,7 @@ func UpdateComment() web.HandlerFunc {// Update the content- c.Enqueue(tasks.NotifyAboutUpdatedComment(action.Content, getPost.Result))+ c.Enqueue(tasks.NotifyAboutUpdatedComment(getPost.Result, comment))return c.Ok(web.Map{})}diff --git a/app/handlers/apiv1/post_test.go b/app/handlers/apiv1/post_test.goindex 193ae7837..ab1d6acfd 100644--- a/app/handlers/apiv1/post_test.go+++ b/app/handlers/apiv1/post_test.go@@ -67,14 +67,14 @@ func TestCreatePostHandler_WithoutTitle(t *testing.T) {func TestCreatePostHandler_WithNonExistentTag(t *testing.T) {if env.Config.PostCreationWithTagsEnabled {RegisterT(t)-+bus.AddHandler(func(ctx context.Context, q *query.GetTagBySlug) error {return app.ErrNotFound})bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {return app.ErrNotFound})-+code, _ := mock.NewServer().OnTenant(mock.DemoTenant).AsUser(mock.JonSnow).@@ -87,7 +87,7 @@ func TestCreatePostHandler_WithNonExistentTag(t *testing.T) {func TestCreatePostHandler_WithPrivateTagAsVisitor(t *testing.T) {if env.Config.PostCreationWithTagsEnabled {RegisterT(t)-+privateTag := &entity.Tag{ID: 1,Name: "private_tag",@@ -102,11 +102,11 @@ func TestCreatePostHandler_WithPrivateTagAsVisitor(t *testing.T) {}return app.ErrNotFound})-+bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {return app.ErrNotFound})-+code, _ := mock.NewServer().OnTenant(mock.DemoTenant).AsUser(mock.AryaStark).@@ -119,7 +119,7 @@ func TestCreatePostHandler_WithPrivateTagAsVisitor(t *testing.T) {func TestCreatePostHandler_WithPublicTagAsVisitor(t *testing.T) {if env.Config.PostCreationWithTagsEnabled {RegisterT(t)-+var newPost *cmd.AddNewPostbus.AddHandler(func(ctx context.Context, c *cmd.AddNewPost) error {newPost = c@@ -130,7 +130,7 @@ func TestCreatePostHandler_WithPublicTagAsVisitor(t *testing.T) {}return nil})-+publicTag := &entity.Tag{ID: 1,Name: "public_tag",@@ -145,21 +145,21 @@ func TestCreatePostHandler_WithPublicTagAsVisitor(t *testing.T) {}return app.ErrNotFound})-+var tagAssignment *cmd.AssignTagbus.AddHandler(func(ctx context.Context, c *cmd.AssignTag) error {tagAssignment = creturn nil})-+bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {return app.ErrNotFound})-+bus.AddHandler(func(ctx context.Context, c *cmd.SetAttachments) error { return nil })bus.AddHandler(func(ctx context.Context, c *cmd.AddVote) error { return nil })bus.AddHandler(func(ctx context.Context, c *cmd.UploadImages) error { return nil })-+code, _ := mock.NewServer().OnTenant(mock.DemoTenant).AsUser(mock.AryaStark).@@ -174,7 +174,7 @@ func TestCreatePostHandler_WithPublicTagAsVisitor(t *testing.T) {func TestCreatePostHandler_WithPublicTagAndPrivateTagAsCollaborator(t *testing.T) {if env.Config.PostCreationWithTagsEnabled {RegisterT(t)-+var newPost *cmd.AddNewPostbus.AddHandler(func(ctx context.Context, c *cmd.AddNewPost) error {newPost = c@@ -185,7 +185,7 @@ func TestCreatePostHandler_WithPublicTagAndPrivateTagAsCollaborator(t *testing.T}return nil})-+publicTag := &entity.Tag{ID: 1,Name: "public_tag",@@ -211,7 +211,7 @@ func TestCreatePostHandler_WithPublicTagAndPrivateTagAsCollaborator(t *testing.T}return app.ErrNotFound})-+tagAssignments := make([]*cmd.AssignTag, 2)bus.AddHandler(func(ctx context.Context, c *cmd.AssignTag) error {if c.Tag.Slug == "public_tag" {@@ -221,15 +221,15 @@ func TestCreatePostHandler_WithPublicTagAndPrivateTagAsCollaborator(t *testing.T}return nil})-+bus.AddHandler(func(ctx context.Context, q *query.GetPostBySlug) error {return app.ErrNotFound})-+bus.AddHandler(func(ctx context.Context, c *cmd.SetAttachments) error { return nil })bus.AddHandler(func(ctx context.Context, c *cmd.AddVote) error { return nil })bus.AddHandler(func(ctx context.Context, c *cmd.UploadImages) error { return nil })-+code, _ := mock.NewServer().OnTenant(mock.DemoTenant).AsUser(mock.JonSnow).@@ -746,11 +746,11 @@ func TestPostCommentHandlerMentions(t *testing.T) {OnTenant(mock.DemoTenant).AsUser(mock.JonSnow).AddParam("number", post.Number).- ExecutePost(apiv1.PostComment(), `{ "content": "Hello @{\"id\":1,\"name\":\"Jon Snow\",\"isNew\":true}!" }`)+ ExecutePost(apiv1.PostComment(), `{ "content": "Hello @[Jon Snow]!" }`)Expect(code).Equals(http.StatusOK)Expect(newComment.Post).Equals(post)- Expect(newComment.Content).Equals("Hello @{\"id\":1,\"name\":\"Jon Snow\"}!")+ Expect(newComment.Content).Equals("Hello @[Jon Snow]!")}func TestPostCommentHandler_WithoutContent(t *testing.T) {diff --git a/app/models/cmd/mention_notification.go b/app/models/cmd/mention_notification.gonew file mode 100644index 000000000..dd9af79ce--- /dev/null+++ b/app/models/cmd/mention_notification.go@@ -0,0 +1,6 @@+package cmd++type AddMentionNotification struct {+ UserID int `db:"user_id"`+ CommentID int `db:"comment_id"`+}diff --git a/app/models/entity/comment.go b/app/models/entity/comment.goindex ddac8b4a8..b07135415 100644--- a/app/models/entity/comment.go+++ b/app/models/entity/comment.go@@ -20,10 +20,4 @@ type Comment struct {EditedAt *time.Time `json:"editedAt,omitempty"`EditedBy *User `json:"editedBy,omitempty"`ReactionCounts []ReactionCounts `json:"reactionCounts,omitempty"`- Mentions []Mention `json:"_"`-}--func (c *Comment) ParseMentions() {- mentionString := CommentString(c.Content)- c.Mentions = mentionString.ParseMentions()}diff --git a/app/models/entity/mention.go b/app/models/entity/mention.goindex 085b4356c..6b619abcd 100644--- a/app/models/entity/mention.go+++ b/app/models/entity/mention.go@@ -1,69 +1,29 @@package entityimport (- "encoding/json""regexp"- "strings")-type Mention struct {- ID int `json:"id"`- Name string `json:"name"`- IsNew bool `json:"isNew"`-}-type CommentString string-const mentionRegex = `@{([^{}]+)}`+const mentionRegex = `@\[(.*?)\]`-func (commentString CommentString) ParseMentions() []Mention {+func (commentString CommentString) ParseMentions() []string {r, _ := regexp.Compile(mentionRegex)+ matches := r.FindAllStringSubmatch(string(commentString), -1)- // Remove escaped quotes from the input string- input := strings.ReplaceAll(string(commentString), `\"`, `"`)-- matches := r.FindAllString(input, -1)-- mentions := []Mention{}+ mentions := []string{}for _, match := range matches {-- jsonMention := match[1:]-- var mention Mention- err := json.Unmarshal([]byte(jsonMention), &mention)- if err == nil {- if mention.ID > 0 && mention.Name != "" {- mentions = append(mentions, mention)- }+ if len(match) >= 2 && match[1] != "" {+ mentions = append(mentions, match[1])}}return mentions}-func (mentionString CommentString) FormatMentionJson(jsonOperator func(Mention) string) string {-+func (commentString CommentString) SanitizeMentions() string {r, _ := regexp.Compile(mentionRegex)-- // Remove escaped quotes from the input string- input := strings.ReplaceAll(string(mentionString), `\"`, `"`)-- return r.ReplaceAllStringFunc(input, func(match string) string {- jsonMention := match[1:]-- var mention Mention-- err := json.Unmarshal([]byte(jsonMention), &mention)- if err != nil {- return match- }-- if mention.ID == 0 || mention.Name == "" {- return match- }-- return "@" + jsonOperator(mention)- })-+ return r.ReplaceAllString(string(commentString), "@$1")}diff --git a/app/models/entity/mention_notification.go b/app/models/entity/mention_notification.gonew file mode 100644index 000000000..ce681740b--- /dev/null+++ b/app/models/entity/mention_notification.go@@ -0,0 +1,14 @@+package entity++import (+ "time"+)++// NotificationLog represents a record of a notification that was sent to a user+type MentionNotification struct {+ ID int `json:"id" db:"id"`+ TenantID int `json:"-" db:"tenant_id"`+ UserID int `json:"userId" db:"user_id"`+ CommentID int `json:"commentId,omitempty" db:"comment_id"`+ CreatedAt time.Time `json:"createdAt" db:"created_on"`+}diff --git a/app/models/entity/mention_test.go b/app/models/entity/mention_test.godeleted file mode 100644index e519928ce..000000000--- a/app/models/entity/mention_test.go+++ /dev/null@@ -1,92 +0,0 @@-package entity_test--import (- "testing"-- "github.com/getfider/fider/app/models/entity"-- . "github.com/getfider/fider/app/pkg/assert"-)--func TestComment_ParseMentions(t *testing.T) {- RegisterT(t)- tests := []struct {- name string- content string- expected []entity.Mention- }{- {- name: "no mentions",- content: "This is a regular comment \\\" just here",- expected: []entity.Mention{},- },- {- name: "Simple mention",- content: `Hello there @{"id":1,"name":"John Doe","isNew":false} how are you`,- expected: []entity.Mention{{ID: 1, Name: "John Doe", IsNew: false}},- },- {- name: "Simple mention 2",- content: `Hello there @{"id":2,"name":"John Doe Smith","isNew":true} how are you`,- expected: []entity.Mention{{ID: 2, Name: "John Doe Smith", IsNew: true}},- },- {- name: "Multiple mentions",- content: `Hello there @{"id":2,"name":"John Doe Smith","isNew":true} and @{"id":1,"name":"John Doe","isNew":false} how are you`,- expected: []entity.Mention{{ID: 2, Name: "John Doe Smith", IsNew: true}, {ID: 1, Name: "John Doe", IsNew: false}},- },- {- name: "Some odd JSON",- content: `Hello there @{"id":2,name:"John Doe Smith","isNew":true} how are you`,- expected: []entity.Mention{},- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- comment := &entity.Comment{Content: tt.content}- comment.ParseMentions()- Expect(comment.Mentions).Equals(tt.expected)- })- }-}--func TestStripMentionMetaData(t *testing.T) {- RegisterT(t)-- for input, expected := range map[string]string{- `@{\"id\":1,\"name\":\"John Doe quoted\"}`: "@John Doe quoted",- `@{"id":1,"name":"John Doe"}`: "@John Doe",- `@{"id":1,"name":"JohnDoe"}`: "@JohnDoe",- `@{\"id\":1,\"name\":\"JohnDoe quoted\"}`: "@JohnDoe quoted",- `@{"id":1,"name":"John Smith Doe"}`: "@John Smith Doe",- `@{\"id\":1,\"name\":\"John Smith Doe quoted\"}`: "@John Smith Doe quoted",- "Hello there how are you": "Hello there how are you",- `Hello there @{"id":1,"name":"John Doe"}`: "Hello there @John Doe",- `Hello there @{"id":1,"name":"John Doe quoted"}`: "Hello there @John Doe quoted",- `Hello both @{"id":1,"name":"John Doe"} and @{"id":2,"name":"John Smith"}`: "Hello both @John Doe and @John Smith",- } {- output := entity.CommentString(input).FormatMentionJson(func(mention entity.Mention) string {- return mention.Name- })- Expect(output).Equals(expected)- }-}--func TestStripMentionMetaDataDoesntBreakUserInput(t *testing.T) {- RegisterT(t)-- for input, expected := range map[string]string{- `There is nothing here`: "There is nothing here",- `There is nothing here {ok}`: "There is nothing here {ok}",- `This is a message for {{matt}}`: "This is a message for {{matt}}",- `This is a message for {{id:1,wiggles:true}}`: "This is a message for {{id:1,wiggles:true}}",- `Although uncommon, someone could enter @{something} like this`: "Although uncommon, someone could enter @{something} like this",- `Or @{"id":100,"wiggles":"yes"} something like this`: `Or @{"id":100,"wiggles":"yes"} something like this`,- } {- output := entity.CommentString(input).FormatMentionJson(func(mention entity.Mention) string {- return mention.Name- })- Expect(output).Equals(expected)- }-}diff --git a/app/models/query/notification.go b/app/models/query/notification.goindex eac7410dc..18dbac63c 100644--- a/app/models/query/notification.go+++ b/app/models/query/notification.go@@ -25,3 +25,9 @@ type GetActiveSubscribers struct {Result []*entity.User}++type GetMentionNotifications struct {+ CommentID int++ Result []*entity.MentionNotification+}diff --git a/app/pkg/markdown/markdown.go b/app/pkg/markdown/markdown.goindex 758c6b88a..17df3839d 100644--- a/app/pkg/markdown/markdown.go+++ b/app/pkg/markdown/markdown.go@@ -5,7 +5,6 @@ import ("io""strings"- "github.com/getfider/fider/app/models/entity""github.com/gomarkdown/markdown""github.com/gomarkdown/markdown/ast"@@ -58,15 +57,3 @@ func Full(input string) template.HTML {output := markdown.ToHTML([]byte(input), parser, fullRenderer)return template.HTML(strings.TrimSpace(string(output)))}--// StripMentionMetaData removes all mention metadata from a markdown string-// Example input: Hello there @{\"id\":1,\"name\":\"John Doe\"}"-// Example output: Hello there @John Doe-func StripMentionMetaData(input string) string {-- mentionString := entity.CommentString(input)- return mentionString.FormatMentionJson(func(mention entity.Mention) string {- return mention.Name- })--}diff --git a/app/services/sqlstore/postgres/mention_notification.go b/app/services/sqlstore/postgres/mention_notification.gonew file mode 100644index 000000000..3fac2fa75--- /dev/null+++ b/app/services/sqlstore/postgres/mention_notification.go@@ -0,0 +1,62 @@+package postgres++import (+ "context"+ "time"++ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/dbx"+ "github.com/getfider/fider/app/pkg/errors"+)++func AddMentionNotification(ctx context.Context, c *cmd.AddMentionNotification) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ now := time.Now()++ query := `+ INSERT INTO mention_notifications (tenant_id, user_id, comment_id, created_on)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (tenant_id, user_id, comment_id) DO NOTHING+ `+ _, err := trx.Execute(query,+ tenant.ID,+ c.UserID,+ c.CommentID,+ now)++ if err != nil {+ return errors.Wrap(err, "failed to insert notification log")+ }++ return nil+ })+}++func getMentionsNotifications(ctx context.Context, q *query.GetMentionNotifications) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ q.Result = make([]*entity.MentionNotification, 0)++ params := []interface{}{+ tenant.ID,+ q.CommentID,+ }++ query := `+ SELECT id, tenant_id, user_id, comment_id, created_on+ FROM mention_notifications+ WHERE tenant_id = $1+ AND comment_id = $2+ `++ query += " ORDER BY created_on DESC"++ err := trx.Select(&q.Result, query, params...)+ if err != nil {+ return errors.Wrap(err, "failed to get mention notification logs")+ }++ return nil+ })+}diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex 37e77cb20..6761de539 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -136,6 +136,8 @@ func (s Service) Init() {bus.AddHandler(setSystemSettings)bus.AddHandler(getSystemSettings)+ bus.AddHandler(AddMentionNotification)+ bus.AddHandler(getMentionsNotifications)}type SqlHandler func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) errordiff --git a/app/tasks/new_comment.go b/app/tasks/new_comment.goindex a44399a4f..82552da12 100644--- a/app/tasks/new_comment.go+++ b/app/tasks/new_comment.go@@ -2,11 +2,13 @@ package tasksimport ("fmt"+ "slices""github.com/getfider/fider/app/models/cmd""github.com/getfider/fider/app/models/dto""github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/models/query""github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/i18n""github.com/getfider/fider/app/pkg/log"@@ -20,7 +22,9 @@ import (func NotifyAboutNewComment(comment *entity.Comment, post *entity.Post) worker.Task {return describe("Notify about new comment", func(c *worker.Context) error {- comment.ParseMentions()+ // comment.ParseMentions()+ contentString := entity.CommentString(comment.Content)+ mentions := contentString.ParseMentions()// Web notificationusers, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventNewComment)@@ -48,18 +52,31 @@ func NotifyAboutNewComment(comment *entity.Comment, post *entity.Post) worker.Ta// Web notification - mentionstitle = fmt.Sprintf("**%s** mentioned you in **%s**", author.Name, post.Title)- if comment.Mentions != nil {+ if mentions != nil {users, err = getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventMention)if err != nil {return c.Failure(err)}+ // Get the existing mentions that have been sent for this comment+ mentionNotifications := &query.GetMentionNotifications{+ CommentID: comment.ID,+ }+ err := bus.Dispatch(c, mentionNotifications)+ if err != nil {+ return c.Failure(err)+ }+// Iterate the mentions- for _, mention := range comment.Mentions {+ for _, mention := range mentions {// Check if the user is in the list of mention subscribers (users)for _, u := range users {- if u.ID == mention.ID && mention.IsNew {++ if u.Name == mention && !slices.ContainsFunc(mentionNotifications.Result,+ func(n *entity.MentionNotification) bool {+ return n.UserID == u.ID+ }) {err = bus.Dispatch(c, &cmd.AddNewNotification{User: u,Title: title,@@ -69,14 +86,23 @@ func NotifyAboutNewComment(comment *entity.Comment, post *entity.Post) worker.Taif err != nil {return c.Failure(err)}++ // Also send the notification log+ err = bus.Dispatch(c, &cmd.AddMentionNotification{+ UserID: u.ID,+ CommentID: comment.ID,+ })+ if err != nil {+ return c.Failure(err)+ }+}+}}}- strippedContent := markdown.StripMentionMetaData(comment.Content)-// Standard email notitificationsusers, err = getActiveSubscribers(c, post, enum.NotificationChannelEmail, enum.NotificationEventNewComment)if err != nil {@@ -90,37 +116,55 @@ func NotifyAboutNewComment(comment *entity.Comment, post *entity.Post) worker.Ta}}- sendEmailNotifications(c, post, to, strippedContent, enum.NotificationEventNewComment)+ sendEmailNotifications(c, post, to, contentString.SanitizeMentions(), enum.NotificationEventNewComment)// Mentionsto = make([]dto.Recipient, 0)- if comment.Mentions != nil {+ if mentions != nil {users, err = getActiveSubscribers(c, post, enum.NotificationChannelEmail, enum.NotificationEventMention)if err != nil {return c.Failure(err)}- // Iterate the mentions- for _, mention := range comment.Mentions {+ // Get the existing mentions that have been sent for this comment+ mentionNotifications := &query.GetMentionNotifications{+ CommentID: comment.ID,+ }+ err = bus.Dispatch(c, mentionNotifications)+ if err != nil {+ return c.Failure(err)+ }- // Check if the user is in the list of mention subscribers (users)+ for _, mention := range mentions {for _, u := range users {- if u.ID == mention.ID && mention.IsNew {++ if u.Name == mention && !slices.ContainsFunc(mentionNotifications.Result,+ func(n *entity.MentionNotification) bool {+ return n.UserID == u.ID+ }) {to = append(to, dto.NewRecipient(u.Name, u.Email, dto.Props{}))- break++ // Also send the notification log+ err = bus.Dispatch(c, &cmd.AddMentionNotification{+ UserID: u.ID,+ CommentID: comment.ID,+ })+ if err != nil {+ return c.Failure(err)+ }}}}}- sendEmailNotifications(c, post, to, strippedContent, enum.NotificationEventMention)+ sendEmailNotifications(c, post, to, contentString.SanitizeMentions(), enum.NotificationEventMention)tenant := c.Tenant()baseURL, logoURL := web.BaseURL(c), web.LogoURL(c)- webhookProps := webhook.Props{"comment": strippedContent}+ webhookProps := webhook.Props{"comment": contentString.SanitizeMentions()}webhookProps.SetPost(post, "post", baseURL, true, true)webhookProps.SetUser(author, "author")webhookProps.SetTenant(tenant, "tenant", baseURL, logoURL)@@ -137,10 +181,10 @@ func NotifyAboutNewComment(comment *entity.Comment, post *entity.Post) worker.Ta})}-func NotifyAboutUpdatedComment(content string, post *entity.Post) worker.Task {+func NotifyAboutUpdatedComment(post *entity.Post, comment *entity.Comment) worker.Task {return describe("Notify about updated comment", func(c *worker.Context) error {- contentString := entity.CommentString(content)+ contentString := entity.CommentString(comment.Content)mentions := contentString.ParseMentions()log.Infof(c, "Comment updated: @{Comment:Yellow}. Mentions @{MentionsCount}", dto.Props{@@ -151,6 +195,7 @@ func NotifyAboutUpdatedComment(content string, post *entity.Post) worker.Task {author := c.User()title := fmt.Sprintf("**%s** mentioned you in **%s**", author.Name, post.Title)link := fmt.Sprintf("/posts/%d/%s", post.Number, post.Slug)+ mentionNotificationSent := falseif mentions != nil {users, err := getActiveSubscribers(c, post, enum.NotificationChannelWeb, enum.NotificationEventMention)@@ -158,11 +203,23 @@ func NotifyAboutUpdatedComment(content string, post *entity.Post) worker.Task {return c.Failure(err)}+ // Get the existing mentions that have been sent for this comment+ mentionNotifications := &query.GetMentionNotifications{+ CommentID: comment.ID,+ }+ err = bus.Dispatch(c, mentionNotifications)+ if err != nil {+ return c.Failure(err)+ }+// Iterate the mentionsfor _, mention := range mentions {// Check if the user is in the list of mention subscribers (users)for _, u := range users {- if u.ID == mention.ID && mention.IsNew {+ if u.Name == mention && !slices.ContainsFunc(mentionNotifications.Result,+ func(n *entity.MentionNotification) bool {+ return n.UserID == u.ID+ }) {err = bus.Dispatch(c, &cmd.AddNewNotification{User: u,Title: title,@@ -172,14 +229,22 @@ func NotifyAboutUpdatedComment(content string, post *entity.Post) worker.Task {if err != nil {return c.Failure(err)}++ // Also send the notification log+ err = bus.Dispatch(c, &cmd.AddMentionNotification{+ UserID: u.ID,+ CommentID: comment.ID,+ })+ if err != nil {+ return c.Failure(err)+ }+ mentionNotificationSent = true}}}}- strippedContent := markdown.StripMentionMetaData(content)-to := make([]dto.Recipient, 0)if mentions != nil {@@ -188,19 +253,40 @@ func NotifyAboutUpdatedComment(content string, post *entity.Post) worker.Task {return c.Failure(err)}+ // Get the existing mentions that have been sent for this comment+ mentionNotifications := &query.GetMentionNotifications{+ CommentID: comment.ID,+ }+ err = bus.Dispatch(c, mentionNotifications)+ if err != nil {+ return c.Failure(err)+ }+for _, mention := range mentions {// Check if the user is in the list of mention subscribers (users)for _, u := range users {- if u.ID == mention.ID && mention.IsNew {+ if u.Name == mention && !slices.ContainsFunc(mentionNotifications.Result,+ func(n *entity.MentionNotification) bool {+ return n.UserID == u.ID+ }) {to = append(to, dto.NewRecipient(u.Name, u.Email, dto.Props{}))- break++ // Also send the notification log+ if !mentionNotificationSent {+ err = bus.Dispatch(c, &cmd.AddMentionNotification{+ UserID: u.ID,+ CommentID: comment.ID,+ })+ if err != nil {+ return c.Failure(err)+ }+ }}}}-}- sendEmailNotifications(c, post, to, strippedContent, enum.NotificationEventMention)+ sendEmailNotifications(c, post, to, contentString.SanitizeMentions(), enum.NotificationEventMention)return nil})diff --git a/app/tasks/new_comment_test.go b/app/tasks/new_comment_test.goindex a609c7125..c8d444420 100644--- a/app/tasks/new_comment_test.go+++ b/app/tasks/new_comment_test.go@@ -4,6 +4,7 @@ import ("context""html/template""testing"+ "time""github.com/getfider/fider/app/pkg/webhook"@@ -30,6 +31,17 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {return nil})+ addNotificationLogs := make([]*cmd.AddMentionNotification, 0)+ bus.AddListener(func(ctx context.Context, c *cmd.AddMentionNotification) error {+ addNotificationLogs = append(addNotificationLogs, c)+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetMentionNotifications) error {+ q.Result = []*entity.MentionNotification{}+ return nil+ })+bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {if q.Event.UserSettingsKeyName == "event_notification_new_comment" {q.Result = []*entity.User{@@ -120,6 +132,8 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {"tenant_status": mock.DemoTenant.Status.String(),"tenant_url": "http://domain.com",})++ Expect(addNotificationLogs).HasLen(0)}func TestNotifyAboutNewCommentTask_WithMention(t *testing.T) {@@ -132,6 +146,12 @@ func TestNotifyAboutNewCommentTask_WithMention(t *testing.T) {return nil})+ addNotificationLogs := make([]*cmd.AddMentionNotification, 0)+ bus.AddHandler(func(ctx context.Context, c *cmd.AddMentionNotification) error {+ addNotificationLogs = append(addNotificationLogs, c)+ return nil+ })+bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {if q.Event.UserSettingsKeyName == "event_notification_mention" {q.Result = []*entity.User{@@ -143,6 +163,11 @@ func TestNotifyAboutNewCommentTask_WithMention(t *testing.T) {return nil})+ bus.AddHandler(func(ctx context.Context, q *query.GetMentionNotifications) error {+ q.Result = []*entity.MentionNotification{}+ return nil+ })+var triggerWebhooks *cmd.TriggerWebhooksbus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {triggerWebhooks = c@@ -158,7 +183,7 @@ func TestNotifyAboutNewCommentTask_WithMention(t *testing.T) {Description: "TypeScript is great, please add support for it",User: mock.JonSnow,}- task := tasks.NotifyAboutNewComment(&entity.Comment{Content: "I agree with @{\"id\":1,\"name\":\"Jon Snow\",\"isNew\":true}"}, post)+ task := tasks.NotifyAboutNewComment(&entity.Comment{Content: "I agree with @[Jon Snow]"}, post)err := worker.OnTenant(mock.DemoTenant).@@ -222,6 +247,14 @@ func TestNotifyAboutNewCommentTask_WithMention(t *testing.T) {"tenant_status": mock.DemoTenant.Status.String(),"tenant_url": "http://domain.com",})++ Expect(addNotificationLogs).HasLen(2)+ Expect(addNotificationLogs[0].UserID).Equals(mock.JonSnow.ID)+ Expect(addNotificationLogs[0].CommentID).Equals(0)++ Expect(addNotificationLogs[1].UserID).Equals(mock.JonSnow.ID)+ Expect(addNotificationLogs[1].CommentID).Equals(0)+}func TestNotifyAboutUpdatedComment(t *testing.T) {@@ -234,6 +267,17 @@ func TestNotifyAboutUpdatedComment(t *testing.T) {return nil})+ addNotificationLogs := make([]*cmd.AddMentionNotification, 0)+ bus.AddHandler(func(ctx context.Context, c *cmd.AddMentionNotification) error {+ addNotificationLogs = append(addNotificationLogs, c)+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetMentionNotifications) error {+ q.Result = []*entity.MentionNotification{}+ return nil+ })+bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {q.Result = []*entity.User{mock.JonSnow,@@ -251,8 +295,14 @@ func TestNotifyAboutUpdatedComment(t *testing.T) {User: mock.JonSnow,}- commentString := "I agree with @{\"id\":1,\"name\":\"Jon Snow\",\"isNew\":true} but not @{\"id\":2,\"name\":\"Arya Stark\",\"isNew\":false}"- task := tasks.NotifyAboutUpdatedComment(commentString, post)+ comment := &entity.Comment{+ ID: 1,+ Content: "I agree with @[Jon Snow] but not @[Arya Stark]",+ CreatedAt: time.Now(),+ User: mock.AryaStark,+ }++ task := tasks.NotifyAboutUpdatedComment(post, comment)err := worker.OnTenant(mock.DemoTenant).@@ -291,4 +341,68 @@ func TestNotifyAboutUpdatedComment(t *testing.T) {Expect(addNewNotification.Link).Equals("/posts/1/add-support-for-typescript")Expect(addNewNotification.Title).Equals("**Arya Stark** mentioned you in **Add support for TypeScript**")Expect(addNewNotification.User).Equals(mock.JonSnow)++ Expect(addNotificationLogs).HasLen(1)+ Expect(addNotificationLogs[0].UserID).Equals(mock.JonSnow.ID)+ Expect(addNotificationLogs[0].CommentID).Equals(1)++}++func TestNotifyAboutUpdatedComment_UserAlreadyMentioned(t *testing.T) {+ RegisterT(t)+ bus.Init(emailmock.Service{})++ var addNewNotification *cmd.AddNewNotification+ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {+ addNewNotification = c+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetMentionNotifications) error {+ q.Result = []*entity.MentionNotification{+ {+ UserID: mock.JonSnow.ID,+ CommentID: 1,+ TenantID: mock.DemoTenant.ID,+ },+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {+ q.Result = []*entity.User{+ mock.JonSnow,+ }+ return nil+ })++ worker := mock.NewWorker()+ post := &entity.Post{+ ID: 1,+ Number: 1,+ Title: "Add support for TypeScript",+ Slug: "add-support-for-typescript",+ Description: "TypeScript is great, please add support for it",+ User: mock.JonSnow,+ }++ comment := &entity.Comment{+ ID: 1,+ Content: "I agree with @[Jon Snow] but not @[Arya Stark]",+ CreatedAt: time.Now(),+ User: mock.AryaStark,+ }++ task := tasks.NotifyAboutUpdatedComment(post, comment)++ err := worker.+ OnTenant(mock.DemoTenant).+ AsUser(mock.AryaStark).+ WithBaseURL("http://domain.com").+ Execute(task)++ Expect(err).IsNil()+ Expect(emailmock.MessageHistory).HasLen(0)++ Expect(addNewNotification).IsNil()}diff --git a/locale/de/client.json b/locale/de/client.jsonindex a916e8751..511479ccc 100644--- a/locale/de/client.json+++ b/locale/de/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Erledigt","enum.poststatus.declined": "Abgelehnt","enum.poststatus.deleted": "Gelöscht",diff --git a/locale/el/client.json b/locale/el/client.jsonindex ca5a28876..8d7ad5f43 100644--- a/locale/el/client.json+++ b/locale/el/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Ολοκληρωμένο","enum.poststatus.declined": "Απορρίφθηκε","enum.poststatus.deleted": "Διαγραμμένο",diff --git a/locale/en/client.json b/locale/en/client.jsonindex fd8355594..6af6af752 100644--- a/locale/en/client.json+++ b/locale/en/client.json@@ -15,6 +15,7 @@"action.vote": "Vote for this idea","action.voted": "Voted!","d41FkJ": "{count, plural, one {# tag} other {# tags}}",+ "editor.markdownmode": "Markdown editor","enum.poststatus.completed": "Completed","enum.poststatus.declined": "Declined","enum.poststatus.deleted": "Deleted",diff --git a/locale/es-ES/client.json b/locale/es-ES/client.jsonindex 89db5aa1d..8bfba5365 100644--- a/locale/es-ES/client.json+++ b/locale/es-ES/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Completado","enum.poststatus.declined": "Rechazado","enum.poststatus.deleted": "Eliminado",diff --git a/locale/fr/client.json b/locale/fr/client.jsonindex eea67e84d..f5bdf871c 100644--- a/locale/fr/client.json+++ b/locale/fr/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Terminé","enum.poststatus.declined": "Refusé","enum.poststatus.deleted": "Supprimé",diff --git a/locale/it/client.json b/locale/it/client.jsonindex dd3ae8d9a..cd9c24fd9 100644--- a/locale/it/client.json+++ b/locale/it/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Completato","enum.poststatus.declined": "Rifiutato","enum.poststatus.deleted": "Eliminato",diff --git a/locale/nl/client.json b/locale/nl/client.jsonindex f1060134d..b84526865 100644--- a/locale/nl/client.json+++ b/locale/nl/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Voltooid","enum.poststatus.declined": "Afgewezen","enum.poststatus.deleted": "Verwijderd",diff --git a/locale/pl/client.json b/locale/pl/client.jsonindex dcbf61117..a19a36be4 100644--- a/locale/pl/client.json+++ b/locale/pl/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Ukończone","enum.poststatus.declined": "Odrzucone","enum.poststatus.deleted": "Usunięte",diff --git a/locale/pt-BR/client.json b/locale/pt-BR/client.jsonindex ddb3ab1e2..16020b311 100644--- a/locale/pt-BR/client.json+++ b/locale/pt-BR/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Completado","enum.poststatus.declined": "Rejeitado","enum.poststatus.deleted": "Removido",diff --git a/locale/ru/client.json b/locale/ru/client.jsonindex 5675214f0..c324b8025 100644--- a/locale/ru/client.json+++ b/locale/ru/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Выполнено","enum.poststatus.declined": "Отклонено","enum.poststatus.deleted": "Удалено",diff --git a/locale/sk/client.json b/locale/sk/client.jsonindex 8fd5a2b00..476bf810d 100644--- a/locale/sk/client.json+++ b/locale/sk/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Dokončené","enum.poststatus.declined": "Odmietnuté","enum.poststatus.deleted": "Vymazané",diff --git a/locale/sv-SE/client.json b/locale/sv-SE/client.jsonindex 43503fc80..472e93d9d 100644--- a/locale/sv-SE/client.json+++ b/locale/sv-SE/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Avslutad","enum.poststatus.declined": "Nekad","enum.poststatus.deleted": "Borttagen",diff --git a/locale/tr/client.json b/locale/tr/client.jsonindex 818bb3723..0f71e3ffa 100644--- a/locale/tr/client.json+++ b/locale/tr/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "Tamamlandı","enum.poststatus.declined": "Reddedildi","enum.poststatus.deleted": "Silindi",diff --git a/locale/zh-CN/client.json b/locale/zh-CN/client.jsonindex b2ebc03ad..cac0ad14f 100644--- a/locale/zh-CN/client.json+++ b/locale/zh-CN/client.json@@ -15,6 +15,7 @@"action.vote": "","action.voted": "","d41FkJ": "",+ "editor.markdownmode": "","enum.poststatus.completed": "完成","enum.poststatus.declined": "拒绝","enum.poststatus.deleted": "删除",diff --git a/migrations/202503202000_mentions_notifications.sql b/migrations/202503202000_mentions_notifications.sqlnew file mode 100644index 000000000..fd4776d23--- /dev/null+++ b/migrations/202503202000_mentions_notifications.sql@@ -0,0 +1,15 @@+create table+ if not exists mention_notifications (+ id serial not null,+ tenant_id int not null,+ user_id int not null,+ comment_id int null,+ created_on timestamptz not null default now (),+ primary key (id),+ foreign key (tenant_id) references tenants (id),+ foreign key (user_id) references users (id),+ foreign key (comment_id) references comments (id),+ constraint unique_mention_notification unique (tenant_id, user_id, comment_id)+ );++create index idx_mention_notifications_tenant_user on notification_logs (tenant_id, user_id);\ No newline at end of filediff --git a/public/components/common/form/CommentEditor.tsx b/public/components/common/form/CommentEditor.tsxindex 9536c0e77..531d9d159 100644--- a/public/components/common/form/CommentEditor.tsx+++ b/public/components/common/form/CommentEditor.tsx@@ -20,7 +20,6 @@ import IconStrike from "@fider/assets/images/heroicons-strike.svg"import IconCode from "@fider/assets/images/heroicons-code.svg"import IconAt from "@fider/assets/images/heroicons-at.svg"import IconOrderedList from "@fider/assets/images/heroicons-orderedlist.svg"-// import IconMarkdown from "@fider/assets/images/heroicons-h2.svg"import IconBulletList from "@fider/assets/images/heroicons-bulletlist.svg"import { Icon } from "@fider/components"@@ -161,7 +160,8 @@ interface CommentEditorProps {const markdownToHtml = (markdownString: string) => {return markdownString- .split("\n\n")+ .replace("\n\n", "\n")+ .split("\n").map((line: string) => `<p>${line}</p>`).join("")}@@ -197,6 +197,7 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {const updated = ({ editor }: { editor: Editor; transaction: any }): void => {const markdown = isRawMarkdownMode ? editor.getText() : editor.storage.markdown.getMarkdown()+ console.log("updated", markdown)props.onChange && props.onChange(markdown)}diff --git a/public/components/common/form/CustomMention.ts b/public/components/common/form/CustomMention.tsindex bf86eba59..66019cea8 100644--- a/public/components/common/form/CustomMention.ts+++ b/public/components/common/form/CustomMention.ts@@ -7,7 +7,7 @@ export const CustomMention = Mention.extend({return {markdown: {serialize: (state: any, node: { attrs: { id: string; label: string } }) => {- state.write(`@{"id":${node.attrs.id},"name":"${node.attrs.label}"}`)+ state.write(`@[${node.attrs.label}]`)},parse: {setup(markdownit: MarkdownIt) {@@ -23,27 +23,19 @@ export const CustomMention = Mention.extend({}markdownit.inline.ruler.before("text", "mention", (state: MarkdownIt.StateInline, silent: boolean) => {- const match = state.src.slice(state.pos).match(/^@\{([^}]+)\}/)+ const match = state.src.slice(state.pos).match(/^@\[(.+?)\]/)if (!match) return falseif (!silent) {- try {- const data = JSON.parse(`{${match[1]}}`)- const token = state.push("mention_open", "span", 1)- token.attrs = [- ["id", data.id],- ["label", data.name],- ]+ const label = match[1]+ const token = state.push("mention_open", "span", 1)+ token.attrs = [["label", label]]- // Add the text content token- const contentToken = state.push("text", "", 0)- contentToken.content = `@${data.name}`+ // Add the text content token+ const contentToken = state.push("text", "", 0)+ contentToken.content = `@${label}`- // Close the mention span- state.push("mention_close", "span", -1)- } catch (error) {- console.error("Failed to parse mention:", match[1])- return false- }+ // Close the mention span+ state.push("mention_close", "span", -1)}state.pos += match[0].lengthdiff --git a/public/services/markdown.ts b/public/services/markdown.tsindex 802d1d507..47a2bb34c 100644--- a/public/services/markdown.ts+++ b/public/services/markdown.ts@@ -27,15 +27,9 @@ const fullRenderer = new marked.Renderer()fullRenderer.image = () => ""fullRenderer.link = linkfullRenderer.text = (text: string) => {- // Handling mention links (they're in the format @{id:1234, name:'John Doe'})- return text.replace(/@{([^}]+)}/g, (match) => {- try {- const json = match.substring(1).replace(/"/g, '"')- const mention = JSON.parse(json)- return `<span class="text-blue-600">@${mention.name}</span>`- } catch {- return match- }+ // Handling mention links (they're in the format @[name])+ return text.replace(/@\[(.*?)\]/g, (match, name) => {+ return `<span class="text-blue-600">@${name}</span>`})}