From e37e902ddf3344c06f7d32c9fbf329881a74644f Mon Sep 17 00:00:00 2001 From: catalintomai <56169943+catalintomai@users.noreply.github.com> Date: Sun, 11 Apr 2021 19:54:46 -0700 Subject: [PATCH] MM-29584: Make apps plugin hook invocation/registration conditional (#16769) --- plugin/helpers_bots.go | 24 +++++++++++++++++++++--- plugin/helpers_bots_test.go | 16 ++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/plugin/helpers_bots.go b/plugin/helpers_bots.go index 8b964ae657..31e1f0b4fa 100644 --- a/plugin/helpers_bots.go +++ b/plugin/helpers_bots.go @@ -70,6 +70,7 @@ type shouldProcessMessageOptions struct { FilterChannelIDs []string FilterUserIDs []string OnlyBotDMs bool + BotID string } // AllowSystemMessages configures a call to ShouldProcessMessage to return true for system messages. @@ -126,6 +127,15 @@ func OnlyBotDMs() ShouldProcessMessageOption { } } +// If provided, BotID configures ShouldProcessMessage to skip its retrieval from the store. +// +// By default, posts from all non-bot users are allowed. +func BotID(botID string) ShouldProcessMessageOption { + return func(options *shouldProcessMessageOptions) { + options.BotID = botID + } +} + // ShouldProcessMessage implements Helpers.ShouldProcessMessage func (p *HelpersImpl) ShouldProcessMessage(post *model.Post, options ...ShouldProcessMessageOption) (bool, error) { messageProcessOptions := &shouldProcessMessageOptions{} @@ -133,9 +143,17 @@ func (p *HelpersImpl) ShouldProcessMessage(post *model.Post, options ...ShouldPr option(messageProcessOptions) } - botIDBytes, kvGetErr := p.API.KVGet(BotUserKey) - if kvGetErr != nil { - return false, errors.Wrap(kvGetErr, "failed to get bot") + var botIDBytes []byte + var kvGetErr *model.AppError + + if messageProcessOptions.BotID != "" { + botIDBytes = []byte(messageProcessOptions.BotID) + } else { + botIDBytes, kvGetErr = p.API.KVGet(BotUserKey) + + if kvGetErr != nil { + return false, errors.Wrap(kvGetErr, "failed to get bot") + } } if botIDBytes != nil { diff --git a/plugin/helpers_bots_test.go b/plugin/helpers_bots_test.go index 1d4ec4d43b..8c4089050a 100644 --- a/plugin/helpers_bots_test.go +++ b/plugin/helpers_bots_test.go @@ -560,4 +560,20 @@ func TestShouldProcessMessage(t *testing.T) { assert.True(t, shouldProcessMessage) }) + t.Run("should process the message when we pass the botId as input", func(t *testing.T) { + userID := "user-id" + channelID := "1" + api := setupAPI() + api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) + p.API = api + api.On("GetUser", userID).Return(&model.User{IsBot: false}, nil) + + // we should skip the store Get + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) + + shouldProcessMessage, err := p.ShouldProcessMessage(&model.Post{ChannelId: channelID, UserId: userID}, plugin.BotID(expectedBotID)) + assert.Nil(t, err) + + assert.True(t, shouldProcessMessage) + }) }