MM-56083 Add PatchMultipleMembersNotifyProps plugin API (#25690)

* Add ChannelStore.UpdateMultipleMembersNotifyProps

* Make UpdateMultipleMembersNotifyProps return updated values from the DB

* Add UpdateChannelMembersNotifications plugin API

* Extract i18n

* Fix style

* Make layers

* Change to PatchMultipleMembersNotifyProps

* Add limit to PatchChannelMembersNotifyProps

* Add additional unit tests

* Address feedback

* Lowercase decodeJSON

* Have PatchMultipleMembersNotifyProps update LastUpdateAt

* Fix tests that relied on unreliable return order

* Fix i18n
Этот коммит содержится в:
Harrison Healey
2024-01-11 13:24:52 -05:00
коммит произвёл GitHub
родитель aafe7439af
Коммит 4d96c11314
21 изменённых файлов: 780 добавлений и 37 удалений

Просмотреть файл

@@ -950,6 +950,7 @@ type AppIface interface {
OriginChecker() func(*http.Request) bool
OutgoingOAuthConnections() einterfaces.OutgoingOAuthConnectionInterface
PatchChannel(c request.CTX, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError)
PatchChannelMembersNotifyProps(c request.CTX, members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, *model.AppError)
PatchPost(c request.CTX, postID string, patch *model.PostPatch) (*model.Post, *model.AppError)
PatchRetentionPolicy(patch *model.RetentionPolicyWithTeamAndChannelIDs) (*model.RetentionPolicyWithTeamAndChannelCounts, *model.AppError)
PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError)

Просмотреть файл

@@ -24,6 +24,10 @@ import (
"github.com/mattermost/mattermost/server/v8/channels/store/sqlstore"
)
const (
UpdateMultipleMaximum = 200
)
// channelsWrapper provides an implementation of `product.ChannelService` to be used by products.
type channelsWrapper struct {
app *App
@@ -1360,15 +1364,66 @@ func (a *App) UpdateChannelMemberNotifyProps(c request.CTX, data map[string]stri
a.invalidateCacheForChannelMembersNotifyProps(member.ChannelId)
// Notify the clients that the member notify props changed
err = a.sendUpdateChannelMemberNotifyPropsEvent(member)
if err != nil {
return nil, model.NewAppError("UpdateChannelMemberNotifyProps", "api.marshal_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
return member, nil
}
func (a *App) PatchChannelMembersNotifyProps(c request.CTX, members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, *model.AppError) {
if len(members) > UpdateMultipleMaximum {
return nil, model.NewAppError("PatchChannelMembersNotifyProps", "app.channel.patch_channel_members_notify_props.too_many", map[string]any{"Max": UpdateMultipleMaximum}, "", http.StatusBadRequest)
}
updated, err := a.Srv().Store().Channel().PatchMultipleMembersNotifyProps(members, notifyProps)
if err != nil {
var appErr *model.AppError
switch {
case errors.As(err, &appErr):
return nil, appErr
default:
return nil, model.NewAppError("UpdateMultipleMembersNotifyProps", "app.channel.patch_channel_members_notify_props.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
}
// Invalidate caches for the users and channels that have changed
userIds := make(map[string]bool)
channelIds := make(map[string]bool)
for _, member := range updated {
userIds[member.UserId] = true
channelIds[member.ChannelId] = true
}
for userId := range userIds {
a.InvalidateCacheForUser(userId)
}
for channelId := range channelIds {
a.invalidateCacheForChannelMembersNotifyProps(channelId)
}
// Notify clients that their notify props have changed
for _, member := range updated {
err := a.sendUpdateChannelMemberNotifyPropsEvent(member)
if err != nil {
c.Logger().Warn("Failed to send WebSocket event for updated channel member notify props", mlog.Err(err))
}
}
return updated, nil
}
func (a *App) sendUpdateChannelMemberNotifyPropsEvent(member *model.ChannelMember) error {
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil, "")
memberJSON, jsonErr := json.Marshal(member)
if jsonErr != nil {
return nil, model.NewAppError("UpdateChannelMemberNotifyProps", "api.marshal_error", nil, "", http.StatusInternalServerError).Wrap(jsonErr)
return jsonErr
}
evt.Add("channelMember", string(memberJSON))
a.Publish(evt)
return member, nil
return nil
}
func (a *App) updateChannelMember(c request.CTX, member *model.ChannelMember) (*model.ChannelMember, *model.AppError) {

Просмотреть файл

@@ -2670,3 +2670,130 @@ func TestConvertGroupMessageToChannel(t *testing.T) {
require.Nil(t, appErr)
require.Equal(t, model.ChannelTypePrivate, convertedChannel.Type)
}
func TestPatchChannelMembersNotifyProps(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
t.Run("should update multiple users' notify props", func(t *testing.T) {
user1 := th.CreateUser()
user2 := th.CreateUser()
channel1 := th.CreateChannel(th.Context, th.BasicTeam)
channel2 := th.CreateChannel(th.Context, th.BasicTeam)
th.LinkUserToTeam(user1, th.BasicTeam)
th.LinkUserToTeam(user2, th.BasicTeam)
th.AddUserToChannel(user1, channel1)
th.AddUserToChannel(user1, channel2)
th.AddUserToChannel(user2, channel1)
th.AddUserToChannel(user2, channel2)
result, appErr := th.App.PatchChannelMembersNotifyProps(th.Context, []*model.ChannelMemberIdentifier{
{UserId: user1.Id, ChannelId: channel1.Id},
{UserId: user1.Id, ChannelId: channel2.Id},
{UserId: user2.Id, ChannelId: channel1.Id},
}, map[string]string{
model.DesktopNotifyProp: model.ChannelNotifyNone,
"custom_key": "custom_value",
})
require.Nil(t, appErr)
// Confirm specified fields were updated
assert.Equal(t, model.ChannelNotifyNone, result[0].NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "custom_value", result[0].NotifyProps["custom_key"])
assert.Equal(t, model.ChannelNotifyNone, result[1].NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "custom_value", result[1].NotifyProps["custom_key"])
assert.Equal(t, model.ChannelNotifyNone, result[2].NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "custom_value", result[2].NotifyProps["custom_key"])
// Confirm unspecified fields were unchanged
assert.Equal(t, model.ChannelNotifyDefault, result[0].NotifyProps[model.PushNotifyProp])
assert.Equal(t, model.ChannelNotifyDefault, result[1].NotifyProps[model.PushNotifyProp])
assert.Equal(t, model.ChannelNotifyDefault, result[2].NotifyProps[model.PushNotifyProp])
// Confirm other members were unchanged
otherMember, appErr := th.App.GetChannelMember(th.Context, channel2.Id, user2.Id)
require.Nil(t, appErr)
assert.Equal(t, model.ChannelNotifyDefault, otherMember.NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "", otherMember.NotifyProps["custom_key"])
assert.Equal(t, model.ChannelNotifyDefault, otherMember.NotifyProps[model.PushNotifyProp])
})
t.Run("should send WS events for each user", func(t *testing.T) {
user1 := th.CreateUser()
user2 := th.CreateUser()
channel1 := th.CreateChannel(th.Context, th.BasicTeam)
channel2 := th.CreateChannel(th.Context, th.BasicTeam)
th.LinkUserToTeam(user1, th.BasicTeam)
th.LinkUserToTeam(user2, th.BasicTeam)
th.AddUserToChannel(user1, channel1)
th.AddUserToChannel(user1, channel2)
th.AddUserToChannel(user2, channel1)
messages1, closeWS1 := connectFakeWebSocket(t, th, user1.Id, "")
defer closeWS1()
messages2, closeWS2 := connectFakeWebSocket(t, th, user2.Id, "")
defer closeWS2()
_, appErr := th.App.PatchChannelMembersNotifyProps(th.Context, []*model.ChannelMemberIdentifier{
{UserId: user1.Id, ChannelId: channel1.Id},
{UserId: user1.Id, ChannelId: channel2.Id},
{UserId: user2.Id, ChannelId: channel1.Id},
}, map[string]string{
model.DesktopNotifyProp: model.ChannelNotifyNone,
"custom_key": "custom_value",
})
require.Nil(t, appErr)
// User1, Channel1
received := <-messages1
assert.Equal(t, model.WebsocketEventChannelMemberUpdated, received.EventType())
member := decodeJSON(received.GetData()["channelMember"], &model.ChannelMember{})
assert.Equal(t, user1.Id, member.UserId)
assert.Contains(t, []string{channel1.Id, channel2.Id}, member.ChannelId)
assert.Equal(t, model.ChannelNotifyNone, member.NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "custom_value", member.NotifyProps["custom_key"])
assert.Equal(t, model.ChannelNotifyDefault, member.NotifyProps[model.PushNotifyProp])
// User1, Channel2
received = <-messages1
assert.Equal(t, model.WebsocketEventChannelMemberUpdated, received.EventType())
member = decodeJSON(received.GetData()["channelMember"], &model.ChannelMember{})
assert.Equal(t, user1.Id, member.UserId)
assert.Contains(t, []string{channel1.Id, channel2.Id}, member.ChannelId)
assert.Equal(t, model.ChannelNotifyNone, member.NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "custom_value", member.NotifyProps["custom_key"])
assert.Equal(t, model.ChannelNotifyDefault, member.NotifyProps[model.PushNotifyProp])
// User2, Channel1
received = <-messages2
assert.Equal(t, model.WebsocketEventChannelMemberUpdated, received.EventType())
member = decodeJSON(received.GetData()["channelMember"], &model.ChannelMember{})
assert.Equal(t, user2.Id, member.UserId)
assert.Equal(t, channel1.Id, member.ChannelId)
assert.Equal(t, model.ChannelNotifyNone, member.NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "custom_value", member.NotifyProps["custom_key"])
assert.Equal(t, model.ChannelNotifyDefault, member.NotifyProps[model.PushNotifyProp])
})
t.Run("should return an error when trying to update too many users at once", func(t *testing.T) {
identifiers := make([]*model.ChannelMemberIdentifier, 201)
for i := 0; i < len(identifiers); i++ {
identifiers[i] = &model.ChannelMemberIdentifier{UserId: "fakeuser", ChannelId: "fakechannel"}
}
_, appErr := th.App.PatchChannelMembersNotifyProps(th.Context, identifiers, map[string]string{})
assert.NotNil(t, appErr)
})
}

Просмотреть файл

@@ -4,7 +4,11 @@
package app
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -724,3 +728,24 @@ func NewTestId() string {
func (th *TestHelper) NewPluginAPI(manifest *model.Manifest) plugin.API {
return th.App.NewPluginAPI(th.Context, manifest)
}
func decodeJSON[T any](o any, result *T) *T {
var r io.Reader
switch v := o.(type) {
case string:
r = strings.NewReader(v)
case []byte:
r = bytes.NewReader(v)
case io.Reader:
r = v
default:
panic(fmt.Sprintf("Unable to decode JSON from %T (%v)", v, v))
}
err := json.NewDecoder(r).Decode(result)
if err != nil {
panic(err)
}
return result
}

Просмотреть файл

@@ -12990,6 +12990,28 @@ func (a *OpenTracingAppLayer) PatchChannel(c request.CTX, channel *model.Channel
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) PatchChannelMembersNotifyProps(c request.CTX, members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchChannelMembersNotifyProps")
a.ctx = newCtx
a.app.Srv().Store().SetContext(newCtx)
defer func() {
a.app.Srv().Store().SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.PatchChannelMembersNotifyProps(c, members, notifyProps)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
ext.Error.Set(span, true)
}
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) PatchChannelModerationsForChannel(c request.CTX, channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchChannelModerationsForChannel")

Просмотреть файл

@@ -621,6 +621,11 @@ func (api *PluginAPI) UpdateChannelMemberNotifications(channelID, userID string,
return api.app.UpdateChannelMemberNotifyProps(api.ctx, notifications, channelID, userID)
}
func (api *PluginAPI) PatchChannelMembersNotifications(members []*model.ChannelMemberIdentifier, notifications map[string]string) *model.AppError {
_, err := api.app.PatchChannelMembersNotifyProps(api.ctx, members, notifications)
return err
}
func (api *PluginAPI) DeleteChannelMember(channelID, userID string) *model.AppError {
return api.app.LeaveChannel(api.ctx, channelID, userID)
}

Просмотреть файл

@@ -2401,3 +2401,118 @@ func TestPluginServeMetrics(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "METRICS SUBPATH", string(body))
}
func TestPluginUpdateChannelMembersNotifications(t *testing.T) {
t.Run("using API directly", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
api := th.SetupPluginAPI()
channel := th.CreateChannel(th.Context, th.BasicTeam)
th.AddUserToChannel(th.BasicUser, channel)
th.AddUserToChannel(th.BasicUser2, channel)
member1, err := api.GetChannelMember(channel.Id, th.BasicUser.Id)
require.Nil(t, err)
require.Equal(t, "", member1.NotifyProps["test_field"])
require.Equal(t, model.IgnoreChannelMentionsDefault, member1.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
member2, err := api.GetChannelMember(channel.Id, th.BasicUser2.Id)
require.Nil(t, err)
require.Equal(t, "", member2.NotifyProps["test_field"])
require.Equal(t, model.IgnoreChannelMentionsDefault, member2.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
err = api.PatchChannelMembersNotifications(
[]*model.ChannelMemberIdentifier{
{ChannelId: channel.Id, UserId: th.BasicUser.Id},
{ChannelId: channel.Id, UserId: th.BasicUser2.Id},
},
map[string]string{
"test_field": "test_value",
model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsOn,
},
)
require.Nil(t, err)
updated1, err := api.GetChannelMember(member1.ChannelId, member1.UserId)
require.Nil(t, err)
updated2, err := api.GetChannelMember(member2.ChannelId, member2.UserId)
require.Nil(t, err)
assert.Equal(t, member1.NotifyProps[model.MarkUnreadNotifyProp], updated1.NotifyProps[model.MarkUnreadNotifyProp])
assert.Equal(t, "test_value", updated1.NotifyProps["test_field"])
assert.Equal(t, model.IgnoreChannelMentionsOn, updated1.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
assert.Equal(t, member2.NotifyProps[model.MarkUnreadNotifyProp], updated2.NotifyProps[model.MarkUnreadNotifyProp])
assert.Equal(t, "test_value", updated2.NotifyProps["test_field"])
assert.Equal(t, model.IgnoreChannelMentionsOn, updated2.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
})
t.Run("using plugin", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
channel := th.CreateChannel(th.Context, th.BasicTeam)
th.AddUserToChannel(th.BasicUser, channel)
th.AddUserToChannel(th.BasicUser2, channel)
member1, err := th.App.GetChannelMember(th.Context, channel.Id, th.BasicUser.Id)
require.Nil(t, err)
require.Equal(t, "", member1.NotifyProps["test_field"])
require.Equal(t, model.IgnoreChannelMentionsDefault, member1.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
member2, err := th.App.GetChannelMember(th.Context, channel.Id, th.BasicUser2.Id)
require.Nil(t, err)
require.Equal(t, "", member2.NotifyProps["test_field"])
require.Equal(t, model.IgnoreChannelMentionsDefault, member2.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
pluginCode := `
package main
import (
"github.com/mattermost/mattermost/server/public/plugin"
"github.com/mattermost/mattermost/server/public/model"
)
const (
channelID = "` + channel.Id + `"
userID1 = "` + th.BasicUser.Id + `"
userID2 = "` + th.BasicUser2.Id + `"
)
type TestPlugin struct {
plugin.MattermostPlugin
}
func (p *TestPlugin) OnActivate() error {
return p.API.PatchChannelMembersNotifications(
[]*model.ChannelMemberIdentifier{
{ChannelId: channelID, UserId: userID1},
{ChannelId: channelID, UserId: userID2},
},
map[string]string{
"test_field": "test_value",
model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsOn,
},
)
}
func main() {
plugin.ClientMain(&TestPlugin{})
}`
pluginID := "testplugin"
pluginManifest := `{"id": "testplugin", "server": {"executable": "backend.exe"}}`
setupPluginAPITest(t, pluginCode, pluginManifest, pluginID, th.App, th.Context)
updated1, err := th.App.GetChannelMember(th.Context, member1.ChannelId, member1.UserId)
require.Nil(t, err)
updated2, err := th.App.GetChannelMember(th.Context, member2.ChannelId, member2.UserId)
require.Nil(t, err)
assert.Equal(t, member1.NotifyProps[model.MarkUnreadNotifyProp], updated1.NotifyProps[model.MarkUnreadNotifyProp])
assert.Equal(t, "test_value", updated1.NotifyProps["test_field"])
assert.Equal(t, model.IgnoreChannelMentionsOn, updated1.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
assert.Equal(t, member2.NotifyProps[model.MarkUnreadNotifyProp], updated2.NotifyProps[model.MarkUnreadNotifyProp])
assert.Equal(t, "test_value", updated2.NotifyProps["test_field"])
assert.Equal(t, model.IgnoreChannelMentionsOn, updated2.NotifyProps[model.IgnoreChannelMentionsNotifyProp])
})
}