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])
})
}

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

@@ -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()

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

@@ -5054,6 +5054,14 @@
"id": "app.channel.move_channel.members_do_not_match.error",
"translation": "Unable to move a channel unless all its members are already members of the destination team."
},
{
"id": "app.channel.patch_channel_members_notify_props.app_error",
"translation": "Unable to update channel members' notify props."
},
{
"id": "app.channel.patch_channel_members_notify_props.too_many",
"translation": "Unable to update that many channel members. Only {{.Max}} channel members can be updated at once."
},
{
"id": "app.channel.permanent_delete.app_error",
"translation": "Unable to delete the channel."

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

@@ -4,6 +4,7 @@
package model
import (
"fmt"
"net/http"
"strings"
"unicode/utf8"
@@ -116,38 +117,8 @@ func (o *ChannelMember) IsValid() *AppError {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.user_id.app_error", nil, "", http.StatusBadRequest)
}
notifyLevel := o.NotifyProps[DesktopNotifyProp]
if len(notifyLevel) > 20 || !IsChannelNotifyLevelValid(notifyLevel) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.notify_level.app_error", nil, "notify_level="+notifyLevel, http.StatusBadRequest)
}
markUnreadLevel := o.NotifyProps[MarkUnreadNotifyProp]
if len(markUnreadLevel) > 20 || !IsChannelMarkUnreadLevelValid(markUnreadLevel) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.unread_level.app_error", nil, "mark_unread_level="+markUnreadLevel, http.StatusBadRequest)
}
if pushLevel, ok := o.NotifyProps[PushNotifyProp]; ok {
if len(pushLevel) > 20 || !IsChannelNotifyLevelValid(pushLevel) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.push_level.app_error", nil, "push_notification_level="+pushLevel, http.StatusBadRequest)
}
}
if sendEmail, ok := o.NotifyProps[EmailNotifyProp]; ok {
if len(sendEmail) > 20 || !IsSendEmailValid(sendEmail) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.email_value.app_error", nil, "push_notification_level="+sendEmail, http.StatusBadRequest)
}
}
if ignoreChannelMentions, ok := o.NotifyProps[IgnoreChannelMentionsNotifyProp]; ok {
if len(ignoreChannelMentions) > 40 || !IsIgnoreChannelMentionsValid(ignoreChannelMentions) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.ignore_channel_mentions_value.app_error", nil, "ignore_channel_mentions="+ignoreChannelMentions, http.StatusBadRequest)
}
}
if channelAutoFollowThreads, ok := o.NotifyProps[ChannelAutoFollowThreads]; ok {
if len(channelAutoFollowThreads) > 3 || !IsChannelAutoFollowThreadsValid(channelAutoFollowThreads) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.channel_auto_follow_threads_value.app_error", nil, "channel_auto_follow_threads="+channelAutoFollowThreads, http.StatusBadRequest)
}
if appErr := IsChannelMemberNotifyPropsValid(o.NotifyProps, false); appErr != nil {
return appErr
}
if len(o.Roles) > UserRolesMaxLength {
@@ -155,9 +126,49 @@ func (o *ChannelMember) IsValid() *AppError {
map[string]any{"Limit": UserRolesMaxLength}, "", http.StatusBadRequest)
}
jsonStringNotifyProps := string(ToJSON(o.NotifyProps))
return nil
}
func IsChannelMemberNotifyPropsValid(notifyProps map[string]string, allowMissingFields bool) *AppError {
if notifyLevel, ok := notifyProps[DesktopNotifyProp]; ok || !allowMissingFields {
if len(notifyLevel) > 20 || !IsChannelNotifyLevelValid(notifyLevel) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.notify_level.app_error", nil, "notify_level="+notifyLevel, http.StatusBadRequest)
}
}
if markUnreadLevel, ok := notifyProps[MarkUnreadNotifyProp]; ok || !allowMissingFields {
if len(markUnreadLevel) > 20 || !IsChannelMarkUnreadLevelValid(markUnreadLevel) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.unread_level.app_error", nil, "mark_unread_level="+markUnreadLevel, http.StatusBadRequest)
}
}
if pushLevel, ok := notifyProps[PushNotifyProp]; ok {
if len(pushLevel) > 20 || !IsChannelNotifyLevelValid(pushLevel) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.push_level.app_error", nil, "push_notification_level="+pushLevel, http.StatusBadRequest)
}
}
if sendEmail, ok := notifyProps[EmailNotifyProp]; ok {
if len(sendEmail) > 20 || !IsSendEmailValid(sendEmail) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.email_value.app_error", nil, "push_notification_level="+sendEmail, http.StatusBadRequest)
}
}
if ignoreChannelMentions, ok := notifyProps[IgnoreChannelMentionsNotifyProp]; ok {
if len(ignoreChannelMentions) > 40 || !IsIgnoreChannelMentionsValid(ignoreChannelMentions) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.ignore_channel_mentions_value.app_error", nil, "ignore_channel_mentions="+ignoreChannelMentions, http.StatusBadRequest)
}
}
if channelAutoFollowThreads, ok := notifyProps[ChannelAutoFollowThreads]; ok {
if len(channelAutoFollowThreads) > 3 || !IsChannelAutoFollowThreadsValid(channelAutoFollowThreads) {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.channel_auto_follow_threads_value.app_error", nil, "channel_auto_follow_threads="+channelAutoFollowThreads, http.StatusBadRequest)
}
}
jsonStringNotifyProps := string(ToJSON(notifyProps))
if utf8.RuneCountInString(jsonStringNotifyProps) > ChannelMemberNotifyPropsMaxRunes {
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.notify_props.app_error", nil, "channel_id="+o.ChannelId+" user_id="+o.UserId, http.StatusBadRequest)
return NewAppError("ChannelMember.IsValid", "model.channel_member.is_valid.notify_props.app_error", nil, fmt.Sprint("length=", utf8.RuneCountInString(jsonStringNotifyProps)), http.StatusBadRequest)
}
return nil
@@ -220,3 +231,8 @@ func GetDefaultChannelNotifyProps() StringMap {
ChannelAutoFollowThreads: ChannelAutoFollowThreadsOff,
}
}
type ChannelMemberIdentifier struct {
ChannelId string `json:"channel_id"`
UserId string `json:"user_id"`
}

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

