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
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
aafe7439af
Коммит
4d96c11314
@@ -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])
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2090,6 +2090,24 @@ func (s *OpenTracingLayerChannelStore) MigrateChannelMembers(fromChannelID strin
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (s *OpenTracingLayerChannelStore) PatchMultipleMembersNotifyProps(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, error) {
|
||||
origCtx := s.Root.Store.Context()
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(s.Root.Store.Context(), "ChannelStore.PatchMultipleMembersNotifyProps")
|
||||
s.Root.Store.SetContext(newCtx)
|
||||
defer func() {
|
||||
s.Root.Store.SetContext(origCtx)
|
||||
}()
|
||||
|
||||
defer span.Finish()
|
||||
result, err := s.ChannelStore.PatchMultipleMembersNotifyProps(members, notifyProps)
|
||||
if err != nil {
|
||||
span.LogFields(spanlog.Error(err))
|
||||
ext.Error.Set(span, true)
|
||||
}
|
||||
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (s *OpenTracingLayerChannelStore) PermanentDelete(ctx request.CTX, channelID string) error {
|
||||
origCtx := s.Root.Store.Context()
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(s.Root.Store.Context(), "ChannelStore.PermanentDelete")
|
||||
|
||||
@@ -2279,6 +2279,27 @@ func (s *RetryLayerChannelStore) MigrateChannelMembers(fromChannelID string, fro
|
||||
|
||||
}
|
||||
|
||||
func (s *RetryLayerChannelStore) PatchMultipleMembersNotifyProps(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, error) {
|
||||
|
||||
tries := 0
|
||||
for {
|
||||
result, err := s.ChannelStore.PatchMultipleMembersNotifyProps(members, notifyProps)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
if !isRepeatableError(err) {
|
||||
return result, err
|
||||
}
|
||||
tries++
|
||||
if tries >= 3 {
|
||||
err = errors.Wrap(err, "giving up after 3 consecutive repeatable transaction failures")
|
||||
return result, err
|
||||
}
|
||||
timepkg.Sleep(100 * timepkg.Millisecond)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (s *RetryLayerChannelStore) PermanentDelete(ctx request.CTX, channelID string) error {
|
||||
|
||||
tries := 0
|
||||
|
||||
@@ -1922,6 +1922,88 @@ func (s SqlChannelStore) UpdateMemberNotifyProps(channelID, userID string, props
|
||||
return dbMember.ToModel(), err
|
||||
}
|
||||
|
||||
// PatchMultipleMembersNotifyProps updates the NotifyProps of multiple channel members at once without modifying
|
||||
// unspecified fields.
|
||||
//
|
||||
// Note that the returned array may not be in the same order as the provided IDs.
|
||||
func (s SqlChannelStore) PatchMultipleMembersNotifyProps(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, error) {
|
||||
if len(notifyProps) == 0 {
|
||||
return nil, errors.New("PatchMultipleMembersNotifyProps: No notifyProps specified")
|
||||
}
|
||||
|
||||
if err := model.IsChannelMemberNotifyPropsValid(notifyProps, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Make the where clause first since it'll be used multiple times
|
||||
whereClause := sq.Or{}
|
||||
for _, member := range members {
|
||||
whereClause = append(whereClause, sq.And{
|
||||
sq.Eq{"ChannelId": member.ChannelId},
|
||||
sq.Eq{"UserId": member.UserId},
|
||||
})
|
||||
}
|
||||
|
||||
// Update the channel members
|
||||
builder := s.getQueryBuilder().Update("ChannelMembers")
|
||||
|
||||
if s.DriverName() == model.DatabaseDriverPostgres {
|
||||
jsonNotifyProps := string(model.ToJSON(notifyProps))
|
||||
builder = builder.Set("notifyprops", sq.Expr("notifyprops || ?::jsonb", jsonNotifyProps))
|
||||
} else {
|
||||
// Unpack the keys and values to pass to MySQL
|
||||
jsonArgs, jsonSQL := constructMySQLJSONArgs(notifyProps)
|
||||
jsonExpr := sq.Expr(fmt.Sprintf("JSON_SET(NotifyProps, %s)", jsonSQL), jsonArgs...)
|
||||
|
||||
// Example: UPDATE ChannelMembers
|
||||
// SET NotifyProps = JSON_SET(NotifyProps, '$.mark_unread', '"yes"' [, ...])
|
||||
// WHERE ...
|
||||
builder = builder.Set("NotifyProps", jsonExpr)
|
||||
}
|
||||
|
||||
builder = builder.Set("LastUpdateAt", model.GetMillis())
|
||||
|
||||
builder = builder.Where(whereClause)
|
||||
|
||||
transaction, err := s.GetMasterX().Beginx()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "begin_transaction")
|
||||
}
|
||||
defer finalizeTransactionX(transaction, &err)
|
||||
|
||||
transaction.trace = true
|
||||
|
||||
result, err := transaction.ExecBuilder(builder)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "PatchMultipleMembersNotifyProps: Failed to update ChannelMembers")
|
||||
} else if count, _ := result.RowsAffected(); count != int64(len(members)) {
|
||||
return nil, errors.Wrap(err, "PatchMultipleMembersNotifyProps: Unable to update all ChannelMembers, some must not exist")
|
||||
}
|
||||
|
||||
// Get the updated channel members
|
||||
selectSQL, selectArgs, err := s.channelMembersForTeamWithSchemeSelectQuery.
|
||||
Where(whereClause).ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "PatchMultipleMembersNotifyProps_Select_ToSql")
|
||||
}
|
||||
|
||||
var dbMembers []*channelMemberWithSchemeRoles
|
||||
if err := transaction.Select(&dbMembers, selectSQL, selectArgs...); err != nil {
|
||||
return nil, errors.Wrapf(err, "PatchMultipleMembersNotifyProps: Failed to get updated ChannelMembers")
|
||||
}
|
||||
|
||||
if err := transaction.Commit(); err != nil {
|
||||
return nil, errors.Wrap(err, "commit_transaction")
|
||||
}
|
||||
|
||||
updated := make([]*model.ChannelMember, len(dbMembers))
|
||||
for i, dbMember := range dbMembers {
|
||||
updated[i] = dbMember.ToModel()
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (s SqlChannelStore) GetMembers(channelID string, offset, limit int) (model.ChannelMembers, error) {
|
||||
sql, args, err := s.channelMembersForTeamWithSchemeSelectQuery.
|
||||
Where(sq.Eq{
|
||||
|
||||
@@ -225,6 +225,7 @@ type ChannelStore interface {
|
||||
// UpdateMemberNotifyProps patches the notifyProps field with the given props map.
|
||||
// It replaces existing fields and creates new ones which don't exist.
|
||||
UpdateMemberNotifyProps(channelID, userID string, props map[string]string) (*model.ChannelMember, error)
|
||||
PatchMultipleMembersNotifyProps(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, error)
|
||||
GetMembers(channelID string, offset, limit int) (model.ChannelMembers, error)
|
||||
GetMember(ctx context.Context, channelID string, userID string) (*model.ChannelMember, error)
|
||||
GetMemberLastViewedAt(ctx context.Context, channelID string, userID string) (int64, error)
|
||||
|
||||
@@ -90,6 +90,7 @@ func TestChannelStore(t *testing.T, rctx request.CTX, ss store.Store, s SqlStore
|
||||
t.Run("SaveMultipleMembers", func(t *testing.T) { testChannelSaveMultipleMembers(t, rctx, ss) })
|
||||
t.Run("UpdateMember", func(t *testing.T) { testChannelUpdateMember(t, rctx, ss) })
|
||||
t.Run("UpdateMemberNotifyProps", func(t *testing.T) { testChannelUpdateMemberNotifyProps(t, rctx, ss) })
|
||||
t.Run("PatchMultipleMembersNotifyProps", func(t *testing.T) { testChannelPatchMultipleMembersNotifyProps(t, rctx, ss) })
|
||||
t.Run("UpdateMultipleMembers", func(t *testing.T) { testChannelUpdateMultipleMembers(t, rctx, ss) })
|
||||
t.Run("RemoveMember", func(t *testing.T) { testChannelRemoveMember(t, rctx, ss) })
|
||||
t.Run("RemoveMembers", func(t *testing.T) { testChannelRemoveMembers(t, rctx, ss) })
|
||||
@@ -3283,6 +3284,133 @@ func testChannelUpdateMemberNotifyProps(t *testing.T, rctx request.CTX, ss store
|
||||
})
|
||||
}
|
||||
|
||||
func testChannelPatchMultipleMembersNotifyProps(t *testing.T, rctx request.CTX, ss store.Store) {
|
||||
t.Run("should save multiple channel members' notify props at once", func(t *testing.T) {
|
||||
channel1, err := ss.Channel().Save(&model.Channel{
|
||||
Name: model.NewId(),
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, -1)
|
||||
require.NoError(t, err)
|
||||
channel2, err := ss.Channel().Save(&model.Channel{
|
||||
Name: model.NewId(),
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, -1)
|
||||
require.NoError(t, err)
|
||||
|
||||
user1, err := ss.User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
|
||||
require.NoError(t, err)
|
||||
user2, err := ss.User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
|
||||
require.NoError(t, err)
|
||||
original1, err := ss.Channel().SaveMember(&model.ChannelMember{
|
||||
ChannelId: channel1.Id,
|
||||
UserId: user1.Id,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
original2, err := ss.Channel().SaveMember(&model.ChannelMember{
|
||||
ChannelId: channel1.Id,
|
||||
UserId: user2.Id,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
original3, err := ss.Channel().SaveMember(&model.ChannelMember{
|
||||
ChannelId: channel2.Id,
|
||||
UserId: user1.Id,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, model.ChannelNotifyDefault, original1.NotifyProps[model.DesktopNotifyProp])
|
||||
require.Equal(t, model.ChannelAutoFollowThreadsOff, original1.NotifyProps[model.ChannelAutoFollowThreads])
|
||||
require.Equal(t, "", original1.NotifyProps["test_key"])
|
||||
require.Equal(t, model.ChannelNotifyDefault, original2.NotifyProps[model.DesktopNotifyProp])
|
||||
require.Equal(t, model.ChannelAutoFollowThreadsOff, original2.NotifyProps[model.ChannelAutoFollowThreads])
|
||||
require.Equal(t, "", original2.NotifyProps["test_key"])
|
||||
require.Equal(t, model.ChannelNotifyDefault, original3.NotifyProps[model.DesktopNotifyProp])
|
||||
require.Equal(t, model.ChannelAutoFollowThreadsOff, original3.NotifyProps[model.ChannelAutoFollowThreads])
|
||||
require.Equal(t, "", original3.NotifyProps["test_key"])
|
||||
|
||||
// Sleep for 1ms to ensure that the LastUpdateAt will change
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
|
||||
// Save the channel members
|
||||
updated, err := ss.Channel().PatchMultipleMembersNotifyProps(
|
||||
[]*model.ChannelMemberIdentifier{
|
||||
{
|
||||
ChannelId: original1.ChannelId,
|
||||
UserId: original1.UserId,
|
||||
},
|
||||
{
|
||||
ChannelId: original2.ChannelId,
|
||||
UserId: original2.UserId,
|
||||
},
|
||||
{
|
||||
ChannelId: original3.ChannelId,
|
||||
UserId: original3.UserId,
|
||||
},
|
||||
},
|
||||
map[string]string{
|
||||
model.ChannelAutoFollowThreads: model.ChannelAutoFollowThreadsOff,
|
||||
"test_key": "test_value",
|
||||
},
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
// Ensure the specified fields changed and that the unspecified fields did not
|
||||
assert.Equal(t, original1.NotifyProps[model.DesktopNotifyProp], updated[0].NotifyProps[model.DesktopNotifyProp])
|
||||
assert.Equal(t, model.ChannelAutoFollowThreadsOff, updated[0].NotifyProps[model.ChannelAutoFollowThreads])
|
||||
assert.Equal(t, "test_value", updated[0].NotifyProps["test_key"])
|
||||
assert.Equal(t, original2.NotifyProps[model.DesktopNotifyProp], updated[1].NotifyProps[model.DesktopNotifyProp])
|
||||
assert.Equal(t, model.ChannelAutoFollowThreadsOff, updated[1].NotifyProps[model.ChannelAutoFollowThreads])
|
||||
assert.Equal(t, "test_value", updated[1].NotifyProps["test_key"])
|
||||
assert.Equal(t, original3.NotifyProps[model.DesktopNotifyProp], updated[2].NotifyProps[model.DesktopNotifyProp])
|
||||
assert.Equal(t, model.ChannelAutoFollowThreadsOff, updated[2].NotifyProps[model.ChannelAutoFollowThreads])
|
||||
assert.Equal(t, "test_value", updated[2].NotifyProps["test_key"])
|
||||
|
||||
assert.Equal(t, original1.NotifyProps[model.DesktopNotifyProp], updated[0].NotifyProps[model.DesktopNotifyProp])
|
||||
assert.Equal(t, original2.NotifyProps[model.DesktopNotifyProp], updated[1].NotifyProps[model.DesktopNotifyProp])
|
||||
assert.Equal(t, original3.NotifyProps[model.DesktopNotifyProp], updated[2].NotifyProps[model.DesktopNotifyProp])
|
||||
|
||||
// Ensure that LastUpdateAt was updated
|
||||
assert.Greater(t, updated[0].LastUpdateAt, original1.LastUpdateAt)
|
||||
assert.Greater(t, updated[1].LastUpdateAt, original2.LastUpdateAt)
|
||||
assert.Greater(t, updated[2].LastUpdateAt, original3.LastUpdateAt)
|
||||
})
|
||||
|
||||
t.Run("should not allow saving invalid notify props", func(t *testing.T) {
|
||||
channel, err := ss.Channel().Save(&model.Channel{
|
||||
Name: model.NewId(),
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, -1)
|
||||
require.NoError(t, err)
|
||||
|
||||
user, err := ss.User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
|
||||
require.NoError(t, err)
|
||||
_, err = ss.Channel().SaveMember(&model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: user.Id,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Save the channel member
|
||||
_, err = ss.Channel().PatchMultipleMembersNotifyProps(
|
||||
[]*model.ChannelMemberIdentifier{
|
||||
{
|
||||
ChannelId: channel.Id,
|
||||
UserId: user.Id,
|
||||
},
|
||||
},
|
||||
map[string]string{
|
||||
model.MarkUnreadNotifyProp: "garbage",
|
||||
},
|
||||
)
|
||||
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func testChannelRemoveMember(t *testing.T, rctx request.CTX, ss store.Store) {
|
||||
u1, err := ss.User().Save(&model.User{Username: model.NewId(), Email: MakeEmail()})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -1943,6 +1943,32 @@ func (_m *ChannelStore) MigrateChannelMembers(fromChannelID string, fromUserID s
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// PatchMultipleMembersNotifyProps provides a mock function with given fields: members, notifyProps
|
||||
func (_m *ChannelStore) PatchMultipleMembersNotifyProps(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, error) {
|
||||
ret := _m.Called(members, notifyProps)
|
||||
|
||||
var r0 []*model.ChannelMember
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(0).(func([]*model.ChannelMemberIdentifier, map[string]string) ([]*model.ChannelMember, error)); ok {
|
||||
return rf(members, notifyProps)
|
||||
}
|
||||
if rf, ok := ret.Get(0).(func([]*model.ChannelMemberIdentifier, map[string]string) []*model.ChannelMember); ok {
|
||||
r0 = rf(members, notifyProps)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]*model.ChannelMember)
|
||||
}
|
||||
}
|
||||
|
||||
if rf, ok := ret.Get(1).(func([]*model.ChannelMemberIdentifier, map[string]string) error); ok {
|
||||
r1 = rf(members, notifyProps)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// PermanentDelete provides a mock function with given fields: ctx, channelID
|
||||
func (_m *ChannelStore) PermanentDelete(ctx request.CTX, channelID string) error {
|
||||
ret := _m.Called(ctx, channelID)
|
||||
|
||||
@@ -1950,6 +1950,22 @@ func (s *TimerLayerChannelStore) MigrateChannelMembers(fromChannelID string, fro
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (s *TimerLayerChannelStore) PatchMultipleMembersNotifyProps(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, error) {
|
||||
start := time.Now()
|
||||
|
||||
result, err := s.ChannelStore.PatchMultipleMembersNotifyProps(members, notifyProps)
|
||||
|
||||
elapsed := float64(time.Since(start)) / float64(time.Second)
|
||||
if s.Root.Metrics != nil {
|
||||
success := "false"
|
||||
if err == nil {
|
||||
success = "true"
|
||||
}
|
||||
s.Root.Metrics.ObserveStoreMethodDuration("ChannelStore.PatchMultipleMembersNotifyProps", success, elapsed)
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (s *TimerLayerChannelStore) PermanentDelete(ctx request.CTX, channelID string) error {
|
||||
start := time.Now()
|
||||
|
||||
|
||||
Ссылка в новой задаче
Block a user