@@ -7,6 +7,7 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -18,8 +19,11 @@ func TestChannelMemberIsValid(t *testing.T) {
o.ChannelId = NewId()
require.NotNil(t, o.IsValid(), "should be invalid")
o.NotifyProps = GetDefaultChannelNotifyProps()
o.UserId = NewId()
require.NotNil(t, o.IsValid(), "should be invalid because of missing notify props")
o.NotifyProps = GetDefaultChannelNotifyProps()
require.Nil(t, o.IsValid(), "should be valid")
o.NotifyProps["desktop"] = "junk"
require.NotNil(t, o.IsValid(), "should be invalid")
@@ -42,3 +46,15 @@ func TestChannelMemberIsValid(t *testing.T) {
o.NotifyProps["property"] = strings.Repeat("Z", ChannelMemberNotifyPropsMaxRunes)
require.NotNil(t, o.IsValid(), "should be invalid")
}
func TestIsChannelMemberNotifyPropsValid(t *testing.T) {
t.Run("should require certain fields unless allowMissingFields is true", func(t *testing.T) {
notifyProps := map[string]string{}
err := IsChannelMemberNotifyPropsValid(notifyProps, false)
assert.NotNil(t, err)
err = IsChannelMemberNotifyPropsValid(notifyProps, true)
assert.Nil(t, err)
})
}

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

@@ -600,6 +600,15 @@ type API interface {
// Minimum server version: 5.2
UpdateChannelMemberNotifications(channelId, userID string, notifications map[string]string) (*model.ChannelMember, *model.AppError)
// PatchChannelMembersNotifications updates the notification properties for multiple channel members.
// Other changes made to the channel memberships will be ignored. A maximum of 200 members can be
// updated at once.
//
// @tag Channel
// @tag User
// Minimum server version: 9.5
PatchChannelMembersNotifications(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) *model.AppError
// GetGroup gets a group by ID.
//
// @tag Group

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

@@ -657,6 +657,13 @@ func (api *apiTimerLayer) UpdateChannelMemberNotifications(channelId, userID str
return _returnsA, _returnsB
}
func (api *apiTimerLayer) PatchChannelMembersNotifications(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) *model.AppError {
startTime := timePkg.Now()
_returnsA := api.apiImpl.PatchChannelMembersNotifications(members, notifyProps)
api.recordTime(startTime, "PatchChannelMembersNotifications", _returnsA == nil)
return _returnsA
}
func (api *apiTimerLayer) GetGroup(groupId string) (*model.Group, *model.AppError) {
startTime := timePkg.Now()
_returnsA, _returnsB := api.apiImpl.GetGroup(groupId)

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

@@ -3663,6 +3663,35 @@ func (s *apiRPCServer) UpdateChannelMemberNotifications(args *Z_UpdateChannelMem
return nil
}
type Z_PatchChannelMembersNotificationsArgs struct {
A []*model.ChannelMemberIdentifier
B map[string]string
}
type Z_PatchChannelMembersNotificationsReturns struct {
A *model.AppError
}
func (g *apiRPCClient) PatchChannelMembersNotifications(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) *model.AppError {
_args := &Z_PatchChannelMembersNotificationsArgs{members, notifyProps}
_returns := &Z_PatchChannelMembersNotificationsReturns{}
if err := g.client.Call("Plugin.PatchChannelMembersNotifications", _args, _returns); err != nil {
log.Printf("RPC call to PatchChannelMembersNotifications API failed: %s", err.Error())
}
return _returns.A
}
func (s *apiRPCServer) PatchChannelMembersNotifications(args *Z_PatchChannelMembersNotificationsArgs, returns *Z_PatchChannelMembersNotificationsReturns) error {
if hook, ok := s.impl.(interface {
PatchChannelMembersNotifications(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) *model.AppError
}); ok {
returns.A = hook.PatchChannelMembersNotifications(args.A, args.B)
} else {
return encodableError(fmt.Errorf("API PatchChannelMembersNotifications called but not implemented."))
}
return nil
}
type Z_GetGroupArgs struct {
A string
}

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

@@ -3226,6 +3226,22 @@ func (_m *API) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot,
return r0, r1
}
// PatchChannelMembersNotifications provides a mock function with given fields: members, notifyProps
func (_m *API) PatchChannelMembersNotifications(members []*model.ChannelMemberIdentifier, notifyProps map[string]string) *model.AppError {
ret := _m.Called(members, notifyProps)
var r0 *model.AppError
if rf, ok := ret.Get(0).(func([]*model.ChannelMemberIdentifier, map[string]string) *model.AppError); ok {
r0 = rf(members, notifyProps)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*model.AppError)
}
}
return r0
}
// PermanentDeleteBot provides a mock function with given fields: botUserId
func (_m *API) PermanentDeleteBot(botUserId string) *model.AppError {
ret := _m.Called(botUserId)