From 6dc897b04fe3e91cf8a7616e774a18c8f09fe887 Mon Sep 17 00:00:00 2001 From: Tim Scheuermann Date: Thu, 14 Jul 2022 12:01:29 +0300 Subject: [PATCH] MM-45193 Use context for channel logging (#20575) --- api4/apitestlib.go | 21 +- api4/channel.go | 270 +++++------ api4/channel_category.go | 38 +- api4/channel_local.go | 34 +- api4/channel_test.go | 82 ++-- api4/command.go | 4 +- api4/data_retention.go | 2 +- api4/file.go | 6 +- api4/group.go | 12 +- api4/insights.go | 17 +- api4/insights_test.go | 28 +- api4/integration_action.go | 4 +- api4/post.go | 60 +-- api4/post_test.go | 54 +-- api4/preference.go | 2 +- api4/resolver.go | 14 +- api4/resolver_channel.go | 8 +- api4/resolver_channel_member.go | 10 +- api4/resolver_channel_member_test.go | 4 +- api4/resolver_channel_test.go | 6 +- api4/resolver_sidebar_categories_test.go | 4 +- api4/resolver_team.go | 2 +- api4/resolver_team_member_test.go | 4 +- api4/shared_channel_test.go | 4 +- api4/system.go | 2 +- api4/team.go | 2 +- api4/team_local.go | 2 +- api4/upload.go | 6 +- api4/upload_test.go | 8 +- api4/user.go | 22 +- api4/user_test.go | 24 +- api4/webhook.go | 22 +- api4/webhook_local.go | 2 +- app/app_iface.go | 266 +++++----- app/authorization.go | 28 +- app/authorization_test.go | 12 +- app/auto_responder.go | 4 +- app/channel.go | 444 ++++++++--------- app/channel_category.go | 31 +- app/channel_category_test.go | 115 +++-- app/channel_test.go | 378 +++++++-------- app/channels.go | 8 +- app/command.go | 14 +- app/context.go | 2 +- app/export_test.go | 16 +- app/file.go | 2 +- app/group_test.go | 2 +- app/helper_test.go | 23 +- app/import.go | 4 +- app/import_functions.go | 24 +- app/import_functions_test.go | 172 +++---- app/integration_action.go | 2 +- app/integration_action_test.go | 2 +- app/notification.go | 50 +- app/notification_email.go | 15 +- app/notification_email_test.go | 44 +- app/notification_push.go | 31 +- app/notification_push_test.go | 17 +- app/notification_test.go | 82 ++-- app/opentracing/opentracing_layer.go | 482 +++++++++---------- app/permissions.go | 5 +- app/plugin_api.go | 49 +- app/plugin_commands.go | 2 +- app/plugin_hooks_test.go | 1 + app/plugin_test.go | 2 +- app/post.go | 102 ++-- app/post_metadata.go | 43 +- app/post_metadata_test.go | 104 ++-- app/post_test.go | 162 +++---- app/reaction.go | 4 +- app/reaction_test.go | 4 +- app/request/context.go | 27 +- app/role_test.go | 8 +- app/server.go | 8 +- app/session_test.go | 2 +- app/shared_channel.go | 9 +- app/shared_channel_notifier_test.go | 4 +- app/shared_channel_test.go | 14 +- app/slack.go | 2 +- app/slashcommands/command_channel_header.go | 10 +- app/slashcommands/command_channel_purpose.go | 6 +- app/slashcommands/command_channel_rename.go | 6 +- app/slashcommands/command_groupmsg.go | 4 +- app/slashcommands/command_invite.go | 13 +- app/slashcommands/command_invite_test.go | 2 +- app/slashcommands/command_join.go | 4 +- app/slashcommands/command_leave.go | 6 +- app/slashcommands/command_leave_test.go | 17 +- app/slashcommands/command_loadtest.go | 6 +- app/slashcommands/command_mute.go | 4 +- app/slashcommands/command_mute_test.go | 17 +- app/slashcommands/command_remove.go | 9 +- app/slashcommands/command_remove_test.go | 10 +- app/slashcommands/command_share.go | 24 +- app/slashcommands/command_test.go | 6 +- app/slashcommands/helper_test.go | 8 +- app/syncables.go | 6 +- app/syncables_test.go | 35 +- app/team.go | 14 +- app/team_test.go | 24 +- app/upload.go | 4 +- app/upload_test.go | 28 +- app/user.go | 34 +- app/user_test.go | 86 ++-- app/user_viewmembers_test.go | 6 +- app/web_conn_test.go | 2 +- app/webhook.go | 12 +- app/webhook_test.go | 2 +- services/sharedchannel/attachment.go | 3 +- services/sharedchannel/channelinvite.go | 8 +- services/sharedchannel/channelinvite_test.go | 4 +- services/sharedchannel/mock_AppIface_test.go | 94 ++-- services/sharedchannel/permalink_test.go | 4 +- services/sharedchannel/service.go | 22 +- services/sharedchannel/sync_recv.go | 22 +- services/sharedchannel/sync_send.go | 3 +- services/slackimport/slackimport.go | 27 +- services/slackimport/slackimport_test.go | 10 +- web/handlers.go | 2 + web/saml.go | 2 +- web/web_test.go | 4 +- wsapi/user.go | 3 +- 122 files changed, 2133 insertions(+), 2082 deletions(-) diff --git a/api4/apitestlib.go b/api4/apitestlib.go index 1caa897a55..5ac2a9bac4 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -146,9 +146,10 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent Server: s, ConfigStore: configStore, IncludeCacheLayer: includeCache, - Context: &request.Context{}, + Context: request.EmptyContext(testLogger), TestLogger: testLogger, } + th.Context.SetLogger(testLogger) if s.SearchEngine != nil && s.SearchEngine.BleveEngine != nil && searchEngine != nil { searchEngine.BleveEngine = s.SearchEngine.BleveEngine @@ -467,14 +468,14 @@ func (th *TestHelper) InitBasic() *TestHelper { th.BasicPost = th.CreatePost() th.LinkUserToTeam(th.BasicUser, th.BasicTeam) th.LinkUserToTeam(th.BasicUser2, th.BasicTeam) - th.App.AddUserToChannel(th.BasicUser, th.BasicChannel, false) - th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel, false) - th.App.AddUserToChannel(th.BasicUser, th.BasicChannel2, false) - th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel2, false) - th.App.AddUserToChannel(th.BasicUser, th.BasicPrivateChannel, false) - th.App.AddUserToChannel(th.BasicUser2, th.BasicPrivateChannel, false) - th.App.AddUserToChannel(th.BasicUser, th.BasicDeletedChannel, false) - th.App.AddUserToChannel(th.BasicUser2, th.BasicDeletedChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, th.BasicChannel2, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, th.BasicChannel2, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, th.BasicPrivateChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, th.BasicPrivateChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, th.BasicDeletedChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, th.BasicDeletedChannel, false) th.App.UpdateUserRoles(th.BasicUser.Id, model.SystemUserRoleId, false) th.Client.DeleteChannel(th.BasicDeletedChannel.Id) th.LoginBasic() @@ -894,7 +895,7 @@ func (th *TestHelper) UnlinkUserFromTeam(user *model.User, team *model.Team) { } func (th *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember { - member, err := th.App.AddUserToChannel(user, channel, false) + member, err := th.App.AddUserToChannel(th.Context, user, channel, false) if err != nil { panic(err) } diff --git a/api4/channel.go b/api4/channel.go index 34ec2e058a..72abc6bc0e 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -112,7 +112,7 @@ func createChannel(c *Context, w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(sc); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -138,7 +138,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("updateChannel", audit.Fail) defer c.LogAuditRec(auditRec) - originalOldChannel, appErr := c.App.GetChannel(channel.Id) + originalOldChannel, appErr := c.App.GetChannel(c.AppContext, channel.Id) if appErr != nil { c.Err = appErr return @@ -149,20 +149,20 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { switch oldChannel.Type { case model.ChannelTypeOpen: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePublicChannelProperties) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePublicChannelProperties) { c.SetPermissionError(model.PermissionManagePublicChannelProperties) return } case model.ChannelTypePrivate: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePrivateChannelProperties) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePrivateChannelProperties) { c.SetPermissionError(model.PermissionManagePrivateChannelProperties) return } case model.ChannelTypeGroup, model.ChannelTypeDirect: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. - if _, errGet := c.App.GetChannelMember(context.Background(), channel.Id, c.AppContext.Session().UserId); errGet != nil { + if _, errGet := c.App.GetChannelMember(c.AppContext, channel.Id, c.AppContext.Session().UserId); errGet != nil { c.Err = model.NewAppError("updateChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -207,7 +207,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { oldChannel.GroupConstrained = channel.GroupConstrained } - updatedChannel, appErr := c.App.UpdateChannel(oldChannel) + updatedChannel, appErr := c.App.UpdateChannel(c.AppContext, oldChannel) if appErr != nil { c.Err = appErr return @@ -216,7 +216,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { if oldChannelDisplayName != channel.DisplayName { if err := c.App.PostUpdateChannelDisplayNameMessage(c.AppContext, c.AppContext.Session().UserId, channel, oldChannelDisplayName, channel.DisplayName); err != nil { - mlog.Warn("Error while posting channel display name message", mlog.Err(err)) + c.Logger.Warn("Error while posting channel display name message", mlog.Err(err)) } } @@ -224,7 +224,7 @@ func updateChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("name=" + channel.Name) if err := json.NewEncoder(w).Encode(oldChannel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -241,7 +241,7 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -252,12 +252,12 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", channel) auditRec.AddMeta("new_type", privacy) - if model.ChannelType(privacy) == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionConvertPrivateChannelToPublic) { + if model.ChannelType(privacy) == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionConvertPrivateChannelToPublic) { c.SetPermissionError(model.PermissionConvertPrivateChannelToPublic) return } - if model.ChannelType(privacy) == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionConvertPublicChannelToPrivate) { + if model.ChannelType(privacy) == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionConvertPublicChannelToPrivate) { c.SetPermissionError(model.PermissionConvertPublicChannelToPrivate) return } @@ -286,7 +286,7 @@ func updateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("name=" + updatedChannel.Name) if err := json.NewEncoder(w).Encode(updatedChannel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -302,7 +302,7 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - originalOldChannel, appErr := c.App.GetChannel(c.Params.ChannelId) + originalOldChannel, appErr := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if appErr != nil { c.Err = appErr return @@ -315,20 +315,20 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { switch oldChannel.Type { case model.ChannelTypeOpen: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePublicChannelProperties) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePublicChannelProperties) { c.SetPermissionError(model.PermissionManagePublicChannelProperties) return } case model.ChannelTypePrivate: - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePrivateChannelProperties) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionManagePrivateChannelProperties) { c.SetPermissionError(model.PermissionManagePrivateChannelProperties) return } case model.ChannelTypeGroup, model.ChannelTypeDirect: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. - if _, appErr = c.App.GetChannelMember(context.Background(), c.Params.ChannelId, c.AppContext.Session().UserId); appErr != nil { + if _, appErr = c.App.GetChannelMember(c.AppContext, c.Params.ChannelId, c.AppContext.Session().UserId); appErr != nil { c.Err = model.NewAppError("patchChannel", "api.channel.patch_update_channel.forbidden.app_error", nil, "", http.StatusForbidden) return } @@ -351,7 +351,7 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - appErr = c.App.FillInChannelProps(rchannel) + appErr = c.App.FillInChannelProps(c.AppContext, rchannel) if appErr != nil { c.Err = appErr return @@ -362,7 +362,7 @@ func patchChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("patch", rchannel) if err := json.NewEncoder(w).Encode(rchannel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -372,7 +372,7 @@ func restoreChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -398,7 +398,7 @@ func restoreChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("name=" + channel.Name) if err := json.NewEncoder(w).Encode(channel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -463,7 +463,7 @@ func createDirectChannel(c *Context, w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(sc); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -475,14 +475,14 @@ func searchGroupChannels(c *Context, w http.ResponseWriter, r *http.Request) { return } - groupChannels, appErr := c.App.SearchGroupChannels(c.AppContext.Session().UserId, props.Term) + groupChannels, appErr := c.App.SearchGroupChannels(c.AppContext, c.AppContext.Session().UserId, props.Term) if appErr != nil { c.Err = appErr return } if err := json.NewEncoder(w).Encode(groupChannels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -536,7 +536,7 @@ func createGroupChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - groupChannel, err := c.App.CreateGroupChannel(userIds, c.AppContext.Session().UserId) + groupChannel, err := c.App.CreateGroupChannel(c.AppContext, userIds, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -547,7 +547,7 @@ func createGroupChannel(c *Context, w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(groupChannel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -557,32 +557,32 @@ func getChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return } if channel.Type == model.ChannelTypeOpen { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadPublicChannel) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } } - err = c.App.FillInChannelProps(channel) + err = c.App.FillInChannelProps(c.AppContext, channel) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -597,19 +597,19 @@ func getChannelUnread(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - channelUnread, err := c.App.GetChannelUnread(c.Params.ChannelId, c.Params.UserId) + channelUnread, err := c.App.GetChannelUnread(c.AppContext, c.Params.ChannelId, c.Params.UserId) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channelUnread); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -619,30 +619,30 @@ func getChannelStats(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - memberCount, err := c.App.GetChannelMemberCount(c.Params.ChannelId) + memberCount, err := c.App.GetChannelMemberCount(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return } - guestCount, err := c.App.GetChannelGuestCount(c.Params.ChannelId) + guestCount, err := c.App.GetChannelGuestCount(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return } - pinnedPostCount, err := c.App.GetChannelPinnedPostCount(c.Params.ChannelId) + pinnedPostCount, err := c.App.GetChannelPinnedPostCount(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return } - filesCount, err := c.App.GetChannelFileCount(c.Params.ChannelId) + filesCount, err := c.App.GetChannelFileCount(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -656,7 +656,7 @@ func getChannelStats(c *Context, w http.ResponseWriter, r *http.Request) { FilesCount: filesCount, } if err := json.NewEncoder(w).Encode(stats); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -666,12 +666,12 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - posts, err := c.App.GetPinnedPosts(c.Params.ChannelId) + posts, err := c.App.GetPinnedPosts(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -681,8 +681,8 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { return } - clientPostList := c.App.PreparePostListForClient(posts) - clientPostList, err = c.App.SanitizePostListMetadataForUser(clientPostList, c.AppContext.Session().UserId) + clientPostList := c.App.PreparePostListForClient(c.AppContext, posts) + clientPostList, err = c.App.SanitizePostListMetadataForUser(c.AppContext, clientPostList, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -690,7 +690,7 @@ func getPinnedPosts(c *Context, w http.ResponseWriter, r *http.Request) { w.Header().Set(model.HeaderEtagServer, clientPostList.Etag()) if err := clientPostList.EncodeJSON(w); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -719,14 +719,14 @@ func getAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { opts.IncludePolicyID = true } - channels, err := c.App.GetAllChannels(c.Params.Page, c.Params.PerPage, opts) + channels, err := c.App.GetAllChannels(c.AppContext, c.Params.Page, c.Params.PerPage, opts) if err != nil { c.Err = err return } if c.Params.IncludeTotalCount { - totalCount, err := c.App.GetAllChannelsCount(opts) + totalCount, err := c.App.GetAllChannelsCount(c.AppContext, opts) if err != nil { c.Err = err return @@ -736,13 +736,13 @@ func getAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { TotalCount: totalCount, } if err := json.NewEncoder(w).Encode(cwc); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -757,20 +757,20 @@ func getPublicChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request return } - channels, err := c.App.GetPublicChannelsForTeam(c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage) + channels, err := c.App.GetPublicChannelsForTeam(c.AppContext, c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage) if err != nil { c.Err = err return } - err = c.App.FillInChannelsProps(channels) + err = c.App.FillInChannelsProps(c.AppContext, channels) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -780,20 +780,20 @@ func getDeletedChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Reques return } - channels, err := c.App.GetDeletedChannels(c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage, c.AppContext.Session().UserId) + channels, err := c.App.GetDeletedChannels(c.AppContext, c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage, c.AppContext.Session().UserId) if err != nil { c.Err = err return } - err = c.App.FillInChannelsProps(channels) + err = c.App.FillInChannelsProps(c.AppContext, channels) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -808,20 +808,20 @@ func getPrivateChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Reques return } - channels, err := c.App.GetPrivateChannelsForTeam(c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage) + channels, err := c.App.GetPrivateChannelsForTeam(c.AppContext, c.Params.TeamId, c.Params.Page*c.Params.PerPage, c.Params.PerPage) if err != nil { c.Err = err return } - err = c.App.FillInChannelsProps(channels) + err = c.App.FillInChannelsProps(c.AppContext, channels) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -849,20 +849,20 @@ func getPublicChannelsByIdsForTeam(c *Context, w http.ResponseWriter, r *http.Re return } - channels, err := c.App.GetPublicChannelsByIdsForTeam(c.Params.TeamId, channelIds) + channels, err := c.App.GetPublicChannelsByIdsForTeam(c.AppContext, c.Params.TeamId, channelIds) if err != nil { c.Err = err return } - err = c.App.FillInChannelsProps(channels) + err = c.App.FillInChannelsProps(c.AppContext, channels) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -892,7 +892,7 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques return } - channels, err := c.App.GetChannelsForTeamForUser(c.Params.TeamId, c.Params.UserId, &model.ChannelSearchOpts{ + channels, err := c.App.GetChannelsForTeamForUser(c.AppContext, c.Params.TeamId, c.Params.UserId, &model.ChannelSearchOpts{ IncludeDeleted: c.Params.IncludeDeleted, LastDeleteAt: lastDeleteAt, }) @@ -905,7 +905,7 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques return } - err = c.App.FillInChannelsProps(channels) + err = c.App.FillInChannelsProps(c.AppContext, channels) if err != nil { c.Err = err return @@ -913,7 +913,7 @@ func getChannelsForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques w.Header().Set(model.HeaderEtagServer, channels.Etag()) if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -950,7 +950,7 @@ func getChannelsForUser(c *Context, w http.ResponseWriter, r *http.Request) { w.Write([]byte(`[`)) enc := json.NewEncoder(w) for { - channels, err := c.App.GetChannelsForUser(c.Params.UserId, c.Params.IncludeDeleted, lastDeleteAt, pageSize, fromChannelID) + channels, err := c.App.GetChannelsForUser(c.AppContext, c.Params.UserId, c.Params.IncludeDeleted, lastDeleteAt, pageSize, fromChannelID) if err != nil { // If the page size was a perfect multiple of the total number of results, // then the last query will always return zero results. @@ -961,7 +961,7 @@ func getChannelsForUser(c *Context, w http.ResponseWriter, r *http.Request) { return } - err = c.App.FillInChannelsProps(channels) + err = c.App.FillInChannelsProps(c.AppContext, channels) if err != nil { c.Err = err return @@ -974,7 +974,7 @@ func getChannelsForUser(c *Context, w http.ResponseWriter, r *http.Request) { for i, ch := range channels { if err := enc.Encode(ch); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } if i < len(channels)-1 { w.Write([]byte(`,`)) @@ -1003,7 +1003,7 @@ func autocompleteChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Requ name := r.URL.Query().Get("name") - channels, err := c.App.AutocompleteChannelsForTeam(c.Params.TeamId, c.AppContext.Session().UserId, name) + channels, err := c.App.AutocompleteChannelsForTeam(c.AppContext, c.Params.TeamId, c.AppContext.Session().UserId, name) if err != nil { c.Err = err return @@ -1012,7 +1012,7 @@ func autocompleteChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Requ // Don't fill in channels props, since unused by client and potentially expensive. if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1024,14 +1024,14 @@ func autocompleteChannelsForTeamForSearch(c *Context, w http.ResponseWriter, r * name := r.URL.Query().Get("name") - channels, err := c.App.AutocompleteChannelsForSearch(c.Params.TeamId, c.AppContext.Session().UserId, name) + channels, err := c.App.AutocompleteChannelsForSearch(c.AppContext, c.Params.TeamId, c.AppContext.Session().UserId, name) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1051,7 +1051,7 @@ func searchChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request) { var channels model.ChannelList var appErr *model.AppError if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionListTeamChannels) { - channels, appErr = c.App.SearchChannels(c.Params.TeamId, props.Term) + channels, appErr = c.App.SearchChannels(c.AppContext, c.Params.TeamId, props.Term) } else { // If the user is not a team member, return a 404 if _, appErr = c.App.GetTeamMember(c.Params.TeamId, c.AppContext.Session().UserId); appErr != nil { @@ -1059,7 +1059,7 @@ func searchChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - channels, appErr = c.App.SearchChannelsForUser(c.AppContext.Session().UserId, c.Params.TeamId, props.Term) + channels, appErr = c.App.SearchChannelsForUser(c.AppContext, c.AppContext.Session().UserId, c.Params.TeamId, props.Term) } if appErr != nil { @@ -1070,7 +1070,7 @@ func searchChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Request) { // Don't fill in channels props, since unused by client and potentially expensive. if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1090,7 +1090,7 @@ func searchArchivedChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Re var channels model.ChannelList var appErr *model.AppError if c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), c.Params.TeamId, model.PermissionListTeamChannels) { - channels, appErr = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.AppContext.Session().UserId) + channels, appErr = c.App.SearchArchivedChannels(c.AppContext, c.Params.TeamId, props.Term, c.AppContext.Session().UserId) } else { // If the user is not a team member, return a 404 if _, appErr = c.App.GetTeamMember(c.Params.TeamId, c.AppContext.Session().UserId); appErr != nil { @@ -1098,7 +1098,7 @@ func searchArchivedChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Re return } - channels, appErr = c.App.SearchArchivedChannels(c.Params.TeamId, props.Term, c.AppContext.Session().UserId) + channels, appErr = c.App.SearchArchivedChannels(c.AppContext, c.Params.TeamId, props.Term, c.AppContext.Session().UserId) } if appErr != nil { @@ -1109,7 +1109,7 @@ func searchArchivedChannelsForTeam(c *Context, w http.ResponseWriter, r *http.Re // Don't fill in channels props, since unused by client and potentially expensive. if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1133,14 +1133,14 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { if !fromSysConsole { // If the request is not coming from system_console, only show the user level channels // from all teams. - channels, err := c.App.AutocompleteChannels(c.AppContext.Session().UserId, props.Term) + channels, err := c.App.AutocompleteChannels(c.AppContext, c.AppContext.Session().UserId, props.Term) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } return } @@ -1177,7 +1177,7 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { opts.IncludePolicyID = true } - channels, totalCount, appErr := c.App.SearchAllChannels(props.Term, opts) + channels, totalCount, appErr := c.App.SearchAllChannels(c.AppContext, props.Term, opts) if appErr != nil { c.Err = appErr return @@ -1188,13 +1188,13 @@ func searchAllChannels(c *Context, w http.ResponseWriter, r *http.Request) { data := model.ChannelsWithCount{Channels: channels, TotalCount: totalCount} if err := json.NewEncoder(w).Encode(data); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } return } if err := json.NewEncoder(w).Encode(channels); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1204,7 +1204,7 @@ func deleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -1219,19 +1219,19 @@ func deleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionDeletePublicChannel) { + if channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionDeletePublicChannel) { c.SetPermissionError(model.PermissionDeletePublicChannel) return } - if channel.Type == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionDeletePrivateChannel) { + if channel.Type == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionDeletePrivateChannel) { c.SetPermissionError(model.PermissionDeletePrivateChannel) return } if c.Params.Permanent { if *c.App.Config().ServiceSettings.EnableAPIChannelDeletion { - err = c.App.PermanentDeleteChannel(channel) + err = c.App.PermanentDeleteChannel(c.AppContext, channel) } else { err = model.NewAppError("deleteChannel", "api.user.delete_channel.not_enabled.app_error", nil, "channelId="+c.Params.ChannelId, http.StatusUnauthorized) } @@ -1256,32 +1256,32 @@ func getChannelByName(c *Context, w http.ResponseWriter, r *http.Request) { } includeDeleted, _ := strconv.ParseBool(r.URL.Query().Get("include_deleted")) - channel, appErr := c.App.GetChannelByName(c.Params.ChannelName, c.Params.TeamId, includeDeleted) + channel, appErr := c.App.GetChannelByName(c.AppContext, c.Params.ChannelName, c.Params.TeamId, includeDeleted) if appErr != nil { c.Err = appErr return } if channel.Type == model.ChannelTypeOpen { - if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadPublicChannel) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { c.Err = model.NewAppError("getChannelByName", "app.channel.get_by_name.missing.app_error", nil, "teamId="+channel.TeamId+", "+"name="+channel.Name+"", http.StatusNotFound) return } } - appErr = c.App.FillInChannelProps(channel) + appErr = c.App.FillInChannelProps(c.AppContext, channel) if appErr != nil { c.Err = appErr return } if err := json.NewEncoder(w).Encode(channel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1292,14 +1292,14 @@ func getChannelByNameForTeamName(c *Context, w http.ResponseWriter, r *http.Requ } includeDeleted, _ := strconv.ParseBool(r.URL.Query().Get("include_deleted")) - channel, appErr := c.App.GetChannelByNameForTeamName(c.Params.ChannelName, c.Params.TeamName, includeDeleted) + channel, appErr := c.App.GetChannelByNameForTeamName(c.AppContext, c.Params.ChannelName, c.Params.TeamName, includeDeleted) if appErr != nil { c.Err = appErr return } teamOk := c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel) - channelOk := c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) + channelOk := c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionReadChannel) if channel.Type == model.ChannelTypeOpen { if !teamOk && !channelOk { @@ -1311,14 +1311,14 @@ func getChannelByNameForTeamName(c *Context, w http.ResponseWriter, r *http.Requ return } - appErr = c.App.FillInChannelProps(channel) + appErr = c.App.FillInChannelProps(c.AppContext, channel) if appErr != nil { c.Err = appErr return } if err := json.NewEncoder(w).Encode(channel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1328,19 +1328,19 @@ func getChannelMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - members, err := c.App.GetChannelMembersPage(c.Params.ChannelId, c.Params.Page, c.Params.PerPage) + members, err := c.App.GetChannelMembersPage(c.AppContext, c.Params.ChannelId, c.Params.Page, c.Params.PerPage) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(members); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1350,12 +1350,12 @@ func getChannelMembersTimezones(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - membersTimezones, err := c.App.GetChannelMembersTimezones(c.Params.ChannelId) + membersTimezones, err := c.App.GetChannelMembersTimezones(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -1376,19 +1376,19 @@ func getChannelMembersByIds(c *Context, w http.ResponseWriter, r *http.Request) return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - members, err := c.App.GetChannelMembersByIds(c.Params.ChannelId, userIds) + members, err := c.App.GetChannelMembersByIds(c.AppContext, c.Params.ChannelId, userIds) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(members); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1398,19 +1398,21 @@ func getChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - member, err := c.App.GetChannelMember(app.WithMaster(context.Background()), c.Params.ChannelId, c.Params.UserId) + ctx := c.AppContext + ctx.SetContext(app.WithMaster(ctx.Context())) + member, err := c.App.GetChannelMember(ctx, c.Params.ChannelId, c.Params.UserId) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(member); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1430,14 +1432,14 @@ func getChannelMembersForTeamForUser(c *Context, w http.ResponseWriter, r *http. return } - members, err := c.App.GetChannelMembersForUser(c.Params.TeamId, c.Params.UserId) + members, err := c.App.GetChannelMembersForUser(c.AppContext, c.Params.TeamId, c.Params.UserId) if err != nil { c.Err = err return } if err := json.NewEncoder(w).Encode(members); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1469,7 +1471,7 @@ func viewChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - times, err := c.App.ViewChannel(&view, c.Params.UserId, c.AppContext.Session().Id, view.CollapsedThreadsSupported) + times, err := c.App.ViewChannel(c.AppContext, &view, c.Params.UserId, c.AppContext.Session().Id, view.CollapsedThreadsSupported) if err != nil { c.Err = err return @@ -1485,7 +1487,7 @@ func viewChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if err := json.NewEncoder(w).Encode(resp); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1508,12 +1510,12 @@ func updateChannelMemberRoles(c *Context, w http.ResponseWriter, r *http.Request auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("roles", newRoles) - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManageChannelRoles) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionManageChannelRoles) { c.SetPermissionError(model.PermissionManageChannelRoles) return } - if _, err := c.App.UpdateChannelMemberRoles(c.Params.ChannelId, c.Params.UserId, newRoles); err != nil { + if _, err := c.App.UpdateChannelMemberRoles(c.AppContext, c.Params.ChannelId, c.Params.UserId, newRoles); err != nil { c.Err = err return } @@ -1540,12 +1542,12 @@ func updateChannelMemberSchemeRoles(c *Context, w http.ResponseWriter, r *http.R auditRec.AddMeta("channel_id", c.Params.ChannelId) auditRec.AddMeta("roles", schemeRoles) - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionManageChannelRoles) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionManageChannelRoles) { c.SetPermissionError(model.PermissionManageChannelRoles) return } - if _, err := c.App.UpdateChannelMemberSchemeRoles(c.Params.ChannelId, c.Params.UserId, schemeRoles.SchemeGuest, schemeRoles.SchemeUser, schemeRoles.SchemeAdmin); err != nil { + if _, err := c.App.UpdateChannelMemberSchemeRoles(c.AppContext, c.Params.ChannelId, c.Params.UserId, schemeRoles.SchemeGuest, schemeRoles.SchemeUser, schemeRoles.SchemeAdmin); err != nil { c.Err = err return } @@ -1577,7 +1579,7 @@ func updateChannelMemberNotifyProps(c *Context, w http.ResponseWriter, r *http.R return } - _, err := c.App.UpdateChannelMemberNotifyProps(props, c.Params.ChannelId, c.Params.UserId) + _, err := c.App.UpdateChannelMemberNotifyProps(c.AppContext, props, c.Params.ChannelId, c.Params.UserId) if err != nil { c.Err = err return @@ -1624,7 +1626,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } } - channel, err := c.App.GetChannel(member.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, member.ChannelId) if err != nil { c.Err = err return @@ -1640,7 +1642,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } isNewMembership := false - if _, err = c.App.GetChannelMember(context.Background(), member.ChannelId, member.UserId); err != nil { + if _, err = c.App.GetChannelMember(c.AppContext, member.ChannelId, member.UserId); err != nil { if err.Id == app.MissingChannelMemberError { isNewMembership = true } else { @@ -1660,7 +1662,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } else if isSelfAdd && !isNewMembership { // nothing to do, since already in the channel } else if !isSelfAdd { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePublicChannelMembers) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionManagePublicChannelMembers) { c.SetPermissionError(model.PermissionManagePublicChannelMembers) return } @@ -1669,14 +1671,14 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { if channel.Type == model.ChannelTypePrivate { if isSelfAdd && isNewMembership { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { c.SetPermissionError(model.PermissionManagePrivateChannelMembers) return } } else if isSelfAdd && !isNewMembership { // nothing to do, since already in the channel } else if !isSelfAdd { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { c.SetPermissionError(model.PermissionManagePrivateChannelMembers) return } @@ -1709,7 +1711,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } if postRootId != "" { - err := c.App.UpdateThreadFollowForUserFromChannelAdd(cm.UserId, channel.TeamId, postRootId) + err := c.App.UpdateThreadFollowForUserFromChannelAdd(c.AppContext, cm.UserId, channel.TeamId, postRootId) if err != nil { c.Err = err return @@ -1722,7 +1724,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(cm); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -1732,7 +1734,7 @@ func removeChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -1760,12 +1762,12 @@ func removeChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } if c.Params.UserId != c.AppContext.Session().UserId { - if channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePublicChannelMembers) { + if channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionManagePublicChannelMembers) { c.SetPermissionError(model.PermissionManagePublicChannelMembers) return } - if channel.Type == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { + if channel.Type == model.ChannelTypePrivate && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionManagePrivateChannelMembers) { c.SetPermissionError(model.PermissionManagePrivateChannelMembers) return } @@ -1820,7 +1822,7 @@ func updateChannelScheme(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -1831,7 +1833,7 @@ func updateChannelScheme(c *Context, w http.ResponseWriter, r *http.Request) { channel.SchemeId = &scheme.Id - _, err = c.App.UpdateChannelScheme(channel) + _, err = c.App.UpdateChannelScheme(c.AppContext, channel) if err != nil { c.Err = err return @@ -1903,7 +1905,7 @@ func channelMemberCountsByGroup(c *Context, w http.ResponseWriter, r *http.Reque return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } @@ -1941,13 +1943,13 @@ func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return } - channelModerations, err := c.App.GetChannelModerationsForChannel(channel) + channelModerations, err := c.App.GetChannelModerationsForChannel(c.AppContext, channel) if err != nil { c.Err = err return @@ -1981,7 +1983,7 @@ func patchChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) return } - channel, appErr := c.App.GetChannel(c.Params.ChannelId) + channel, appErr := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if appErr != nil { c.Err = appErr return @@ -1995,7 +1997,7 @@ func patchChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) return } - channelModerations, appErr := c.App.PatchChannelModerationsForChannel(channel, channelModerationsPatch) + channelModerations, appErr := c.App.PatchChannelModerationsForChannel(c.AppContext, channel, channelModerationsPatch) if appErr != nil { c.Err = appErr return @@ -2018,7 +2020,7 @@ func moveChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -2066,7 +2068,7 @@ func moveChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - err = c.App.RemoveAllDeactivatedMembersFromChannel(channel) + err = c.App.RemoveAllDeactivatedMembersFromChannel(c.AppContext, channel) if err != nil { c.Err = err return @@ -2091,6 +2093,6 @@ func moveChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("team=" + team.Name) if err := json.NewEncoder(w).Encode(channel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } diff --git a/api4/channel_category.go b/api4/channel_category.go index f46b6a2fec..fe9c0c0ef3 100644 --- a/api4/channel_category.go +++ b/api4/channel_category.go @@ -23,7 +23,7 @@ func getCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.Requ return } - categories, err := c.App.GetSidebarCategoriesForTeamForUser(c.Params.UserId, c.Params.TeamId) + categories, err := c.App.GetSidebarCategoriesForTeamForUser(c.AppContext, c.Params.UserId, c.Params.TeamId) if err != nil { c.Err = err return @@ -64,7 +64,7 @@ func createCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req return } - category, appErr := c.App.CreateSidebarCategory(c.Params.UserId, c.Params.TeamId, &categoryCreateRequest) + category, appErr := c.App.CreateSidebarCategory(c.AppContext, c.Params.UserId, c.Params.TeamId, &categoryCreateRequest) if appErr != nil { c.Err = appErr return @@ -92,7 +92,7 @@ func getCategoryOrderForTeamForUser(c *Context, w http.ResponseWriter, r *http.R return } - order, err := c.App.GetSidebarCategoryOrder(c.Params.UserId, c.Params.TeamId) + order, err := c.App.GetSidebarCategoryOrder(c.AppContext, c.Params.UserId, c.Params.TeamId) if err != nil { c.Err = err return @@ -118,13 +118,13 @@ func updateCategoryOrderForTeamForUser(c *Context, w http.ResponseWriter, r *htt categoryOrder := model.ArrayFromJSON(r.Body) for _, categoryId := range categoryOrder { - if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, categoryId) { + if !c.App.SessionHasPermissionToCategory(c.AppContext, *c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, categoryId) { c.SetInvalidParam("category") return } } - err := c.App.UpdateSidebarCategoryOrder(c.Params.UserId, c.Params.TeamId, categoryOrder) + err := c.App.UpdateSidebarCategoryOrder(c.AppContext, c.Params.UserId, c.Params.TeamId, categoryOrder) if err != nil { c.Err = err return @@ -140,12 +140,12 @@ func getCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Reques return } - if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { + if !c.App.SessionHasPermissionToCategory(c.AppContext, *c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { c.SetPermissionError(model.PermissionEditOtherUsers) return } - categories, err := c.App.GetSidebarCategory(c.Params.CategoryId) + categories, err := c.App.GetSidebarCategory(c.AppContext, c.Params.CategoryId) if err != nil { c.Err = err return @@ -182,7 +182,7 @@ func updateCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.R } for _, category := range categoriesUpdateRequest { - if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, category.Id) { + if !c.App.SessionHasPermissionToCategory(c.AppContext, *c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, category.Id) { c.SetInvalidParam("category") return } @@ -193,7 +193,7 @@ func updateCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.R return } - categories, appErr := c.App.UpdateSidebarCategories(c.Params.UserId, c.Params.TeamId, categoriesUpdateRequest) + categories, appErr := c.App.UpdateSidebarCategories(c.AppContext, c.Params.UserId, c.Params.TeamId, categoriesUpdateRequest) if appErr != nil { c.Err = appErr return @@ -210,7 +210,7 @@ func updateCategoriesForTeamForUser(c *Context, w http.ResponseWriter, r *http.R } func validateSidebarCategory(c *Context, teamId, userId string, category *model.SidebarCategoryWithChannels) *model.AppError { - channels, err := c.App.GetChannelsForTeamForUser(teamId, userId, &model.ChannelSearchOpts{ + channels, err := c.App.GetChannelsForTeamForUser(c.AppContext, teamId, userId, &model.ChannelSearchOpts{ IncludeDeleted: true, LastDeleteAt: 0, }) @@ -218,13 +218,13 @@ func validateSidebarCategory(c *Context, teamId, userId string, category *model. return model.NewAppError("validateSidebarCategory", "api.invalid_channel", nil, err.Error(), http.StatusBadRequest) } - category.Channels = validateSidebarCategoryChannels(userId, category.Channels, channels) + category.Channels = validateSidebarCategoryChannels(c, userId, category.Channels, channels) return nil } func validateSidebarCategories(c *Context, teamId, userId string, categories []*model.SidebarCategoryWithChannels) *model.AppError { - channels, err := c.App.GetChannelsForTeamForUser(teamId, userId, &model.ChannelSearchOpts{ + channels, err := c.App.GetChannelsForTeamForUser(c.AppContext, teamId, userId, &model.ChannelSearchOpts{ IncludeDeleted: true, LastDeleteAt: 0, }) @@ -233,13 +233,13 @@ func validateSidebarCategories(c *Context, teamId, userId string, categories []* } for _, category := range categories { - category.Channels = validateSidebarCategoryChannels(userId, category.Channels, channels) + category.Channels = validateSidebarCategoryChannels(c, userId, category.Channels, channels) } return nil } -func validateSidebarCategoryChannels(userId string, channelIds []string, channels model.ChannelList) []string { +func validateSidebarCategoryChannels(c *Context, userId string, channelIds []string, channels model.ChannelList) []string { var filtered []string for _, channelId := range channelIds { @@ -254,7 +254,7 @@ func validateSidebarCategoryChannels(userId string, channelIds []string, channel if found { filtered = append(filtered, channelId) } else { - mlog.Info("Stopping user from adding channel to their sidebar when they are not a member", mlog.String("user_id", userId), mlog.String("channel_id", channelId)) + c.Logger.Info("Stopping user from adding channel to their sidebar when they are not a member", mlog.String("user_id", userId), mlog.String("channel_id", channelId)) } } @@ -267,7 +267,7 @@ func updateCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req return } - if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { + if !c.App.SessionHasPermissionToCategory(c.AppContext, *c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -289,7 +289,7 @@ func updateCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req categoryUpdateRequest.Id = c.Params.CategoryId - categories, appErr := c.App.UpdateSidebarCategories(c.Params.UserId, c.Params.TeamId, []*model.SidebarCategoryWithChannels{&categoryUpdateRequest}) + categories, appErr := c.App.UpdateSidebarCategories(c.AppContext, c.Params.UserId, c.Params.TeamId, []*model.SidebarCategoryWithChannels{&categoryUpdateRequest}) if appErr != nil { c.Err = appErr return @@ -311,7 +311,7 @@ func deleteCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req return } - if !c.App.SessionHasPermissionToCategory(*c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { + if !c.App.SessionHasPermissionToCategory(c.AppContext, *c.AppContext.Session(), c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) { c.SetPermissionError(model.PermissionEditOtherUsers) return } @@ -319,7 +319,7 @@ func deleteCategoryForTeamForUser(c *Context, w http.ResponseWriter, r *http.Req auditRec := c.MakeAuditRecord("deleteCategoryForTeamForUser", audit.Fail) defer c.LogAuditRec(auditRec) - appErr := c.App.DeleteSidebarCategory(c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) + appErr := c.App.DeleteSidebarCategory(c.AppContext, c.Params.UserId, c.Params.TeamId, c.Params.CategoryId) if appErr != nil { c.Err = appErr return diff --git a/api4/channel_local.go b/api4/channel_local.go index 8119d956b7..5784d63a3e 100644 --- a/api4/channel_local.go +++ b/api4/channel_local.go @@ -61,7 +61,7 @@ func localCreateChannel(c *Context, w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(sc); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -78,7 +78,7 @@ func localUpdateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Reques return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -105,7 +105,7 @@ func localUpdateChannelPrivacy(c *Context, w http.ResponseWriter, r *http.Reques c.LogAudit("name=" + updatedChannel.Name) if err := json.NewEncoder(w).Encode(updatedChannel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -115,7 +115,7 @@ func localRestoreChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -135,7 +135,7 @@ func localRestoreChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("name=" + channel.Name) if err := json.NewEncoder(w).Encode(channel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -175,7 +175,7 @@ func localAddChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { } } - channel, err := c.App.GetChannel(member.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, member.ChannelId) if err != nil { c.Err = err return @@ -220,7 +220,7 @@ func localAddChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(cm); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -230,7 +230,7 @@ func localRemoveChannelMember(c *Context, w http.ResponseWriter, r *http.Request return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -281,7 +281,7 @@ func localPatchChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - originalOldChannel, appErr := c.App.GetChannel(c.Params.ChannelId) + originalOldChannel, appErr := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if appErr != nil { c.Err = appErr return @@ -293,13 +293,13 @@ func localPatchChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("channel", channel) channel.Patch(patch) - rchannel, appErr := c.App.UpdateChannel(channel) + rchannel, appErr := c.App.UpdateChannel(c.AppContext, channel) if appErr != nil { c.Err = appErr return } - appErr = c.App.FillInChannelProps(rchannel) + appErr = c.App.FillInChannelProps(c.AppContext, rchannel) if appErr != nil { c.Err = appErr return @@ -310,7 +310,7 @@ func localPatchChannel(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("patch", rchannel) if err := json.NewEncoder(w).Encode(rchannel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -320,7 +320,7 @@ func localMoveChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -357,7 +357,7 @@ func localMoveChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - err = c.App.RemoveAllDeactivatedMembersFromChannel(channel) + err = c.App.RemoveAllDeactivatedMembersFromChannel(c.AppContext, channel) if err != nil { c.Err = err return @@ -382,7 +382,7 @@ func localMoveChannel(c *Context, w http.ResponseWriter, r *http.Request) { c.LogAudit("team=" + team.Name) if err := json.NewEncoder(w).Encode(channel); err != nil { - mlog.Warn("Error while writing response", mlog.Err(err)) + c.Logger.Warn("Error while writing response", mlog.Err(err)) } } @@ -392,7 +392,7 @@ func localDeleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -408,7 +408,7 @@ func localDeleteChannel(c *Context, w http.ResponseWriter, r *http.Request) { } if c.Params.Permanent { - err = c.App.PermanentDeleteChannel(channel) + err = c.App.PermanentDeleteChannel(c.AppContext, channel) } else { err = c.App.DeleteChannel(c.AppContext, channel, "") } diff --git a/api4/channel_test.go b/api4/channel_test.go index 38dc0e8cd9..a47a92b12b 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -184,7 +184,7 @@ func TestUpdateChannel(t *testing.T) { require.Equal(t, private.Purpose, newPrivateChannel.Purpose, "Update failed for Purpose in private channel") //Test updating default channel's name and returns error - defaultChannel, _ := th.App.GetChannelByName(model.DefaultChannelName, team.Id, false) + defaultChannel, _ := th.App.GetChannelByName(th.Context, model.DefaultChannelName, team.Id, false) defaultChannel.Name = "testing" _, resp, err = client.UpdateChannel(defaultChannel) require.Error(t, err) @@ -286,7 +286,7 @@ func TestPatchChannel(t *testing.T) { require.Equal(t, oldName, channel.Name, "should not have updated") //Test updating default channel's name and returns error - defaultChannel, _ := th.App.GetChannelByName(model.DefaultChannelName, team.Id, false) + defaultChannel, _ := th.App.GetChannelByName(th.Context, model.DefaultChannelName, team.Id, false) defaultChannelPatch := &model.ChannelPatch{ Name: new(string), } @@ -560,7 +560,7 @@ func TestCreateGroupChannel(t *testing.T) { require.NotNil(t, rgc, "should have created a group channel") require.Equal(t, model.ChannelTypeGroup, rgc.Type, "should have created a channel of group type") - m, _ := th.App.GetChannelMembersPage(rgc.Id, 0, 10) + m, _ := th.App.GetChannelMembersPage(th.Context, rgc.Id, 0, 10) require.Len(t, m, 3, "should have 3 channel members") // saving duplicate group channel @@ -568,7 +568,7 @@ func TestCreateGroupChannel(t *testing.T) { require.NoError(t, err) require.Equal(t, rgc.Id, rgc2.Id, "should have returned existing channel") - m2, _ := th.App.GetChannelMembersPage(rgc2.Id, 0, 10) + m2, _ := th.App.GetChannelMembersPage(th.Context, rgc2.Id, 0, 10) require.Equal(t, m, m2) _, resp, err = client.CreateGroupChannel([]string{user2.Id}) @@ -1030,7 +1030,7 @@ func TestGetChannelsForTeamForUser(t *testing.T) { CreatorId: th.BasicUser.Id, } th.App.CreateChannel(th.Context, testChannel, true) - defer th.App.PermanentDeleteChannel(testChannel) + defer th.App.PermanentDeleteChannel(th.Context, testChannel) channels, _, err := client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "") require.NoError(t, err) assert.Equal(t, 6, len(channels)) @@ -1063,8 +1063,8 @@ func TestGetChannelsForUser(t *testing.T) { ch1 := th.CreateChannelWithClientAndTeam(client, model.ChannelTypeOpen, myTeam.Id) ch2 := th.CreateChannelWithClientAndTeam(client, model.ChannelTypePrivate, myTeam.Id) th.LinkUserToTeam(th.BasicUser, myTeam) - th.App.AddUserToChannel(th.BasicUser, ch1, false) - th.App.AddUserToChannel(th.BasicUser, ch2, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch1, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch2, false) channels, _, err := client.GetChannelsForUserWithLastDeleteAt(th.BasicUser.Id, 0) require.NoError(t, err) @@ -1096,7 +1096,7 @@ func TestGetChannelsForUser(t *testing.T) { // Creating some more channels to be exactly 100 to test page size boundaries. for i := 0; i < 91; i++ { ch1 = th.CreateChannelWithClientAndTeam(client, model.ChannelTypeOpen, myTeam.Id) - th.App.AddUserToChannel(th.BasicUser, ch1, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch1, false) } channels, _, err = client.GetChannelsForUserWithLastDeleteAt(th.BasicUser.Id, 0) @@ -1790,7 +1790,7 @@ func TestDeleteChannel(t *testing.T) { _, err := client.DeleteChannel(publicChannel1.Id) require.NoError(t, err) - ch, appErr := th.App.GetChannel(publicChannel1.Id) + ch, appErr := th.App.GetChannel(th.Context, publicChannel1.Id) require.Nilf(t, appErr, "Expected nil, Got %v", appErr) require.True(t, ch.DeleteAt != 0, "should have returned one with a populated DeleteAt.") @@ -1805,13 +1805,13 @@ func TestDeleteChannel(t *testing.T) { // successful delete of channel with multiple members publicChannel3 := th.CreatePublicChannel() - th.App.AddUserToChannel(user, publicChannel3, false) - th.App.AddUserToChannel(user2, publicChannel3, false) + th.App.AddUserToChannel(th.Context, user, publicChannel3, false) + th.App.AddUserToChannel(th.Context, user2, publicChannel3, false) _, err = client.DeleteChannel(publicChannel3.Id) require.NoError(t, err) // default channel cannot be deleted. - defaultChannel, _ := th.App.GetChannelByName(model.DefaultChannelName, team.Id, false) + defaultChannel, _ := th.App.GetChannelByName(th.Context, model.DefaultChannelName, team.Id, false) resp, err = client.DeleteChannel(defaultChannel.Id) require.Error(t, err) CheckBadRequestStatus(t, resp) @@ -1885,9 +1885,9 @@ func TestDeleteChannel2(t *testing.T) { // channels created by SystemAdmin publicChannel6 := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypeOpen) privateChannel7 := th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) - th.App.AddUserToChannel(user, publicChannel6, false) - th.App.AddUserToChannel(user, privateChannel7, false) - th.App.AddUserToChannel(user, privateChannel7, false) + th.App.AddUserToChannel(th.Context, user, publicChannel6, false) + th.App.AddUserToChannel(th.Context, user, privateChannel7, false) + th.App.AddUserToChannel(th.Context, user, privateChannel7, false) // successful delete by user _, err := client.DeleteChannel(publicChannel6.Id) @@ -1905,9 +1905,9 @@ func TestDeleteChannel2(t *testing.T) { // channels created by SystemAdmin publicChannel6 = th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypeOpen) privateChannel7 = th.CreateChannelWithClient(th.SystemAdminClient, model.ChannelTypePrivate) - th.App.AddUserToChannel(user, publicChannel6, false) - th.App.AddUserToChannel(user, privateChannel7, false) - th.App.AddUserToChannel(user, privateChannel7, false) + th.App.AddUserToChannel(th.Context, user, publicChannel6, false) + th.App.AddUserToChannel(th.Context, user, privateChannel7, false) + th.App.AddUserToChannel(th.Context, user, privateChannel7, false) // cannot delete by user resp, err := client.DeleteChannel(publicChannel6.Id) @@ -1975,7 +1975,7 @@ func TestPermanentDeleteChannel(t *testing.T) { _, err := c.PermanentDeleteChannel(publicChannel.Id) require.NoError(t, err) - _, appErr := th.App.GetChannel(publicChannel.Id) + _, appErr := th.App.GetChannel(th.Context, publicChannel.Id) assert.NotNil(t, appErr) resp, err := c.PermanentDeleteChannel("junk") @@ -1988,7 +1988,7 @@ func TestUpdateChannelPrivacy(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - defaultChannel, _ := th.App.GetChannelByName(model.DefaultChannelName, th.BasicTeam.Id, false) + defaultChannel, _ := th.App.GetChannelByName(th.Context, model.DefaultChannelName, th.BasicTeam.Id, false) type testTable []struct { name string @@ -2045,7 +2045,7 @@ func TestUpdateChannelPrivacy(t *testing.T) { updatedChannel, _, err := client.UpdateChannelPrivacy(tc.channel.Id, tc.expectedPrivacy) require.NoError(t, err) assert.Equal(t, tc.expectedPrivacy, updatedChannel.Type) - updatedChannel, appErr := th.App.GetChannel(tc.channel.Id) + updatedChannel, appErr := th.App.GetChannel(th.Context, tc.channel.Id) require.Nil(t, appErr) assert.Equal(t, tc.expectedPrivacy, updatedChannel.Type) }) @@ -2424,7 +2424,7 @@ func TestViewChannel(t *testing.T) { require.NoError(t, err) require.Equal(t, "OK", viewResp.Status, "should have passed") - channel, _ := th.App.GetChannel(th.BasicChannel.Id) + channel, _ := th.App.GetChannel(th.Context, th.BasicChannel.Id) require.Equal(t, channel.LastPostAt, viewResp.LastViewedAtTimes[channel.Id], "LastPostAt does not match returned LastViewedAt time") @@ -2637,7 +2637,7 @@ func TestUpdateChannelRoles(t *testing.T) { channel := th.CreatePublicChannel() // Adds User 2 to the channel, making them a channel member by default. - th.App.AddUserToChannel(th.BasicUser2, channel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, channel, false) // User 1 promotes User 2 _, err := client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, ChannelAdmin) @@ -2847,7 +2847,7 @@ func TestUpdateChannelNotifyProps(t *testing.T) { _, err := client.UpdateChannelNotifyProps(th.BasicChannel.Id, th.BasicUser.Id, props) require.NoError(t, err) - member, appErr := th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + member, appErr := th.App.GetChannelMember(th.Context, th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, appErr) require.Equal(t, model.ChannelNotifyMention, member.NotifyProps[model.DesktopNotifyProp], "bad update") require.Equal(t, model.ChannelMarkUnreadMention, member.NotifyProps[model.MarkUnreadNotifyProp], "bad update") @@ -3039,7 +3039,7 @@ func TestAddChannelMember(t *testing.T) { // Set a channel to group-constrained privateChannel.GroupConstrained = model.NewBool(true) - _, appErr := th.App.UpdateChannel(privateChannel) + _, appErr := th.App.UpdateChannel(th.Context, privateChannel) require.Nil(t, appErr) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { @@ -3266,9 +3266,9 @@ func TestRemoveChannelMember(t *testing.T) { t.Run("success", func(t *testing.T) { // Setup the system administrator to listen for websocket events from the channels. th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam) - _, appErr := th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel, false) + _, appErr := th.App.AddUserToChannel(th.Context, th.SystemAdminUser, th.BasicChannel, false) require.Nil(t, appErr) - _, appErr = th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel2, false) + _, appErr = th.App.AddUserToChannel(th.Context, th.SystemAdminUser, th.BasicChannel2, false) require.Nil(t, appErr) props := map[string]string{} props[model.DesktopNotifyProp] = model.ChannelNotifyAll @@ -3312,7 +3312,7 @@ func TestRemoveChannelMember(t *testing.T) { } } - th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, th.BasicChannel, false) _, err2 = client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id) require.NoError(t, err2) @@ -3343,18 +3343,18 @@ func TestRemoveChannelMember(t *testing.T) { // Leave deleted channel th.LoginBasic() deletedChannel := th.CreatePublicChannel() - th.App.AddUserToChannel(th.BasicUser, deletedChannel, false) - th.App.AddUserToChannel(th.BasicUser2, deletedChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, deletedChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, deletedChannel, false) deletedChannel.DeleteAt = 1 - th.App.UpdateChannel(deletedChannel) + th.App.UpdateChannel(th.Context, deletedChannel) _, err = client.RemoveUserFromChannel(deletedChannel.Id, th.BasicUser.Id) require.NoError(t, err) th.LoginBasic() private := th.CreatePrivateChannel() - th.App.AddUserToChannel(th.BasicUser2, private, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, private, false) _, err = client.RemoveUserFromChannel(private.Id, th.BasicUser2.Id) require.NoError(t, err) @@ -3365,7 +3365,7 @@ func TestRemoveChannelMember(t *testing.T) { CheckForbiddenStatus(t, resp) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { - th.App.AddUserToChannel(th.BasicUser, private, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, private, false) _, err = client.RemoveUserFromChannel(private.Id, th.BasicUser.Id) require.NoError(t, err) }) @@ -3421,7 +3421,7 @@ func TestRemoveChannelMember(t *testing.T) { // If the channel is group-constrained the user cannot be removed privateChannel.GroupConstrained = model.NewBool(true) - _, appErr := th.App.UpdateChannel(privateChannel) + _, appErr := th.App.UpdateChannel(th.Context, privateChannel) require.Nil(t, appErr) _, err = client.RemoveUserFromChannel(privateChannel.Id, user2.Id) CheckErrorID(t, err, "api.channel.remove_member.group_constrained.app_error") @@ -3913,7 +3913,7 @@ func TestChannelMembersMinusGroupMembers(t *testing.T) { require.Nil(t, appErr) channel.GroupConstrained = model.NewBool(true) - channel, appErr = th.App.UpdateChannel(channel) + channel, appErr = th.App.UpdateChannel(th.Context, channel) require.Nil(t, appErr) group1 := th.CreateGroup() @@ -4056,7 +4056,7 @@ func TestGetChannelModerations(t *testing.T) { t.Run("Returns value false and enabled true for permissions that are not present in channel scheme but present in team scheme", func(t *testing.T) { scheme := th.SetupChannelScheme() channel.SchemeId = &scheme.Id - _, appErr := th.App.UpdateChannelScheme(channel) + _, appErr := th.App.UpdateChannelScheme(th.Context, channel) require.Nil(t, appErr) th.RemovePermissionFromRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) @@ -4081,7 +4081,7 @@ func TestGetChannelModerations(t *testing.T) { scheme := th.SetupChannelScheme() channel.SchemeId = &scheme.Id - th.App.UpdateChannelScheme(channel) + th.App.UpdateChannelScheme(th.Context, channel) th.RemovePermissionFromRole(model.PermissionCreatePost.Id, scheme.DefaultChannelGuestRole) th.RemovePermissionFromRole(model.PermissionCreatePost.Id, teamScheme.DefaultChannelGuestRole) @@ -4230,12 +4230,12 @@ func TestPatchChannelModerations(t *testing.T) { require.Equal(t, moderation.Roles.Members.Enabled, true) } } - channel, _ = th.App.GetChannel(channel.Id) + channel, _ = th.App.GetChannel(th.Context, channel.Id) require.NotNil(t, channel.SchemeId) }) t.Run("Removes the existing scheme when moderated permissions are set back to higher scoped values", func(t *testing.T) { - channel, _ = th.App.GetChannel(channel.Id) + channel, _ = th.App.GetChannel(th.Context, channel.Id) schemeId := channel.SchemeId scheme, _ := th.App.GetScheme(*schemeId) @@ -4263,7 +4263,7 @@ func TestPatchChannelModerations(t *testing.T) { require.Equal(t, moderation.Roles.Members.Enabled, true) } - channel, _ = th.App.GetChannel(channel.Id) + channel, _ = th.App.GetChannel(th.Context, channel.Id) require.Nil(t, channel.SchemeId) scheme, _ = th.App.GetScheme(*schemeId) @@ -4462,7 +4462,7 @@ func TestMoveChannel(t *testing.T) { t.Run("Should fail when trying to move a group channel", func(t *testing.T) { user := th.CreateUser() - gmChannel, appErr := th.App.CreateGroupChannel([]string{th.BasicUser.Id, th.SystemAdminUser.Id, th.TeamAdminUser.Id}, user.Id) + gmChannel, appErr := th.App.CreateGroupChannel(th.Context, []string{th.BasicUser.Id, th.SystemAdminUser.Id, th.TeamAdminUser.Id}, user.Id) require.Nil(t, appErr) _, _, err := client.MoveChannel(gmChannel.Id, team1.Id, false) require.Error(t, err) diff --git a/api4/command.go b/api4/command.go index 4db1ee886c..c775fd805f 100644 --- a/api4/command.go +++ b/api4/command.go @@ -314,12 +314,12 @@ func executeCommand(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("commandargs", commandArgs) // checks that user is a member of the specified channel, and that they have permission to use slash commands in it - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), commandArgs.ChannelId, model.PermissionUseSlashCommands) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), commandArgs.ChannelId, model.PermissionUseSlashCommands) { c.SetPermissionError(model.PermissionUseSlashCommands) return } - channel, err := c.App.GetChannel(commandArgs.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, commandArgs.ChannelId) if err != nil { c.Err = err return diff --git a/api4/data_retention.go b/api4/data_retention.go index 824f8b8f7b..10cc28b0a2 100644 --- a/api4/data_retention.go +++ b/api4/data_retention.go @@ -356,7 +356,7 @@ func searchChannelsInPolicy(c *Context, w http.ResponseWriter, r *http.Request) TeamIds: props.TeamIds, } - channels, _, appErr := c.App.SearchAllChannels(props.Term, opts) + channels, _, appErr := c.App.SearchAllChannels(c.AppContext, props.Term, opts) if appErr != nil { c.Err = appErr return diff --git a/api4/file.go b/api4/file.go index 365dd48d09..21c7cd556b 100644 --- a/api4/file.go +++ b/api4/file.go @@ -167,7 +167,7 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F defer c.LogAuditRec(auditRec) auditRec.AddMeta("channel_id", c.Params.ChannelId) - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionUploadFile) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionUploadFile) { c.SetPermissionError(model.PermissionUploadFile) return nil } @@ -312,7 +312,7 @@ NextPart: if c.Err != nil { return nil } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, model.PermissionUploadFile) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, model.PermissionUploadFile) { c.SetPermissionError(model.PermissionUploadFile) return nil } @@ -401,7 +401,7 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader, if c.Err != nil { return nil } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionUploadFile) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channelId, model.PermissionUploadFile) { c.SetPermissionError(model.PermissionUploadFile) return nil } diff --git a/api4/group.go b/api4/group.go index ff9c116a83..049cfb1ef8 100644 --- a/api4/group.go +++ b/api4/group.go @@ -575,7 +575,7 @@ func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType return c.App.MakePermissionError(c.AppContext.Session(), []*model.Permission{model.PermissionManageTeam}) } case model.GroupSyncableTypeChannel: - channel, err := c.App.GetChannel(syncableID) + channel, err := c.App.GetChannel(c.AppContext, syncableID) if err != nil { return err } @@ -587,7 +587,7 @@ func verifyLinkUnlinkPermission(c *Context, syncableType model.GroupSyncableType permission = model.PermissionManagePublicChannelMembers } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), syncableID, permission) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), syncableID, permission) { return c.App.MakePermissionError(c.AppContext.Session(), []*model.Permission{permission}) } } @@ -716,7 +716,7 @@ func getGroupsByChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(c.Params.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, c.Params.ChannelId) if err != nil { c.Err = err return @@ -727,7 +727,7 @@ func getGroupsByChannel(c *Context, w http.ResponseWriter, r *http.Request) { } else { permission = model.PermissionReadPublicChannelGroups } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), c.Params.ChannelId, permission) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), c.Params.ChannelId, permission) { c.SetPermissionError(permission) return } @@ -889,7 +889,7 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { } if channelID != "" { - channel, err := c.App.GetChannel(channelID) + channel, err := c.App.GetChannel(c.AppContext, channelID) if err != nil { c.Err = err return @@ -900,7 +900,7 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { } else { permission = model.PermissionManagePublicChannelMembers } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelID, permission) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channelID, permission) { c.SetPermissionError(permission) return } diff --git a/api4/insights.go b/api4/insights.go index ba49bf5a34..39493a97f3 100644 --- a/api4/insights.go +++ b/api4/insights.go @@ -8,7 +8,6 @@ import ( "net/http" "time" - "github.com/mattermost/mattermost-server/v6/app" "github.com/mattermost/mattermost-server/v6/model" ) @@ -149,7 +148,7 @@ func getTopChannelsForTeamSince(c *Context, w http.ResponseWriter, r *http.Reque loc := user.GetTimezoneLocation() startTime := model.StartOfDayForTimeRange(c.Params.TimeRange, loc) - topChannels, err := c.App.GetTopChannelsForTeamSince(c.Params.TeamId, c.AppContext.Session().UserId, &model.InsightsOpts{ + topChannels, err := c.App.GetTopChannelsForTeamSince(c.AppContext, c.Params.TeamId, c.AppContext.Session().UserId, &model.InsightsOpts{ StartUnixMilli: startTime.UnixMilli(), Page: c.Params.Page, PerPage: c.Params.PerPage, @@ -159,7 +158,7 @@ func getTopChannelsForTeamSince(c *Context, w http.ResponseWriter, r *http.Reque return } - topChannels.PostCountByDuration, err = postCountByDurationViewModel(c.App, topChannels, startTime, c.Params.TimeRange, nil, loc) + topChannels.PostCountByDuration, err = postCountByDurationViewModel(c, topChannels, startTime, c.Params.TimeRange, nil, loc) if err != nil { c.Err = err return @@ -205,7 +204,7 @@ func getTopChannelsForUserSince(c *Context, w http.ResponseWriter, r *http.Reque loc := user.GetTimezoneLocation() startTime := model.StartOfDayForTimeRange(c.Params.TimeRange, loc) - topChannels, err := c.App.GetTopChannelsForUserSince(c.AppContext.Session().UserId, c.Params.TeamId, &model.InsightsOpts{ + topChannels, err := c.App.GetTopChannelsForUserSince(c.AppContext, c.AppContext.Session().UserId, c.Params.TeamId, &model.InsightsOpts{ StartUnixMilli: startTime.UnixMilli(), Page: c.Params.Page, PerPage: c.Params.PerPage, @@ -216,7 +215,7 @@ func getTopChannelsForUserSince(c *Context, w http.ResponseWriter, r *http.Reque return } - topChannels.PostCountByDuration, err = postCountByDurationViewModel(c.App, topChannels, startTime, c.Params.TimeRange, &c.AppContext.Session().UserId, loc) + topChannels.PostCountByDuration, err = postCountByDurationViewModel(c, topChannels, startTime, c.Params.TimeRange, &c.AppContext.Session().UserId, loc) if err != nil { c.Err = err return @@ -265,7 +264,7 @@ func getTopThreadsForTeamSince(c *Context, w http.ResponseWriter, r *http.Reques startTime := model.StartOfDayForTimeRange(c.Params.TimeRange, user.GetTimezoneLocation()) - topThreads, err := c.App.GetTopThreadsForTeamSince(c.Params.TeamId, c.AppContext.Session().UserId, &model.InsightsOpts{ + topThreads, err := c.App.GetTopThreadsForTeamSince(c.AppContext, c.Params.TeamId, c.AppContext.Session().UserId, &model.InsightsOpts{ StartUnixMilli: startTime.UnixMilli(), Page: c.Params.Page, PerPage: c.Params.PerPage, @@ -321,7 +320,7 @@ func getTopThreadsForUserSince(c *Context, w http.ResponseWriter, r *http.Reques startTime := model.StartOfDayForTimeRange(c.Params.TimeRange, user.GetTimezoneLocation()) - topThreads, err := c.App.GetTopThreadsForUserSince(c.Params.TeamId, c.AppContext.Session().UserId, &model.InsightsOpts{ + topThreads, err := c.App.GetTopThreadsForUserSince(c.AppContext, c.Params.TeamId, c.AppContext.Session().UserId, &model.InsightsOpts{ StartUnixMilli: startTime.UnixMilli(), Page: c.Params.Page, PerPage: c.Params.PerPage, @@ -342,7 +341,7 @@ func getTopThreadsForUserSince(c *Context, w http.ResponseWriter, r *http.Reques } // postCountByDurationViewModel expects a list of channels that are pre-authorized for the given user to view. -func postCountByDurationViewModel(app app.AppIface, topChannelList *model.TopChannelList, startTime *time.Time, timeRange string, userID *string, location *time.Location) (model.ChannelPostCountByDuration, *model.AppError) { +func postCountByDurationViewModel(c *Context, topChannelList *model.TopChannelList, startTime *time.Time, timeRange string, userID *string, location *time.Location) (model.ChannelPostCountByDuration, *model.AppError) { if len(topChannelList.Items) == 0 { return nil, nil } @@ -354,7 +353,7 @@ func postCountByDurationViewModel(app app.AppIface, topChannelList *model.TopCha } else { grouping = model.PostsByDay } - postCountsByDay, err := app.PostCountsByDuration(channelIDs, startTime.UnixMilli(), userID, grouping, location) + postCountsByDay, err := c.App.PostCountsByDuration(c.AppContext, channelIDs, startTime.UnixMilli(), userID, grouping, location) if err != nil { return nil, err } diff --git a/api4/insights_test.go b/api4/insights_test.go index 06395382f7..38f23367d7 100644 --- a/api4/insights_test.go +++ b/api4/insights_test.go @@ -439,9 +439,9 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { channel4 := th.CreatePublicChannel() channel5 := th.CreatePrivateChannel() channel6 := th.CreatePrivateChannel() - th.App.AddUserToChannel(th.BasicUser, channel4, false) - th.App.AddUserToChannel(th.BasicUser, channel5, false) - th.App.AddUserToChannel(th.BasicUser, channel6, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channel4, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channel5, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channel6, false) channelIDs := [6]string{th.BasicChannel.Id, th.BasicChannel2.Id, th.BasicPrivateChannel.Id, channel4.Id, channel5.Id, channel6.Id} @@ -535,9 +535,9 @@ func TestGetTopChannelsForUserSince(t *testing.T) { channel4 := th.CreatePublicChannel() channel5 := th.CreatePrivateChannel() channel6 := th.CreatePrivateChannel() - th.App.AddUserToChannel(th.BasicUser, channel4, false) - th.App.AddUserToChannel(th.BasicUser, channel5, false) - th.App.AddUserToChannel(th.BasicUser, channel6, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channel4, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channel5, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channel6, false) channelIDs := [6]string{th.BasicChannel.Id, th.BasicChannel2.Id, th.BasicPrivateChannel.Id, channel4.Id, channel5.Id, channel6.Id} @@ -612,9 +612,9 @@ func TestGetTopThreadsForTeamSince(t *testing.T) { channelPublic := th.BasicChannel channelPrivate := th.BasicPrivateChannel - th.App.AddUserToChannel(th.BasicUser, channelPublic, false) - th.App.AddUserToChannel(th.BasicUser, channelPrivate, false) - th.App.AddUserToChannel(th.BasicUser2, channelPublic, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channelPublic, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channelPrivate, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, channelPublic, false) th.App.RemoveUserFromChannel(th.Context, th.BasicUser2.Id, th.BasicUser.Id, channelPrivate) // create two threads: one in public channel, one in private @@ -698,9 +698,9 @@ func TestGetTopThreadsForUserSince(t *testing.T) { channelPublic := th.BasicChannel channelPrivate := th.BasicPrivateChannel - th.App.AddUserToChannel(th.BasicUser, channelPublic, false) - th.App.AddUserToChannel(th.BasicUser, channelPrivate, false) - th.App.AddUserToChannel(th.BasicUser2, channelPublic, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channelPublic, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, channelPrivate, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, channelPublic, false) // create two threads: one in public channel, one in private // post in public channel has both users interacting, post in private only has user1 interacting @@ -770,7 +770,7 @@ func TestGetTopThreadsForUserSince(t *testing.T) { require.Equal(t, topUser2Threads.Items[0].Post.ReplyCount, int64(1)) // deleting the root post results in the thread not making it to top threads list - _, appErr = th.App.DeletePost(rootPostPublicChannel.Id, th.BasicUser.Id) + _, appErr = th.App.DeletePost(th.Context, rootPostPublicChannel.Id, th.BasicUser.Id) require.Nil(t, appErr) client.Logout() @@ -803,7 +803,7 @@ func TestGetTopThreadsForUserSince(t *testing.T) { require.Len(t, topUser2ThreadsAfterPrivateReply.Items, 1) // deleting reply, and unfollowing thread - _, appErr = th.App.DeletePost(replyPostUser2InPrivate.Id, th.BasicUser2.Id) + _, appErr = th.App.DeletePost(th.Context, replyPostUser2InPrivate.Id, th.BasicUser2.Id) require.Nil(t, appErr) // unfollow thread _, err := th.App.Srv().Store.Thread().MaintainMembership(th.BasicUser2.Id, rootPostPrivateChannel.Id, store.ThreadMembershipOpts{ diff --git a/api4/integration_action.go b/api4/integration_action.go index be19c4928b..474c1c93ff 100644 --- a/api4/integration_action.go +++ b/api4/integration_action.go @@ -39,7 +39,7 @@ func doPostAction(c *Context, w http.ResponseWriter, r *http.Request) { c.Err = model.NewAppError("DoPostAction", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest) return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), cookie.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), cookie.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } @@ -101,7 +101,7 @@ func submitDialog(c *Context, w http.ResponseWriter, r *http.Request) { submit.UserId = c.AppContext.Session().UserId - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), submit.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), submit.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } diff --git a/api4/post.go b/api4/post.go index 99187afa6f..6698e8d924 100644 --- a/api4/post.go +++ b/api4/post.go @@ -55,9 +55,9 @@ func createPost(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("post", &post) hasPermission := false - if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionCreatePost) { + if c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), post.ChannelId, model.PermissionCreatePost) { hasPermission = true - } else if channel, err := c.App.GetChannel(post.ChannelId); err == nil { + } else if channel, err := c.App.GetChannel(c.AppContext, post.ChannelId); err == nil { // Temporary permission check method until advanced permissions, please do not copy if channel.Type == model.ChannelTypeOpen && c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionCreatePostPublic) { hasPermission = true @@ -129,12 +129,12 @@ func createEphemeralPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - rp := c.App.SendEphemeralPost(ephRequest.UserID, c.App.PostWithProxyRemovedFromImageURLs(ephRequest.Post)) + rp := c.App.SendEphemeralPost(c.AppContext, ephRequest.UserID, c.App.PostWithProxyRemovedFromImageURLs(ephRequest.Post)) w.WriteHeader(http.StatusCreated) rp = model.AddPostActionCookies(rp, c.App.PostActionCookieSecret()) - rp = c.App.PreparePostForClientWithEmbedsAndImages(rp, true, false) - rp, err := c.App.SanitizePostMetadataForUser(rp, c.AppContext.Session().UserId) + rp = c.App.PreparePostForClientWithEmbedsAndImages(c.AppContext, rp, true, false) + rp, err := c.App.SanitizePostMetadataForUser(c.AppContext, rp, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -179,13 +179,13 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { page := c.Params.Page perPage := c.Params.PerPage - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } if !*c.App.Config().TeamSettings.ExperimentalViewArchivedChannels { - channel, err := c.App.GetChannel(channelId) + channel, err := c.App.GetChannel(c.AppContext, channelId) if err != nil { c.Err = err return @@ -238,8 +238,8 @@ func getPostsForChannel(c *Context, w http.ResponseWriter, r *http.Request) { } c.App.AddCursorIdsForPostList(list, afterPost, beforePost, since, page, perPage, collapsedThreads) - clientPostList := c.App.PreparePostListForClient(list) - clientPostList, err = c.App.SanitizePostListMetadataForUser(clientPostList, c.AppContext.Session().UserId) + clientPostList := c.App.PreparePostListForClient(c.AppContext, list) + clientPostList, err = c.App.SanitizePostListMetadataForUser(c.AppContext, clientPostList, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -263,7 +263,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht } channelId := c.Params.ChannelId - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } @@ -277,7 +277,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht collapsedThreads := r.URL.Query().Get("collapsedThreads") == "true" collapsedThreadsExtended := r.URL.Query().Get("collapsedThreadsExtended") == "true" - postList, err := c.App.GetPostsForChannelAroundLastUnread(channelId, userId, c.Params.LimitBefore, c.Params.LimitAfter, skipFetchThreads, collapsedThreads, collapsedThreadsExtended) + postList, err := c.App.GetPostsForChannelAroundLastUnread(c.AppContext, channelId, userId, c.Params.LimitBefore, c.Params.LimitAfter, skipFetchThreads, collapsedThreads, collapsedThreadsExtended) if err != nil { c.Err = err return @@ -301,8 +301,8 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht postList.NextPostId = c.App.GetNextPostIdFromPostList(postList, collapsedThreads) postList.PrevPostId = c.App.GetPrevPostIdFromPostList(postList, collapsedThreads) - clientPostList := c.App.PreparePostListForClient(postList) - clientPostList, err = c.App.SanitizePostListMetadataForUser(clientPostList, c.AppContext.Session().UserId) + clientPostList := c.App.PreparePostListForClient(c.AppContext, postList) + clientPostList, err = c.App.SanitizePostListMetadataForUser(c.AppContext, clientPostList, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -354,7 +354,7 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request) if !ok { allowed = false - if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionReadChannel) { + if c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), post.ChannelId, model.PermissionReadChannel) { allowed = true } @@ -370,8 +370,8 @@ func getFlaggedPostsForUser(c *Context, w http.ResponseWriter, r *http.Request) } pl.SortByCreateAt() - clientPostList := c.App.PreparePostListForClient(pl) - clientPostList, err = c.App.SanitizePostListMetadataForUser(clientPostList, c.AppContext.Session().UserId) + clientPostList := c.App.PreparePostListForClient(c.AppContext, pl) + clientPostList, err = c.App.SanitizePostListMetadataForUser(c.AppContext, clientPostList, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -394,7 +394,7 @@ func getPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - post, err := c.App.GetPostIfAuthorized(c.Params.PostId, c.AppContext.Session(), includeDeleted) + post, err := c.App.GetPostIfAuthorized(c.AppContext, c.Params.PostId, c.AppContext.Session(), includeDeleted) if err != nil { c.Err = err @@ -406,8 +406,8 @@ func getPost(c *Context, w http.ResponseWriter, r *http.Request) { return } - post = c.App.PreparePostForClientWithEmbedsAndImages(post, false, false) - post, err = c.App.SanitizePostMetadataForUser(post, c.AppContext.Session().UserId) + post = c.App.PreparePostForClientWithEmbedsAndImages(c.AppContext, post, false, false) + post, err = c.App.SanitizePostMetadataForUser(c.AppContext, post, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -451,7 +451,7 @@ func getPostsByIds(c *Context, w http.ResponseWriter, r *http.Request) { if val, ok := channelMap[post.ChannelId]; ok { channel = val } else { - channel, err = c.App.GetChannel(post.ChannelId) + channel, err = c.App.GetChannel(c.AppContext, post.ChannelId) if err != nil { c.Err = err return @@ -459,7 +459,7 @@ func getPostsByIds(c *Context, w http.ResponseWriter, r *http.Request) { channelMap[channel.Id] = channel } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { if channel.Type != model.ChannelTypeOpen || (channel.Type == model.ChannelTypeOpen && !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), channel.TeamId, model.PermissionReadPublicChannel)) { continue } @@ -495,18 +495,18 @@ func deletePost(c *Context, w http.ResponseWriter, _ *http.Request) { auditRec.AddMeta("post", post) if c.AppContext.Session().UserId == post.UserId { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionDeletePost) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), post.ChannelId, model.PermissionDeletePost) { c.SetPermissionError(model.PermissionDeletePost) return } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionDeleteOthersPosts) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), post.ChannelId, model.PermissionDeleteOthersPosts) { c.SetPermissionError(model.PermissionDeleteOthersPosts) return } } - if _, err := c.App.DeletePost(c.Params.PostId, c.AppContext.Session().UserId); err != nil { + if _, err := c.App.DeletePost(c.AppContext, c.Params.PostId, c.AppContext.Session().UserId); err != nil { c.Err = err return } @@ -579,7 +579,7 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { return } - if _, err = c.App.GetPostIfAuthorized(post.Id, c.AppContext.Session(), false); err != nil { + if _, err = c.App.GetPostIfAuthorized(c.AppContext, post.Id, c.AppContext.Session(), false); err != nil { c.Err = err return } @@ -588,8 +588,8 @@ func getPostThread(c *Context, w http.ResponseWriter, r *http.Request) { return } - clientPostList := c.App.PreparePostListForClient(list) - clientPostList, err = c.App.SanitizePostListMetadataForUser(clientPostList, c.AppContext.Session().UserId) + clientPostList := c.App.PreparePostListForClient(c.AppContext, list) + clientPostList, err = c.App.SanitizePostListMetadataForUser(c.AppContext, clientPostList, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -683,8 +683,8 @@ func searchPosts(c *Context, w http.ResponseWriter, r *http.Request, teamId stri return } - clientPostList := c.App.PreparePostListForClient(results.PostList) - clientPostList, err = c.App.SanitizePostListMetadataForUser(clientPostList, c.AppContext.Session().UserId) + clientPostList := c.App.PreparePostListForClient(c.AppContext, results.PostList) + clientPostList, err = c.App.SanitizePostListMetadataForUser(c.AppContext, clientPostList, c.AppContext.Session().UserId) if err != nil { c.Err = err return @@ -826,7 +826,7 @@ func setPostUnread(c *Context, w http.ResponseWriter, r *http.Request) { return } - state, err := c.App.MarkChannelAsUnreadFromPost(c.Params.PostId, c.Params.UserId, collapsedThreadsSupported) + state, err := c.App.MarkChannelAsUnreadFromPost(c.AppContext, c.Params.PostId, c.Params.UserId, collapsedThreadsSupported) if err != nil { c.Err = err return diff --git a/api4/post_test.go b/api4/post_test.go index cd536c11db..5db9de4b24 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -546,7 +546,7 @@ func TestCreatePostSendOutOfChannelMentions(t *testing.T) { inChannelUser := th.CreateUser() th.LinkUserToTeam(inChannelUser, th.BasicTeam) - th.App.AddUserToChannel(inChannelUser, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, inChannelUser, th.BasicChannel, false) post1 := &model.Post{ChannelId: th.BasicChannel.Id, Message: "@" + inChannelUser.Username} _, resp, err := client.CreatePost(post1) @@ -2113,7 +2113,7 @@ func TestDeletePostEvent(t *testing.T) { func TestDeletePostMessage(t *testing.T) { th := Setup(t).InitBasic() th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam) - th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, th.SystemAdminUser, th.BasicChannel, false) defer th.TearDown() @@ -2469,8 +2469,8 @@ func TestSearchPostsFromUser(t *testing.T) { th.LoginTeamAdmin() user := th.CreateUser() th.LinkUserToTeam(user, th.BasicTeam) - th.App.AddUserToChannel(user, th.BasicChannel, false) - th.App.AddUserToChannel(user, th.BasicChannel2, false) + th.App.AddUserToChannel(th.Context, user, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, user, th.BasicChannel2, false) message := "sgtitlereview with space" _ = th.CreateMessagePost(message) @@ -2653,15 +2653,15 @@ func TestSetChannelUnread(t *testing.T) { require.NotNil(t, pp2) // Ensure that post have been read - unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, c1.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(4), unread.MsgCount) - unread, appErr := th.App.GetChannelUnread(c1.Id, u2.Id) + unread, appErr := th.App.GetChannelUnread(th.Context, c1.Id, u2.Id) require.Nil(t, appErr) require.Equal(t, int64(4), unread.MsgCount) - _, appErr = th.App.ViewChannel(c1toc2, u2.Id, s2.Id, false) + _, appErr = th.App.ViewChannel(th.Context, c1toc2, u2.Id, s2.Id, false) require.Nil(t, appErr) - unread, appErr = th.App.GetChannelUnread(c1.Id, u2.Id) + unread, appErr = th.App.GetChannelUnread(th.Context, c1.Id, u2.Id) require.Nil(t, appErr) require.Equal(t, int64(0), unread.MsgCount) @@ -2669,7 +2669,7 @@ func TestSetChannelUnread(t *testing.T) { r, err := th.Client.SetPostUnread(u1.Id, p2.Id, true) require.NoError(t, err) CheckOKStatus(t, r) - unread, appErr := th.App.GetChannelUnread(c1.Id, u1.Id) + unread, appErr := th.App.GetChannelUnread(th.Context, c1.Id, u1.Id) require.Nil(t, appErr) assert.Equal(t, int64(2), unread.MsgCount) }) @@ -2684,32 +2684,32 @@ func TestSetChannelUnread(t *testing.T) { require.NotNil(t, p1) // Ensure that post have been read - unread, err := th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(4), unread.MsgCount) cv := &model.ChannelView{ChannelId: dc.Id} - _, appErr := th.App.ViewChannel(cv, u1.Id, s2.Id, false) + _, appErr := th.App.ViewChannel(th.Context, cv, u1.Id, s2.Id, false) require.Nil(t, appErr) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(0), unread.MsgCount) r, _ := th.Client.SetPostUnread(u1.Id, p.Id, false) assert.Equal(t, 200, r.StatusCode) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(3), unread.MsgCount) // Ensure that post have been read - _, appErr = th.App.ViewChannel(cv, u1.Id, s2.Id, false) + _, appErr = th.App.ViewChannel(th.Context, cv, u1.Id, s2.Id, false) require.Nil(t, appErr) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(0), unread.MsgCount) r, _ = th.Client.SetPostUnread(u1.Id, p1.Id, false) assert.Equal(t, 200, r.StatusCode) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(1), unread.MsgCount) }) @@ -2726,36 +2726,36 @@ func TestSetChannelUnread(t *testing.T) { require.Nil(t, appErr) // Ensure that post have been read - unread, err := th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(4), unread.MsgCount) require.Equal(t, int64(1), unread.MsgCountRoot) cv := &model.ChannelView{ChannelId: dc.Id} - _, appErr = th.App.ViewChannel(cv, u1.Id, s2.Id, false) + _, appErr = th.App.ViewChannel(th.Context, cv, u1.Id, s2.Id, false) require.Nil(t, appErr) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(0), unread.MsgCount) require.Equal(t, int64(0), unread.MsgCountRoot) r, _ := th.Client.SetPostUnread(u1.Id, rootPost.Id, false) assert.Equal(t, 200, r.StatusCode) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(4), unread.MsgCount) require.Equal(t, int64(1), unread.MsgCountRoot) // Ensure that post have been read - _, appErr = th.App.ViewChannel(cv, u1.Id, s2.Id, false) + _, appErr = th.App.ViewChannel(th.Context, cv, u1.Id, s2.Id, false) require.Nil(t, appErr) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(0), unread.MsgCount) require.Equal(t, int64(0), unread.MsgCountRoot) r, _ = th.Client.SetPostUnread(u1.Id, reply2.Id, false) assert.Equal(t, 200, r.StatusCode) - unread, err = th.App.GetChannelUnread(dc.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, dc.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(2), unread.MsgCount) require.Equal(t, int64(0), unread.MsgCountRoot) @@ -2764,12 +2764,12 @@ func TestSetChannelUnread(t *testing.T) { t.Run("Unread on a private channel", func(t *testing.T) { r, _ := th.Client.SetPostUnread(u1.Id, pp2.Id, true) assert.Equal(t, 200, r.StatusCode) - unread, appErr := th.App.GetChannelUnread(th.BasicPrivateChannel.Id, u1.Id) + unread, appErr := th.App.GetChannelUnread(th.Context, th.BasicPrivateChannel.Id, u1.Id) require.Nil(t, appErr) assert.Equal(t, int64(1), unread.MsgCount) r, _ = th.Client.SetPostUnread(u1.Id, pp1.Id, true) assert.Equal(t, 200, r.StatusCode) - unread, appErr = th.App.GetChannelUnread(th.BasicPrivateChannel.Id, u1.Id) + unread, appErr = th.App.GetChannelUnread(th.Context, th.BasicPrivateChannel.Id, u1.Id) require.Nil(t, appErr) assert.Equal(t, int64(2), unread.MsgCount) }) @@ -2843,7 +2843,7 @@ func TestSetPostUnreadWithoutCollapsedThreads(t *testing.T) { _, err = th.Client.SetPostUnread(th.BasicUser.Id, replyPost1.Id, false) require.NoError(t, err) - channelUnread, appErr := th.App.GetChannelUnread(th.BasicChannel.Id, th.BasicUser.Id) + channelUnread, appErr := th.App.GetChannelUnread(th.Context, th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, appErr) require.Equal(t, int64(3), channelUnread.MentionCount) @@ -2891,7 +2891,7 @@ func TestSetPostUnreadWithoutCollapsedThreads(t *testing.T) { t.Run("Mark root post as unread", func(t *testing.T) { _, err := th.Client.SetPostUnread(th.BasicUser.Id, rootPost1.Id, false) require.NoError(t, err) - channelUnread, appErr := th.App.GetChannelUnread(th.BasicChannel.Id, th.BasicUser.Id) + channelUnread, appErr := th.App.GetChannelUnread(th.Context, th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, appErr) require.Equal(t, int64(4), channelUnread.MentionCount) diff --git a/api4/preference.go b/api4/preference.go index b89a96ecc3..09a19f9834 100644 --- a/api4/preference.go +++ b/api4/preference.go @@ -116,7 +116,7 @@ func updatePreferences(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), post.ChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), post.ChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } diff --git a/api4/resolver.go b/api4/resolver.go index ebb50590a7..6cc43e3d33 100644 --- a/api4/resolver.go +++ b/api4/resolver.go @@ -80,7 +80,7 @@ func (r *resolver) Channels(ctx context.Context, args struct { } // TODO: convert this to a streaming API. - channels, appErr := c.App.GetChannelsForTeamForUserWithCursor(args.TeamID, args.UserID, &model.ChannelSearchOpts{ + channels, appErr := c.App.GetChannelsForTeamForUserWithCursor(c.AppContext, args.TeamID, args.UserID, &model.ChannelSearchOpts{ IncludeDeleted: args.IncludeDeleted, LastDeleteAt: int(args.LastDeleteAt), LastUpdateAt: int(args.LastUpdateAt), @@ -90,7 +90,7 @@ func (r *resolver) Channels(ctx context.Context, args struct { return nil, appErr } - appErr = c.App.FillInChannelsProps(channels) + appErr = c.App.FillInChannelsProps(c.AppContext, channels) if appErr != nil { return nil, appErr } @@ -236,12 +236,14 @@ func (*resolver) ChannelMembers(ctx context.Context, args struct { // If it's a single channel if args.ChannelID != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), args.ChannelID, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), args.ChannelID, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return nil, c.Err } - member, appErr := c.App.GetChannelMember(app.WithMaster(context.Background()), args.ChannelID, args.UserID) + ctx := c.AppContext + ctx.SetContext(app.WithMaster(ctx.Context())) + member, appErr := c.App.GetChannelMember(ctx, args.ChannelID, args.UserID) if appErr != nil { return nil, appErr } @@ -345,7 +347,7 @@ func (*resolver) SidebarCategories(ctx context.Context, args struct { var categories *model.OrderedSidebarCategories var appErr *model.AppError if !args.ExcludeTeam { - categories, appErr = c.App.GetSidebarCategoriesForTeamForUser(args.UserID, args.TeamID) + categories, appErr = c.App.GetSidebarCategoriesForTeamForUser(c.AppContext, args.UserID, args.TeamID) if appErr != nil { return nil, appErr } @@ -354,7 +356,7 @@ func (*resolver) SidebarCategories(ctx context.Context, args struct { TeamID: args.TeamID, ExcludeTeam: args.ExcludeTeam, } - categories, appErr = c.App.GetSidebarCategories(args.UserID, opts) + categories, appErr = c.App.GetSidebarCategories(c.AppContext, args.UserID, opts) if appErr != nil { return nil, appErr } diff --git a/api4/resolver_channel.go b/api4/resolver_channel.go index 04f926b894..3cf4d28893 100644 --- a/api4/resolver_channel.go +++ b/api4/resolver_channel.go @@ -36,22 +36,22 @@ func (ch *channel) Stats(ctx context.Context) (*model.ChannelStats, error) { return nil, err } - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), ch.Id, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), ch.Id, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return nil, c.Err } - memberCount, appErr := c.App.GetChannelMemberCount(ch.Id) + memberCount, appErr := c.App.GetChannelMemberCount(c.AppContext, ch.Id) if appErr != nil { return nil, appErr } - guestCount, appErr := c.App.GetChannelGuestCount(ch.Id) + guestCount, appErr := c.App.GetChannelGuestCount(c.AppContext, ch.Id) if appErr != nil { return nil, appErr } - pinnedPostCount, appErr := c.App.GetChannelPinnedPostCount(ch.Id) + pinnedPostCount, appErr := c.App.GetChannelPinnedPostCount(c.AppContext, ch.Id) if appErr != nil { return nil, appErr } diff --git a/api4/resolver_channel_member.go b/api4/resolver_channel_member.go index f2fcd597f4..0d712e2632 100644 --- a/api4/resolver_channel_member.go +++ b/api4/resolver_channel_member.go @@ -68,7 +68,7 @@ func graphQLChannelsLoader(ctx context.Context, keys dataloader.Keys) []*dataloa } func getGraphQLChannels(c *web.Context, channelIDs []string) ([]*channel, error) { - channels, appErr := c.App.GetChannels(channelIDs) + channels, appErr := c.App.GetChannels(c.AppContext, channelIDs) if appErr != nil { return nil, appErr } @@ -92,18 +92,18 @@ func getGraphQLChannels(c *web.Context, channelIDs []string) ([]*channel, error) teamsForOpenChannels = append(teamsForOpenChannels, teamID) } - if len(openChannels) > 0 && !c.App.SessionHasPermissionToChannels(*c.AppContext.Session(), openChannels, model.PermissionReadChannel) && - !c.App.SessionHasPermissionToTeams(*c.AppContext.Session(), teamsForOpenChannels, model.PermissionReadPublicChannel) { + if len(openChannels) > 0 && !c.App.SessionHasPermissionToChannels(c.AppContext, *c.AppContext.Session(), openChannels, model.PermissionReadChannel) && + !c.App.SessionHasPermissionToTeams(c.AppContext, *c.AppContext.Session(), teamsForOpenChannels, model.PermissionReadPublicChannel) { c.SetPermissionError(model.PermissionReadPublicChannel) return nil, c.Err } - if len(nonOpenChannels) > 0 && !c.App.SessionHasPermissionToChannels(*c.AppContext.Session(), nonOpenChannels, model.PermissionReadChannel) { + if len(nonOpenChannels) > 0 && !c.App.SessionHasPermissionToChannels(c.AppContext, *c.AppContext.Session(), nonOpenChannels, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return nil, c.Err } - appErr = c.App.FillInChannelsProps(model.ChannelList(channels)) + appErr = c.App.FillInChannelsProps(c.AppContext, model.ChannelList(channels)) if appErr != nil { return nil, appErr } diff --git a/api4/resolver_channel_member_test.go b/api4/resolver_channel_member_test.go index c6c8119f57..d4278145e7 100644 --- a/api4/resolver_channel_member_test.go +++ b/api4/resolver_channel_member_test.go @@ -24,8 +24,8 @@ func TestGraphQLChannelMembers(t *testing.T) { ch1 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, myTeam.Id) ch2 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypePrivate, myTeam.Id) th.LinkUserToTeam(th.BasicUser, myTeam) - th.App.AddUserToChannel(th.BasicUser, ch1, false) - th.App.AddUserToChannel(th.BasicUser, ch2, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch1, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch2, false) // Creating some msgcount th.CreateMessagePostWithClient(th.Client, th.BasicChannel, "basic post") diff --git a/api4/resolver_channel_test.go b/api4/resolver_channel_test.go index 11f1a7f11e..627706bd48 100644 --- a/api4/resolver_channel_test.go +++ b/api4/resolver_channel_test.go @@ -24,8 +24,8 @@ func TestGraphQLChannels(t *testing.T) { ch1 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, myTeam.Id) ch2 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypePrivate, myTeam.Id) th.LinkUserToTeam(th.BasicUser, myTeam) - th.App.AddUserToChannel(th.BasicUser, ch1, false) - th.App.AddUserToChannel(th.BasicUser, ch2, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch1, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch2, false) th.CreateDmChannel(th.BasicUser2) var q struct { @@ -413,7 +413,7 @@ func TestGraphQLChannels(t *testing.T) { require.Len(t, q.Channels, 3) for _, ch := range q.Channels { require.Equal(t, ch.ID, ch.Stats.ChannelId) - count, appErr := th.App.GetChannelMemberCount(ch.Stats.ChannelId) + count, appErr := th.App.GetChannelMemberCount(th.Context, ch.Stats.ChannelId) require.Nil(t, appErr) require.Equal(t, float64(count), ch.Stats.MemberCount) } diff --git a/api4/resolver_sidebar_categories_test.go b/api4/resolver_sidebar_categories_test.go index 2c8b68252c..2b8af0a7bc 100644 --- a/api4/resolver_sidebar_categories_test.go +++ b/api4/resolver_sidebar_categories_test.go @@ -101,8 +101,8 @@ func TestGraphQLSidebarCategories(t *testing.T) { ch1 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, myTeam.Id) ch2 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypePrivate, myTeam.Id) th.LinkUserToTeam(th.BasicUser, myTeam) - th.App.AddUserToChannel(th.BasicUser, ch1, false) - th.App.AddUserToChannel(th.BasicUser, ch2, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch1, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch2, false) input = graphQLInput{ OperationName: "sidebarCategories", diff --git a/api4/resolver_team.go b/api4/resolver_team.go index 7f2435b64c..7bf95a2685 100644 --- a/api4/resolver_team.go +++ b/api4/resolver_team.go @@ -71,7 +71,7 @@ func getGraphQLTeams(c *web.Context, teamIDs []string) ([]*model.Team, error) { } } - if !c.App.SessionHasPermissionToTeams(*c.AppContext.Session(), teamsToCheck, model.PermissionViewMembers) { + if !c.App.SessionHasPermissionToTeams(c.AppContext, *c.AppContext.Session(), teamsToCheck, model.PermissionViewMembers) { c.SetPermissionError(model.PermissionViewTeam) return nil, c.Err } diff --git a/api4/resolver_team_member_test.go b/api4/resolver_team_member_test.go index 671260e6e3..d8aa832317 100644 --- a/api4/resolver_team_member_test.go +++ b/api4/resolver_team_member_test.go @@ -179,8 +179,8 @@ func TestGraphQLTeamMembers(t *testing.T) { ch1 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, myTeam.Id) ch2 := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypePrivate, myTeam.Id) th.LinkUserToTeam(th.BasicUser, myTeam) - th.App.AddUserToChannel(th.BasicUser, ch1, false) - th.App.AddUserToChannel(th.BasicUser, ch2, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch1, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, ch2, false) input := graphQLInput{ OperationName: "teamMembers", diff --git a/api4/shared_channel_test.go b/api4/shared_channel_test.go index 7aa65872fc..e26732d8f7 100644 --- a/api4/shared_channel_test.go +++ b/api4/shared_channel_test.go @@ -44,7 +44,7 @@ func TestGetAllSharedChannels(t *testing.T) { CreatorId: th.BasicChannel.CreatorId, RemoteId: model.NewId(), } - _, err := th.App.SaveSharedChannel(sc) + _, err := th.App.SaveSharedChannel(th.Context, sc) require.NoError(t, err) savedIds = append(savedIds, channel.Id) } @@ -124,7 +124,7 @@ func TestGetRemoteClusterById(t *testing.T) { CreatorId: th.BasicChannel.CreatorId, RemoteId: rc.RemoteId, } - sc, err := th.App.SaveSharedChannel(sc) + sc, err := th.App.SaveSharedChannel(th.Context, sc) require.NoError(t, err) // create a shared channel remote to connect them diff --git a/api4/system.go b/api4/system.go index 700f4b8e06..713b266d5b 100644 --- a/api4/system.go +++ b/api4/system.go @@ -569,7 +569,7 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) { // Return post data only when PostId is passed. if ack.PostId != "" && ack.NotificationType == model.PushTypeMessage { - if _, appErr := c.App.GetPostIfAuthorized(ack.PostId, c.AppContext.Session(), false); appErr != nil { + if _, appErr := c.App.GetPostIfAuthorized(c.AppContext, ack.PostId, c.AppContext.Session(), false); appErr != nil { c.Err = appErr return } diff --git a/api4/team.go b/api4/team.go index ae7ffdeb65..52c651bca7 100644 --- a/api4/team.go +++ b/api4/team.go @@ -431,7 +431,7 @@ func deleteTeam(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError if c.Params.Permanent { if *c.App.Config().ServiceSettings.EnableAPITeamDeletion { - err = c.App.PermanentDeleteTeamId(c.Params.TeamId) + err = c.App.PermanentDeleteTeamId(c.AppContext, c.Params.TeamId) } else { err = model.NewAppError("deleteTeam", "api.user.delete_team.not_enabled.app_error", nil, "teamId="+c.Params.TeamId, http.StatusUnauthorized) } diff --git a/api4/team_local.go b/api4/team_local.go index db29d7fb48..ebde6bd68c 100644 --- a/api4/team_local.go +++ b/api4/team_local.go @@ -52,7 +52,7 @@ func localDeleteTeam(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError if c.Params.Permanent { - err = c.App.PermanentDeleteTeamId(c.Params.TeamId) + err = c.App.PermanentDeleteTeamId(c.AppContext, c.Params.TeamId) } else { err = c.App.SoftDeleteTeam(c.Params.TeamId) } diff --git a/api4/upload.go b/api4/upload.go index f6b665bb69..bf0e270230 100644 --- a/api4/upload.go +++ b/api4/upload.go @@ -54,7 +54,7 @@ func createUpload(c *Context, w http.ResponseWriter, r *http.Request) { } } else { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PermissionUploadFile) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), us.ChannelId, model.PermissionUploadFile) { c.SetPermissionError(model.PermissionUploadFile) return } @@ -65,7 +65,7 @@ func createUpload(c *Context, w http.ResponseWriter, r *http.Request) { if c.AppContext.Session().UserId != "" { us.UserId = c.AppContext.Session().UserId } - rus, err := c.App.CreateUploadSession(&us) + rus, err := c.App.CreateUploadSession(c.AppContext, &us) if err != nil { c.Err = err return @@ -132,7 +132,7 @@ func uploadData(c *Context, w http.ResponseWriter, r *http.Request) { return } } else { - if us.UserId != c.AppContext.Session().UserId || !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), us.ChannelId, model.PermissionUploadFile) { + if us.UserId != c.AppContext.Session().UserId || !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), us.ChannelId, model.PermissionUploadFile) { c.SetPermissionError(model.PermissionUploadFile) return } diff --git a/api4/upload_test.go b/api4/upload_test.go index 6bcfa2630e..d01e24bcdd 100644 --- a/api4/upload_test.go +++ b/api4/upload_test.go @@ -116,7 +116,7 @@ func TestGetUpload(t *testing.T) { Filename: "upload", FileSize: 8 * 1024 * 1024, } - us, err := th.App.CreateUploadSession(us) + us, err := th.App.CreateUploadSession(th.Context, us) require.Nil(t, err) require.NotNil(t, us) require.NotEmpty(t, us) @@ -176,7 +176,7 @@ func TestGetUploadsForUser(t *testing.T) { Filename: "upload", FileSize: 8 * 1024 * 1024, } - us, err := th.App.CreateUploadSession(us) + us, err := th.App.CreateUploadSession(th.Context, us) require.Nil(t, err) require.NotNil(t, us) require.NotEmpty(t, us) @@ -210,7 +210,7 @@ func TestUploadData(t *testing.T) { Filename: "upload", FileSize: 8 * 1024 * 1024, } - us, err := th.App.CreateUploadSession(us) + us, err := th.App.CreateUploadSession(th.Context, us) require.Nil(t, err) require.NotNil(t, us) require.NotEmpty(t, us) @@ -251,7 +251,7 @@ func TestUploadData(t *testing.T) { Filename: "upload", FileSize: 8 * 1024 * 1024, } - _, appErr := th.App.CreateUploadSession(us2) + _, appErr := th.App.CreateUploadSession(th.Context, us2) require.Nil(t, appErr) info, resp, err := th.SystemAdminClient.UploadData(us2.Id, bytes.NewReader(data)) diff --git a/api4/user.go b/api4/user.go index 568e1cbbe5..f33fea3c21 100644 --- a/api4/user.go +++ b/api4/user.go @@ -739,7 +739,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { if inChannelId != "" { if !*c.App.Config().TeamSettings.ExperimentalViewArchivedChannels { - channel, appErr := c.App.GetChannel(inChannelId) + channel, appErr := c.App.GetChannel(c.AppContext, inChannelId) if appErr != nil { c.Err = appErr return @@ -760,7 +760,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersWithoutTeamPage(userGetOptions, c.IsSystemAdmin()) } else if notInChannelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), notInChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), notInChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } @@ -796,7 +796,7 @@ func getUsers(c *Context, w http.ResponseWriter, r *http.Request) { profiles, err = c.App.GetUsersInTeamPage(userGetOptions, c.IsSystemAdmin()) } } else if inChannelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), inChannelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), inChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } @@ -1002,12 +1002,12 @@ func searchUsers(c *Context, w http.ResponseWriter, r *http.Request) { } } - if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), props.InChannelId, model.PermissionReadChannel) { + if props.InChannelId != "" && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), props.InChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } - if props.NotInChannelId != "" && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), props.NotInChannelId, model.PermissionReadChannel) { + if props.NotInChannelId != "" && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), props.NotInChannelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } @@ -1093,7 +1093,7 @@ func autocompleteUsers(c *Context, w http.ResponseWriter, r *http.Request) { } if channelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionReadChannel) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channelId, model.PermissionReadChannel) { c.SetPermissionError(model.PermissionReadChannel) return } @@ -2697,7 +2697,7 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := c.App.DemoteUserToGuest(user); err != nil { + if err := c.App.DemoteUserToGuest(c.AppContext, user); err != nil { c.Err = err return } @@ -2723,7 +2723,7 @@ func publishUserTyping(c *Context, w http.ResponseWriter, r *http.Request) { return } - if !c.App.HasPermissionToChannel(c.Params.UserId, typingRequest.ChannelId, model.PermissionCreatePost) { + if !c.App.HasPermissionToChannel(c.AppContext, c.Params.UserId, typingRequest.ChannelId, model.PermissionCreatePost) { c.SetPermissionError(model.PermissionCreatePost) return } @@ -2846,7 +2846,7 @@ func getChannelMembersForUser(c *Context, w http.ResponseWriter, r *http.Request return } - members, err := c.App.GetChannelMembersWithTeamDataForUserWithPagination(c.Params.UserId, c.Params.Page, c.Params.PerPage) + members, err := c.App.GetChannelMembersWithTeamDataForUserWithPagination(c.AppContext, c.Params.UserId, c.Params.Page, c.Params.PerPage) if err != nil { c.Err = err return @@ -3092,7 +3092,7 @@ func updateReadStateThreadByUser(c *Context, w http.ResponseWriter, r *http.Requ return } - thread, err := c.App.UpdateThreadReadForUser(c.AppContext.Session().Id, c.Params.UserId, c.Params.TeamId, c.Params.ThreadId, c.Params.Timestamp) + thread, err := c.App.UpdateThreadReadForUser(c.AppContext, c.AppContext.Session().Id, c.Params.UserId, c.Params.TeamId, c.Params.ThreadId, c.Params.Timestamp) if err != nil { c.Err = err return @@ -3128,7 +3128,7 @@ func setUnreadThreadByPostId(c *Context, w http.ResponseWriter, r *http.Request) return } - thread, err := c.App.UpdateThreadReadForUserByPost(c.AppContext.Session().Id, c.Params.UserId, c.Params.TeamId, c.Params.ThreadId, c.Params.PostId) + thread, err := c.App.UpdateThreadReadForUserByPost(c.AppContext, c.AppContext.Session().Id, c.Params.UserId, c.Params.TeamId, c.Params.ThreadId, c.Params.PostId) if err != nil { c.Err = err return diff --git a/api4/user_test.go b/api4/user_test.go index ef04227abe..4788fe570b 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -408,7 +408,7 @@ func TestCreateUserWebSocketEvent(t *testing.T) { _, _, errr = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, guest.Id, "") require.Nil(t, errr) - _, errr = th.App.AddUserToChannel(guest, th.BasicChannel, false) + _, errr = th.App.AddUserToChannel(th.Context, guest, th.BasicChannel, false) require.Nil(t, errr) guestClient := th.CreateClient() @@ -1603,7 +1603,7 @@ func TestGetUsersByGroupChannelIds(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - gc1, appErr := th.App.CreateGroupChannel([]string{th.BasicUser.Id, th.SystemAdminUser.Id, th.TeamAdminUser.Id}, th.BasicUser.Id) + gc1, appErr := th.App.CreateGroupChannel(th.Context, []string{th.BasicUser.Id, th.SystemAdminUser.Id, th.TeamAdminUser.Id}, th.BasicUser.Id) require.Nil(t, appErr) usersByChannelId, _, err := th.Client.GetUsersByGroupChannelIds([]string{gc1.Id}) @@ -2124,7 +2124,7 @@ func TestPermanentDeleteAllUsers(t *testing.T) { require.Nil(t, appErr) require.NotNil(t, rTeam) - rChannel, appErr := th.App.GetChannel(channel.Id) + rChannel, appErr := th.App.GetChannel(th.Context, channel.Id) require.Nil(t, appErr) require.NotNil(t, rChannel) }) @@ -2627,9 +2627,9 @@ func TestGetUsersInChannel(t *testing.T) { TeamId: th.BasicTeam.Id, }) require.NoError(t, appErr) - _, aErr := th.App.AddUserToChannel(th.BasicUser, channel, false) + _, aErr := th.App.AddUserToChannel(th.Context, th.BasicUser, channel, false) require.Nil(t, aErr) - _, aErr = th.App.AddUserToChannel(th.BasicUser2, channel, false) + _, aErr = th.App.AddUserToChannel(th.Context, th.BasicUser2, channel, false) require.Nil(t, aErr) th.SystemAdminClient.DeleteChannel(channel.Id) @@ -5228,7 +5228,7 @@ func TestPromoteGuestToUser(t *testing.T) { _, err = c.PromoteGuestToUser(user.Id) require.NoError(t, err) - defer require.Nil(t, th.App.DemoteUserToGuest(user)) + defer require.Nil(t, th.App.DemoteUserToGuest(th.Context, user)) }, "promote a guest to user") t.Run("websocket update user event", func(t *testing.T) { @@ -5371,11 +5371,11 @@ func TestGetKnownUsers(t *testing.T) { th.LinkUserToTeam(u3, t2) th.LinkUserToTeam(u4, t3) - th.App.AddUserToChannel(u1, c1, false) - th.App.AddUserToChannel(u1, c2, false) - th.App.AddUserToChannel(u2, c1, false) - th.App.AddUserToChannel(u3, c2, false) - th.App.AddUserToChannel(u4, c3, false) + th.App.AddUserToChannel(th.Context, u1, c1, false) + th.App.AddUserToChannel(th.Context, u1, c2, false) + th.App.AddUserToChannel(th.Context, u2, c1, false) + th.App.AddUserToChannel(th.Context, u3, c2, false) + th.App.AddUserToChannel(th.Context, u4, c3, false) t.Run("get know users sharing no channels", func(t *testing.T) { _, _, _ = th.Client.Login(u4.Email, u4.Password) @@ -6214,7 +6214,7 @@ func TestFollowThreads(t *testing.T) { t.Run("No permission to channel", func(t *testing.T) { // Add user1 to private channel - _, appErr := th.App.AddUserToChannel(th.BasicUser, th.BasicPrivateChannel2, false) + _, appErr := th.App.AddUserToChannel(th.Context, th.BasicUser, th.BasicPrivateChannel2, false) require.Nil(t, appErr) defer th.App.RemoveUserFromChannel(th.Context, th.BasicUser.Id, "", th.BasicPrivateChannel2) diff --git a/api4/webhook.go b/api4/webhook.go index be01b9d054..e6403e25c0 100644 --- a/api4/webhook.go +++ b/api4/webhook.go @@ -34,7 +34,7 @@ func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(hook.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, hook.ChannelId) if err != nil { c.Err = err return @@ -50,7 +50,7 @@ func createIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + if channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { c.LogAudit("fail - bad channel permissions") c.SetPermissionError(model.PermissionReadChannel) return @@ -127,7 +127,7 @@ func updateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err := c.App.GetChannel(updatedHook.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, updatedHook.ChannelId) if err != nil { c.Err = err return @@ -151,7 +151,7 @@ func updateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - if channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { + if channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channel.Id, model.PermissionReadChannel) { c.LogAudit("fail - bad channel permissions") c.SetPermissionError(model.PermissionReadChannel) return @@ -244,14 +244,14 @@ func getIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", hook.TeamId) c.LogAudit("attempt") - channel, err = c.App.GetChannel(hook.ChannelId) + channel, err = c.App.GetChannel(c.AppContext, hook.ChannelId) if err != nil { c.Err = err return } if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageIncomingWebhooks) || - (channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PermissionReadChannel)) { + (channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), hook.ChannelId, model.PermissionReadChannel)) { c.LogAudit("fail - bad permissions") c.SetPermissionError(model.PermissionManageIncomingWebhooks) return @@ -289,7 +289,7 @@ func deleteIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { return } - channel, err = c.App.GetChannel(hook.ChannelId) + channel, err = c.App.GetChannel(c.AppContext, hook.ChannelId) if err != nil { c.Err = err return @@ -304,7 +304,7 @@ func deleteIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("team_id", hook.TeamId) if !c.App.SessionHasPermissionToTeam(*c.AppContext.Session(), hook.TeamId, model.PermissionManageIncomingWebhooks) || - (channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), hook.ChannelId, model.PermissionReadChannel)) { + (channel.Type != model.ChannelTypeOpen && !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), hook.ChannelId, model.PermissionReadChannel)) { c.LogAudit("fail - bad permissions") c.SetPermissionError(model.PermissionManageIncomingWebhooks) return @@ -379,7 +379,7 @@ func updateOutgoingHook(c *Context, w http.ResponseWriter, r *http.Request) { updatedHook.CreatorId = c.AppContext.Session().UserId - rhook, err := c.App.UpdateOutgoingWebhook(oldHook, &updatedHook) + rhook, err := c.App.UpdateOutgoingWebhook(c.AppContext, oldHook, &updatedHook) if err != nil { c.Err = err return @@ -454,13 +454,13 @@ func getOutgoingHooks(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError if channelId != "" { - if !c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionManageOutgoingWebhooks) { + if !c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channelId, model.PermissionManageOutgoingWebhooks) { c.SetPermissionError(model.PermissionManageOutgoingWebhooks) return } // Remove userId as a filter if they have permission to manage others. - if c.App.SessionHasPermissionToChannel(*c.AppContext.Session(), channelId, model.PermissionManageOthersOutgoingWebhooks) { + if c.App.SessionHasPermissionToChannel(c.AppContext, *c.AppContext.Session(), channelId, model.PermissionManageOthersOutgoingWebhooks) { userId = "" } diff --git a/api4/webhook_local.go b/api4/webhook_local.go index b9a45a2d34..93c02a35b6 100644 --- a/api4/webhook_local.go +++ b/api4/webhook_local.go @@ -38,7 +38,7 @@ func localCreateIncomingHook(c *Context, w http.ResponseWriter, r *http.Request) return } - channel, err := c.App.GetChannel(hook.ChannelId) + channel, err := c.App.GetChannel(c.AppContext, hook.ChannelId) if err != nil { c.Err = err return diff --git a/app/app_iface.go b/app/app_iface.go index c193d08007..e1e0aeb057 100644 --- a/app/app_iface.go +++ b/app/app_iface.go @@ -44,7 +44,7 @@ type AppIface interface { // @openTracingParams teamID, skipSlackParsing CreateCommandPost(c *request.Context, post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) // AddChannelMember adds a user to a channel. It is a wrapper over AddUserToChannel. - AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) + AddChannelMember(c request.CTX, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) // AddCursorIdsForPostList adds NextPostId and PrevPostId as cursor to the PostList. // The conditional blocks ensure that it sets those cursor IDs immediately as afterPost, beforePost or empty, // and only query to database whenever necessary. @@ -52,7 +52,7 @@ type AppIface interface { // AddPublicKey will add plugin public key to the config. Overwrites the previous file AddPublicKey(name string, key io.Reader) *model.AppError // AddUserToChannel adds a user to a given channel. - AddUserToChannel(user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) + AddUserToChannel(c request.CTX, user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) // Caller must close the first return value FileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) // ChannelMembersMinusGroupMembers returns the set of users in the given channel minus the set of users in the given @@ -86,7 +86,7 @@ type AppIface interface { // CreateBot creates the given bot and corresponding user. CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model.AppError) // CreateChannelScheme creates a new Scheme of scope channel and assigns it to the channel. - CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model.AppError) + CreateChannelScheme(c request.CTX, channel *model.Channel) (*model.Scheme, *model.AppError) // CreateDefaultMemberships adds users to teams and channels based on their group memberships and how those groups // are configured to sync with teams and channels for group members on or after the given timestamp. // If includeRemovedMembers is true, then members who left or were removed from a team/channel will @@ -108,9 +108,9 @@ type AppIface interface { // 'off-topic' and be included in the return results in addition to 'town-square'. For example: // ['town-square', 'game-of-thrones', 'wow'] // - DefaultChannelNames() []string + DefaultChannelNames(c request.CTX) []string // DeleteChannelScheme deletes a channels scheme and sets its SchemeId to nil. - DeleteChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) + DeleteChannelScheme(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) // DeleteGroupConstrainedMemberships deletes team and channel memberships of users who aren't members of the allowed // groups of all group-constrained teams and channels. DeleteGroupConstrainedMemberships(c *request.Context) error @@ -118,7 +118,7 @@ type AppIface interface { DeletePublicKey(name string) *model.AppError // DemoteUserToGuest Convert user's roles and all his membership's roles from // regular user roles to guest roles. - DemoteUserToGuest(user *model.User) *model.AppError + DemoteUserToGuest(c request.CTX, user *model.User) *model.AppError // DisablePlugin will set the config for an installed plugin to disabled, triggering deactivation if active. // Notifies cluster peers through config change. DisablePlugin(id string) *model.AppError @@ -146,7 +146,7 @@ type AppIface interface { // channel_mentions. // // If channel is nil, FillInPostProps will look up the channel corresponding to the post. - FillInPostProps(post *model.Post, channel *model.Channel) *model.AppError + FillInPostProps(c request.CTX, post *model.Post, channel *model.Channel) *model.AppError // FilterNonGroupChannelMembers returns the subset of the given user IDs of the users who are not members of groups // associated to the channel excluding bots FilterNonGroupChannelMembers(userIDs []string, channel *model.Channel) ([]string, error) @@ -163,7 +163,7 @@ type AppIface interface { // GetChannelGroupUsers returns the users who are associated to the channel via GroupChannels and GroupMembers. GetChannelGroupUsers(channelID string) ([]*model.User, *model.AppError) // GetChannelModerationsForChannel Gets a channels ChannelModerations from either the higherScoped roles or from the channel scheme roles. - GetChannelModerationsForChannel(channel *model.Channel) ([]*model.ChannelModeration, *model.AppError) + GetChannelModerationsForChannel(c request.CTX, channel *model.Channel) ([]*model.ChannelModeration, *model.AppError) // GetClusterPluginStatuses returns the status for plugins installed anywhere in the cluster. GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) // GetConfigFile proxies access to the given configuration file to the underlying config store. @@ -213,7 +213,7 @@ type AppIface interface { // GetSanitizedConfig gets the configuration for a system admin without any secrets. GetSanitizedConfig() *model.Config // GetSchemeRolesForChannel Checks if a channel or its team has an override scheme for channel roles and returns the scheme roles or default channel roles. - GetSchemeRolesForChannel(channelID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) + GetSchemeRolesForChannel(c request.CTX, channelID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) // GetSessionLengthInMillis returns the session length, in milliseconds, // based on the type of session (Mobile, SSO, Web/LDAP). GetSessionLengthInMillis(session *model.Session) int64 @@ -224,7 +224,7 @@ type AppIface interface { // GetTeamGroupUsers returns the users who are associated to the team via GroupTeams and GroupMembers. GetTeamGroupUsers(teamID string) ([]*model.User, *model.AppError) // GetTeamSchemeChannelRoles Checks if a team has an override scheme and returns the scheme channel role names or default channel role names. - GetTeamSchemeChannelRoles(teamID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) + GetTeamSchemeChannelRoles(c request.CTX, teamID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) // GetTotalUsersStats is used for the DM list total GetTotalUsersStats(viewRestrictions *model.ViewUsersRestrictions) (*model.UsersStats, *model.AppError) // HasRemote returns whether a given channelID is present in the channel remotes or not. @@ -244,16 +244,16 @@ type AppIface interface { // MakeAuditRecord creates a audit record pre-populated with defaults. MakeAuditRecord(event string, initialStatus string) *audit.Record // MarkChanelAsUnreadFromPost will take a post and set the channel as unread from that one. - MarkChannelAsUnreadFromPost(postID string, userID string, collapsedThreadsSupported bool) (*model.ChannelUnreadAt, *model.AppError) + MarkChannelAsUnreadFromPost(c request.CTX, postID string, userID string, collapsedThreadsSupported bool) (*model.ChannelUnreadAt, *model.AppError) // MentionsToPublicChannels returns all the mentions to public channels, // linking them to their channels - MentionsToPublicChannels(message, teamID string) model.ChannelMentionMap + MentionsToPublicChannels(c request.CTX, message, teamID string) model.ChannelMentionMap // MentionsToTeamMembers returns all the @ mentions found in message that // belong to users in the specified team, linking them to their users MentionsToTeamMembers(message, teamID string) model.UserMentionMap // MoveChannel method is prone to data races if someone joins to channel during the move process. However this // function is only exposed to sysadmins and the possibility of this edge case is relatively small. - MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError + MoveChannel(c request.CTX, team *model.Team, channel *model.Channel, user *model.User) *model.AppError // NewWebConn returns a new WebConn instance. NewWebConn(cfg *WebConnConfig) *WebConn // NotifySessionsExpired is called periodically from the job server to notify any mobile sessions that have expired. @@ -264,7 +264,7 @@ type AppIface interface { // PatchBot applies the given patch to the bot and corresponding user. PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) // PatchChannelModerationsForChannel Updates a channels scheme roles based on a given ChannelModerationPatch, if the permissions match the higher scoped role the scheme is deleted. - PatchChannelModerationsForChannel(channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) + PatchChannelModerationsForChannel(c request.CTX, channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) // Perform an HTTP POST request to an integration's action endpoint. // Caller must consume and close returned http.Response as necessary. // For internal requests, requests are routed directly to a plugin ServerHTTP hook @@ -279,12 +279,12 @@ type AppIface interface { // use a sinceUnixMillis parameter value as returned by model.GetStartOfDayMillis. // // WARNING: PostCountsByDuration PERFORMS NO AUTHORIZATION CHECKS ON THE GIVEN CHANNELS. - PostCountsByDuration(channelIDs []string, sinceUnixMillis int64, userID *string, grouping model.PostCountGrouping, groupingLocation *time.Location) ([]*model.DurationPostCount, *model.AppError) + PostCountsByDuration(c request.CTX, channelIDs []string, sinceUnixMillis int64, userID *string, grouping model.PostCountGrouping, groupingLocation *time.Location) ([]*model.DurationPostCount, *model.AppError) // PromoteGuestToUser Convert user's roles and all his membership's roles from // guest roles to regular user roles. PromoteGuestToUser(c *request.Context, user *model.User, requestorId string) *model.AppError // RenameChannel is used to rename the channel Name and the DisplayName fields - RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) + RenameChannel(c request.CTX, channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) // RenameTeam is used to rename the team Name and the DisplayName fields RenameTeam(team *model.Team, newTeamName string, newDisplayName string) (*model.Team, *model.AppError) // RevokeSessionsFromAllUsers will go through all the sessions active @@ -293,19 +293,19 @@ type AppIface interface { // SaveConfig replaces the active configuration, optionally notifying cluster peers. SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) (*model.Config, *model.Config, *model.AppError) // SearchAllChannels returns a list of channels, the total count of the results of the search (if the paginate search option is true), and an error. - SearchAllChannels(term string, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, int64, *model.AppError) + SearchAllChannels(c request.CTX, term string, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, int64, *model.AppError) // SearchAllTeams returns a team list and the total count of the results SearchAllTeams(searchOpts *model.TeamSearch) ([]*model.Team, int64, *model.AppError) // SendNoCardPaymentFailedEmail SendNoCardPaymentFailedEmail() *model.AppError // SessionHasPermissionToChannels returns true only if user has access to all channels. - SessionHasPermissionToChannels(session model.Session, channelIDs []string, permission *model.Permission) bool + SessionHasPermissionToChannels(c request.CTX, session model.Session, channelIDs []string, permission *model.Permission) bool // SessionHasPermissionToManageBot returns nil if the session has access to manage the given bot. // This function deviates from other authorization checks in returning an error instead of just // a boolean, allowing the permission failure to be exposed with more granularity. SessionHasPermissionToManageBot(session model.Session, botUserId string) *model.AppError // SessionHasPermissionToTeams returns true only if user has access to all teams. - SessionHasPermissionToTeams(session model.Session, teamIDs []string, permission *model.Permission) bool + SessionHasPermissionToTeams(c request.CTX, session model.Session, teamIDs []string, permission *model.Permission) bool // SessionIsRegistered determines if a specific session has been registered SessionIsRegistered(session model.Session) bool // SetSessionExpireInHours sets the session's expiry the specified number of hours @@ -358,9 +358,9 @@ type AppIface interface { // UpdateBotOwner changes a bot's owner to the given value. UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError) // UpdateChannel updates a given channel by its Id. It also publishes the CHANNEL_UPDATED event. - UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) + UpdateChannel(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) // UpdateChannelScheme saves the new SchemeId of the channel passed. - UpdateChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) + UpdateChannelScheme(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) // UpdateDNDStatusOfUsers is a recurring task which is started when server starts // which unsets dnd status of users if needed and saves and broadcasts it UpdateDNDStatusOfUsers() @@ -396,7 +396,7 @@ type AppIface interface { ActivateMfa(userID, token string) *model.AppError AddChannelsToRetentionPolicy(policyID string, channelIDs []string) *model.AppError AddConfigListener(listener func(*model.Config, *model.Config)) string - AddDirectChannels(teamID string, user *model.User) *model.AppError + AddDirectChannels(c request.CTX, teamID string, user *model.User) *model.AppError AddLdapPrivateCertificate(fileData *multipart.FileHeader) *model.AppError AddLdapPublicCertificate(fileData *multipart.FileHeader) *model.AppError AddRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError) @@ -426,14 +426,14 @@ type AppIface interface { AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request) AuthenticateUserForLogin(c *request.Context, id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectURI string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError) - AutocompleteChannels(userID, term string) (model.ChannelListWithTeamData, *model.AppError) - AutocompleteChannelsForSearch(teamID string, userID string, term string) (model.ChannelList, *model.AppError) - AutocompleteChannelsForTeam(teamID, userID, term string) (model.ChannelList, *model.AppError) + AutocompleteChannels(c request.CTX, userID, term string) (model.ChannelListWithTeamData, *model.AppError) + AutocompleteChannelsForSearch(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) + AutocompleteChannelsForTeam(c request.CTX, teamID, userID, term string) (model.ChannelList, *model.AppError) AutocompleteUsersInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) AutocompleteUsersInTeam(teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) BroadcastStatus(status *model.Status) BuildPostReactions(postID string) (*[]ReactionImportData, *model.AppError) - BuildPushNotificationMessage(contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError) + BuildPushNotificationMessage(c request.CTX, contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError) BuildSamlMetadataObject(idpMetadata []byte) (*model.SamlMetadataResponse, *model.AppError) BulkExport(writer io.Writer, outPath string, opts model.BulkExportOpts) *model.AppError BulkImport(c *request.Context, jsonlReader io.Reader, attachmentsReader *zip.Reader, dryRun bool, workers int) (*model.AppError, int) @@ -452,7 +452,7 @@ type AppIface interface { CheckUserPostflightAuthenticationCriteria(user *model.User) *model.AppError CheckUserPreflightAuthenticationCriteria(user *model.User, mfaToken string) *model.AppError CheckWebConn(userID, connectionID string) *CheckConnResult - ClearChannelMembersCache(channelID string) + ClearChannelMembersCache(c request.CTX, channelID string) ClearLatestVersionCache() ClearSessionCacheForAllUsers() ClearSessionCacheForAllUsersSkipClusterSend() @@ -471,13 +471,13 @@ type AppIface interface { Compliance() einterfaces.ComplianceInterface Config() *model.Config CopyFileInfos(userID string, fileIDs []string) ([]string, *model.AppError) - CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) - CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) + CreateChannel(c request.CTX, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) + CreateChannelWithUser(c request.CTX, channel *model.Channel, userID string) (*model.Channel, *model.AppError) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) CreateCommandWebhook(commandID string, args *model.CommandArgs) (*model.CommandWebhook, *model.AppError) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *multipart.Form) (*model.Emoji, *model.AppError) CreateGroup(group *model.Group) (*model.Group, *model.AppError) - CreateGroupChannel(userIDs []string, creatorId string) (*model.Channel, *model.AppError) + CreateGroupChannel(c request.CTX, userIDs []string, creatorId string) (*model.Channel, *model.AppError) CreateGroupWithUserIds(group *model.GroupWithUserIds) (*model.Group, *model.AppError) CreateIncomingWebhookForChannel(creatorId string, channel *model.Channel, hook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) CreateJob(job *model.Job) (*model.Job, *model.AppError) @@ -486,24 +486,24 @@ type AppIface interface { CreateOAuthUser(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) CreatePasswordRecoveryToken(userID, email string) (*model.Token, *model.AppError) - CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) + CreatePost(c request.CTX, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) CreatePostAsUser(c *request.Context, post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) - CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) + CreatePostMissingChannel(c request.CTX, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) CreateRetentionPolicy(policy *model.RetentionPolicyWithTeamAndChannelIDs) (*model.RetentionPolicyWithTeamAndChannelCounts, *model.AppError) CreateRole(role *model.Role) (*model.Role, *model.AppError) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) CreateSession(session *model.Session) (*model.Session, *model.AppError) - CreateSidebarCategory(userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) + CreateSidebarCategory(c request.CTX, userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) CreateTeam(c *request.Context, team *model.Team) (*model.Team, *model.AppError) CreateTeamWithUser(c *request.Context, team *model.Team, userID string) (*model.Team, *model.AppError) CreateTermsOfService(text, userID string) (*model.TermsOfService, *model.AppError) - CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) + CreateUploadSession(c request.CTX, us *model.UploadSession) (*model.UploadSession, *model.AppError) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) CreateUserAsAdmin(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) CreateUserFromSignup(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError) CreateUserWithInviteId(c *request.Context, user *model.User, inviteId, redirect string) (*model.User, *model.AppError) CreateUserWithToken(c *request.Context, user *model.User, token *model.Token) (*model.User, *model.AppError) - CreateWebhookPost(c *request.Context, userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) + CreateWebhookPost(c request.CTX, userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) DBHealthCheckDelete() error DBHealthCheckWrite() error DataRetention() einterfaces.DataRetentionInterface @@ -513,7 +513,7 @@ type AppIface interface { DeleteAllExpiredPluginKeys() *model.AppError DeleteAllKeysForPlugin(pluginID string) *model.AppError DeleteBrandImage() *model.AppError - DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError + DeleteChannel(c request.CTX, channel *model.Channel, userID string) *model.AppError DeleteCommand(commandID string) *model.AppError DeleteEmoji(emoji *model.Emoji) *model.AppError DeleteEphemeralPost(userID, postID string) @@ -526,7 +526,7 @@ type AppIface interface { DeleteOAuthApp(appID string) *model.AppError DeleteOutgoingWebhook(hookID string) *model.AppError DeletePluginKey(pluginID string, key string) *model.AppError - DeletePost(postID, deleteByID string) (*model.Post, *model.AppError) + DeletePost(c request.CTX, postID, deleteByID string) (*model.Post, *model.AppError) DeletePreferences(userID string, preferences model.Preferences) *model.AppError DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError DeleteRemoteCluster(remoteClusterId string) (bool, *model.AppError) @@ -534,7 +534,7 @@ type AppIface interface { DeleteScheme(schemeId string) (*model.Scheme, *model.AppError) DeleteSharedChannel(channelID string) (bool, error) DeleteSharedChannelRemote(id string) (bool, error) - DeleteSidebarCategory(userID, teamID, categoryId string) *model.AppError + DeleteSidebarCategory(c request.CTX, userID, teamID, categoryId string) *model.AppError DeleteToken(token *model.Token) *model.AppError DisableAutoResponder(userID string, asAdmin bool) *model.AppError DisableUserAccessToken(token *model.UserAccessToken) *model.AppError @@ -559,16 +559,16 @@ type AppIface interface { FileExists(path string) (bool, *model.AppError) FileModTime(path string) (time.Time, *model.AppError) FileSize(path string) (int64, *model.AppError) - FillInChannelProps(channel *model.Channel) *model.AppError - FillInChannelsProps(channelList model.ChannelList) *model.AppError + FillInChannelProps(c request.CTX, channel *model.Channel) *model.AppError + FillInChannelsProps(c request.CTX, channelList model.ChannelList) *model.AppError FilterUsersByVisible(viewer *model.User, otherUsers []*model.User) ([]*model.User, *model.AppError) FindTeamByName(name string) bool GenerateMfaSecret(userID string) (*model.MfaSecret, *model.AppError) GeneratePublicLink(siteURL string, info *model.FileInfo) string GenerateSupportPacket() []model.FileData GetActivePluginManifests() ([]*model.Manifest, *model.AppError) - GetAllChannels(page, perPage int, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, *model.AppError) - GetAllChannelsCount(opts model.ChannelSearchOpts) (int64, *model.AppError) + GetAllChannels(c request.CTX, page, perPage int, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, *model.AppError) + GetAllChannelsCount(c request.CTX, opts model.ChannelSearchOpts) (int64, *model.AppError) GetAllPrivateTeams() ([]*model.Team, *model.AppError) GetAllPublicTeams() ([]*model.Team, *model.AppError) GetAllRemoteClusters(filter model.RemoteClusterQueryFilter) ([]*model.RemoteCluster, *model.AppError) @@ -585,32 +585,32 @@ type AppIface interface { GetAuthorizedAppsForUser(userID string, page, perPage int) ([]*model.OAuthApp, *model.AppError) GetBrandImage() ([]byte, *model.AppError) GetBulkReactionsForPosts(postIDs []string) (map[string][]*model.Reaction, *model.AppError) - GetChannel(channelID string) (*model.Channel, *model.AppError) - GetChannelByName(channelName, teamID string, includeDeleted bool) (*model.Channel, *model.AppError) - GetChannelByNameForTeamName(channelName, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) - GetChannelCounts(teamID string, userID string) (*model.ChannelCounts, *model.AppError) - GetChannelFileCount(channelID string) (int64, *model.AppError) - GetChannelGuestCount(channelID string) (int64, *model.AppError) - GetChannelMember(ctx context.Context, channelID string, userID string) (*model.ChannelMember, *model.AppError) - GetChannelMemberCount(channelID string) (int64, *model.AppError) - GetChannelMembersByIds(channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) - GetChannelMembersForUser(teamID string, userID string) (model.ChannelMembers, *model.AppError) - GetChannelMembersForUserWithPagination(userID string, page, perPage int) ([]*model.ChannelMember, *model.AppError) - GetChannelMembersPage(channelID string, page, perPage int) (model.ChannelMembers, *model.AppError) - GetChannelMembersTimezones(channelID string) ([]string, *model.AppError) - GetChannelMembersWithTeamDataForUserWithPagination(userID string, page, perPage int) (model.ChannelMembersWithTeamData, *model.AppError) - GetChannelPinnedPostCount(channelID string) (int64, *model.AppError) + GetChannel(c request.CTX, channelID string) (*model.Channel, *model.AppError) + GetChannelByName(c request.CTX, channelName, teamID string, includeDeleted bool) (*model.Channel, *model.AppError) + GetChannelByNameForTeamName(c request.CTX, channelName, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) + GetChannelCounts(c request.CTX, teamID string, userID string) (*model.ChannelCounts, *model.AppError) + GetChannelFileCount(c request.CTX, channelID string) (int64, *model.AppError) + GetChannelGuestCount(c request.CTX, channelID string) (int64, *model.AppError) + GetChannelMember(c request.CTX, channelID string, userID string) (*model.ChannelMember, *model.AppError) + GetChannelMemberCount(c request.CTX, channelID string) (int64, *model.AppError) + GetChannelMembersByIds(c request.CTX, channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) + GetChannelMembersForUser(c request.CTX, teamID string, userID string) (model.ChannelMembers, *model.AppError) + GetChannelMembersForUserWithPagination(c request.CTX, userID string, page, perPage int) ([]*model.ChannelMember, *model.AppError) + GetChannelMembersPage(c request.CTX, channelID string, page, perPage int) (model.ChannelMembers, *model.AppError) + GetChannelMembersTimezones(c request.CTX, channelID string) ([]string, *model.AppError) + GetChannelMembersWithTeamDataForUserWithPagination(c request.CTX, userID string, page, perPage int) (model.ChannelMembersWithTeamData, *model.AppError) + GetChannelPinnedPostCount(c request.CTX, channelID string) (int64, *model.AppError) GetChannelPoliciesForUser(userID string, offset, limit int) (*model.RetentionPolicyForChannelList, *model.AppError) - GetChannelUnread(channelID, userID string) (*model.ChannelUnread, *model.AppError) - GetChannels(channelIDs []string) ([]*model.Channel, *model.AppError) - GetChannelsByNames(channelNames []string, teamID string) ([]*model.Channel, *model.AppError) + GetChannelUnread(c request.CTX, channelID, userID string) (*model.ChannelUnread, *model.AppError) + GetChannels(c request.CTX, channelIDs []string) ([]*model.Channel, *model.AppError) + GetChannelsByNames(c request.CTX, channelNames []string, teamID string) ([]*model.Channel, *model.AppError) GetChannelsForRetentionPolicy(policyID string, offset, limit int) (*model.ChannelsWithCount, *model.AppError) GetChannelsForScheme(scheme *model.Scheme, offset int, limit int) (model.ChannelList, *model.AppError) GetChannelsForSchemePage(scheme *model.Scheme, page int, perPage int) (model.ChannelList, *model.AppError) - GetChannelsForTeamForUser(teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) - GetChannelsForTeamForUserWithCursor(teamID string, userID string, opts *model.ChannelSearchOpts, afterChannelID string) (model.ChannelList, *model.AppError) - GetChannelsForUser(userID string, includeDeleted bool, lastDeleteAt, pageSize int, fromChannelID string) (model.ChannelList, *model.AppError) - GetChannelsUserNotIn(teamID string, userID string, offset int, limit int) (model.ChannelList, *model.AppError) + GetChannelsForTeamForUser(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) + GetChannelsForTeamForUserWithCursor(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts, afterChannelID string) (model.ChannelList, *model.AppError) + GetChannelsForUser(c request.CTX, userID string, includeDeleted bool, lastDeleteAt, pageSize int, fromChannelID string) (model.ChannelList, *model.AppError) + GetChannelsUserNotIn(c request.CTX, teamID string, userID string, offset int, limit int) (model.ChannelList, *model.AppError) GetCloudSession(token string) (*model.Session, *model.AppError) GetClusterId() string GetClusterStatus() []*model.ClusterInfo @@ -622,7 +622,7 @@ type AppIface interface { GetCookieDomain() string GetCustomStatus(userID string) (*model.CustomStatus, *model.AppError) GetDefaultProfileImage(user *model.User) ([]byte, *model.AppError) - GetDeletedChannels(teamID string, offset int, limit int, userID string) (model.ChannelList, *model.AppError) + GetDeletedChannels(c request.CTX, teamID string, offset int, limit int, userID string) (model.ChannelList, *model.AppError) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) GetEmojiImage(emojiId string) ([]byte, string, *model.AppError) @@ -639,7 +639,7 @@ type AppIface interface { GetGroup(id string, opts *model.GetGroupOpts) (*model.Group, *model.AppError) GetGroupByName(name string, opts model.GroupSearchOpts) (*model.Group, *model.AppError) GetGroupByRemoteID(remoteID string, groupSource model.GroupSource) (*model.Group, *model.AppError) - GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) + GetGroupChannel(c request.CTX, userIDs []string) (*model.Channel, *model.AppError) GetGroupMemberCount(groupID string) (int64, *model.AppError) GetGroupMemberUsers(groupID string) ([]*model.User, *model.AppError) GetGroupMemberUsersPage(groupID string, page int, perPage int) ([]*model.User, int, *model.AppError) @@ -674,7 +674,7 @@ type AppIface interface { GetNewUsersForTeamPage(teamID string, page, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) GetNextPostIdFromPostList(postList *model.PostList, collapsedThreads bool) string GetNotificationNameFormat(user *model.User) string - GetNumberOfChannelsOnTeam(teamID string) (int, *model.AppError) + GetNumberOfChannelsOnTeam(c request.CTX, teamID string) (int, *model.AppError) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) GetOAuthAccessTokenForImplicitFlow(userID string, authRequest *model.AuthorizeRequest) (*model.Session, *model.AppError) GetOAuthApp(appID string) (*model.OAuthApp, *model.AppError) @@ -687,7 +687,7 @@ type AppIface interface { GetOAuthStateToken(token string) (*model.Token, *model.AppError) GetOnboarding() (*model.System, *model.AppError) GetOpenGraphMetadata(requestURL string) ([]byte, error) - GetOrCreateDirectChannel(c *request.Context, userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) + GetOrCreateDirectChannel(c request.CTX, userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) GetOutgoingWebhook(hookID string) (*model.OutgoingWebhook, *model.AppError) GetOutgoingWebhooksForChannelPageByUser(channelID string, userID string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) GetOutgoingWebhooksForTeamPage(teamID string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) @@ -695,31 +695,31 @@ type AppIface interface { GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) GetOutgoingWebhooksPageByUser(userID string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) - GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError) - GetPinnedPosts(channelID string) (*model.PostList, *model.AppError) + GetPermalinkPost(c request.CTX, postID string, userID string) (*model.PostList, *model.AppError) + GetPinnedPosts(c request.CTX, channelID string) (*model.PostList, *model.AppError) GetPluginKey(pluginID string, key string) ([]byte, *model.AppError) GetPlugins() (*model.PluginsResponse, *model.AppError) GetPostAfterTime(channelID string, time int64, collapsedThreads bool) (*model.Post, *model.AppError) GetPostIdAfterTime(channelID string, time int64, collapsedThreads bool) (string, *model.AppError) GetPostIdBeforeTime(channelID string, time int64, collapsedThreads bool) (string, *model.AppError) - GetPostIfAuthorized(postID string, session *model.Session, includeDeleted bool) (*model.Post, *model.AppError) + GetPostIfAuthorized(c request.CTX, postID string, session *model.Session, includeDeleted bool) (*model.Post, *model.AppError) GetPostThread(postID string, opts model.GetPostsOptions, userID string) (*model.PostList, *model.AppError) GetPosts(channelID string, offset int, limit int) (*model.PostList, *model.AppError) GetPostsAfterPost(options model.GetPostsOptions) (*model.PostList, *model.AppError) GetPostsAroundPost(before bool, options model.GetPostsOptions) (*model.PostList, *model.AppError) GetPostsBeforePost(options model.GetPostsOptions) (*model.PostList, *model.AppError) GetPostsEtag(channelID string, collapsedThreads bool) string - GetPostsForChannelAroundLastUnread(channelID, userID string, limitBefore, limitAfter int, skipFetchThreads bool, collapsedThreads, collapsedThreadsExtended bool) (*model.PostList, *model.AppError) + GetPostsForChannelAroundLastUnread(c request.CTX, channelID, userID string, limitBefore, limitAfter int, skipFetchThreads bool, collapsedThreads, collapsedThreadsExtended bool) (*model.PostList, *model.AppError) GetPostsPage(options model.GetPostsOptions) (*model.PostList, *model.AppError) GetPostsSince(options model.GetPostsSinceOptions) (*model.PostList, *model.AppError) GetPreferenceByCategoryAndNameForUser(userID string, category string, preferenceName string) (*model.Preference, *model.AppError) GetPreferenceByCategoryForUser(userID string, category string) (model.Preferences, *model.AppError) GetPreferencesForUser(userID string) (model.Preferences, *model.AppError) GetPrevPostIdFromPostList(postList *model.PostList, collapsedThreads bool) string - GetPrivateChannelsForTeam(teamID string, offset int, limit int) (model.ChannelList, *model.AppError) + GetPrivateChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) - GetPublicChannelsByIdsForTeam(teamID string, channelIDs []string) (model.ChannelList, *model.AppError) - GetPublicChannelsForTeam(teamID string, offset int, limit int) (model.ChannelList, *model.AppError) + GetPublicChannelsByIdsForTeam(c request.CTX, teamID string, channelIDs []string) (model.ChannelList, *model.AppError) + GetPublicChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) GetReactionsForPost(postID string) ([]*model.Reaction, *model.AppError) GetRecentSearchesForUser(userID string) ([]*model.SearchParams, *model.AppError) GetRecentlyActiveUsersForTeam(teamID string) (map[string]*model.User, *model.AppError) @@ -753,10 +753,10 @@ type AppIface interface { GetSharedChannelRemotesStatus(channelID string) ([]*model.SharedChannelRemoteStatus, error) GetSharedChannels(page int, perPage int, opts model.SharedChannelFilterOpts) ([]*model.SharedChannel, *model.AppError) GetSharedChannelsCount(opts model.SharedChannelFilterOpts) (int64, error) - GetSidebarCategories(userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) - GetSidebarCategoriesForTeamForUser(userID, teamID string) (*model.OrderedSidebarCategories, *model.AppError) - GetSidebarCategory(categoryId string) (*model.SidebarCategoryWithChannels, *model.AppError) - GetSidebarCategoryOrder(userID, teamID string) ([]string, *model.AppError) + GetSidebarCategories(c request.CTX, userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) + GetSidebarCategoriesForTeamForUser(c request.CTX, userID, teamID string) (*model.OrderedSidebarCategories, *model.AppError) + GetSidebarCategory(c request.CTX, categoryId string) (*model.SidebarCategoryWithChannels, *model.AppError) + GetSidebarCategoryOrder(c request.CTX, userID, teamID string) ([]string, *model.AppError) GetSinglePost(postID string, includeDeleted bool) (*model.Post, *model.AppError) GetSiteURL() string GetStatus(userID string) (*model.Status, *model.AppError) @@ -789,12 +789,12 @@ type AppIface interface { GetThreadMembershipsForUser(userID, teamID string) ([]*model.ThreadMembership, error) GetThreadsForUser(userID, teamID string, options model.GetUserThreadsOpts) (*model.Threads, *model.AppError) GetTokenById(token string) (*model.Token, *model.AppError) - GetTopChannelsForTeamSince(teamID, userID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) - GetTopChannelsForUserSince(userID, teamID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) + GetTopChannelsForTeamSince(c request.CTX, teamID, userID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) + GetTopChannelsForUserSince(c request.CTX, userID, teamID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) GetTopReactionsForTeamSince(teamID string, userID string, opts *model.InsightsOpts) (*model.TopReactionList, *model.AppError) GetTopReactionsForUserSince(userID string, teamID string, opts *model.InsightsOpts) (*model.TopReactionList, *model.AppError) - GetTopThreadsForTeamSince(teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) - GetTopThreadsForUserSince(teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) + GetTopThreadsForTeamSince(c request.CTX, teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) + GetTopThreadsForUserSince(c request.CTX, teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) GetUploadSession(uploadId string) (*model.UploadSession, *model.AppError) GetUploadSessionsForUser(userID string) ([]*model.UploadSession, *model.AppError) GetUser(userID string) (*model.User, *model.AppError) @@ -846,9 +846,9 @@ type AppIface interface { HandleIncomingWebhook(c *request.Context, hookID string, req *model.IncomingWebhookRequest) *model.AppError HandleMessageExportConfig(cfg *model.Config, appCfg *model.Config) HasPermissionTo(askingUserId string, permission *model.Permission) bool - HasPermissionToChannel(askingUserId string, channelID string, permission *model.Permission) bool + HasPermissionToChannel(c request.CTX, askingUserId string, channelID string, permission *model.Permission) bool HasPermissionToChannelByPost(askingUserId string, postID string, permission *model.Permission) bool - HasPermissionToReadChannel(userID string, channel *model.Channel) bool + HasPermissionToReadChannel(c request.CTX, userID string, channel *model.Channel) bool HasPermissionToTeam(askingUserId string, teamID string, permission *model.Permission) bool HasPermissionToUser(askingUserId string, userID string) bool HasSharedChannel(channelID string) (bool, error) @@ -864,18 +864,18 @@ type AppIface interface { InviteGuestsToChannelsGracefully(teamID string, guestsInvite *model.GuestsInvite, senderId string) ([]*model.EmailInviteWithError, *model.AppError) InviteNewUsersToTeam(emailList []string, teamID, senderId string) *model.AppError InviteNewUsersToTeamGracefully(memberInvite *model.MemberInvite, teamID, senderId string, reminderInterval string) ([]*model.EmailInviteWithError, *model.AppError) - IsCRTEnabledForUser(userID string) bool + IsCRTEnabledForUser(c request.CTX, userID string) bool IsFirstUserAccount() bool IsLeader() bool IsPasswordValid(password string) *model.AppError IsPhase2MigrationCompleted() *model.AppError IsUserAway(lastActivityAt int64) bool IsUserSignUpAllowed() *model.AppError - JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError - JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError + JoinChannel(c request.CTX, channel *model.Channel, userID string) *model.AppError + JoinDefaultChannels(c request.CTX, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError JoinUserToTeam(c *request.Context, team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) Ldap() einterfaces.LdapInterface - LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError + LeaveChannel(c request.CTX, channelID string, userID string) *model.AppError LeaveTeam(c *request.Context, team *model.Team, user *model.User, requestorId string) *model.AppError License() *model.License LimitedClientConfig() map[string]string @@ -889,7 +889,7 @@ type AppIface interface { Log() *mlog.Logger LoginByOAuth(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) MakePermissionError(s *model.Session, permissions []*model.Permission) *model.AppError - MarkChannelsAsViewed(channelIDs []string, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) + MarkChannelsAsViewed(c request.CTX, channelIDs []string, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) MaxPostSize() int MessageExport() einterfaces.MessageExportInterface Metrics() einterfaces.MetricsInterface @@ -905,7 +905,7 @@ type AppIface interface { NotifySystemAdminsToUpgrade(c *request.Context, currentUserTeamID string) *model.AppError OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError OriginChecker() func(*http.Request) bool - PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) + PatchChannel(c request.CTX, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) PatchPost(c *request.Context, 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) @@ -913,22 +913,22 @@ type AppIface interface { PatchTeam(teamID string, patch *model.TeamPatch) (*model.Team, *model.AppError) PatchUser(userID string, patch *model.UserPatch, asAdmin bool) (*model.User, *model.AppError) PermanentDeleteAllUsers(c *request.Context) *model.AppError - PermanentDeleteChannel(channel *model.Channel) *model.AppError - PermanentDeleteTeam(team *model.Team) *model.AppError - PermanentDeleteTeamId(teamID string) *model.AppError + PermanentDeleteChannel(c request.CTX, channel *model.Channel) *model.AppError + PermanentDeleteTeam(c request.CTX, team *model.Team) *model.AppError + PermanentDeleteTeamId(c request.CTX, teamID string) *model.AppError PermanentDeleteUser(c *request.Context, user *model.User) *model.AppError PluginCommandsForTeam(teamID string) []*model.Command PostActionCookieSecret() []byte - PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError + PostAddToChannelMessage(c request.CTX, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError PostPatchWithProxyRemovedFromImageURLs(patch *model.PostPatch) *model.PostPatch - PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError - PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError - PostUpdateChannelPurposeMessage(c *request.Context, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError + PostUpdateChannelDisplayNameMessage(c request.CTX, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError + PostUpdateChannelHeaderMessage(c request.CTX, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError + PostUpdateChannelPurposeMessage(c request.CTX, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError PostWithProxyAddedToImageURLs(post *model.Post) *model.Post PostWithProxyRemovedFromImageURLs(post *model.Post) *model.Post PreparePostForClient(originalPost *model.Post, isNewPost, isEditPost bool) *model.Post - PreparePostForClientWithEmbedsAndImages(originalPost *model.Post, isNewPost, isEditPost bool) *model.Post - PreparePostListForClient(originalList *model.PostList) *model.PostList + PreparePostForClientWithEmbedsAndImages(c request.CTX, originalPost *model.Post, isNewPost, isEditPost bool) *model.Post + PreparePostListForClient(c request.CTX, originalList *model.PostList) *model.PostList ProcessSlackText(text string) string Publish(message *model.WebSocketEvent) PublishUserTyping(userID, channelID, parentId string) *model.AppError @@ -942,7 +942,7 @@ type AppIface interface { RegenerateTeamInviteId(teamID string) (*model.Team, *model.AppError) RegisterPluginCommand(pluginID string, command *model.Command) error ReloadConfig() error - RemoveAllDeactivatedMembersFromChannel(channel *model.Channel) *model.AppError + RemoveAllDeactivatedMembersFromChannel(c request.CTX, channel *model.Channel) *model.AppError RemoveChannelsFromRetentionPolicy(policyID string, channelIDs []string) *model.AppError RemoveConfigListener(id string) RemoveCustomStatus(userID string) *model.AppError @@ -956,14 +956,14 @@ type AppIface interface { RemoveSamlPublicCertificate() *model.AppError RemoveTeamIcon(teamID string) *model.AppError RemoveTeamsFromRetentionPolicy(policyID string, teamIDs []string) *model.AppError - RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError + RemoveUserFromChannel(c request.CTX, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError RemoveUserFromTeam(c *request.Context, teamID string, userID string, requestorId string) *model.AppError - RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError + RemoveUsersFromChannelNotMemberOfTeam(c request.CTX, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId string, isBot bool) *model.AppError ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model.AppError ResetPermissionsSystem() *model.AppError ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs []string) (numAffected int, appErr *model.AppError) - RestoreChannel(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) + RestoreChannel(c request.CTX, channel *model.Channel, userID string) (*model.Channel, *model.AppError) RestoreTeam(teamID string) *model.AppError RestrictUsersGetByPermissions(userID string, options *model.UserGetOptions) (*model.UserGetOptions, *model.AppError) RestrictUsersSearchByPermissions(userID string, options *model.UserSearchOptions) (*model.UserSearchOptions, *model.AppError) @@ -976,8 +976,8 @@ type AppIface interface { RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError RolesGrantPermission(roleNames []string, permissionId string) bool Saml() einterfaces.SamlInterface - SanitizePostListMetadataForUser(postList *model.PostList, userID string) (*model.PostList, *model.AppError) - SanitizePostMetadataForUser(post *model.Post, userID string) (*model.Post, *model.AppError) + SanitizePostListMetadataForUser(c request.CTX, postList *model.PostList, userID string) (*model.PostList, *model.AppError) + SanitizePostMetadataForUser(c request.CTX, post *model.Post, userID string) (*model.Post, *model.AppError) SanitizeProfile(user *model.User, asAdmin bool) SanitizeTeam(session model.Session, team *model.Team) *model.Team SanitizeTeams(session model.Session, teams []*model.Team) []*model.Team @@ -985,18 +985,18 @@ type AppIface interface { SaveBrandImage(imageData *multipart.FileHeader) *model.AppError SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) - SaveSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error) + SaveSharedChannel(c request.CTX, sc *model.SharedChannel) (*model.SharedChannel, error) SaveSharedChannelRemote(remote *model.SharedChannelRemote) (*model.SharedChannelRemote, error) SaveUserTermsOfService(userID, termsOfServiceId string, accepted bool) *model.AppError SchemesIterator(scope string, batchSize int) func() []*model.Scheme - SearchArchivedChannels(teamID string, term string, userID string) (model.ChannelList, *model.AppError) - SearchChannels(teamID string, term string) (model.ChannelList, *model.AppError) - SearchChannelsForUser(userID, teamID, term string) (model.ChannelList, *model.AppError) - SearchChannelsUserNotIn(teamID string, userID string, term string) (model.ChannelList, *model.AppError) + SearchArchivedChannels(c request.CTX, teamID string, term string, userID string) (model.ChannelList, *model.AppError) + SearchChannels(c request.CTX, teamID string, term string) (model.ChannelList, *model.AppError) + SearchChannelsForUser(c request.CTX, userID, teamID, term string) (model.ChannelList, *model.AppError) + SearchChannelsUserNotIn(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emoji, *model.AppError) SearchEngine() *searchengine.Broker SearchFilesInTeamForUser(c *request.Context, terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int, modifier string) (*model.FileInfoList, *model.AppError) - SearchGroupChannels(userID, term string) (model.ChannelList, *model.AppError) + SearchGroupChannels(c request.CTX, userID, term string) (model.ChannelList, *model.AppError) SearchPostsForUser(c *request.Context, terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int, modifier string) (*model.PostSearchResults, *model.AppError) SearchPostsInTeam(teamID string, paramsList []*model.SearchParams) (*model.PostList, *model.AppError) SearchPrivateTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError) @@ -1011,11 +1011,11 @@ type AppIface interface { SearchUsersNotInTeam(notInTeamId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) SearchUsersWithoutTeam(term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) SendAckToPushProxy(ack *model.PushNotificationAck) error - SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) - SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) + SendAutoResponse(c request.CTX, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) + SendAutoResponseIfNecessary(c request.CTX, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) SendEmailVerification(user *model.User, newEmail, redirect string) *model.AppError - SendEphemeralPost(userID string, post *model.Post) *model.Post - SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList, setOnline bool) ([]string, error) + SendEphemeralPost(c request.CTX, userID string, post *model.Post) *model.Post + SendNotifications(c request.CTX, post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList, setOnline bool) ([]string, error) SendPasswordReset(email string, siteURL string) (bool, *model.AppError) SendPaymentFailedEmail(failedPayment *model.FailedPayment) *model.AppError SendTestPushNotification(deviceID string) string @@ -1023,8 +1023,8 @@ type AppIface interface { ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, sourcePluginId, destinationPluginId string) SessionHasPermissionTo(session model.Session, permission *model.Permission) bool SessionHasPermissionToAny(session model.Session, permissions []*model.Permission) bool - SessionHasPermissionToCategory(session model.Session, userID, teamID, categoryId string) bool - SessionHasPermissionToChannel(session model.Session, channelID string, permission *model.Permission) bool + SessionHasPermissionToCategory(c request.CTX, session model.Session, userID, teamID, categoryId string) bool + SessionHasPermissionToChannel(c request.CTX, session model.Session, channelID string, permission *model.Permission) bool SessionHasPermissionToChannelByPost(session model.Session, postID string, permission *model.Permission) bool SessionHasPermissionToCreateJob(session model.Session, job *model.Job) (bool, *model.Permission) SessionHasPermissionToGroup(session model.Session, groupID string, permission *model.Permission) bool @@ -1032,7 +1032,7 @@ type AppIface interface { SessionHasPermissionToTeam(session model.Session, teamID string, permission *model.Permission) bool SessionHasPermissionToUser(session model.Session, userID string) bool SessionHasPermissionToUserOrBot(session model.Session, userID string) bool - SetActiveChannel(userID string, channelID string) *model.AppError + SetActiveChannel(c request.CTX, userID string, channelID string) *model.AppError SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap) SetChannels(ch *Channels) SetCustomStatus(userID string, cs *model.CustomStatus) *model.AppError @@ -1074,18 +1074,18 @@ type AppIface interface { TestLdap() *model.AppError TestSiteURL(siteURL string) *model.AppError Timezones() *timezones.Timezones - ToggleMuteChannel(channelID, userID string) (*model.ChannelMember, *model.AppError) + ToggleMuteChannel(c request.CTX, channelID, userID string) (*model.ChannelMember, *model.AppError) TotalWebsocketConnections() int - TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) + TriggerWebhook(c request.CTX, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) UnregisterPluginCommand(pluginID, teamID, trigger string) UpdateActive(c *request.Context, user *model.User, active bool) (*model.User, *model.AppError) - UpdateChannelMemberNotifyProps(data map[string]string, channelID string, userID string) (*model.ChannelMember, *model.AppError) - UpdateChannelMemberRoles(channelID string, userID string, newRoles string) (*model.ChannelMember, *model.AppError) - UpdateChannelMemberSchemeRoles(channelID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError) - UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) + UpdateChannelMemberNotifyProps(c request.CTX, data map[string]string, channelID string, userID string) (*model.ChannelMember, *model.AppError) + UpdateChannelMemberRoles(c request.CTX, channelID string, userID string, newRoles string) (*model.ChannelMember, *model.AppError) + UpdateChannelMemberSchemeRoles(c request.CTX, channelID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError) + UpdateChannelPrivacy(c request.CTX, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) UpdateConfig(f func(*model.Config)) - UpdateEphemeralPost(userID string, post *model.Post) *model.Post + UpdateEphemeralPost(c request.CTX, userID string, post *model.Post) *model.Post UpdateExpiredDNDStatuses() ([]*model.Status, error) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) UpdateGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) @@ -1097,7 +1097,7 @@ type AppIface interface { UpdateMobileAppBadge(userID string) UpdateOAuthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError - UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) + UpdateOutgoingWebhook(c request.CTX, oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) UpdatePassword(user *model.User, newPassword string) *model.AppError UpdatePasswordAsUser(userID, currentPassword, newPassword string) *model.AppError UpdatePasswordByUserIdSendEmail(userID, newPassword, method string) *model.AppError @@ -1110,17 +1110,17 @@ type AppIface interface { UpdateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) UpdateSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error) UpdateSharedChannelRemoteCursor(id string, cursor model.GetPostsSinceForSyncCursor) error - UpdateSidebarCategories(userID, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) - UpdateSidebarCategoryOrder(userID, teamID string, categoryOrder []string) *model.AppError + UpdateSidebarCategories(c request.CTX, userID, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) + UpdateSidebarCategoryOrder(c request.CTX, userID, teamID string, categoryOrder []string) *model.AppError UpdateTeam(team *model.Team) (*model.Team, *model.AppError) UpdateTeamMemberRoles(teamID string, userID string, newRoles string) (*model.TeamMember, *model.AppError) UpdateTeamMemberSchemeRoles(teamID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.TeamMember, *model.AppError) UpdateTeamPrivacy(teamID string, teamType string, allowOpenInvite bool) *model.AppError UpdateTeamScheme(team *model.Team) (*model.Team, *model.AppError) UpdateThreadFollowForUser(userID, teamID, threadID string, state bool) *model.AppError - UpdateThreadFollowForUserFromChannelAdd(userID, teamID, threadID string) *model.AppError - UpdateThreadReadForUser(currentSessionId, userID, teamID, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError) - UpdateThreadReadForUserByPost(currentSessionId, userID, teamID, threadID, postID string) (*model.ThreadResponse, *model.AppError) + UpdateThreadFollowForUserFromChannelAdd(c request.CTX, userID, teamID, threadID string) *model.AppError + UpdateThreadReadForUser(c request.CTX, currentSessionId, userID, teamID, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError) + UpdateThreadReadForUserByPost(c request.CTX, currentSessionId, userID, teamID, threadID, postID string) (*model.ThreadResponse, *model.AppError) UpdateThreadsReadForUser(userID, teamID string) *model.AppError UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) UpdateUserActive(c *request.Context, userID string, active bool) *model.AppError @@ -1137,6 +1137,6 @@ type AppIface interface { UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError VerifyUserEmail(userID, email string) *model.AppError - ViewChannel(view *model.ChannelView, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) + ViewChannel(c request.CTX, view *model.ChannelView, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) WriteFile(fr io.Reader, path string) (int64, *model.AppError) } diff --git a/app/authorization.go b/app/authorization.go index 96607a7b74..ee161ddbee 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -4,12 +4,12 @@ package app import ( - "context" "database/sql" "errors" "net/http" "strings" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/mlog" ) @@ -58,7 +58,7 @@ func (a *App) SessionHasPermissionToTeam(session model.Session, teamID string, p } // SessionHasPermissionToTeams returns true only if user has access to all teams. -func (a *App) SessionHasPermissionToTeams(session model.Session, teamIDs []string, permission *model.Permission) bool { +func (a *App) SessionHasPermissionToTeams(c request.CTX, session model.Session, teamIDs []string, permission *model.Permission) bool { for _, teamID := range teamIDs { if teamID == "" { return false @@ -91,7 +91,7 @@ func (a *App) SessionHasPermissionToTeams(session model.Session, teamIDs []strin return a.RolesGrantPermission(session.GetUserRoles(), permission.Id) } -func (a *App) SessionHasPermissionToChannel(session model.Session, channelID string, permission *model.Permission) bool { +func (a *App) SessionHasPermissionToChannel(c request.CTX, session model.Session, channelID string, permission *model.Permission) bool { if channelID == "" { return false } @@ -108,7 +108,7 @@ func (a *App) SessionHasPermissionToChannel(session model.Session, channelID str } } - channel, appErr := a.GetChannel(channelID) + channel, appErr := a.GetChannel(c, channelID) if appErr != nil && appErr.StatusCode == http.StatusNotFound { return false } @@ -125,7 +125,7 @@ func (a *App) SessionHasPermissionToChannel(session model.Session, channelID str } // SessionHasPermissionToChannels returns true only if user has access to all channels. -func (a *App) SessionHasPermissionToChannels(session model.Session, channelIDs []string, permission *model.Permission) bool { +func (a *App) SessionHasPermissionToChannels(c request.CTX, session model.Session, channelIDs []string, permission *model.Permission) bool { for _, channelID := range channelIDs { if channelID == "" { return false @@ -158,7 +158,7 @@ func (a *App) SessionHasPermissionToChannels(session model.Session, channelIDs [ return true } - channels, appErr := a.GetChannels(channelIDs) + channels, appErr := a.GetChannels(c, channelIDs) if appErr != nil && appErr.StatusCode == http.StatusNotFound { return false } @@ -177,7 +177,7 @@ func (a *App) SessionHasPermissionToChannels(session model.Session, channelIDs [ } if appErr == nil && len(teamIDs) > 0 { - return a.SessionHasPermissionToTeams(session, teamIDs, permission) + return a.SessionHasPermissionToTeams(c, session, teamIDs, permission) } return a.SessionHasPermissionTo(session, permission) @@ -219,11 +219,11 @@ func (a *App) SessionHasPermissionToChannelByPost(session model.Session, postID return a.SessionHasPermissionTo(session, permission) } -func (a *App) SessionHasPermissionToCategory(session model.Session, userID, teamID, categoryId string) bool { +func (a *App) SessionHasPermissionToCategory(c request.CTX, session model.Session, userID, teamID, categoryId string) bool { if a.SessionHasPermissionTo(session, model.PermissionEditOtherUsers) { return true } - category, err := a.GetSidebarCategory(categoryId) + category, err := a.GetSidebarCategory(c, categoryId) return err == nil && category != nil && category.UserId == session.UserId && category.UserId == userID && category.TeamId == teamID } @@ -285,12 +285,12 @@ func (a *App) HasPermissionToTeam(askingUserId string, teamID string, permission return a.HasPermissionTo(askingUserId, permission) } -func (a *App) HasPermissionToChannel(askingUserId string, channelID string, permission *model.Permission) bool { +func (a *App) HasPermissionToChannel(c request.CTX, askingUserId string, channelID string, permission *model.Permission) bool { if channelID == "" || askingUserId == "" { return false } - channelMember, err := a.GetChannelMember(context.Background(), channelID, askingUserId) + channelMember, err := a.GetChannelMember(c, channelID, askingUserId) if err == nil { roles := channelMember.GetRoles() if a.RolesGrantPermission(roles, permission.Id) { @@ -299,7 +299,7 @@ func (a *App) HasPermissionToChannel(askingUserId string, channelID string, perm } var channel *model.Channel - channel, err = a.GetChannel(channelID) + channel, err = a.GetChannel(c, channelID) if err == nil { return a.HasPermissionToTeam(askingUserId, channel.TeamId, permission) } @@ -393,6 +393,6 @@ func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId s return nil } -func (a *App) HasPermissionToReadChannel(userID string, channel *model.Channel) bool { - return a.HasPermissionToChannel(userID, channel.Id, model.PermissionReadChannel) || (channel.Type == model.ChannelTypeOpen && a.HasPermissionToTeam(userID, channel.TeamId, model.PermissionReadPublicChannel)) +func (a *App) HasPermissionToReadChannel(c request.CTX, userID string, channel *model.Channel) bool { + return a.HasPermissionToChannel(c, userID, channel.Id, model.PermissionReadChannel) || (channel.Type == model.ChannelTypeOpen && a.HasPermissionToTeam(userID, channel.TeamId, model.PermissionReadPublicChannel)) } diff --git a/app/authorization_test.go b/app/authorization_test.go index c93aaa2529..c115fa8e64 100644 --- a/app/authorization_test.go +++ b/app/authorization_test.go @@ -78,7 +78,7 @@ func TestSessionHasPermissionToChannel(t *testing.T) { } t.Run("basic user can access basic channel", func(t *testing.T) { - assert.True(t, th.App.SessionHasPermissionToChannel(session, th.BasicChannel.Id, model.PermissionAddReaction)) + assert.True(t, th.App.SessionHasPermissionToChannel(th.Context, session, th.BasicChannel.Id, model.PermissionAddReaction)) }) t.Run("does not panic if fetching channel causes an error", func(t *testing.T) { @@ -103,7 +103,7 @@ func TestSessionHasPermissionToChannel(t *testing.T) { // If there's an error returned from the GetChannel call the code should continue to cascade and since there // are no session level permissions in this test case, the permission should be denied. - assert.False(t, th.App.SessionHasPermissionToChannel(session, th.BasicUser.Id, model.PermissionAddReaction)) + assert.False(t, th.App.SessionHasPermissionToChannel(th.Context, session, th.BasicUser.Id, model.PermissionAddReaction)) }) } @@ -113,16 +113,16 @@ func TestHasPermissionToCategory(t *testing.T) { session, err := th.App.CreateSession(&model.Session{UserId: th.BasicUser.Id, Props: model.StringMap{}}) require.Nil(t, err) - categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id) + categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.Context, th.BasicUser.Id, th.BasicTeam.Id) require.Nil(t, err) _, err = th.App.GetSession(session.Token) require.Nil(t, err) - require.True(t, th.App.SessionHasPermissionToCategory(*session, th.BasicUser.Id, th.BasicTeam.Id, categories.Order[0])) + require.True(t, th.App.SessionHasPermissionToCategory(th.Context, *session, th.BasicUser.Id, th.BasicTeam.Id, categories.Order[0])) - categories2, err := th.App.GetSidebarCategoriesForTeamForUser(th.BasicUser2.Id, th.BasicTeam.Id) + categories2, err := th.App.GetSidebarCategoriesForTeamForUser(th.Context, th.BasicUser2.Id, th.BasicTeam.Id) require.Nil(t, err) - require.False(t, th.App.SessionHasPermissionToCategory(*session, th.BasicUser.Id, th.BasicTeam.Id, categories2.Order[0])) + require.False(t, th.App.SessionHasPermissionToCategory(th.Context, *session, th.BasicUser.Id, th.BasicTeam.Id, categories2.Order[0])) } func TestSessionHasPermissionToGroup(t *testing.T) { diff --git a/app/auto_responder.go b/app/auto_responder.go index 0fd819cec4..90411ef419 100644 --- a/app/auto_responder.go +++ b/app/auto_responder.go @@ -21,7 +21,7 @@ func (a *App) checkIfRespondedToday(createdAt int64, channelId, userId string) ( ) } -func (a *App) SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { +func (a *App) SendAutoResponseIfNecessary(c request.CTX, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { if channel.Type != model.ChannelTypeDirect { return false, nil } @@ -52,7 +52,7 @@ func (a *App) SendAutoResponseIfNecessary(c *request.Context, channel *model.Cha return a.SendAutoResponse(c, channel, receiver, post) } -func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { +func (a *App) SendAutoResponse(c request.CTX, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { if receiver == nil || receiver.NotifyProps == nil { return false, nil } diff --git a/app/channel.go b/app/channel.go index 59b1aa05b4..80fcb9c978 100644 --- a/app/channel.go +++ b/app/channel.go @@ -26,22 +26,22 @@ type channelsWrapper struct { srv *Server } -func (s *channelsWrapper) GetDirectChannel(userID1, userID2 string) (*model.Channel, *model.AppError) { - return s.srv.getDirectChannel(userID1, userID2) +func (s *channelsWrapper) GetDirectChannel(c request.CTX, userID1, userID2 string) (*model.Channel, *model.AppError) { + return s.srv.getDirectChannel(c, userID1, userID2) } // GetChannelByID gets a Channel by its ID. -func (s *channelsWrapper) GetChannelByID(channelID string) (*model.Channel, *model.AppError) { - return s.srv.getChannel(channelID) +func (s *channelsWrapper) GetChannelByID(c request.CTX, channelID string) (*model.Channel, *model.AppError) { + return s.srv.getChannel(c, channelID) } // GetChannelMember gets a channel member by userID. -func (s *channelsWrapper) GetChannelMember(channelID string, userID string) (*model.ChannelMember, *model.AppError) { - return s.srv.getChannelMember(context.Background(), channelID, userID) +func (s *channelsWrapper) GetChannelMember(c request.CTX, channelID string, userID string) (*model.ChannelMember, *model.AppError) { + return s.srv.getChannelMember(c, channelID, userID) } -func (s *channelsWrapper) GetChannelsForTeamForUser(teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { - return s.srv.getChannelsForTeamForUser(teamID, userID, opts) +func (s *channelsWrapper) GetChannelsForTeamForUser(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { + return s.srv.getChannelsForTeamForUser(c, teamID, userID, opts) } // DefaultChannelNames returns the list of system-wide default channel names. @@ -52,7 +52,7 @@ func (s *channelsWrapper) GetChannelsForTeamForUser(teamID string, userID string // 'off-topic' and be included in the return results in addition to 'town-square'. For example: // ['town-square', 'game-of-thrones', 'wow'] // -func (a *App) DefaultChannelNames() []string { +func (a *App) DefaultChannelNames(c request.CTX) []string { names := []string{"town-square"} if len(a.Config().TeamSettings.ExperimentalDefaultChannels) == 0 { @@ -70,7 +70,7 @@ func (a *App) DefaultChannelNames() []string { return names } -func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { +func (a *App) JoinDefaultChannels(c request.CTX, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { var requestor *model.User var nErr error if userRequestorId != "" { @@ -87,7 +87,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model } var err *model.AppError - for _, channelName := range a.DefaultChannelNames() { + for _, channelName := range a.DefaultChannelNames(c) { channel, channelErr := a.Srv().Store.Channel().GetByName(teamID, channelName, true) if channelErr != nil { var nfErr *store.ErrNotFound @@ -120,7 +120,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages { if aErr := a.postJoinMessageForDefaultChannel(c, user, requestor, channel); aErr != nil { - mlog.Warn("Failed to post join/leave message", mlog.Err(aErr)) + c.Logger().Warn("Failed to post join/leave message", mlog.Err(aErr)) } } @@ -150,7 +150,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model return nil } -func (a *App) postJoinMessageForDefaultChannel(c *request.Context, user *model.User, requestor *model.User, channel *model.Channel) *model.AppError { +func (a *App) postJoinMessageForDefaultChannel(c request.CTX, user *model.User, requestor *model.User, channel *model.Channel) *model.AppError { if channel.Name == model.DefaultChannelName { if requestor == nil { if err := a.postJoinTeamMessage(c, user, channel); err != nil { @@ -176,7 +176,7 @@ func (a *App) postJoinMessageForDefaultChannel(c *request.Context, user *model.U return nil } -func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *App) CreateChannelWithUser(c request.CTX, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { if channel.IsGroupOrDirect() { return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.direct_channel.app_error", nil, "", http.StatusBadRequest) } @@ -186,7 +186,7 @@ func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, } // Get total number of channels on current team - count, err := a.GetNumberOfChannelsOnTeam(channel.TeamId) + count, err := a.GetNumberOfChannelsOnTeam(c, channel.TeamId) if err != nil { return nil, err } @@ -218,7 +218,7 @@ func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, } // RenameChannel is used to rename the channel Name and the DisplayName fields -func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) { +func (a *App) RenameChannel(c request.CTX, channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) { if channel.Type == model.ChannelTypeDirect { return nil, model.NewAppError("RenameChannel", "api.channel.rename_channel.cant_rename_direct_messages.app_error", nil, "", http.StatusBadRequest) } @@ -232,7 +232,7 @@ func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDi channel.DisplayName = newDisplayName } - newChannel, err := a.UpdateChannel(channel) + newChannel, err := a.UpdateChannel(c, channel) if err != nil { return nil, err } @@ -240,7 +240,7 @@ func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDi return newChannel, nil } -func (a *App) CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { +func (a *App) CreateChannel(c request.CTX, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { channel.DisplayName = strings.TrimSpace(channel.DisplayName) sc, nErr := a.Srv().Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) if nErr != nil { @@ -326,8 +326,8 @@ func (a *App) CreateChannel(c *request.Context, channel *model.Channel, addMembe return sc, nil } -func (a *App) GetOrCreateDirectChannel(c *request.Context, userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { - channel, nErr := a.getDirectChannel(userID, otherUserID) +func (a *App) GetOrCreateDirectChannel(c request.CTX, userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { + channel, nErr := a.getDirectChannel(c, userID, otherUserID) if nErr != nil { return nil, nErr } @@ -361,7 +361,7 @@ func (a *App) GetOrCreateDirectChannel(c *request.Context, userID, otherUserID s } } - channel, err := a.createDirectChannel(userID, otherUserID, channelOptions...) + channel, err := a.createDirectChannel(c, userID, otherUserID, channelOptions...) if err != nil { if err.Id == store.ChannelExistsError { return channel, nil @@ -373,8 +373,8 @@ func (a *App) GetOrCreateDirectChannel(c *request.Context, userID, otherUserID s return channel, nil } -func (a *App) getOrCreateDirectChannelWithUser(c *request.Context, user, otherUser *model.User) (*model.Channel, *model.AppError) { - channel, nErr := a.getDirectChannel(user.Id, otherUser.Id) +func (a *App) getOrCreateDirectChannelWithUser(c request.CTX, user, otherUser *model.User) (*model.Channel, *model.AppError) { + channel, nErr := a.getDirectChannel(c, user.Id, otherUser.Id) if nErr != nil { return nil, nErr } @@ -383,7 +383,7 @@ func (a *App) getOrCreateDirectChannelWithUser(c *request.Context, user, otherUs return channel, nil } - channel, err := a.createDirectChannelWithUser(user, otherUser) + channel, err := a.createDirectChannelWithUser(c, user, otherUser) if err != nil { if err.Id == store.ChannelExistsError { return channel, nil @@ -395,7 +395,7 @@ func (a *App) getOrCreateDirectChannelWithUser(c *request.Context, user, otherUs return channel, nil } -func (a *App) handleCreationEvent(c *request.Context, userID, otherUserID string, channel *model.Channel) { +func (a *App) handleCreationEvent(c request.CTX, userID, otherUserID string, channel *model.Channel) { a.InvalidateCacheForUser(userID) a.InvalidateCacheForUser(otherUserID) @@ -415,7 +415,7 @@ func (a *App) handleCreationEvent(c *request.Context, userID, otherUserID string a.Publish(message) } -func (a *App) createDirectChannel(userID string, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { +func (a *App) createDirectChannel(c request.CTX, userID string, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { users, err := a.Srv().Store.User().GetMany(context.Background(), []string{userID, otherUserID}) if err != nil { return nil, model.NewAppError("CreateDirectChannel", "api.channel.create_direct_channel.invalid_user.app_error", nil, err.Error(), http.StatusBadRequest) @@ -445,10 +445,10 @@ func (a *App) createDirectChannel(userID string, otherUserID string, channelOpti user = users[1] otherUser = users[0] } - return a.createDirectChannelWithUser(user, otherUser, channelOptions...) + return a.createDirectChannelWithUser(c, user, otherUser, channelOptions...) } -func (a *App) createDirectChannelWithUser(user, otherUser *model.User, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { +func (a *App) createDirectChannelWithUser(c request.CTX, user, otherUser *model.User, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { channel, nErr := a.Srv().Store.Channel().CreateDirectChannel(user, otherUser, channelOptions...) if nErr != nil { var invErr *store.ErrInvalidInput @@ -506,7 +506,7 @@ func (a *App) createDirectChannelWithUser(user, otherUser *model.User, channelOp Type: channel.Type, } - if _, err := a.SaveSharedChannel(sc); err != nil { + if _, err := a.SaveSharedChannel(c, sc); err != nil { return nil, model.NewAppError("CreateDirectChannel", "app.sharedchannel.dm_channel_creation.internal_error", nil, err.Error(), http.StatusInternalServerError) } } @@ -514,8 +514,8 @@ func (a *App) createDirectChannelWithUser(user, otherUser *model.User, channelOp return channel, nil } -func (a *App) CreateGroupChannel(userIDs []string, creatorId string) (*model.Channel, *model.AppError) { - channel, err := a.createGroupChannel(userIDs) +func (a *App) CreateGroupChannel(c request.CTX, userIDs []string, creatorId string) (*model.Channel, *model.AppError) { + channel, err := a.createGroupChannel(c, userIDs) if err != nil { if err.Id == store.ChannelExistsError { return channel, nil @@ -534,7 +534,7 @@ func (a *App) CreateGroupChannel(userIDs []string, creatorId string) (*model.Cha return channel, nil } -func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppError) { +func (a *App) createGroupChannel(c request.CTX, userIDs []string) (*model.Channel, *model.AppError) { if len(userIDs) > model.ChannelGroupMaxUsers || len(userIDs) < model.ChannelGroupMinUsers { return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } @@ -613,7 +613,7 @@ func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppEr return channel, nil } -func (a *App) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) { +func (a *App) GetGroupChannel(c request.CTX, userIDs []string) (*model.Channel, *model.AppError) { if len(userIDs) > model.ChannelGroupMaxUsers || len(userIDs) < model.ChannelGroupMinUsers { return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } @@ -627,7 +627,7 @@ func (a *App) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_user.app_error", nil, "user_ids="+model.ArrayToJSON(userIDs), http.StatusBadRequest) } - channel, appErr := a.GetChannelByName(model.GetGroupNameFromUserIds(userIDs), "", true) + channel, appErr := a.GetChannelByName(c, model.GetGroupNameFromUserIds(userIDs), "", true) if appErr != nil { return nil, appErr } @@ -636,7 +636,7 @@ func (a *App) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError } // UpdateChannel updates a given channel by its Id. It also publishes the CHANNEL_UPDATED event. -func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) { +func (a *App) UpdateChannel(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) { _, err := a.Srv().Store.Channel().Update(channel) if err != nil { var appErr *model.AppError @@ -656,7 +656,7 @@ func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppE messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelUpdated, "", channel.Id, "", nil) channelJSON, jsonErr := json.Marshal(channel) if jsonErr != nil { - mlog.Warn("Failed to encode channel to JSON", mlog.Err(jsonErr)) + c.Logger().Warn("Failed to encode channel to JSON", mlog.Err(jsonErr)) } messageWs.Add("channel", string(channelJSON)) a.Publish(messageWs) @@ -665,7 +665,7 @@ func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppE } // CreateChannelScheme creates a new Scheme of scope channel and assigns it to the channel. -func (a *App) CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model.AppError) { +func (a *App) CreateChannelScheme(c request.CTX, channel *model.Channel) (*model.Scheme, *model.AppError) { scheme, err := a.CreateScheme(&model.Scheme{ Name: model.NewId(), DisplayName: model.NewId(), @@ -676,37 +676,37 @@ func (a *App) CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model } channel.SchemeId = &scheme.Id - if _, err := a.UpdateChannelScheme(channel); err != nil { + if _, err := a.UpdateChannelScheme(c, channel); err != nil { return nil, err } return scheme, nil } // DeleteChannelScheme deletes a channels scheme and sets its SchemeId to nil. -func (a *App) DeleteChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) { +func (a *App) DeleteChannelScheme(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) { if channel.SchemeId != nil && *channel.SchemeId != "" { if _, err := a.DeleteScheme(*channel.SchemeId); err != nil { return nil, err } } channel.SchemeId = nil - return a.UpdateChannelScheme(channel) + return a.UpdateChannelScheme(c, channel) } // UpdateChannelScheme saves the new SchemeId of the channel passed. -func (a *App) UpdateChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) { +func (a *App) UpdateChannelScheme(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) { var oldChannel *model.Channel var err *model.AppError - if oldChannel, err = a.GetChannel(channel.Id); err != nil { + if oldChannel, err = a.GetChannel(c, channel.Id); err != nil { return nil, err } oldChannel.SchemeId = channel.SchemeId - return a.UpdateChannel(oldChannel) + return a.UpdateChannel(c, oldChannel) } -func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { - channel, err := a.UpdateChannel(oldChannel) +func (a *App) UpdateChannelPrivacy(c request.CTX, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { + channel, err := a.UpdateChannel(c, oldChannel) if err != nil { return channel, err } @@ -718,7 +718,7 @@ func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel channel.Type = model.ChannelTypeOpen } // revert to previous channel privacy - a.UpdateChannel(channel) + a.UpdateChannel(c, channel) return channel, err } @@ -731,7 +731,7 @@ func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel return channel, nil } -func (a *App) postChannelPrivacyMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postChannelPrivacyMessage(c request.CTX, user *model.User, channel *model.Channel) *model.AppError { var authorId string var authorUsername string if user != nil { @@ -768,7 +768,7 @@ func (a *App) postChannelPrivacyMessage(c *request.Context, user *model.User, ch return nil } -func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *App) RestoreChannel(c request.CTX, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { if channel.DeleteAt == 0 { return nil, model.NewAppError("restoreChannel", "api.channel.restore_channel.restored.app_error", nil, "", http.StatusBadRequest) } @@ -812,13 +812,13 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID } if _, err := a.CreatePost(c, post, channel, false, true); err != nil { - mlog.Warn("Failed to post unarchive message", mlog.Err(err)) + c.Logger().Warn("Failed to post unarchive message", mlog.Err(err)) } } else { a.Srv().Go(func() { systemBot, err := a.GetSystemBot() if err != nil { - mlog.Error("Failed to post unarchive message", mlog.Err(err)) + c.Logger().Error("Failed to post unarchive message", mlog.Err(err)) return } @@ -833,7 +833,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID } if _, err := a.CreatePost(c, post, channel, false, true); err != nil { - mlog.Error("Failed to post unarchive message", mlog.Err(err)) + c.Logger().Error("Failed to post unarchive message", mlog.Err(err)) } }) } @@ -841,32 +841,32 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID return channel, nil } -func (a *App) PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { +func (a *App) PatchChannel(c request.CTX, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { oldChannelDisplayName := channel.DisplayName oldChannelHeader := channel.Header oldChannelPurpose := channel.Purpose channel.Patch(patch) - channel, err := a.UpdateChannel(channel) + channel, err := a.UpdateChannel(c, channel) if err != nil { return nil, err } if oldChannelDisplayName != channel.DisplayName { if err = a.PostUpdateChannelDisplayNameMessage(c, userID, channel, oldChannelDisplayName, channel.DisplayName); err != nil { - mlog.Warn(err.Error()) + c.Logger().Warn(err.Error()) } } if channel.Header != oldChannelHeader { if err = a.PostUpdateChannelHeaderMessage(c, userID, channel, oldChannelHeader, channel.Header); err != nil { - mlog.Warn(err.Error()) + c.Logger().Warn(err.Error()) } } if channel.Purpose != oldChannelPurpose { if err = a.PostUpdateChannelPurposeMessage(c, userID, channel, oldChannelPurpose, channel.Purpose); err != nil { - mlog.Warn(err.Error()) + c.Logger().Warn(err.Error()) } } @@ -874,8 +874,8 @@ func (a *App) PatchChannel(c *request.Context, channel *model.Channel, patch *mo } // GetSchemeRolesForChannel Checks if a channel or its team has an override scheme for channel roles and returns the scheme roles or default channel roles. -func (a *App) GetSchemeRolesForChannel(channelID string) (guestRoleName, userRoleName, adminRoleName string, err *model.AppError) { - channel, err := a.GetChannel(channelID) +func (a *App) GetSchemeRolesForChannel(c request.CTX, channelID string) (guestRoleName, userRoleName, adminRoleName string, err *model.AppError) { + channel, err := a.GetChannel(c, channelID) if err != nil { return } @@ -894,11 +894,11 @@ func (a *App) GetSchemeRolesForChannel(channelID string) (guestRoleName, userRol return } - return a.GetTeamSchemeChannelRoles(channel.TeamId) + return a.GetTeamSchemeChannelRoles(c, channel.TeamId) } // GetTeamSchemeChannelRoles Checks if a team has an override scheme and returns the scheme channel role names or default channel role names. -func (a *App) GetTeamSchemeChannelRoles(teamID string) (guestRoleName, userRoleName, adminRoleName string, err *model.AppError) { +func (a *App) GetTeamSchemeChannelRoles(c request.CTX, teamID string) (guestRoleName, userRoleName, adminRoleName string, err *model.AppError) { team, err := a.GetTeam(teamID) if err != nil { return @@ -924,8 +924,8 @@ func (a *App) GetTeamSchemeChannelRoles(teamID string) (guestRoleName, userRoleN } // GetChannelModerationsForChannel Gets a channels ChannelModerations from either the higherScoped roles or from the channel scheme roles. -func (a *App) GetChannelModerationsForChannel(channel *model.Channel) ([]*model.ChannelModeration, *model.AppError) { - guestRoleName, memberRoleName, _, err := a.GetSchemeRolesForChannel(channel.Id) +func (a *App) GetChannelModerationsForChannel(c request.CTX, channel *model.Channel) ([]*model.ChannelModeration, *model.AppError) { + guestRoleName, memberRoleName, _, err := a.GetSchemeRolesForChannel(c, channel.Id) if err != nil { return nil, err } @@ -943,7 +943,7 @@ func (a *App) GetChannelModerationsForChannel(channel *model.Channel) ([]*model. } } - higherScopedGuestRoleName, higherScopedMemberRoleName, _, err := a.GetTeamSchemeChannelRoles(channel.TeamId) + higherScopedGuestRoleName, higherScopedMemberRoleName, _, err := a.GetTeamSchemeChannelRoles(c, channel.TeamId) if err != nil { return nil, err } @@ -960,12 +960,12 @@ func (a *App) GetChannelModerationsForChannel(channel *model.Channel) ([]*model. } } - return buildChannelModerations(channel.Type, memberRole, guestRole, higherScopedMemberRole, higherScopedGuestRole), nil + return buildChannelModerations(c, channel.Type, memberRole, guestRole, higherScopedMemberRole, higherScopedGuestRole), nil } // PatchChannelModerationsForChannel Updates a channels scheme roles based on a given ChannelModerationPatch, if the permissions match the higher scoped role the scheme is deleted. -func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) { - higherScopedGuestRoleName, higherScopedMemberRoleName, _, err := a.GetTeamSchemeChannelRoles(channel.TeamId) +func (a *App) PatchChannelModerationsForChannel(c request.CTX, channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) { + higherScopedGuestRoleName, higherScopedMemberRoleName, _, err := a.GetTeamSchemeChannelRoles(c, channel.TeamId) if err != nil { return nil, err } @@ -1003,7 +1003,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM var scheme *model.Scheme // Channel has no scheme so create one if channel.SchemeId == nil || *channel.SchemeId == "" { - scheme, err = a.CreateChannelScheme(channel) + scheme, err = a.CreateChannelScheme(c, channel) if err != nil { return nil, err } @@ -1018,7 +1018,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM message := model.NewWebSocketEvent(model.WebsocketEventChannelSchemeUpdated, "", channel.Id, "", nil) a.Publish(message) - mlog.Info("Permission scheme created.", mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) + c.Logger().Info("Permission scheme created.", mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) } else { scheme, err = a.GetScheme(*channel.SchemeId) if err != nil { @@ -1051,17 +1051,17 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM permissionModified := *channelModerationPatch.Name if channelModerationPatch.Roles.Guests != nil && utils.StringInSlice(permissionModified, model.ChannelModeratedPermissionsChangedByPatch(guestRole, guestRolePatch)) { if *channelModerationPatch.Roles.Guests { - mlog.Info("Permission enabled for guests.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) + c.Logger().Info("Permission enabled for guests.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) } else { - mlog.Info("Permission disabled for guests.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) + c.Logger().Info("Permission disabled for guests.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) } } if channelModerationPatch.Roles.Members != nil && utils.StringInSlice(permissionModified, model.ChannelModeratedPermissionsChangedByPatch(memberRole, memberRolePatch)) { if *channelModerationPatch.Roles.Members { - mlog.Info("Permission enabled for members.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) + c.Logger().Info("Permission enabled for members.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) } else { - mlog.Info("Permission disabled for members.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) + c.Logger().Info("Permission disabled for members.", mlog.String("permission", permissionModified), mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) } } } @@ -1070,7 +1070,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM guestRolePermissionsUnmodified := len(model.ChannelModeratedPermissionsChangedByPatch(higherScopedGuestRole, guestRolePatch)) == 0 if memberRolePermissionsUnmodified && guestRolePermissionsUnmodified { // The channel scheme matches the permissions of its higherScoped scheme so delete the scheme - if _, err = a.DeleteChannelScheme(channel); err != nil { + if _, err = a.DeleteChannelScheme(c, channel); err != nil { return nil, err } @@ -1079,7 +1079,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM memberRole = higherScopedMemberRole guestRole = higherScopedGuestRole - mlog.Info("Permission scheme deleted.", mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) + c.Logger().Info("Permission scheme deleted.", mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name)) } else { memberRole, err = a.PatchRole(memberRole, memberRolePatch) if err != nil { @@ -1091,7 +1091,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM } } - cErr := a.forEachChannelMember(channel.Id, func(channelMember model.ChannelMember) error { + cErr := a.forEachChannelMember(c, channel.Id, func(channelMember model.ChannelMember) error { a.Srv().Store.Channel().InvalidateAllChannelMembersForUser(channelMember.UserId) return nil }) @@ -1099,10 +1099,10 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM return nil, model.NewAppError("PatchChannelModerationsForChannel", "api.channel.patch_channel_moderations.cache_invalidation.error", nil, cErr.Error(), http.StatusInternalServerError) } - return buildChannelModerations(channel.Type, memberRole, guestRole, higherScopedMemberRole, higherScopedGuestRole), nil + return buildChannelModerations(c, channel.Type, memberRole, guestRole, higherScopedMemberRole, higherScopedGuestRole), nil } -func buildChannelModerations(channelType model.ChannelType, memberRole *model.Role, guestRole *model.Role, higherScopedMemberRole *model.Role, higherScopedGuestRole *model.Role) []*model.ChannelModeration { +func buildChannelModerations(c request.CTX, channelType model.ChannelType, memberRole *model.Role, guestRole *model.Role, higherScopedMemberRole *model.Role, higherScopedGuestRole *model.Role) []*model.ChannelModeration { var memberPermissions, guestPermissions, higherScopedMemberPermissions, higherScopedGuestPermissions map[string]bool if memberRole != nil { memberPermissions = memberRole.GetChannelModeratedPermissions(channelType) @@ -1146,14 +1146,14 @@ func buildChannelModerations(channelType model.ChannelType, memberRole *model.Ro return channelModerations } -func (a *App) UpdateChannelMemberRoles(channelID string, userID string, newRoles string) (*model.ChannelMember, *model.AppError) { +func (a *App) UpdateChannelMemberRoles(c request.CTX, channelID string, userID string, newRoles string) (*model.ChannelMember, *model.AppError) { var member *model.ChannelMember var err *model.AppError - if member, err = a.GetChannelMember(context.Background(), channelID, userID); err != nil { + if member, err = a.GetChannelMember(c, channelID, userID); err != nil { return nil, err } - schemeGuestRole, schemeUserRole, schemeAdminRole, err := a.GetSchemeRolesForChannel(channelID) + schemeGuestRole, schemeUserRole, schemeAdminRole, err := a.GetSchemeRolesForChannel(c, channelID) if err != nil { return nil, err } @@ -1202,11 +1202,11 @@ func (a *App) UpdateChannelMemberRoles(channelID string, userID string, newRoles member.ExplicitRoles = strings.Join(newExplicitRoles, " ") - return a.updateChannelMember(member) + return a.updateChannelMember(c, member) } -func (a *App) UpdateChannelMemberSchemeRoles(channelID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError) { - member, err := a.GetChannelMember(context.Background(), channelID, userID) +func (a *App) UpdateChannelMemberSchemeRoles(c request.CTX, channelID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError) { + member, err := a.GetChannelMember(c, channelID, userID) if err != nil { return nil, err } @@ -1224,10 +1224,10 @@ func (a *App) UpdateChannelMemberSchemeRoles(channelID string, userID string, is member.ExplicitRoles = RemoveRoles([]string{model.ChannelGuestRoleId, model.ChannelUserRoleId, model.ChannelAdminRoleId}, member.ExplicitRoles) } - return a.updateChannelMember(member) + return a.updateChannelMember(c, member) } -func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelID string, userID string) (*model.ChannelMember, *model.AppError) { +func (a *App) UpdateChannelMemberNotifyProps(c request.CTX, data map[string]string, channelID string, userID string) (*model.ChannelMember, *model.AppError) { filteredProps := make(map[string]string) // update whichever notify properties have been provided, but don't change the others @@ -1280,7 +1280,7 @@ func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelID s evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil) memberJSON, jsonErr := json.Marshal(member) if jsonErr != nil { - mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) + c.Logger().Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) } evt.Add("channelMember", string(memberJSON)) a.Publish(evt) @@ -1288,7 +1288,7 @@ func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelID s return member, nil } -func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMember, *model.AppError) { +func (a *App) updateChannelMember(c request.CTX, member *model.ChannelMember) (*model.ChannelMember, *model.AppError) { member, nErr := a.Srv().Store.Channel().UpdateMember(member) if nErr != nil { var appErr *model.AppError @@ -1309,7 +1309,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil) memberJSON, jsonErr := json.Marshal(member) if jsonErr != nil { - mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) + c.Logger().Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) } evt.Add("channelMember", string(memberJSON)) a.Publish(evt) @@ -1317,7 +1317,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe return member, nil } -func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { +func (a *App) DeleteChannel(c request.CTX, channel *model.Channel, userID string) *model.AppError { ihc := make(chan store.StoreResult, 1) ohc := make(chan store.StoreResult, 1) @@ -1385,13 +1385,13 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s } if _, err := a.CreatePost(c, post, channel, false, true); err != nil { - mlog.Warn("Failed to post archive message", mlog.Err(err)) + c.Logger().Warn("Failed to post archive message", mlog.Err(err)) } } else { a.Srv().Go(func() { systemBot, err := a.GetSystemBot() if err != nil { - mlog.Error("Failed to post archive message", mlog.Err(err)) + c.Logger().Error("Failed to post archive message", mlog.Err(err)) return } @@ -1406,7 +1406,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s } if _, err := a.CreatePost(c, post, channel, false, true); err != nil { - mlog.Error("Failed to post archive message", mlog.Err(err)) + c.Logger().Error("Failed to post archive message", mlog.Err(err)) } }) } @@ -1414,14 +1414,14 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s now := model.GetMillis() for _, hook := range incomingHooks { if err := a.Srv().Store.Webhook().DeleteIncoming(hook.Id, now); err != nil { - mlog.Warn("Encountered error deleting incoming webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) + c.Logger().Warn("Encountered error deleting incoming webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) } a.invalidateCacheForWebhook(hook.Id) } for _, hook := range outgoingHooks { if err := a.Srv().Store.Webhook().DeleteOutgoing(hook.Id, now); err != nil { - mlog.Warn("Encountered error deleting outgoing webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) + c.Logger().Warn("Encountered error deleting outgoing webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) } } @@ -1440,7 +1440,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s return nil } -func (a *App) addUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) { +func (a *App) addUserToChannel(c request.CTX, user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) { if channel.Type != model.ChannelTypeOpen && channel.Type != model.ChannelTypePrivate { return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest) } @@ -1499,7 +1499,7 @@ func (a *App) addUserToChannel(user *model.User, channel *model.Channel) (*model } // AddUserToChannel adds a user to a given channel. -func (a *App) AddUserToChannel(user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) { +func (a *App) AddUserToChannel(c request.CTX, user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) { if !skipTeamMemberIntegrityCheck { teamMember, nErr := a.Srv().Store.Team().GetMember(context.Background(), channel.TeamId, user.Id) if nErr != nil { @@ -1517,7 +1517,7 @@ func (a *App) AddUserToChannel(user *model.User, channel *model.Channel, skipTea } } - newMember, err := a.addUserToChannel(user, channel) + newMember, err := a.addUserToChannel(c, user, channel) if err != nil { return nil, err } @@ -1541,7 +1541,7 @@ type ChannelMemberOpts struct { } // AddChannelMember adds a user to a channel. It is a wrapper over AddUserToChannel. -func (a *App) AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { +func (a *App) AddChannelMember(c request.CTX, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { if member, err := a.Srv().Store.Channel().GetMember(context.Background(), channel.Id, userID); err != nil { var nfErr *store.ErrNotFound if !errors.As(err, &nfErr) { @@ -1565,7 +1565,7 @@ func (a *App) AddChannelMember(c *request.Context, userID string, channel *model } } - cm, err := a.AddUserToChannel(user, channel, opts.SkipTeamMemberIntegrityCheck) + cm, err := a.AddUserToChannel(c, user, channel, opts.SkipTeamMemberIntegrityCheck) if err != nil { return nil, err } @@ -1593,7 +1593,7 @@ func (a *App) AddChannelMember(c *request.Context, userID string, channel *model return cm, nil } -func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError { +func (a *App) AddDirectChannels(c request.CTX, teamID string, user *model.User) *model.AppError { var profiles []*model.User options := &model.UserGetOptions{InTeamId: teamID, Page: 0, PerPage: 100} profiles, err := a.Srv().Store.User().GetProfiles(options) @@ -1629,7 +1629,7 @@ func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError return nil } -func (a *App) PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { +func (a *App) PostUpdateChannelHeaderMessage(c request.CTX, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { user, err := a.Srv().Store.User().Get(context.Background(), userID) if err != nil { return model.NewAppError("PostUpdateChannelHeaderMessage", "api.channel.post_update_channel_header_message_and_forget.retrieve_user.error", nil, err.Error(), http.StatusBadRequest) @@ -1663,7 +1663,7 @@ func (a *App) PostUpdateChannelHeaderMessage(c *request.Context, userID string, return nil } -func (a *App) PostUpdateChannelPurposeMessage(c *request.Context, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { +func (a *App) PostUpdateChannelPurposeMessage(c request.CTX, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { user, err := a.Srv().Store.User().Get(context.Background(), userID) if err != nil { return model.NewAppError("PostUpdateChannelPurposeMessage", "app.channel.post_update_channel_purpose_message.retrieve_user.error", nil, err.Error(), http.StatusBadRequest) @@ -1696,7 +1696,7 @@ func (a *App) PostUpdateChannelPurposeMessage(c *request.Context, userID string, return nil } -func (a *App) PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { +func (a *App) PostUpdateChannelDisplayNameMessage(c request.CTX, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { user, err := a.Srv().Store.User().Get(context.Background(), userID) if err != nil { return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.retrieve_user.error", nil, err.Error(), http.StatusBadRequest) @@ -1723,11 +1723,11 @@ func (a *App) PostUpdateChannelDisplayNameMessage(c *request.Context, userID str return nil } -func (a *App) GetChannel(channelID string) (*model.Channel, *model.AppError) { - return a.Srv().getChannel(channelID) +func (a *App) GetChannel(c request.CTX, channelID string) (*model.Channel, *model.AppError) { + return a.Srv().getChannel(c, channelID) } -func (s *Server) getChannel(channelID string) (*model.Channel, *model.AppError) { +func (s *Server) getChannel(c request.CTX, channelID string) (*model.Channel, *model.AppError) { channel, err := s.Store.Channel().Get(channelID, true) if err != nil { var nfErr *store.ErrNotFound @@ -1741,7 +1741,7 @@ func (s *Server) getChannel(channelID string) (*model.Channel, *model.AppError) return channel, nil } -func (a *App) GetChannels(channelIDs []string) ([]*model.Channel, *model.AppError) { +func (a *App) GetChannels(c request.CTX, channelIDs []string) ([]*model.Channel, *model.AppError) { channels, err := a.Srv().Store.Channel().GetMany(channelIDs, true) if err != nil { var nfErr *store.ErrNotFound @@ -1755,7 +1755,7 @@ func (a *App) GetChannels(channelIDs []string) ([]*model.Channel, *model.AppErro return channels, nil } -func (a *App) GetChannelByName(channelName, teamID string, includeDeleted bool) (*model.Channel, *model.AppError) { +func (a *App) GetChannelByName(c request.CTX, channelName, teamID string, includeDeleted bool) (*model.Channel, *model.AppError) { var channel *model.Channel var err error @@ -1778,7 +1778,7 @@ func (a *App) GetChannelByName(channelName, teamID string, includeDeleted bool) return channel, nil } -func (a *App) GetChannelsByNames(channelNames []string, teamID string) ([]*model.Channel, *model.AppError) { +func (a *App) GetChannelsByNames(c request.CTX, channelNames []string, teamID string) ([]*model.Channel, *model.AppError) { channels, err := a.Srv().Store.Channel().GetByNames(teamID, channelNames, true) if err != nil { return nil, model.NewAppError("GetChannelsByNames", "app.channel.get_by_name.existing.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -1786,7 +1786,7 @@ func (a *App) GetChannelsByNames(channelNames []string, teamID string) ([]*model return channels, nil } -func (a *App) GetChannelByNameForTeamName(channelName, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) { +func (a *App) GetChannelByNameForTeamName(c request.CTX, channelName, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) { var team *model.Team team, err := a.Srv().Store.Team().GetByName(teamName) @@ -1822,7 +1822,7 @@ func (a *App) GetChannelByNameForTeamName(channelName, teamName string, includeD return result, nil } -func (s *Server) getChannelsForTeamForUser(teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { +func (s *Server) getChannelsForTeamForUser(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { list, err := s.Store.Channel().GetChannels(teamID, userID, opts) if err != nil { var nfErr *store.ErrNotFound @@ -1837,11 +1837,11 @@ func (s *Server) getChannelsForTeamForUser(teamID string, userID string, opts *m return list, nil } -func (a *App) GetChannelsForTeamForUser(teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { - return a.Srv().getChannelsForTeamForUser(teamID, userID, opts) +func (a *App) GetChannelsForTeamForUser(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { + return a.Srv().getChannelsForTeamForUser(c, teamID, userID, opts) } -func (a *App) GetChannelsForTeamForUserWithCursor(teamID string, userID string, opts *model.ChannelSearchOpts, afterChannelID string) (model.ChannelList, *model.AppError) { +func (a *App) GetChannelsForTeamForUserWithCursor(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts, afterChannelID string) (model.ChannelList, *model.AppError) { list, err := a.Srv().Store.Channel().GetChannelsWithCursor(teamID, userID, opts, afterChannelID) if err != nil { var nfErr *store.ErrNotFound @@ -1856,7 +1856,7 @@ func (a *App) GetChannelsForTeamForUserWithCursor(teamID string, userID string, return list, nil } -func (a *App) GetChannelsForUser(userID string, includeDeleted bool, lastDeleteAt, pageSize int, fromChannelID string) (model.ChannelList, *model.AppError) { +func (a *App) GetChannelsForUser(c request.CTX, userID string, includeDeleted bool, lastDeleteAt, pageSize int, fromChannelID string) (model.ChannelList, *model.AppError) { list, err := a.Srv().Store.Channel().GetChannelsByUser(userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID) if err != nil { var nfErr *store.ErrNotFound @@ -1871,9 +1871,9 @@ func (a *App) GetChannelsForUser(userID string, includeDeleted bool, lastDeleteA return list, nil } -func (a *App) GetAllChannels(page, perPage int, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, *model.AppError) { +func (a *App) GetAllChannels(c request.CTX, page, perPage int, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, *model.AppError) { if opts.ExcludeDefaultChannels { - opts.ExcludeChannelNames = a.DefaultChannelNames() + opts.ExcludeChannelNames = a.DefaultChannelNames(c) } storeOpts := store.ChannelSearchOpts{ ExcludeChannelNames: opts.ExcludeChannelNames, @@ -1890,9 +1890,9 @@ func (a *App) GetAllChannels(page, perPage int, opts model.ChannelSearchOpts) (m return channels, nil } -func (a *App) GetAllChannelsCount(opts model.ChannelSearchOpts) (int64, *model.AppError) { +func (a *App) GetAllChannelsCount(c request.CTX, opts model.ChannelSearchOpts) (int64, *model.AppError) { if opts.ExcludeDefaultChannels { - opts.ExcludeChannelNames = a.DefaultChannelNames() + opts.ExcludeChannelNames = a.DefaultChannelNames(c) } storeOpts := store.ChannelSearchOpts{ ExcludeChannelNames: opts.ExcludeChannelNames, @@ -1907,7 +1907,7 @@ func (a *App) GetAllChannelsCount(opts model.ChannelSearchOpts) (int64, *model.A return count, nil } -func (a *App) GetDeletedChannels(teamID string, offset int, limit int, userID string) (model.ChannelList, *model.AppError) { +func (a *App) GetDeletedChannels(c request.CTX, teamID string, offset int, limit int, userID string) (model.ChannelList, *model.AppError) { list, err := a.Srv().Store.Channel().GetDeleted(teamID, offset, limit, userID) if err != nil { var nfErr *store.ErrNotFound @@ -1922,7 +1922,7 @@ func (a *App) GetDeletedChannels(teamID string, offset int, limit int, userID st return list, nil } -func (a *App) GetChannelsUserNotIn(teamID string, userID string, offset int, limit int) (model.ChannelList, *model.AppError) { +func (a *App) GetChannelsUserNotIn(c request.CTX, teamID string, userID string, offset int, limit int) (model.ChannelList, *model.AppError) { channels, err := a.Srv().Store.Channel().GetMoreChannels(teamID, userID, offset, limit) if err != nil { return nil, model.NewAppError("GetChannelsUserNotIn", "app.channel.get_more_channels.get.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -1930,7 +1930,7 @@ func (a *App) GetChannelsUserNotIn(teamID string, userID string, offset int, lim return channels, nil } -func (a *App) GetPublicChannelsByIdsForTeam(teamID string, channelIDs []string) (model.ChannelList, *model.AppError) { +func (a *App) GetPublicChannelsByIdsForTeam(c request.CTX, teamID string, channelIDs []string) (model.ChannelList, *model.AppError) { list, err := a.Srv().Store.Channel().GetPublicChannelsByIdsForTeam(teamID, channelIDs) if err != nil { var nfErr *store.ErrNotFound @@ -1945,7 +1945,7 @@ func (a *App) GetPublicChannelsByIdsForTeam(teamID string, channelIDs []string) return list, nil } -func (a *App) GetPublicChannelsForTeam(teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { +func (a *App) GetPublicChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { list, err := a.Srv().Store.Channel().GetPublicChannelsForTeam(teamID, offset, limit) if err != nil { return nil, model.NewAppError("GetPublicChannelsForTeam", "app.channel.get_public_channels.get.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -1954,7 +1954,7 @@ func (a *App) GetPublicChannelsForTeam(teamID string, offset int, limit int) (mo return list, nil } -func (a *App) GetPrivateChannelsForTeam(teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { +func (a *App) GetPrivateChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { list, err := a.Srv().Store.Channel().GetPrivateChannelsForTeam(teamID, offset, limit) if err != nil { return nil, model.NewAppError("GetPrivateChannelsForTeam", "app.channel.get_private_channels.get.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -1963,12 +1963,12 @@ func (a *App) GetPrivateChannelsForTeam(teamID string, offset int, limit int) (m return list, nil } -func (a *App) GetChannelMember(ctx context.Context, channelID string, userID string) (*model.ChannelMember, *model.AppError) { - return a.Srv().getChannelMember(ctx, channelID, userID) +func (a *App) GetChannelMember(c request.CTX, channelID string, userID string) (*model.ChannelMember, *model.AppError) { + return a.Srv().getChannelMember(c, channelID, userID) } -func (s *Server) getChannelMember(ctx context.Context, channelID string, userID string) (*model.ChannelMember, *model.AppError) { - channelMember, err := s.Store.Channel().GetMember(ctx, channelID, userID) +func (s *Server) getChannelMember(c request.CTX, channelID string, userID string) (*model.ChannelMember, *model.AppError) { + channelMember, err := s.Store.Channel().GetMember(c.Context(), channelID, userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1982,7 +1982,7 @@ func (s *Server) getChannelMember(ctx context.Context, channelID string, userID return channelMember, nil } -func (a *App) GetChannelMembersPage(channelID string, page, perPage int) (model.ChannelMembers, *model.AppError) { +func (a *App) GetChannelMembersPage(c request.CTX, channelID string, page, perPage int) (model.ChannelMembers, *model.AppError) { channelMembers, err := a.Srv().Store.Channel().GetMembers(channelID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetChannelMembersPage", "app.channel.get_members.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -1991,7 +1991,7 @@ func (a *App) GetChannelMembersPage(channelID string, page, perPage int) (model. return channelMembers, nil } -func (a *App) GetChannelMembersTimezones(channelID string) ([]string, *model.AppError) { +func (a *App) GetChannelMembersTimezones(c request.CTX, channelID string) ([]string, *model.AppError) { membersTimezones, err := a.Srv().Store.Channel().GetChannelMembersTimezones(channelID) if err != nil { return nil, model.NewAppError("GetChannelMembersTimezones", "app.channel.get_members.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2008,7 +2008,7 @@ func (a *App) GetChannelMembersTimezones(channelID string) ([]string, *model.App return model.RemoveDuplicateStrings(timezones), nil } -func (a *App) GetChannelMembersByIds(channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) { +func (a *App) GetChannelMembersByIds(c request.CTX, channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) { members, err := a.Srv().Store.Channel().GetMembersByIds(channelID, userIDs) if err != nil { return nil, model.NewAppError("GetChannelMembersByIds", "app.channel.get_members_by_ids.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2017,7 +2017,7 @@ func (a *App) GetChannelMembersByIds(channelID string, userIDs []string) (model. return members, nil } -func (a *App) GetChannelMembersForUser(teamID string, userID string) (model.ChannelMembers, *model.AppError) { +func (a *App) GetChannelMembersForUser(c request.CTX, teamID string, userID string) (model.ChannelMembers, *model.AppError) { channelMembers, err := a.Srv().Store.Channel().GetMembersForUser(teamID, userID) if err != nil { return nil, model.NewAppError("GetChannelMembersForUser", "app.channel.get_members.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2026,7 +2026,7 @@ func (a *App) GetChannelMembersForUser(teamID string, userID string) (model.Chan return channelMembers, nil } -func (a *App) GetChannelMembersForUserWithPagination(userID string, page, perPage int) ([]*model.ChannelMember, *model.AppError) { +func (a *App) GetChannelMembersForUserWithPagination(c request.CTX, userID string, page, perPage int) ([]*model.ChannelMember, *model.AppError) { m, err := a.Srv().Store.Channel().GetMembersForUserWithPagination(userID, page, perPage) if err != nil { return nil, model.NewAppError("GetChannelMembersForUserWithPagination", "app.channel.get_members.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2040,7 +2040,7 @@ func (a *App) GetChannelMembersForUserWithPagination(userID string, page, perPag return members, nil } -func (a *App) GetChannelMembersWithTeamDataForUserWithPagination(userID string, page, perPage int) (model.ChannelMembersWithTeamData, *model.AppError) { +func (a *App) GetChannelMembersWithTeamDataForUserWithPagination(c request.CTX, userID string, page, perPage int) (model.ChannelMembersWithTeamData, *model.AppError) { m, err := a.Srv().Store.Channel().GetMembersForUserWithPagination(userID, page, perPage) if err != nil { return nil, model.NewAppError("GetChannelMembersForUserWithPagination", "app.channel.get_members.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2049,7 +2049,7 @@ func (a *App) GetChannelMembersWithTeamDataForUserWithPagination(userID string, return m, nil } -func (a *App) GetChannelMemberCount(channelID string) (int64, *model.AppError) { +func (a *App) GetChannelMemberCount(c request.CTX, channelID string) (int64, *model.AppError) { count, err := a.Srv().Store.Channel().GetMemberCount(channelID, true) if err != nil { return 0, model.NewAppError("GetChannelMemberCount", "app.channel.get_member_count.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2058,7 +2058,7 @@ func (a *App) GetChannelMemberCount(channelID string) (int64, *model.AppError) { return count, nil } -func (a *App) GetChannelFileCount(channelID string) (int64, *model.AppError) { +func (a *App) GetChannelFileCount(c request.CTX, channelID string) (int64, *model.AppError) { count, err := a.Srv().Store.Channel().GetFileCount(channelID) if err != nil { return 0, model.NewAppError("SqlChannelStore.GetFileCount", "app.channel.get_file_count.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2067,7 +2067,7 @@ func (a *App) GetChannelFileCount(channelID string) (int64, *model.AppError) { return count, nil } -func (a *App) GetChannelGuestCount(channelID string) (int64, *model.AppError) { +func (a *App) GetChannelGuestCount(c request.CTX, channelID string) (int64, *model.AppError) { count, err := a.Srv().Store.Channel().GetGuestCount(channelID, true) if err != nil { return 0, model.NewAppError("SqlChannelStore.GetGuestCount", "app.channel.get_member_count.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2076,7 +2076,7 @@ func (a *App) GetChannelGuestCount(channelID string) (int64, *model.AppError) { return count, nil } -func (a *App) GetChannelPinnedPostCount(channelID string) (int64, *model.AppError) { +func (a *App) GetChannelPinnedPostCount(c request.CTX, channelID string) (int64, *model.AppError) { count, err := a.Srv().Store.Channel().GetPinnedPostCount(channelID, true) if err != nil { return 0, model.NewAppError("GetChannelPinnedPostCount", "app.channel.get_pinnedpost_count.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2085,7 +2085,7 @@ func (a *App) GetChannelPinnedPostCount(channelID string) (int64, *model.AppErro return count, nil } -func (a *App) GetChannelCounts(teamID string, userID string) (*model.ChannelCounts, *model.AppError) { +func (a *App) GetChannelCounts(c request.CTX, teamID string, userID string) (*model.ChannelCounts, *model.AppError) { counts, err := a.Srv().Store.Channel().GetChannelCounts(teamID, userID) if err != nil { return nil, model.NewAppError("SqlChannelStore.GetChannelCounts", "app.channel.get_channel_counts.get.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -2094,7 +2094,7 @@ func (a *App) GetChannelCounts(teamID string, userID string) (*model.ChannelCoun return counts, nil } -func (a *App) GetChannelUnread(channelID, userID string) (*model.ChannelUnread, *model.AppError) { +func (a *App) GetChannelUnread(c request.CTX, channelID, userID string) (*model.ChannelUnread, *model.AppError) { channelUnread, err := a.Srv().Store.Channel().GetChannelUnread(channelID, userID) if err != nil { var nfErr *store.ErrNotFound @@ -2113,7 +2113,7 @@ func (a *App) GetChannelUnread(channelID, userID string) (*model.ChannelUnread, return channelUnread, nil } -func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { +func (a *App) JoinChannel(c request.CTX, channel *model.Channel, userID string) *model.AppError { userChan := make(chan store.StoreResult, 1) memberChan := make(chan store.StoreResult, 1) go func() { @@ -2150,7 +2150,7 @@ func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID str return model.NewAppError("JoinChannel", "api.channel.join_channel.permissions.app_error", nil, "", http.StatusBadRequest) } - cm, err := a.AddUserToChannel(user, channel, false) + cm, err := a.AddUserToChannel(c, user, channel, false) if err != nil { return err } @@ -2172,7 +2172,7 @@ func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID str return nil } -func (a *App) postJoinChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postJoinChannelMessage(c request.CTX, user *model.User, channel *model.Channel) *model.AppError { message := fmt.Sprintf(i18n.T("api.channel.join_channel.post_and_forget"), user.Username) postType := model.PostTypeJoinChannel @@ -2198,7 +2198,7 @@ func (a *App) postJoinChannelMessage(c *request.Context, user *model.User, chann return nil } -func (a *App) postJoinTeamMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postJoinTeamMessage(c request.CTX, user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.join_team.post_and_forget"), user.Username), @@ -2216,7 +2216,7 @@ func (a *App) postJoinTeamMessage(c *request.Context, user *model.User, channel return nil } -func (a *App) LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError { +func (a *App) LeaveChannel(c request.CTX, channelID string, userID string) *model.AppError { sc := make(chan store.StoreResult, 1) go func() { channel, err := a.Srv().Store.Channel().Get(channelID, true) @@ -2292,7 +2292,7 @@ func (a *App) LeaveChannel(c *request.Context, channelID string, userID string) return nil } -func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postLeaveChannelMessage(c request.CTX, user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, // Message here embeds `@username`, not just `username`, to ensure that mentions @@ -2313,7 +2313,7 @@ func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, chan return nil } -func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { +func (a *App) PostAddToChannelMessage(c request.CTX, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { message := fmt.Sprintf(i18n.T("api.channel.add_member.added"), addedUser.Username, user.Username) postType := model.PostTypeAddToChannel @@ -2343,7 +2343,7 @@ func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, adde return nil } -func (a *App) postAddToTeamMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { +func (a *App) postAddToTeamMessage(c request.CTX, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(i18n.T("api.team.add_user_to_team.added"), addedUser.Username, user.Username), @@ -2365,7 +2365,7 @@ func (a *App) postAddToTeamMessage(c *request.Context, user *model.User, addedUs return nil } -func (a *App) postRemoveFromChannelMessage(c *request.Context, removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError { +func (a *App) postRemoveFromChannelMessage(c request.CTX, removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError { messageUserId := removerUserId if messageUserId == "" { systemBot, err := a.GetSystemBot() @@ -2397,7 +2397,7 @@ func (a *App) postRemoveFromChannelMessage(c *request.Context, removerUserId str return nil } -func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *App) removeUserFromChannel(c request.CTX, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { user, nErr := a.Srv().Store.User().Get(context.Background(), userIDToRemove) if nErr != nil { var nfErr *store.ErrNotFound @@ -2426,7 +2426,7 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r } } - cm, err := a.GetChannelMember(context.Background(), channel.Id, userIDToRemove) + cm, err := a.GetChannelMember(c, channel.Id, userIDToRemove) if err != nil { return err } @@ -2439,7 +2439,7 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r } if isGuest { - currentMembers, err := a.GetChannelMembersForUser(channel.TeamId, userIDToRemove) + currentMembers, err := a.GetChannelMembersForUser(c, channel.TeamId, userIDToRemove) if err != nil { return err } @@ -2491,7 +2491,7 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r return nil } -func (a *App) RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *App) RemoveUserFromChannel(c request.CTX, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { var err *model.AppError if err = a.removeUserFromChannel(c, userIDToRemove, removerUserId, channel); err != nil { @@ -2518,7 +2518,7 @@ func (a *App) RemoveUserFromChannel(c *request.Context, userIDToRemove string, r return nil } -func (a *App) GetNumberOfChannelsOnTeam(teamID string) (int, *model.AppError) { +func (a *App) GetNumberOfChannelsOnTeam(c request.CTX, teamID string) (int, *model.AppError) { // Get total number of channels on current team list, err := a.Srv().Store.Channel().GetTeamChannels(teamID) if err != nil { @@ -2533,7 +2533,7 @@ func (a *App) GetNumberOfChannelsOnTeam(teamID string) (int, *model.AppError) { return len(list), nil } -func (a *App) SetActiveChannel(userID string, channelID string) *model.AppError { +func (a *App) SetActiveChannel(c request.CTX, userID string, channelID string) *model.AppError { status, err := a.GetStatus(userID) oldStatus := model.StatusOffline @@ -2558,7 +2558,7 @@ func (a *App) SetActiveChannel(userID string, channelID string) *model.AppError return nil } -func (a *App) IsCRTEnabledForUser(userID string) bool { +func (a *App) IsCRTEnabledForUser(c request.CTX, userID string) bool { appCRT := *a.Config().ServiceSettings.CollapsedThreads if appCRT == model.CollapsedThreadsDisabled { return false @@ -2575,9 +2575,9 @@ func (a *App) IsCRTEnabledForUser(userID string) bool { } // MarkChanelAsUnreadFromPost will take a post and set the channel as unread from that one. -func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string, collapsedThreadsSupported bool) (*model.ChannelUnreadAt, *model.AppError) { - if !collapsedThreadsSupported || !a.IsCRTEnabledForUser(userID) { - return a.markChannelAsUnreadFromPostCRTUnsupported(postID, userID) +func (a *App) MarkChannelAsUnreadFromPost(c request.CTX, postID string, userID string, collapsedThreadsSupported bool) (*model.ChannelUnreadAt, *model.AppError) { + if !collapsedThreadsSupported || !a.IsCRTEnabledForUser(c, userID) { + return a.markChannelAsUnreadFromPostCRTUnsupported(c, postID, userID) } post, err := a.GetSinglePost(postID, false) if err != nil { @@ -2589,7 +2589,7 @@ func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string, collapse return nil, err } - unreadMentions, unreadMentionsRoot, err := a.countMentionsFromPost(user, post) + unreadMentions, unreadMentionsRoot, err := a.countMentionsFromPost(c, user, post) if err != nil { return nil, err } @@ -2599,13 +2599,13 @@ func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string, collapse return channelUnread, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, nErr.Error(), http.StatusInternalServerError) } - a.sendWebSocketPostUnreadEvent(channelUnread, postID, false) + a.sendWebSocketPostUnreadEvent(c, channelUnread, postID, false) a.UpdateMobileAppBadge(userID) return channelUnread, nil } -func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID string) (*model.ChannelUnreadAt, *model.AppError) { +func (a *App) markChannelAsUnreadFromPostCRTUnsupported(c request.CTX, postID string, userID string) (*model.ChannelUnreadAt, *model.AppError) { post, err := a.GetSinglePost(postID, false) if err != nil { return nil, err @@ -2621,7 +2621,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st threadId = post.Id } - unreadMentions, unreadMentionsRoot, err := a.countMentionsFromPost(user, post) + unreadMentions, unreadMentionsRoot, err := a.countMentionsFromPost(c, user, post) if err != nil { return nil, err } @@ -2635,7 +2635,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st return channelUnread, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, nErr.Error(), http.StatusInternalServerError) } - a.sendWebSocketPostUnreadEvent(channelUnread, postID, true) + a.sendWebSocketPostUnreadEvent(c, channelUnread, postID, true) a.UpdateMobileAppBadge(userID) return channelUnread, nil } @@ -2678,7 +2678,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st // If threadmembership already exists but user had previously unfollowed the thread, then follow the thread again. threadMembership.Following = true threadMembership.LastViewed = post.CreateAt - 1 - threadMembership.UnreadMentions, err = a.countThreadMentions(user, rootPost, channel.TeamId, post.CreateAt-1) + threadMembership.UnreadMentions, err = a.countThreadMentions(c, user, rootPost, channel.TeamId, post.CreateAt-1) if err != nil { return nil, err } @@ -2693,10 +2693,10 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st a.sanitizeProfiles(thread.Participants, false) thread.Post.SanitizeProps() - if a.IsCRTEnabledForUser(userID) { + if a.IsCRTEnabledForUser(c, userID) { payload, jsonErr := json.Marshal(thread) if jsonErr != nil { - mlog.Warn("Failed to encode thread to JSON") + c.Logger().Warn("Failed to encode thread to JSON") } message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, channel.TeamId, "", userID, nil) message.Add("thread", string(payload)) @@ -2708,12 +2708,12 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st if nErr != nil { return channelUnread, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, nErr.Error(), http.StatusInternalServerError) } - a.sendWebSocketPostUnreadEvent(channelUnread, postID, false) + a.sendWebSocketPostUnreadEvent(c, channelUnread, postID, false) a.UpdateMobileAppBadge(userID) return channelUnread, nil } -func (a *App) sendWebSocketPostUnreadEvent(channelUnread *model.ChannelUnreadAt, postID string, withMsgCountRoot bool) { +func (a *App) sendWebSocketPostUnreadEvent(c request.CTX, channelUnread *model.ChannelUnreadAt, postID string, withMsgCountRoot bool) { message := model.NewWebSocketEvent(model.WebsocketEventPostUnread, channelUnread.TeamId, channelUnread.ChannelId, channelUnread.UserId, nil) message.Add("msg_count", channelUnread.MsgCount) if withMsgCountRoot { @@ -2726,7 +2726,7 @@ func (a *App) sendWebSocketPostUnreadEvent(channelUnread *model.ChannelUnreadAt, a.Publish(message) } -func (a *App) AutocompleteChannels(userID, term string) (model.ChannelListWithTeamData, *model.AppError) { +func (a *App) AutocompleteChannels(c request.CTX, userID, term string) (model.ChannelListWithTeamData, *model.AppError) { includeDeleted := *a.Config().TeamSettings.ExperimentalViewArchivedChannels term = strings.TrimSpace(term) @@ -2743,7 +2743,7 @@ func (a *App) AutocompleteChannels(userID, term string) (model.ChannelListWithTe return channelList, nil } -func (a *App) AutocompleteChannelsForTeam(teamID, userID, term string) (model.ChannelList, *model.AppError) { +func (a *App) AutocompleteChannelsForTeam(c request.CTX, teamID, userID, term string) (model.ChannelList, *model.AppError) { includeDeleted := *a.Config().TeamSettings.ExperimentalViewArchivedChannels term = strings.TrimSpace(term) @@ -2760,7 +2760,7 @@ func (a *App) AutocompleteChannelsForTeam(teamID, userID, term string) (model.Ch return channelList, nil } -func (a *App) AutocompleteChannelsForSearch(teamID string, userID string, term string) (model.ChannelList, *model.AppError) { +func (a *App) AutocompleteChannelsForSearch(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) { includeDeleted := *a.Config().TeamSettings.ExperimentalViewArchivedChannels term = strings.TrimSpace(term) @@ -2774,9 +2774,9 @@ func (a *App) AutocompleteChannelsForSearch(teamID string, userID string, term s } // SearchAllChannels returns a list of channels, the total count of the results of the search (if the paginate search option is true), and an error. -func (a *App) SearchAllChannels(term string, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, int64, *model.AppError) { +func (a *App) SearchAllChannels(c request.CTX, term string, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, int64, *model.AppError) { if opts.ExcludeDefaultChannels { - opts.ExcludeChannelNames = a.DefaultChannelNames() + opts.ExcludeChannelNames = a.DefaultChannelNames(c) } storeOpts := store.ChannelSearchOpts{ ExcludeChannelNames: opts.ExcludeChannelNames, @@ -2806,7 +2806,7 @@ func (a *App) SearchAllChannels(term string, opts model.ChannelSearchOpts) (mode return channelList, totalCount, nil } -func (a *App) SearchChannels(teamID string, term string) (model.ChannelList, *model.AppError) { +func (a *App) SearchChannels(c request.CTX, teamID string, term string) (model.ChannelList, *model.AppError) { includeDeleted := *a.Config().TeamSettings.ExperimentalViewArchivedChannels term = strings.TrimSpace(term) @@ -2819,7 +2819,7 @@ func (a *App) SearchChannels(teamID string, term string) (model.ChannelList, *mo return channelList, nil } -func (a *App) SearchArchivedChannels(teamID string, term string, userID string) (model.ChannelList, *model.AppError) { +func (a *App) SearchArchivedChannels(c request.CTX, teamID string, term string, userID string) (model.ChannelList, *model.AppError) { term = strings.TrimSpace(term) channelList, err := a.Srv().Store.Channel().SearchArchivedInTeam(teamID, term, userID) @@ -2830,7 +2830,7 @@ func (a *App) SearchArchivedChannels(teamID string, term string, userID string) return channelList, nil } -func (a *App) SearchChannelsForUser(userID, teamID, term string) (model.ChannelList, *model.AppError) { +func (a *App) SearchChannelsForUser(c request.CTX, userID, teamID, term string) (model.ChannelList, *model.AppError) { includeDeleted := *a.Config().TeamSettings.ExperimentalViewArchivedChannels term = strings.TrimSpace(term) @@ -2843,7 +2843,7 @@ func (a *App) SearchChannelsForUser(userID, teamID, term string) (model.ChannelL return channelList, nil } -func (a *App) SearchGroupChannels(userID, term string) (model.ChannelList, *model.AppError) { +func (a *App) SearchGroupChannels(c request.CTX, userID, term string) (model.ChannelList, *model.AppError) { if term == "" { return model.ChannelList{}, nil } @@ -2855,7 +2855,7 @@ func (a *App) SearchGroupChannels(userID, term string) (model.ChannelList, *mode return channelList, nil } -func (a *App) SearchChannelsUserNotIn(teamID string, userID string, term string) (model.ChannelList, *model.AppError) { +func (a *App) SearchChannelsUserNotIn(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) { term = strings.TrimSpace(term) channelList, err := a.Srv().Store.Channel().SearchMore(userID, teamID, term) if err != nil { @@ -2865,20 +2865,20 @@ func (a *App) SearchChannelsUserNotIn(teamID string, userID string, term string) return channelList, nil } -func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { +func (a *App) MarkChannelsAsViewed(c request.CTX, channelIDs []string, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { // I start looking for channels with notifications before I mark it as read, to clear the push notifications if needed channelsToClearPushNotifications := []string{} if a.canSendPushNotifications() { for _, channelID := range channelIDs { channel, errCh := a.Srv().Store.Channel().Get(channelID, true) if errCh != nil { - mlog.Warn("Failed to get channel", mlog.Err(errCh)) + c.Logger().Warn("Failed to get channel", mlog.Err(errCh)) continue } member, err := a.Srv().Store.Channel().GetMember(context.Background(), channelID, userID) if err != nil { - mlog.Warn("Failed to get membership", mlog.Err(err)) + c.Logger().Warn("Failed to get membership", mlog.Err(err)) continue } @@ -2886,7 +2886,7 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe if notify == model.ChannelNotifyDefault { user, err := a.GetUser(userID) if err != nil { - mlog.Warn("Failed to get user", mlog.String("user_id", userID), mlog.Err(err)) + c.Logger().Warn("Failed to get user", mlog.String("user_id", userID), mlog.Err(err)) continue } notify = user.NotifyProps[model.PushNotifyProp] @@ -2908,7 +2908,7 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe } var err error - updateThreads := *a.Config().ServiceSettings.ThreadAutoFollow && (!collapsedThreadsSupported || !a.IsCRTEnabledForUser(userID)) + updateThreads := *a.Config().ServiceSettings.ThreadAutoFollow && (!collapsedThreadsSupported || !a.IsCRTEnabledForUser(c, userID)) if updateThreads { err = a.Srv().Store.Thread().MarkAllAsReadByChannels(userID, channelIDs) if err != nil { @@ -2938,7 +2938,7 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe a.clearPushNotification(currentSessionId, userID, channelID, "") } - if updateThreads && a.IsCRTEnabledForUser(userID) { + if updateThreads && a.IsCRTEnabledForUser(c, userID) { timestamp := model.GetMillis() for _, channelID := range channelIDs { message := model.NewWebSocketEvent(model.WebsocketEventThreadReadChanged, "", channelID, userID, nil) @@ -2950,8 +2950,8 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe return times, nil } -func (a *App) ViewChannel(view *model.ChannelView, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { - if err := a.SetActiveChannel(userID, view.ChannelId); err != nil { +func (a *App) ViewChannel(c request.CTX, view *model.ChannelView, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { + if err := a.SetActiveChannel(c, userID, view.ChannelId); err != nil { return nil, err } @@ -2969,10 +2969,10 @@ func (a *App) ViewChannel(view *model.ChannelView, userID string, currentSession return map[string]int64{}, nil } - return a.MarkChannelsAsViewed(channelIDs, userID, currentSessionId, collapsedThreadsSupported) + return a.MarkChannelsAsViewed(c, channelIDs, userID, currentSessionId, collapsedThreadsSupported) } -func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError { +func (a *App) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *model.AppError { if err := a.Srv().Store.Post().PermanentDeleteByChannel(channel.Id); err != nil { return model.NewAppError("PermanentDeleteChannel", "app.post.permanent_delete_by_channel.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -3004,7 +3004,7 @@ func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError { return nil } -func (a *App) RemoveAllDeactivatedMembersFromChannel(channel *model.Channel) *model.AppError { +func (a *App) RemoveAllDeactivatedMembersFromChannel(c request.CTX, channel *model.Channel) *model.AppError { err := a.Srv().Store.Channel().RemoveAllDeactivatedMembers(channel.Id) if err != nil { return model.NewAppError("RemoveAllDeactivatedMembersFromChannel", "app.channel.remove_all_deactivated_members.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -3015,9 +3015,9 @@ func (a *App) RemoveAllDeactivatedMembersFromChannel(channel *model.Channel) *mo // MoveChannel method is prone to data races if someone joins to channel during the move process. However this // function is only exposed to sysadmins and the possibility of this edge case is relatively small. -func (a *App) MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { +func (a *App) MoveChannel(c request.CTX, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { // Check that all channel members are in the destination team. - channelMembers, err := a.GetChannelMembersPage(channel.Id, 0, 10000000) + channelMembers, err := a.GetChannelMembersPage(c, channel.Id, 0, 10000000) if err != nil { return err } @@ -3040,7 +3040,7 @@ func (a *App) MoveChannel(c *request.Context, team *model.Team, channel *model.C } for _, channelMember := range channelMembers { if _, ok := teamMembersMap[channelMember.UserId]; !ok { - mlog.Warn("Not member of the target team", mlog.String("userId", channelMember.UserId)) + c.Logger().Warn("Not member of the target team", mlog.String("userId", channelMember.UserId)) } } return model.NewAppError("MoveChannel", "app.channel.move_channel.members_do_not_match.error", nil, "", http.StatusInternalServerError) @@ -3078,45 +3078,45 @@ func (a *App) MoveChannel(c *request.Context, team *model.Team, channel *model.C } if incomingWebhooks, err := a.GetIncomingWebhooksForTeamPage(previousTeam.Id, 0, 10000000); err != nil { - mlog.Warn("Failed to get incoming webhooks", mlog.Err(err)) + c.Logger().Warn("Failed to get incoming webhooks", mlog.Err(err)) } else { for _, webhook := range incomingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id if _, err := a.Srv().Store.Webhook().UpdateIncoming(webhook); err != nil { - mlog.Warn("Failed to move incoming webhook to new team", mlog.String("webhook id", webhook.Id)) + c.Logger().Warn("Failed to move incoming webhook to new team", mlog.String("webhook id", webhook.Id)) } } } } if outgoingWebhooks, err := a.GetOutgoingWebhooksForTeamPage(previousTeam.Id, 0, 10000000); err != nil { - mlog.Warn("Failed to get outgoing webhooks", mlog.Err(err)) + c.Logger().Warn("Failed to get outgoing webhooks", mlog.Err(err)) } else { for _, webhook := range outgoingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id if _, err := a.Srv().Store.Webhook().UpdateOutgoing(webhook); err != nil { - mlog.Warn("Failed to move outgoing webhook to new team.", mlog.String("webhook id", webhook.Id)) + c.Logger().Warn("Failed to move outgoing webhook to new team.", mlog.String("webhook id", webhook.Id)) } } } } if err := a.RemoveUsersFromChannelNotMemberOfTeam(c, user, channel, team); err != nil { - mlog.Warn("error while removing non-team member users", mlog.Err(err)) + c.Logger().Warn("error while removing non-team member users", mlog.Err(err)) } if user != nil { if err := a.postChannelMoveMessage(c, user, channel, previousTeam); err != nil { - mlog.Warn("error while posting move channel message", mlog.Err(err)) + c.Logger().Warn("error while posting move channel message", mlog.Err(err)) } } return nil } -func (a *App) postChannelMoveMessage(c *request.Context, user *model.User, channel *model.Channel, previousTeam *model.Team) *model.AppError { +func (a *App) postChannelMoveMessage(c request.CTX, user *model.User, channel *model.Channel, previousTeam *model.Team) *model.AppError { post := &model.Post{ ChannelId: channel.Id, @@ -3135,8 +3135,8 @@ func (a *App) postChannelMoveMessage(c *request.Context, user *model.User, chann return nil } -func (a *App) RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { - channelMembers, err := a.GetChannelMembersPage(channel.Id, 0, 10000000) +func (a *App) RemoveUsersFromChannelNotMemberOfTeam(c request.CTX, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { + channelMembers, err := a.GetChannelMembersPage(c, channel.Id, 0, 10000000) if err != nil { return err } @@ -3174,7 +3174,7 @@ func (a *App) RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover return nil } -func (a *App) GetPinnedPosts(channelID string) (*model.PostList, *model.AppError) { +func (a *App) GetPinnedPosts(c request.CTX, channelID string) (*model.PostList, *model.AppError) { posts, err := a.Srv().Store.Channel().GetPinnedPosts(channelID) if err != nil { return nil, model.NewAppError("GetPinnedPosts", "app.channel.pinned_posts.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -3187,7 +3187,7 @@ func (a *App) GetPinnedPosts(channelID string) (*model.PostList, *model.AppError return posts, nil } -func (a *App) ToggleMuteChannel(channelID, userID string) (*model.ChannelMember, *model.AppError) { +func (a *App) ToggleMuteChannel(c request.CTX, channelID, userID string) (*model.ChannelMember, *model.AppError) { member, nErr := a.Srv().Store.Channel().GetMember(context.Background(), channelID, userID) if nErr != nil { var appErr *model.AppError @@ -3204,7 +3204,7 @@ func (a *App) ToggleMuteChannel(channelID, userID string) (*model.ChannelMember, member.SetChannelMuted(!member.IsChannelMuted()) - member, err := a.updateChannelMember(member) + member, err := a.updateChannelMember(c, member) if err != nil { return nil, err } @@ -3214,7 +3214,7 @@ func (a *App) ToggleMuteChannel(channelID, userID string) (*model.ChannelMember, return member, nil } -func (a *App) setChannelsMuted(channelIDs []string, userID string, muted bool) ([]*model.ChannelMember, *model.AppError) { +func (a *App) setChannelsMuted(c request.CTX, channelIDs []string, userID string, muted bool) ([]*model.ChannelMember, *model.AppError) { members, nErr := a.Srv().Store.Channel().GetMembersByChannelIds(channelIDs, userID) if nErr != nil { var appErr *model.AppError @@ -3263,7 +3263,7 @@ func (a *App) setChannelsMuted(channelIDs []string, userID string, muted bool) ( memberJSON, jsonErr := json.Marshal(member) if jsonErr != nil { - mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) + c.Logger().Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) } evt.Add("channelMember", string(memberJSON)) @@ -3273,11 +3273,11 @@ func (a *App) setChannelsMuted(channelIDs []string, userID string, muted bool) ( return updated, nil } -func (a *App) FillInChannelProps(channel *model.Channel) *model.AppError { - return a.FillInChannelsProps(model.ChannelList{channel}) +func (a *App) FillInChannelProps(c request.CTX, channel *model.Channel) *model.AppError { + return a.FillInChannelsProps(c, model.ChannelList{channel}) } -func (a *App) FillInChannelsProps(channelList model.ChannelList) *model.AppError { +func (a *App) FillInChannelsProps(c request.CTX, channelList model.ChannelList) *model.AppError { // Group the channels by team and call GetChannelsByNames just once per team. channelsByTeam := make(map[string]model.ChannelList) for _, channel := range channelList { @@ -3303,7 +3303,7 @@ func (a *App) FillInChannelsProps(channelList model.ChannelList) *model.AppError } if len(allChannelMentionNames) > 0 { - mentionedChannels, err := a.GetChannelsByNames(allChannelMentionNames, teamID) + mentionedChannels, err := a.GetChannelsByNames(c, allChannelMentionNames, teamID) if err != nil { return err } @@ -3337,7 +3337,7 @@ func (a *App) FillInChannelsProps(channelList model.ChannelList) *model.AppError return nil } -func (a *App) forEachChannelMember(channelID string, f func(model.ChannelMember) error) error { +func (a *App) forEachChannelMember(c request.CTX, channelID string, f func(model.ChannelMember) error) error { perPage := 100 page := 0 @@ -3364,20 +3364,20 @@ func (a *App) forEachChannelMember(channelID string, f func(model.ChannelMember) return nil } -func (a *App) ClearChannelMembersCache(channelID string) { +func (a *App) ClearChannelMembersCache(c request.CTX, channelID string) { clearSessionCache := func(channelMember model.ChannelMember) error { a.ClearSessionCacheForUser(channelMember.UserId) message := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", channelMember.UserId, nil) memberJSON, jsonErr := json.Marshal(channelMember) if jsonErr != nil { - mlog.Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) + c.Logger().Warn("Failed to encode channel member to JSON", mlog.Err(jsonErr)) } message.Add("channelMember", string(memberJSON)) a.Publish(message) return nil } - if err := a.forEachChannelMember(channelID, clearSessionCache); err != nil { - a.Log().Warn("error clearing cache for channel members", mlog.String("channel_id", channelID)) + if err := a.forEachChannelMember(c, channelID, clearSessionCache); err != nil { + c.Logger().Warn("error clearing cache for channel members", mlog.String("channel_id", channelID)) } } @@ -3390,11 +3390,11 @@ func (a *App) GetMemberCountsByGroup(ctx context.Context, channelID string, incl return channelMemberCounts, nil } -func (a *App) getDirectChannel(userID, otherUserID string) (*model.Channel, *model.AppError) { - return a.Srv().getDirectChannel(userID, otherUserID) +func (a *App) getDirectChannel(c request.CTX, userID, otherUserID string) (*model.Channel, *model.AppError) { + return a.Srv().getDirectChannel(c, userID, otherUserID) } -func (s *Server) getDirectChannel(userID, otherUserID string) (*model.Channel, *model.AppError) { +func (s *Server) getDirectChannel(c request.CTX, userID, otherUserID string) (*model.Channel, *model.AppError) { channel, nErr := s.Store.Channel().GetByName("", model.GetDMNameFromIds(userID, otherUserID), true) if nErr != nil { var nfErr *store.ErrNotFound @@ -3408,7 +3408,7 @@ func (s *Server) getDirectChannel(userID, otherUserID string) (*model.Channel, * return channel, nil } -func (a *App) GetTopChannelsForTeamSince(teamID, userID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { +func (a *App) GetTopChannelsForTeamSince(c request.CTX, teamID, userID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("GetTopChannelsForTeamSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } @@ -3420,7 +3420,7 @@ func (a *App) GetTopChannelsForTeamSince(teamID, userID string, opts *model.Insi return topChannels, nil } -func (a *App) GetTopChannelsForUserSince(userID, teamID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { +func (a *App) GetTopChannelsForUserSince(c request.CTX, userID, teamID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("GetTopChannelsForUserSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } @@ -3437,7 +3437,7 @@ func (a *App) GetTopChannelsForUserSince(userID, teamID string, opts *model.Insi // use a sinceUnixMillis parameter value as returned by model.GetStartOfDayMillis. // // WARNING: PostCountsByDuration PERFORMS NO AUTHORIZATION CHECKS ON THE GIVEN CHANNELS. -func (a *App) PostCountsByDuration(channelIDs []string, sinceUnixMillis int64, userID *string, grouping model.PostCountGrouping, groupingLocation *time.Location) ([]*model.DurationPostCount, *model.AppError) { +func (a *App) PostCountsByDuration(c request.CTX, channelIDs []string, sinceUnixMillis int64, userID *string, grouping model.PostCountGrouping, groupingLocation *time.Location) ([]*model.DurationPostCount, *model.AppError) { if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("PostCountsByDuration", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } diff --git a/app/channel_category.go b/app/channel_category.go index 1726218005..4cba5b9b17 100644 --- a/app/channel_category.go +++ b/app/channel_category.go @@ -8,6 +8,7 @@ import ( "errors" "net/http" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store" @@ -22,7 +23,7 @@ func (a *App) createInitialSidebarCategories(userID string, opts *store.SidebarC return categories, nil } -func (a *App) GetSidebarCategoriesForTeamForUser(userID, teamID string) (*model.OrderedSidebarCategories, *model.AppError) { +func (a *App) GetSidebarCategoriesForTeamForUser(c request.CTX, userID, teamID string) (*model.OrderedSidebarCategories, *model.AppError) { var appErr *model.AppError categories, err := a.Srv().Store.Channel().GetSidebarCategoriesForTeamForUser(userID, teamID) if err == nil && len(categories.Categories) == 0 { @@ -49,7 +50,7 @@ func (a *App) GetSidebarCategoriesForTeamForUser(userID, teamID string) (*model. return categories, nil } -func (a *App) GetSidebarCategories(userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) { +func (a *App) GetSidebarCategories(c request.CTX, userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) { var appErr *model.AppError categories, err := a.Srv().Store.Channel().GetSidebarCategories(userID, opts) if err == nil && len(categories.Categories) == 0 { @@ -73,7 +74,7 @@ func (a *App) GetSidebarCategories(userID string, opts *store.SidebarCategorySea return categories, nil } -func (a *App) GetSidebarCategoryOrder(userID, teamID string) ([]string, *model.AppError) { +func (a *App) GetSidebarCategoryOrder(c request.CTX, userID, teamID string) ([]string, *model.AppError) { categories, err := a.Srv().Store.Channel().GetSidebarCategoryOrder(userID, teamID) if err != nil { var nfErr *store.ErrNotFound @@ -88,7 +89,7 @@ func (a *App) GetSidebarCategoryOrder(userID, teamID string) ([]string, *model.A return categories, nil } -func (a *App) GetSidebarCategory(categoryId string) (*model.SidebarCategoryWithChannels, *model.AppError) { +func (a *App) GetSidebarCategory(c request.CTX, categoryId string) (*model.SidebarCategoryWithChannels, *model.AppError) { category, err := a.Srv().Store.Channel().GetSidebarCategory(categoryId) if err != nil { var nfErr *store.ErrNotFound @@ -103,7 +104,7 @@ func (a *App) GetSidebarCategory(categoryId string) (*model.SidebarCategoryWithC return category, nil } -func (a *App) CreateSidebarCategory(userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) { +func (a *App) CreateSidebarCategory(c request.CTX, userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) { category, err := a.Srv().Store.Channel().CreateSidebarCategory(userID, teamID, newCategory) if err != nil { var nfErr *store.ErrNotFound @@ -120,7 +121,7 @@ func (a *App) CreateSidebarCategory(userID, teamID string, newCategory *model.Si return category, nil } -func (a *App) UpdateSidebarCategoryOrder(userID, teamID string, categoryOrder []string) *model.AppError { +func (a *App) UpdateSidebarCategoryOrder(c request.CTX, userID, teamID string, categoryOrder []string) *model.AppError { err := a.Srv().Store.Channel().UpdateSidebarCategoryOrder(userID, teamID, categoryOrder) if err != nil { var nfErr *store.ErrNotFound @@ -140,7 +141,7 @@ func (a *App) UpdateSidebarCategoryOrder(userID, teamID string, categoryOrder [] return nil } -func (a *App) UpdateSidebarCategories(userID, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) { +func (a *App) UpdateSidebarCategories(c request.CTX, userID, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) { updatedCategories, originalCategories, err := a.Srv().Store.Channel().UpdateSidebarCategories(userID, teamID, categories) if err != nil { return nil, model.NewAppError("UpdateSidebarCategories", "app.channel.sidebar_categories.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -150,19 +151,19 @@ func (a *App) UpdateSidebarCategories(userID, teamID string, categories []*model updatedCategoriesJSON, jsonErr := json.Marshal(updatedCategories) if jsonErr != nil { - mlog.Warn("Failed to encode original categories to JSON", mlog.Err(jsonErr)) + c.Logger().Warn("Failed to encode original categories to JSON", mlog.Err(jsonErr)) } message.Add("updatedCategories", string(updatedCategoriesJSON)) a.Publish(message) - a.muteChannelsForUpdatedCategories(userID, updatedCategories, originalCategories) + a.muteChannelsForUpdatedCategories(c, userID, updatedCategories, originalCategories) return updatedCategories, nil } -func (a *App) muteChannelsForUpdatedCategories(userID string, updatedCategories []*model.SidebarCategoryWithChannels, originalCategories []*model.SidebarCategoryWithChannels) { +func (a *App) muteChannelsForUpdatedCategories(c request.CTX, userID string, updatedCategories []*model.SidebarCategoryWithChannels, originalCategories []*model.SidebarCategoryWithChannels) { var channelsToMute []string var channelsToUnmute []string @@ -210,9 +211,9 @@ func (a *App) muteChannelsForUpdatedCategories(userID string, updatedCategories } if len(channelsToMute) > 0 { - _, err := a.setChannelsMuted(channelsToMute, userID, true) + _, err := a.setChannelsMuted(c, channelsToMute, userID, true) if err != nil { - mlog.Error( + c.Logger().Error( "Failed to mute channels to match category", mlog.String("user_id", userID), mlog.Err(err), @@ -221,9 +222,9 @@ func (a *App) muteChannelsForUpdatedCategories(userID string, updatedCategories } if len(channelsToUnmute) > 0 { - _, err := a.setChannelsMuted(channelsToUnmute, userID, false) + _, err := a.setChannelsMuted(c, channelsToUnmute, userID, false) if err != nil { - mlog.Error( + c.Logger().Error( "Failed to unmute channels to match category", mlog.String("user_id", userID), mlog.Err(err), @@ -267,7 +268,7 @@ func diffChannelsBetweenCategories(updatedCategories []*model.SidebarCategoryWit return channelsDiff } -func (a *App) DeleteSidebarCategory(userID, teamID, categoryId string) *model.AppError { +func (a *App) DeleteSidebarCategory(c request.CTX, userID, teamID, categoryId string) *model.AppError { err := a.Srv().Store.Channel().DeleteSidebarCategory(categoryId) if err != nil { var invErr *store.ErrInvalidInput diff --git a/app/channel_category_test.go b/app/channel_category_test.go index 33e79a4783..d85ef9d89a 100644 --- a/app/channel_category_test.go +++ b/app/channel_category_test.go @@ -4,7 +4,6 @@ package app import ( - "context" "testing" "github.com/stretchr/testify/assert" @@ -17,8 +16,8 @@ func TestSidebarCategory(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - basicChannel2 := th.CreateChannel(th.BasicTeam) - defer th.App.PermanentDeleteChannel(basicChannel2) + basicChannel2 := th.CreateChannel(th.Context, th.BasicTeam) + defer th.App.PermanentDeleteChannel(th.Context, basicChannel2) user := th.CreateUser() defer th.App.Srv().Store.User().PermanentDelete(user.Id) th.LinkUserToTeam(user, th.BasicTeam) @@ -32,10 +31,10 @@ func TestSidebarCategory(t *testing.T) { }, Channels: []string{th.BasicChannel.Id, basicChannel2.Id, basicChannel2.Id}, } - _, err := th.App.CreateSidebarCategory(user.Id, th.BasicTeam.Id, &catData) + _, err := th.App.CreateSidebarCategory(th.Context, user.Id, th.BasicTeam.Id, &catData) require.NotNil(t, err, "Should return error due to duplicate IDs") catData.Channels = []string{th.BasicChannel.Id, basicChannel2.Id} - cat, err := th.App.CreateSidebarCategory(user.Id, th.BasicTeam.Id, &catData) + cat, err := th.App.CreateSidebarCategory(th.Context, user.Id, th.BasicTeam.Id, &catData) require.Nil(t, err, "Expected no error") require.NotNil(t, cat, "Expected category object, got nil") createdCategory = cat @@ -44,7 +43,7 @@ func TestSidebarCategory(t *testing.T) { t.Run("UpdateSidebarCategories", func(t *testing.T) { require.NotNil(t, createdCategory) createdCategory.Channels = []string{th.BasicChannel.Id} - updatedCat, err := th.App.UpdateSidebarCategories(user.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{createdCategory}) + updatedCat, err := th.App.UpdateSidebarCategories(th.Context, user.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{createdCategory}) require.Nil(t, err, "Expected no error") require.NotNil(t, updatedCat, "Expected category object, got nil") require.Len(t, updatedCat, 1) @@ -53,14 +52,14 @@ func TestSidebarCategory(t *testing.T) { }) t.Run("UpdateSidebarCategoryOrder", func(t *testing.T) { - err := th.App.UpdateSidebarCategoryOrder(user.Id, th.BasicTeam.Id, []string{th.BasicChannel.Id, basicChannel2.Id}) + err := th.App.UpdateSidebarCategoryOrder(th.Context, user.Id, th.BasicTeam.Id, []string{th.BasicChannel.Id, basicChannel2.Id}) require.NotNil(t, err, "Should return error due to invalid order") - actualOrder, err := th.App.GetSidebarCategoryOrder(user.Id, th.BasicTeam.Id) + actualOrder, err := th.App.GetSidebarCategoryOrder(th.Context, user.Id, th.BasicTeam.Id) require.Nil(t, err, "Should fetch order successfully") actualOrder[2], actualOrder[3] = actualOrder[3], actualOrder[2] - err = th.App.UpdateSidebarCategoryOrder(user.Id, th.BasicTeam.Id, actualOrder) + err = th.App.UpdateSidebarCategoryOrder(th.Context, user.Id, th.BasicTeam.Id, actualOrder) require.Nil(t, err, "Should update order successfully") // We create a copy of actualOrder to prevent racy read @@ -68,12 +67,12 @@ func TestSidebarCategory(t *testing.T) { newOrder := make([]string, len(actualOrder)) copy(newOrder, actualOrder) newOrder[2] = "asd" - err = th.App.UpdateSidebarCategoryOrder(user.Id, th.BasicTeam.Id, newOrder) + err = th.App.UpdateSidebarCategoryOrder(th.Context, user.Id, th.BasicTeam.Id, newOrder) require.NotNil(t, err, "Should return error due to invalid id") }) t.Run("GetSidebarCategoryOrder", func(t *testing.T) { - catOrder, err := th.App.GetSidebarCategoryOrder(user.Id, th.BasicTeam.Id) + catOrder, err := th.App.GetSidebarCategoryOrder(th.Context, user.Id, th.BasicTeam.Id) require.Nil(t, err, "Expected no error") require.Len(t, catOrder, 4) require.Equal(t, catOrder[1], createdCategory.Id, "the newly created category should be after favorites") @@ -85,7 +84,7 @@ func TestGetSidebarCategories(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - _, err := th.App.CreateSidebarCategory(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ + _, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ UserId: th.BasicUser.Id, TeamId: th.BasicTeam.Id, @@ -94,7 +93,7 @@ func TestGetSidebarCategories(t *testing.T) { }) require.Nil(t, err) - categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id) + categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.Context, th.BasicUser.Id, th.BasicTeam.Id) assert.Nil(t, err) assert.Len(t, categories.Categories, 4) }) @@ -113,7 +112,7 @@ func TestGetSidebarCategories(t *testing.T) { }, 100) require.NoError(t, err) - categories, appErr := th.App.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, team.Id) + categories, appErr := th.App.GetSidebarCategoriesForTeamForUser(th.Context, th.BasicUser.Id, team.Id) assert.Nil(t, appErr) assert.Len(t, categories.Categories, 3) }) @@ -131,7 +130,7 @@ func TestGetSidebarCategories(t *testing.T) { require.NoError(t, err) }() - categories, appErr := th.App.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id) + categories, appErr := th.App.GetSidebarCategoriesForTeamForUser(th.Context, th.BasicUser.Id, th.BasicTeam.Id) assert.Nil(t, categories) assert.NotNil(t, appErr) assert.Equal(t, "app.channel.sidebar_categories.app_error", appErr.Id) @@ -143,20 +142,20 @@ func TestUpdateSidebarCategories(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, th.BasicTeam.Id) + categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.Context, th.BasicUser.Id, th.BasicTeam.Id) require.Nil(t, err) channelsCategory := categories.Categories[1] // Create some channels to be part of the channels category - channel1 := th.CreateChannel(th.BasicTeam) + channel1 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel1) - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel2) // Mute the category - updated, err := th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + updated, err := th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: channelsCategory.Id, @@ -169,15 +168,15 @@ func TestUpdateSidebarCategories(t *testing.T) { assert.True(t, updated[0].Muted) // Confirm that the channels are now muted - member1, err := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err := th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member1.IsChannelMuted()) - member2, err := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err := th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member2.IsChannelMuted()) // Unmute the category - updated, err = th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + updated, err = th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: channelsCategory.Id, @@ -190,10 +189,10 @@ func TestUpdateSidebarCategories(t *testing.T) { assert.False(t, updated[0].Muted) // Confirm that the channels are now unmuted - member1, err = th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err = th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member1.IsChannelMuted()) - member2, err = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member2.IsChannelMuted()) }) @@ -203,14 +202,14 @@ func TestUpdateSidebarCategories(t *testing.T) { defer th.TearDown() // Create some channels - channel1 := th.CreateChannel(th.BasicTeam) + channel1 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel1) - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel2) // And some categories - mutedCategory, err := th.App.CreateSidebarCategory(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ + mutedCategory, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ DisplayName: "muted", Muted: true, @@ -219,7 +218,7 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) require.True(t, mutedCategory.Muted) - unmutedCategory, err := th.App.CreateSidebarCategory(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ + unmutedCategory, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ DisplayName: "unmuted", Muted: false, @@ -230,7 +229,7 @@ func TestUpdateSidebarCategories(t *testing.T) { require.False(t, unmutedCategory.Muted) // Move the channels - _, err = th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + _, err = th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: mutedCategory.Id, @@ -251,15 +250,15 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) // Confirm that the channels are now muted - member1, err := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err := th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member1.IsChannelMuted()) - member2, err := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err := th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member2.IsChannelMuted()) // Move the channels back - _, err = th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + _, err = th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: mutedCategory.Id, @@ -280,10 +279,10 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) // Confirm that the channels are now unmuted - member1, err = th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err = th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member1.IsChannelMuted()) - member2, err = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member2.IsChannelMuted()) }) @@ -293,14 +292,14 @@ func TestUpdateSidebarCategories(t *testing.T) { defer th.TearDown() // Create some channels - channel1 := th.CreateChannel(th.BasicTeam) + channel1 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel1) - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel2) // And some categories - category1, err := th.App.CreateSidebarCategory(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ + category1, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ DisplayName: "category1", Muted: true, @@ -309,7 +308,7 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) require.True(t, category1.Muted) - category2, err := th.App.CreateSidebarCategory(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ + category2, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ DisplayName: "category2", Muted: true, @@ -320,7 +319,7 @@ func TestUpdateSidebarCategories(t *testing.T) { require.True(t, category2.Muted) // Move the unmuted channels - _, err = th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + _, err = th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: category1.Id, @@ -341,21 +340,21 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) // Confirm that the channels are still unmuted - member1, err := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err := th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member1.IsChannelMuted()) - member2, err := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err := th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member2.IsChannelMuted()) // Mute the channels manually - _, err = th.App.ToggleMuteChannel(channel1.Id, th.BasicUser.Id) + _, err = th.App.ToggleMuteChannel(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) - _, err = th.App.ToggleMuteChannel(channel2.Id, th.BasicUser.Id) + _, err = th.App.ToggleMuteChannel(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) // Move the muted channels back - _, err = th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + _, err = th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: category1.Id, @@ -376,10 +375,10 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) // Confirm that the channels are still muted - member1, err = th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err = th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member1.IsChannelMuted()) - member2, err = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member2.IsChannelMuted()) }) @@ -389,14 +388,14 @@ func TestUpdateSidebarCategories(t *testing.T) { defer th.TearDown() // Create some channels - channel1 := th.CreateChannel(th.BasicTeam) + channel1 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel1) - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel2) // And some categories - category1, err := th.App.CreateSidebarCategory(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ + category1, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ DisplayName: "category1", Muted: false, @@ -405,7 +404,7 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) require.False(t, category1.Muted) - category2, err := th.App.CreateSidebarCategory(th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ + category2, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ DisplayName: "category2", Muted: false, @@ -416,7 +415,7 @@ func TestUpdateSidebarCategories(t *testing.T) { require.False(t, category2.Muted) // Move the unmuted channels - _, err = th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + _, err = th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: category1.Id, @@ -437,21 +436,21 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) // Confirm that the channels are still unmuted - member1, err := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err := th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member1.IsChannelMuted()) - member2, err := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err := th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.False(t, member2.IsChannelMuted()) // Mute the channels manually - _, err = th.App.ToggleMuteChannel(channel1.Id, th.BasicUser.Id) + _, err = th.App.ToggleMuteChannel(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) - _, err = th.App.ToggleMuteChannel(channel2.Id, th.BasicUser.Id) + _, err = th.App.ToggleMuteChannel(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) // Move the muted channels back - _, err = th.App.UpdateSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ + _, err = th.App.UpdateSidebarCategories(th.Context, th.BasicUser.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{ { SidebarCategory: model.SidebarCategory{ Id: category1.Id, @@ -472,10 +471,10 @@ func TestUpdateSidebarCategories(t *testing.T) { require.Nil(t, err) // Confirm that the channels are still muted - member1, err = th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err = th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member1.IsChannelMuted()) - member2, err = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) assert.True(t, member2.IsChannelMuted()) }) diff --git a/app/channel_test.go b/app/channel_test.go index 49585bf754..d42d608f3c 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -37,7 +37,7 @@ func TestPermanentDeleteChannel(t *testing.T) { require.NotNil(t, channel, "Channel shouldn't be nil") require.Nil(t, err) defer func() { - th.App.PermanentDeleteChannel(channel) + th.App.PermanentDeleteChannel(th.Context, channel) }() incoming, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, channel, &model.IncomingWebhook{ChannelId: channel.Id}) @@ -62,7 +62,7 @@ func TestPermanentDeleteChannel(t *testing.T) { require.NotNil(t, outgoing, "Outgoing webhook should not be nil") require.Nil(t, err, "Unable to get new outgoing webhook") - err = th.App.PermanentDeleteChannel(channel) + err = th.App.PermanentDeleteChannel(th.Context, channel) require.Nil(t, err) incoming, err = th.App.GetIncomingWebhook(incoming.Id) @@ -80,10 +80,10 @@ func TestRemoveAllDeactivatedMembersFromChannel(t *testing.T) { var err *model.AppError team := th.CreateTeam() - channel := th.CreateChannel(team) + channel := th.CreateChannel(th.Context, team) defer func() { - th.App.PermanentDeleteChannel(channel) - th.App.PermanentDeleteTeam(team) + th.App.PermanentDeleteChannel(th.Context, channel) + th.App.PermanentDeleteTeam(th.Context, team) }() _, _, err = th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, "") @@ -92,18 +92,18 @@ func TestRemoveAllDeactivatedMembersFromChannel(t *testing.T) { deactivatedUser := th.CreateUser() _, _, err = th.App.AddUserToTeam(th.Context, team.Id, deactivatedUser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(deactivatedUser, channel, false) + _, err = th.App.AddUserToChannel(th.Context, deactivatedUser, channel, false) require.Nil(t, err) - channelMembers, err := th.App.GetChannelMembersPage(channel.Id, 0, 10000000) + channelMembers, err := th.App.GetChannelMembersPage(th.Context, channel.Id, 0, 10000000) require.Nil(t, err) require.Len(t, channelMembers, 2) _, err = th.App.UpdateActive(th.Context, deactivatedUser, false) require.Nil(t, err) - err = th.App.RemoveAllDeactivatedMembersFromChannel(channel) + err = th.App.RemoveAllDeactivatedMembersFromChannel(th.Context, channel) require.Nil(t, err) - channelMembers, err = th.App.GetChannelMembersPage(channel.Id, 0, 10000000) + channelMembers, err = th.App.GetChannelMembersPage(th.Context, channel.Id, 0, 10000000) require.Nil(t, err) require.Len(t, channelMembers, 1) } @@ -116,11 +116,11 @@ func TestMoveChannel(t *testing.T) { sourceTeam := th.CreateTeam() targetTeam := th.CreateTeam() - channel1 := th.CreateChannel(sourceTeam) + channel1 := th.CreateChannel(th.Context, sourceTeam) defer func() { - th.App.PermanentDeleteChannel(channel1) - th.App.PermanentDeleteTeam(sourceTeam) - th.App.PermanentDeleteTeam(targetTeam) + th.App.PermanentDeleteChannel(th.Context, channel1) + th.App.PermanentDeleteTeam(th.Context, sourceTeam) + th.App.PermanentDeleteTeam(th.Context, targetTeam) }() _, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, th.BasicUser.Id, "") @@ -132,10 +132,10 @@ func TestMoveChannel(t *testing.T) { _, _, err = th.App.AddUserToTeam(th.Context, targetTeam.Id, th.BasicUser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(th.BasicUser, channel1, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser, channel1, false) require.Nil(t, err) - _, err = th.App.AddUserToChannel(th.BasicUser2, channel1, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser2, channel1, false) require.Nil(t, err) err = th.App.MoveChannel(th.Context, targetTeam, channel1, th.BasicUser) @@ -150,15 +150,15 @@ func TestMoveChannel(t *testing.T) { // Test moving a channel with a deactivated user who isn't in the destination team. // It should fail, unless removeDeactivatedMembers is true. deactivatedUser := th.CreateUser() - channel2 := th.CreateChannel(sourceTeam) - defer th.App.PermanentDeleteChannel(channel2) + channel2 := th.CreateChannel(th.Context, sourceTeam) + defer th.App.PermanentDeleteChannel(th.Context, channel2) _, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, deactivatedUser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(th.BasicUser, channel2, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser, channel2, false) require.Nil(t, err) - _, err = th.App.AddUserToChannel(deactivatedUser, channel2, false) + _, err = th.App.AddUserToChannel(th.Context, deactivatedUser, channel2, false) require.Nil(t, err) _, err = th.App.UpdateActive(th.Context, deactivatedUser, false) @@ -178,7 +178,7 @@ func TestMoveChannel(t *testing.T) { channel3, err = th.App.CreateChannel(th.Context, channel3, false) require.Nil(t, err) - defer th.App.PermanentDeleteChannel(channel3) + defer th.App.PermanentDeleteChannel(th.Context, channel3) err = th.App.MoveChannel(th.Context, targetTeam, channel3, th.BasicUser) assert.Nil(t, err) @@ -190,14 +190,14 @@ func TestMoveChannel(t *testing.T) { sourceTeam := th.CreateTeam() targetTeam := th.CreateTeam() - channel := th.CreateChannel(sourceTeam) + channel := th.CreateChannel(th.Context, sourceTeam) th.LinkUserToTeam(th.BasicUser, sourceTeam) th.LinkUserToTeam(th.BasicUser, targetTeam) th.AddUserToChannel(th.BasicUser, channel) // Put the channel in a custom category so that it explicitly exists in SidebarChannels - category, err := th.App.CreateSidebarCategory(th.BasicUser.Id, sourceTeam.Id, &model.SidebarCategoryWithChannels{ + category, err := th.App.CreateSidebarCategory(th.Context, th.BasicUser.Id, sourceTeam.Id, &model.SidebarCategoryWithChannels{ SidebarCategory: model.SidebarCategory{ DisplayName: "new category", }, @@ -209,17 +209,17 @@ func TestMoveChannel(t *testing.T) { err = th.App.MoveChannel(th.Context, targetTeam, channel, th.BasicUser) require.Nil(t, err) - moved, err := th.App.GetChannel(channel.Id) + moved, err := th.App.GetChannel(th.Context, channel.Id) require.Nil(t, err) require.Equal(t, targetTeam.Id, moved.TeamId) // The channel should no longer be on the old team - updatedCategory, err := th.App.GetSidebarCategory(category.Id) + updatedCategory, err := th.App.GetSidebarCategory(th.Context, category.Id) require.Nil(t, err) assert.Equal(t, []string{}, updatedCategory.Channels) // And it should be on the new team instead - categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.BasicUser.Id, targetTeam.Id) + categories, err := th.App.GetSidebarCategoriesForTeamForUser(th.Context, th.BasicUser.Id, targetTeam.Id) require.Nil(t, err) require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type) assert.Contains(t, categories.Categories[1].Channels, channel.Id) @@ -232,11 +232,11 @@ func TestRemoveUsersFromChannelNotMemberOfTeam(t *testing.T) { team := th.CreateTeam() team2 := th.CreateTeam() - channel1 := th.CreateChannel(team) + channel1 := th.CreateChannel(th.Context, team) defer func() { - th.App.PermanentDeleteChannel(channel1) - th.App.PermanentDeleteTeam(team) - th.App.PermanentDeleteTeam(team2) + th.App.PermanentDeleteChannel(th.Context, channel1) + th.App.PermanentDeleteTeam(th.Context, team) + th.App.PermanentDeleteTeam(th.Context, team2) }() _, _, err := th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, "") @@ -246,15 +246,15 @@ func TestRemoveUsersFromChannelNotMemberOfTeam(t *testing.T) { _, _, err = th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser2.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(th.BasicUser, channel1, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser, channel1, false) require.Nil(t, err) - _, err = th.App.AddUserToChannel(th.BasicUser2, channel1, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser2, channel1, false) require.Nil(t, err) err = th.App.RemoveUsersFromChannelNotMemberOfTeam(th.Context, th.SystemAdminUser, channel1, team2) require.Nil(t, err) - channelMembers, err := th.App.GetChannelMembersPage(channel1.Id, 0, 10000000) + channelMembers, err := th.App.GetChannelMembersPage(th.Context, channel1.Id, 0, 10000000) require.Nil(t, err) require.Len(t, channelMembers, 1) members := make([]model.ChannelMember, len(channelMembers)) @@ -328,8 +328,8 @@ func TestJoinDefaultChannelsExperimentalDefaultChannels(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - basicChannel2 := th.CreateChannel(th.BasicTeam) - defer th.App.PermanentDeleteChannel(basicChannel2) + basicChannel2 := th.CreateChannel(th.Context, th.BasicTeam) + defer th.App.PermanentDeleteChannel(th.Context, basicChannel2) defaultChannelList := []string{th.BasicChannel.Name, basicChannel2.Name, basicChannel2.Name} th.App.Config().TeamSettings.ExperimentalDefaultChannels = defaultChannelList @@ -337,10 +337,10 @@ func TestJoinDefaultChannelsExperimentalDefaultChannels(t *testing.T) { th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "") for _, channelName := range defaultChannelList { - channel, err := th.App.GetChannelByName(channelName, th.BasicTeam.Id, false) + channel, err := th.App.GetChannelByName(th.Context, channelName, th.BasicTeam.Id, false) require.Nil(t, err, "Expected nil, didn't receive nil") - member, err := th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + member, err := th.App.GetChannelMember(th.Context, channel.Id, user.Id) require.NotNil(t, member, "Expected member object, got nil") require.Nil(t, err, "Expected nil object, didn't receive nil") @@ -352,7 +352,7 @@ func TestCreateChannelPublicCreatesChannelMemberHistoryRecord(t *testing.T) { defer th.TearDown() // creates a public channel and adds basic user to it - publicChannel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen) + publicChannel := th.createChannel(th.Context, th.BasicTeam, model.ChannelTypeOpen) // there should be a ChannelMemberHistory record for the user histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) @@ -367,7 +367,7 @@ func TestCreateChannelPrivateCreatesChannelMemberHistoryRecord(t *testing.T) { defer th.TearDown() // creates a private channel and adds basic user to it - privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate) + privateChannel := th.createChannel(th.Context, th.BasicTeam, model.ChannelTypePrivate) // there should be a ChannelMemberHistory record for the user histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id) @@ -381,7 +381,7 @@ func TestCreateChannelDisplayNameTrimsWhitespace(t *testing.T) { defer th.TearDown() channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) - defer th.App.PermanentDeleteChannel(channel) + defer th.App.PermanentDeleteChannel(th.Context, channel) require.Nil(t, err) require.Equal(t, channel.DisplayName, "Public 1") } @@ -390,7 +390,7 @@ func TestUpdateChannelPrivacy(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate) + privateChannel := th.createChannel(th.Context, th.BasicTeam, model.ChannelTypePrivate) privateChannel.Type = model.ChannelTypeOpen publicChannel, err := th.App.UpdateChannelPrivacy(th.Context, privateChannel, th.BasicUser) @@ -455,7 +455,7 @@ func TestCreateGroupChannelCreatesChannelMemberHistoryRecord(t *testing.T) { groupUserIds = append(groupUserIds, user2.Id) groupUserIds = append(groupUserIds, th.BasicUser.Id) - channel, err := th.App.CreateGroupChannel(groupUserIds, th.BasicUser.Id) + channel, err := th.App.CreateGroupChannel(th.Context, groupUserIds, th.BasicUser.Id) require.Nil(t, err, "Failed to create group channel.") histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) @@ -540,9 +540,9 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { groupUserIds = append(groupUserIds, th.BasicUser.Id) groupUserIds = append(groupUserIds, user.Id) - channel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen) + channel := th.createChannel(th.Context, th.BasicTeam, model.ChannelTypeOpen) - _, err = th.App.AddUserToChannel(user, channel, false) + _, err = th.App.AddUserToChannel(th.Context, user, channel, false) require.Nil(t, err, "Failed to add user to channel.") // there should be a ChannelMemberHistory record for the user @@ -564,7 +564,7 @@ func TestLeaveDefaultChannel(t *testing.T) { guest := th.CreateGuest() th.LinkUserToTeam(guest, th.BasicTeam) - townSquare, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, false) + townSquare, err := th.App.GetChannelByName(th.Context, "town-square", th.BasicTeam.Id, false) require.Nil(t, err) th.AddUserToChannel(guest, townSquare) th.AddUserToChannel(th.BasicUser, townSquare) @@ -573,14 +573,14 @@ func TestLeaveDefaultChannel(t *testing.T) { err = th.App.LeaveChannel(th.Context, townSquare.Id, th.BasicUser.Id) assert.NotNil(t, err, "It should fail to remove a regular user from the default channel") assert.Equal(t, err.Id, "api.channel.remove.default.app_error") - _, err = th.App.GetChannelMember(context.Background(), townSquare.Id, th.BasicUser.Id) + _, err = th.App.GetChannelMember(th.Context, townSquare.Id, th.BasicUser.Id) assert.Nil(t, err) }) t.Run("Guest leaves the default channel", func(t *testing.T) { err = th.App.LeaveChannel(th.Context, townSquare.Id, guest.Id) assert.Nil(t, err, "It should allow to remove a guest user from the default channel") - _, err = th.App.GetChannelMember(context.Background(), townSquare.Id, guest.Id) + _, err = th.App.GetChannelMember(th.Context, townSquare.Id, guest.Id) assert.NotNil(t, err) }) } @@ -592,7 +592,7 @@ func TestLeaveLastChannel(t *testing.T) { guest := th.CreateGuest() th.LinkUserToTeam(guest, th.BasicTeam) - townSquare, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, false) + townSquare, err := th.App.GetChannelByName(th.Context, "town-square", th.BasicTeam.Id, false) require.Nil(t, err) th.AddUserToChannel(guest, townSquare) th.AddUserToChannel(guest, th.BasicChannel) @@ -607,7 +607,7 @@ func TestLeaveLastChannel(t *testing.T) { t.Run("Guest leaves last channel", func(t *testing.T) { err = th.App.LeaveChannel(th.Context, th.BasicChannel.Id, guest.Id) assert.Nil(t, err, "It should allow to remove a guest user from the default channel") - _, err = th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, guest.Id) + _, err = th.App.GetChannelMember(th.Context, th.BasicChannel.Id, guest.Id) assert.NotNil(t, err) _, err = th.App.GetTeamMember(th.BasicTeam.Id, guest.Id) assert.Nil(t, err, "It should remove the team membership") @@ -627,7 +627,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { groupUserIds = append(groupUserIds, th.BasicUser.Id) groupUserIds = append(groupUserIds, user.Id) - channel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen) + channel := th.createChannel(th.Context, th.BasicTeam, model.ChannelTypeOpen) _, err = th.App.AddChannelMember(th.Context, user.Id, channel, ChannelMemberOpts{}) require.Nil(t, err, "Failed to add user to channel.") @@ -663,7 +663,7 @@ func TestAppUpdateChannelScheme(t *testing.T) { mockID := model.NewString("x") channel.SchemeId = mockID - updatedChannel, err := th.App.UpdateChannelScheme(channel) + updatedChannel, err := th.App.UpdateChannelScheme(th.Context, channel) require.Nil(t, err) if updatedChannel.SchemeId != mockID { @@ -678,45 +678,45 @@ func TestSetChannelsMuted(t *testing.T) { channel1 := th.BasicChannel - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel2) // Ensure that both channels start unmuted - member1, err := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err := th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) require.False(t, member1.IsChannelMuted()) - member2, err := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err := th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) require.False(t, member2.IsChannelMuted()) // Mute both channels - updated, err := th.App.setChannelsMuted([]string{channel1.Id, channel2.Id}, th.BasicUser.Id, true) + updated, err := th.App.setChannelsMuted(th.Context, []string{channel1.Id, channel2.Id}, th.BasicUser.Id, true) require.Nil(t, err) assert.True(t, updated[0].IsChannelMuted()) assert.True(t, updated[1].IsChannelMuted()) // Verify that the channels are muted in the database - member1, err = th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err = th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) require.True(t, member1.IsChannelMuted()) - member2, err = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) require.True(t, member2.IsChannelMuted()) // Unm both channels - updated, err = th.App.setChannelsMuted([]string{channel1.Id, channel2.Id}, th.BasicUser.Id, false) + updated, err = th.App.setChannelsMuted(th.Context, []string{channel1.Id, channel2.Id}, th.BasicUser.Id, false) require.Nil(t, err) assert.False(t, updated[0].IsChannelMuted()) assert.False(t, updated[1].IsChannelMuted()) // Verify that the channels are muted in the database - member1, err = th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + member1, err = th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) require.Nil(t, err) require.False(t, member1.IsChannelMuted()) - member2, err = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + member2, err = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) require.Nil(t, err) require.False(t, member2.IsChannelMuted()) }) @@ -728,15 +728,15 @@ func TestFillInChannelProps(t *testing.T) { channelPublic1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) - defer th.App.PermanentDeleteChannel(channelPublic1) + defer th.App.PermanentDeleteChannel(th.Context, channelPublic1) channelPublic2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) - defer th.App.PermanentDeleteChannel(channelPublic2) + defer th.App.PermanentDeleteChannel(th.Context, channelPublic2) channelPrivate, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Private", Name: "private", Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id}, false) require.Nil(t, err) - defer th.App.PermanentDeleteChannel(channelPrivate) + defer th.App.PermanentDeleteChannel(th.Context, channelPrivate) otherTeamId := model.NewId() otherTeam := &model.Team{ @@ -747,11 +747,11 @@ func TestFillInChannelProps(t *testing.T) { } otherTeam, err = th.App.CreateTeam(th.Context, otherTeam) require.Nil(t, err) - defer th.App.PermanentDeleteTeam(otherTeam) + defer th.App.PermanentDeleteTeam(th.Context, otherTeam) channelOtherTeam, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.ChannelTypeOpen, TeamId: otherTeam.Id}, false) require.Nil(t, err) - defer th.App.PermanentDeleteChannel(channelOtherTeam) + defer th.App.PermanentDeleteChannel(th.Context, channelOtherTeam) // Note that purpose is intentionally plaintext below. @@ -804,7 +804,7 @@ func TestFillInChannelProps(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.Description, func(t *testing.T) { - err = th.App.FillInChannelProps(testCase.Channel) + err = th.App.FillInChannelProps(th.Context, testCase.Channel) require.Nil(t, err) assert.Equal(t, testCase.ExpectedChannelProps, testCase.Channel.Props) @@ -916,7 +916,7 @@ func TestFillInChannelProps(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.Description, func(t *testing.T) { - err = th.App.FillInChannelsProps(testCase.Channels) + err = th.App.FillInChannelsProps(th.Context, testCase.Channels) require.Nil(t, err) for _, channel := range testCase.Channels { @@ -941,7 +941,7 @@ func TestRenameChannel(t *testing.T) { }{ { "Rename open channel", - th.createChannel(th.BasicTeam, model.ChannelTypeOpen), + th.createChannel(th.Context, th.BasicTeam, model.ChannelTypeOpen), false, "newchannelname", "newchannelname", @@ -949,7 +949,7 @@ func TestRenameChannel(t *testing.T) { }, { "Fail on rename open channel with bad name", - th.createChannel(th.BasicTeam, model.ChannelTypeOpen), + th.createChannel(th.Context, th.BasicTeam, model.ChannelTypeOpen), true, "6zii9a9g6pruzj451x3esok54h__wr4j4g8zqtnhmkw771pfpynqwo", "", @@ -957,7 +957,7 @@ func TestRenameChannel(t *testing.T) { }, { "Success on rename open channel with consecutive underscores in name", - th.createChannel(th.BasicTeam, model.ChannelTypeOpen), + th.createChannel(th.Context, th.BasicTeam, model.ChannelTypeOpen), false, "foo__bar", "foo__bar", @@ -973,7 +973,7 @@ func TestRenameChannel(t *testing.T) { }, { "Fail on rename group message channel", - th.CreateGroupChannel(th.BasicUser2, th.CreateUser()), + th.CreateGroupChannel(th.Context, th.BasicUser2, th.CreateUser()), true, "newchannelname", "", @@ -983,7 +983,7 @@ func TestRenameChannel(t *testing.T) { for _, tc := range testCases { t.Run(tc.Name, func(t *testing.T) { - channel, err := th.App.RenameChannel(tc.Channel, tc.ChannelName, "New Display Name") + channel, err := th.App.RenameChannel(th.Context, tc.Channel, tc.ChannelName, "New Display Name") if tc.ExpectError { assert.NotNil(t, err) } else { @@ -1012,16 +1012,16 @@ func TestGetChannelMembersTimezones(t *testing.T) { user3 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} ruser, _ := th.App.CreateUser(th.Context, &user3) - th.App.AddUserToChannel(ruser, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, ruser, th.BasicChannel, false) ruser.Timezone["automaticTimezone"] = "NoWhere/Island" th.App.UpdateUser(ruser, false) user4 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} ruser, _ = th.App.CreateUser(th.Context, &user4) - th.App.AddUserToChannel(ruser, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, ruser, th.BasicChannel, false) - timezones, err := th.App.GetChannelMembersTimezones(th.BasicChannel.Id) + timezones, err := th.App.GetChannelMembersTimezones(th.Context, th.BasicChannel.Id) require.Nil(t, err, "Failed to get the timezones for a channel.") assert.Equal(t, 2, len(timezones)) @@ -1037,10 +1037,10 @@ func TestGetChannelsForUser(t *testing.T) { TeamId: th.BasicTeam.Id, } th.App.CreateChannel(th.Context, channel, true) - defer th.App.PermanentDeleteChannel(channel) + defer th.App.PermanentDeleteChannel(th.Context, channel) defer th.TearDown() - channelList, err := th.App.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, &model.ChannelSearchOpts{ + channelList, err := th.App.GetChannelsForTeamForUser(th.Context, th.BasicTeam.Id, th.BasicUser.Id, &model.ChannelSearchOpts{ IncludeDeleted: false, LastDeleteAt: 0, }) @@ -1050,7 +1050,7 @@ func TestGetChannelsForUser(t *testing.T) { th.App.DeleteChannel(th.Context, channel, th.BasicUser.Id) // Now we get all the non-archived channels for the user - channelList, err = th.App.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, &model.ChannelSearchOpts{ + channelList, err = th.App.GetChannelsForTeamForUser(th.Context, th.BasicTeam.Id, th.BasicUser.Id, &model.ChannelSearchOpts{ IncludeDeleted: false, LastDeleteAt: 0, }) @@ -1058,7 +1058,7 @@ func TestGetChannelsForUser(t *testing.T) { require.Len(t, channelList, 3) // Now we get all the channels, even though are archived, for the user - channelList, err = th.App.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, &model.ChannelSearchOpts{ + channelList, err = th.App.GetChannelsForTeamForUser(th.Context, th.BasicTeam.Id, th.BasicUser.Id, &model.ChannelSearchOpts{ IncludeDeleted: true, LastDeleteAt: 0, }) @@ -1073,12 +1073,12 @@ func TestGetPublicChannelsForTeam(t *testing.T) { var expectedChannels []*model.Channel - townSquare, err := th.App.GetChannelByName("town-square", team.Id, false) + townSquare, err := th.App.GetChannelByName(th.Context, "town-square", team.Id, false) require.Nil(t, err) require.NotNil(t, townSquare) expectedChannels = append(expectedChannels, townSquare) - offTopic, err := th.App.GetChannelByName("off-topic", team.Id, false) + offTopic, err := th.App.GetChannelByName(th.Context, "off-topic", team.Id, false) require.Nil(t, err) require.NotNil(t, offTopic) expectedChannels = append(expectedChannels, offTopic) @@ -1094,16 +1094,16 @@ func TestGetPublicChannelsForTeam(t *testing.T) { rchannel, err = th.App.CreateChannel(th.Context, &channel, false) require.Nil(t, err) require.NotNil(t, rchannel) - defer th.App.PermanentDeleteChannel(rchannel) + defer th.App.PermanentDeleteChannel(th.Context, rchannel) // Store the user ids for comparison later expectedChannels = append(expectedChannels, rchannel) } // Fetch public channels multiple times - channelList, err := th.App.GetPublicChannelsForTeam(team.Id, 0, 5) + channelList, err := th.App.GetPublicChannelsForTeam(th.Context, team.Id, 0, 5) require.Nil(t, err) - channelList2, err := th.App.GetPublicChannelsForTeam(team.Id, 5, 5) + channelList2, err := th.App.GetPublicChannelsForTeam(th.Context, team.Id, 5, 5) require.Nil(t, err) channels := append(channelList, channelList2...) @@ -1127,16 +1127,16 @@ func TestGetPrivateChannelsForTeam(t *testing.T) { rchannel, err := th.App.CreateChannel(th.Context, &channel, false) require.Nil(t, err) require.NotNil(t, rchannel) - defer th.App.PermanentDeleteChannel(rchannel) + defer th.App.PermanentDeleteChannel(th.Context, rchannel) // Store the user ids for comparison later expectedChannels = append(expectedChannels, rchannel) } // Fetch private channels multiple times - channelList, err := th.App.GetPrivateChannelsForTeam(team.Id, 0, 5) + channelList, err := th.App.GetPrivateChannelsForTeam(th.Context, team.Id, 0, 5) require.Nil(t, err) - channelList2, err := th.App.GetPrivateChannelsForTeam(team.Id, 5, 5) + channelList2, err := th.App.GetPrivateChannelsForTeam(th.Context, team.Id, 5, 5) require.Nil(t, err) channels := append(channelList, channelList2...) @@ -1154,10 +1154,10 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) + _, err = th.App.AddUserToChannel(th.Context, ruser, th.BasicChannel, false) require.Nil(t, err) - _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_user") + _, err = th.App.UpdateChannelMemberRoles(th.Context, th.BasicChannel.Id, ruser.Id, "channel_user") require.NotNil(t, err, "Should fail when try to modify the guest role") }) @@ -1168,10 +1168,10 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) + _, err = th.App.AddUserToChannel(th.Context, ruser, th.BasicChannel, false) require.Nil(t, err) - _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_guest") + _, err = th.App.UpdateChannelMemberRoles(th.Context, th.BasicChannel.Id, ruser.Id, "channel_guest") require.NotNil(t, err, "Should fail when try to modify the guest role") }) @@ -1182,10 +1182,10 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) + _, err = th.App.AddUserToChannel(th.Context, ruser, th.BasicChannel, false) require.Nil(t, err) - _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_user channel_admin") + _, err = th.App.UpdateChannelMemberRoles(th.Context, th.BasicChannel.Id, ruser.Id, "channel_user channel_admin") require.Nil(t, err, "Should work when you not modify guest role") }) @@ -1196,13 +1196,13 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) + _, err = th.App.AddUserToChannel(th.Context, ruser, th.BasicChannel, false) require.Nil(t, err) _, err = th.App.CreateRole(&model.Role{Name: "custom", DisplayName: "custom", Description: "custom"}) require.Nil(t, err) - _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_guest custom") + _, err = th.App.UpdateChannelMemberRoles(th.Context, th.BasicChannel.Id, ruser.Id, "channel_guest custom") require.Nil(t, err, "Should work when you not modify guest role") }) @@ -1213,10 +1213,10 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) { _, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "") require.Nil(t, err) - _, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false) + _, err = th.App.AddUserToChannel(th.Context, ruser, th.BasicChannel, false) require.Nil(t, err) - _, err = th.App.UpdateChannelMemberRoles(th.BasicChannel.Id, ruser.Id, "channel_guest channel_user") + _, err = th.App.UpdateChannelMemberRoles(th.Context, th.BasicChannel.Id, ruser.Id, "channel_guest channel_user") require.NotNil(t, err, "Should work when you not modify guest role") }) } @@ -1225,7 +1225,7 @@ func TestDefaultChannelNames(t *testing.T) { th := Setup(t) defer th.TearDown() - actual := th.App.DefaultChannelNames() + actual := th.App.DefaultChannelNames(th.Context) expect := []string{"town-square", "off-topic"} require.ElementsMatch(t, expect, actual) @@ -1233,7 +1233,7 @@ func TestDefaultChannelNames(t *testing.T) { cfg.TeamSettings.ExperimentalDefaultChannels = []string{"foo", "bar"} }) - actual = th.App.DefaultChannelNames() + actual = th.App.DefaultChannelNames(th.Context) expect = []string{"town-square", "foo", "bar"} require.ElementsMatch(t, expect, actual) } @@ -1252,19 +1252,19 @@ func TestSearchChannelsForUser(t *testing.T) { require.Nil(t, err) defer func() { - th.App.PermanentDeleteChannel(c1) - th.App.PermanentDeleteChannel(c2) - th.App.PermanentDeleteChannel(c3) + th.App.PermanentDeleteChannel(th.Context, c1) + th.App.PermanentDeleteChannel(th.Context, c2) + th.App.PermanentDeleteChannel(th.Context, c3) }() // add user to test-dev-1 and dev3 - _, err = th.App.AddUserToChannel(th.BasicUser, c1, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser, c1, false) require.Nil(t, err) - _, err = th.App.AddUserToChannel(th.BasicUser, c3, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser, c3, false) require.Nil(t, err) searchAndCheck := func(t *testing.T, term string, expectedDisplayNames []string) { - res, searchErr := th.App.SearchChannelsForUser(th.BasicUser.Id, th.BasicTeam.Id, term) + res, searchErr := th.App.SearchChannelsForUser(th.Context, th.BasicUser.Id, th.BasicTeam.Id, term) require.Nil(t, searchErr) require.Len(t, res, len(expectedDisplayNames)) @@ -1284,7 +1284,7 @@ func TestSearchChannelsForUser(t *testing.T) { }) t.Run("After adding user to test-dev-2, search for dev, the three channels should be returned", func(t *testing.T) { - _, err = th.App.AddUserToChannel(th.BasicUser, c2, false) + _, err = th.App.AddUserToChannel(th.Context, th.BasicUser, c2, false) require.Nil(t, err) searchAndCheck(t, "dev", []string{"test-dev-1", "test-dev-2", "dev-3"}) @@ -1298,7 +1298,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { u1 := th.BasicUser u2 := th.BasicUser2 c1 := th.BasicChannel - pc1 := th.CreatePrivateChannel(th.BasicTeam) + pc1 := th.CreatePrivateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(u2, c1) th.AddUserToChannel(u1, pc1) th.AddUserToChannel(u2, pc1) @@ -1311,81 +1311,81 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { require.NotNil(t, pp1) pp2 := th.CreatePost(pc1) - unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, c1.Id, u1.Id) require.Nil(t, err) require.Equal(t, int64(4), unread.MsgCount) - unread, err = th.App.GetChannelUnread(c1.Id, u2.Id) + unread, err = th.App.GetChannelUnread(th.Context, c1.Id, u2.Id) require.Nil(t, err) require.Equal(t, int64(4), unread.MsgCount) - _, err = th.App.MarkChannelsAsViewed([]string{c1.Id, pc1.Id}, u1.Id, "", false) + _, err = th.App.MarkChannelsAsViewed(th.Context, []string{c1.Id, pc1.Id}, u1.Id, "", false) require.Nil(t, err) - _, err = th.App.MarkChannelsAsViewed([]string{c1.Id, pc1.Id}, u2.Id, "", false) + _, err = th.App.MarkChannelsAsViewed(th.Context, []string{c1.Id, pc1.Id}, u2.Id, "", false) require.Nil(t, err) - unread, err = th.App.GetChannelUnread(c1.Id, u2.Id) + unread, err = th.App.GetChannelUnread(th.Context, c1.Id, u2.Id) require.Nil(t, err) require.Equal(t, int64(0), unread.MsgCount) t.Run("Unread but last one", func(t *testing.T) { - response, err := th.App.MarkChannelAsUnreadFromPost(p2.Id, u1.Id, true) + response, err := th.App.MarkChannelAsUnreadFromPost(th.Context, p2.Id, u1.Id, true) require.Nil(t, err) require.NotNil(t, response) assert.Equal(t, int64(2), response.MsgCount) - unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, c1.Id, u1.Id) require.Nil(t, err) assert.Equal(t, int64(2), unread.MsgCount) assert.Equal(t, p2.CreateAt-1, response.LastViewedAt) }) t.Run("Unread last one", func(t *testing.T) { - response, err := th.App.MarkChannelAsUnreadFromPost(p3.Id, u1.Id, true) + response, err := th.App.MarkChannelAsUnreadFromPost(th.Context, p3.Id, u1.Id, true) require.Nil(t, err) require.NotNil(t, response) assert.Equal(t, int64(3), response.MsgCount) - unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, c1.Id, u1.Id) require.Nil(t, err) assert.Equal(t, int64(1), unread.MsgCount) assert.Equal(t, p3.CreateAt-1, response.LastViewedAt) }) t.Run("Unread first one", func(t *testing.T) { - response, err := th.App.MarkChannelAsUnreadFromPost(p1.Id, u1.Id, true) + response, err := th.App.MarkChannelAsUnreadFromPost(th.Context, p1.Id, u1.Id, true) require.Nil(t, err) require.NotNil(t, response) assert.Equal(t, int64(1), response.MsgCount) - unread, err := th.App.GetChannelUnread(c1.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, c1.Id, u1.Id) require.Nil(t, err) assert.Equal(t, int64(3), unread.MsgCount) assert.Equal(t, p1.CreateAt-1, response.LastViewedAt) }) t.Run("Other users are unaffected", func(t *testing.T) { - unread, err := th.App.GetChannelUnread(c1.Id, u2.Id) + unread, err := th.App.GetChannelUnread(th.Context, c1.Id, u2.Id) require.Nil(t, err) assert.Equal(t, int64(0), unread.MsgCount) }) t.Run("Unread on a private channel", func(t *testing.T) { - response, err := th.App.MarkChannelAsUnreadFromPost(pp1.Id, u1.Id, true) + response, err := th.App.MarkChannelAsUnreadFromPost(th.Context, pp1.Id, u1.Id, true) require.Nil(t, err) require.NotNil(t, response) assert.Equal(t, int64(0), response.MsgCount) - unread, err := th.App.GetChannelUnread(pc1.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, pc1.Id, u1.Id) require.Nil(t, err) assert.Equal(t, int64(2), unread.MsgCount) assert.Equal(t, pp1.CreateAt-1, response.LastViewedAt) - response, err = th.App.MarkChannelAsUnreadFromPost(pp2.Id, u1.Id, true) + response, err = th.App.MarkChannelAsUnreadFromPost(th.Context, pp2.Id, u1.Id, true) assert.Nil(t, err) assert.Equal(t, int64(1), response.MsgCount) - unread, err = th.App.GetChannelUnread(pc1.Id, u1.Id) + unread, err = th.App.GetChannelUnread(th.Context, pc1.Id, u1.Id) require.Nil(t, err) assert.Equal(t, int64(1), unread.MsgCount) assert.Equal(t, pp2.CreateAt-1, response.LastViewedAt) }) t.Run("Unread with mentions", func(t *testing.T) { - c2 := th.CreateChannel(th.BasicTeam) - _, err := th.App.AddUserToChannel(u2, c2, false) + c2 := th.CreateChannel(th.Context, th.BasicTeam) + _, err := th.App.AddUserToChannel(th.Context, u2, c2, false) require.Nil(t, err) p4, err := th.App.CreatePost(th.Context, &model.Post{ @@ -1403,13 +1403,13 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { Message: "@" + u1.Username, }, c2, false, true) - response, err := th.App.MarkChannelAsUnreadFromPost(p4.Id, u1.Id, true) + response, err := th.App.MarkChannelAsUnreadFromPost(th.Context, p4.Id, u1.Id, true) assert.Nil(t, err) assert.Equal(t, int64(1), response.MsgCount) assert.Equal(t, int64(2), response.MentionCount) assert.Equal(t, int64(1), response.MentionCountRoot) - unread, err := th.App.GetChannelUnread(c2.Id, u1.Id) + unread, err := th.App.GetChannelUnread(th.Context, c2.Id, u1.Id) require.Nil(t, err) assert.Equal(t, int64(2), unread.MsgCount) assert.Equal(t, int64(2), unread.MentionCount) @@ -1426,13 +1426,13 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { _, err := th.App.CreatePost(th.Context, &model.Post{ChannelId: dc.Id, UserId: th.BasicUser.Id, Message: "testReply", RootId: dm1.Id}, dc, false, false) assert.Nil(t, err) - response, err := th.App.MarkChannelAsUnreadFromPost(dm1.Id, u2.Id, true) + response, err := th.App.MarkChannelAsUnreadFromPost(th.Context, dm1.Id, u2.Id, true) assert.Nil(t, err) assert.Equal(t, int64(0), response.MsgCount) assert.Equal(t, int64(4), response.MentionCount) assert.Equal(t, int64(3), response.MentionCountRoot) - unread, err := th.App.GetChannelUnread(dc.Id, u2.Id) + unread, err := th.App.GetChannelUnread(th.Context, dc.Id, u2.Id) require.Nil(t, err) assert.Equal(t, int64(4), unread.MsgCount) assert.Equal(t, int64(4), unread.MentionCount) @@ -1440,7 +1440,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) { }) t.Run("Can't unread an imaginary post", func(t *testing.T) { - response, err := th.App.MarkChannelAsUnreadFromPost("invalid4ofngungryquinj976y", u1.Id, true) + response, err := th.App.MarkChannelAsUnreadFromPost(th.Context, "invalid4ofngungryquinj976y", u1.Id, true) assert.NotNil(t, err) assert.Nil(t, response) }) @@ -1478,7 +1478,7 @@ func TestAddUserToChannel(t *testing.T) { require.Nil(t, err) // verify user was added as a non-admin - cm1, err := th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, ruser1.Id) + cm1, err := th.App.GetChannelMember(th.Context, th.BasicChannel.Id, ruser1.Id) require.Nil(t, err) require.False(t, cm1.SchemeAdmin) @@ -1498,17 +1498,17 @@ func TestAddUserToChannel(t *testing.T) { require.Nil(t, err) // Should allow a bot to be added to a public group synced channel - _, err = th.App.AddUserToChannel(botUser, th.BasicChannel, false) + _, err = th.App.AddUserToChannel(th.Context, botUser, th.BasicChannel, false) require.Nil(t, err) // verify user was added as an admin - cm2, err := th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, ruser2.Id) + cm2, err := th.App.GetChannelMember(th.Context, th.BasicChannel.Id, ruser2.Id) require.Nil(t, err) require.True(t, cm2.SchemeAdmin) - privateChannel := th.CreatePrivateChannel(th.BasicTeam) + privateChannel := th.CreatePrivateChannel(th.Context, th.BasicTeam) privateChannel.GroupConstrained = model.NewBool(true) - _, err = th.App.UpdateChannel(privateChannel) + _, err = th.App.UpdateChannel(th.Context, privateChannel) require.Nil(t, err) _, err = th.App.UpsertGroupSyncable(&model.GroupSyncable{ @@ -1519,11 +1519,11 @@ func TestAddUserToChannel(t *testing.T) { require.Nil(t, err) // Should allow a group synced user to be added to a group synced private channel - _, err = th.App.AddUserToChannel(ruser1, privateChannel, false) + _, err = th.App.AddUserToChannel(th.Context, ruser1, privateChannel, false) require.Nil(t, err) // Should allow a bot to be added to a private group synced channel - _, err = th.App.AddUserToChannel(botUser, privateChannel, false) + _, err = th.App.AddUserToChannel(th.Context, botUser, privateChannel, false) require.Nil(t, err) } @@ -1542,11 +1542,11 @@ func TestRemoveUserFromChannel(t *testing.T) { th.App.AddTeamMember(th.Context, th.BasicTeam.Id, ruser.Id) th.App.AddTeamMember(th.Context, th.BasicTeam.Id, bot.UserId) - privateChannel := th.CreatePrivateChannel(th.BasicTeam) + privateChannel := th.CreatePrivateChannel(th.Context, th.BasicTeam) - _, err := th.App.AddUserToChannel(ruser, privateChannel, false) + _, err := th.App.AddUserToChannel(th.Context, ruser, privateChannel, false) require.Nil(t, err) - _, err = th.App.AddUserToChannel(botUser, privateChannel, false) + _, err = th.App.AddUserToChannel(th.Context, botUser, privateChannel, false) require.Nil(t, err) group := th.CreateGroup() @@ -1561,7 +1561,7 @@ func TestRemoveUserFromChannel(t *testing.T) { require.Nil(t, err) privateChannel.GroupConstrained = model.NewBool(true) - _, err = th.App.UpdateChannel(privateChannel) + _, err = th.App.UpdateChannel(th.Context, privateChannel) require.Nil(t, err) // Should not allow a group synced user to be removed from channel @@ -1867,7 +1867,7 @@ func TestPatchChannelModerationsForChannel(t *testing.T) { higherScopedPermissionsOverridden := tc.HigherScopedMemberPermissions != nil || tc.HigherScopedGuestPermissions != nil // If the test case restricts higher scoped permissions. if higherScopedPermissionsOverridden { - higherScopedGuestRoleName, higherScopedMemberRoleName, _, _ := th.App.GetTeamSchemeChannelRoles(channel.TeamId) + higherScopedGuestRoleName, higherScopedMemberRoleName, _, _ := th.App.GetTeamSchemeChannelRoles(th.Context, channel.TeamId) if tc.HigherScopedMemberPermissions != nil { higherScopedMemberRole, err := th.App.GetRoleByName(context.Background(), higherScopedMemberRoleName) require.Nil(t, err) @@ -1887,14 +1887,14 @@ func TestPatchChannelModerationsForChannel(t *testing.T) { } } - moderations, appErr := th.App.PatchChannelModerationsForChannel(channel, tc.ChannelModerationsPatch) + moderations, appErr := th.App.PatchChannelModerationsForChannel(th.Context, channel, tc.ChannelModerationsPatch) if tc.ShouldError { require.NotNil(t, appErr) return } require.Nil(t, appErr) - updatedChannel, _ := th.App.GetChannel(channel.Id) + updatedChannel, _ := th.App.GetChannel(th.Context, channel.Id) if tc.ShouldHaveNoChannelScheme { require.Nil(t, updatedChannel.SchemeId) } else { @@ -1923,7 +1923,7 @@ func TestPatchChannelModerationsForChannel(t *testing.T) { } if tc.RevertChannelModerationsPatch != nil { - th.App.PatchChannelModerationsForChannel(channel, tc.RevertChannelModerationsPatch) + th.App.PatchChannelModerationsForChannel(th.Context, channel, tc.RevertChannelModerationsPatch) } }) } @@ -1952,21 +1952,21 @@ func TestPatchChannelModerationsForChannel(t *testing.T) { wg.Add(20) for i := 0; i < 10; i++ { go func() { - th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), addCreatePosts) - th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), removeCreatePosts) + th.App.PatchChannelModerationsForChannel(th.Context, channel.DeepCopy(), addCreatePosts) + th.App.PatchChannelModerationsForChannel(th.Context, channel.DeepCopy(), removeCreatePosts) wg.Done() }() } for i := 0; i < 10; i++ { go func() { - th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), addCreatePosts) - th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), removeCreatePosts) + th.App.PatchChannelModerationsForChannel(th.Context, channel.DeepCopy(), addCreatePosts) + th.App.PatchChannelModerationsForChannel(th.Context, channel.DeepCopy(), removeCreatePosts) wg.Done() }() } wg.Wait() - higherScopedGuestRoleName, higherScopedMemberRoleName, _, _ := th.App.GetTeamSchemeChannelRoles(channel.TeamId) + higherScopedGuestRoleName, higherScopedMemberRoleName, _, _ := th.App.GetTeamSchemeChannelRoles(th.Context, channel.TeamId) higherScopedMemberRole, _ := th.App.GetRoleByName(context.Background(), higherScopedMemberRoleName) higherScopedGuestRole, _ := th.App.GetRoleByName(context.Background(), higherScopedGuestRoleName) assert.Contains(t, higherScopedMemberRole.Permissions, createPosts) @@ -1993,13 +1993,13 @@ func TestPatchChannelModerationsForChannel(t *testing.T) { mockSession := model.Session{UserId: user.Id} - _, err := th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), addCreatePosts) + _, err := th.App.PatchChannelModerationsForChannel(th.Context, channel.DeepCopy(), addCreatePosts) require.Nil(t, err) - require.True(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PermissionCreatePost)) + require.True(t, th.App.SessionHasPermissionToChannel(th.Context, mockSession, channel.Id, model.PermissionCreatePost)) - _, err = th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), removeCreatePosts) + _, err = th.App.PatchChannelModerationsForChannel(th.Context, channel.DeepCopy(), removeCreatePosts) require.Nil(t, err) - require.False(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PermissionCreatePost)) + require.False(t, th.App.SessionHasPermissionToChannel(th.Context, mockSession, channel.Id, model.PermissionCreatePost)) }) } @@ -2041,7 +2041,7 @@ func TestMarkChannelsAsViewedPanic(t *testing.T) { mockThreadStore.On("MarkAllAsReadByChannels", "userID", []string{"channelID"}).Return(nil) mockStore.On("Thread").Return(&mockThreadStore) - _, appErr := th.App.MarkChannelsAsViewed([]string{"channelID"}, "userID", th.Context.Session().Id, false) + _, appErr := th.App.MarkChannelsAsViewed(th.Context, []string{"channelID"}, "userID", th.Context.Session().Id, false) require.Nil(t, appErr) } @@ -2065,7 +2065,7 @@ func TestClearChannelMembersCache(t *testing.T) { mockStore.On("Channel").Return(&mockChannelStore) mockStore.On("GetDBSchemaVersion").Return(1, nil) - th.App.ClearChannelMembersCache("channelID") + th.App.ClearChannelMembersCache(th.Context, "channelID") } func TestGetMemberCountsByGroup(t *testing.T) { @@ -2152,7 +2152,7 @@ func TestViewChannelCollapsedThreadsTurnedOff(t *testing.T) { require.Truef(t, found, "did not find created thread in user's threads") // Mark channel as read from a client that supports CRT - _, appErr = th.App.MarkChannelsAsViewed([]string{c1.Id}, u1.Id, th.Context.Session().Id, true) + _, appErr = th.App.MarkChannelsAsViewed(th.Context, []string{c1.Id}, u1.Id, th.Context.Session().Id, true) require.Nil(t, appErr) // Thread should be marked as read because CRT has been turned off by user @@ -2219,11 +2219,11 @@ func TestMarkChannelAsUnreadFromPostCollapsedThreadsTurnedOff(t *testing.T) { require.Nil(t, appErr) t.Run("Mark reply post as unread", func(t *testing.T) { - _, err := th.App.MarkChannelAsUnreadFromPost(replyPost1.Id, th.BasicUser.Id, true) + _, err := th.App.MarkChannelAsUnreadFromPost(th.Context, replyPost1.Id, th.BasicUser.Id, true) require.Nil(t, err) // Get channel unreads // Easier to reason with ChannelUnread now, than channelUnreadAt from the previous call - channelUnread, err := th.App.GetChannelUnread(th.BasicChannel.Id, th.BasicUser.Id) + channelUnread, err := th.App.GetChannelUnread(th.Context, th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, err) require.Equal(t, int64(3), channelUnread.MentionCount) @@ -2243,11 +2243,11 @@ func TestMarkChannelAsUnreadFromPostCollapsedThreadsTurnedOff(t *testing.T) { }) t.Run("Mark root post as unread", func(t *testing.T) { - _, err := th.App.MarkChannelAsUnreadFromPost(rootPost1.Id, th.BasicUser.Id, true) + _, err := th.App.MarkChannelAsUnreadFromPost(th.Context, rootPost1.Id, th.BasicUser.Id, true) require.Nil(t, err) // Get channel unreads // Easier to reason with ChannelUnread now, than channelUnreadAt from the previous call - channelUnread, err := th.App.GetChannelUnread(th.BasicChannel.Id, th.BasicUser.Id) + channelUnread, err := th.App.GetChannelUnread(th.Context, th.BasicChannel.Id, th.BasicUser.Id) require.Nil(t, err) require.Equal(t, int64(4), channelUnread.MentionCount) @@ -2287,7 +2287,7 @@ func TestMarkUnreadCRTOffUpdatesThreads(t *testing.T) { th.LinkUserToTeam(user3, th.BasicTeam) th.AddUserToChannel(user3, th.BasicChannel) - _, appErr = th.App.MarkChannelAsUnreadFromPost(editedPost.Id, user3.Id, false) + _, appErr = th.App.MarkChannelAsUnreadFromPost(th.Context, editedPost.Id, user3.Id, false) require.Nil(t, appErr) threadMembership, appErr := th.App.GetThreadMembershipForUser(user3.Id, rootPost.Id) require.Nil(t, appErr) @@ -2370,7 +2370,7 @@ func TestIsCRTEnabledForUser(t *testing.T) { mockPreferenceStore.On("Get", mock.Anything, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled).Return(&model.Preference{Value: tc.pref.val}, tc.pref.err) mockStore.On("Preference").Return(&mockPreferenceStore) - res := th.App.IsCRTEnabledForUser(mock.Anything) + res := th.App.IsCRTEnabledForUser(th.Context, mock.Anything) assert.Equal(t, tc.expected, res) }) @@ -2381,7 +2381,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) // add a bot post to ensure it's not counted _, err := th.Server.Store.Post().Save(&model.Post{ @@ -2394,7 +2394,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { }) require.NoError(t, err) - channel3 := th.CreatePrivateChannel(th.BasicTeam) + channel3 := th.CreatePrivateChannel(th.Context, th.BasicTeam) // add a webhook post to ensure it's not counted _, err = th.Server.Store.Post().Save(&model.Post{ @@ -2407,9 +2407,9 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { }) require.NoError(t, err) - channel4 := th.CreatePrivateChannel(th.BasicTeam) - channel5 := th.CreateChannel(th.BasicTeam) - channel6 := th.CreatePrivateChannel(th.BasicTeam) + channel4 := th.CreatePrivateChannel(th.Context, th.BasicTeam) + channel5 := th.CreateChannel(th.Context, th.BasicTeam) + channel6 := th.CreatePrivateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel2) th.AddUserToChannel(th.BasicUser, channel3) th.AddUserToChannel(th.BasicUser, channel4) @@ -2440,7 +2440,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { timeRange := model.StartOfDayForTimeRange(model.TimeRangeToday, time.Now().Location()) t.Run("get-top-channels-for-team-since", func(t *testing.T) { - topChannels, err := th.App.GetTopChannelsForTeamSince(th.BasicChannel.TeamId, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 0, PerPage: 5}) + topChannels, err := th.App.GetTopChannelsForTeamSince(th.Context, th.BasicChannel.TeamId, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 0, PerPage: 5}) require.Nil(t, err) for i, channel := range topChannels.Items { @@ -2448,7 +2448,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { assert.Equal(t, expectedTopChannels[i].MessageCount, channel.MessageCount) } - topChannels, err = th.App.GetTopChannelsForTeamSince(th.BasicChannel.TeamId, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 1, PerPage: 5}) + topChannels, err = th.App.GetTopChannelsForTeamSince(th.Context, th.BasicChannel.TeamId, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 1, PerPage: 5}) require.Nil(t, err) assert.Equal(t, channel6.Id, topChannels.Items[0].ID) assert.Equal(t, int64(1), topChannels.Items[0].MessageCount) @@ -2459,7 +2459,7 @@ func TestGetTopChannelsForUserSince(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) // add a bot post to ensure it's not counted _, err := th.Server.Store.Post().Save(&model.Post{ @@ -2472,7 +2472,7 @@ func TestGetTopChannelsForUserSince(t *testing.T) { }) require.NoError(t, err) - channel3 := th.CreatePrivateChannel(th.BasicTeam) + channel3 := th.CreatePrivateChannel(th.Context, th.BasicTeam) // add a webhook post to ensure it's not counted _, err = th.Server.Store.Post().Save(&model.Post{ @@ -2485,9 +2485,9 @@ func TestGetTopChannelsForUserSince(t *testing.T) { }) require.NoError(t, err) - channel4 := th.CreatePrivateChannel(th.BasicTeam) - channel5 := th.CreateChannel(th.BasicTeam) - channel6 := th.CreatePrivateChannel(th.BasicTeam) + channel4 := th.CreatePrivateChannel(th.Context, th.BasicTeam) + channel5 := th.CreateChannel(th.Context, th.BasicTeam) + channel6 := th.CreatePrivateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channel2) th.AddUserToChannel(th.BasicUser, channel3) th.AddUserToChannel(th.BasicUser, channel4) @@ -2518,7 +2518,7 @@ func TestGetTopChannelsForUserSince(t *testing.T) { timeRange := model.StartOfDayForTimeRange(model.TimeRangeToday, time.Now().Location()) t.Run("get-top-channels-for-user-since", func(t *testing.T) { - topChannels, err := th.App.GetTopChannelsForUserSince(th.BasicUser.Id, "", &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 0, PerPage: 5}) + topChannels, err := th.App.GetTopChannelsForUserSince(th.Context, th.BasicUser.Id, "", &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 0, PerPage: 5}) require.Nil(t, err) for i, channel := range topChannels.Items { @@ -2526,7 +2526,7 @@ func TestGetTopChannelsForUserSince(t *testing.T) { assert.Equal(t, expectedTopChannels[i].MessageCount, channel.MessageCount) } - topChannels, err = th.App.GetTopChannelsForUserSince(th.BasicUser.Id, th.BasicChannel.TeamId, &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 1, PerPage: 5}) + topChannels, err = th.App.GetTopChannelsForUserSince(th.Context, th.BasicUser.Id, th.BasicChannel.TeamId, &model.InsightsOpts{StartUnixMilli: timeRange.UnixMilli(), Page: 1, PerPage: 5}) require.Nil(t, err) assert.Equal(t, channel6.Id, topChannels.Items[0].ID) assert.Equal(t, int64(1), topChannels.Items[0].MessageCount) @@ -2537,17 +2537,17 @@ func TestPostCountsByDuration(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channel2 := th.CreateChannel(th.BasicTeam) - channel3 := th.CreatePrivateChannel(th.BasicTeam) - channel4 := th.CreatePrivateChannel(th.BasicTeam) - channel5 := th.CreateChannel(th.BasicTeam) - channel6 := th.CreatePrivateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) + channel3 := th.CreatePrivateChannel(th.Context, th.BasicTeam) + channel4 := th.CreatePrivateChannel(th.Context, th.BasicTeam) + channel5 := th.CreateChannel(th.Context, th.BasicTeam) + channel6 := th.CreatePrivateChannel(th.Context, th.BasicTeam) defer func() { - th.App.PermanentDeleteChannel(channel2) - th.App.PermanentDeleteChannel(channel3) - th.App.PermanentDeleteChannel(channel4) - th.App.PermanentDeleteChannel(channel5) - th.App.PermanentDeleteChannel(channel6) + th.App.PermanentDeleteChannel(th.Context, channel2) + th.App.PermanentDeleteChannel(th.Context, channel3) + th.App.PermanentDeleteChannel(th.Context, channel4) + th.App.PermanentDeleteChannel(th.Context, channel5) + th.App.PermanentDeleteChannel(th.Context, channel6) }() th.AddUserToChannel(th.BasicUser, channel2) th.AddUserToChannel(th.BasicUser, channel3) @@ -2612,7 +2612,7 @@ func TestPostCountsByDuration(t *testing.T) { sinceUnixMillis := time.Date(2009, time.November, 9, 23, 0, 0, 0, time.UTC).UnixMilli() t.Run("get-post-counts-by-day scoped by user, grouped by day", func(t *testing.T) { - dailyPostCount, err := th.App.PostCountsByDuration(channelIDs, sinceUnixMillis, &th.BasicUser.Id, model.PostsByDay, time.Now().UTC().Location()) + dailyPostCount, err := th.App.PostCountsByDuration(th.Context, channelIDs, sinceUnixMillis, &th.BasicUser.Id, model.PostsByDay, time.Now().UTC().Location()) require.Nil(t, err) require.GreaterOrEqual(t, len(dailyPostCount), 6) @@ -2625,7 +2625,7 @@ func TestPostCountsByDuration(t *testing.T) { }) t.Run("get-post-counts-by-day all users, grouped by day", func(t *testing.T) { - dailyPostCount, err := th.App.PostCountsByDuration(channelIDs, sinceUnixMillis, nil, model.PostsByDay, time.Now().UTC().Location()) + dailyPostCount, err := th.App.PostCountsByDuration(th.Context, channelIDs, sinceUnixMillis, nil, model.PostsByDay, time.Now().UTC().Location()) require.Nil(t, err) require.GreaterOrEqual(t, len(dailyPostCount), 6) @@ -2639,7 +2639,7 @@ func TestPostCountsByDuration(t *testing.T) { t.Run("get-post-counts-by-day all users, grouped by hour", func(t *testing.T) { oneDaySince := time.Date(2009, time.November, 14, 23, 0, 0, 0, time.UTC).UnixMilli() - dailyPostCount, err := th.App.PostCountsByDuration(channelIDs, oneDaySince, nil, model.PostsByHour, time.Now().UTC().Location()) + dailyPostCount, err := th.App.PostCountsByDuration(th.Context, channelIDs, oneDaySince, nil, model.PostsByHour, time.Now().UTC().Location()) require.Nil(t, err) require.GreaterOrEqual(t, len(dailyPostCount), 1) diff --git a/app/channels.go b/app/channels.go index 42e592098b..ee2670eb0f 100644 --- a/app/channels.go +++ b/app/channels.go @@ -178,12 +178,12 @@ func NewChannels(s *Server, services map[ServiceKey]any) (*Channels, error) { if samlInterfaceNew != nil { ch.Saml = samlInterfaceNew(New(ServerConnector(ch))) if err := ch.Saml.ConfigureSP(); err != nil { - mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) + s.Log.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) } ch.AddConfigListener(func(_, _ *model.Config) { if err := ch.Saml.ConfigureSP(); err != nil { - mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) + s.Log.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) } }) } @@ -240,7 +240,7 @@ func NewChannels(s *Server, services map[ServiceKey]any) (*Channels, error) { func (ch *Channels) Start() error { // Start plugins - ctx := request.EmptyContext() + ctx := request.EmptyContext(ch.srv.GetLogger()) ch.initPlugins(ctx, *ch.cfgSvc.Config().PluginSettings.Directory, *ch.cfgSvc.Config().PluginSettings.ClientDirectory) ch.AddConfigListener(func(prevCfg, cfg *model.Config) { @@ -248,7 +248,7 @@ func (ch *Channels) Start() error { // to ensure we don't re-init plugins unnecessarily. diffs, err := config.Diff(prevCfg, cfg) if err != nil { - mlog.Warn("Error in comparing configs", mlog.Err(err)) + ch.srv.Log.Warn("Error in comparing configs", mlog.Err(err)) return } diff --git a/app/command.go b/app/command.go index c943261eae..038979752f 100644 --- a/app/command.go +++ b/app/command.go @@ -75,7 +75,7 @@ func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID str } if (response.ResponseType == "" || response.ResponseType == model.CommandResponseTypeEphemeral) && (response.Text != "" || response.Attachments != nil) { - a.SendEphemeralPost(post.UserId, post) + a.SendEphemeralPost(c, post.UserId, post) } return post, nil @@ -213,7 +213,7 @@ func (a *App) ExecuteCommand(c *request.Context, args *model.CommandArgs) (*mode } // Custom commands can override built ins - cmd, response, appErr = a.tryExecuteCustomCommand(args, trigger, message) + cmd, response, appErr = a.tryExecuteCustomCommand(c, args, trigger, message) if appErr != nil { return nil, appErr } else if cmd != nil && response != nil { @@ -307,7 +307,7 @@ func (a *App) MentionsToTeamMembers(message, teamID string) model.UserMentionMap // MentionsToPublicChannels returns all the mentions to public channels, // linking them to their channels -func (a *App) MentionsToPublicChannels(message, teamID string) model.ChannelMentionMap { +func (a *App) MentionsToPublicChannels(c request.CTX, message, teamID string) model.ChannelMentionMap { type mentionMapItem struct { Name string Id string @@ -321,7 +321,7 @@ func (a *App) MentionsToPublicChannels(message, teamID string) model.ChannelMent wg.Add(1) go func(channelName string) { defer wg.Done() - channel, err := a.GetChannelByName(channelName, teamID, false) + channel, err := a.GetChannelByName(c, channelName, teamID, false) if err != nil { return } @@ -363,7 +363,7 @@ func (a *App) tryExecuteBuiltInCommand(c *request.Context, args *model.CommandAr // tryExecuteCustomCommand attempts to run a custom command based on the given arguments. If no such command can be // found, returns nil for all arguments. -func (a *App) tryExecuteCustomCommand(args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse, *model.AppError) { +func (a *App) tryExecuteCustomCommand(c request.CTX, args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse, *model.AppError) { // Handle custom commands if !*a.Config().ServiceSettings.EnableCommands { return nil, nil, model.NewAppError("ExecuteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) @@ -467,7 +467,7 @@ func (a *App) tryExecuteCustomCommand(args *model.CommandArgs, trigger string, m p[key] = values } - channelMentionMap := a.MentionsToPublicChannels(message, team.Id) + channelMentionMap := a.MentionsToPublicChannels(c, message, team.Id) for key, values := range channelMentionMap.ToURLValues() { p[key] = values } @@ -579,7 +579,7 @@ func (a *App) HandleCommandResponsePost(c *request.Context, command *model.Comma post.SetProps(response.Props) if response.ChannelId != "" { - _, err := a.GetChannelMember(context.Background(), response.ChannelId, args.UserId) + _, err := a.GetChannelMember(c, response.ChannelId, args.UserId) if err != nil { err = model.NewAppError("HandleCommandResponsePost", "api.command.command_post.forbidden.app_error", nil, err.Error(), http.StatusForbidden) return nil, err diff --git a/app/context.go b/app/context.go index 137a67507c..1ec7ad254d 100644 --- a/app/context.go +++ b/app/context.go @@ -16,7 +16,7 @@ func WithMaster(ctx context.Context) context.Context { return sqlstore.WithMaster(ctx) } -func pluginContext(c *request.Context) *plugin.Context { +func pluginContext(c request.CTX) *plugin.Context { context := &plugin.Context{ RequestId: c.RequestId(), SessionId: c.Session().Id, diff --git a/app/export_test.go b/app/export_test.go index 2e13c3b993..c7711afc0c 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -97,7 +97,7 @@ func TestExportUserChannels(t *testing.T) { err := th.App.Srv().Store.Preference().Save(preferences) require.NoError(t, err) - th.App.UpdateChannelMemberNotifyProps(notifyProps, channel.Id, user.Id) + th.App.UpdateChannelMemberNotifyProps(th.Context, notifyProps, channel.Id, user.Id) exportData, appErr := th.App.buildUserChannelMemberships(user.Id, team.Id) require.Nil(t, appErr) assert.Equal(t, len(*exportData), 3) @@ -327,7 +327,7 @@ func TestExportGMChannel(t *testing.T) { th1.LinkUserToTeam(user2, th1.BasicTeam) // GM Channel - th1.CreateGroupChannel(user1, user2) + th1.CreateGroupChannel(th1.Context, user1, user2) var b bytes.Buffer err := th1.App.BulkExport(&b, "somePath", model.BulkExportOpts{}) @@ -359,7 +359,7 @@ func TestExportGMandDMChannels(t *testing.T) { th1.LinkUserToTeam(user2, th1.BasicTeam) // GM Channel - th1.CreateGroupChannel(user1, user2) + th1.CreateGroupChannel(th1.Context, user1, user2) var b bytes.Buffer err := th1.App.BulkExport(&b, "somePath", model.BulkExportOpts{}) @@ -407,7 +407,7 @@ func TestExportDMandGMPost(t *testing.T) { th1.LinkUserToTeam(user2, th1.BasicTeam) // GM Channel - gmChannel := th1.CreateGroupChannel(user1, user2) + gmChannel := th1.CreateGroupChannel(th1.Context, user1, user2) gmMembers := []string{th1.BasicUser.Username, user1.Username, user2.Username} // DM posts @@ -489,7 +489,7 @@ func TestExportPostWithProps(t *testing.T) { th1.LinkUserToTeam(user2, th1.BasicTeam) // GM Channel - gmChannel := th1.CreateGroupChannel(user1, user2) + gmChannel := th1.CreateGroupChannel(th1.Context, user1, user2) gmMembers := []string{th1.BasicUser.Username, user1.Username, user2.Username} // DM posts @@ -709,7 +709,7 @@ func TestExportDeletedTeams(t *testing.T) { defer th1.TearDown() team1 := th1.CreateTeam() - channel1 := th1.CreateChannel(team1) + channel1 := th1.CreateChannel(th1.Context, team1) th1.CreatePost(channel1) // Delete the team to check that this is handled correctly on import. @@ -733,9 +733,9 @@ func TestExportDeletedTeams(t *testing.T) { assert.Equal(t, len(teams1), len(teams2)) assert.ElementsMatch(t, teams1, teams2) - channels1, err := th1.App.GetAllChannels(0, 10, model.ChannelSearchOpts{}) + channels1, err := th1.App.GetAllChannels(th1.Context, 0, 10, model.ChannelSearchOpts{}) assert.Nil(t, err) - channels2, err := th2.App.GetAllChannels(0, 10, model.ChannelSearchOpts{}) + channels2, err := th2.App.GetAllChannels(th1.Context, 0, 10, model.ChannelSearchOpts{}) assert.Nil(t, err) assert.Equal(t, len(channels1), len(channels2)) assert.ElementsMatch(t, channels1, channels2) diff --git a/app/file.go b/app/file.go index 8a4024f650..8d50a5815f 100644 --- a/app/file.go +++ b/app/file.go @@ -520,7 +520,7 @@ func (a *App) UploadFiles(c *request.Context, teamID string, channelID string, u // UploadFile uploads a single file in form of a completely constructed byte array for a channel. func (a *App) UploadFile(c *request.Context, data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) { - _, err := a.GetChannel(channelID) + _, err := a.GetChannel(c, channelID) if err != nil && channelID != "" { return nil, model.NewAppError("UploadFile", "api.file.upload_file.incorrect_channelId.app_error", map[string]any{"channelId": channelID}, "", http.StatusBadRequest) diff --git a/app/group_test.go b/app/group_test.go index 90b6161c9a..9e262b7461 100644 --- a/app/group_test.go +++ b/app/group_test.go @@ -200,7 +200,7 @@ func TestUpsertGroupSyncableTeamGroupConstrained(t *testing.T) { _, err = th.App.UpsertGroupSyncable(model.NewGroupTeam(group1.Id, team.Id, false)) require.Nil(t, err) - channel := th.CreateChannel(team) + channel := th.CreateChannel(th.Context, team) _, err = th.App.UpsertGroupSyncable(model.NewGroupChannel(group2.Id, channel.Id, false)) require.NotNil(t, err) diff --git a/app/helper_test.go b/app/helper_test.go index 58063b9a10..bb6b1cdee4 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -99,12 +99,13 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th := &TestHelper{ App: New(ServerConnector(s.Channels())), - Context: &request.Context{}, + Context: request.EmptyContext(testLogger), Server: s, LogBuffer: buffer, TestLogger: testLogger, IncludeCacheLayer: includeCacheLayer, } + th.Context.SetLogger(testLogger) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.RateLimitSettings.Enable = false }) @@ -245,7 +246,7 @@ func (th *TestHelper) InitBasic() *TestHelper { th.LinkUserToTeam(th.BasicUser, th.BasicTeam) th.LinkUserToTeam(th.BasicUser2, th.BasicTeam) - th.BasicChannel = th.CreateChannel(th.BasicTeam) + th.BasicChannel = th.CreateChannel(th.Context, th.BasicTeam) th.BasicPost = th.CreatePost(th.BasicChannel) return th } @@ -327,15 +328,15 @@ func WithShared(v bool) ChannelOption { } } -func (th *TestHelper) CreateChannel(team *model.Team, options ...ChannelOption) *model.Channel { - return th.createChannel(team, model.ChannelTypeOpen, options...) +func (th *TestHelper) CreateChannel(c request.CTX, team *model.Team, options ...ChannelOption) *model.Channel { + return th.createChannel(c, team, model.ChannelTypeOpen, options...) } -func (th *TestHelper) CreatePrivateChannel(team *model.Team) *model.Channel { - return th.createChannel(team, model.ChannelTypePrivate) +func (th *TestHelper) CreatePrivateChannel(c request.CTX, team *model.Team) *model.Channel { + return th.createChannel(c, team, model.ChannelTypePrivate) } -func (th *TestHelper) createChannel(team *model.Team, channelType model.ChannelType, options ...ChannelOption) *model.Channel { +func (th *TestHelper) createChannel(c request.CTX, team *model.Team, channelType model.ChannelType, options ...ChannelOption) *model.Channel { id := model.NewId() channel := &model.Channel{ @@ -357,7 +358,7 @@ func (th *TestHelper) createChannel(team *model.Team, channelType model.ChannelT if channel.IsShared() { id := model.NewId() - _, err := th.App.SaveSharedChannel(&model.SharedChannel{ + _, err := th.App.SaveSharedChannel(c, &model.SharedChannel{ ChannelId: channel.Id, TeamId: channel.TeamId, Home: false, @@ -383,10 +384,10 @@ func (th *TestHelper) CreateDmChannel(user *model.User) *model.Channel { return channel } -func (th *TestHelper) CreateGroupChannel(user1 *model.User, user2 *model.User) *model.Channel { +func (th *TestHelper) CreateGroupChannel(c request.CTX, user1 *model.User, user2 *model.User) *model.Channel { var err *model.AppError var channel *model.Channel - if channel, err = th.App.CreateGroupChannel([]string{th.BasicUser.Id, user1.Id, user2.Id}, th.BasicUser.Id); err != nil { + if channel, err = th.App.CreateGroupChannel(c, []string{th.BasicUser.Id, user1.Id, user2.Id}, th.BasicUser.Id); err != nil { panic(err) } return channel @@ -439,7 +440,7 @@ func (th *TestHelper) RemoveUserFromTeam(user *model.User, team *model.Team) { } func (th *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember { - member, err := th.App.AddUserToChannel(user, channel, false) + member, err := th.App.AddUserToChannel(th.Context, user, channel, false) if err != nil { panic(err) } diff --git a/app/import.go b/app/import.go index c02a59440c..5822e1d58f 100644 --- a/app/import.go +++ b/app/import.go @@ -302,12 +302,12 @@ func (a *App) importLine(c *request.Context, line LineImportData, dryRun bool) * if line.User == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_user.error", nil, "", http.StatusBadRequest) } - return a.importUser(line.User, dryRun) + return a.importUser(c, line.User, dryRun) case line.Type == "direct_channel": if line.DirectChannel == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_direct_channel.error", nil, "", http.StatusBadRequest) } - return a.importDirectChannel(line.DirectChannel, dryRun) + return a.importDirectChannel(c, line.DirectChannel, dryRun) case line.Type == "emoji": if line.Emoji == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_emoji.error", nil, "", http.StatusBadRequest) diff --git a/app/import_functions.go b/app/import_functions.go index 0a41b93566..42ba70e4d9 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -284,7 +284,7 @@ func (a *App) importChannel(c *request.Context, data *ChannelImportData, dryRun return err } } else { - if _, err := a.UpdateChannel(channel); err != nil { + if _, err := a.UpdateChannel(c, channel); err != nil { return err } } @@ -292,7 +292,7 @@ func (a *App) importChannel(c *request.Context, data *ChannelImportData, dryRun return nil } -func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { +func (a *App) importUser(c request.CTX, data *UserImportData, dryRun bool) *model.AppError { if err := validateUserImportData(data); err != nil { return err } @@ -728,10 +728,10 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError { } } - return a.importUserTeams(savedUser, data.Teams) + return a.importUserTeams(c, savedUser, data.Teams) } -func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *model.AppError { +func (a *App) importUserTeams(c request.CTX, user *model.User, data *[]UserTeamImportData) *model.AppError { if data == nil { return nil } @@ -882,7 +882,7 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod } } channelsToImport := channels[team.Id] - if err := a.importUserChannels(user, team, &channelsToImport); err != nil { + if err := a.importUserChannels(c, user, team, &channelsToImport); err != nil { return err } } @@ -890,7 +890,7 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod return nil } -func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]UserChannelImportData) *model.AppError { +func (a *App) importUserChannels(c request.CTX, user *model.User, team *model.Team, data *[]UserChannelImportData) *model.AppError { if data == nil { return nil } @@ -1040,12 +1040,12 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use for _, member := range append(newMembers, oldMembers...) { if member.ExplicitRoles != rolesByChannelId[member.ChannelId] { - if _, err = a.UpdateChannelMemberRoles(member.ChannelId, user.Id, rolesByChannelId[member.ChannelId]); err != nil { + if _, err = a.UpdateChannelMemberRoles(c, member.ChannelId, user.Id, rolesByChannelId[member.ChannelId]); err != nil { return err } } - a.UpdateChannelMemberSchemeRoles(member.ChannelId, user.Id, isGuestByChannelId[member.ChannelId], isUserByChannelId[member.ChannelId], isAdminByChannelId[member.ChannelId]) + a.UpdateChannelMemberSchemeRoles(c, member.ChannelId, user.Id, isGuestByChannelId[member.ChannelId], isUserByChannelId[member.ChannelId], isAdminByChannelId[member.ChannelId]) } for _, channel := range allChannels { @@ -1564,7 +1564,7 @@ func (a *App) updateFileInfoWithPostId(post *model.Post) { } } } -func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *model.AppError { +func (a *App) importDirectChannel(c request.CTX, data *DirectChannelImportData, dryRun bool) *model.AppError { var err *model.AppError if err = validateDirectChannelImportData(data); err != nil { return err @@ -1587,13 +1587,13 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m var channel *model.Channel if len(userIDs) == 2 { - ch, err := a.createDirectChannel(userIDs[0], userIDs[1]) + ch, err := a.createDirectChannel(c, userIDs[0], userIDs[1]) if err != nil && err.Id != store.ChannelExistsError { return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_direct_channel.error", nil, err.Error(), http.StatusBadRequest) } channel = ch } else { - ch, err := a.createGroupChannel(userIDs) + ch, err := a.createGroupChannel(c, userIDs) if err != nil && err.Id != store.ChannelExistsError { return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_group_channel.error", nil, err.Error(), http.StatusBadRequest) } @@ -1698,7 +1698,7 @@ func (a *App) importMultipleDirectPostLines(c *request.Context, lines []LineImpo } channel = ch } else { - ch, err = a.createGroupChannel(userIDs) + ch, err = a.createGroupChannel(c, userIDs) if err != nil && err.Id != store.ChannelExistsError { return line.LineNumber, model.NewAppError("BulkImport", "app.import.import_direct_post.create_group_channel.error", nil, err.Error(), http.StatusBadRequest) } diff --git a/app/import_functions_test.go b/app/import_functions_test.go index 084cac099d..c764e44c19 100644 --- a/app/import_functions_test.go +++ b/app/import_functions_test.go @@ -671,7 +671,7 @@ func TestImportImportChannel(t *testing.T) { th.CheckChannelsCount(t, channelCount+1) // Get the Channel and check all the fields are correct. - channel, err := th.App.GetChannelByName(*data.Name, team.Id, false) + channel, err := th.App.GetChannelByName(th.Context, *data.Name, team.Id, false) require.Nil(t, err, "Failed to get channel from database.") assert.Equal(t, *data.Name, channel.Name) @@ -695,7 +695,7 @@ func TestImportImportChannel(t *testing.T) { th.CheckChannelsCount(t, channelCount) // Get the Channel and check all the fields are correct. - channel, err = th.App.GetChannelByName(*data.Name, team.Id, false) + channel, err = th.App.GetChannelByName(th.Context, *data.Name, team.Id, false) require.Nil(t, err, "Failed to get channel from database.") assert.Equal(t, *data.Name, channel.Name) @@ -722,7 +722,7 @@ func TestImportImportUser(t *testing.T) { data := UserImportData{ Username: ptrStr(model.NewId()), } - err = th.App.importUser(&data, true) + err = th.App.importUser(th.Context, &data, true) require.Error(t, err, "Should have failed to import invalid user.") // Check that no more users are in the DB. @@ -738,7 +738,7 @@ func TestImportImportUser(t *testing.T) { Username: ptrStr(model.NewId()), Email: ptrStr(model.NewId() + "@example.com"), } - appErr := th.App.importUser(&data, true) + appErr := th.App.importUser(th.Context, &data, true) require.Nil(t, appErr, "Should have succeeded to import valid user.") // Check that no more users are in the DB. @@ -753,7 +753,7 @@ func TestImportImportUser(t *testing.T) { data = UserImportData{ Username: ptrStr(model.NewId()), } - err = th.App.importUser(&data, false) + err = th.App.importUser(th.Context, &data, false) require.Error(t, err, "Should have failed to import invalid user.") // Check that no more users are in the DB. @@ -776,7 +776,7 @@ func TestImportImportUser(t *testing.T) { LastName: ptrStr(model.NewId()), Position: ptrStr(model.NewId()), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) require.Nil(t, appErr, "Should have succeeded to import valid user.") // Check that one more user is in the DB. @@ -819,7 +819,7 @@ func TestImportImportUser(t *testing.T) { data.Roles = ptrStr("system_admin system_user") data.Locale = ptrStr("zh_CN") - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) require.Nil(t, appErr, "Should have succeeded to update valid user %v", err) // Check user count the same. @@ -851,20 +851,20 @@ func TestImportImportUser(t *testing.T) { // Check Password and AuthData together. data.Password = ptrStr("PasswordTest") - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) require.NotNil(t, appErr, "Should have failed to import invalid user.") data.AuthData = nil data.AuthService = nil - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) require.Nil(t, appErr, "Should have succeeded to update valid user %v", err) data.Password = ptrStr("") - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) require.NotNil(t, appErr, "Should have failed to import invalid user.") data.Password = ptrStr(strings.Repeat("0123456789", 10)) - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) require.NotNil(t, appErr, "Should have failed to import invalid user.") data.Password = ptrStr("TestPassword") @@ -887,7 +887,7 @@ func TestImportImportUser(t *testing.T) { DisplayName: ptrStr("Display Name"), Type: &chanTypeOpen, }, false) - channel, appErr := th.App.GetChannelByName(channelName, team.Id, false) + channel, appErr := th.App.GetChannelByName(th.Context, channelName, team.Id, false) require.Nil(t, appErr, "Failed to get channel from database.") username = model.NewId() @@ -904,7 +904,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get team member count") teamMemberCount := len(teamMembers) - channelMemberCount, appErr := th.App.GetChannelMemberCount(channel.Id) + channelMemberCount, appErr := th.App.GetChannelMemberCount(th.Context, channel.Id) require.Nil(t, appErr, "Failed to get channel member count") // Test with an invalid team & channel membership in dry-run mode. @@ -918,7 +918,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, true) + appErr = th.App.importUser(th.Context, &data, true) assert.NotNil(t, appErr) // Test with an unknown team name & invalid channel membership in dry-run mode. @@ -932,7 +932,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, true) + appErr = th.App.importUser(th.Context, &data, true) assert.NotNil(t, appErr) // Test with a valid team & invalid channel membership in dry-run mode. @@ -946,7 +946,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, true) + appErr = th.App.importUser(th.Context, &data, true) assert.NotNil(t, appErr) // Test with a valid team & unknown channel name in dry-run mode. @@ -960,7 +960,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, true) + appErr = th.App.importUser(th.Context, &data, true) assert.Nil(t, appErr) // Test with a valid team & valid channel name in dry-run mode. @@ -974,7 +974,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, true) + appErr = th.App.importUser(th.Context, &data, true) assert.Nil(t, appErr) // Check no new member objects were created because dry run mode. @@ -982,7 +982,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get Team Member Count") require.Len(t, tmc, teamMemberCount, "Number of team members not as expected") - cmc, appErr := th.App.GetChannelMemberCount(channel.Id) + cmc, appErr := th.App.GetChannelMemberCount(th.Context, channel.Id) require.Nil(t, appErr, "Failed to get Channel Member Count") require.Equal(t, channelMemberCount, cmc, "Number of channel members not as expected") @@ -997,7 +997,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.NotNil(t, appErr) // Test with an unknown team name & invalid channel membership in apply mode. @@ -1011,7 +1011,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.NotNil(t, appErr) // Test with a valid team & invalid channel membership in apply mode. @@ -1025,7 +1025,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.NotNil(t, appErr) // Check no new member objects were created because all tests should have failed so far. @@ -1033,7 +1033,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get Team Member Count") require.Len(t, tmc, teamMemberCount) - cmc, appErr = th.App.GetChannelMemberCount(channel.Id) + cmc, appErr = th.App.GetChannelMemberCount(th.Context, channel.Id) require.Nil(t, appErr, "Failed to get Channel Member Count") require.Equal(t, channelMemberCount, cmc) @@ -1048,7 +1048,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.NotNil(t, appErr) // Check only new team member object created because dry run mode. @@ -1056,7 +1056,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get Team Member Count") require.Len(t, tmc, teamMemberCount+1) - cmc, appErr = th.App.GetChannelMemberCount(channel.Id) + cmc, appErr = th.App.GetChannelMemberCount(th.Context, channel.Id) require.Nil(t, appErr, "Failed to get Channel Member Count") require.Equal(t, channelMemberCount, cmc) @@ -1079,7 +1079,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) // Check only new channel member object created because dry run mode. @@ -1087,12 +1087,12 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get Team Member Count") require.Len(t, tmc, teamMemberCount+1, "Number of team members not as expected") - cmc, appErr = th.App.GetChannelMemberCount(channel.Id) + cmc, appErr = th.App.GetChannelMemberCount(th.Context, channel.Id) require.Nil(t, appErr, "Failed to get Channel Member Count") require.Equal(t, channelMemberCount+1, cmc, "Number of channel members not as expected") // Check channel member properties. - channelMember, appErr := th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, appErr := th.App.GetChannelMember(th.Context, channel.Id, user.Id) require.Nil(t, appErr, "Failed to get channel member from database.") assert.Equal(t, "channel_user", channelMember.Roles) assert.Equal(t, "default", channelMember.NotifyProps[model.DesktopNotifyProp]) @@ -1119,7 +1119,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) // Check both member properties. @@ -1127,7 +1127,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get team member from database.") require.Equal(t, "team_user team_admin", teamMember.Roles) - channelMember, appErr = th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, appErr = th.App.GetChannelMember(th.Context, channel.Id, user.Id) require.Nil(t, appErr, "Failed to get channel member Desktop from database.") assert.Equal(t, "channel_user channel_admin", channelMember.Roles) assert.Equal(t, model.UserNotifyMention, channelMember.NotifyProps[model.DesktopNotifyProp]) @@ -1142,7 +1142,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Failed to get Team Member Count") require.Len(t, tmc, teamMemberCount+1, "Number of team members not as expected") - cmc, appErr = th.App.GetChannelMemberCount(channel.Id) + cmc, appErr = th.App.GetChannelMemberCount(th.Context, channel.Id) require.Nil(t, appErr, "Failed to get Channel Member Count") require.Equal(t, channelMemberCount+1, cmc, "Number of channel members not as expected") @@ -1163,7 +1163,7 @@ func TestImportImportUser(t *testing.T) { ShowUnreadSection: ptrStr("true"), EmailInterval: ptrStr("immediately"), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) // Check their values. @@ -1195,7 +1195,7 @@ func TestImportImportUser(t *testing.T) { TutorialStep: ptrStr("2"), EmailInterval: ptrStr("hour"), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) // Check their values again. @@ -1218,7 +1218,7 @@ func TestImportImportUser(t *testing.T) { ChannelTrigger: ptrStr("true"), CommentsTrigger: ptrStr(model.CommentsNotifyRoot), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(username) @@ -1244,7 +1244,7 @@ func TestImportImportUser(t *testing.T) { CommentsTrigger: ptrStr(model.CommentsNotifyRoot), MentionKeys: ptrStr("valid,misc"), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(username) @@ -1270,7 +1270,7 @@ func TestImportImportUser(t *testing.T) { CommentsTrigger: ptrStr(model.CommentsNotifyAny), MentionKeys: ptrStr("misc"), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(username) @@ -1295,7 +1295,7 @@ func TestImportImportUser(t *testing.T) { ChannelTrigger: ptrStr("false"), CommentsTrigger: ptrStr(model.CommentsNotifyAny), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(username) @@ -1327,7 +1327,7 @@ func TestImportImportUser(t *testing.T) { MentionKeys: ptrStr("misc"), } - appErr = th.App.importUser(&data, false) + appErr = th.App.importUser(th.Context, &data, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(username) @@ -1413,7 +1413,7 @@ func TestImportImportUser(t *testing.T) { } appErr = th.App.importChannel(th.Context, channelData, false) assert.Nil(t, appErr) - channel, appErr = th.App.GetChannelByName(*channelData.Name, team.Id, false) + channel, appErr = th.App.GetChannelByName(th.Context, *channelData.Name, team.Id, false) require.Nil(t, appErr, "Failed to get channel from database") // Test with a valid team & valid channel name in apply mode. @@ -1433,7 +1433,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(userData, false) + appErr = th.App.importUser(th.Context, userData, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(*userData.Username) @@ -1447,7 +1447,7 @@ func TestImportImportUser(t *testing.T) { assert.False(t, teamMember.SchemeGuest) assert.Equal(t, "", teamMember.ExplicitRoles) - channelMember, appErr = th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, appErr = th.App.GetChannelMember(th.Context, channel.Id, user.Id) require.Nil(t, appErr, "Failed to get the channel member") assert.True(t, channelMember.SchemeAdmin) @@ -1475,7 +1475,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(deletedUserData, false) + appErr = th.App.importUser(th.Context, deletedUserData, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(*deletedUserData.Username) @@ -1489,7 +1489,7 @@ func TestImportImportUser(t *testing.T) { assert.False(t, teamMember.SchemeGuest) assert.Equal(t, "", teamMember.ExplicitRoles) - channelMember, appErr = th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, appErr = th.App.GetChannelMember(th.Context, channel.Id, user.Id) require.Nil(t, appErr, "Failed to get the channel member") assert.False(t, teamMember.SchemeAdmin) @@ -1517,7 +1517,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - appErr = th.App.importUser(deletedGuestData, false) + appErr = th.App.importUser(th.Context, deletedGuestData, false) assert.Nil(t, appErr) user, appErr = th.App.GetUserByUsername(*deletedGuestData.Username) @@ -1531,7 +1531,7 @@ func TestImportImportUser(t *testing.T) { assert.True(t, teamMember.SchemeGuest) assert.Equal(t, "", teamMember.ExplicitRoles) - channelMember, appErr = th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, appErr = th.App.GetChannelMember(th.Context, channel.Id, user.Id) require.Nil(t, appErr, "Failed to get the channel member") assert.False(t, teamMember.SchemeAdmin) @@ -1544,8 +1544,8 @@ func TestImportUserTeams(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() team2 := th.CreateTeam() - channel2 := th.CreateChannel(th.BasicTeam) - channel3 := th.CreateChannel(team2) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) + channel3 := th.CreateChannel(th.Context, team2) customRole := th.CreateRole("test_custom_role") sampleTheme := "{\"test\":\"#abcdef\"}" @@ -1718,7 +1718,7 @@ func TestImportUserTeams(t *testing.T) { // Two times import must end with the same results for x := 0; x < 2; x++ { - err := th.App.importUserTeams(user, tc.data) + err := th.App.importUserTeams(th.Context, user, tc.data) if tc.expectedError { require.NotNil(t, err) } else { @@ -1757,7 +1757,7 @@ func TestImportUserTeams(t *testing.T) { } th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 1 }) defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 100 }) - err := th.App.importUserTeams(user, data) + err := th.App.importUserTeams(th.Context, user, data) require.NotNil(t, err) }) } @@ -1765,7 +1765,7 @@ func TestImportUserTeams(t *testing.T) { func TestImportUserChannels(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) customRole := th.CreateRole("test_custom_role") sampleNotifyProps := UserChannelNotifyPropsImportData{ Desktop: model.NewString("all"), @@ -1872,7 +1872,7 @@ func TestImportUserChannels(t *testing.T) { // Two times import must end with the same results for x := 0; x < 2; x++ { - appErr := th.App.importUserChannels(user, th.BasicTeam, tc.data) + appErr := th.App.importUserChannels(th.Context, user, th.BasicTeam, tc.data) if tc.expectedError { require.NotNil(t, appErr) } else { @@ -1910,7 +1910,7 @@ func TestImportUserDefaultNotifyProps(t *testing.T) { MentionKeys: ptrStr(""), }, } - require.Nil(t, th.App.importUser(&data, false)) + require.Nil(t, th.App.importUser(th.Context, &data, false)) user, err := th.App.GetUserByUsername(username) require.Nil(t, err) @@ -1958,12 +1958,12 @@ func TestImportimportMultiplePostLines(t *testing.T) { DisplayName: ptrStr("Display Name"), Type: &chanTypeOpen, }, false) - channel, err := th.App.GetChannelByName(channelName, team.Id, false) + channel, err := th.App.GetChannelByName(th.Context, channelName, team.Id, false) require.Nil(t, err, "Failed to get channel from database.") // Create a user. username := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -2211,7 +2211,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { // Post with flags. username2 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username2, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -2473,7 +2473,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { DisplayName: ptrStr("Display Name"), Type: &chanTypeOpen, }, false) - _, err = th.App.GetChannelByName(channelName, team2.Id, false) + _, err = th.App.GetChannelByName(th.Context, channelName, team2.Id, false) require.Nil(t, err, "Failed to get channel from database.") // Count the number of posts in the team2. @@ -2562,12 +2562,12 @@ func TestImportImportPost(t *testing.T) { DisplayName: ptrStr("Display Name"), Type: &chanTypeOpen, }, false) - channel, appErr := th.App.GetChannelByName(channelName, team.Id, false) + channel, appErr := th.App.GetChannelByName(th.Context, channelName, team.Id, false) require.Nil(t, appErr, "Failed to get channel from database.") // Create a user. username := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -2575,7 +2575,7 @@ func TestImportImportPost(t *testing.T) { require.Nil(t, appErr, "Failed to get user from database.") username2 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username2, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -3159,7 +3159,7 @@ func TestImportImportDirectChannel(t *testing.T) { }, Header: ptrStr("Channel Header"), } - err = th.App.importDirectChannel(&data, true) + err = th.App.importDirectChannel(th.Context, &data, true) require.Error(t, err) // Check that no more channels are in the DB. @@ -3171,7 +3171,7 @@ func TestImportImportDirectChannel(t *testing.T) { model.NewId(), model.NewId(), } - appErr := th.App.importDirectChannel(&data, true) + appErr := th.App.importDirectChannel(th.Context, &data, true) require.Nil(t, appErr) // Check that no more channels are in the DB. @@ -3184,7 +3184,7 @@ func TestImportImportDirectChannel(t *testing.T) { model.NewId(), model.NewId(), } - appErr = th.App.importDirectChannel(&data, true) + appErr = th.App.importDirectChannel(th.Context, &data, true) require.Nil(t, appErr) // Check that no more channels are in the DB. @@ -3195,7 +3195,7 @@ func TestImportImportDirectChannel(t *testing.T) { data.Members = &[]string{ model.NewId(), } - err = th.App.importDirectChannel(&data, false) + err = th.App.importDirectChannel(th.Context, &data, false) require.Error(t, err) // Check that no more channels are in the DB. @@ -3207,7 +3207,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser.Username, th.BasicUser2.Username, } - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.Nil(t, appErr) // Check that one more DIRECT channel is in the DB. @@ -3215,7 +3215,7 @@ func TestImportImportDirectChannel(t *testing.T) { AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount) // Do the same DIRECT channel again. - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.Nil(t, appErr) // Check that no more channels are in the DB. @@ -3224,7 +3224,7 @@ func TestImportImportDirectChannel(t *testing.T) { // Update the channel's HEADER data.Header = ptrStr("New Channel Header 2") - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.Nil(t, appErr) // Check that no more channels are in the DB. @@ -3244,7 +3244,7 @@ func TestImportImportDirectChannel(t *testing.T) { user3.Username, model.NewId(), } - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.NotNil(t, appErr) // Check that no more channels are in the DB. @@ -3257,7 +3257,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser2.Username, user3.Username, } - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.Nil(t, appErr) // Check that one more GROUP channel is in the DB. @@ -3265,7 +3265,7 @@ func TestImportImportDirectChannel(t *testing.T) { AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount+1) // Do the same DIRECT channel again. - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.Nil(t, appErr) // Check that no more channels are in the DB. @@ -3274,7 +3274,7 @@ func TestImportImportDirectChannel(t *testing.T) { // Update the channel's HEADER data.Header = ptrStr("New Channel Header 3") - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.Nil(t, appErr) // Check that no more channels are in the DB. @@ -3287,7 +3287,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser2.Id, user3.Id, } - channel, appErr = th.App.createGroupChannel(userIDs) + channel, appErr = th.App.createGroupChannel(th.Context, userIDs) require.Equal(t, appErr.Id, store.ChannelExistsError) require.Equal(t, channel.Header, *data.Header) @@ -3300,7 +3300,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser.Username, th.BasicUser2.Username, } - appErr = th.App.importDirectChannel(&data, false) + appErr = th.App.importDirectChannel(th.Context, &data, false) require.Nil(t, appErr) channel, appErr = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) @@ -3320,7 +3320,7 @@ func TestImportImportDirectPost(t *testing.T) { th.BasicUser2.Username, }, } - appErr := th.App.importDirectChannel(&channelData, false) + appErr := th.App.importDirectChannel(th.Context, &channelData, false) require.Nil(t, appErr) // Get the channel. @@ -3677,7 +3677,7 @@ func TestImportImportDirectPost(t *testing.T) { user3.Username, }, } - appErr = th.App.importDirectChannel(&channelData, false) + appErr = th.App.importDirectChannel(th.Context, &channelData, false) require.Nil(t, appErr) // Get the channel. @@ -3687,7 +3687,7 @@ func TestImportImportDirectPost(t *testing.T) { th.BasicUser2.Id, user3.Id, } - channel, appErr = th.App.createGroupChannel(userIDs) + channel, appErr = th.App.createGroupChannel(th.Context, userIDs) require.Equal(t, appErr.Id, store.ChannelExistsError) groupChannel = channel @@ -4237,12 +4237,12 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { DisplayName: ptrStr("Display Name"), Type: &chanTypeOpen, }, false) - _, appErr = th.App.GetChannelByName(channelName, team.Id, false) + _, appErr = th.App.GetChannelByName(th.Context, channelName, team.Id, false) require.Nil(t, appErr, "Failed to get channel from database.") // Create a user3. username := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4251,7 +4251,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { require.NotNil(t, user3) username2 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username2, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4260,7 +4260,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { // Create direct post users. username3 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username3, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4268,7 +4268,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) { require.Nil(t, appErr, "Failed to get user3 from database.") username4 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username4, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4387,7 +4387,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) { // Create a user. username := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4395,7 +4395,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) { require.Nil(t, appErr, "Failed to get user1 from database.") username2 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username2, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4513,12 +4513,12 @@ func TestZippedImportPostAndRepliesWithAttachments(t *testing.T) { DisplayName: ptrStr("Display Name"), Type: &chanTypeOpen, }, false) - _, appErr = th.App.GetChannelByName(channelName, team.Id, false) + _, appErr = th.App.GetChannelByName(th.Context, channelName, team.Id, false) require.Nil(t, appErr, "Failed to get channel from database.") // Create users username2 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username2, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4527,7 +4527,7 @@ func TestZippedImportPostAndRepliesWithAttachments(t *testing.T) { // Create direct post users. username3 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username3, Email: ptrStr(model.NewId() + "@example.com"), }, false) @@ -4535,7 +4535,7 @@ func TestZippedImportPostAndRepliesWithAttachments(t *testing.T) { require.Nil(t, appErr, "Failed to get user3 from database.") username4 := model.NewId() - th.App.importUser(&UserImportData{ + th.App.importUser(th.Context, &UserImportData{ Username: &username4, Email: ptrStr(model.NewId() + "@example.com"), }, false) diff --git a/app/integration_action.go b/app/integration_action.go index 7d9ee8db8f..6f3d703808 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -301,7 +301,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI for key, value := range retain { ephemeralPost.AddProp(key, value) } - a.SendEphemeralPost(userID, ephemeralPost) + a.SendEphemeralPost(c, userID, ephemeralPost) } return clientTriggerId, nil diff --git a/app/integration_action_test.go b/app/integration_action_test.go index 6ab8ba8967..6dde72a2be 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -140,7 +140,7 @@ func TestPostAction(t *testing.T) { user1 := th.CreateUser() user2 := th.CreateUser() - return th.CreateGroupChannel(user1, user2) + return th.CreateGroupChannel(th.Context, user1, user2) }}, } diff --git a/app/notification.go b/app/notification.go index c371ebf4ae..fac001cc6d 100644 --- a/app/notification.go +++ b/app/notification.go @@ -15,6 +15,7 @@ import ( "github.com/pkg/errors" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/i18n" "github.com/mattermost/mattermost-server/v6/shared/markdown" @@ -36,7 +37,7 @@ func (a *App) canSendPushNotifications() bool { return true } -func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList, setOnline bool) ([]string, error) { +func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList, setOnline bool) ([]string, error) { // Do not send notifications in archived channels if channel.DeleteAt > 0 { return []string{}, nil @@ -59,7 +60,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod }() var gchan chan store.StoreResult - if a.allowGroupMentions(post) { + if a.allowGroupMentions(c, post) { gchan = make(chan store.StoreResult, 1) go func() { groupsMap, err := a.getGroupsAllowedForReferenceInChannel(channel, team) @@ -134,7 +135,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod mentions.addMention(post.UserId, DMMention) } } else { - allowChannelMentions = a.allowChannelMentions(post, len(profileMap)) + allowChannelMentions = a.allowChannelMentions(c, post, len(profileMap)) keywords = a.getMentionKeywordsInChannel(profileMap, allowChannelMentions, channelMemberNotifyPropsMap) mentions = getExplicitMentions(post, keywords, groups) @@ -155,7 +156,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod } if !anyUsersMentionedByGroup { - a.sendNoUsersNotifiedByGroupInChannel(sender, post, channel, group) + a.sendNoUsersNotifiedByGroupInChannel(c, sender, post, channel, group) } } @@ -170,7 +171,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if threadPost.Id == parentPostList.Order[0] && threadPost.IsFromOAuthBot() { continue } - if a.IsCRTEnabledForUser(profile.Id) { + if a.IsCRTEnabledForUser(c, profile.Id) { continue } if profile.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyAny || (profile.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyRoot && threadPost.Id == parentPostList.Order[0]) { @@ -190,7 +191,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod } go func() { - _, err := a.sendOutOfChannelMentions(sender, post, channel, mentions.OtherPotentialMentions) + _, err := a.sendOutOfChannelMentions(c, sender, post, channel, mentions.OtherPotentialMentions) if err != nil { mlog.Error("Failed to send warning for out of channel mentions", mlog.String("user_id", sender.Id), mlog.String("post_id", post.Id), mlog.Err(err)) } @@ -203,7 +204,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod channelMemberNotifyPropsMap[profile.Id][model.PushNotifyProp] == model.ChannelNotifyAll) && (post.UserId != profile.Id || post.GetProp("from_webhook") == "true") && !post.IsSystemMessage() && - !(a.IsCRTEnabledForUser(profile.Id) && post.RootId != "") { + !(a.IsCRTEnabledForUser(c, profile.Id) && post.RootId != "") { allActivityPushUserIds = append(allActivityPushUserIds, profile.Id) } } @@ -330,7 +331,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if isCRTAllowed && post.RootId != "" { for _, uid := range followers { profile := profileMap[uid] - if profile == nil || !a.IsCRTEnabledForUser(uid) { + if profile == nil || !a.IsCRTEnabledForUser(c, uid) { continue } @@ -365,12 +366,12 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod continue } - if a.userAllowsEmail(profileMap[id], channelMemberNotifyPropsMap[id], post) { + if a.userAllowsEmail(c, profileMap[id], channelMemberNotifyPropsMap[id], post) { senderProfileImage, _, err := a.GetProfileImage(sender) if err != nil { a.Log().Warn("Unable to get the sender user profile image.", mlog.String("user_id", sender.Id), mlog.Err(err)) } - if err := a.sendNotificationEmail(notification, profileMap[id], team, senderProfileImage); err != nil { + if err := a.sendNotificationEmail(c, notification, profileMap[id], team, senderProfileImage); err != nil { mlog.Warn("Unable to send notification email.", mlog.Err(err)) } } @@ -383,6 +384,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if mentions.HereMentioned { a.SendEphemeralPost( + c, post.UserId, &model.Post{ ChannelId: post.ChannelId, @@ -394,6 +396,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if mentions.ChannelMentioned { a.SendEphemeralPost( + c, post.UserId, &model.Post{ ChannelId: post.ChannelId, @@ -405,6 +408,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if mentions.AllMentioned { a.SendEphemeralPost( + c, post.UserId, &model.Post{ ChannelId: post.ChannelId, @@ -563,7 +567,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod message.Add("followers", model.ArrayToJSON(notificationsForCRT.Desktop)) } - published, err := a.publishWebsocketEventForPermalinkPost(post, message) + published, err := a.publishWebsocketEventForPermalinkPost(c, post, message) if err != nil { return nil, err } @@ -579,7 +583,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod if profileMap[uid] == nil { continue } - if a.IsCRTEnabledForUser(uid) { + if a.IsCRTEnabledForUser(c, uid) { message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, team.Id, "", uid, nil) threadMembership := participantMemberships[uid] if threadMembership == nil { @@ -626,7 +630,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod a.sanitizeProfiles(userThread.Participants, false) userThread.Post.SanitizeProps() - sanitizedPost, err := a.SanitizePostMetadataForUser(userThread.Post, uid) + sanitizedPost, err := a.SanitizePostMetadataForUser(c, userThread.Post, uid) if err != nil { return nil, err } @@ -655,7 +659,7 @@ func max(a, b int64) int64 { return a } -func (a *App) userAllowsEmail(user *model.User, channelMemberNotificationProps model.StringMap, post *model.Post) bool { +func (a *App) userAllowsEmail(c request.CTX, user *model.User, channelMemberNotificationProps model.StringMap, post *model.Post) bool { // if user is a bot account, then we do not send email if user.IsBot { return false @@ -664,7 +668,7 @@ func (a *App) userAllowsEmail(user *model.User, channelMemberNotificationProps m userAllowsEmails := user.NotifyProps[model.EmailNotifyProp] != "false" // if CRT is ON for user and the post is a reply disregard the channelEmail setting - if channelEmail, ok := channelMemberNotificationProps[model.EmailNotifyProp]; ok && !(a.IsCRTEnabledForUser(user.Id) && post.RootId != "") { + if channelEmail, ok := channelMemberNotificationProps[model.EmailNotifyProp]; ok && !(a.IsCRTEnabledForUser(c, user.Id) && post.RootId != "") { if channelEmail != model.ChannelNotifyDefault { userAllowsEmails = channelEmail != "false" } @@ -696,7 +700,7 @@ func (a *App) userAllowsEmail(user *model.User, channelMemberNotificationProps m return userAllowsEmails && emailNotificationsAllowedForStatus && user.DeleteAt == 0 && !autoResponderRelated } -func (a *App) sendNoUsersNotifiedByGroupInChannel(sender *model.User, post *model.Post, channel *model.Channel, group *model.Group) { +func (a *App) sendNoUsersNotifiedByGroupInChannel(c request.CTX, sender *model.User, post *model.Post, channel *model.Channel, group *model.Group) { T := i18n.GetUserTranslations(sender.Locale) ephemeralPost := &model.Post{ UserId: sender.Id, @@ -704,12 +708,12 @@ func (a *App) sendNoUsersNotifiedByGroupInChannel(sender *model.User, post *mode ChannelId: channel.Id, Message: T("api.post.check_for_out_of_channel_group_users.message.none", model.StringInterface{"GroupName": group.Name}), } - a.SendEphemeralPost(post.UserId, ephemeralPost) + a.SendEphemeralPost(c, post.UserId, ephemeralPost) } // sendOutOfChannelMentions sends an ephemeral post to the sender of a post if any of the given potential mentions // are outside of the post's channel. Returns whether or not an ephemeral post was sent. -func (a *App) sendOutOfChannelMentions(sender *model.User, post *model.Post, channel *model.Channel, potentialMentions []string) (bool, error) { +func (a *App) sendOutOfChannelMentions(c request.CTX, sender *model.User, post *model.Post, channel *model.Channel, potentialMentions []string) (bool, error) { outOfChannelUsers, outOfGroupsUsers, err := a.filterOutOfChannelMentions(sender, post, channel, potentialMentions) if err != nil { return false, err @@ -719,7 +723,7 @@ func (a *App) sendOutOfChannelMentions(sender *model.User, post *model.Post, cha return false, nil } - a.SendEphemeralPost(post.UserId, makeOutOfChannelMentionPost(sender, post, outOfChannelUsers, outOfGroupsUsers)) + a.SendEphemeralPost(c, post.UserId, makeOutOfChannelMentionPost(sender, post, outOfChannelUsers, outOfGroupsUsers)) return true, nil } @@ -1021,8 +1025,8 @@ func getMentionsEnabledFields(post *model.Post) model.StringArray { } // allowChannelMentions returns whether or not the channel mentions are allowed for the given post. -func (a *App) allowChannelMentions(post *model.Post, numProfiles int) bool { - if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseChannelMentions) { +func (a *App) allowChannelMentions(c request.CTX, post *model.Post, numProfiles int) bool { + if !a.HasPermissionToChannel(c, post.UserId, post.ChannelId, model.PermissionUseChannelMentions) { return false } @@ -1038,12 +1042,12 @@ func (a *App) allowChannelMentions(post *model.Post, numProfiles int) bool { } // allowGroupMentions returns whether or not the group mentions are allowed for the given post. -func (a *App) allowGroupMentions(post *model.Post) bool { +func (a *App) allowGroupMentions(c request.CTX, post *model.Post) bool { if license := a.Srv().License(); license == nil || (license.SkuShortName != model.LicenseShortSkuProfessional && license.SkuShortName != model.LicenseShortSkuEnterprise) { return false } - if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseGroupMentions) { + if !a.HasPermissionToChannel(c, post.UserId, post.ChannelId, model.PermissionUseGroupMentions) { return false } diff --git a/app/notification_email.go b/app/notification_email.go index 12b7501607..2736ac7213 100644 --- a/app/notification_email.go +++ b/app/notification_email.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/i18n" "github.com/mattermost/mattermost-server/v6/shared/mlog" @@ -19,7 +20,7 @@ import ( "github.com/pkg/errors" ) -func (a *App) sendNotificationEmail(notification *PostNotification, user *model.User, team *model.Team, senderProfileImage []byte) error { +func (a *App) sendNotificationEmail(c request.CTX, notification *PostNotification, user *model.User, team *model.Team, senderProfileImage []byte) error { channel := notification.Channel post := notification.Post @@ -107,7 +108,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. landingURL := a.GetSiteURL() + "/landing#/" + team.Name - var bodyText, err = a.getNotificationEmailBody(user, post, channel, channelName, senderName, team.Name, landingURL, emailNotificationContentsType, useMilitaryTime, translateFunc, senderPhoto) + var bodyText, err = a.getNotificationEmailBody(c, user, post, channel, channelName, senderName, team.Name, landingURL, emailNotificationContentsType, useMilitaryTime, translateFunc, senderPhoto) if err != nil { return errors.Wrap(err, "unable to render the email notification template") } @@ -215,7 +216,7 @@ type postData struct { /** * Computes the email body for notification messages */ -func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, channel *model.Channel, channelName string, senderName string, teamName string, landingURL string, emailNotificationContentsType string, useMilitaryTime bool, translateFunc i18n.TranslateFunc, senderPhoto string) (string, error) { +func (a *App) getNotificationEmailBody(c request.CTX, recipient *model.User, post *model.Post, channel *model.Channel, channelName string, senderName string, teamName string, landingURL string, emailNotificationContentsType string, useMilitaryTime bool, translateFunc i18n.TranslateFunc, senderPhoto string) (string, error) { pData := postData{ SenderName: truncateUserNames(senderName, 22), SenderPhoto: senderPhoto, @@ -237,7 +238,7 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, mdPostMessage = postMessage } - normalizedPostMessage, err := a.generateHyperlinkForChannels(mdPostMessage, teamName, landingURL) + normalizedPostMessage, err := a.generateHyperlinkForChannels(c, mdPostMessage, teamName, landingURL) if err != nil { mlog.Warn("Encountered error while generating hyperlink for channels", mlog.String("team_name", teamName), mlog.Err(err)) normalizedPostMessage = mdPostMessage @@ -276,7 +277,7 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, } // Override title and subtile for replies with CRT enabled - if a.IsCRTEnabledForUser(recipient.Id) && post.RootId != "" { + if a.IsCRTEnabledForUser(c, recipient.Id) && post.RootId != "" { // Title is the same in all cases data.Props["Title"] = translateFunc("app.notification.body.thread.title", map[string]any{"SenderName": senderName}) @@ -347,7 +348,7 @@ func getFormattedPostTime(user *model.User, post *model.Post, useMilitaryTime bo } } -func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string) (string, *model.AppError) { +func (a *App) generateHyperlinkForChannels(c request.CTX, postMessage, teamName, teamURL string) (string, *model.AppError) { team, err := a.GetTeamByName(teamName) if err != nil { return "", err @@ -358,7 +359,7 @@ func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string return postMessage, nil } - channels, err := a.GetChannelsByNames(channelNames, team.Id) + channels, err := a.GetChannelsByNames(c, channelNames, team.Id) if err != nil { return "", err } diff --git a/app/notification_email_test.go b/app/notification_email_test.go index 41b58e71d4..312cd03872 100644 --- a/app/notification_email_test.go +++ b/app/notification_email_test.go @@ -90,7 +90,7 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "mentioned you in a message", fmt.Sprintf("Expected email text 'mentioned you in a message. Got %s", body)) require.Contains(t, body, post.Message, fmt.Sprintf("Expected email text '%s'. Got %s", post.Message, body)) @@ -121,7 +121,7 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "sent you a new message", fmt.Sprintf("Expected email text 'sent you a new message. Got "+body)) require.Contains(t, body, post.Message, fmt.Sprintf("Expected email text '%s'. Got %s", post.Message, body)) @@ -152,7 +152,7 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "mentioned you in a message", fmt.Sprintf("Expected email text 'mentioned you in a message. Got "+body)) require.Contains(t, body, post.Message, fmt.Sprintf("Expected email text '%s'. Got %s", post.Message, body)) @@ -183,7 +183,7 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "sent you a new message", fmt.Sprintf("Expected email text 'sent you a new message. Got "+body)) require.Contains(t, body, post.Message, fmt.Sprintf("Expected email text '%s'. Got %s", post.Message, body)) @@ -218,7 +218,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeWithTimezone(t *testi teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, false, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, false, translateFunc, "user-avatar.png") require.NoError(t, err) r, _ := regexp.Compile("E([S|D]+)T") zone := r.FindString(body) @@ -267,7 +267,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeNoTimezone(t *testing err = tmp.Execute(&text, fmt.Sprintf("%s:%s %s", formattedTime.Hour, formattedTime.Minute, formattedTime.TimeZone)) require.NoError(t, err) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) postTimeLine := text.String() require.Contains(t, body, postTimeLine, fmt.Sprintf("Expected email text '%s'. Got %s", postTimeLine, body)) @@ -301,7 +301,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime12Hour(t *testing.T) teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, false, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, false, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "2:30 PM", fmt.Sprintf("Expected email text '2:30 PM'. Got %s", body)) } @@ -334,7 +334,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime24Hour(t *testing.T) teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "14:30", fmt.Sprintf("Expected email text '14:30'. Got %s", body)) } @@ -364,7 +364,7 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "mentioned you in a message", fmt.Sprintf("Expected email text 'mentioned you in a message. Got %s", body)) require.Contains(t, body, teamURL, fmt.Sprintf("Expected email text '%s'. Got %s", teamURL, body)) @@ -394,7 +394,7 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "sent you a new message", fmt.Sprintf("Expected email text 'sent you a new message. Got "+body)) require.Contains(t, body, teamURL, fmt.Sprintf("Expected email text '%s'. Got %s", teamURL, body)) @@ -424,7 +424,7 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "mentioned you in a message", fmt.Sprintf("Expected email text 'mentioned you in a message. Got %s", body)) require.Contains(t, body, teamURL, fmt.Sprintf("Expected email text '%s'. Got %s", teamURL, body)) @@ -454,7 +454,7 @@ func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T) teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, "sent you a new message", fmt.Sprintf("Expected email text 'sent you a new message. Got "+body)) require.Contains(t, body, teamURL, fmt.Sprintf("Expected email text '%s'. Got %s", teamURL, body)) @@ -486,7 +486,7 @@ func TestGetNotificationEmailEscapingChars(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, ch, + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, ch, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) @@ -530,7 +530,7 @@ func TestGetNotificationEmailBodyPublicChannelMention(t *testing.T) { channelStoreMock.On("GetByNames", "test", []string{ch.Name}, true).Return([]*model.Channel{ch}, nil) storeMock.On("Channel").Return(&channelStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, ch, + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, ch, ch.Name, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) @@ -596,7 +596,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) { channelStoreMock.On("GetByNames", "test", []string{ch.Name, ch2.Name, ch3.Name}, true).Return([]*model.Channel{ch, ch2, ch3}, nil) storeMock.On("Channel").Return(&channelStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, ch, + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, ch, ch.Name, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) @@ -645,7 +645,7 @@ func TestGetNotificationEmailBodyPrivateChannelMention(t *testing.T) { channelStoreMock.On("GetByNames", "test", []string{ch.Name}, true).Return([]*model.Channel{ch}, nil) storeMock.On("Channel").Return(&channelStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, ch, + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, ch, ch.Name, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) @@ -678,7 +678,7 @@ func TestGenerateHyperlinkForChannelsPublic(t *testing.T) { channelStoreMock.On("GetByNames", "test", []string{ch.Name}, true).Return([]*model.Channel{ch}, nil) storeMock.On("Channel").Return(&channelStoreMock) - outMessage, err := th.App.generateHyperlinkForChannels(message+mention, teamName, teamURL) + outMessage, err := th.App.generateHyperlinkForChannels(th.Context, message+mention, teamName, teamURL) require.Nil(t, err) channelURL := teamURL + "/channels/" + ch.Name assert.Equal(t, message+""+mention+"", outMessage) @@ -728,7 +728,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) { channelStoreMock.On("GetByNames", "test", []string{ch.Name, ch2.Name, ch3.Name}, true).Return([]*model.Channel{ch, ch2, ch3}, nil) storeMock.On("Channel").Return(&channelStoreMock) - outMessage, err := th.App.generateHyperlinkForChannels(message, teamName, teamURL) + outMessage, err := th.App.generateHyperlinkForChannels(th.Context, message, teamName, teamURL) require.Nil(t, err) channelURL := teamURL + "/channels/" + ch.Name channelURL2 := teamURL + "/channels/" + ch2.Name @@ -762,7 +762,7 @@ func TestGenerateHyperlinkForChannelsPrivate(t *testing.T) { channelStoreMock.On("GetByNames", "test", []string{ch.Name}, true).Return([]*model.Channel{ch}, nil) storeMock.On("Channel").Return(&channelStoreMock) - outMessage, err := th.App.generateHyperlinkForChannels(message, teamName, teamURL) + outMessage, err := th.App.generateHyperlinkForChannels(th.Context, message, teamName, teamURL) require.Nil(t, err) assert.Equal(t, message, outMessage) } @@ -791,7 +791,7 @@ func TestLandingLink(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, teamURL, fmt.Sprintf("Expected email text '%s'. Got %s", teamURL, body)) } @@ -821,7 +821,7 @@ func TestLandingLinkPermalink(t *testing.T) { teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) - body, err := th.App.getNotificationEmailBody(recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") + body, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, channelName, senderName, teamName, teamURL, emailNotificationContentsType, true, translateFunc, "user-avatar.png") require.NoError(t, err) require.Contains(t, body, teamURL+"/pl/"+post.Id, fmt.Sprintf("Expected email text '%s'. Got %s", teamURL, body)) } @@ -928,7 +928,7 @@ func TestMarkdownConversion(t *testing.T) { Id: "Test_id", Message: tt.args, } - got, err := th.App.getNotificationEmailBody(recipient, post, channel, "ChannelName", "sender", "testteam", "http://localhost:8065/landing#/testteam", model.EmailNotificationContentsFull, true, i18n.GetUserTranslations("en"), "user-avatar.png") + got, err := th.App.getNotificationEmailBody(th.Context, recipient, post, channel, "ChannelName", "sender", "testteam", "http://localhost:8065/landing#/testteam", model.EmailNotificationContentsFull, true, i18n.GetUserTranslations("en"), "user-avatar.png") require.NoError(t, err) require.Contains(t, got, tt.want) }) diff --git a/app/notification_push.go b/app/notification_push.go index 7d8421ea30..d7c2232253 100644 --- a/app/notification_push.go +++ b/app/notification_push.go @@ -15,6 +15,7 @@ import ( "github.com/pkg/errors" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/i18n" "github.com/mattermost/mattermost-server/v6/shared/mlog" @@ -56,10 +57,11 @@ type PushNotification struct { replyToThreadType string } -func (a *App) sendPushNotificationSync(post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, +func (a *App) sendPushNotificationSync(c request.CTX, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) *model.AppError { cfg := a.Config() msg, appErr := a.BuildPushNotificationMessage( + c, *cfg.EmailSettings.PushNotificationContents, post, user, @@ -218,7 +220,7 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp return senderName + userLocale("api.post.send_notifications_and_forget.push_general_message") } -func (a *App) clearPushNotificationSync(currentSessionId, userID, channelID, rootID string) *model.AppError { +func (a *App) clearPushNotificationSync(c request.CTX, currentSessionId, userID, channelID, rootID string) *model.AppError { msg := &model.PushNotification{ Type: model.PushTypeClear, Version: model.PushMessageV2, @@ -226,7 +228,7 @@ func (a *App) clearPushNotificationSync(currentSessionId, userID, channelID, roo RootId: rootID, ContentAvailable: 1, Badge: 0, - IsCRTEnabled: a.IsCRTEnabledForUser(userID), + IsCRTEnabled: a.IsCRTEnabledForUser(c, userID), } unreadCount, err := a.Srv().Store.User().GetUnreadCount(userID) @@ -288,7 +290,7 @@ func (a *App) UpdateMobileAppBadge(userID string) { } } -func (s *Server) createPushNotificationsHub() { +func (s *Server) createPushNotificationsHub(c request.CTX) { buffer := *s.Config().EmailSettings.PushNotificationBuffer hub := PushNotificationsHub{ notificationsChan: make(chan PushNotification, buffer), @@ -299,11 +301,11 @@ func (s *Server) createPushNotificationsHub() { stopChan: make(chan struct{}), buffer: buffer, } - go hub.start() + go hub.start(c) s.PushNotificationsHub = hub } -func (hub *PushNotificationsHub) start() { +func (hub *PushNotificationsHub) start(c request.CTX) { hub.wg.Add(1) defer hub.wg.Done() for { @@ -330,9 +332,10 @@ func (hub *PushNotificationsHub) start() { var err *model.AppError switch notification.notificationType { case notificationTypeClear: - err = hub.app.clearPushNotificationSync(notification.currentSessionId, notification.userID, notification.channelID, notification.rootID) + err = hub.app.clearPushNotificationSync(c, notification.currentSessionId, notification.userID, notification.channelID, notification.rootID) case notificationTypeMessage: err = hub.app.sendPushNotificationSync( + c, notification.post, notification.user, notification.channel, @@ -552,7 +555,7 @@ func DoesStatusAllowPushNotification(userNotifyProps model.StringMap, status *mo return false } -func (a *App) BuildPushNotificationMessage(contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, +func (a *App) BuildPushNotificationMessage(c request.CTX, contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError) { var msg *model.PushNotification @@ -563,9 +566,9 @@ func (a *App) BuildPushNotificationMessage(contentsConfig string, post *model.Po } if contentsConfig == model.IdLoadedNotification { - msg = a.buildIdLoadedPushNotificationMessage(channel, post, user) + msg = a.buildIdLoadedPushNotificationMessage(c, channel, post, user) } else { - msg = a.buildFullPushNotificationMessage(contentsConfig, post, user, channel, channelName, senderName, explicitMention, channelWideMention, replyToThreadType) + msg = a.buildFullPushNotificationMessage(c, contentsConfig, post, user, channel, channelName, senderName, explicitMention, channelWideMention, replyToThreadType) } unreadCount, err := a.Srv().Store.User().GetUnreadCount(user.Id) @@ -615,13 +618,13 @@ func (a *App) SendTestPushNotification(deviceID string) string { return "true" } -func (a *App) buildIdLoadedPushNotificationMessage(channel *model.Channel, post *model.Post, user *model.User) *model.PushNotification { +func (a *App) buildIdLoadedPushNotificationMessage(c request.CTX, channel *model.Channel, post *model.Post, user *model.User) *model.PushNotification { userLocale := i18n.GetUserTranslations(user.Locale) msg := &model.PushNotification{ PostId: post.Id, ChannelId: post.ChannelId, RootId: post.RootId, - IsCRTEnabled: a.IsCRTEnabledForUser(user.Id), + IsCRTEnabled: a.IsCRTEnabledForUser(c, user.Id), Category: model.CategoryCanReply, Version: model.PushMessageV2, TeamId: channel.TeamId, @@ -634,7 +637,7 @@ func (a *App) buildIdLoadedPushNotificationMessage(channel *model.Channel, post return msg } -func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, +func (a *App) buildFullPushNotificationMessage(c request.CTX, contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) *model.PushNotification { msg := &model.PushNotification{ @@ -656,7 +659,7 @@ func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *mode msg.ChannelName = channelName } - if a.IsCRTEnabledForUser(user.Id) { + if a.IsCRTEnabledForUser(c, user.Id) { msg.IsCRTEnabled = true if post.RootId != "" { if contentsConfig != model.GenericNoChannelNotification { diff --git a/app/notification_push_test.go b/app/notification_push_test.go index 40244c479f..53ac88db13 100644 --- a/app/notification_push_test.go +++ b/app/notification_push_test.go @@ -941,11 +941,11 @@ func TestBuildPushNotificationMessageMentions(t *testing.T) { receiver := th.CreateUser() th.LinkUserToTeam(sender, team) th.LinkUserToTeam(receiver, team) - channel1 := th.CreateChannel(team) + channel1 := th.CreateChannel(th.Context, team) th.AddUserToChannel(sender, channel1) th.AddUserToChannel(receiver, channel1) - channel2 := th.CreateChannel(team) + channel2 := th.CreateChannel(th.Context, team) th.AddUserToChannel(sender, channel2) th.AddUserToChannel(receiver, channel2) @@ -981,7 +981,7 @@ func TestBuildPushNotificationMessageMentions(t *testing.T) { } { t.Run(name, func(t *testing.T) { receiver.NotifyProps["push"] = tc.pushNotifyProps - msg, err := th.App.BuildPushNotificationMessage(model.FullNotification, post, receiver, channel1, channel1.Name, sender.Username, tc.explicitMention, tc.channelWideMention, tc.replyToThreadType) + msg, err := th.App.BuildPushNotificationMessage(th.Context, model.FullNotification, post, receiver, channel1, channel1.Name, sender.Username, tc.explicitMention, tc.channelWideMention, tc.replyToThreadType) require.Nil(t, err) assert.Equal(t, tc.expectedBadge, msg.Badge) }) @@ -1158,7 +1158,7 @@ func TestClearPushNotificationSync(t *testing.T) { *cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDisabled }) - err := th.App.clearPushNotificationSync(sess1.Id, "user1", "channel1", "") + err := th.App.clearPushNotificationSync(th.Context, sess1.Id, "user1", "channel1", "") require.Nil(t, err) // Server side verification. // We verify that 1 request has been sent, and also check the message contents. @@ -1180,7 +1180,7 @@ func TestClearPushNotificationSync(t *testing.T) { mockThreadStore.On("GetTotalUnreadMentions", mock.AnythingOfType("string"), mock.AnythingOfType("string"), mock.Anything).Return(int64(3), nil) mockStore.On("Thread").Return(&mockThreadStore) - err = th.App.clearPushNotificationSync(sess1.Id, "user1", "channel1", "") + err = th.App.clearPushNotificationSync(th.Context, sess1.Id, "user1", "channel1", "") require.Nil(t, err) assert.Equal(t, handler.notifications()[1].Badge, 4) } @@ -1425,6 +1425,9 @@ func TestAllPushNotifications(t *testing.T) { } func TestPushNotificationRace(t *testing.T) { + th := Setup(t) + defer th.TearDown() + memoryStore := config.NewTestMemoryStore() mockStore := testlib.GetMockStoreForSetupFunctions() mockPreferenceStore := mocks.PreferenceStore{} @@ -1452,7 +1455,7 @@ func TestPushNotificationRace(t *testing.T) { app := New(ServerConnector(s.Channels())) require.NotPanics(t, func() { - s.createPushNotificationsHub() + s.createPushNotificationsHub(th.Context) s.StopPushNotificationsHubWorkers() @@ -1495,7 +1498,7 @@ func TestPushNotificationAttachment(t *testing.T) { ch := &model.Channel{} t.Run("The notification should contain the fallback message from the attachment", func(t *testing.T) { - pn := th.App.buildFullPushNotificationMessage("full", post, user, ch, ch.Name, "test", false, false, "") + pn := th.App.buildFullPushNotificationMessage(th.Context, "full", post, user, ch, ch.Name, "test", false, false, "") assert.Equal(t, "test: hello world\nfallback text", pn.Message) }) diff --git a/app/notification_test.go b/app/notification_test.go index f023385c0d..4d482d9bba 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -34,7 +34,7 @@ func TestSendNotifications(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser2, th.BasicChannel, false) post1, appErr := th.App.CreatePostMissingChannel(th.Context, &model.Post{ UserId: th.BasicUser.Id, @@ -45,7 +45,7 @@ func TestSendNotifications(t *testing.T) { }, true) require.Nil(t, appErr) - mentions, err := th.App.SendNotifications(post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) + mentions, err := th.App.SendNotifications(th.Context, post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) require.NoError(t, err) require.NotNil(t, mentions) require.True(t, utils.StringInSlice(th.BasicUser2.Id, mentions), "mentions", mentions) @@ -68,14 +68,14 @@ func TestSendNotifications(t *testing.T) { groupMentionPost, createPostErr := th.App.CreatePost(th.Context, groupMentionPost, th.BasicChannel, false, true) require.Nil(t, createPostErr) - mentions, err = th.App.SendNotifications(groupMentionPost, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) + mentions, err = th.App.SendNotifications(th.Context, groupMentionPost, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) require.NoError(t, err) require.NotNil(t, mentions) require.Len(t, mentions, 0) th.App.Srv().SetLicense(getLicWithSkuShortName(model.LicenseShortSkuProfessional)) - mentions, err = th.App.SendNotifications(groupMentionPost, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) + mentions, err = th.App.SendNotifications(th.Context, groupMentionPost, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) require.NoError(t, err) require.NotNil(t, mentions) require.Len(t, mentions, 1) @@ -91,7 +91,7 @@ func TestSendNotifications(t *testing.T) { }, true) require.Nil(t, appErr) - mentions, err = th.App.SendNotifications(post2, th.BasicTeam, dm, th.BasicUser, nil, true) + mentions, err = th.App.SendNotifications(th.Context, post2, th.BasicTeam, dm, th.BasicUser, nil, true) require.NoError(t, err) require.NotNil(t, mentions) @@ -107,12 +107,12 @@ func TestSendNotifications(t *testing.T) { }, true) require.Nil(t, appErr) - mentions, err = th.App.SendNotifications(post3, th.BasicTeam, dm, th.BasicUser, nil, true) + mentions, err = th.App.SendNotifications(th.Context, post3, th.BasicTeam, dm, th.BasicUser, nil, true) require.NoError(t, err) require.NotNil(t, mentions) th.BasicChannel.DeleteAt = 1 - mentions, err = th.App.SendNotifications(post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) + mentions, err = th.App.SendNotifications(th.Context, post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil, true) require.NoError(t, err) require.Empty(t, mentions) @@ -143,7 +143,7 @@ func TestSendNotifications(t *testing.T) { Order: []string{rootPost.Id, childPost.Id}, Posts: map[string]*model.Post{rootPost.Id: rootPost, childPost.Id: childPost}, } - mentions, err = th.App.SendNotifications(childPost, th.BasicTeam, th.BasicChannel, th.BasicUser2, &postList, true) + mentions, err = th.App.SendNotifications(th.Context, childPost, th.BasicTeam, th.BasicChannel, th.BasicUser2, &postList, true) require.NoError(t, err) require.False(t, utils.StringInSlice(user.Id, mentions)) } @@ -172,7 +172,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { for i := 0; i < 10; i++ { user := th.CreateUser() th.LinkUserToTeam(user, th.BasicTeam) - th.App.AddUserToChannel(user, th.BasicChannel, false) + th.App.AddUserToChannel(th.Context, user, th.BasicChannel, false) users = append(users, user) } @@ -230,7 +230,7 @@ func TestSendOutOfChannelMentions(t *testing.T) { post := &model.Post{} potentialMentions := []string{user2.Username} - sent, err := th.App.sendOutOfChannelMentions(user1, post, channel, potentialMentions) + sent, err := th.App.sendOutOfChannelMentions(th.Context, user1, post, channel, potentialMentions) assert.NoError(t, err) assert.True(t, sent) @@ -240,7 +240,7 @@ func TestSendOutOfChannelMentions(t *testing.T) { post := &model.Post{} potentialMentions := []string{"not a user"} - sent, err := th.App.sendOutOfChannelMentions(user1, post, channel, potentialMentions) + sent, err := th.App.sendOutOfChannelMentions(th.Context, user1, post, channel, potentialMentions) assert.NoError(t, err) assert.False(t, sent) @@ -258,14 +258,14 @@ func TestFilterOutOfChannelMentions(t *testing.T) { user3 := th.CreateUser() guest := th.CreateGuest() user4 := th.CreateUser() - guestAndUser4Channel := th.CreateChannel(th.BasicTeam) + guestAndUser4Channel := th.CreateChannel(th.Context, th.BasicTeam) defer th.App.PermanentDeleteUser(th.Context, guest) th.LinkUserToTeam(user3, th.BasicTeam) th.LinkUserToTeam(user4, th.BasicTeam) th.LinkUserToTeam(guest, th.BasicTeam) - th.App.AddUserToChannel(guest, channel, false) - th.App.AddUserToChannel(user4, guestAndUser4Channel, false) - th.App.AddUserToChannel(guest, guestAndUser4Channel, false) + th.App.AddUserToChannel(th.Context, guest, channel, false) + th.App.AddUserToChannel(th.Context, user4, guestAndUser4Channel, false) + th.App.AddUserToChannel(th.Context, guest, guestAndUser4Channel, false) t.Run("should return users not in the channel", func(t *testing.T) { post := &model.Post{} @@ -385,9 +385,9 @@ func TestFilterOutOfChannelMentions(t *testing.T) { _, appErr = th.App.UpsertGroupMember(group.Id, nonChannelMember.Id) require.Nil(t, appErr) - constrainedChannel := th.CreateChannel(th.BasicTeam) + constrainedChannel := th.CreateChannel(th.Context, th.BasicTeam) constrainedChannel.GroupConstrained = model.NewBool(true) - constrainedChannel, appErr = th.App.UpdateChannel(constrainedChannel) + constrainedChannel, appErr = th.App.UpdateChannel(th.Context, constrainedChannel) require.Nil(t, appErr) _, appErr = th.App.UpsertGroupSyncable(&model.GroupSyncable{ @@ -1056,24 +1056,24 @@ func TestAllowChannelMentions(t *testing.T) { post := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id} t.Run("should return true for a regular post with few channel members", func(t *testing.T) { - allowChannelMentions := th.App.allowChannelMentions(post, 5) + allowChannelMentions := th.App.allowChannelMentions(th.Context, post, 5) assert.True(t, allowChannelMentions) }) t.Run("should return false for a channel header post", func(t *testing.T) { headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypeHeaderChange} - allowChannelMentions := th.App.allowChannelMentions(headerChangePost, 5) + allowChannelMentions := th.App.allowChannelMentions(th.Context, headerChangePost, 5) assert.False(t, allowChannelMentions) }) t.Run("should return false for a channel purpose post", func(t *testing.T) { purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypePurposeChange} - allowChannelMentions := th.App.allowChannelMentions(purposeChangePost, 5) + allowChannelMentions := th.App.allowChannelMentions(th.Context, purposeChangePost, 5) assert.False(t, allowChannelMentions) }) t.Run("should return false for a regular post with many channel members", func(t *testing.T) { - allowChannelMentions := th.App.allowChannelMentions(post, int(*th.App.Config().TeamSettings.MaxNotificationsPerChannel)+1) + allowChannelMentions := th.App.allowChannelMentions(th.Context, post, int(*th.App.Config().TeamSettings.MaxNotificationsPerChannel)+1) assert.False(t, allowChannelMentions) }) @@ -1082,7 +1082,7 @@ func TestAllowChannelMentions(t *testing.T) { defer th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId) th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId) - allowChannelMentions := th.App.allowChannelMentions(post, 5) + allowChannelMentions := th.App.allowChannelMentions(th.Context, post, 5) assert.False(t, allowChannelMentions) }) } @@ -1108,26 +1108,26 @@ func TestAllowGroupMentions(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { th.App.Srv().SetLicense(tc.license) - got := th.App.allowGroupMentions(post) + got := th.App.allowGroupMentions(th.Context, post) assert.Equal(t, tc.want, got) }) } }) t.Run("should return true for a regular post with few channel members", func(t *testing.T) { - allowGroupMentions := th.App.allowGroupMentions(post) + allowGroupMentions := th.App.allowGroupMentions(th.Context, post) assert.True(t, allowGroupMentions) }) t.Run("should return false for a channel header post", func(t *testing.T) { headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypeHeaderChange} - allowGroupMentions := th.App.allowGroupMentions(headerChangePost) + allowGroupMentions := th.App.allowGroupMentions(th.Context, headerChangePost) assert.False(t, allowGroupMentions) }) t.Run("should return false for a channel purpose post", func(t *testing.T) { purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypePurposeChange} - allowGroupMentions := th.App.allowGroupMentions(purposeChangePost) + allowGroupMentions := th.App.allowGroupMentions(th.Context, purposeChangePost) assert.False(t, allowGroupMentions) }) @@ -1138,7 +1138,7 @@ func TestAllowGroupMentions(t *testing.T) { }() th.RemovePermissionFromRole(model.PermissionUseGroupMentions.Id, model.ChannelUserRoleId) th.RemovePermissionFromRole(model.PermissionUseGroupMentions.Id, model.ChannelAdminRoleId) - allowGroupMentions := th.App.allowGroupMentions(post) + allowGroupMentions := th.App.allowGroupMentions(th.Context, post) assert.False(t, allowGroupMentions) }) } @@ -2407,7 +2407,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.True(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) + assert.True(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) }) t.Run("should return false in case the status is ONLINE", func(t *testing.T) { @@ -2420,7 +2420,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) + assert.False(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) }) t.Run("should return false in case the EMAIL_NOTIFY_PROP is false", func(t *testing.T) { @@ -2433,7 +2433,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) + assert.False(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) }) t.Run("should return false in case the MARK_UNREAD_NOTIFY_PROP is CHANNEL_MARK_UNREAD_MENTION", func(t *testing.T) { @@ -2446,7 +2446,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadMention, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) + assert.False(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"})) }) t.Run("should return false in case the Post type is POST_AUTO_RESPONDER", func(t *testing.T) { @@ -2459,7 +2459,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) + assert.False(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) }) t.Run("should return false in case the status is STATUS_OUT_OF_OFFICE", func(t *testing.T) { @@ -2472,7 +2472,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) + assert.False(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) }) t.Run("should return false in case the status is STATUS_ONLINE", func(t *testing.T) { @@ -2485,7 +2485,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) + assert.False(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder})) }) t.Run("should return false in the case user is a bot", func(t *testing.T) { @@ -2498,7 +2498,7 @@ func TestUserAllowsEmail(t *testing.T) { model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll, } - assert.False(t, th.App.userAllowsEmail(user, channelMemberNotifcationProps, &model.Post{Type: model.PostTypeAutoResponder})) + assert.False(t, th.App.userAllowsEmail(th.Context, user, channelMemberNotifcationProps, &model.Post{Type: model.PostTypeAutoResponder})) }) } @@ -2517,13 +2517,13 @@ func TestInsertGroupMentions(t *testing.T) { groupChannelMember := th.CreateUser() th.LinkUserToTeam(groupChannelMember, team) - th.App.AddUserToChannel(groupChannelMember, channel, false) + th.App.AddUserToChannel(th.Context, groupChannelMember, channel, false) _, err = th.App.UpsertGroupMember(group.Id, groupChannelMember.Id) require.Nil(t, err) nonGroupChannelMember := th.CreateUser() th.LinkUserToTeam(nonGroupChannelMember, team) - th.App.AddUserToChannel(nonGroupChannelMember, channel, false) + th.App.AddUserToChannel(th.Context, nonGroupChannelMember, channel, false) nonChannelGroupMember := th.CreateUser() th.LinkUserToTeam(nonChannelGroupMember, team) @@ -2593,7 +2593,7 @@ func TestInsertGroupMentions(t *testing.T) { }) t.Run("should add mentions for members while in group channel", func(t *testing.T) { - groupChannel, err := th.App.CreateGroupChannel([]string{groupChannelMember.Id, nonGroupChannelMember.Id, th.BasicUser.Id}, groupChannelMember.Id) + groupChannel, err := th.App.CreateGroupChannel(th.Context, []string{groupChannelMember.Id, nonGroupChannelMember.Id, th.BasicUser.Id}, groupChannelMember.Id) require.Nil(t, err) mentions := &ExplicitMentions{} @@ -2639,9 +2639,9 @@ func TestGetGroupsAllowedForReferenceInChannel(t *testing.T) { require.Nil(t, err) // Sync first group to constrained channel - constrainedChannel := th.CreateChannel(th.BasicTeam) + constrainedChannel := th.CreateChannel(th.Context, th.BasicTeam) constrainedChannel.GroupConstrained = model.NewBool(true) - constrainedChannel, err = th.App.UpdateChannel(constrainedChannel) + constrainedChannel, err = th.App.UpdateChannel(th.Context, constrainedChannel) require.Nil(t, err) _, err = th.App.UpsertGroupSyncable(&model.GroupSyncable{ GroupId: group1.Id, @@ -2812,7 +2812,7 @@ func TestReplyPostNotificationsWithCRT(t *testing.T) { Order: []string{rootPost.Id, childPost.Id}, Posts: map[string]*model.Post{rootPost.Id: rootPost, childPost.Id: childPost}, } - mentions, err := th.App.SendNotifications(childPost, th.BasicTeam, th.BasicChannel, th.BasicUser2, &postList, true) + mentions, err := th.App.SendNotifications(th.Context, childPost, th.BasicTeam, th.BasicChannel, th.BasicUser2, &postList, true) require.NoError(t, err) assert.False(t, utils.StringInSlice(user.Id, mentions)) diff --git a/app/opentracing/opentracing_layer.go b/app/opentracing/opentracing_layer.go index 38ee875a61..d31592efe5 100644 --- a/app/opentracing/opentracing_layer.go +++ b/app/opentracing/opentracing_layer.go @@ -86,7 +86,7 @@ func (a *OpenTracingAppLayer) ActivateMfa(userID string, token string) *model.Ap return resultVar0 } -func (a *OpenTracingAppLayer) AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts app.ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddChannelMember(c request.CTX, userID string, channel *model.Channel, opts app.ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddChannelMember") @@ -162,7 +162,7 @@ func (a *OpenTracingAppLayer) AddCursorIdsForPostList(originalList *model.PostLi a.app.AddCursorIdsForPostList(originalList, afterPost, beforePost, since, page, perPage, collapsedThreads) } -func (a *OpenTracingAppLayer) AddDirectChannels(teamID string, user *model.User) *model.AppError { +func (a *OpenTracingAppLayer) AddDirectChannels(c request.CTX, teamID string, user *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddDirectChannels") @@ -174,7 +174,7 @@ func (a *OpenTracingAppLayer) AddDirectChannels(teamID string, user *model.User) }() defer span.Finish() - resultVar0 := a.app.AddDirectChannels(teamID, user) + resultVar0 := a.app.AddDirectChannels(c, teamID, user) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -493,7 +493,7 @@ func (a *OpenTracingAppLayer) AddTeamsToRetentionPolicy(policyID string, teamIDs return resultVar0 } -func (a *OpenTracingAppLayer) AddUserToChannel(user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) AddUserToChannel(c request.CTX, user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToChannel") @@ -505,7 +505,7 @@ func (a *OpenTracingAppLayer) AddUserToChannel(user *model.User, channel *model. }() defer span.Finish() - resultVar0, resultVar1 := a.app.AddUserToChannel(user, channel, skipTeamMemberIntegrityCheck) + resultVar0, resultVar1 := a.app.AddUserToChannel(c, user, channel, skipTeamMemberIntegrityCheck) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -826,7 +826,7 @@ func (a *OpenTracingAppLayer) AuthorizeOAuthUser(w http.ResponseWriter, r *http. return resultVar0, resultVar1, resultVar2, resultVar3, resultVar4 } -func (a *OpenTracingAppLayer) AutocompleteChannels(userID string, term string) (model.ChannelListWithTeamData, *model.AppError) { +func (a *OpenTracingAppLayer) AutocompleteChannels(c request.CTX, userID string, term string) (model.ChannelListWithTeamData, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteChannels") @@ -838,7 +838,7 @@ func (a *OpenTracingAppLayer) AutocompleteChannels(userID string, term string) ( }() defer span.Finish() - resultVar0, resultVar1 := a.app.AutocompleteChannels(userID, term) + resultVar0, resultVar1 := a.app.AutocompleteChannels(c, userID, term) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -848,7 +848,7 @@ func (a *OpenTracingAppLayer) AutocompleteChannels(userID string, term string) ( return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AutocompleteChannelsForSearch(teamID string, userID string, term string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) AutocompleteChannelsForSearch(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteChannelsForSearch") @@ -860,7 +860,7 @@ func (a *OpenTracingAppLayer) AutocompleteChannelsForSearch(teamID string, userI }() defer span.Finish() - resultVar0, resultVar1 := a.app.AutocompleteChannelsForSearch(teamID, userID, term) + resultVar0, resultVar1 := a.app.AutocompleteChannelsForSearch(c, teamID, userID, term) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -870,7 +870,7 @@ func (a *OpenTracingAppLayer) AutocompleteChannelsForSearch(teamID string, userI return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) AutocompleteChannelsForTeam(teamID string, userID string, term string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) AutocompleteChannelsForTeam(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteChannelsForTeam") @@ -882,7 +882,7 @@ func (a *OpenTracingAppLayer) AutocompleteChannelsForTeam(teamID string, userID }() defer span.Finish() - resultVar0, resultVar1 := a.app.AutocompleteChannelsForTeam(teamID, userID, term) + resultVar0, resultVar1 := a.app.AutocompleteChannelsForTeam(c, teamID, userID, term) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -973,7 +973,7 @@ func (a *OpenTracingAppLayer) BuildPostReactions(postID string) (*[]app.Reaction return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) BuildPushNotificationMessage(contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError) { +func (a *OpenTracingAppLayer) BuildPushNotificationMessage(c request.CTX, contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BuildPushNotificationMessage") @@ -985,7 +985,7 @@ func (a *OpenTracingAppLayer) BuildPushNotificationMessage(contentsConfig string }() defer span.Finish() - resultVar0, resultVar1 := a.app.BuildPushNotificationMessage(contentsConfig, post, user, channel, channelName, senderName, explicitMention, channelWideMention, replyToThreadType) + resultVar0, resultVar1 := a.app.BuildPushNotificationMessage(c, contentsConfig, post, user, channel, channelName, senderName, explicitMention, channelWideMention, replyToThreadType) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1454,7 +1454,7 @@ func (a *OpenTracingAppLayer) CheckWebConn(userID string, connectionID string) * return resultVar0 } -func (a *OpenTracingAppLayer) ClearChannelMembersCache(channelID string) { +func (a *OpenTracingAppLayer) ClearChannelMembersCache(c request.CTX, channelID string) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearChannelMembersCache") @@ -1466,7 +1466,7 @@ func (a *OpenTracingAppLayer) ClearChannelMembersCache(channelID string) { }() defer span.Finish() - a.app.ClearChannelMembersCache(channelID) + a.app.ClearChannelMembersCache(c, channelID) } func (a *OpenTracingAppLayer) ClearLatestVersionCache() { @@ -1864,7 +1864,7 @@ func (a *OpenTracingAppLayer) CreateBot(c *request.Context, bot *model.Bot) (*mo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) CreateChannel(c request.CTX, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannel") @@ -1886,7 +1886,7 @@ func (a *OpenTracingAppLayer) CreateChannel(c *request.Context, channel *model.C return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model.AppError) { +func (a *OpenTracingAppLayer) CreateChannelScheme(c request.CTX, channel *model.Channel) (*model.Scheme, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannelScheme") @@ -1898,7 +1898,7 @@ func (a *OpenTracingAppLayer) CreateChannelScheme(channel *model.Channel) (*mode }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateChannelScheme(channel) + resultVar0, resultVar1 := a.app.CreateChannelScheme(c, channel) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -1908,7 +1908,7 @@ func (a *OpenTracingAppLayer) CreateChannelScheme(channel *model.Channel) (*mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) CreateChannelWithUser(c request.CTX, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannelWithUser") @@ -2066,7 +2066,7 @@ func (a *OpenTracingAppLayer) CreateGroup(group *model.Group) (*model.Group, *mo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateGroupChannel(userIDs []string, creatorId string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) CreateGroupChannel(c request.CTX, userIDs []string, creatorId string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateGroupChannel") @@ -2078,7 +2078,7 @@ func (a *OpenTracingAppLayer) CreateGroupChannel(userIDs []string, creatorId str }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateGroupChannel(userIDs, creatorId) + resultVar0, resultVar1 := a.app.CreateGroupChannel(c, userIDs, creatorId) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2286,7 +2286,7 @@ func (a *OpenTracingAppLayer) CreatePasswordRecoveryToken(userID string, email s return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) { +func (a *OpenTracingAppLayer) CreatePost(c request.CTX, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePost") @@ -2330,7 +2330,7 @@ func (a *OpenTracingAppLayer) CreatePostAsUser(c *request.Context, post *model.P return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) CreatePostMissingChannel(c request.CTX, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePostMissingChannel") @@ -2440,7 +2440,7 @@ func (a *OpenTracingAppLayer) CreateSession(session *model.Session) (*model.Sess return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateSidebarCategory(userID string, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) { +func (a *OpenTracingAppLayer) CreateSidebarCategory(c request.CTX, userID string, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateSidebarCategory") @@ -2452,7 +2452,7 @@ func (a *OpenTracingAppLayer) CreateSidebarCategory(userID string, teamID string }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateSidebarCategory(userID, teamID, newCategory) + resultVar0, resultVar1 := a.app.CreateSidebarCategory(c, userID, teamID, newCategory) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2528,7 +2528,7 @@ func (a *OpenTracingAppLayer) CreateTermsOfService(text string, userID string) ( return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) { +func (a *OpenTracingAppLayer) CreateUploadSession(c request.CTX, us *model.UploadSession) (*model.UploadSession, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUploadSession") @@ -2540,7 +2540,7 @@ func (a *OpenTracingAppLayer) CreateUploadSession(us *model.UploadSession) (*mod }() defer span.Finish() - resultVar0, resultVar1 := a.app.CreateUploadSession(us) + resultVar0, resultVar1 := a.app.CreateUploadSession(c, us) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -2682,7 +2682,7 @@ func (a *OpenTracingAppLayer) CreateUserWithToken(c *request.Context, user *mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) CreateWebhookPost(c *request.Context, userID string, channel *model.Channel, text string, overrideUsername string, overrideIconURL string, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) CreateWebhookPost(c request.CTX, userID string, channel *model.Channel, text string, overrideUsername string, overrideIconURL string, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateWebhookPost") @@ -2836,7 +2836,7 @@ func (a *OpenTracingAppLayer) DeauthorizeOAuthAppForUser(userID string, appID st return resultVar0 } -func (a *OpenTracingAppLayer) DefaultChannelNames() []string { +func (a *OpenTracingAppLayer) DefaultChannelNames(c request.CTX) []string { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DefaultChannelNames") @@ -2848,7 +2848,7 @@ func (a *OpenTracingAppLayer) DefaultChannelNames() []string { }() defer span.Finish() - resultVar0 := a.app.DefaultChannelNames() + resultVar0 := a.app.DefaultChannelNames(c) return resultVar0 } @@ -2919,7 +2919,7 @@ func (a *OpenTracingAppLayer) DeleteBrandImage() *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { +func (a *OpenTracingAppLayer) DeleteChannel(c request.CTX, channel *model.Channel, userID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteChannel") @@ -2941,7 +2941,7 @@ func (a *OpenTracingAppLayer) DeleteChannel(c *request.Context, channel *model.C return resultVar0 } -func (a *OpenTracingAppLayer) DeleteChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) DeleteChannelScheme(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteChannelScheme") @@ -2953,7 +2953,7 @@ func (a *OpenTracingAppLayer) DeleteChannelScheme(channel *model.Channel) (*mode }() defer span.Finish() - resultVar0, resultVar1 := a.app.DeleteChannelScheme(channel) + resultVar0, resultVar1 := a.app.DeleteChannelScheme(c, channel) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -3242,7 +3242,7 @@ func (a *OpenTracingAppLayer) DeletePluginKey(pluginID string, key string) *mode return resultVar0 } -func (a *OpenTracingAppLayer) DeletePost(postID string, deleteByID string) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) DeletePost(c request.CTX, postID string, deleteByID string) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeletePost") @@ -3254,7 +3254,7 @@ func (a *OpenTracingAppLayer) DeletePost(postID string, deleteByID string) (*mod }() defer span.Finish() - resultVar0, resultVar1 := a.app.DeletePost(postID, deleteByID) + resultVar0, resultVar1 := a.app.DeletePost(c, postID, deleteByID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -3440,7 +3440,7 @@ func (a *OpenTracingAppLayer) DeleteSharedChannelRemote(id string) (bool, error) return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) DeleteSidebarCategory(userID string, teamID string, categoryId string) *model.AppError { +func (a *OpenTracingAppLayer) DeleteSidebarCategory(c request.CTX, userID string, teamID string, categoryId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteSidebarCategory") @@ -3452,7 +3452,7 @@ func (a *OpenTracingAppLayer) DeleteSidebarCategory(userID string, teamID string }() defer span.Finish() - resultVar0 := a.app.DeleteSidebarCategory(userID, teamID, categoryId) + resultVar0 := a.app.DeleteSidebarCategory(c, userID, teamID, categoryId) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -3484,7 +3484,7 @@ func (a *OpenTracingAppLayer) DeleteToken(token *model.Token) *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) DemoteUserToGuest(user *model.User) *model.AppError { +func (a *OpenTracingAppLayer) DemoteUserToGuest(c request.CTX, user *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DemoteUserToGuest") @@ -3496,7 +3496,7 @@ func (a *OpenTracingAppLayer) DemoteUserToGuest(user *model.User) *model.AppErro }() defer span.Finish() - resultVar0 := a.app.DemoteUserToGuest(user) + resultVar0 := a.app.DemoteUserToGuest(c, user) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -4184,7 +4184,7 @@ func (a *OpenTracingAppLayer) FileSize(path string) (int64, *model.AppError) { return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) FillInChannelProps(channel *model.Channel) *model.AppError { +func (a *OpenTracingAppLayer) FillInChannelProps(c request.CTX, channel *model.Channel) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FillInChannelProps") @@ -4196,7 +4196,7 @@ func (a *OpenTracingAppLayer) FillInChannelProps(channel *model.Channel) *model. }() defer span.Finish() - resultVar0 := a.app.FillInChannelProps(channel) + resultVar0 := a.app.FillInChannelProps(c, channel) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -4206,7 +4206,7 @@ func (a *OpenTracingAppLayer) FillInChannelProps(channel *model.Channel) *model. return resultVar0 } -func (a *OpenTracingAppLayer) FillInChannelsProps(channelList model.ChannelList) *model.AppError { +func (a *OpenTracingAppLayer) FillInChannelsProps(c request.CTX, channelList model.ChannelList) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FillInChannelsProps") @@ -4218,7 +4218,7 @@ func (a *OpenTracingAppLayer) FillInChannelsProps(channelList model.ChannelList) }() defer span.Finish() - resultVar0 := a.app.FillInChannelsProps(channelList) + resultVar0 := a.app.FillInChannelsProps(c, channelList) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -4228,7 +4228,7 @@ func (a *OpenTracingAppLayer) FillInChannelsProps(channelList model.ChannelList) return resultVar0 } -func (a *OpenTracingAppLayer) FillInPostProps(post *model.Post, channel *model.Channel) *model.AppError { +func (a *OpenTracingAppLayer) FillInPostProps(c request.CTX, post *model.Post, channel *model.Channel) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FillInPostProps") @@ -4240,7 +4240,7 @@ func (a *OpenTracingAppLayer) FillInPostProps(post *model.Post, channel *model.C }() defer span.Finish() - resultVar0 := a.app.FillInPostProps(post, channel) + resultVar0 := a.app.FillInPostProps(c, post, channel) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -4411,7 +4411,7 @@ func (a *OpenTracingAppLayer) GetActivePluginManifests() ([]*model.Manifest, *mo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetAllChannels(page int, perPage int, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, *model.AppError) { +func (a *OpenTracingAppLayer) GetAllChannels(c request.CTX, page int, perPage int, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllChannels") @@ -4423,7 +4423,7 @@ func (a *OpenTracingAppLayer) GetAllChannels(page int, perPage int, opts model.C }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetAllChannels(page, perPage, opts) + resultVar0, resultVar1 := a.app.GetAllChannels(c, page, perPage, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -4433,7 +4433,7 @@ func (a *OpenTracingAppLayer) GetAllChannels(page int, perPage int, opts model.C return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetAllChannelsCount(opts model.ChannelSearchOpts) (int64, *model.AppError) { +func (a *OpenTracingAppLayer) GetAllChannelsCount(c request.CTX, opts model.ChannelSearchOpts) (int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllChannelsCount") @@ -4445,7 +4445,7 @@ func (a *OpenTracingAppLayer) GetAllChannelsCount(opts model.ChannelSearchOpts) }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetAllChannelsCount(opts) + resultVar0, resultVar1 := a.app.GetAllChannelsCount(c, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -4868,7 +4868,7 @@ func (a *OpenTracingAppLayer) GetBulkReactionsForPosts(postIDs []string) (map[st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannel(channelID string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannel(c request.CTX, channelID string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannel") @@ -4880,7 +4880,7 @@ func (a *OpenTracingAppLayer) GetChannel(channelID string) (*model.Channel, *mod }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannel(channelID) + resultVar0, resultVar1 := a.app.GetChannel(c, channelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -4890,7 +4890,7 @@ func (a *OpenTracingAppLayer) GetChannel(channelID string) (*model.Channel, *mod return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelByName(channelName string, teamID string, includeDeleted bool) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelByName(c request.CTX, channelName string, teamID string, includeDeleted bool) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelByName") @@ -4902,7 +4902,7 @@ func (a *OpenTracingAppLayer) GetChannelByName(channelName string, teamID string }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelByName(channelName, teamID, includeDeleted) + resultVar0, resultVar1 := a.app.GetChannelByName(c, channelName, teamID, includeDeleted) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -4912,7 +4912,7 @@ func (a *OpenTracingAppLayer) GetChannelByName(channelName string, teamID string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelByNameForTeamName(channelName string, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelByNameForTeamName(c request.CTX, channelName string, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelByNameForTeamName") @@ -4924,7 +4924,7 @@ func (a *OpenTracingAppLayer) GetChannelByNameForTeamName(channelName string, te }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelByNameForTeamName(channelName, teamName, includeDeleted) + resultVar0, resultVar1 := a.app.GetChannelByNameForTeamName(c, channelName, teamName, includeDeleted) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -4934,7 +4934,7 @@ func (a *OpenTracingAppLayer) GetChannelByNameForTeamName(channelName string, te return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelCounts(teamID string, userID string) (*model.ChannelCounts, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelCounts(c request.CTX, teamID string, userID string) (*model.ChannelCounts, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelCounts") @@ -4946,7 +4946,7 @@ func (a *OpenTracingAppLayer) GetChannelCounts(teamID string, userID string) (*m }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelCounts(teamID, userID) + resultVar0, resultVar1 := a.app.GetChannelCounts(c, teamID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -4956,7 +4956,7 @@ func (a *OpenTracingAppLayer) GetChannelCounts(teamID string, userID string) (*m return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelFileCount(channelID string) (int64, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelFileCount(c request.CTX, channelID string) (int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelFileCount") @@ -4968,7 +4968,7 @@ func (a *OpenTracingAppLayer) GetChannelFileCount(channelID string) (int64, *mod }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelFileCount(channelID) + resultVar0, resultVar1 := a.app.GetChannelFileCount(c, channelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5000,7 +5000,7 @@ func (a *OpenTracingAppLayer) GetChannelGroupUsers(channelID string) ([]*model.U return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelGuestCount(channelID string) (int64, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelGuestCount(c request.CTX, channelID string) (int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelGuestCount") @@ -5012,7 +5012,7 @@ func (a *OpenTracingAppLayer) GetChannelGuestCount(channelID string) (int64, *mo }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelGuestCount(channelID) + resultVar0, resultVar1 := a.app.GetChannelGuestCount(c, channelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5022,7 +5022,7 @@ func (a *OpenTracingAppLayer) GetChannelGuestCount(channelID string) (int64, *mo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMember(ctx context.Context, channelID string, userID string) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMember(c request.CTX, channelID string, userID string) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMember") @@ -5034,7 +5034,7 @@ func (a *OpenTracingAppLayer) GetChannelMember(ctx context.Context, channelID st }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMember(ctx, channelID, userID) + resultVar0, resultVar1 := a.app.GetChannelMember(c, channelID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5044,7 +5044,7 @@ func (a *OpenTracingAppLayer) GetChannelMember(ctx context.Context, channelID st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMemberCount(channelID string) (int64, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMemberCount(c request.CTX, channelID string) (int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMemberCount") @@ -5056,7 +5056,7 @@ func (a *OpenTracingAppLayer) GetChannelMemberCount(channelID string) (int64, *m }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMemberCount(channelID) + resultVar0, resultVar1 := a.app.GetChannelMemberCount(c, channelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5066,7 +5066,7 @@ func (a *OpenTracingAppLayer) GetChannelMemberCount(channelID string) (int64, *m return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMembersByIds(channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMembersByIds(c request.CTX, channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersByIds") @@ -5078,7 +5078,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersByIds(channelID string, userIDs [ }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMembersByIds(channelID, userIDs) + resultVar0, resultVar1 := a.app.GetChannelMembersByIds(c, channelID, userIDs) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5088,7 +5088,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersByIds(channelID string, userIDs [ return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMembersForUser(teamID string, userID string) (model.ChannelMembers, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMembersForUser(c request.CTX, teamID string, userID string) (model.ChannelMembers, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersForUser") @@ -5100,7 +5100,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersForUser(teamID string, userID str }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMembersForUser(teamID, userID) + resultVar0, resultVar1 := a.app.GetChannelMembersForUser(c, teamID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5110,7 +5110,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersForUser(teamID string, userID str return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMembersForUserWithPagination(userID string, page int, perPage int) ([]*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMembersForUserWithPagination(c request.CTX, userID string, page int, perPage int) ([]*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersForUserWithPagination") @@ -5122,7 +5122,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersForUserWithPagination(userID stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMembersForUserWithPagination(userID, page, perPage) + resultVar0, resultVar1 := a.app.GetChannelMembersForUserWithPagination(c, userID, page, perPage) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5132,7 +5132,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersForUserWithPagination(userID stri return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMembersPage(channelID string, page int, perPage int) (model.ChannelMembers, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMembersPage(c request.CTX, channelID string, page int, perPage int) (model.ChannelMembers, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersPage") @@ -5144,7 +5144,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersPage(channelID string, page int, }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMembersPage(channelID, page, perPage) + resultVar0, resultVar1 := a.app.GetChannelMembersPage(c, channelID, page, perPage) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5154,7 +5154,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersPage(channelID string, page int, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMembersTimezones(channelID string) ([]string, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMembersTimezones(c request.CTX, channelID string) ([]string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersTimezones") @@ -5166,7 +5166,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersTimezones(channelID string) ([]st }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMembersTimezones(channelID) + resultVar0, resultVar1 := a.app.GetChannelMembersTimezones(c, channelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5176,7 +5176,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersTimezones(channelID string) ([]st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelMembersWithTeamDataForUserWithPagination(userID string, page int, perPage int) (model.ChannelMembersWithTeamData, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelMembersWithTeamDataForUserWithPagination(c request.CTX, userID string, page int, perPage int) (model.ChannelMembersWithTeamData, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersWithTeamDataForUserWithPagination") @@ -5188,7 +5188,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersWithTeamDataForUserWithPagination }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelMembersWithTeamDataForUserWithPagination(userID, page, perPage) + resultVar0, resultVar1 := a.app.GetChannelMembersWithTeamDataForUserWithPagination(c, userID, page, perPage) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5198,7 +5198,7 @@ func (a *OpenTracingAppLayer) GetChannelMembersWithTeamDataForUserWithPagination return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelModerationsForChannel(channel *model.Channel) ([]*model.ChannelModeration, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelModerationsForChannel(c request.CTX, channel *model.Channel) ([]*model.ChannelModeration, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelModerationsForChannel") @@ -5210,7 +5210,7 @@ func (a *OpenTracingAppLayer) GetChannelModerationsForChannel(channel *model.Cha }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelModerationsForChannel(channel) + resultVar0, resultVar1 := a.app.GetChannelModerationsForChannel(c, channel) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5220,7 +5220,7 @@ func (a *OpenTracingAppLayer) GetChannelModerationsForChannel(channel *model.Cha return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelPinnedPostCount(channelID string) (int64, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelPinnedPostCount(c request.CTX, channelID string) (int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelPinnedPostCount") @@ -5232,7 +5232,7 @@ func (a *OpenTracingAppLayer) GetChannelPinnedPostCount(channelID string) (int64 }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelPinnedPostCount(channelID) + resultVar0, resultVar1 := a.app.GetChannelPinnedPostCount(c, channelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5264,7 +5264,7 @@ func (a *OpenTracingAppLayer) GetChannelPoliciesForUser(userID string, offset in return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelUnread(channelID string, userID string) (*model.ChannelUnread, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelUnread(c request.CTX, channelID string, userID string) (*model.ChannelUnread, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelUnread") @@ -5276,7 +5276,7 @@ func (a *OpenTracingAppLayer) GetChannelUnread(channelID string, userID string) }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelUnread(channelID, userID) + resultVar0, resultVar1 := a.app.GetChannelUnread(c, channelID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5286,7 +5286,7 @@ func (a *OpenTracingAppLayer) GetChannelUnread(channelID string, userID string) return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannels(channelIDs []string) ([]*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannels(c request.CTX, channelIDs []string) ([]*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannels") @@ -5298,7 +5298,7 @@ func (a *OpenTracingAppLayer) GetChannels(channelIDs []string) ([]*model.Channel }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannels(channelIDs) + resultVar0, resultVar1 := a.app.GetChannels(c, channelIDs) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5308,7 +5308,7 @@ func (a *OpenTracingAppLayer) GetChannels(channelIDs []string) ([]*model.Channel return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelsByNames(channelNames []string, teamID string) ([]*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelsByNames(c request.CTX, channelNames []string, teamID string) ([]*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsByNames") @@ -5320,7 +5320,7 @@ func (a *OpenTracingAppLayer) GetChannelsByNames(channelNames []string, teamID s }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelsByNames(channelNames, teamID) + resultVar0, resultVar1 := a.app.GetChannelsByNames(c, channelNames, teamID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5396,7 +5396,7 @@ func (a *OpenTracingAppLayer) GetChannelsForSchemePage(scheme *model.Scheme, pag return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelsForTeamForUser(teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelsForTeamForUser(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForTeamForUser") @@ -5408,7 +5408,7 @@ func (a *OpenTracingAppLayer) GetChannelsForTeamForUser(teamID string, userID st }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelsForTeamForUser(teamID, userID, opts) + resultVar0, resultVar1 := a.app.GetChannelsForTeamForUser(c, teamID, userID, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5418,7 +5418,7 @@ func (a *OpenTracingAppLayer) GetChannelsForTeamForUser(teamID string, userID st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelsForTeamForUserWithCursor(teamID string, userID string, opts *model.ChannelSearchOpts, afterChannelID string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelsForTeamForUserWithCursor(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts, afterChannelID string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForTeamForUserWithCursor") @@ -5430,7 +5430,7 @@ func (a *OpenTracingAppLayer) GetChannelsForTeamForUserWithCursor(teamID string, }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelsForTeamForUserWithCursor(teamID, userID, opts, afterChannelID) + resultVar0, resultVar1 := a.app.GetChannelsForTeamForUserWithCursor(c, teamID, userID, opts, afterChannelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5440,7 +5440,7 @@ func (a *OpenTracingAppLayer) GetChannelsForTeamForUserWithCursor(teamID string, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelsForUser(userID string, includeDeleted bool, lastDeleteAt int, pageSize int, fromChannelID string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelsForUser(c request.CTX, userID string, includeDeleted bool, lastDeleteAt int, pageSize int, fromChannelID string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForUser") @@ -5452,7 +5452,7 @@ func (a *OpenTracingAppLayer) GetChannelsForUser(userID string, includeDeleted b }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelsForUser(userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID) + resultVar0, resultVar1 := a.app.GetChannelsForUser(c, userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5462,7 +5462,7 @@ func (a *OpenTracingAppLayer) GetChannelsForUser(userID string, includeDeleted b return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetChannelsUserNotIn(teamID string, userID string, offset int, limit int) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetChannelsUserNotIn(c request.CTX, teamID string, userID string, offset int, limit int) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsUserNotIn") @@ -5474,7 +5474,7 @@ func (a *OpenTracingAppLayer) GetChannelsUserNotIn(teamID string, userID string, }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetChannelsUserNotIn(teamID, userID, offset, limit) + resultVar0, resultVar1 := a.app.GetChannelsUserNotIn(c, teamID, userID, offset, limit) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -5755,7 +5755,7 @@ func (a *OpenTracingAppLayer) GetDefaultProfileImage(user *model.User) ([]byte, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetDeletedChannels(teamID string, offset int, limit int, userID string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetDeletedChannels(c request.CTX, teamID string, offset int, limit int, userID string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetDeletedChannels") @@ -5767,7 +5767,7 @@ func (a *OpenTracingAppLayer) GetDeletedChannels(teamID string, offset int, limi }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetDeletedChannels(teamID, offset, limit, userID) + resultVar0, resultVar1 := a.app.GetDeletedChannels(c, teamID, offset, limit, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -6190,7 +6190,7 @@ func (a *OpenTracingAppLayer) GetGroupByRemoteID(remoteID string, groupSource mo return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetGroupChannel(c request.CTX, userIDs []string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupChannel") @@ -6202,7 +6202,7 @@ func (a *OpenTracingAppLayer) GetGroupChannel(userIDs []string) (*model.Channel, }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetGroupChannel(userIDs) + resultVar0, resultVar1 := a.app.GetGroupChannel(c, userIDs) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7072,7 +7072,7 @@ func (a *OpenTracingAppLayer) GetNotificationNameFormat(user *model.User) string return resultVar0 } -func (a *OpenTracingAppLayer) GetNumberOfChannelsOnTeam(teamID string) (int, *model.AppError) { +func (a *OpenTracingAppLayer) GetNumberOfChannelsOnTeam(c request.CTX, teamID string) (int, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetNumberOfChannelsOnTeam") @@ -7084,7 +7084,7 @@ func (a *OpenTracingAppLayer) GetNumberOfChannelsOnTeam(teamID string) (int, *mo }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetNumberOfChannelsOnTeam(teamID) + resultVar0, resultVar1 := a.app.GetNumberOfChannelsOnTeam(c, teamID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7358,7 +7358,7 @@ func (a *OpenTracingAppLayer) GetOpenGraphMetadata(requestURL string) ([]byte, e return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetOrCreateDirectChannel(c *request.Context, userID string, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) GetOrCreateDirectChannel(c request.CTX, userID string, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOrCreateDirectChannel") @@ -7534,7 +7534,7 @@ func (a *OpenTracingAppLayer) GetPasswordRecoveryToken(token string) (*model.Tok return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError) { +func (a *OpenTracingAppLayer) GetPermalinkPost(c request.CTX, postID string, userID string) (*model.PostList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPermalinkPost") @@ -7556,7 +7556,7 @@ func (a *OpenTracingAppLayer) GetPermalinkPost(c *request.Context, postID string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetPinnedPosts(channelID string) (*model.PostList, *model.AppError) { +func (a *OpenTracingAppLayer) GetPinnedPosts(c request.CTX, channelID string) (*model.PostList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPinnedPosts") @@ -7568,7 +7568,7 @@ func (a *OpenTracingAppLayer) GetPinnedPosts(channelID string) (*model.PostList, }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetPinnedPosts(channelID) + resultVar0, resultVar1 := a.app.GetPinnedPosts(c, channelID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7749,7 +7749,7 @@ func (a *OpenTracingAppLayer) GetPostIdBeforeTime(channelID string, time int64, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetPostIfAuthorized(postID string, session *model.Session, includeDeleted bool) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) GetPostIfAuthorized(c request.CTX, postID string, session *model.Session, includeDeleted bool) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostIfAuthorized") @@ -7761,7 +7761,7 @@ func (a *OpenTracingAppLayer) GetPostIfAuthorized(postID string, session *model. }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetPostIfAuthorized(postID, session, includeDeleted) + resultVar0, resultVar1 := a.app.GetPostIfAuthorized(c, postID, session, includeDeleted) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -7920,7 +7920,7 @@ func (a *OpenTracingAppLayer) GetPostsEtag(channelID string, collapsedThreads bo return resultVar0 } -func (a *OpenTracingAppLayer) GetPostsForChannelAroundLastUnread(channelID string, userID string, limitBefore int, limitAfter int, skipFetchThreads bool, collapsedThreads bool, collapsedThreadsExtended bool) (*model.PostList, *model.AppError) { +func (a *OpenTracingAppLayer) GetPostsForChannelAroundLastUnread(c request.CTX, channelID string, userID string, limitBefore int, limitAfter int, skipFetchThreads bool, collapsedThreads bool, collapsedThreadsExtended bool) (*model.PostList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsForChannelAroundLastUnread") @@ -7932,7 +7932,7 @@ func (a *OpenTracingAppLayer) GetPostsForChannelAroundLastUnread(channelID strin }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetPostsForChannelAroundLastUnread(channelID, userID, limitBefore, limitAfter, skipFetchThreads, collapsedThreads, collapsedThreadsExtended) + resultVar0, resultVar1 := a.app.GetPostsForChannelAroundLastUnread(c, channelID, userID, limitBefore, limitAfter, skipFetchThreads, collapsedThreads, collapsedThreadsExtended) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -8091,7 +8091,7 @@ func (a *OpenTracingAppLayer) GetPrevPostIdFromPostList(postList *model.PostList return resultVar0 } -func (a *OpenTracingAppLayer) GetPrivateChannelsForTeam(teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetPrivateChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPrivateChannelsForTeam") @@ -8103,7 +8103,7 @@ func (a *OpenTracingAppLayer) GetPrivateChannelsForTeam(teamID string, offset in }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetPrivateChannelsForTeam(teamID, offset, limit) + resultVar0, resultVar1 := a.app.GetPrivateChannelsForTeam(c, teamID, offset, limit) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -8157,7 +8157,7 @@ func (a *OpenTracingAppLayer) GetProfileImage(user *model.User) ([]byte, bool, * return resultVar0, resultVar1, resultVar2 } -func (a *OpenTracingAppLayer) GetPublicChannelsByIdsForTeam(teamID string, channelIDs []string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetPublicChannelsByIdsForTeam(c request.CTX, teamID string, channelIDs []string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPublicChannelsByIdsForTeam") @@ -8169,7 +8169,7 @@ func (a *OpenTracingAppLayer) GetPublicChannelsByIdsForTeam(teamID string, chann }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetPublicChannelsByIdsForTeam(teamID, channelIDs) + resultVar0, resultVar1 := a.app.GetPublicChannelsByIdsForTeam(c, teamID, channelIDs) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -8179,7 +8179,7 @@ func (a *OpenTracingAppLayer) GetPublicChannelsByIdsForTeam(teamID string, chann return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetPublicChannelsForTeam(teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetPublicChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPublicChannelsForTeam") @@ -8191,7 +8191,7 @@ func (a *OpenTracingAppLayer) GetPublicChannelsForTeam(teamID string, offset int }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetPublicChannelsForTeam(teamID, offset, limit) + resultVar0, resultVar1 := a.app.GetPublicChannelsForTeam(c, teamID, offset, limit) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -8670,7 +8670,7 @@ func (a *OpenTracingAppLayer) GetSchemeByName(name string) (*model.Scheme, *mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetSchemeRolesForChannel(channelID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) { +func (a *OpenTracingAppLayer) GetSchemeRolesForChannel(c request.CTX, channelID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSchemeRolesForChannel") @@ -8682,7 +8682,7 @@ func (a *OpenTracingAppLayer) GetSchemeRolesForChannel(channelID string) (guestR }() defer span.Finish() - resultVar0, resultVar1, resultVar2, resultVar3 := a.app.GetSchemeRolesForChannel(channelID) + resultVar0, resultVar1, resultVar2, resultVar3 := a.app.GetSchemeRolesForChannel(c, channelID) if resultVar3 != nil { span.LogFields(spanlog.Error(resultVar3)) @@ -8995,7 +8995,7 @@ func (a *OpenTracingAppLayer) GetSharedChannelsCount(opts model.SharedChannelFil return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetSidebarCategories(userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) { +func (a *OpenTracingAppLayer) GetSidebarCategories(c request.CTX, userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategories") @@ -9007,7 +9007,7 @@ func (a *OpenTracingAppLayer) GetSidebarCategories(userID string, opts *store.Si }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetSidebarCategories(userID, opts) + resultVar0, resultVar1 := a.app.GetSidebarCategories(c, userID, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9017,7 +9017,7 @@ func (a *OpenTracingAppLayer) GetSidebarCategories(userID string, opts *store.Si return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetSidebarCategoriesForTeamForUser(userID string, teamID string) (*model.OrderedSidebarCategories, *model.AppError) { +func (a *OpenTracingAppLayer) GetSidebarCategoriesForTeamForUser(c request.CTX, userID string, teamID string) (*model.OrderedSidebarCategories, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategoriesForTeamForUser") @@ -9029,7 +9029,7 @@ func (a *OpenTracingAppLayer) GetSidebarCategoriesForTeamForUser(userID string, }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetSidebarCategoriesForTeamForUser(userID, teamID) + resultVar0, resultVar1 := a.app.GetSidebarCategoriesForTeamForUser(c, userID, teamID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9039,7 +9039,7 @@ func (a *OpenTracingAppLayer) GetSidebarCategoriesForTeamForUser(userID string, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetSidebarCategory(categoryId string) (*model.SidebarCategoryWithChannels, *model.AppError) { +func (a *OpenTracingAppLayer) GetSidebarCategory(c request.CTX, categoryId string) (*model.SidebarCategoryWithChannels, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategory") @@ -9051,7 +9051,7 @@ func (a *OpenTracingAppLayer) GetSidebarCategory(categoryId string) (*model.Side }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetSidebarCategory(categoryId) + resultVar0, resultVar1 := a.app.GetSidebarCategory(c, categoryId) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9061,7 +9061,7 @@ func (a *OpenTracingAppLayer) GetSidebarCategory(categoryId string) (*model.Side return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetSidebarCategoryOrder(userID string, teamID string) ([]string, *model.AppError) { +func (a *OpenTracingAppLayer) GetSidebarCategoryOrder(c request.CTX, userID string, teamID string) ([]string, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategoryOrder") @@ -9073,7 +9073,7 @@ func (a *OpenTracingAppLayer) GetSidebarCategoryOrder(userID string, teamID stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetSidebarCategoryOrder(userID, teamID) + resultVar0, resultVar1 := a.app.GetSidebarCategoryOrder(c, userID, teamID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9508,7 +9508,7 @@ func (a *OpenTracingAppLayer) GetTeamPoliciesForUser(userID string, offset int, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetTeamSchemeChannelRoles(teamID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) { +func (a *OpenTracingAppLayer) GetTeamSchemeChannelRoles(c request.CTX, teamID string) (guestRoleName string, userRoleName string, adminRoleName string, err *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamSchemeChannelRoles") @@ -9520,7 +9520,7 @@ func (a *OpenTracingAppLayer) GetTeamSchemeChannelRoles(teamID string) (guestRol }() defer span.Finish() - resultVar0, resultVar1, resultVar2, resultVar3 := a.app.GetTeamSchemeChannelRoles(teamID) + resultVar0, resultVar1, resultVar2, resultVar3 := a.app.GetTeamSchemeChannelRoles(c, teamID) if resultVar3 != nil { span.LogFields(spanlog.Error(resultVar3)) @@ -9860,7 +9860,7 @@ func (a *OpenTracingAppLayer) GetTokenById(token string) (*model.Token, *model.A return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetTopChannelsForTeamSince(teamID string, userID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetTopChannelsForTeamSince(c request.CTX, teamID string, userID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopChannelsForTeamSince") @@ -9872,7 +9872,7 @@ func (a *OpenTracingAppLayer) GetTopChannelsForTeamSince(teamID string, userID s }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetTopChannelsForTeamSince(teamID, userID, opts) + resultVar0, resultVar1 := a.app.GetTopChannelsForTeamSince(c, teamID, userID, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9882,7 +9882,7 @@ func (a *OpenTracingAppLayer) GetTopChannelsForTeamSince(teamID string, userID s return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetTopChannelsForUserSince(userID string, teamID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) GetTopChannelsForUserSince(c request.CTX, userID string, teamID string, opts *model.InsightsOpts) (*model.TopChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopChannelsForUserSince") @@ -9894,7 +9894,7 @@ func (a *OpenTracingAppLayer) GetTopChannelsForUserSince(userID string, teamID s }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetTopChannelsForUserSince(userID, teamID, opts) + resultVar0, resultVar1 := a.app.GetTopChannelsForUserSince(c, userID, teamID, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9948,7 +9948,7 @@ func (a *OpenTracingAppLayer) GetTopReactionsForUserSince(userID string, teamID return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetTopThreadsForTeamSince(teamID string, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { +func (a *OpenTracingAppLayer) GetTopThreadsForTeamSince(c request.CTX, teamID string, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopThreadsForTeamSince") @@ -9960,7 +9960,7 @@ func (a *OpenTracingAppLayer) GetTopThreadsForTeamSince(teamID string, userID st }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetTopThreadsForTeamSince(teamID, userID, opts) + resultVar0, resultVar1 := a.app.GetTopThreadsForTeamSince(c, teamID, userID, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -9970,7 +9970,7 @@ func (a *OpenTracingAppLayer) GetTopThreadsForTeamSince(teamID string, userID st return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetTopThreadsForUserSince(teamID string, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { +func (a *OpenTracingAppLayer) GetTopThreadsForUserSince(c request.CTX, teamID string, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopThreadsForUserSince") @@ -9982,7 +9982,7 @@ func (a *OpenTracingAppLayer) GetTopThreadsForUserSince(teamID string, userID st }() defer span.Finish() - resultVar0, resultVar1 := a.app.GetTopThreadsForUserSince(teamID, userID, opts) + resultVar0, resultVar1 := a.app.GetTopThreadsForUserSince(c, teamID, userID, opts) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -11095,7 +11095,7 @@ func (a *OpenTracingAppLayer) HasPermissionTo(askingUserId string, permission *m return resultVar0 } -func (a *OpenTracingAppLayer) HasPermissionToChannel(askingUserId string, channelID string, permission *model.Permission) bool { +func (a *OpenTracingAppLayer) HasPermissionToChannel(c request.CTX, askingUserId string, channelID string, permission *model.Permission) bool { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionToChannel") @@ -11107,7 +11107,7 @@ func (a *OpenTracingAppLayer) HasPermissionToChannel(askingUserId string, channe }() defer span.Finish() - resultVar0 := a.app.HasPermissionToChannel(askingUserId, channelID, permission) + resultVar0 := a.app.HasPermissionToChannel(c, askingUserId, channelID, permission) return resultVar0 } @@ -11129,7 +11129,7 @@ func (a *OpenTracingAppLayer) HasPermissionToChannelByPost(askingUserId string, return resultVar0 } -func (a *OpenTracingAppLayer) HasPermissionToReadChannel(userID string, channel *model.Channel) bool { +func (a *OpenTracingAppLayer) HasPermissionToReadChannel(c request.CTX, userID string, channel *model.Channel) bool { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionToReadChannel") @@ -11141,7 +11141,7 @@ func (a *OpenTracingAppLayer) HasPermissionToReadChannel(userID string, channel }() defer span.Finish() - resultVar0 := a.app.HasPermissionToReadChannel(userID, channel) + resultVar0 := a.app.HasPermissionToReadChannel(c, userID, channel) return resultVar0 } @@ -11494,7 +11494,7 @@ func (a *OpenTracingAppLayer) InviteNewUsersToTeamGracefully(memberInvite *model return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) IsCRTEnabledForUser(userID string) bool { +func (a *OpenTracingAppLayer) IsCRTEnabledForUser(c request.CTX, userID string) bool { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsCRTEnabledForUser") @@ -11506,7 +11506,7 @@ func (a *OpenTracingAppLayer) IsCRTEnabledForUser(userID string) bool { }() defer span.Finish() - resultVar0 := a.app.IsCRTEnabledForUser(userID) + resultVar0 := a.app.IsCRTEnabledForUser(c, userID) return resultVar0 } @@ -11628,7 +11628,7 @@ func (a *OpenTracingAppLayer) IsUserSignUpAllowed() *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError { +func (a *OpenTracingAppLayer) JoinChannel(c request.CTX, channel *model.Channel, userID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinChannel") @@ -11650,7 +11650,7 @@ func (a *OpenTracingAppLayer) JoinChannel(c *request.Context, channel *model.Cha return resultVar0 } -func (a *OpenTracingAppLayer) JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { +func (a *OpenTracingAppLayer) JoinDefaultChannels(c request.CTX, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinDefaultChannels") @@ -11694,7 +11694,7 @@ func (a *OpenTracingAppLayer) JoinUserToTeam(c *request.Context, team *model.Tea return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError { +func (a *OpenTracingAppLayer) LeaveChannel(c request.CTX, channelID string, userID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LeaveChannel") @@ -12058,7 +12058,7 @@ func (a *OpenTracingAppLayer) MakePermissionError(s *model.Session, permissions return resultVar0 } -func (a *OpenTracingAppLayer) MarkChannelAsUnreadFromPost(postID string, userID string, collapsedThreadsSupported bool) (*model.ChannelUnreadAt, *model.AppError) { +func (a *OpenTracingAppLayer) MarkChannelAsUnreadFromPost(c request.CTX, postID string, userID string, collapsedThreadsSupported bool) (*model.ChannelUnreadAt, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MarkChannelAsUnreadFromPost") @@ -12070,7 +12070,7 @@ func (a *OpenTracingAppLayer) MarkChannelAsUnreadFromPost(postID string, userID }() defer span.Finish() - resultVar0, resultVar1 := a.app.MarkChannelAsUnreadFromPost(postID, userID, collapsedThreadsSupported) + resultVar0, resultVar1 := a.app.MarkChannelAsUnreadFromPost(c, postID, userID, collapsedThreadsSupported) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -12080,7 +12080,7 @@ func (a *OpenTracingAppLayer) MarkChannelAsUnreadFromPost(postID string, userID return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) MarkChannelsAsViewed(channelIDs []string, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { +func (a *OpenTracingAppLayer) MarkChannelsAsViewed(c request.CTX, channelIDs []string, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MarkChannelsAsViewed") @@ -12092,7 +12092,7 @@ func (a *OpenTracingAppLayer) MarkChannelsAsViewed(channelIDs []string, userID s }() defer span.Finish() - resultVar0, resultVar1 := a.app.MarkChannelsAsViewed(channelIDs, userID, currentSessionId, collapsedThreadsSupported) + resultVar0, resultVar1 := a.app.MarkChannelsAsViewed(c, channelIDs, userID, currentSessionId, collapsedThreadsSupported) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -12119,7 +12119,7 @@ func (a *OpenTracingAppLayer) MaxPostSize() int { return resultVar0 } -func (a *OpenTracingAppLayer) MentionsToPublicChannels(message string, teamID string) model.ChannelMentionMap { +func (a *OpenTracingAppLayer) MentionsToPublicChannels(c request.CTX, message string, teamID string) model.ChannelMentionMap { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MentionsToPublicChannels") @@ -12131,7 +12131,7 @@ func (a *OpenTracingAppLayer) MentionsToPublicChannels(message string, teamID st }() defer span.Finish() - resultVar0 := a.app.MentionsToPublicChannels(message, teamID) + resultVar0 := a.app.MentionsToPublicChannels(c, message, teamID) return resultVar0 } @@ -12192,7 +12192,7 @@ func (a *OpenTracingAppLayer) MigrateIdLDAP(toAttribute string) *model.AppError return resultVar0 } -func (a *OpenTracingAppLayer) MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { +func (a *OpenTracingAppLayer) MoveChannel(c request.CTX, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MoveChannel") @@ -12466,7 +12466,7 @@ func (a *OpenTracingAppLayer) PatchBot(botUserId string, botPatch *model.BotPatc return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) PatchChannel(c request.CTX, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchChannel") @@ -12488,7 +12488,7 @@ func (a *OpenTracingAppLayer) PatchChannel(c *request.Context, channel *model.Ch return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) PatchChannelModerationsForChannel(channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) { +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") @@ -12500,7 +12500,7 @@ func (a *OpenTracingAppLayer) PatchChannelModerationsForChannel(channel *model.C }() defer span.Finish() - resultVar0, resultVar1 := a.app.PatchChannelModerationsForChannel(channel, channelModerationsPatch) + resultVar0, resultVar1 := a.app.PatchChannelModerationsForChannel(c, channel, channelModerationsPatch) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -12686,7 +12686,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteBot(botUserId string) *model.AppErr return resultVar0 } -func (a *OpenTracingAppLayer) PermanentDeleteChannel(channel *model.Channel) *model.AppError { +func (a *OpenTracingAppLayer) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteChannel") @@ -12698,7 +12698,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteChannel(channel *model.Channel) *mo }() defer span.Finish() - resultVar0 := a.app.PermanentDeleteChannel(channel) + resultVar0 := a.app.PermanentDeleteChannel(c, channel) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12708,7 +12708,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteChannel(channel *model.Channel) *mo return resultVar0 } -func (a *OpenTracingAppLayer) PermanentDeleteTeam(team *model.Team) *model.AppError { +func (a *OpenTracingAppLayer) PermanentDeleteTeam(c request.CTX, team *model.Team) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteTeam") @@ -12720,7 +12720,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteTeam(team *model.Team) *model.AppEr }() defer span.Finish() - resultVar0 := a.app.PermanentDeleteTeam(team) + resultVar0 := a.app.PermanentDeleteTeam(c, team) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12730,7 +12730,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteTeam(team *model.Team) *model.AppEr return resultVar0 } -func (a *OpenTracingAppLayer) PermanentDeleteTeamId(teamID string) *model.AppError { +func (a *OpenTracingAppLayer) PermanentDeleteTeamId(c request.CTX, teamID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteTeamId") @@ -12742,7 +12742,7 @@ func (a *OpenTracingAppLayer) PermanentDeleteTeamId(teamID string) *model.AppErr }() defer span.Finish() - resultVar0 := a.app.PermanentDeleteTeamId(teamID) + resultVar0 := a.app.PermanentDeleteTeamId(c, teamID) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -12830,7 +12830,7 @@ func (a *OpenTracingAppLayer) PostActionCookieSecret() []byte { return resultVar0 } -func (a *OpenTracingAppLayer) PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { +func (a *OpenTracingAppLayer) PostAddToChannelMessage(c request.CTX, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostAddToChannelMessage") @@ -12852,7 +12852,7 @@ func (a *OpenTracingAppLayer) PostAddToChannelMessage(c *request.Context, user * return resultVar0 } -func (a *OpenTracingAppLayer) PostCountsByDuration(channelIDs []string, sinceUnixMillis int64, userID *string, grouping model.PostCountGrouping, groupingLocation *time.Location) ([]*model.DurationPostCount, *model.AppError) { +func (a *OpenTracingAppLayer) PostCountsByDuration(c request.CTX, channelIDs []string, sinceUnixMillis int64, userID *string, grouping model.PostCountGrouping, groupingLocation *time.Location) ([]*model.DurationPostCount, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostCountsByDuration") @@ -12864,7 +12864,7 @@ func (a *OpenTracingAppLayer) PostCountsByDuration(channelIDs []string, sinceUni }() defer span.Finish() - resultVar0, resultVar1 := a.app.PostCountsByDuration(channelIDs, sinceUnixMillis, userID, grouping, groupingLocation) + resultVar0, resultVar1 := a.app.PostCountsByDuration(c, channelIDs, sinceUnixMillis, userID, grouping, groupingLocation) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -12891,7 +12891,7 @@ func (a *OpenTracingAppLayer) PostPatchWithProxyRemovedFromImageURLs(patch *mode return resultVar0 } -func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName string, newChannelDisplayName string) *model.AppError { +func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(c request.CTX, userID string, channel *model.Channel, oldChannelDisplayName string, newChannelDisplayName string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelDisplayNameMessage") @@ -12913,7 +12913,7 @@ func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(c *request.Con return resultVar0 } -func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader string, newChannelHeader string) *model.AppError { +func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(c request.CTX, userID string, channel *model.Channel, oldChannelHeader string, newChannelHeader string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelHeaderMessage") @@ -12935,7 +12935,7 @@ func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(c *request.Context, return resultVar0 } -func (a *OpenTracingAppLayer) PostUpdateChannelPurposeMessage(c *request.Context, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { +func (a *OpenTracingAppLayer) PostUpdateChannelPurposeMessage(c request.CTX, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelPurposeMessage") @@ -13008,7 +13008,7 @@ func (a *OpenTracingAppLayer) PreparePostForClient(originalPost *model.Post, isN return resultVar0 } -func (a *OpenTracingAppLayer) PreparePostForClientWithEmbedsAndImages(originalPost *model.Post, isNewPost bool, isEditPost bool) *model.Post { +func (a *OpenTracingAppLayer) PreparePostForClientWithEmbedsAndImages(c request.CTX, originalPost *model.Post, isNewPost bool, isEditPost bool) *model.Post { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PreparePostForClientWithEmbedsAndImages") @@ -13020,12 +13020,12 @@ func (a *OpenTracingAppLayer) PreparePostForClientWithEmbedsAndImages(originalPo }() defer span.Finish() - resultVar0 := a.app.PreparePostForClientWithEmbedsAndImages(originalPost, isNewPost, isEditPost) + resultVar0 := a.app.PreparePostForClientWithEmbedsAndImages(c, originalPost, isNewPost, isEditPost) return resultVar0 } -func (a *OpenTracingAppLayer) PreparePostListForClient(originalList *model.PostList) *model.PostList { +func (a *OpenTracingAppLayer) PreparePostListForClient(c request.CTX, originalList *model.PostList) *model.PostList { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PreparePostListForClient") @@ -13037,7 +13037,7 @@ func (a *OpenTracingAppLayer) PreparePostListForClient(originalList *model.PostL }() defer span.Finish() - resultVar0 := a.app.PreparePostListForClient(originalList) + resultVar0 := a.app.PreparePostListForClient(c, originalList) return resultVar0 } @@ -13348,7 +13348,7 @@ func (a *OpenTracingAppLayer) ReloadConfig() error { return resultVar0 } -func (a *OpenTracingAppLayer) RemoveAllDeactivatedMembersFromChannel(channel *model.Channel) *model.AppError { +func (a *OpenTracingAppLayer) RemoveAllDeactivatedMembersFromChannel(c request.CTX, channel *model.Channel) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveAllDeactivatedMembersFromChannel") @@ -13360,7 +13360,7 @@ func (a *OpenTracingAppLayer) RemoveAllDeactivatedMembersFromChannel(channel *mo }() defer span.Finish() - resultVar0 := a.app.RemoveAllDeactivatedMembersFromChannel(channel) + resultVar0 := a.app.RemoveAllDeactivatedMembersFromChannel(c, channel) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -13649,7 +13649,7 @@ func (a *OpenTracingAppLayer) RemoveTeamsFromRetentionPolicy(policyID string, te return resultVar0 } -func (a *OpenTracingAppLayer) RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *OpenTracingAppLayer) RemoveUserFromChannel(c request.CTX, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUserFromChannel") @@ -13693,7 +13693,7 @@ func (a *OpenTracingAppLayer) RemoveUserFromTeam(c *request.Context, teamID stri return resultVar0 } -func (a *OpenTracingAppLayer) RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { +func (a *OpenTracingAppLayer) RemoveUsersFromChannelNotMemberOfTeam(c request.CTX, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUsersFromChannelNotMemberOfTeam") @@ -13715,7 +13715,7 @@ func (a *OpenTracingAppLayer) RemoveUsersFromChannelNotMemberOfTeam(c *request.C return resultVar0 } -func (a *OpenTracingAppLayer) RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) RenameChannel(c request.CTX, channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RenameChannel") @@ -13727,7 +13727,7 @@ func (a *OpenTracingAppLayer) RenameChannel(channel *model.Channel, newChannelNa }() defer span.Finish() - resultVar0, resultVar1 := a.app.RenameChannel(channel, newChannelName, newDisplayName) + resultVar0, resultVar1 := a.app.RenameChannel(c, channel, newChannelName, newDisplayName) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -13847,7 +13847,7 @@ func (a *OpenTracingAppLayer) ResetSamlAuthDataToEmail(includeDeleted bool, dryR return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) RestoreChannel(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) RestoreChannel(c request.CTX, channel *model.Channel, userID string) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestoreChannel") @@ -14121,7 +14121,7 @@ func (a *OpenTracingAppLayer) RolesGrantPermission(roleNames []string, permissio return resultVar0 } -func (a *OpenTracingAppLayer) SanitizePostListMetadataForUser(postList *model.PostList, userID string) (*model.PostList, *model.AppError) { +func (a *OpenTracingAppLayer) SanitizePostListMetadataForUser(c request.CTX, postList *model.PostList, userID string) (*model.PostList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SanitizePostListMetadataForUser") @@ -14133,7 +14133,7 @@ func (a *OpenTracingAppLayer) SanitizePostListMetadataForUser(postList *model.Po }() defer span.Finish() - resultVar0, resultVar1 := a.app.SanitizePostListMetadataForUser(postList, userID) + resultVar0, resultVar1 := a.app.SanitizePostListMetadataForUser(c, postList, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14143,7 +14143,7 @@ func (a *OpenTracingAppLayer) SanitizePostListMetadataForUser(postList *model.Po return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SanitizePostMetadataForUser(post *model.Post, userID string) (*model.Post, *model.AppError) { +func (a *OpenTracingAppLayer) SanitizePostMetadataForUser(c request.CTX, post *model.Post, userID string) (*model.Post, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SanitizePostMetadataForUser") @@ -14155,7 +14155,7 @@ func (a *OpenTracingAppLayer) SanitizePostMetadataForUser(post *model.Post, user }() defer span.Finish() - resultVar0, resultVar1 := a.app.SanitizePostMetadataForUser(post, userID) + resultVar0, resultVar1 := a.app.SanitizePostMetadataForUser(c, post, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14317,7 +14317,7 @@ func (a *OpenTracingAppLayer) SaveReactionForPost(c *request.Context, reaction * return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SaveSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error) { +func (a *OpenTracingAppLayer) SaveSharedChannel(c request.CTX, sc *model.SharedChannel) (*model.SharedChannel, error) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveSharedChannel") @@ -14329,7 +14329,7 @@ func (a *OpenTracingAppLayer) SaveSharedChannel(sc *model.SharedChannel) (*model }() defer span.Finish() - resultVar0, resultVar1 := a.app.SaveSharedChannel(sc) + resultVar0, resultVar1 := a.app.SaveSharedChannel(c, sc) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14400,7 +14400,7 @@ func (a *OpenTracingAppLayer) SchemesIterator(scope string, batchSize int) func( return resultVar0 } -func (a *OpenTracingAppLayer) SearchAllChannels(term string, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, int64, *model.AppError) { +func (a *OpenTracingAppLayer) SearchAllChannels(c request.CTX, term string, opts model.ChannelSearchOpts) (model.ChannelListWithTeamData, int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchAllChannels") @@ -14412,7 +14412,7 @@ func (a *OpenTracingAppLayer) SearchAllChannels(term string, opts model.ChannelS }() defer span.Finish() - resultVar0, resultVar1, resultVar2 := a.app.SearchAllChannels(term, opts) + resultVar0, resultVar1, resultVar2 := a.app.SearchAllChannels(c, term, opts) if resultVar2 != nil { span.LogFields(spanlog.Error(resultVar2)) @@ -14444,7 +14444,7 @@ func (a *OpenTracingAppLayer) SearchAllTeams(searchOpts *model.TeamSearch) ([]*m return resultVar0, resultVar1, resultVar2 } -func (a *OpenTracingAppLayer) SearchArchivedChannels(teamID string, term string, userID string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) SearchArchivedChannels(c request.CTX, teamID string, term string, userID string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchArchivedChannels") @@ -14456,7 +14456,7 @@ func (a *OpenTracingAppLayer) SearchArchivedChannels(teamID string, term string, }() defer span.Finish() - resultVar0, resultVar1 := a.app.SearchArchivedChannels(teamID, term, userID) + resultVar0, resultVar1 := a.app.SearchArchivedChannels(c, teamID, term, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14466,7 +14466,7 @@ func (a *OpenTracingAppLayer) SearchArchivedChannels(teamID string, term string, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SearchChannels(teamID string, term string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) SearchChannels(c request.CTX, teamID string, term string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchChannels") @@ -14478,7 +14478,7 @@ func (a *OpenTracingAppLayer) SearchChannels(teamID string, term string) (model. }() defer span.Finish() - resultVar0, resultVar1 := a.app.SearchChannels(teamID, term) + resultVar0, resultVar1 := a.app.SearchChannels(c, teamID, term) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14488,7 +14488,7 @@ func (a *OpenTracingAppLayer) SearchChannels(teamID string, term string) (model. return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SearchChannelsForUser(userID string, teamID string, term string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) SearchChannelsForUser(c request.CTX, userID string, teamID string, term string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchChannelsForUser") @@ -14500,7 +14500,7 @@ func (a *OpenTracingAppLayer) SearchChannelsForUser(userID string, teamID string }() defer span.Finish() - resultVar0, resultVar1 := a.app.SearchChannelsForUser(userID, teamID, term) + resultVar0, resultVar1 := a.app.SearchChannelsForUser(c, userID, teamID, term) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14510,7 +14510,7 @@ func (a *OpenTracingAppLayer) SearchChannelsForUser(userID string, teamID string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SearchChannelsUserNotIn(teamID string, userID string, term string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) SearchChannelsUserNotIn(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchChannelsUserNotIn") @@ -14522,7 +14522,7 @@ func (a *OpenTracingAppLayer) SearchChannelsUserNotIn(teamID string, userID stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.SearchChannelsUserNotIn(teamID, userID, term) + resultVar0, resultVar1 := a.app.SearchChannelsUserNotIn(c, teamID, userID, term) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14593,7 +14593,7 @@ func (a *OpenTracingAppLayer) SearchFilesInTeamForUser(c *request.Context, terms return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SearchGroupChannels(userID string, term string) (model.ChannelList, *model.AppError) { +func (a *OpenTracingAppLayer) SearchGroupChannels(c request.CTX, userID string, term string) (model.ChannelList, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchGroupChannels") @@ -14605,7 +14605,7 @@ func (a *OpenTracingAppLayer) SearchGroupChannels(userID string, term string) (m }() defer span.Finish() - resultVar0, resultVar1 := a.app.SearchGroupChannels(userID, term) + resultVar0, resultVar1 := a.app.SearchGroupChannels(c, userID, term) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -14923,7 +14923,7 @@ func (a *OpenTracingAppLayer) SendAckToPushProxy(ack *model.PushNotificationAck) return resultVar0 } -func (a *OpenTracingAppLayer) SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { +func (a *OpenTracingAppLayer) SendAutoResponse(c request.CTX, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendAutoResponse") @@ -14945,7 +14945,7 @@ func (a *OpenTracingAppLayer) SendAutoResponse(c *request.Context, channel *mode return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { +func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(c request.CTX, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendAutoResponseIfNecessary") @@ -14989,7 +14989,7 @@ func (a *OpenTracingAppLayer) SendEmailVerification(user *model.User, newEmail s return resultVar0 } -func (a *OpenTracingAppLayer) SendEphemeralPost(userID string, post *model.Post) *model.Post { +func (a *OpenTracingAppLayer) SendEphemeralPost(c request.CTX, userID string, post *model.Post) *model.Post { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendEphemeralPost") @@ -15001,7 +15001,7 @@ func (a *OpenTracingAppLayer) SendEphemeralPost(userID string, post *model.Post) }() defer span.Finish() - resultVar0 := a.app.SendEphemeralPost(userID, post) + resultVar0 := a.app.SendEphemeralPost(c, userID, post) return resultVar0 } @@ -15028,7 +15028,7 @@ func (a *OpenTracingAppLayer) SendNoCardPaymentFailedEmail() *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList, setOnline bool) ([]string, error) { +func (a *OpenTracingAppLayer) SendNotifications(c request.CTX, post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList, setOnline bool) ([]string, error) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendNotifications") @@ -15040,7 +15040,7 @@ func (a *OpenTracingAppLayer) SendNotifications(post *model.Post, team *model.Te }() defer span.Finish() - resultVar0, resultVar1 := a.app.SendNotifications(post, team, channel, sender, parentPostList, setOnline) + resultVar0, resultVar1 := a.app.SendNotifications(c, post, team, channel, sender, parentPostList, setOnline) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -15182,7 +15182,7 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToAny(session model.Session, p return resultVar0 } -func (a *OpenTracingAppLayer) SessionHasPermissionToCategory(session model.Session, userID string, teamID string, categoryId string) bool { +func (a *OpenTracingAppLayer) SessionHasPermissionToCategory(c request.CTX, session model.Session, userID string, teamID string, categoryId string) bool { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToCategory") @@ -15194,12 +15194,12 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToCategory(session model.Sessi }() defer span.Finish() - resultVar0 := a.app.SessionHasPermissionToCategory(session, userID, teamID, categoryId) + resultVar0 := a.app.SessionHasPermissionToCategory(c, session, userID, teamID, categoryId) return resultVar0 } -func (a *OpenTracingAppLayer) SessionHasPermissionToChannel(session model.Session, channelID string, permission *model.Permission) bool { +func (a *OpenTracingAppLayer) SessionHasPermissionToChannel(c request.CTX, session model.Session, channelID string, permission *model.Permission) bool { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToChannel") @@ -15211,7 +15211,7 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToChannel(session model.Sessio }() defer span.Finish() - resultVar0 := a.app.SessionHasPermissionToChannel(session, channelID, permission) + resultVar0 := a.app.SessionHasPermissionToChannel(c, session, channelID, permission) return resultVar0 } @@ -15233,7 +15233,7 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToChannelByPost(session model. return resultVar0 } -func (a *OpenTracingAppLayer) SessionHasPermissionToChannels(session model.Session, channelIDs []string, permission *model.Permission) bool { +func (a *OpenTracingAppLayer) SessionHasPermissionToChannels(c request.CTX, session model.Session, channelIDs []string, permission *model.Permission) bool { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToChannels") @@ -15245,7 +15245,7 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToChannels(session model.Sessi }() defer span.Finish() - resultVar0 := a.app.SessionHasPermissionToChannels(session, channelIDs, permission) + resultVar0 := a.app.SessionHasPermissionToChannels(c, session, channelIDs, permission) return resultVar0 } @@ -15340,7 +15340,7 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToTeam(session model.Session, return resultVar0 } -func (a *OpenTracingAppLayer) SessionHasPermissionToTeams(session model.Session, teamIDs []string, permission *model.Permission) bool { +func (a *OpenTracingAppLayer) SessionHasPermissionToTeams(c request.CTX, session model.Session, teamIDs []string, permission *model.Permission) bool { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToTeams") @@ -15352,7 +15352,7 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToTeams(session model.Session, }() defer span.Finish() - resultVar0 := a.app.SessionHasPermissionToTeams(session, teamIDs, permission) + resultVar0 := a.app.SessionHasPermissionToTeams(c, session, teamIDs, permission) return resultVar0 } @@ -15408,7 +15408,7 @@ func (a *OpenTracingAppLayer) SessionIsRegistered(session model.Session) bool { return resultVar0 } -func (a *OpenTracingAppLayer) SetActiveChannel(userID string, channelID string) *model.AppError { +func (a *OpenTracingAppLayer) SetActiveChannel(c request.CTX, userID string, channelID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetActiveChannel") @@ -15420,7 +15420,7 @@ func (a *OpenTracingAppLayer) SetActiveChannel(userID string, channelID string) }() defer span.Finish() - resultVar0 := a.app.SetActiveChannel(userID, channelID) + resultVar0 := a.app.SetActiveChannel(c, userID, channelID) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -16368,7 +16368,7 @@ func (a *OpenTracingAppLayer) TestSiteURL(siteURL string) *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) ToggleMuteChannel(channelID string, userID string) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) ToggleMuteChannel(c request.CTX, channelID string, userID string) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ToggleMuteChannel") @@ -16380,7 +16380,7 @@ func (a *OpenTracingAppLayer) ToggleMuteChannel(channelID string, userID string) }() defer span.Finish() - resultVar0, resultVar1 := a.app.ToggleMuteChannel(channelID, userID) + resultVar0, resultVar1 := a.app.ToggleMuteChannel(c, channelID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16407,7 +16407,7 @@ func (a *OpenTracingAppLayer) TotalWebsocketConnections() int { return resultVar0 } -func (a *OpenTracingAppLayer) TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { +func (a *OpenTracingAppLayer) TriggerWebhook(c request.CTX, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TriggerWebhook") @@ -16503,7 +16503,7 @@ func (a *OpenTracingAppLayer) UpdateBotOwner(botUserId string, newOwnerId string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateChannel(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannel") @@ -16515,7 +16515,7 @@ func (a *OpenTracingAppLayer) UpdateChannel(channel *model.Channel) (*model.Chan }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateChannel(channel) + resultVar0, resultVar1 := a.app.UpdateChannel(c, channel) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16525,7 +16525,7 @@ func (a *OpenTracingAppLayer) UpdateChannel(channel *model.Channel) (*model.Chan return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateChannelMemberNotifyProps(data map[string]string, channelID string, userID string) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateChannelMemberNotifyProps(c request.CTX, data map[string]string, channelID string, userID string) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelMemberNotifyProps") @@ -16537,7 +16537,7 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberNotifyProps(data map[string]str }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateChannelMemberNotifyProps(data, channelID, userID) + resultVar0, resultVar1 := a.app.UpdateChannelMemberNotifyProps(c, data, channelID, userID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16547,7 +16547,7 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberNotifyProps(data map[string]str return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateChannelMemberRoles(channelID string, userID string, newRoles string) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateChannelMemberRoles(c request.CTX, channelID string, userID string, newRoles string) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelMemberRoles") @@ -16559,7 +16559,7 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberRoles(channelID string, userID }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateChannelMemberRoles(channelID, userID, newRoles) + resultVar0, resultVar1 := a.app.UpdateChannelMemberRoles(c, channelID, userID, newRoles) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16569,7 +16569,7 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberRoles(channelID string, userID return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateChannelMemberSchemeRoles(channelID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateChannelMemberSchemeRoles(c request.CTX, channelID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelMemberSchemeRoles") @@ -16581,7 +16581,7 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberSchemeRoles(channelID string, u }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateChannelMemberSchemeRoles(channelID, userID, isSchemeGuest, isSchemeUser, isSchemeAdmin) + resultVar0, resultVar1 := a.app.UpdateChannelMemberSchemeRoles(c, channelID, userID, isSchemeGuest, isSchemeUser, isSchemeAdmin) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16591,7 +16591,7 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberSchemeRoles(channelID string, u return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateChannelPrivacy(c request.CTX, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelPrivacy") @@ -16613,7 +16613,7 @@ func (a *OpenTracingAppLayer) UpdateChannelPrivacy(c *request.Context, oldChanne return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateChannelScheme(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelScheme") @@ -16625,7 +16625,7 @@ func (a *OpenTracingAppLayer) UpdateChannelScheme(channel *model.Channel) (*mode }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateChannelScheme(channel) + resultVar0, resultVar1 := a.app.UpdateChannelScheme(c, channel) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -16687,7 +16687,7 @@ func (a *OpenTracingAppLayer) UpdateDNDStatusOfUsers() { a.app.UpdateDNDStatusOfUsers() } -func (a *OpenTracingAppLayer) UpdateEphemeralPost(userID string, post *model.Post) *model.Post { +func (a *OpenTracingAppLayer) UpdateEphemeralPost(c request.CTX, userID string, post *model.Post) *model.Post { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateEphemeralPost") @@ -16699,7 +16699,7 @@ func (a *OpenTracingAppLayer) UpdateEphemeralPost(userID string, post *model.Pos }() defer span.Finish() - resultVar0 := a.app.UpdateEphemeralPost(userID, post) + resultVar0 := a.app.UpdateEphemeralPost(c, userID, post) return resultVar0 } @@ -16932,7 +16932,7 @@ func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *mod return resultVar0 } -func (a *OpenTracingAppLayer) UpdateOutgoingWebhook(oldHook *model.OutgoingWebhook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateOutgoingWebhook(c request.CTX, oldHook *model.OutgoingWebhook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOutgoingWebhook") @@ -16944,7 +16944,7 @@ func (a *OpenTracingAppLayer) UpdateOutgoingWebhook(oldHook *model.OutgoingWebho }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateOutgoingWebhook(oldHook, updatedHook) + resultVar0, resultVar1 := a.app.UpdateOutgoingWebhook(c, oldHook, updatedHook) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -17240,7 +17240,7 @@ func (a *OpenTracingAppLayer) UpdateSharedChannelRemoteCursor(id string, cursor return resultVar0 } -func (a *OpenTracingAppLayer) UpdateSidebarCategories(userID string, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateSidebarCategories(c request.CTX, userID string, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateSidebarCategories") @@ -17252,7 +17252,7 @@ func (a *OpenTracingAppLayer) UpdateSidebarCategories(userID string, teamID stri }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateSidebarCategories(userID, teamID, categories) + resultVar0, resultVar1 := a.app.UpdateSidebarCategories(c, userID, teamID, categories) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -17262,7 +17262,7 @@ func (a *OpenTracingAppLayer) UpdateSidebarCategories(userID string, teamID stri return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateSidebarCategoryOrder(userID string, teamID string, categoryOrder []string) *model.AppError { +func (a *OpenTracingAppLayer) UpdateSidebarCategoryOrder(c request.CTX, userID string, teamID string, categoryOrder []string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateSidebarCategoryOrder") @@ -17274,7 +17274,7 @@ func (a *OpenTracingAppLayer) UpdateSidebarCategoryOrder(userID string, teamID s }() defer span.Finish() - resultVar0 := a.app.UpdateSidebarCategoryOrder(userID, teamID, categoryOrder) + resultVar0 := a.app.UpdateSidebarCategoryOrder(c, userID, teamID, categoryOrder) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -17416,7 +17416,7 @@ func (a *OpenTracingAppLayer) UpdateThreadFollowForUser(userID string, teamID st return resultVar0 } -func (a *OpenTracingAppLayer) UpdateThreadFollowForUserFromChannelAdd(userID string, teamID string, threadID string) *model.AppError { +func (a *OpenTracingAppLayer) UpdateThreadFollowForUserFromChannelAdd(c request.CTX, userID string, teamID string, threadID string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadFollowForUserFromChannelAdd") @@ -17428,7 +17428,7 @@ func (a *OpenTracingAppLayer) UpdateThreadFollowForUserFromChannelAdd(userID str }() defer span.Finish() - resultVar0 := a.app.UpdateThreadFollowForUserFromChannelAdd(userID, teamID, threadID) + resultVar0 := a.app.UpdateThreadFollowForUserFromChannelAdd(c, userID, teamID, threadID) if resultVar0 != nil { span.LogFields(spanlog.Error(resultVar0)) @@ -17438,7 +17438,7 @@ func (a *OpenTracingAppLayer) UpdateThreadFollowForUserFromChannelAdd(userID str return resultVar0 } -func (a *OpenTracingAppLayer) UpdateThreadReadForUser(currentSessionId string, userID string, teamID string, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateThreadReadForUser(c request.CTX, currentSessionId string, userID string, teamID string, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadReadForUser") @@ -17450,7 +17450,7 @@ func (a *OpenTracingAppLayer) UpdateThreadReadForUser(currentSessionId string, u }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateThreadReadForUser(currentSessionId, userID, teamID, threadID, timestamp) + resultVar0, resultVar1 := a.app.UpdateThreadReadForUser(c, currentSessionId, userID, teamID, threadID, timestamp) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -17460,7 +17460,7 @@ func (a *OpenTracingAppLayer) UpdateThreadReadForUser(currentSessionId string, u return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) UpdateThreadReadForUserByPost(currentSessionId string, userID string, teamID string, threadID string, postID string) (*model.ThreadResponse, *model.AppError) { +func (a *OpenTracingAppLayer) UpdateThreadReadForUserByPost(c request.CTX, currentSessionId string, userID string, teamID string, threadID string, postID string) (*model.ThreadResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadReadForUserByPost") @@ -17472,7 +17472,7 @@ func (a *OpenTracingAppLayer) UpdateThreadReadForUserByPost(currentSessionId str }() defer span.Finish() - resultVar0, resultVar1 := a.app.UpdateThreadReadForUserByPost(currentSessionId, userID, teamID, threadID, postID) + resultVar0, resultVar1 := a.app.UpdateThreadReadForUserByPost(c, currentSessionId, userID, teamID, threadID, postID) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) @@ -17996,7 +17996,7 @@ func (a *OpenTracingAppLayer) VerifyUserEmail(userID string, email string) *mode return resultVar0 } -func (a *OpenTracingAppLayer) ViewChannel(view *model.ChannelView, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { +func (a *OpenTracingAppLayer) ViewChannel(c request.CTX, view *model.ChannelView, userID string, currentSessionId string, collapsedThreadsSupported bool) (map[string]int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ViewChannel") @@ -18008,7 +18008,7 @@ func (a *OpenTracingAppLayer) ViewChannel(view *model.ChannelView, userID string }() defer span.Finish() - resultVar0, resultVar1 := a.app.ViewChannel(view, userID, currentSessionId, collapsedThreadsSupported) + resultVar0, resultVar1 := a.app.ViewChannel(c, view, userID, currentSessionId, collapsedThreadsSupported) if resultVar1 != nil { span.LogFields(spanlog.Error(resultVar1)) diff --git a/app/permissions.go b/app/permissions.go index 8d3bf69e5f..80f4b05c21 100644 --- a/app/permissions.go +++ b/app/permissions.go @@ -13,6 +13,7 @@ import ( "github.com/pkg/errors" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" ) @@ -27,8 +28,8 @@ func (s *permissionsServiceWrapper) HasPermissionToTeam(userID string, teamID st return s.app.HasPermissionToTeam(userID, teamID, permission) } -func (s *permissionsServiceWrapper) HasPermissionToChannel(askingUserID string, channelID string, permission *model.Permission) bool { - return s.app.HasPermissionToChannel(askingUserID, channelID, permission) +func (s *permissionsServiceWrapper) HasPermissionToChannel(c request.CTX, askingUserID string, channelID string, permission *model.Permission) bool { + return s.app.HasPermissionToChannel(c, askingUserID, channelID, permission) } func (a *App) ResetPermissionsSystem() *model.AppError { diff --git a/app/plugin_api.go b/app/plugin_api.go index dde877d0d3..6e0edeab21 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -5,7 +5,6 @@ package app import ( "bytes" - "context" "encoding/json" "fmt" "io" @@ -418,7 +417,7 @@ func (api *PluginAPI) CreateChannel(channel *model.Channel) (*model.Channel, *mo } func (api *PluginAPI) DeleteChannel(channelID string) *model.AppError { - channel, err := api.app.GetChannel(channelID) + channel, err := api.app.GetChannel(api.ctx, channelID) if err != nil { return err } @@ -426,7 +425,7 @@ func (api *PluginAPI) DeleteChannel(channelID string) *model.AppError { } func (api *PluginAPI) GetPublicChannelsForTeam(teamID string, page, perPage int) ([]*model.Channel, *model.AppError) { - channels, err := api.app.GetPublicChannelsForTeam(teamID, page*perPage, perPage) + channels, err := api.app.GetPublicChannelsForTeam(api.ctx, teamID, page*perPage, perPage) if err != nil { return nil, err } @@ -434,19 +433,19 @@ func (api *PluginAPI) GetPublicChannelsForTeam(teamID string, page, perPage int) } func (api *PluginAPI) GetChannel(channelID string) (*model.Channel, *model.AppError) { - return api.app.GetChannel(channelID) + return api.app.GetChannel(api.ctx, channelID) } func (api *PluginAPI) GetChannelByName(teamID, name string, includeDeleted bool) (*model.Channel, *model.AppError) { - return api.app.GetChannelByName(name, teamID, includeDeleted) + return api.app.GetChannelByName(api.ctx, name, teamID, includeDeleted) } func (api *PluginAPI) GetChannelByNameForTeamName(teamName, channelName string, includeDeleted bool) (*model.Channel, *model.AppError) { - return api.app.GetChannelByNameForTeamName(channelName, teamName, includeDeleted) + return api.app.GetChannelByNameForTeamName(api.ctx, channelName, teamName, includeDeleted) } func (api *PluginAPI) GetChannelsForTeamForUser(teamID, userID string, includeDeleted bool) ([]*model.Channel, *model.AppError) { - channels, err := api.app.GetChannelsForTeamForUser(teamID, userID, &model.ChannelSearchOpts{ + channels, err := api.app.GetChannelsForTeamForUser(api.ctx, teamID, userID, &model.ChannelSearchOpts{ IncludeDeleted: includeDeleted, LastDeleteAt: 0, }) @@ -457,11 +456,11 @@ func (api *PluginAPI) GetChannelsForTeamForUser(teamID, userID string, includeDe } func (api *PluginAPI) GetChannelStats(channelID string) (*model.ChannelStats, *model.AppError) { - memberCount, err := api.app.GetChannelMemberCount(channelID) + memberCount, err := api.app.GetChannelMemberCount(api.ctx, channelID) if err != nil { return nil, err } - guestCount, err := api.app.GetChannelMemberCount(channelID) + guestCount, err := api.app.GetChannelMemberCount(api.ctx, channelID) if err != nil { return nil, err } @@ -473,15 +472,15 @@ func (api *PluginAPI) GetDirectChannel(userID1, userID2 string) (*model.Channel, } func (api *PluginAPI) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) { - return api.app.CreateGroupChannel(userIDs, "") + return api.app.CreateGroupChannel(api.ctx, userIDs, "") } func (api *PluginAPI) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) { - return api.app.UpdateChannel(channel) + return api.app.UpdateChannel(api.ctx, channel) } func (api *PluginAPI) SearchChannels(teamID string, term string) ([]*model.Channel, *model.AppError) { - channels, err := api.app.SearchChannels(teamID, term) + channels, err := api.app.SearchChannels(api.ctx, teamID, term) if err != nil { return nil, err } @@ -489,15 +488,15 @@ func (api *PluginAPI) SearchChannels(teamID string, term string) ([]*model.Chann } func (api *PluginAPI) CreateChannelSidebarCategory(userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) { - return api.app.CreateSidebarCategory(userID, teamID, newCategory) + return api.app.CreateSidebarCategory(api.ctx, userID, teamID, newCategory) } func (api *PluginAPI) GetChannelSidebarCategories(userID, teamID string) (*model.OrderedSidebarCategories, *model.AppError) { - return api.app.GetSidebarCategoriesForTeamForUser(userID, teamID) + return api.app.GetSidebarCategoriesForTeamForUser(api.ctx, userID, teamID) } func (api *PluginAPI) UpdateChannelSidebarCategories(userID, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) { - return api.app.UpdateSidebarCategories(userID, teamID, categories) + return api.app.UpdateSidebarCategories(api.ctx, userID, teamID, categories) } func (api *PluginAPI) SearchUsers(search *model.UserSearch) ([]*model.User, *model.AppError) { @@ -576,29 +575,29 @@ func (api *PluginAPI) AddUserToChannel(channelID, userID, asUserID string) (*mod } func (api *PluginAPI) GetChannelMember(channelID, userID string) (*model.ChannelMember, *model.AppError) { - return api.app.GetChannelMember(context.Background(), channelID, userID) + return api.app.GetChannelMember(api.ctx, channelID, userID) } func (api *PluginAPI) GetChannelMembers(channelID string, page, perPage int) (model.ChannelMembers, *model.AppError) { - return api.app.GetChannelMembersPage(channelID, page, perPage) + return api.app.GetChannelMembersPage(api.ctx, channelID, page, perPage) } func (api *PluginAPI) GetChannelMembersByIds(channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) { - return api.app.GetChannelMembersByIds(channelID, userIDs) + return api.app.GetChannelMembersByIds(api.ctx, channelID, userIDs) } func (api *PluginAPI) GetChannelMembersForUser(_, userID string, page, perPage int) ([]*model.ChannelMember, *model.AppError) { // The team ID parameter was never used in the SQL query. // But we keep this to maintain compatibility. - return api.app.GetChannelMembersForUserWithPagination(userID, page, perPage) + return api.app.GetChannelMembersForUserWithPagination(api.ctx, userID, page, perPage) } func (api *PluginAPI) UpdateChannelMemberRoles(channelID, userID, newRoles string) (*model.ChannelMember, *model.AppError) { - return api.app.UpdateChannelMemberRoles(channelID, userID, newRoles) + return api.app.UpdateChannelMemberRoles(api.ctx, channelID, userID, newRoles) } func (api *PluginAPI) UpdateChannelMemberNotifications(channelID, userID string, notifications map[string]string) (*model.ChannelMember, *model.AppError) { - return api.app.UpdateChannelMemberNotifyProps(notifications, channelID, userID) + return api.app.UpdateChannelMemberNotifyProps(api.ctx, notifications, channelID, userID) } func (api *PluginAPI) DeleteChannelMember(channelID, userID string) *model.AppError { @@ -644,11 +643,11 @@ func (api *PluginAPI) GetReactions(postID string) ([]*model.Reaction, *model.App } func (api *PluginAPI) SendEphemeralPost(userID string, post *model.Post) *model.Post { - return api.app.SendEphemeralPost(userID, post) + return api.app.SendEphemeralPost(api.ctx, userID, post) } func (api *PluginAPI) UpdateEphemeralPost(userID string, post *model.Post) *model.Post { - return api.app.UpdateEphemeralPost(userID, post) + return api.app.UpdateEphemeralPost(api.ctx, userID, post) } func (api *PluginAPI) DeleteEphemeralPost(userID, postID string) { @@ -656,7 +655,7 @@ func (api *PluginAPI) DeleteEphemeralPost(userID, postID string) { } func (api *PluginAPI) DeletePost(postID string) *model.AppError { - _, err := api.app.DeletePost(postID, api.id) + _, err := api.app.DeletePost(api.ctx, postID, api.id) return err } @@ -923,7 +922,7 @@ func (api *PluginAPI) HasPermissionToTeam(userID, teamID string, permission *mod } func (api *PluginAPI) HasPermissionToChannel(userID, channelID string, permission *model.Permission) bool { - return api.app.HasPermissionToChannel(userID, channelID, permission) + return api.app.HasPermissionToChannel(api.ctx, userID, channelID, permission) } func (api *PluginAPI) RolesGrantPermission(roleNames []string, permissionId string) bool { diff --git a/app/plugin_commands.go b/app/plugin_commands.go index 46201601e4..3caa1547ab 100644 --- a/app/plugin_commands.go +++ b/app/plugin_commands.go @@ -154,7 +154,7 @@ func (a *App) tryExecutePluginCommand(c *request.Context, args *model.CommandArg args.AddUserMention(username, userID) } - for channelName, channelID := range a.MentionsToPublicChannels(args.Command, args.TeamId) { + for channelName, channelID := range a.MentionsToPublicChannels(c, args.Command, args.TeamId) { args.AddChannelMention(channelName, channelID) } diff --git a/app/plugin_hooks_test.go b/app/plugin_hooks_test.go index 08a160bbad..32945cfed7 100644 --- a/app/plugin_hooks_test.go +++ b/app/plugin_hooks_test.go @@ -912,6 +912,7 @@ func TestHookContext(t *testing.T) { // We don't actually have a session, we are faking it so just set something arbitrarily ctx := request.NewContext(context.Background(), model.NewId(), model.NewId(), model.NewId(), model.NewId(), model.NewId(), model.Session{}, nil) + ctx.SetLogger(th.TestLogger) ctx.Session().Id = model.NewId() var mockAPI plugintest.API diff --git a/app/plugin_test.go b/app/plugin_test.go index 552d373a44..3342f12a5b 100644 --- a/app/plugin_test.go +++ b/app/plugin_test.go @@ -638,7 +638,7 @@ func TestChannelsPluginsInit(t *testing.T) { defer th.TearDown() runNoPanicTest := func(t *testing.T) { - ctx := request.EmptyContext() + ctx := request.EmptyContext(th.TestLogger) path, _ := fileutils.FindDir("tests") require.NotPanics(t, func() { diff --git a/app/post.go b/app/post.go index 04eba9c3e1..01c17df6dd 100644 --- a/app/post.go +++ b/app/post.go @@ -75,9 +75,9 @@ func (a *App) CreatePostAsUser(c *request.Context, post *model.Post, currentSess // the post is NOT a reply post with CRT enabled _, fromWebhook := post.GetProps()["from_webhook"] _, fromBot := post.GetProps()["from_bot"] - isCRTReply := post.RootId != "" && a.IsCRTEnabledForUser(post.UserId) + isCRTReply := post.RootId != "" && a.IsCRTEnabledForUser(c, post.UserId) if !fromWebhook && !fromBot && !isCRTReply { - if _, err := a.MarkChannelsAsViewed([]string{post.ChannelId}, post.UserId, currentSessionId, true); err != nil { + if _, err := a.MarkChannelsAsViewed(c, []string{post.ChannelId}, post.UserId, currentSessionId, true); err != nil { mlog.Warn( "Encountered error updating last viewed", mlog.String("channel_id", post.ChannelId), @@ -90,7 +90,7 @@ func (a *App) CreatePostAsUser(c *request.Context, post *model.Post, currentSess return rp, nil } -func (a *App) CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { +func (a *App) CreatePostMissingChannel(c request.CTX, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { channel, err := a.Srv().Store.Channel().Get(post.ChannelId, true) if err != nil { var nfErr *store.ErrNotFound @@ -147,7 +147,7 @@ func (a *App) deduplicateCreatePost(post *model.Post) (foundPost *model.Post, er return actualPost, nil } -func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) { +func (a *App) CreatePost(c request.CTX, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) { foundPost, err := a.deduplicateCreatePost(post) if err != nil { return nil, err @@ -199,7 +199,7 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch } var ephemeralPost *model.Post - if post.Type == "" && !a.HasPermissionToChannel(user.Id, channel.Id, model.PermissionUseChannelMentions) { + if post.Type == "" && !a.HasPermissionToChannel(c, user.Id, channel.Id, model.PermissionUseChannelMentions) { mention := post.DisableMentionHighlights() if mention != "" { T := i18n.GetUserTranslations(user.Locale) @@ -233,7 +233,7 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch post.Hashtags, _ = model.ParseHashtags(post.Message) - if err = a.FillInPostProps(post, channel); err != nil { + if err = a.FillInPostProps(c, post, channel); err != nil { return nil, err } @@ -280,7 +280,7 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch post.CreateAt = model.GetMillis() } - post = a.getEmbedsAndImages(post, true) + post = a.getEmbedsAndImages(c, post, true) previewPost := post.GetPreviewPost() if previewPost != nil { post.AddProp(model.PostPropsPreviewedPost, previewPost.PostID) @@ -359,10 +359,10 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch // Send any ephemeral posts after the post is created to ensure it shows up after the latest post created if ephemeralPost != nil { - a.SendEphemeralPost(post.UserId, ephemeralPost) + a.SendEphemeralPost(c, post.UserId, ephemeralPost) } - rpost, err = a.SanitizePostMetadataForUser(rpost, c.Session().UserId) + rpost, err = a.SanitizePostMetadataForUser(c, rpost, c.Session().UserId) if err != nil { return nil, err } @@ -409,7 +409,7 @@ func (a *App) attachFilesToPost(post *model.Post) *model.AppError { // channel_mentions. // // If channel is nil, FillInPostProps will look up the channel corresponding to the post. -func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.AppError { +func (a *App) FillInPostProps(c request.CTX, post *model.Post, channel *model.Channel) *model.AppError { channelMentions := post.ChannelMentions() channelMentionsProp := make(map[string]any) @@ -422,7 +422,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A channel = postChannel } - mentionedChannels, err := a.GetChannelsByNames(channelMentions, channel.TeamId) + mentionedChannels, err := a.GetChannelsByNames(c, channelMentions, channel.TeamId) if err != nil { return err } @@ -449,14 +449,14 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A } matched := atMentionPattern.MatchString(post.Message) - if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseGroupMentions) { + if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(c, post.UserId, post.ChannelId, model.PermissionUseGroupMentions) { post.AddProp(model.PostPropsGroupHighlightDisabled, true) } return nil } -func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error { +func (a *App) handlePostEvents(c request.CTX, post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error { var team *model.Team if channel.TeamId != "" { t, err := a.Srv().Store.Team().Get(channel.TeamId) @@ -472,7 +472,7 @@ func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model a.invalidateCacheForChannel(channel) a.invalidateCacheForChannelPosts(channel.Id) - if _, err := a.SendNotifications(post, team, channel, user, parentPostList, setOnline); err != nil { + if _, err := a.SendNotifications(c, post, team, channel, user, parentPostList, setOnline); err != nil { return err } @@ -496,7 +496,7 @@ func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model return nil } -func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post { +func (a *App) SendEphemeralPost(c request.CTX, userID string, post *model.Post) *model.Post { post.Type = model.PostTypeEphemeral // fill in fields which haven't been specified which have sensible defaults @@ -512,7 +512,7 @@ func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post { post.GenerateActionIds() message := model.NewWebSocketEvent(model.WebsocketEventEphemeralMessage, "", post.ChannelId, userID, nil) - post = a.PreparePostForClientWithEmbedsAndImages(post, true, false) + post = a.PreparePostForClientWithEmbedsAndImages(c, post, true, false) post = model.AddPostActionCookies(post, a.PostActionCookieSecret()) postJSON, jsonErr := post.ToJSON() @@ -525,7 +525,7 @@ func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post { return post } -func (a *App) UpdateEphemeralPost(userID string, post *model.Post) *model.Post { +func (a *App) UpdateEphemeralPost(c request.CTX, userID string, post *model.Post) *model.Post { post.Type = model.PostTypeEphemeral post.UpdateAt = model.GetMillis() @@ -535,7 +535,7 @@ func (a *App) UpdateEphemeralPost(userID string, post *model.Post) *model.Post { post.GenerateActionIds() message := model.NewWebSocketEvent(model.WebsocketEventPostEdited, "", post.ChannelId, userID, nil) - post = a.PreparePostForClientWithEmbedsAndImages(post, true, false) + post = a.PreparePostForClientWithEmbedsAndImages(c, post, true, false) post = model.AddPostActionCookies(post, a.PostActionCookieSecret()) postJSON, jsonErr := post.ToJSON() if jsonErr != nil { @@ -604,7 +604,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) return nil, err } - channel, err := a.GetChannel(oldPost.ChannelId) + channel, err := a.GetChannel(c, oldPost.ChannelId) if err != nil { return nil, err } @@ -633,7 +633,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) newPost.EditAt = model.GetMillis() } - if err = a.FillInPostProps(post, nil); err != nil { + if err = a.FillInPostProps(c, post, nil); err != nil { return nil, err } @@ -674,7 +674,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) }) } - rpost = a.PreparePostForClientWithEmbedsAndImages(rpost, false, true) + rpost = a.PreparePostForClientWithEmbedsAndImages(c, rpost, false, true) // Ensure IsFollowing is nil since this updated post will be broadcast to all users // and we don't want to have to populate it for every single user and broadcast to each @@ -693,7 +693,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) } message.Add("post", postJSON) - published, err := a.publishWebsocketEventForPermalinkPost(rpost, message) + published, err := a.publishWebsocketEventForPermalinkPost(c, rpost, message) if err != nil { return nil, err } @@ -706,7 +706,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) return rpost, nil } -func (a *App) publishWebsocketEventForPermalinkPost(post *model.Post, message *model.WebSocketEvent) (published bool, err *model.AppError) { +func (a *App) publishWebsocketEventForPermalinkPost(c request.CTX, post *model.Post, message *model.WebSocketEvent) (published bool, err *model.AppError) { var previewedPostID string if val, ok := post.GetProp(model.PostPropsPreviewedPost).(string); ok { previewedPostID = val @@ -728,12 +728,12 @@ func (a *App) publishWebsocketEventForPermalinkPost(post *model.Post, message *m return false, err } - channelMembers, err := a.GetChannelMembersPage(post.ChannelId, 0, 10000000) + channelMembers, err := a.GetChannelMembersPage(c, post.ChannelId, 0, 10000000) if err != nil { return false, err } - permalinkPreviewedChannel, err := a.GetChannel(previewedPost.ChannelId) + permalinkPreviewedChannel, err := a.GetChannel(c, previewedPost.ChannelId) if err != nil { if err.StatusCode == http.StatusNotFound { mlog.Warn("channel containing permalinked post not found", mlog.String("referenced_channel_id", previewedPost.ChannelId)) @@ -748,7 +748,7 @@ func (a *App) publishWebsocketEventForPermalinkPost(post *model.Post, message *m post.Metadata.Embeds[0].Data = permalinkPreviewedPost } - postForUser := a.sanitizePostMetadataForUserAndChannel(post, permalinkPreviewedPost, permalinkPreviewedChannel, cm.UserId) + postForUser := a.sanitizePostMetadataForUserAndChannel(c, post, permalinkPreviewedPost, permalinkPreviewedChannel, cm.UserId) // Using DeepCopy here to avoid a race condition // between publishing the event and setting the "post" data value below. @@ -774,7 +774,7 @@ func (a *App) PatchPost(c *request.Context, postID string, patch *model.PostPatc return nil, err } - channel, err := a.GetChannel(post.ChannelId) + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return nil, err } @@ -784,7 +784,7 @@ func (a *App) PatchPost(c *request.Context, postID string, patch *model.PostPatc return nil, err } - if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseChannelMentions) { + if !a.HasPermissionToChannel(c, post.UserId, post.ChannelId, model.PermissionUseChannelMentions) { patch.DisableMentionHighlights() } @@ -946,7 +946,7 @@ func (a *App) GetFlaggedPostsForChannel(userID, channelID string, offset int, li return postList, nil } -func (a *App) GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError) { +func (a *App) GetPermalinkPost(c request.CTX, postID string, userID string) (*model.PostList, *model.AppError) { list, nErr := a.Srv().Store.Post().Get(context.Background(), postID, model.GetPostsOptions{}, userID, a.Config().GetSanitizeOptions()) if nErr != nil { var nfErr *store.ErrNotFound @@ -966,7 +966,7 @@ func (a *App) GetPermalinkPost(c *request.Context, postID string, userID string) } post := list.Posts[list.Order[0]] - channel, err := a.GetChannel(post.ChannelId) + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return nil, err } @@ -1174,10 +1174,10 @@ func (a *App) AddCursorIdsForPostList(originalList *model.PostList, afterPost, b originalList.NextPostId = nextPostId originalList.PrevPostId = prevPostId } -func (a *App) GetPostsForChannelAroundLastUnread(channelID, userID string, limitBefore, limitAfter int, skipFetchThreads bool, collapsedThreads, collapsedThreadsExtended bool) (*model.PostList, *model.AppError) { +func (a *App) GetPostsForChannelAroundLastUnread(c request.CTX, channelID, userID string, limitBefore, limitAfter int, skipFetchThreads bool, collapsedThreads, collapsedThreadsExtended bool) (*model.PostList, *model.AppError) { var member *model.ChannelMember var err *model.AppError - if member, err = a.GetChannelMember(context.Background(), channelID, userID); err != nil { + if member, err = a.GetChannelMember(c, channelID, userID); err != nil { return nil, err } else if member.LastViewedAt == 0 { return model.NewPostList(), nil @@ -1219,13 +1219,13 @@ func (a *App) GetPostsForChannelAroundLastUnread(channelID, userID string, limit return postList, nil } -func (a *App) DeletePost(postID, deleteByID string) (*model.Post, *model.AppError) { +func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post, *model.AppError) { post, nErr := a.Srv().Store.Post().GetSingle(postID, false) if nErr != nil { return nil, model.NewAppError("DeletePost", "app.post.get.app_error", nil, nErr.Error(), http.StatusBadRequest) } - channel, err := a.GetChannel(post.ChannelId) + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return nil, err } @@ -1299,7 +1299,7 @@ func (a *App) parseAndFetchChannelIdByNameFromInFilter(c *request.Context, chann userIDs = append(userIDs, user.Id) } - channel, err := a.GetGroupChannel(userIDs) + channel, err := a.GetGroupChannel(c, userIDs) if err != nil { return nil, err } @@ -1318,7 +1318,7 @@ func (a *App) parseAndFetchChannelIdByNameFromInFilter(c *request.Context, chann return channel, nil } - channel, err := a.GetChannelByName(channelName, teamID, includeDeleted) + channel, err := a.GetChannelByName(c, channelName, teamID, includeDeleted) if err != nil { return nil, err } @@ -1642,8 +1642,8 @@ func (a *App) MaxPostSize() int { } // countThreadMentions returns the number of times the user is mentioned in a specified thread after the timestamp. -func (a *App) countThreadMentions(user *model.User, post *model.Post, teamID string, timestamp int64) (int64, *model.AppError) { - channel, err := a.GetChannel(post.ChannelId) +func (a *App) countThreadMentions(c request.CTX, user *model.User, post *model.Post, teamID string, timestamp int64) (int64, *model.AppError) { + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return 0, err } @@ -1702,8 +1702,8 @@ func (a *App) countThreadMentions(user *model.User, post *model.Post, teamID str // countMentionsFromPost returns the number of posts in the post's channel that mention the user after and including the // given post. -func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, int, *model.AppError) { - channel, err := a.GetChannel(post.ChannelId) +func (a *App) countMentionsFromPost(c request.CTX, user *model.User, post *model.Post) (int, int, *model.AppError) { + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return 0, 0, err } @@ -1718,7 +1718,7 @@ func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, in return count, countRoot, nil } - channelMember, err := a.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, err := a.GetChannelMember(c, channel.Id, user.Id) if err != nil { return 0, 0, err } @@ -1850,18 +1850,18 @@ func (a *App) GetThreadMembershipsForUser(userID, teamID string) ([]*model.Threa return a.Srv().Store.Thread().GetMembershipsForUser(userID, teamID) } -func (a *App) GetPostIfAuthorized(postID string, session *model.Session, includeDeleted bool) (*model.Post, *model.AppError) { +func (a *App) GetPostIfAuthorized(c request.CTX, postID string, session *model.Session, includeDeleted bool) (*model.Post, *model.AppError) { post, err := a.GetSinglePost(postID, includeDeleted) if err != nil { return nil, err } - channel, err := a.GetChannel(post.ChannelId) + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return nil, err } - if !a.SessionHasPermissionToChannel(*session, channel.Id, model.PermissionReadChannel) { + if !a.SessionHasPermissionToChannel(c, *session, channel.Id, model.PermissionReadChannel) { if channel.Type == model.ChannelTypeOpen { if !a.SessionHasPermissionToTeam(*session, channel.TeamId, model.PermissionReadPublicChannel) { return nil, a.MakePermissionError(session, []*model.Permission{model.PermissionReadPublicChannel}) @@ -1895,7 +1895,7 @@ func (a *App) GetPostsByIds(postIDs []string) ([]*model.Post, bool, *model.AppEr return posts, hasInaccessiblePosts, nil } -func (a *App) GetTopThreadsForTeamSince(teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { +func (a *App) GetTopThreadsForTeamSince(c request.CTX, teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.insights.feature_disabled", nil, "", http.StatusNotImplemented) } @@ -1904,14 +1904,14 @@ func (a *App) GetTopThreadsForTeamSince(teamID, userID string, opts *model.Insig if err != nil { return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.post.get_top_threads_for_team_since.app_error", nil, err.Error(), http.StatusInternalServerError) } - topThreadsWithEmbedAndImage, err := includeEmbedsAndImages(a, topThreads, userID) + topThreadsWithEmbedAndImage, err := includeEmbedsAndImages(a, c, topThreads, userID) if err != nil { return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.post.get_top_threads_for_team_since.app_error", nil, err.Error(), http.StatusInternalServerError) } return topThreadsWithEmbedAndImage, nil } -func (a *App) GetTopThreadsForUserSince(teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { +func (a *App) GetTopThreadsForUserSince(c request.CTX, teamID, userID string, opts *model.InsightsOpts) (*model.TopThreadList, *model.AppError) { if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.insights.feature_disabled", nil, "", http.StatusNotImplemented) } @@ -1920,17 +1920,17 @@ func (a *App) GetTopThreadsForUserSince(teamID, userID string, opts *model.Insig if err != nil { return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.post.get_top_threads_for_team_since.app_error", nil, err.Error(), http.StatusInternalServerError) } - topThreadsWithEmbedAndImage, err := includeEmbedsAndImages(a, topThreads, userID) + topThreadsWithEmbedAndImage, err := includeEmbedsAndImages(a, c, topThreads, userID) if err != nil { return nil, model.NewAppError("GetTopChannelsForUserSince", "app.post.get_top_threads_for_user_since.app_error", nil, err.Error(), http.StatusInternalServerError) } return topThreadsWithEmbedAndImage, nil } -func includeEmbedsAndImages(a *App, topThreadList *model.TopThreadList, userID string) (*model.TopThreadList, error) { +func includeEmbedsAndImages(a *App, c request.CTX, topThreadList *model.TopThreadList, userID string) (*model.TopThreadList, error) { for _, topThread := range topThreadList.Items { - topThread.Post = a.PreparePostForClientWithEmbedsAndImages(topThread.Post, false, false) - sanitizedPost, err := a.SanitizePostMetadataForUser(topThread.Post, userID) + topThread.Post = a.PreparePostForClientWithEmbedsAndImages(c, topThread.Post, false, false) + sanitizedPost, err := a.SanitizePostMetadataForUser(c, topThread.Post, userID) if err != nil { return nil, err } diff --git a/app/post_metadata.go b/app/post_metadata.go index ee552e3998..f5ff89cb19 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -18,6 +18,7 @@ import ( "github.com/dyatlov/go-opengraph/opengraph" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/services/cache" "github.com/mattermost/mattermost-server/v6/shared/markdown" @@ -51,7 +52,7 @@ func (s *Server) initPostMetadata() { }) } -func (a *App) PreparePostListForClient(originalList *model.PostList) *model.PostList { +func (a *App) PreparePostListForClient(c request.CTX, originalList *model.PostList) *model.PostList { list := &model.PostList{ Posts: make(map[string]*model.Post, len(originalList.Posts)), Order: originalList.Order, @@ -62,7 +63,7 @@ func (a *App) PreparePostListForClient(originalList *model.PostList) *model.Post } for id, originalPost := range originalList.Posts { - post := a.PreparePostForClientWithEmbedsAndImages(originalPost, false, false) + post := a.PreparePostForClientWithEmbedsAndImages(c, originalPost, false, false) list.Posts[id] = post } @@ -132,13 +133,13 @@ func (a *App) PreparePostForClient(originalPost *model.Post, isNewPost, isEditPo return post } -func (a *App) PreparePostForClientWithEmbedsAndImages(originalPost *model.Post, isNewPost, isEditPost bool) *model.Post { +func (a *App) PreparePostForClientWithEmbedsAndImages(c request.CTX, originalPost *model.Post, isNewPost, isEditPost bool) *model.Post { post := a.PreparePostForClient(originalPost, isNewPost, isEditPost) - post = a.getEmbedsAndImages(post, isNewPost) + post = a.getEmbedsAndImages(c, post, isNewPost) return post } -func (a *App) getEmbedsAndImages(post *model.Post, isNewPost bool) *model.Post { +func (a *App) getEmbedsAndImages(c request.CTX, post *model.Post, isNewPost bool) *model.Post { if post.Metadata == nil { post.Metadata = &model.PostMetadata{} } @@ -150,7 +151,7 @@ func (a *App) getEmbedsAndImages(post *model.Post, isNewPost bool) *model.Post { post.Metadata.Embeds = []*model.PostEmbed{} } - if embed, err := a.getEmbedForPost(post, firstLink, isNewPost); err != nil { + if embed, err := a.getEmbedForPost(c, post, firstLink, isNewPost); err != nil { appErr, ok := err.(*model.AppError) isNotFound := ok && appErr.StatusCode == http.StatusNotFound // Ignore NotFound errors. @@ -160,23 +161,23 @@ func (a *App) getEmbedsAndImages(post *model.Post, isNewPost bool) *model.Post { } else if embed != nil { post.Metadata.Embeds = append(post.Metadata.Embeds, embed) } - post.Metadata.Images = a.getImagesForPost(post, images, isNewPost) + post.Metadata.Images = a.getImagesForPost(c, post, images, isNewPost) return post } -func (a *App) sanitizePostMetadataForUserAndChannel(post *model.Post, previewedPost *model.PreviewPost, previewedChannel *model.Channel, userID string) *model.Post { +func (a *App) sanitizePostMetadataForUserAndChannel(c request.CTX, post *model.Post, previewedPost *model.PreviewPost, previewedChannel *model.Channel, userID string) *model.Post { if post.Metadata == nil || len(post.Metadata.Embeds) == 0 || previewedPost == nil { return post } - if previewedChannel != nil && !a.HasPermissionToReadChannel(userID, previewedChannel) { + if previewedChannel != nil && !a.HasPermissionToReadChannel(c, userID, previewedChannel) { post.Metadata.Embeds[0].Data = nil } return post } -func (a *App) SanitizePostMetadataForUser(post *model.Post, userID string) (*model.Post, *model.AppError) { +func (a *App) SanitizePostMetadataForUser(c request.CTX, post *model.Post, userID string) (*model.Post, *model.AppError) { if post.Metadata == nil || len(post.Metadata.Embeds) == 0 { return post, nil } @@ -186,22 +187,22 @@ func (a *App) SanitizePostMetadataForUser(post *model.Post, userID string) (*mod return post, nil } - previewedChannel, err := a.GetChannel(previewPost.Post.ChannelId) + previewedChannel, err := a.GetChannel(c, previewPost.Post.ChannelId) if err != nil { return nil, err } - if previewedChannel != nil && !a.HasPermissionToReadChannel(userID, previewedChannel) { + if previewedChannel != nil && !a.HasPermissionToReadChannel(c, userID, previewedChannel) { post.Metadata.Embeds[0].Data = nil } return post, nil } -func (a *App) SanitizePostListMetadataForUser(postList *model.PostList, userID string) (*model.PostList, *model.AppError) { +func (a *App) SanitizePostListMetadataForUser(c request.CTX, postList *model.PostList, userID string) (*model.PostList, *model.AppError) { clonedPostList := postList.Clone() for postID, post := range clonedPostList.Posts { - sanitizedPost, err := a.SanitizePostMetadataForUser(post, userID) + sanitizedPost, err := a.SanitizePostMetadataForUser(c, post, userID) if err != nil { return nil, err } @@ -236,7 +237,7 @@ func (a *App) getEmojisAndReactionsForPost(post *model.Post) ([]*model.Emoji, [] return emojis, reactions, nil } -func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool) (*model.PostEmbed, error) { +func (a *App) getEmbedForPost(c request.CTX, post *model.Post, firstLink string, isNewPost bool) (*model.PostEmbed, error) { if _, ok := post.GetProps()["attachments"]; ok { return &model.PostEmbed{ Type: model.PostEmbedMessageAttachment, @@ -259,7 +260,7 @@ func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool return nil, nil } - og, image, permalink, err := a.getLinkMetadata(firstLink, post.CreateAt, isNewPost, post.GetPreviewedPostProp()) + og, image, permalink, err := a.getLinkMetadata(c, firstLink, post.CreateAt, isNewPost, post.GetPreviewedPostProp()) if err != nil { return nil, err } @@ -294,7 +295,7 @@ func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool }, nil } -func (a *App) getImagesForPost(post *model.Post, imageURLs []string, isNewPost bool) map[string]*model.PostImage { +func (a *App) getImagesForPost(c request.CTX, post *model.Post, imageURLs []string, isNewPost bool) map[string]*model.PostImage { images := map[string]*model.PostImage{} for _, embed := range post.Metadata.Embeds { @@ -336,7 +337,7 @@ func (a *App) getImagesForPost(post *model.Post, imageURLs []string, isNewPost b } for _, imageURL := range imageURLs { - if _, image, _, err := a.getLinkMetadata(imageURL, post.CreateAt, isNewPost, post.GetPreviewedPostProp()); err != nil { + if _, image, _, err := a.getLinkMetadata(c, imageURL, post.CreateAt, isNewPost, post.GetPreviewedPostProp()); err != nil { appErr, ok := err.(*model.AppError) isNotFound := ok && appErr.StatusCode == http.StatusNotFound // Ignore NotFound errors. @@ -513,7 +514,7 @@ func (a *App) containsPermalink(post *model.Post) bool { return looksLikeAPermalink(link, a.GetSiteURL()) } -func (a *App) getLinkMetadata(requestURL string, timestamp int64, isNewPost bool, previewedPostPropVal string) (*opengraph.OpenGraph, *model.PostImage, *model.Permalink, error) { +func (a *App) getLinkMetadata(c request.CTX, requestURL string, timestamp int64, isNewPost bool, previewedPostPropVal string) (*opengraph.OpenGraph, *model.PostImage, *model.Permalink, error) { requestURL = resolveMetadataURL(requestURL, a.GetSiteURL()) timestamp = model.FloorToNearestHour(timestamp) @@ -547,7 +548,7 @@ func (a *App) getLinkMetadata(requestURL string, timestamp int64, isNewPost bool return nil, nil, nil, appErr } - referencedChannel, appErr := a.GetChannel(referencedPost.ChannelId) + referencedChannel, appErr := a.GetChannel(c, referencedPost.ChannelId) if appErr != nil { return nil, nil, nil, appErr } @@ -568,7 +569,7 @@ func (a *App) getLinkMetadata(requestURL string, timestamp int64, isNewPost bool permalink = &model.Permalink{PreviewPost: model.NewPreviewPost(referencedPost, referencedTeam, referencedChannel)} } else { // referencedPost does not contain a permalink: we get its metadata - referencedPostWithMetadata := a.PreparePostForClientWithEmbedsAndImages(referencedPost, false, false) + referencedPostWithMetadata := a.PreparePostForClientWithEmbedsAndImages(c, referencedPost, false, false) permalink = &model.Permalink{PreviewPost: model.NewPreviewPost(referencedPostWithMetadata, referencedTeam, referencedChannel)} } } else { diff --git a/app/post_metadata_test.go b/app/post_metadata_test.go index 9f3566a5e5..5101fa4208 100644 --- a/app/post_metadata_test.go +++ b/app/post_metadata_test.go @@ -39,7 +39,7 @@ func TestPreparePostListForClient(t *testing.T) { postList.AddPost(&model.Post{}) } - clientPostList := th.App.PreparePostListForClient(postList) + clientPostList := th.App.PreparePostListForClient(th.Context, postList) t.Run("doesn't mutate provided post list", func(t *testing.T) { assert.NotEqual(t, clientPostList, postList, "should've returned a new post list") @@ -422,7 +422,7 @@ func TestPreparePostForClient(t *testing.T) { }, th.BasicChannel, false, true) require.Nil(t, err) post.Metadata.Embeds = nil - clientPost := th.App.PreparePostForClientWithEmbedsAndImages(post, false, false) + clientPost := th.App.PreparePostForClientWithEmbedsAndImages(th.Context, post, false, false) // Reminder that only the first link gets an embed and dimensions @@ -500,7 +500,7 @@ func TestPreparePostForClient(t *testing.T) { }, th.BasicChannel, false, true) require.Nil(t, err) post.Metadata.Embeds = nil - clientPost := th.App.PreparePostForClientWithEmbedsAndImages(post, false, false) + clientPost := th.App.PreparePostForClientWithEmbedsAndImages(th.Context, post, false, false) t.Run("populates embeds", func(t *testing.T) { assert.ElementsMatch(t, []*model.PostEmbed{ @@ -539,7 +539,7 @@ func TestPreparePostForClient(t *testing.T) { th.AddReactionToPost(post, th.BasicUser, "taco") - post, err = th.App.DeletePost(post.Id, th.BasicUser.Id) + post, err = th.App.DeletePost(th.Context, post.Id, th.BasicUser.Id) require.Nil(t, err) // DeleteAt isn't set on the post returned by App.DeletePost @@ -580,7 +580,7 @@ func TestPreparePostForClient(t *testing.T) { }, th.BasicChannel, false, true) require.Nil(t, err) previewPost.Metadata.Embeds = nil - clientPost := th.App.PreparePostForClientWithEmbedsAndImages(previewPost, false, false) + clientPost := th.App.PreparePostForClientWithEmbedsAndImages(th.Context, previewPost, false, false) firstEmbed := clientPost.Metadata.Embeds[0] preview := firstEmbed.Data.(*model.PreviewPost) require.Equal(t, referencedPost.Id, preview.PostID) @@ -596,10 +596,10 @@ func TestPreparePostForClient(t *testing.T) { th.Context.Session().UserId = th.BasicUser.Id - directChannel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + directChannel, err := th.App.createDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) require.Nil(t, err) - groupChannel, err := th.App.createGroupChannel([]string{th.BasicUser.Id, th.BasicUser2.Id, th.CreateUser().Id}) + groupChannel, err := th.App.createGroupChannel(th.Context, []string{th.BasicUser.Id, th.BasicUser2.Id, th.CreateUser().Id}) require.Nil(t, err) testCases := []struct { @@ -639,7 +639,7 @@ func TestPreparePostForClient(t *testing.T) { require.Nil(t, err) previewPost.Metadata.Embeds = nil - clientPost := th.App.PreparePostForClientWithEmbedsAndImages(previewPost, false, false) + clientPost := th.App.PreparePostForClientWithEmbedsAndImages(th.Context, previewPost, false, false) firstEmbed := clientPost.Metadata.Embeds[0] preview := firstEmbed.Data.(*model.PreviewPost) @@ -677,7 +677,7 @@ func TestPreparePostForClient(t *testing.T) { require.Nil(t, err) previewPost.Metadata.Embeds = nil - clientPost := th.App.PreparePostForClientWithEmbedsAndImages(previewPost, false, false) + clientPost := th.App.PreparePostForClientWithEmbedsAndImages(th.Context, previewPost, false, false) firstEmbed := clientPost.Metadata.Embeds[0] preview := firstEmbed.Data.(*model.PreviewPost) referencedPostFirstEmbed := preview.Post.Metadata.Embeds[0] @@ -724,7 +724,7 @@ func TestPreparePostForClient(t *testing.T) { require.Nil(t, err) previewPost.Metadata.Embeds = nil - clientPost := th.App.PreparePostForClientWithEmbedsAndImages(previewPost, false, false) + clientPost := th.App.PreparePostForClientWithEmbedsAndImages(th.Context, previewPost, false, false) firstEmbed := clientPost.Metadata.Embeds[0] preview := firstEmbed.Data.(*model.PreviewPost) referencedPostMetadata := preview.Post.Metadata @@ -874,7 +874,7 @@ func testProxyOpenGraphImage(t *testing.T, th *TestHelper, shouldProxy bool) { require.Nil(t, err) post.Metadata.Embeds = nil - embeds := th.App.PreparePostForClientWithEmbedsAndImages(post, false, false).Metadata.Embeds + embeds := th.App.PreparePostForClientWithEmbedsAndImages(th.Context, post, false, false).Metadata.Embeds require.Len(t, embeds, 1, "should have one embed") embed := embeds[0] @@ -953,7 +953,7 @@ func TestGetEmbedForPost(t *testing.T) { }) t.Run("should return a message attachment when the post has one", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{ + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{ Props: model.StringInterface{ "attachments": []*model.SlackAttachment{ { @@ -970,7 +970,7 @@ func TestGetEmbedForPost(t *testing.T) { }) t.Run("should return an image embed when the first link is an image", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{}, imageURL, false) + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{}, imageURL, false) assert.Equal(t, &model.PostEmbed{ Type: model.PostEmbedImage, @@ -980,7 +980,7 @@ func TestGetEmbedForPost(t *testing.T) { }) t.Run("should return an opengraph embed", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{}, ogURL, false) + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{}, ogURL, false) assert.Equal(t, &model.PostEmbed{ Type: model.PostEmbedOpengraph, @@ -997,7 +997,7 @@ func TestGetEmbedForPost(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LocalizationSettings.DefaultServerLocale = "fr" }) - embed, err := th.App.getEmbedForPost(&model.Post{}, ogURL, false) + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{}, ogURL, false) assert.Equal(t, &model.PostEmbed{ Type: model.PostEmbedOpengraph, @@ -1011,7 +1011,7 @@ func TestGetEmbedForPost(t *testing.T) { }) t.Run("should return a link embed", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{}, otherURL, false) + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{}, otherURL, false) assert.Equal(t, &model.PostEmbed{ Type: model.PostEmbedLink, @@ -1031,7 +1031,7 @@ func TestGetEmbedForPost(t *testing.T) { }) t.Run("should return an embedded message attachment", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{ + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{ Props: model.StringInterface{ "attachments": []*model.SlackAttachment{ { @@ -1048,21 +1048,21 @@ func TestGetEmbedForPost(t *testing.T) { }) t.Run("should not return an opengraph embed", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{}, ogURL, false) + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{}, ogURL, false) assert.Nil(t, embed) assert.NoError(t, err) }) t.Run("should not return an image embed", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{}, imageURL, false) + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{}, imageURL, false) assert.Nil(t, embed) assert.NoError(t, err) }) t.Run("should not return a link embed", func(t *testing.T) { - embed, err := th.App.getEmbedForPost(&model.Post{}, otherURL, false) + embed, err := th.App.getEmbedForPost(th.Context, &model.Post{}, otherURL, false) assert.Nil(t, embed) assert.NoError(t, err) @@ -1092,7 +1092,7 @@ func TestGetImagesForPost(t *testing.T) { } imageURL := server.URL + "/image.png" - images := th.App.getImagesForPost(post, []string{imageURL}, false) + images := th.App.getImagesForPost(th.Context, post, []string{imageURL}, false) assert.Equal(t, images, map[string]*model.PostImage{ imageURL: { @@ -1120,7 +1120,7 @@ func TestGetImagesForPost(t *testing.T) { } imageURL := server.URL + "/bad_image.png" - images := th.App.getImagesForPost(post, []string{imageURL}, false) + images := th.App.getImagesForPost(th.Context, post, []string{imageURL}, false) assert.Equal(t, images, map[string]*model.PostImage{}) }) @@ -1168,7 +1168,7 @@ func TestGetImagesForPost(t *testing.T) { }, } - images := th.App.getImagesForPost(post, []string{}, false) + images := th.App.getImagesForPost(th.Context, post, []string{}, false) assert.Equal(t, images, map[string]*model.PostImage{ imageURL: { @@ -1222,7 +1222,7 @@ func TestGetImagesForPost(t *testing.T) { }, } - images := th.App.getImagesForPost(post, []string{}, false) + images := th.App.getImagesForPost(th.Context, post, []string{}, false) assert.Equal(t, images, map[string]*model.PostImage{ imageURL: { @@ -1276,7 +1276,7 @@ func TestGetImagesForPost(t *testing.T) { }, } - images := th.App.getImagesForPost(post, []string{}, false) + images := th.App.getImagesForPost(th.Context, post, []string{}, false) assert.Equal(t, images, map[string]*model.PostImage{ imageURL: { @@ -1306,7 +1306,7 @@ func TestGetImagesForPost(t *testing.T) { }, } - images := th.App.getImagesForPost(post, []string{}, false) + images := th.App.getImagesForPost(th.Context, post, []string{}, false) assert.Equal(t, images, map[string]*model.PostImage{}) }) } @@ -1980,7 +1980,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") require.NotNil(t, og) assert.Nil(t, img) @@ -1995,7 +1995,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp+60*1000, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp+60*1000, false, "") require.NotNil(t, og) assert.Nil(t, img) @@ -2012,7 +2012,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(differentURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(differentURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, differentURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) @@ -2028,7 +2028,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, differentTimestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, differentTimestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, differentTimestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) @@ -2055,7 +2055,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.True(t, ok, "data should already exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") require.NotNil(t, og) assert.Nil(t, img) @@ -2072,7 +2072,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.True(t, ok, "data should already exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp+60*1000, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp+60*1000, false, "") require.NotNil(t, og) assert.Nil(t, img) @@ -2091,7 +2091,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(differentURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(differentURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, differentURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) @@ -2109,7 +2109,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, differentTimestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, differentTimestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, differentTimestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) @@ -2130,7 +2130,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.NotNil(t, og) assert.Nil(t, img) @@ -2150,7 +2150,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.NotNil(t, og) assert.Nil(t, img) @@ -2178,7 +2178,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.NotNil(t, img) @@ -2206,7 +2206,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) @@ -2236,7 +2236,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) @@ -2270,7 +2270,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) @@ -2301,7 +2301,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, ok = th.App.getLinkMetadataFromDatabase(requestURL, timestamp) require.False(t, ok, "data should not exist in database") - _, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + _, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") require.NoError(t, err) _, _, _, ok = getLinkMetadataFromCache(requestURL, timestamp) @@ -2323,7 +2323,7 @@ func TestGetLinkMetadata(t *testing.T) { requestURL := server.URL + "/json?name=" + t.Name() timestamp := int64(1547510400000) - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) assert.NoError(t, err) @@ -2338,7 +2338,7 @@ func TestGetLinkMetadata(t *testing.T) { cacheLinkMetadata(requestURL, timestamp, &opengraph.OpenGraph{Title: "cached"}, nil, nil) - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, true, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, true, "") assert.NotNil(t, og) assert.Nil(t, img) assert.NoError(t, err) @@ -2353,7 +2353,7 @@ func TestGetLinkMetadata(t *testing.T) { th.App.saveLinkMetadataToDatabase(requestURL, timestamp, &opengraph.OpenGraph{Title: "cached"}, nil) - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, true, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, true, "") assert.Nil(t, og) assert.Nil(t, img) assert.NoError(t, err) @@ -2376,7 +2376,7 @@ func TestGetLinkMetadata(t *testing.T) { requestURL := "/image?height=200&width=300&name=" + t.Name() timestamp := int64(1547510400000) - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.NotNil(t, img) assert.NoError(t, err) @@ -2404,7 +2404,7 @@ func TestGetLinkMetadata(t *testing.T) { requestURL := server.URL + "/image?height=200&width=300&name=" + t.Name() timestamp := int64(1547510400000) - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) assert.Error(t, err) @@ -2414,7 +2414,7 @@ func TestGetLinkMetadata(t *testing.T) { requestURL = th.App.GetSiteURL() + "/api/v4/image?url=" + url.QueryEscape(requestURL) // Note that this request still fails while testing because the request made by the image proxy is blocked - og, img, _, err = th.App.getLinkMetadata(requestURL, timestamp, false, "") + og, img, _, err = th.App.getLinkMetadata(th.Context, requestURL, timestamp, false, "") assert.Nil(t, og) assert.Nil(t, img) assert.Error(t, err) @@ -2428,7 +2428,7 @@ func TestGetLinkMetadata(t *testing.T) { requestURL := server.URL + "/mixed?name=" + t.Name() timestamp := int64(1547510400000) - og, img, _, err := th.App.getLinkMetadata(requestURL, timestamp, true, "") + og, img, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, true, "") assert.Nil(t, og) assert.NotNil(t, img) assert.NoError(t, err) @@ -2447,7 +2447,7 @@ func TestGetLinkMetadata(t *testing.T) { requestURL := server.URL + "/pl/5rpoy4o3nbgwjm7gs4cm71h6ho" timestamp := int64(1547510400000) - _, _, _, err := th.App.getLinkMetadata(requestURL, timestamp, true, "") + _, _, _, err := th.App.getLinkMetadata(th.Context, requestURL, timestamp, true, "") assert.Error(t, err) }) } @@ -2699,7 +2699,7 @@ func TestSanitizePostMetadataForUserAndChannel(t *testing.T) { *cfg.ServiceSettings.SiteURL = "http://mymattermost.com" }) - directChannel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + directChannel, err := th.App.createDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) assert.Nil(t, err) userID := model.NewId() @@ -2724,7 +2724,7 @@ func TestSanitizePostMetadataForUserAndChannel(t *testing.T) { previewedPost := model.NewPreviewPost(post, th.BasicTeam, directChannel) - actual := th.App.sanitizePostMetadataForUserAndChannel(post, previewedPost, directChannel, th.BasicUser2.Id) + actual := th.App.sanitizePostMetadataForUserAndChannel(th.Context, post, previewedPost, directChannel, th.BasicUser2.Id) assert.NotNil(t, actual.Metadata.Embeds[0].Data) guestID := model.NewId() @@ -2738,6 +2738,6 @@ func TestSanitizePostMetadataForUserAndChannel(t *testing.T) { guest, appErr := th.App.CreateGuest(th.Context, guest) require.Nil(t, appErr) - actual = th.App.sanitizePostMetadataForUserAndChannel(post, previewedPost, directChannel, guest.Id) + actual = th.App.sanitizePostMetadataForUserAndChannel(th.Context, post, previewedPost, directChannel, guest.Id) assert.Nil(t, actual.Metadata.Embeds[0].Data) } diff --git a/app/post_test.go b/app/post_test.go index ff05ad9f68..bc38d528aa 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -319,7 +319,7 @@ func TestUpdatePostInArchivedChannel(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - archivedChannel := th.CreateChannel(th.BasicTeam) + archivedChannel := th.CreateChannel(th.Context, th.BasicTeam) post := th.CreatePost(archivedChannel) th.App.DeleteChannel(th.Context, archivedChannel, "") @@ -339,7 +339,7 @@ func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) { userNotInChannel := th.BasicUser rootPost := th.BasicPost - _, err := th.App.AddUserToChannel(userInChannel, channel, false) + _, err := th.App.AddUserToChannel(th.Context, userInChannel, channel, false) require.Nil(t, err) err = th.App.RemoveUserFromChannel(th.Context, userNotInChannel.Id, "", channel) @@ -416,9 +416,9 @@ func TestPostChannelMentions(t *testing.T) { TeamId: th.BasicTeam.Id, }, false) require.Nil(t, err) - defer th.App.PermanentDeleteChannel(channelToMention) + defer th.App.PermanentDeleteChannel(th.Context, channelToMention) - _, err = th.App.AddUserToChannel(user, channel, false) + _, err = th.App.AddUserToChannel(th.Context, user, channel, false) require.Nil(t, err) post := &model.Post{ @@ -649,7 +649,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) { assert.Nil(t, err) // Delete the post. - _, err = th.App.DeletePost(post.Id, userID) + _, err = th.App.DeletePost(th.Context, post.Id, userID) assert.Nil(t, err) // Wait for the cleanup routine to finish. @@ -664,11 +664,11 @@ func TestDeletePostInArchivedChannel(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - archivedChannel := th.CreateChannel(th.BasicTeam) + archivedChannel := th.CreateChannel(th.Context, th.BasicTeam) post := th.CreatePost(archivedChannel) th.App.DeleteChannel(th.Context, archivedChannel, "") - _, err := th.App.DeletePost(post.Id, "") + _, err := th.App.DeletePost(th.Context, post.Id, "") require.NotNil(t, err) require.Equal(t, "api.post.delete_post.can_not_delete_post_in_deleted.error", err.Id) } @@ -776,7 +776,7 @@ func TestCreatePost(t *testing.T) { permalink := fmt.Sprintf("%s/%s/pl/%s", *th.App.Config().ServiceSettings.SiteURL, th.BasicTeam.Name, referencedPost.Id) - channelForPreview := th.CreateChannel(th.BasicTeam) + channelForPreview := th.CreateChannel(th.Context, th.BasicTeam) previewPost := &model.Post{ ChannelId: channelForPreview.Id, Message: permalink, @@ -793,7 +793,7 @@ func TestCreatePost(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channelForPreview := th.CreateChannel(th.BasicTeam) + channelForPreview := th.CreateChannel(th.Context, th.BasicTeam) referencedPost := &model.Post{ ChannelId: th.BasicChannel.Id, @@ -840,7 +840,7 @@ func TestCreatePost(t *testing.T) { user1 := th.CreateUser() user2 := th.CreateUser() - directChannel, err := th.App.createDirectChannel(user1.Id, user2.Id) + directChannel, err := th.App.createDirectChannel(th.Context, user1.Id, user2.Id) require.Nil(t, err) referencedPost := &model.Post{ @@ -896,7 +896,7 @@ func TestCreatePost(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - channelForPreview := th.CreateChannel(th.BasicTeam) + channelForPreview := th.CreateChannel(th.Context, th.BasicTeam) for i := 0; i < 20; i++ { user := th.CreateUser() @@ -1230,7 +1230,7 @@ func TestPatchPostInArchivedChannel(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - archivedChannel := th.CreateChannel(th.BasicTeam) + archivedChannel := th.CreateChannel(th.Context, th.BasicTeam) post := th.CreatePost(archivedChannel) th.App.DeleteChannel(th.Context, archivedChannel, "") @@ -1297,7 +1297,7 @@ func TestUpdatePost(t *testing.T) { permalink := fmt.Sprintf("%s/%s/pl/%s", *th.App.Config().ServiceSettings.SiteURL, th.BasicTeam.Name, referencedPost.Id) - channelForTestPost := th.CreateChannel(th.BasicTeam) + channelForTestPost := th.CreateChannel(th.Context, th.BasicTeam) testPost := &model.Post{ ChannelId: channelForTestPost.Id, Message: "hello world", @@ -1327,7 +1327,7 @@ func TestUpdatePost(t *testing.T) { user1 := th.CreateUser() user2 := th.CreateUser() - directChannel, err := th.App.createDirectChannel(user1.Id, user2.Id) + directChannel, err := th.App.createDirectChannel(th.Context, user1.Id, user2.Id) require.Nil(t, err) referencedPost := &model.Post{ @@ -1573,7 +1573,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) post1, err := th.App.CreatePost(th.Context, &model.Post{ @@ -1595,7 +1595,7 @@ func TestCountMentionsFromPost(t *testing.T) { }, channel, false, true) require.Nil(t, err) - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 0, count) @@ -1608,7 +1608,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) user2.NotifyProps[model.MentionKeysNotifyProp] = "apple" @@ -1634,7 +1634,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post1 and post3 should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 2, count) @@ -1647,7 +1647,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) user2.NotifyProps[model.ChannelMentionsNotifyProp] = "true" @@ -1673,7 +1673,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post2 and post3 should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 2, count) @@ -1686,7 +1686,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) user2.NotifyProps[model.ChannelMentionsNotifyProp] = "false" @@ -1710,7 +1710,7 @@ func TestCountMentionsFromPost(t *testing.T) { }, channel, false, true) require.Nil(t, err) - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 0, count) @@ -1723,12 +1723,12 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) user2.NotifyProps[model.ChannelMentionsNotifyProp] = "true" - _, err := th.App.UpdateChannelMemberNotifyProps(map[string]string{ + _, err := th.App.UpdateChannelMemberNotifyProps(th.Context, map[string]string{ model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsOn, }, channel.Id, user2.Id) require.Nil(t, err) @@ -1752,7 +1752,7 @@ func TestCountMentionsFromPost(t *testing.T) { }, channel, false, true) require.Nil(t, err) - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 0, count) @@ -1765,7 +1765,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyRoot @@ -1806,7 +1806,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post2 should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 1, count) @@ -1819,7 +1819,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny @@ -1860,7 +1860,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post2 and post5 should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 2, count) @@ -1873,7 +1873,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) post1, err := th.App.CreatePost(th.Context, &model.Post{ @@ -1909,7 +1909,7 @@ func TestCountMentionsFromPost(t *testing.T) { // should be mentioned by post2 and post3 - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 2, count) @@ -1922,7 +1922,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel, err := th.App.createDirectChannel(user1.Id, user2.Id) + channel, err := th.App.createDirectChannel(th.Context, user1.Id, user2.Id) require.Nil(t, err) post1, err := th.App.CreatePost(th.Context, &model.Post{ @@ -1939,12 +1939,12 @@ func TestCountMentionsFromPost(t *testing.T) { }, channel, false, true) require.Nil(t, err) - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 2, count) - count, _, err = th.App.countMentionsFromPost(user1, post1) + count, _, err = th.App.countMentionsFromPost(th.Context, user1, post1) assert.Nil(t, err) assert.Equal(t, 0, count) @@ -1957,7 +1957,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) _, err := th.App.CreatePost(th.Context, &model.Post{ @@ -1981,7 +1981,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post1 and post3 should mention the user, but we only count post3 - count, _, err := th.App.countMentionsFromPost(user2, post2) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post2) assert.Nil(t, err) assert.Equal(t, 1, count) @@ -1994,7 +1994,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) post1, err := th.App.CreatePost(th.Context, &model.Post{ @@ -2012,7 +2012,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post2 should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 1, count) @@ -2025,7 +2025,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny @@ -2059,7 +2059,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post4 should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post3) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post3) assert.Nil(t, err) assert.Equal(t, 1, count) @@ -2072,7 +2072,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) post1, err := th.App.CreatePost(th.Context, &model.Post{ @@ -2099,7 +2099,7 @@ func TestCountMentionsFromPost(t *testing.T) { // post3 should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, 1, count) @@ -2112,7 +2112,7 @@ func TestCountMentionsFromPost(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) numPosts := 215 @@ -2135,7 +2135,7 @@ func TestCountMentionsFromPost(t *testing.T) { // Every post should mention the user - count, _, err := th.App.countMentionsFromPost(user2, post1) + count, _, err := th.App.countMentionsFromPost(th.Context, user2, post1) assert.Nil(t, err) assert.Equal(t, numPosts, count) @@ -2150,7 +2150,7 @@ func TestFillInPostProps(t *testing.T) { user1 := th.BasicUser - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) post1, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user1.Id, @@ -2159,7 +2159,7 @@ func TestFillInPostProps(t *testing.T) { }, channel, false, true) require.Nil(t, err) - err = th.App.FillInPostProps(post1, channel) + err = th.App.FillInPostProps(th.Context, post1, channel) assert.Nil(t, err) assert.Equal(t, post1.Props, model.StringInterface{}) @@ -2181,7 +2181,7 @@ func TestFillInPostProps(t *testing.T) { require.Nil(t, err) th.LinkUserToTeam(guest, th.BasicTeam) - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(guest, channel) post1, err := th.App.CreatePost(th.Context, &model.Post{ @@ -2191,7 +2191,7 @@ func TestFillInPostProps(t *testing.T) { }, channel, false, true) require.Nil(t, err) - err = th.App.FillInPostProps(post1, channel) + err = th.App.FillInPostProps(th.Context, post1, channel) assert.Nil(t, err) assert.Equal(t, post1.Props, model.StringInterface{}) @@ -2214,7 +2214,7 @@ func TestFillInPostProps(t *testing.T) { require.Nil(t, err) th.LinkUserToTeam(guest, th.BasicTeam) - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(guest, channel) post1, err := th.App.CreatePost(th.Context, &model.Post{ @@ -2224,7 +2224,7 @@ func TestFillInPostProps(t *testing.T) { }, channel, false, true) require.Nil(t, err) - err = th.App.FillInPostProps(post1, channel) + err = th.App.FillInPostProps(th.Context, post1, channel) assert.Nil(t, err) assert.Equal(t, post1.Props, model.StringInterface{"disable_group_highlight": true}) @@ -2243,7 +2243,7 @@ func TestThreadMembership(t *testing.T) { user1 := th.BasicUser user2 := th.BasicUser2 - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) postRoot, err := th.App.CreatePost(th.Context, &model.Post{ @@ -2405,7 +2405,7 @@ func TestViewChannelShouldNotUpdateThreads(t *testing.T) { m, e := th.App.GetThreadMembershipsForUser(user2.Id, th.BasicTeam.Id) require.NoError(t, e) - th.App.ViewChannel(&model.ChannelView{ + th.App.ViewChannel(th.Context, &model.ChannelView{ ChannelId: channel.Id, PrevChannelId: "", }, user2.Id, "", true) @@ -2427,7 +2427,7 @@ func TestCollapsedThreadFetch(t *testing.T) { user2 := th.BasicUser2 t.Run("should only return root posts, enriched", func(t *testing.T) { - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) defer th.App.DeleteChannel(th.Context, channel, user1.Id) @@ -2448,8 +2448,8 @@ func TestCollapsedThreadFetch(t *testing.T) { thread, nErr := th.App.Srv().Store.Thread().Get(postRoot.Id) require.NoError(t, nErr) require.Len(t, thread.Participants, 1) - th.App.MarkChannelAsUnreadFromPost(postRoot.Id, user1.Id, true) - l, err := th.App.GetPostsForChannelAroundLastUnread(channel.Id, user1.Id, 10, 10, true, true, false) + th.App.MarkChannelAsUnreadFromPost(th.Context, postRoot.Id, user1.Id, true) + l, err := th.App.GetPostsForChannelAroundLastUnread(th.Context, channel.Id, user1.Id, 10, 10, true, true, false) require.Nil(t, err) require.Len(t, l.Order, 1) require.EqualValues(t, 1, l.Posts[postRoot.Id].ReplyCount) @@ -2459,7 +2459,7 @@ func TestCollapsedThreadFetch(t *testing.T) { require.True(t, *l.Posts[postRoot.Id].IsFollowing) // try extended fetch - l, err = th.App.GetPostsForChannelAroundLastUnread(channel.Id, user1.Id, 10, 10, true, true, true) + l, err = th.App.GetPostsForChannelAroundLastUnread(th.Context, channel.Id, user1.Id, 10, 10, true, true, true) require.Nil(t, err) require.Len(t, l.Order, 1) require.NotEmpty(t, l.Posts[postRoot.Id].Participants[0].Email) @@ -2472,7 +2472,7 @@ func TestCollapsedThreadFetch(t *testing.T) { cfg.FeatureFlags.CollapsedThreads = true }) - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(user2, channel) defer th.App.DeleteChannel(th.Context, channel, user1.Id) @@ -2515,7 +2515,7 @@ func TestCollapsedThreadFetch(t *testing.T) { }) require.Nil(t, err) - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) th.LinkUserToTeam(user3, th.BasicTeam) th.AddUserToChannel(user3, channel) defer th.App.DeleteChannel(th.Context, channel, user1.Id) @@ -2553,10 +2553,10 @@ func TestCollapsedThreadFetch(t *testing.T) { require.NotEmpty(t, l.Posts[postRoot.Id].Participants[0].Email) require.Empty(t, l.Posts[postRoot.Id].Participants[0].AuthData) - th.App.MarkChannelAsUnreadFromPost(postRoot.Id, user1.Id, true) + th.App.MarkChannelAsUnreadFromPost(th.Context, postRoot.Id, user1.Id, true) // extended fetch posts around - l, err = th.App.GetPostsForChannelAroundLastUnread(channel.Id, user1.Id, 10, 10, true, true, true) + l, err = th.App.GetPostsForChannelAroundLastUnread(th.Context, channel.Id, user1.Id, 10, 10, true, true, true) require.Nil(t, err) require.Len(t, l.Order, 1) require.NotEmpty(t, l.Posts[postRoot.Id].Participants[0].Email) @@ -2628,7 +2628,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { user := th.BasicUser - channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) _, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, @@ -2652,7 +2652,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { user := th.BasicUser - channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, @@ -2680,7 +2680,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { user := th.BasicUser - channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, @@ -2689,7 +2689,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { }, channel, false, true) require.Nil(t, err, "Creating a post should not error") - _, err = th.App.DeletePost(post.Id, user.Id) + _, err = th.App.DeletePost(th.Context, post.Id, user.Id) require.Nil(t, err, "Deleting a post should not error") // one creation and two deletes @@ -2747,7 +2747,7 @@ func TestGetPostIfAuthorized(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - privateChannel := th.CreatePrivateChannel(th.BasicTeam) + privateChannel := th.CreatePrivateChannel(th.Context, th.BasicTeam) post, err := th.App.CreatePost(th.Context, &model.Post{UserId: th.BasicUser.Id, ChannelId: privateChannel.Id, Message: "Hello"}, privateChannel, false, false) require.Nil(t, err) require.NotNil(t, post) @@ -2761,11 +2761,11 @@ func TestGetPostIfAuthorized(t *testing.T) { require.NotNil(t, session2) // User is not authorized to get post - _, err = th.App.GetPostIfAuthorized(post.Id, session2, false) + _, err = th.App.GetPostIfAuthorized(th.Context, post.Id, session2, false) require.NotNil(t, err) // User is authorized to get post - _, err = th.App.GetPostIfAuthorized(post.Id, session1, false) + _, err = th.App.GetPostIfAuthorized(th.Context, post.Id, session1, false) require.Nil(t, err) } @@ -2887,8 +2887,8 @@ func TestGetTopThreadsForTeamSince(t *testing.T) { defer th.TearDown() // create a public channel, a private channel - channelPublic := th.CreateChannel(th.BasicTeam) - channelPrivate := th.CreatePrivateChannel(th.BasicTeam) + channelPublic := th.CreateChannel(th.Context, th.BasicTeam) + channelPrivate := th.CreatePrivateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channelPublic) th.AddUserToChannel(th.BasicUser, channelPrivate) th.AddUserToChannel(th.BasicUser2, channelPublic) @@ -2937,20 +2937,20 @@ func TestGetTopThreadsForTeamSince(t *testing.T) { // get top threads for team, as user 1 and user 2 // user 1 should see both threads, while user 2 should see only thread in public channel. - topTeamThreadsByUser1, appErr := th.App.GetTopThreadsForTeamSince(th.BasicTeam.Id, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topTeamThreadsByUser1, appErr := th.App.GetTopThreadsForTeamSince(th.Context, th.BasicTeam.Id, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topTeamThreadsByUser1.Items, 2) require.Equal(t, topTeamThreadsByUser1.Items[0].Post.Id, rootPostPrivateChannel.Id) require.Equal(t, topTeamThreadsByUser1.Items[1].Post.Id, rootPostPublicChannel.Id) - topTeamThreadsByUser2, appErr := th.App.GetTopThreadsForTeamSince(th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topTeamThreadsByUser2, appErr := th.App.GetTopThreadsForTeamSince(th.Context, th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topTeamThreadsByUser2.Items, 1) require.Equal(t, topTeamThreadsByUser2.Items[0].Post.Id, rootPostPublicChannel.Id) // add user2 to private channel and it can see 2 top threads. th.AddUserToChannel(th.BasicUser2, channelPrivate) - topTeamThreadsByUser2IncludingPrivate, appErr := th.App.GetTopThreadsForTeamSince(th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topTeamThreadsByUser2IncludingPrivate, appErr := th.App.GetTopThreadsForTeamSince(th.Context, th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topTeamThreadsByUser2IncludingPrivate.Items, 2) } @@ -2959,8 +2959,8 @@ func TestGetTopThreadsForUserSince(t *testing.T) { defer th.TearDown() // create a public channel, a private channel - channelPublic := th.CreateChannel(th.BasicTeam) - channelPrivate := th.CreatePrivateChannel(th.BasicTeam) + channelPublic := th.CreateChannel(th.Context, th.BasicTeam) + channelPrivate := th.CreatePrivateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.BasicUser, channelPublic) th.AddUserToChannel(th.BasicUser, channelPrivate) th.AddUserToChannel(th.BasicUser2, channelPublic) @@ -3012,7 +3012,7 @@ func TestGetTopThreadsForUserSince(t *testing.T) { // user 1 should see both threads, while user 2 should see only thread in public channel // (even if user2 is in the private channel it hasn't interacted with the thread there.) - topUser1Threads, appErr := th.App.GetTopThreadsForUserSince(th.BasicTeam.Id, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topUser1Threads, appErr := th.App.GetTopThreadsForUserSince(th.Context, th.BasicTeam.Id, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topUser1Threads.Items, 2) require.Equal(t, topUser1Threads.Items[0].Post.Id, rootPostPrivateChannel.Id) @@ -3021,17 +3021,17 @@ func TestGetTopThreadsForUserSince(t *testing.T) { require.Contains(t, topUser1Threads.Items[1].Participants, th.BasicUser2.Id) require.Equal(t, topUser1Threads.Items[1].ReplyCount, int64(1)) - topUser2Threads, appErr := th.App.GetTopThreadsForUserSince(th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topUser2Threads, appErr := th.App.GetTopThreadsForUserSince(th.Context, th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topUser2Threads.Items, 1) require.Equal(t, topUser2Threads.Items[0].Post.Id, rootPostPublicChannel.Id) require.Equal(t, topUser2Threads.Items[0].ReplyCount, int64(1)) // deleting the root post results in the thread not making it to top threads list - _, appErr = th.App.DeletePost(rootPostPublicChannel.Id, th.BasicUser.Id) + _, appErr = th.App.DeletePost(th.Context, rootPostPublicChannel.Id, th.BasicUser.Id) require.Nil(t, appErr) - topUser1ThreadsAfterPost1Delete, appErr := th.App.GetTopThreadsForUserSince(th.BasicTeam.Id, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topUser1ThreadsAfterPost1Delete, appErr := th.App.GetTopThreadsForUserSince(th.Context, th.BasicTeam.Id, th.BasicUser.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topUser1ThreadsAfterPost1Delete.Items, 1) @@ -3044,12 +3044,12 @@ func TestGetTopThreadsForUserSince(t *testing.T) { }, channelPrivate, false, true) require.Nil(t, appErr) - topUser2ThreadsAfterPrivateReply, appErr := th.App.GetTopThreadsForUserSince(th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topUser2ThreadsAfterPrivateReply, appErr := th.App.GetTopThreadsForUserSince(th.Context, th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topUser2ThreadsAfterPrivateReply.Items, 1) // deleting reply, and unfollowing thread - _, appErr = th.App.DeletePost(replyPostUser2InPrivate.Id, th.BasicUser2.Id) + _, appErr = th.App.DeletePost(th.Context, replyPostUser2InPrivate.Id, th.BasicUser2.Id) require.Nil(t, appErr) // unfollow thread _, err := th.App.Srv().Store.Thread().MaintainMembership(th.BasicUser2.Id, rootPostPrivateChannel.Id, store.ThreadMembershipOpts{ @@ -3058,7 +3058,7 @@ func TestGetTopThreadsForUserSince(t *testing.T) { }) require.NoError(t, err) - topUser2ThreadsAfterPrivateReplyDelete, appErr := th.App.GetTopThreadsForUserSince(th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) + topUser2ThreadsAfterPrivateReplyDelete, appErr := th.App.GetTopThreadsForUserSince(th.Context, th.BasicTeam.Id, th.BasicUser2.Id, &model.InsightsOpts{StartUnixMilli: 200, PerPage: 100}) require.Nil(t, appErr) require.Len(t, topUser2ThreadsAfterPrivateReplyDelete.Items, 0) } diff --git a/app/reaction.go b/app/reaction.go index 5f4c7557cd..26aa7d8414 100644 --- a/app/reaction.go +++ b/app/reaction.go @@ -20,7 +20,7 @@ func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) return nil, err } - channel, err := a.GetChannel(post.ChannelId) + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return nil, err } @@ -126,7 +126,7 @@ func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction return err } - channel, err := a.GetChannel(post.ChannelId) + channel, err := a.GetChannel(c, post.ChannelId) if err != nil { return err } diff --git a/app/reaction_test.go b/app/reaction_test.go index 3a3908731f..e0d536d775 100644 --- a/app/reaction_test.go +++ b/app/reaction_test.go @@ -25,7 +25,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { user := th.BasicUser - channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, @@ -60,7 +60,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { user := th.BasicUser - channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) post, err := th.App.CreatePost(th.Context, &model.Post{ UserId: user.Id, diff --git a/app/request/context.go b/app/request/context.go index e822c25568..a7dbf3cf7d 100644 --- a/app/request/context.go +++ b/app/request/context.go @@ -38,9 +38,10 @@ func NewContext(ctx context.Context, requestId, ipAddress, path, userAgent, acce } } -func EmptyContext() *Context { +func EmptyContext(logger mlog.LoggerIFace) *Context { return &Context{ t: i18n.T, + logger: logger, context: context.Background(), } } @@ -116,3 +117,27 @@ func (c *Context) SetAppError(err *model.AppError) { func (c *Context) AppError() *model.AppError { return c.err } + +type CTX interface { + T(string, ...interface{}) string + Session() *model.Session + RequestId() string + IPAddress() string + Path() string + UserAgent() string + AcceptLanguage() string + Context() context.Context + SetSession(s *model.Session) + SetT(i18n.TranslateFunc) + SetRequestId(string) + SetIPAddress(string) + SetUserAgent(string) + SetAcceptLanguage(string) + SetPath(string) + SetContext(ctx context.Context) + GetT() i18n.TranslateFunc + SetLogger(mlog.LoggerIFace) + Logger() mlog.LoggerIFace + SetAppError(*model.AppError) + AppError() *model.AppError +} diff --git a/app/role_test.go b/app/role_test.go index 5333081327..2e10c0d3c0 100644 --- a/app/role_test.go +++ b/app/role_test.go @@ -114,15 +114,15 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th defer th.App.DeleteScheme(channelScheme.Id) team := th.CreateTeam() - defer th.App.PermanentDeleteTeamId(team.Id) + defer th.App.PermanentDeleteTeamId(th.Context, team.Id) // Make a channel - channel := th.CreateChannel(team) - defer th.App.PermanentDeleteChannel(channel) + channel := th.CreateChannel(th.Context, team) + defer th.App.PermanentDeleteChannel(th.Context, channel) // Set the channel scheme channel.SchemeId = &channelScheme.Id - channel, err = th.App.UpdateChannelScheme(channel) + channel, err = th.App.UpdateChannelScheme(th.Context, channel) require.Nil(t, err) // Get the truth table from CSV diff --git a/app/server.go b/app/server.go index a71856b02c..e047dc3a96 100644 --- a/app/server.go +++ b/app/server.go @@ -480,7 +480,7 @@ func NewServer(options ...Option) (*Server, error) { return nil, errors.Wrap(err, "Unable to create opengraphdata cache") } - s.createPushNotificationsHub() + s.createPushNotificationsHub(request.EmptyContext(s.GetLogger())) if err2 := i18n.InitTranslations(*s.Config().LocalizationSettings.DefaultServerLocale, *s.Config().LocalizationSettings.DefaultClientLocale); err2 != nil { return nil, errors.Wrapf(err2, "unable to load Mattermost translation files") @@ -653,7 +653,8 @@ func NewServer(options ...Option) (*Server, error) { s.AddConfigListener(func(old, new *model.Config) { appInstance := New(ServerConnector(s.Channels())) if *old.GuestAccountsSettings.Enable && !*new.GuestAccountsSettings.Enable { - if appErr := appInstance.DeactivateGuests(request.EmptyContext()); appErr != nil { + c := request.EmptyContext(s.GetLogger()) + if appErr := appInstance.DeactivateGuests(c); appErr != nil { mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) } } @@ -662,7 +663,8 @@ func NewServer(options ...Option) (*Server, error) { // Disable active guest accounts on first run if guest accounts are disabled if !*s.Config().GuestAccountsSettings.Enable { appInstance := New(ServerConnector(s.Channels())) - if appErr := appInstance.DeactivateGuests(request.EmptyContext()); appErr != nil { + c := request.EmptyContext(s.GetLogger()) + if appErr := appInstance.DeactivateGuests(c); appErr != nil { mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) } } diff --git a/app/session_test.go b/app/session_test.go index 9aaa629d73..ec51d43913 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -134,7 +134,7 @@ func TestUpdateSessionOnPromoteDemote(t *testing.T) { require.Nil(t, err) assert.Equal(t, "false", rsession.Props[model.SessionPropIsGuest]) - err = th.App.DemoteUserToGuest(user) + err = th.App.DemoteUserToGuest(th.Context, user) require.Nil(t, err) rsession, err = th.App.GetSession(session.Token) diff --git a/app/shared_channel.go b/app/shared_channel.go index 8478ad9b9c..d993fafd54 100644 --- a/app/shared_channel.go +++ b/app/shared_channel.go @@ -8,13 +8,14 @@ import ( "fmt" "net/http" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/store" ) -func (a *App) checkChannelNotShared(channelId string) error { +func (a *App) checkChannelNotShared(c request.CTX, channelId string) error { // check that channel exists. - if _, err := a.GetChannel(channelId); err != nil { + if _, err := a.GetChannel(c, channelId); err != nil { return fmt.Errorf("cannot share this channel: %w", err) } @@ -58,8 +59,8 @@ func (a *App) CheckCanInviteToSharedChannel(channelId string) error { // SharedChannels -func (a *App) SaveSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error) { - if err := a.checkChannelNotShared(sc.ChannelId); err != nil { +func (a *App) SaveSharedChannel(c request.CTX, sc *model.SharedChannel) (*model.SharedChannel, error) { + if err := a.checkChannelNotShared(c, sc.ChannelId); err != nil { return nil, err } return a.Srv().Store.SharedChannel().Save(sc) diff --git a/app/shared_channel_notifier_test.go b/app/shared_channel_notifier_test.go index 9454b5dba0..510fe9a19c 100644 --- a/app/shared_channel_notifier_test.go +++ b/app/shared_channel_notifier_test.go @@ -31,7 +31,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { mockService := NewMockSharedChannelService(nil) mockService.active = true th.App.ch.srv.SetSharedChannelSyncService(mockService) - channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) websocketEvent := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, model.NewId(), channel.Id, "", nil) @@ -61,7 +61,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { mockService.active = true th.App.ch.srv.SetSharedChannelSyncService(mockService) - channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), channel.Id, "", nil) th.App.ch.srv.SharedChannelSyncHandler(websocketEvent) diff --git a/app/shared_channel_test.go b/app/shared_channel_test.go index f2674980e0..d01269116c 100644 --- a/app/shared_channel_test.go +++ b/app/shared_channel_test.go @@ -15,9 +15,9 @@ import ( func TestApp_CheckCanInviteToSharedChannel(t *testing.T) { th := Setup(t).InitBasic() - channel1 := th.CreateChannel(th.BasicTeam) - channel2 := th.CreateChannel(th.BasicTeam) - channel3 := th.CreateChannel(th.BasicTeam) + channel1 := th.CreateChannel(th.Context, th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) + channel3 := th.CreateChannel(th.Context, th.BasicTeam) data := []struct { channelId string @@ -38,22 +38,22 @@ func TestApp_CheckCanInviteToSharedChannel(t *testing.T) { CreatorId: th.BasicUser.Id, RemoteId: d.remoteId, } - _, err := th.App.SaveSharedChannel(sc) + _, err := th.App.SaveSharedChannel(th.Context, sc) require.NoError(t, err) } t.Run("Test checkChannelNotShared: not yet shared channel", func(t *testing.T) { - err := th.App.checkChannelNotShared(channel3.Id) + err := th.App.checkChannelNotShared(th.Context, channel3.Id) assert.NoError(t, err, "unshared channel should not error") }) t.Run("Test checkChannelNotShared: already shared channel", func(t *testing.T) { - err := th.App.checkChannelNotShared(channel1.Id) + err := th.App.checkChannelNotShared(th.Context, channel1.Id) assert.Error(t, err, "already shared channel should error") }) t.Run("Test checkChannelNotShared: invalid channel", func(t *testing.T) { - err := th.App.checkChannelNotShared(model.NewId()) + err := th.App.checkChannelNotShared(th.Context, model.NewId()) assert.Error(t, err, "invalid channel should error") }) diff --git a/app/slack.go b/app/slack.go index b355396955..0661850f5e 100644 --- a/app/slack.go +++ b/app/slack.go @@ -50,7 +50,7 @@ func (a *App) SlackImport(c *request.Context, fileData multipart.File, fileSize } importer := slackimport.New(a.ch.srv.Store, actions, a.Config()) - return importer.SlackImport(fileData, fileSize, teamID) + return importer.SlackImport(c, fileData, fileSize, teamID) } func (a *App) ProcessSlackText(text string) string { diff --git a/app/slashcommands/command_channel_header.go b/app/slashcommands/command_channel_header.go index d6c25dab08..4096174190 100644 --- a/app/slashcommands/command_channel_header.go +++ b/app/slashcommands/command_channel_header.go @@ -4,8 +4,6 @@ package slashcommands import ( - "context" - "github.com/mattermost/mattermost-server/v6/app" "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" @@ -38,7 +36,7 @@ func (*HeaderProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := a.GetChannel(args.ChannelId) + channel, err := a.GetChannel(c, args.ChannelId) if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_header.channel.app_error"), @@ -48,7 +46,7 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com switch channel.Type { case model.ChannelTypeOpen: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, @@ -56,7 +54,7 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com } case model.ChannelTypePrivate: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, @@ -66,7 +64,7 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com case model.ChannelTypeGroup, model.ChannelTypeDirect: // Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership. var channelMember *model.ChannelMember - channelMember, err = a.GetChannelMember(context.Background(), args.ChannelId, args.UserId) + channelMember, err = a.GetChannelMember(c, args.ChannelId, args.UserId) if err != nil || channelMember == nil { return &model.CommandResponse{ Text: args.T("api.command_channel_header.permission.app_error"), diff --git a/app/slashcommands/command_channel_purpose.go b/app/slashcommands/command_channel_purpose.go index b3760934b0..dfe0824470 100644 --- a/app/slashcommands/command_channel_purpose.go +++ b/app/slashcommands/command_channel_purpose.go @@ -36,7 +36,7 @@ func (*PurposeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comm } func (*PurposeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := a.GetChannel(args.ChannelId) + channel, err := a.GetChannel(c, args.ChannelId) if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.channel.app_error"), @@ -46,14 +46,14 @@ func (*PurposeProvider) DoCommand(a *app.App, c *request.Context, args *model.Co switch channel.Type { case model.ChannelTypeOpen: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, } } case model.ChannelTypePrivate: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, diff --git a/app/slashcommands/command_channel_rename.go b/app/slashcommands/command_channel_rename.go index cf2987c993..ec0655b3a9 100644 --- a/app/slashcommands/command_channel_rename.go +++ b/app/slashcommands/command_channel_rename.go @@ -39,7 +39,7 @@ func (*RenameProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma } func (*RenameProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := a.GetChannel(args.ChannelId) + channel, err := a.GetChannel(c, args.ChannelId) if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.channel.app_error"), @@ -49,14 +49,14 @@ func (*RenameProvider) DoCommand(a *app.App, c *request.Context, args *model.Com switch channel.Type { case model.ChannelTypeOpen: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, } } case model.ChannelTypePrivate: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) { return &model.CommandResponse{ Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, diff --git a/app/slashcommands/command_groupmsg.go b/app/slashcommands/command_groupmsg.go index 4b26675f9e..c728c2330b 100644 --- a/app/slashcommands/command_groupmsg.go +++ b/app/slashcommands/command_groupmsg.go @@ -110,13 +110,13 @@ func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.C var channelErr *model.AppError if a.HasPermissionTo(args.UserId, model.PermissionCreateGroupChannel) { - groupChannel, channelErr = a.CreateGroupChannel(targetUsersSlice, args.UserId) + groupChannel, channelErr = a.CreateGroupChannel(c, targetUsersSlice, args.UserId) if channelErr != nil { mlog.Error(channelErr.Error()) return &model.CommandResponse{Text: args.T("api.command_groupmsg.group_fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } } else { - groupChannel, channelErr = a.GetGroupChannel(targetUsersSlice) + groupChannel, channelErr = a.GetGroupChannel(c, targetUsersSlice) if channelErr != nil { return &model.CommandResponse{Text: args.T("api.command_groupmsg.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_invite.go b/app/slashcommands/command_invite.go index 6ba9e22dc8..60f217cd3e 100644 --- a/app/slashcommands/command_invite.go +++ b/app/slashcommands/command_invite.go @@ -4,7 +4,6 @@ package slashcommands import ( - "context" "strings" "github.com/mattermost/mattermost-server/v6/app" @@ -73,7 +72,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com if len(splitMessage) > 1 && splitMessage[1] != "" { targetChannelName := strings.TrimPrefix(strings.TrimSpace(splitMessage[1]), "~") - if channelToJoin, err = a.GetChannelByName(targetChannelName, args.TeamId, false); err != nil { + if channelToJoin, err = a.GetChannelByName(c, targetChannelName, args.TeamId, false); err != nil { return &model.CommandResponse{ Text: args.T("api.command_invite.channel.error", map[string]any{ "Channel": targetChannelName, @@ -82,7 +81,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com } } } else { - channelToJoin, err = a.GetChannel(args.ChannelId) + channelToJoin, err = a.GetChannel(c, args.ChannelId) if err != nil { return &model.CommandResponse{ Text: args.T("api.command_invite.channel.app_error"), @@ -94,7 +93,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com // Permissions Check switch channelToJoin.Type { case model.ChannelTypeOpen: - if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PermissionManagePublicChannelMembers) { + if !a.HasPermissionToChannel(c, args.UserId, channelToJoin.Id, model.PermissionManagePublicChannelMembers) { return &model.CommandResponse{ Text: args.T("api.command_invite.permission.app_error", map[string]any{ "User": userProfile.Username, @@ -104,8 +103,8 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com } } case model.ChannelTypePrivate: - if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PermissionManagePrivateChannelMembers) { - if _, err = a.GetChannelMember(context.Background(), channelToJoin.Id, args.UserId); err == nil { + if !a.HasPermissionToChannel(c, args.UserId, channelToJoin.Id, model.PermissionManagePrivateChannelMembers) { + if _, err = a.GetChannelMember(c, channelToJoin.Id, args.UserId); err == nil { // User doing the inviting is a member of the channel. return &model.CommandResponse{ Text: args.T("api.command_invite.permission.app_error", map[string]any{ @@ -131,7 +130,7 @@ func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.Com } // Check if user is already in the channel - _, err = a.GetChannelMember(context.Background(), channelToJoin.Id, userProfile.Id) + _, err = a.GetChannelMember(c, channelToJoin.Id, userProfile.Id) if err == nil { return &model.CommandResponse{ Text: args.T("api.command_invite.user_already_in_channel.app_error", map[string]any{ diff --git a/app/slashcommands/command_invite_test.go b/app/slashcommands/command_invite_test.go index 25525a8cd2..5de53899c0 100644 --- a/app/slashcommands/command_invite_test.go +++ b/app/slashcommands/command_invite_test.go @@ -76,7 +76,7 @@ func TestInviteProvider(t *testing.T) { _, err = th.App.AddChannelMember(th.Context, th.BasicUser.Id, groupChannel, app.ChannelMemberOpts{}) require.Nil(t, err) groupChannel.GroupConstrained = model.NewBool(true) - groupChannel, _ = th.App.UpdateChannel(groupChannel) + groupChannel, _ = th.App.UpdateChannel(th.Context, groupChannel) groupChannelNonUser := "@" + th.BasicUser2.Username + " ~" + groupChannel.Name diff --git a/app/slashcommands/command_join.go b/app/slashcommands/command_join.go index dd70bed6c0..d15493217d 100644 --- a/app/slashcommands/command_join.go +++ b/app/slashcommands/command_join.go @@ -55,11 +55,11 @@ func (*JoinProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma switch channel.Type { case model.ChannelTypeOpen: - if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PermissionJoinPublicChannels) { + if !a.HasPermissionToChannel(c, args.UserId, channel.Id, model.PermissionJoinPublicChannels) { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } case model.ChannelTypePrivate: - if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PermissionReadChannel) { + if !a.HasPermissionToChannel(c, args.UserId, channel.Id, model.PermissionReadChannel) { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } default: diff --git a/app/slashcommands/command_leave.go b/app/slashcommands/command_leave.go index e3b0893ac1..2010fc305d 100644 --- a/app/slashcommands/command_leave.go +++ b/app/slashcommands/command_leave.go @@ -37,7 +37,7 @@ func (*LeaveProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comman func (*LeaveProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { var channel *model.Channel var noChannelErr *model.AppError - if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil { + if channel, noChannelErr = a.GetChannel(c, args.ChannelId); noChannelErr != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } @@ -65,11 +65,11 @@ func (*LeaveProvider) DoCommand(a *app.App, c *request.Context, args *model.Comm } if user.IsGuest() { - members, err := a.GetChannelMembersForUser(team.Id, args.UserId) + members, err := a.GetChannelMembersForUser(c, team.Id, args.UserId) if err != nil || len(members) == 0 { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } - channel, err := a.GetChannel(members[0].ChannelId) + channel, err := a.GetChannel(c, members[0].ChannelId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_leave_test.go b/app/slashcommands/command_leave_test.go index b04b5492c2..1abbc9048f 100644 --- a/app/slashcommands/command_leave_test.go +++ b/app/slashcommands/command_leave_test.go @@ -4,7 +4,6 @@ package slashcommands import ( - "context" "testing" "github.com/stretchr/testify/assert" @@ -35,17 +34,17 @@ func TestLeaveProviderDoCommand(t *testing.T) { CreatorId: th.BasicUser.Id, }, false) - defaultChannel, err := th.App.GetChannelByName(model.DefaultChannelName, th.BasicTeam.Id, false) + defaultChannel, err := th.App.GetChannelByName(th.Context, model.DefaultChannelName, th.BasicTeam.Id, false) require.Nil(t, err) guest := th.createGuest() th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, th.BasicUser.Id, th.BasicUser.Id) - th.App.AddUserToChannel(th.BasicUser, publicChannel, false) - th.App.AddUserToChannel(th.BasicUser, privateChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, publicChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, privateChannel, false) th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, guest.Id, guest.Id) - th.App.AddUserToChannel(guest, publicChannel, false) - th.App.AddUserToChannel(guest, defaultChannel, false) + th.App.AddUserToChannel(th.Context, guest, publicChannel, false) + th.App.AddUserToChannel(th.Context, guest, defaultChannel, false) t.Run("Should error when no Channel ID in args", func(t *testing.T) { args := &model.CommandArgs{ @@ -81,7 +80,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+model.DefaultChannelName, actual.GotoLocation) assert.Equal(t, "", actual.ResponseType) - _, err = th.App.GetChannelMember(context.Background(), publicChannel.Id, th.BasicUser.Id) + _, err = th.App.GetChannelMember(th.Context, publicChannel.Id, th.BasicUser.Id) assert.NotNil(t, err) assert.NotNil(t, err.Id, "app.channel.get_member.missing.app_error") }) @@ -123,7 +122,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+publicChannel.Name, actual.GotoLocation) assert.Equal(t, "", actual.ResponseType) - _, err = th.App.GetChannelMember(context.Background(), defaultChannel.Id, guest.Id) + _, err = th.App.GetChannelMember(th.Context, defaultChannel.Id, guest.Id) assert.NotNil(t, err) assert.NotNil(t, err.Id, "app.channel.get_member.missing.app_error") }) @@ -141,7 +140,7 @@ func TestLeaveProviderDoCommand(t *testing.T) { assert.Equal(t, args.SiteURL+"/", actual.GotoLocation) assert.Equal(t, "", actual.ResponseType) - _, err = th.App.GetChannelMember(context.Background(), publicChannel.Id, guest.Id) + _, err = th.App.GetChannelMember(th.Context, publicChannel.Id, guest.Id) assert.NotNil(t, err) assert.NotNil(t, err.Id, "app.channel.get_member.missing.app_error") }) diff --git a/app/slashcommands/command_loadtest.go b/app/slashcommands/command_loadtest.go index 0b744637fa..f92e1895af 100644 --- a/app/slashcommands/command_loadtest.go +++ b/app/slashcommands/command_loadtest.go @@ -160,7 +160,7 @@ func (lt *LoadTestProvider) doCommand(a *app.App, c *request.Context, args *mode } if strings.HasPrefix(message, "post") { - return lt.PostCommand(a, args, message) + return lt.PostCommand(a, c, args, message) } if strings.HasPrefix(message, "threaded_post") { @@ -444,7 +444,7 @@ func getMatch(re *regexp.Regexp, text string) string { return "" } -func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) { +func (*LoadTestProvider) PostCommand(a *app.App, c request.CTX, args *model.CommandArgs, message string) (*model.CommandResponse, error) { textMessage := getMatch(messageRE, message) if textMessage == "" { return &model.CommandResponse{Text: "No message to post", ResponseType: model.CommandResponseTypeEphemeral}, nil @@ -457,7 +457,7 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag } channelName := getMatch(channelRE, message) - channel, err := a.GetChannelByName(channelName, team.Id, true) + channel, err := a.GetChannelByName(c, channelName, team.Id, true) if err != nil { return &model.CommandResponse{Text: "Failed to get a channel", ResponseType: model.CommandResponseTypeEphemeral}, err } diff --git a/app/slashcommands/command_mute.go b/app/slashcommands/command_mute.go index ab24f8c919..96319b86fc 100644 --- a/app/slashcommands/command_mute.go +++ b/app/slashcommands/command_mute.go @@ -41,7 +41,7 @@ func (*MuteProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma var channel *model.Channel var noChannelErr *model.AppError - if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil { + if channel, noChannelErr = a.GetChannel(c, args.ChannelId); noChannelErr != nil { return &model.CommandResponse{Text: args.T("api.command_mute.no_channel.error"), ResponseType: model.CommandResponseTypeEphemeral} } @@ -62,7 +62,7 @@ func (*MuteProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma } } - channelMember, err := a.ToggleMuteChannel(channel.Id, args.UserId) + channelMember, err := a.ToggleMuteChannel(c, channel.Id, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_mute.not_member.error", map[string]any{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_mute_test.go b/app/slashcommands/command_mute_test.go index 921d519e83..53286f6959 100644 --- a/app/slashcommands/command_mute_test.go +++ b/app/slashcommands/command_mute_test.go @@ -4,7 +4,6 @@ package slashcommands import ( - "context" "testing" "time" @@ -23,7 +22,7 @@ func TestMuteCommandNoChannel(t *testing.T) { } channel1 := th.BasicChannel - channel1M, channel1MError := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + channel1M, channel1MError := th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) assert.Nil(t, channel1MError, "User is not a member of channel 1") assert.NotEqual( @@ -46,7 +45,7 @@ func TestMuteCommandNoArgs(t *testing.T) { defer th.tearDown() channel1 := th.BasicChannel - channel1M, _ := th.App.GetChannelMember(context.Background(), channel1.Id, th.BasicUser.Id) + channel1M, _ := th.App.GetChannelMember(th.Context, channel1.Id, th.BasicUser.Id) assert.Equal(t, model.ChannelNotifyAll, channel1M.NotifyProps[model.MarkUnreadNotifyProp]) @@ -88,7 +87,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { CreatorId: th.BasicUser.Id, }, true) - channel2M, _ := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + channel2M, _ := th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) @@ -101,7 +100,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { UserId: th.BasicUser.Id, }, channel2.Name) assert.Equal(t, "api.command_mute.success_mute", resp.Text) - channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + channel2M, _ = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) assert.Equal(t, model.ChannelNotifyMention, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) // Now unmute the channel @@ -112,7 +111,7 @@ func TestMuteCommandSpecificChannel(t *testing.T) { }, "~"+channel2.Name) assert.Equal(t, "api.command_mute.success_unmute", resp.Text) - channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + channel2M, _ = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) } @@ -174,7 +173,7 @@ func TestMuteCommandDMChannel(t *testing.T) { } channel2, _ := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id) - channel2M, _ := th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + channel2M, _ := th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) @@ -188,7 +187,7 @@ func TestMuteCommandDMChannel(t *testing.T) { }, "") assert.Equal(t, "api.command_mute.success_mute_direct_msg", resp.Text) time.Sleep(time.Millisecond) - channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + channel2M, _ = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) assert.Equal(t, model.ChannelNotifyMention, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) // Now unmute the channel @@ -200,6 +199,6 @@ func TestMuteCommandDMChannel(t *testing.T) { assert.Equal(t, "api.command_mute.success_unmute_direct_msg", resp.Text) time.Sleep(time.Millisecond) - channel2M, _ = th.App.GetChannelMember(context.Background(), channel2.Id, th.BasicUser.Id) + channel2M, _ = th.App.GetChannelMember(th.Context, channel2.Id, th.BasicUser.Id) assert.Equal(t, model.ChannelNotifyAll, channel2M.NotifyProps[model.MarkUnreadNotifyProp]) } diff --git a/app/slashcommands/command_remove.go b/app/slashcommands/command_remove.go index daa42edca3..ce95e67a58 100644 --- a/app/slashcommands/command_remove.go +++ b/app/slashcommands/command_remove.go @@ -4,7 +4,6 @@ package slashcommands import ( - "context" "strings" "github.com/mattermost/mattermost-server/v6/app" @@ -67,7 +66,7 @@ func (*KickProvider) DoCommand(a *app.App, c *request.Context, args *model.Comma } func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := a.GetChannel(args.ChannelId) + channel, err := a.GetChannel(c, args.ChannelId) if err != nil { return &model.CommandResponse{ Text: args.T("api.command_channel_remove.channel.app_error"), @@ -77,14 +76,14 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message switch channel.Type { case model.ChannelTypeOpen: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelMembers) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePublicChannelMembers) { return &model.CommandResponse{ Text: args.T("api.command_remove.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, } } case model.ChannelTypePrivate: - if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelMembers) { + if !a.HasPermissionToChannel(c, args.UserId, args.ChannelId, model.PermissionManagePrivateChannelMembers) { return &model.CommandResponse{ Text: args.T("api.command_remove.permission.app_error"), ResponseType: model.CommandResponseTypeEphemeral, @@ -124,7 +123,7 @@ func doCommand(a *app.App, c *request.Context, args *model.CommandArgs, message } } - _, err = a.GetChannelMember(context.Background(), args.ChannelId, userProfile.Id) + _, err = a.GetChannelMember(c, args.ChannelId, userProfile.Id) if err != nil { nameFormat := *a.Config().TeamSettings.TeammateNameDisplay return &model.CommandResponse{ diff --git a/app/slashcommands/command_remove_test.go b/app/slashcommands/command_remove_test.go index 617a387bb0..32fe1a2213 100644 --- a/app/slashcommands/command_remove_test.go +++ b/app/slashcommands/command_remove_test.go @@ -35,8 +35,8 @@ func TestRemoveProviderDoCommand(t *testing.T) { targetUser := th.createUser() th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, targetUser.Id, targetUser.Id) - th.App.AddUserToChannel(targetUser, publicChannel, false) - th.App.AddUserToChannel(targetUser, privateChannel, false) + th.App.AddUserToChannel(th.Context, targetUser, publicChannel, false) + th.App.AddUserToChannel(th.Context, targetUser, privateChannel, false) // Try a public channel *without* permission. args := &model.CommandArgs{ @@ -49,7 +49,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { assert.Equal(t, "api.command_remove.permission.app_error", actual) // Try a public channel *with* permission. - th.App.AddUserToChannel(th.BasicUser, publicChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, publicChannel, false) args = &model.CommandArgs{ T: func(s string, args ...any) string { return s }, ChannelId: publicChannel.Id, @@ -70,7 +70,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { assert.Equal(t, "api.command_remove.permission.app_error", actual) // Try a private channel *with* permission. - th.App.AddUserToChannel(th.BasicUser, privateChannel, false) + th.App.AddUserToChannel(th.Context, th.BasicUser, privateChannel, false) args = &model.CommandArgs{ T: func(s string, args ...any) string { return s }, ChannelId: privateChannel.Id, @@ -110,7 +110,7 @@ func TestRemoveProviderDoCommand(t *testing.T) { // Try a public channel with a deactivated user. deactivatedUser := th.createUser() th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, deactivatedUser.Id, deactivatedUser.Id) - th.App.AddUserToChannel(deactivatedUser, publicChannel, false) + th.App.AddUserToChannel(th.Context, deactivatedUser, publicChannel, false) th.App.UpdateActive(th.Context, deactivatedUser, false) args = &model.CommandArgs{ diff --git a/app/slashcommands/command_share.go b/app/slashcommands/command_share.go index 2411c0b1af..5d526f8640 100644 --- a/app/slashcommands/command_share.go +++ b/app/slashcommands/command_share.go @@ -59,11 +59,11 @@ func (sp *ShareProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Com } } -func (sp *ShareProvider) GetAutoCompleteListItems(a *app.App, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) ([]model.AutocompleteListItem, error) { +func (sp *ShareProvider) GetAutoCompleteListItems(c request.CTX, a *app.App, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) ([]model.AutocompleteListItem, error) { switch { case strings.Contains(parsed, " share "): - return sp.getAutoCompleteShareChannel(a, commandArgs, arg) + return sp.getAutoCompleteShareChannel(c, a, commandArgs, arg) case strings.Contains(parsed, " invite "): @@ -77,8 +77,8 @@ func (sp *ShareProvider) GetAutoCompleteListItems(a *app.App, commandArgs *model return nil, errors.New("invalid action") } -func (sp *ShareProvider) getAutoCompleteShareChannel(a *app.App, commandArgs *model.CommandArgs, arg *model.AutocompleteArg) ([]model.AutocompleteListItem, error) { - channel, err := a.GetChannel(commandArgs.ChannelId) +func (sp *ShareProvider) getAutoCompleteShareChannel(c request.CTX, a *app.App, commandArgs *model.CommandArgs, arg *model.AutocompleteArg) ([]model.AutocompleteListItem, error) { + channel, err := a.GetChannel(c, commandArgs.ChannelId) if err != nil { return nil, err } @@ -141,11 +141,11 @@ func (sp *ShareProvider) DoCommand(a *app.App, c *request.Context, args *model.C switch action { case "share": - return sp.doShareChannel(a, args, margs) + return sp.doShareChannel(a, c, args, margs) case "unshare": return sp.doUnshareChannel(a, args, margs) case "invite": - return sp.doInviteRemote(a, args, margs) + return sp.doInviteRemote(a, c, args, margs) case "uninvite": return sp.doUninviteRemote(a, args, margs) case "status": @@ -154,9 +154,9 @@ func (sp *ShareProvider) DoCommand(a *app.App, c *request.Context, args *model.C return responsef(args.T("api.command_share.unknown_action", map[string]any{"Action": action, "Actions": AvailableShareActions})) } -func (sp *ShareProvider) doShareChannel(a *app.App, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { +func (sp *ShareProvider) doShareChannel(a *app.App, c request.CTX, args *model.CommandArgs, margs map[string]string) *model.CommandResponse { // check that channel exists. - channel, errApp := a.GetChannel(args.ChannelId) + channel, errApp := a.GetChannel(c, args.ChannelId) if errApp != nil { return responsef(args.T("api.command_share.share_channel.error", map[string]any{"Error": errApp.Error()})) } @@ -194,7 +194,7 @@ func (sp *ShareProvider) doShareChannel(a *app.App, args *model.CommandArgs, mar CreatorId: args.UserId, } - if _, err := a.SaveSharedChannel(sc); err != nil { + if _, err := a.SaveSharedChannel(c, sc); err != nil { return responsef(args.T("api.command_share.share_channel.error", map[string]any{"Error": err.Error()})) } @@ -222,7 +222,7 @@ func (sp *ShareProvider) doUnshareChannel(a *app.App, args *model.CommandArgs, m return responsef("##### " + args.T("api.command_share.shared_channel_unavailable")) } -func (sp *ShareProvider) doInviteRemote(a *app.App, args *model.CommandArgs, margs map[string]string) (resp *model.CommandResponse) { +func (sp *ShareProvider) doInviteRemote(a *app.App, c request.CTX, args *model.CommandArgs, margs map[string]string) (resp *model.CommandResponse) { remoteId, ok := margs["connectionID"] if !ok || remoteId == "" { return responsef(args.T("api.command_share.must_specify_valid_remote")) @@ -243,7 +243,7 @@ func (sp *ShareProvider) doInviteRemote(a *app.App, args *model.CommandArgs, mar } if !hasChan { // If it doesn't exist, then create it. - resp2 := sp.doShareChannel(a, args, margs) + resp2 := sp.doShareChannel(a, c, args, margs) // We modify the outgoing response by prepending the text // from the shareChannel response. defer func() { @@ -262,7 +262,7 @@ func (sp *ShareProvider) doInviteRemote(a *app.App, args *model.CommandArgs, mar return responsef(args.T("api.command_share.remote_id_invalid.error", map[string]any{"Error": appErr.Error()})) } - channel, errApp := a.GetChannel(args.ChannelId) + channel, errApp := a.GetChannel(c, args.ChannelId) if errApp != nil { return responsef(args.T("api.command_share.channel_invite.error", map[string]any{"Name": rc.DisplayName, "Error": errApp.Error()})) } diff --git a/app/slashcommands/command_test.go b/app/slashcommands/command_test.go index a227b6e9e3..0ed82c9778 100644 --- a/app/slashcommands/command_test.go +++ b/app/slashcommands/command_test.go @@ -50,8 +50,8 @@ func TestMoveCommand(t *testing.T) { assert.Nil(t, err) defer func() { - th.App.PermanentDeleteTeam(sourceTeam) - th.App.PermanentDeleteTeam(targetTeam) + th.App.PermanentDeleteTeam(th.Context, sourceTeam) + th.App.PermanentDeleteTeam(th.Context, targetTeam) }() // Move a command and check the team is updated. @@ -610,7 +610,7 @@ func TestMentionsToPublicChannels(t *testing.T) { } for _, data := range fixture { - actualMap := th.App.MentionsToPublicChannels(data.message, data.inTeam) + actualMap := th.App.MentionsToPublicChannels(th.Context, data.message, data.inTeam) require.Equal(t, actualMap, data.expectedMap) } } diff --git a/app/slashcommands/helper_test.go b/app/slashcommands/helper_test.go index 56ba662f7f..2435c71feb 100644 --- a/app/slashcommands/helper_test.go +++ b/app/slashcommands/helper_test.go @@ -91,7 +91,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th := &TestHelper{ App: app.New(app.ServerConnector(s.Channels())), - Context: &request.Context{}, + Context: request.EmptyContext(testLogger), Server: s, LogBuffer: buffer, TestLogger: testLogger, @@ -280,7 +280,7 @@ func (th *TestHelper) createChannel(team *model.Team, channelType model.ChannelT if channel.IsShared() { id := model.NewId() - _, err := th.App.SaveSharedChannel(&model.SharedChannel{ + _, err := th.App.SaveSharedChannel(th.Context, &model.SharedChannel{ ChannelId: channel.Id, TeamId: channel.TeamId, Home: false, @@ -327,7 +327,7 @@ func (th *TestHelper) createDmChannel(user *model.User) *model.Channel { func (th *TestHelper) createGroupChannel(user1 *model.User, user2 *model.User) *model.Channel { var err *model.AppError var channel *model.Channel - if channel, err = th.App.CreateGroupChannel([]string{th.BasicUser.Id, user1.Id, user2.Id}, th.BasicUser.Id); err != nil { + if channel, err = th.App.CreateGroupChannel(th.Context, []string{th.BasicUser.Id, user1.Id, user2.Id}, th.BasicUser.Id); err != nil { panic(err) } return channel @@ -358,7 +358,7 @@ func (th *TestHelper) linkUserToTeam(user *model.User, team *model.Team) { } func (th *TestHelper) addUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember { - member, err := th.App.AddUserToChannel(user, channel, false) + member, err := th.App.AddUserToChannel(th.Context, user, channel, false) if err != nil { panic(err) } diff --git a/app/syncables.go b/app/syncables.go index 123bc756b6..4362991713 100644 --- a/app/syncables.go +++ b/app/syncables.go @@ -25,7 +25,7 @@ func (a *App) createDefaultChannelMemberships(c *request.Context, since int64, c } for _, userChannel := range channelMembers { - channel, err := a.GetChannel(userChannel.ChannelID) + channel, err := a.GetChannel(c, userChannel.ChannelID) if err != nil { return err } @@ -179,7 +179,7 @@ func (a *App) deleteGroupConstrainedChannelMemberships(c *request.Context, chann } for _, userChannel := range channelMembers { - channel, err := a.GetChannel(userChannel.ChannelId) + channel, err := a.GetChannel(c, userChannel.ChannelId) if err != nil { return err } @@ -250,6 +250,6 @@ func (a *App) SyncRolesAndMembership(c *request.Context, syncableID string, sync case model.GroupSyncableTypeChannel: a.createDefaultChannelMemberships(c, since, &syncableID, includeRemovedMembers) a.deleteGroupConstrainedChannelMemberships(c, &syncableID) - a.ClearChannelMembersCache(syncableID) + a.ClearChannelMembersCache(c, syncableID) } } diff --git a/app/syncables_test.go b/app/syncables_test.go index 778d4159d3..c996546f80 100644 --- a/app/syncables_test.go +++ b/app/syncables_test.go @@ -4,7 +4,6 @@ package app import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -114,7 +113,7 @@ func TestCreateDefaultMemberships(t *testing.T) { if err != nil { t.Errorf("error retrieving team member: %s", err.Error()) } - _, err = th.App.GetChannelMember(context.Background(), practiceChannel.Id, singer1.Id) + _, err = th.App.GetChannelMember(th.Context, practiceChannel.Id, singer1.Id) if err != nil { t.Errorf("error retrieving channel member: %s", err.Error()) } @@ -129,7 +128,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("expected %d team members but got %d", expected, actual) } - cMembersCount, err := th.App.GetChannelMemberCount(practiceChannel.Id) + cMembersCount, err := th.App.GetChannelMemberCount(th.Context, practiceChannel.Id) if err != nil { t.Errorf("error retrieving team members: %s", err.Error()) } @@ -143,7 +142,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("wrong error: %s", err.Id) } - _, err = th.App.GetChannelMember(context.Background(), experimentsChannel.Id, scientist1.Id) + _, err = th.App.GetChannelMember(th.Context, experimentsChannel.Id, scientist1.Id) if err.Id != "app.channel.get_member.missing.app_error" { t.Errorf("wrong error: %s", err.Id) } @@ -158,7 +157,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("expected %d team members but got %d", expected, actual) } - cMembersCount, err = th.App.GetChannelMemberCount(experimentsChannel.Id) + cMembersCount, err = th.App.GetChannelMemberCount(th.Context, experimentsChannel.Id) if err != nil { t.Errorf("error retrieving team members: %s", err.Error()) } @@ -185,7 +184,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("error retrieving team member: %s", err.Error()) } - _, err = th.App.GetChannelMember(context.Background(), experimentsChannel.Id, scientist1.Id) + _, err = th.App.GetChannelMember(th.Context, experimentsChannel.Id, scientist1.Id) if err.Id != "app.channel.get_member.missing.app_error" { t.Errorf("wrong error: %s", err.Id) } @@ -201,7 +200,7 @@ func TestCreateDefaultMemberships(t *testing.T) { } expected = 0 - cMembersCount, err = th.App.GetChannelMemberCount(experimentsChannel.Id) + cMembersCount, err = th.App.GetChannelMemberCount(th.Context, experimentsChannel.Id) if err != nil { t.Errorf("error retrieving team members: %s", err.Error()) } @@ -223,7 +222,7 @@ func TestCreateDefaultMemberships(t *testing.T) { } expected = 1 - cMembersCount, err = th.App.GetChannelMemberCount(experimentsChannel.Id) + cMembersCount, err = th.App.GetChannelMemberCount(th.Context, experimentsChannel.Id) if err != nil { t.Errorf("error retrieving team members: %s", err.Error()) } @@ -256,7 +255,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Error("expected team member to remain deleted") } - _, err = th.App.GetChannelMember(context.Background(), practiceChannel.Id, singer1.Id) + _, err = th.App.GetChannelMember(th.Context, practiceChannel.Id, singer1.Id) if err == nil { t.Error("Expected channel member to remain deleted") } @@ -311,7 +310,7 @@ func TestCreateDefaultMemberships(t *testing.T) { t.Errorf("failed to populate syncables: %s", pErr.Error()) } - _, err = th.App.GetChannelMember(context.Background(), experimentsChannel.Id, scientist1.Id) + _, err = th.App.GetChannelMember(th.Context, experimentsChannel.Id, scientist1.Id) if err == nil { t.Error("Expected channel member to remain deleted") } @@ -330,7 +329,7 @@ func TestCreateDefaultMemberships(t *testing.T) { } // Channel member is re-added. - _, err = th.App.GetChannelMember(context.Background(), experimentsChannel.Id, scientist1.Id) + _, err = th.App.GetChannelMember(th.Context, experimentsChannel.Id, scientist1.Id) if err != nil { t.Errorf("expected channel member: %s", err.Error()) } @@ -368,7 +367,7 @@ func TestCreateDefaultMemberships(t *testing.T) { require.NoError(t, pErr) // Ensure only the restricted user was added to both the team and channel - cMembersCount, err = th.App.GetChannelMemberCount(restrictedChannel.Id) + cMembersCount, err = th.App.GetChannelMemberCount(th.Context, restrictedChannel.Id) require.Nil(t, err) require.Equal(t, cMembersCount, int64(1)) tmembers, err := th.App.GetTeamMembers(restrictedTeam.Id, 0, 100, nil) @@ -406,7 +405,7 @@ func TestDeleteGroupMemberships(t *testing.T) { // make channel group-constrained channel := th.BasicChannel channel.GroupConstrained = model.NewBool(true) - channel, err = th.App.UpdateChannel(channel) + channel, err = th.App.UpdateChannel(th.Context, channel) require.Nil(t, err) require.True(t, *channel.GroupConstrained) @@ -421,7 +420,7 @@ func TestDeleteGroupMemberships(t *testing.T) { require.Nil(t, err) require.Len(t, tmembers, 3) - cmemberCount, err := th.App.GetChannelMemberCount(th.BasicChannel.Id) + cmemberCount, err := th.App.GetChannelMemberCount(th.Context, th.BasicChannel.Id) require.Nil(t, err) require.Equal(t, 3, int(cmemberCount)) @@ -439,7 +438,7 @@ func TestDeleteGroupMemberships(t *testing.T) { require.Len(t, tmembers, 1) require.Equal(t, th.SystemAdminUser.Id, tmembers[0].UserId) - cmembers, err := th.App.GetChannelMembersPage(channel.Id, 0, 99) + cmembers, err := th.App.GetChannelMembersPage(th.Context, channel.Id, 0, 99) require.Nil(t, err) require.Len(t, cmembers, 1) require.Equal(t, th.SystemAdminUser.Id, cmembers[0].UserId) @@ -451,9 +450,9 @@ func TestSyncSyncableRoles(t *testing.T) { team := th.CreateTeam() - channel := th.CreateChannel(team) + channel := th.CreateChannel(th.Context, team) channel.GroupConstrained = model.NewBool(true) - channel, err := th.App.UpdateChannel(channel) + channel, err := th.App.UpdateChannel(th.Context, channel) require.Nil(t, err) user1 := th.CreateUser() @@ -506,7 +505,7 @@ func TestSyncSyncableRoles(t *testing.T) { require.Nil(t, err) require.True(t, tm.SchemeAdmin) - cm, err := th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + cm, err := th.App.GetChannelMember(th.Context, channel.Id, user.Id) require.Nil(t, err) require.True(t, cm.SchemeAdmin) } diff --git a/app/team.go b/app/team.go index 0ad5fa2b88..965459f412 100644 --- a/app/team.go +++ b/app/team.go @@ -697,7 +697,7 @@ func (a *App) AddUserToTeamByToken(c *request.Context, userID string, tokenID st } for _, channel := range channels { - _, err := a.AddUserToChannel(user, channel, false) + _, err := a.AddUserToChannel(c, user, channel, false) if err != nil { mlog.Warn("Error adding user to channel", mlog.Err(err)) } @@ -1193,7 +1193,7 @@ func (a *App) RemoveUserFromTeam(c *request.Context, teamID string, userID strin return nil } -func (a *App) postProcessTeamMemberLeave(c *request.Context, teamMember *model.TeamMember, requestorId string) *model.AppError { +func (a *App) postProcessTeamMemberLeave(c request.CTX, teamMember *model.TeamMember, requestorId string) *model.AppError { if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil { var actor *model.User if requestorId != "" { @@ -1745,16 +1745,16 @@ func (a *App) GetTeamsUnreadForUser(excludeTeamId string, userID string, include return members, nil } -func (a *App) PermanentDeleteTeamId(teamID string) *model.AppError { +func (a *App) PermanentDeleteTeamId(c request.CTX, teamID string) *model.AppError { team, err := a.GetTeam(teamID) if err != nil { return err } - return a.PermanentDeleteTeam(team) + return a.PermanentDeleteTeam(c, team) } -func (a *App) PermanentDeleteTeam(team *model.Team) *model.AppError { +func (a *App) PermanentDeleteTeam(c request.CTX, team *model.Team) *model.AppError { team.DeleteAt = model.GetMillis() if _, err := a.Srv().Store.Team().Update(team); err != nil { var invErr *store.ErrInvalidInput @@ -1775,8 +1775,8 @@ func (a *App) PermanentDeleteTeam(team *model.Team) *model.AppError { return model.NewAppError("PermanentDeleteTeam", "app.channel.get_channels.get.app_error", nil, err.Error(), http.StatusInternalServerError) } } else { - for _, c := range channels { - a.PermanentDeleteChannel(c) + for _, ch := range channels { + a.PermanentDeleteChannel(c, ch) } } diff --git a/app/team_test.go b/app/team_test.go index ce84ff5877..9423927cec 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -185,7 +185,7 @@ func TestAddUserToTeam(t *testing.T) { _, _, err := th.App.AddUserToTeam(th.Context, team.Id, user.Id, "") require.Nil(t, err) - res, err := th.App.GetSidebarCategoriesForTeamForUser(user.Id, team.Id) + res, err := th.App.GetSidebarCategoriesForTeamForUser(th.Context, user.Id, team.Id) require.Nil(t, err) assert.Len(t, res.Categories, 3) assert.Equal(t, model.SidebarCategoryFavorites, res.Categories[0].Type) @@ -270,7 +270,7 @@ func TestAddUserToTeamByToken(t *testing.T) { _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") - members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, ruser.Id) + members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, ruser.Id) require.Nil(t, err) assert.Len(t, members, 2) }) @@ -370,7 +370,7 @@ func TestAddUserToTeamByToken(t *testing.T) { _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") - members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, rguest.Id) + members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, rguest.Id) require.Nil(t, err) require.Len(t, members, 1) assert.Equal(t, members[0].ChannelId, th.BasicChannel.Id) @@ -429,7 +429,7 @@ func TestAddUserToTeamByToken(t *testing.T) { _, _, err := th.App.AddUserToTeamByToken(th.Context, user.Id, token.Token) require.Nil(t, err) - res, err := th.App.GetSidebarCategoriesForTeamForUser(user.Id, team.Id) + res, err := th.App.GetSidebarCategoriesForTeamForUser(th.Context, user.Id, team.Id) require.Nil(t, err) assert.Len(t, res.Categories, 3) assert.Equal(t, model.SidebarCategoryFavorites, res.Categories[0].Type) @@ -670,7 +670,7 @@ func TestPermanentDeleteTeam(t *testing.T) { require.Nil(t, err, "Should create a team") defer func() { - th.App.PermanentDeleteTeam(team) + th.App.PermanentDeleteTeam(th.Context, team) }() command, err := th.App.CreateCommand(&model.Command{ @@ -687,7 +687,7 @@ func TestPermanentDeleteTeam(t *testing.T) { require.NotNil(t, command, "command should not be nil") require.Nil(t, err, "unable to get new command") - err = th.App.PermanentDeleteTeam(team) + err = th.App.PermanentDeleteTeam(th.Context, team) require.Nil(t, err) command, err = th.App.GetCommand(command.Id) @@ -697,18 +697,18 @@ func TestPermanentDeleteTeam(t *testing.T) { // Test deleting a team with no channels. team = th.CreateTeam() defer func() { - th.App.PermanentDeleteTeam(team) + th.App.PermanentDeleteTeam(th.Context, team) }() - channels, err := th.App.GetPublicChannelsForTeam(team.Id, 0, 1000) + channels, err := th.App.GetPublicChannelsForTeam(th.Context, team.Id, 0, 1000) require.Nil(t, err) for _, channel := range channels { - err2 := th.App.PermanentDeleteChannel(channel) + err2 := th.App.PermanentDeleteChannel(th.Context, channel) require.Nil(t, err2) } - err = th.App.PermanentDeleteTeam(team) + err = th.App.PermanentDeleteTeam(th.Context, team) require.Nil(t, err) } @@ -929,7 +929,7 @@ func TestJoinUserToTeam(t *testing.T) { maxUsersPerTeam := th.App.Config().TeamSettings.MaxUsersPerTeam defer func() { th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.MaxUsersPerTeam = maxUsersPerTeam }) - th.App.PermanentDeleteTeam(team) + th.App.PermanentDeleteTeam(th.Context, team) }() one := 1 th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.MaxUsersPerTeam = &one }) @@ -1250,7 +1250,7 @@ func TestGetTeamStats(t *testing.T) { teamStats, err := th.App.GetTeamStats(th.BasicTeam.Id, restrictions) require.Nil(t, err) require.NotNil(t, teamStats) - members, err := th.App.GetChannelMembersPage(th.BasicChannel.Id, 0, 5) + members, err := th.App.GetChannelMembersPage(th.Context, th.BasicChannel.Id, 0, 5) require.Nil(t, err) assert.Equal(t, int64(len(members)), teamStats.TotalMemberCount) assert.Equal(t, int64(len(members)), teamStats.ActiveMemberCount) diff --git a/app/upload.go b/app/upload.go index d84829cef5..b1e37fd0b4 100644 --- a/app/upload.go +++ b/app/upload.go @@ -117,7 +117,7 @@ func (a *App) runPluginsHook(c *request.Context, info *model.FileInfo, file io.R return nil } -func (a *App) CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) { +func (a *App) CreateUploadSession(c request.CTX, us *model.UploadSession) (*model.UploadSession, *model.AppError) { if us.FileSize > *a.Config().FileSettings.MaxFileSize { return nil, model.NewAppError("CreateUploadSession", "app.upload.create.upload_too_large.app_error", map[string]any{"channelId": us.ChannelId}, "", http.StatusRequestEntityTooLarge) @@ -136,7 +136,7 @@ func (a *App) CreateUploadSession(us *model.UploadSession) (*model.UploadSession } if us.Type == model.UploadTypeAttachment { - channel, err := a.GetChannel(us.ChannelId) + channel, err := a.GetChannel(c, us.ChannelId) if err != nil { return nil, model.NewAppError("CreateUploadSession", "app.upload.create.incorrect_channel_id.app_error", map[string]any{"channelId": us.ChannelId}, "", http.StatusBadRequest) diff --git a/app/upload_test.go b/app/upload_test.go index be4482b419..447914fa25 100644 --- a/app/upload_test.go +++ b/app/upload_test.go @@ -36,14 +36,14 @@ func TestCreateUploadSession(t *testing.T) { maxFileSize := *th.App.Config().FileSettings.MaxFileSize th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.MaxFileSize = us.FileSize - 1 }) defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.MaxFileSize = maxFileSize }) - u, err := th.App.CreateUploadSession(us) + u, err := th.App.CreateUploadSession(th.Context, us) require.NotNil(t, err) require.Equal(t, "app.upload.create.upload_too_large.app_error", err.Id) require.Nil(t, u) }) t.Run("invalid Id", func(t *testing.T) { - u, err := th.App.CreateUploadSession(us) + u, err := th.App.CreateUploadSession(th.Context, us) require.NotNil(t, err) require.Equal(t, "model.upload_session.is_valid.id.app_error", err.Id) require.Nil(t, u) @@ -52,7 +52,7 @@ func TestCreateUploadSession(t *testing.T) { t.Run("invalid UserId", func(t *testing.T) { us.Id = model.NewId() us.UserId = "" - u, err := th.App.CreateUploadSession(us) + u, err := th.App.CreateUploadSession(th.Context, us) require.NotNil(t, err) require.Equal(t, "model.upload_session.is_valid.user_id.app_error", err.Id) require.Nil(t, u) @@ -61,7 +61,7 @@ func TestCreateUploadSession(t *testing.T) { t.Run("invalid ChannelId", func(t *testing.T) { us.UserId = th.BasicUser.Id us.ChannelId = "" - u, err := th.App.CreateUploadSession(us) + u, err := th.App.CreateUploadSession(th.Context, us) require.NotNil(t, err) require.Equal(t, "model.upload_session.is_valid.channel_id.app_error", err.Id) require.Nil(t, u) @@ -69,17 +69,17 @@ func TestCreateUploadSession(t *testing.T) { t.Run("non-existing channel", func(t *testing.T) { us.ChannelId = model.NewId() - u, err := th.App.CreateUploadSession(us) + u, err := th.App.CreateUploadSession(th.Context, us) require.NotNil(t, err) require.Equal(t, "app.upload.create.incorrect_channel_id.app_error", err.Id) require.Nil(t, u) }) t.Run("deleted channel", func(t *testing.T) { - ch := th.CreateChannel(th.BasicTeam) + ch := th.CreateChannel(th.Context, th.BasicTeam) th.App.DeleteChannel(th.Context, ch, th.BasicUser.Id) us.ChannelId = ch.Id - u, err := th.App.CreateUploadSession(us) + u, err := th.App.CreateUploadSession(th.Context, us) require.NotNil(t, err) require.Equal(t, "app.upload.create.cannot_upload_to_deleted_channel.app_error", err.Id) require.Nil(t, u) @@ -87,7 +87,7 @@ func TestCreateUploadSession(t *testing.T) { t.Run("success", func(t *testing.T) { us.ChannelId = th.BasicChannel.Id - u, err := th.App.CreateUploadSession(us) + u, err := th.App.CreateUploadSession(th.Context, us) require.Nil(t, err) require.NotEmpty(t, u) }) @@ -106,7 +106,7 @@ func TestUploadData(t *testing.T) { FileSize: 8 * 1024 * 1024, } - us, uploadSessionAppErr := th.App.CreateUploadSession(us) + us, uploadSessionAppErr := th.App.CreateUploadSession(th.Context, us) require.Nil(t, uploadSessionAppErr) require.NotEmpty(t, us) @@ -177,7 +177,7 @@ func TestUploadData(t *testing.T) { t.Run("all at once success", func(t *testing.T) { us.Id = model.NewId() var appErr *model.AppError - us, appErr = th.App.CreateUploadSession(us) + us, appErr = th.App.CreateUploadSession(th.Context, us) require.Nil(t, appErr) require.NotEmpty(t, us) @@ -194,7 +194,7 @@ func TestUploadData(t *testing.T) { us.Id = model.NewId() us.FileSize = 1024 * 1024 var appErr *model.AppError - us, appErr = th.App.CreateUploadSession(us) + us, appErr = th.App.CreateUploadSession(th.Context, us) require.Nil(t, appErr) require.NotEmpty(t, us) @@ -221,7 +221,7 @@ func TestUploadData(t *testing.T) { us.Filename = "test.png" us.FileSize = int64(len(data)) var appErr *model.AppError - us, appErr = th.App.CreateUploadSession(us) + us, appErr = th.App.CreateUploadSession(th.Context, us) require.Nil(t, appErr) require.NotEmpty(t, us) @@ -241,7 +241,7 @@ func TestUploadData(t *testing.T) { us.Filename = "test.gif" us.FileSize = int64(len(gifData)) var appErr *model.AppError - us, appErr = th.App.CreateUploadSession(us) + us, appErr = th.App.CreateUploadSession(th.Context, us) require.Nil(t, appErr) require.NotEmpty(t, us) @@ -266,7 +266,7 @@ func TestUploadDataConcurrent(t *testing.T) { } var appErr *model.AppError - us, appErr = th.App.CreateUploadSession(us) + us, appErr = th.App.CreateUploadSession(th.Context, us) require.Nil(t, appErr) require.NotEmpty(t, us) diff --git a/app/user.go b/app/user.go index 75aeb4ad3b..89dabb2f82 100644 --- a/app/user.go +++ b/app/user.go @@ -98,7 +98,7 @@ func (a *App) CreateUserWithToken(c *request.Context, user *model.User, token *m return nil, err } - a.AddDirectChannels(team.Id, ruser) + a.AddDirectChannels(c, team.Id, ruser) if token.Type == TokenTypeGuestInvitation || (token.Type == TokenTypeTeamInvitation && len(channels) > 0) { for _, channel := range channels { @@ -151,7 +151,7 @@ func (a *App) CreateUserWithInviteId(c *request.Context, user *model.User, invit return nil, err } - a.AddDirectChannels(team.Id, ruser) + a.AddDirectChannels(c, team.Id, ruser) if err := a.Srv().EmailService.SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.DisableWelcomeEmail, ruser.Locale, a.GetSiteURL(), redirect); err != nil { mlog.Warn("Failed to send welcome email on create user with inviteId", mlog.Err(err)) @@ -367,7 +367,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re return nil, err } - err = a.AddDirectChannels(teamID, user) + err = a.AddDirectChannels(c, teamID, user) if err != nil { mlog.Warn("Failed to add direct channels", mlog.Err(err)) } @@ -905,14 +905,14 @@ func (a *App) userDeactivated(c *request.Context, userID string) *model.AppError return nil } -func (a *App) invalidateUserChannelMembersCaches(userID string) *model.AppError { +func (a *App) invalidateUserChannelMembersCaches(c request.CTX, userID string) *model.AppError { teamsForUser, err := a.GetTeamsForUser(userID) if err != nil { return err } for _, team := range teamsForUser { - channelsForUser, err := a.GetChannelsForTeamForUser(team.Id, userID, &model.ChannelSearchOpts{ + channelsForUser, err := a.GetChannelsForTeamForUser(c, team.Id, userID, &model.ChannelSearchOpts{ IncludeDeleted: false, LastDeleteAt: 0, }) @@ -960,7 +960,7 @@ func (a *App) UpdateActive(c *request.Context, user *model.User, active bool) (* } } - a.invalidateUserChannelMembersCaches(user.Id) + a.invalidateUserChannelMembersCaches(c, user.Id) a.InvalidateCacheForUser(user.Id) a.sendUpdatedUserEvent(*ruser) @@ -2185,7 +2185,7 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor for _, member := range teamMembers { a.sendUpdatedMemberRoleEvent(user.Id, member) - channelMembers, err := a.GetChannelMembersForUser(member.TeamId, user.Id) + channelMembers, err := a.GetChannelMembersForUser(c, member.TeamId, user.Id) if err != nil { mlog.Warn("Failed to get channel members for user on promote guest to user", mlog.Err(err)) } @@ -2209,7 +2209,7 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor // DemoteUserToGuest Convert user's roles and all his membership's roles from // regular user roles to guest roles. -func (a *App) DemoteUserToGuest(user *model.User) *model.AppError { +func (a *App) DemoteUserToGuest(c request.CTX, user *model.User) *model.AppError { demotedUser, nErr := a.ch.srv.userService.DemoteUserToGuest(user) a.InvalidateCacheForUser(user.Id) if nErr != nil { @@ -2229,7 +2229,7 @@ func (a *App) DemoteUserToGuest(user *model.User) *model.AppError { for _, member := range teamMembers { a.sendUpdatedMemberRoleEvent(user.Id, member) - channelMembers, err := a.GetChannelMembersForUser(member.TeamId, user.Id) + channelMembers, err := a.GetChannelMembersForUser(c, member.TeamId, user.Id) if err != nil { mlog.Warn("Failed to get channel members for users on demote user to guest", mlog.Err(err)) continue @@ -2468,7 +2468,7 @@ func (a *App) UpdateThreadFollowForUser(userID, teamID, threadID string, state b return nil } -func (a *App) UpdateThreadFollowForUserFromChannelAdd(userID, teamID, threadID string) *model.AppError { +func (a *App) UpdateThreadFollowForUserFromChannelAdd(c request.CTX, userID, teamID, threadID string) *model.AppError { opts := store.ThreadMembershipOpts{ Following: true, IncrementMentions: false, @@ -2489,7 +2489,7 @@ func (a *App) UpdateThreadFollowForUserFromChannelAdd(userID, teamID, threadID s if appErr != nil { return appErr } - tm.UnreadMentions, appErr = a.countThreadMentions(user, post, teamID, post.CreateAt-1) + tm.UnreadMentions, appErr = a.countThreadMentions(c, user, post, teamID, post.CreateAt-1) if appErr != nil { return appErr } @@ -2510,7 +2510,7 @@ func (a *App) UpdateThreadFollowForUserFromChannelAdd(userID, teamID, threadID s } a.sanitizeProfiles(userThread.Participants, false) userThread.Post.SanitizeProps() - sanitizedPost, appErr := a.SanitizePostMetadataForUser(userThread.Post, userID) + sanitizedPost, appErr := a.SanitizePostMetadataForUser(c, userThread.Post, userID) if appErr != nil { return appErr } @@ -2528,7 +2528,7 @@ func (a *App) UpdateThreadFollowForUserFromChannelAdd(userID, teamID, threadID s return nil } -func (a *App) UpdateThreadReadForUserByPost(currentSessionId, userID, teamID, threadID, postID string) (*model.ThreadResponse, *model.AppError) { +func (a *App) UpdateThreadReadForUserByPost(c request.CTX, currentSessionId, userID, teamID, threadID, postID string) (*model.ThreadResponse, *model.AppError) { post, err := a.GetSinglePost(postID, false) if err != nil { return nil, err @@ -2538,10 +2538,10 @@ func (a *App) UpdateThreadReadForUserByPost(currentSessionId, userID, teamID, th return nil, model.NewAppError("UpdateThreadReadForUser", "app.user.update_thread_read_for_user_by_post.app_error", nil, "", http.StatusBadRequest) } - return a.UpdateThreadReadForUser(currentSessionId, userID, teamID, threadID, post.CreateAt-1) + return a.UpdateThreadReadForUser(c, currentSessionId, userID, teamID, threadID, post.CreateAt-1) } -func (a *App) UpdateThreadReadForUser(currentSessionId, userID, teamID, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError) { +func (a *App) UpdateThreadReadForUser(c request.CTX, currentSessionId, userID, teamID, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError) { user, err := a.GetUser(userID) if err != nil { return nil, err @@ -2566,7 +2566,7 @@ func (a *App) UpdateThreadReadForUser(currentSessionId, userID, teamID, threadID if err != nil { return nil, err } - membership.UnreadMentions, err = a.countThreadMentions(user, post, teamID, timestamp) + membership.UnreadMentions, err = a.countThreadMentions(c, user, post, teamID, timestamp) if err != nil { return nil, err } @@ -2587,7 +2587,7 @@ func (a *App) UpdateThreadReadForUser(currentSessionId, userID, teamID, threadID } // Clear if user has read the messages - if thread.UnreadReplies == 0 && a.IsCRTEnabledForUser(userID) { + if thread.UnreadReplies == 0 && a.IsCRTEnabledForUser(c, userID) { a.clearPushNotification(currentSessionId, userID, post.ChannelId, threadID) } diff --git a/app/user_test.go b/app/user_test.go index 63491c3f53..ad4786e52c 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -914,7 +914,7 @@ func TestCreateUserWithToken(t *testing.T) { _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") - members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newUser.Id) + members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newUser.Id) require.Nil(t, err) assert.Len(t, members, 2) }) @@ -936,7 +936,7 @@ func TestCreateUserWithToken(t *testing.T) { _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") - members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newGuest.Id) + members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newGuest.Id) require.Nil(t, err) require.Len(t, members, 1) assert.Equal(t, members[0].ChannelId, th.BasicChannel.Id) @@ -982,7 +982,7 @@ func TestCreateUserWithToken(t *testing.T) { _, nErr := th.App.Srv().Store.Token().GetByToken(grantedDomainToken.Token) require.Error(t, nErr) - members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newGuest.Id) + members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newGuest.Id) require.Nil(t, err) require.Len(t, members, 1) assert.Equal(t, members[0].ChannelId, th.BasicChannel.Id) @@ -1019,7 +1019,7 @@ func TestCreateUserWithToken(t *testing.T) { _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) require.Error(t, nErr) - members, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, newGuest.Id) + members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newGuest.Id) require.Nil(t, err) require.Len(t, members, 1) assert.Equal(t, members[0].ChannelId, th.BasicChannel.Id) @@ -1149,24 +1149,24 @@ func TestGetViewUsersRestrictions(t *testing.T) { th.App.UpdateTeamMemberRoles(team1.Id, user1.Id, "team_user team_admin") - team1channel1 := th.CreateChannel(team1) - team1channel2 := th.CreateChannel(team1) - th.CreateChannel(team1) // Another channel - team1offtopic, err := th.App.GetChannelByName("off-topic", team1.Id, false) + team1channel1 := th.CreateChannel(th.Context, team1) + team1channel2 := th.CreateChannel(th.Context, team1) + th.CreateChannel(th.Context, team1) // Another channel + team1offtopic, err := th.App.GetChannelByName(th.Context, "off-topic", team1.Id, false) require.Nil(t, err) - team1townsquare, err := th.App.GetChannelByName("town-square", team1.Id, false) + team1townsquare, err := th.App.GetChannelByName(th.Context, "town-square", team1.Id, false) require.Nil(t, err) - team2channel1 := th.CreateChannel(team2) - th.CreateChannel(team2) // Another channel - team2offtopic, err := th.App.GetChannelByName("off-topic", team2.Id, false) + team2channel1 := th.CreateChannel(th.Context, team2) + th.CreateChannel(th.Context, team2) // Another channel + team2offtopic, err := th.App.GetChannelByName(th.Context, "off-topic", team2.Id, false) require.Nil(t, err) - team2townsquare, err := th.App.GetChannelByName("town-square", team2.Id, false) + team2townsquare, err := th.App.GetChannelByName(th.Context, "town-square", team2.Id, false) require.Nil(t, err) - th.App.AddUserToChannel(user1, team1channel1, false) - th.App.AddUserToChannel(user1, team1channel2, false) - th.App.AddUserToChannel(user1, team2channel1, false) + th.App.AddUserToChannel(th.Context, user1, team1channel1, false) + th.App.AddUserToChannel(th.Context, user1, team1channel2, false) + th.App.AddUserToChannel(th.Context, user1, team2channel1, false) addPermission := func(role *model.Role, permission string) *model.AppError { newPermissions := append(role.Permissions, permission) @@ -1317,7 +1317,7 @@ func TestPromoteGuestToUser(t *testing.T) { assert.Nil(t, err) assert.False(t, teamMember.SchemeGuest) assert.True(t, teamMember.SchemeUser) - _, err = th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, guest.Id) + _, err = th.App.GetChannelMember(th.Context, th.BasicChannel.Id, guest.Id) assert.Nil(t, err) assert.False(t, teamMember.SchemeGuest) assert.True(t, teamMember.SchemeUser) @@ -1336,7 +1336,7 @@ func TestPromoteGuestToUser(t *testing.T) { require.True(t, channelMember.SchemeGuest) require.False(t, channelMember.SchemeUser) - channelMembers, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, guest.Id) + channelMembers, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, guest.Id) require.Nil(t, err) require.Len(t, channelMembers, 1) @@ -1349,12 +1349,12 @@ func TestPromoteGuestToUser(t *testing.T) { assert.Nil(t, err) assert.False(t, teamMember.SchemeGuest) assert.True(t, teamMember.SchemeUser) - _, err = th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, guest.Id) + _, err = th.App.GetChannelMember(th.Context, th.BasicChannel.Id, guest.Id) assert.Nil(t, err) assert.False(t, teamMember.SchemeGuest) assert.True(t, teamMember.SchemeUser) - channelMembers, err = th.App.GetChannelMembersForUser(th.BasicTeam.Id, guest.Id) + channelMembers, err = th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, guest.Id) require.Nil(t, err) assert.Len(t, channelMembers, 3) }) @@ -1368,20 +1368,20 @@ func TestPromoteGuestToUser(t *testing.T) { require.True(t, teamMember.SchemeGuest) require.False(t, teamMember.SchemeUser) - guestCount, _ := th.App.GetChannelGuestCount(th.BasicChannel.Id) + guestCount, _ := th.App.GetChannelGuestCount(th.Context, th.BasicChannel.Id) require.Equal(t, int64(0), guestCount) channelMember := th.AddUserToChannel(guest, th.BasicChannel) require.True(t, channelMember.SchemeGuest) require.False(t, channelMember.SchemeUser) - guestCount, _ = th.App.GetChannelGuestCount(th.BasicChannel.Id) + guestCount, _ = th.App.GetChannelGuestCount(th.Context, th.BasicChannel.Id) require.Equal(t, int64(1), guestCount) err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id) require.Nil(t, err) - guestCount, _ = th.App.GetChannelGuestCount(th.BasicChannel.Id) + guestCount, _ = th.App.GetChannelGuestCount(th.Context, th.BasicChannel.Id) require.Equal(t, int64(0), guestCount) }) } @@ -1399,27 +1399,27 @@ func TestDemoteUserToGuest(t *testing.T) { require.True(t, teamMember.SchemeUser) require.False(t, teamMember.SchemeGuest) - guestCount, _ := th.App.GetChannelGuestCount(th.BasicChannel.Id) + guestCount, _ := th.App.GetChannelGuestCount(th.Context, th.BasicChannel.Id) require.Equal(t, int64(0), guestCount) channelMember := th.AddUserToChannel(user, th.BasicChannel) require.True(t, channelMember.SchemeUser) require.False(t, channelMember.SchemeGuest) - guestCount, _ = th.App.GetChannelGuestCount(th.BasicChannel.Id) + guestCount, _ = th.App.GetChannelGuestCount(th.Context, th.BasicChannel.Id) require.Equal(t, int64(0), guestCount) - err = th.App.DemoteUserToGuest(user) + err = th.App.DemoteUserToGuest(th.Context, user) require.Nil(t, err) - guestCount, _ = th.App.GetChannelGuestCount(th.BasicChannel.Id) + guestCount, _ = th.App.GetChannelGuestCount(th.Context, th.BasicChannel.Id) require.Equal(t, int64(1), guestCount) }) t.Run("Must fail with guest user", func(t *testing.T) { guest := th.CreateGuest() require.Equal(t, "system_guest", guest.Roles) - err := th.App.DemoteUserToGuest(guest) + err := th.App.DemoteUserToGuest(th.Context, guest) require.Nil(t, err) user, err := th.App.GetUser(guest.Id) @@ -1431,7 +1431,7 @@ func TestDemoteUserToGuest(t *testing.T) { user := th.CreateUser() require.Equal(t, "system_user", user.Roles) - err := th.App.DemoteUserToGuest(user) + err := th.App.DemoteUserToGuest(th.Context, user) require.Nil(t, err) user, err = th.App.GetUser(user.Id) assert.Nil(t, err) @@ -1447,7 +1447,7 @@ func TestDemoteUserToGuest(t *testing.T) { require.True(t, teamMember.SchemeUser) require.False(t, teamMember.SchemeGuest) - err = th.App.DemoteUserToGuest(user) + err = th.App.DemoteUserToGuest(th.Context, user) require.Nil(t, err) user, err = th.App.GetUser(user.Id) assert.Nil(t, err) @@ -1471,7 +1471,7 @@ func TestDemoteUserToGuest(t *testing.T) { require.True(t, channelMember.SchemeUser) require.False(t, channelMember.SchemeGuest) - err = th.App.DemoteUserToGuest(user) + err = th.App.DemoteUserToGuest(th.Context, user) require.Nil(t, err) user, err = th.App.GetUser(user.Id) assert.Nil(t, err) @@ -1480,7 +1480,7 @@ func TestDemoteUserToGuest(t *testing.T) { assert.Nil(t, err) assert.False(t, teamMember.SchemeUser) assert.True(t, teamMember.SchemeGuest) - _, err = th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, user.Id) + _, err = th.App.GetChannelMember(th.Context, th.BasicChannel.Id, user.Id) assert.Nil(t, err) assert.False(t, teamMember.SchemeUser) assert.True(t, teamMember.SchemeGuest) @@ -1499,11 +1499,11 @@ func TestDemoteUserToGuest(t *testing.T) { require.True(t, channelMember.SchemeUser) require.False(t, channelMember.SchemeGuest) - channelMembers, err := th.App.GetChannelMembersForUser(th.BasicTeam.Id, user.Id) + channelMembers, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, user.Id) require.Nil(t, err) require.Len(t, channelMembers, 3) - err = th.App.DemoteUserToGuest(user) + err = th.App.DemoteUserToGuest(th.Context, user) require.Nil(t, err) user, err = th.App.GetUser(user.Id) assert.Nil(t, err) @@ -1512,12 +1512,12 @@ func TestDemoteUserToGuest(t *testing.T) { assert.Nil(t, err) assert.False(t, teamMember.SchemeUser) assert.True(t, teamMember.SchemeGuest) - _, err = th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, user.Id) + _, err = th.App.GetChannelMember(th.Context, th.BasicChannel.Id, user.Id) assert.Nil(t, err) assert.False(t, teamMember.SchemeUser) assert.True(t, teamMember.SchemeGuest) - channelMembers, err = th.App.GetChannelMembersForUser(th.BasicTeam.Id, user.Id) + channelMembers, err = th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, user.Id) require.Nil(t, err) assert.Len(t, channelMembers, 3) }) @@ -1537,18 +1537,18 @@ func TestDemoteUserToGuest(t *testing.T) { require.True(t, teamMember.SchemeAdmin) require.False(t, teamMember.SchemeGuest) - channel := th.CreateChannel(team) + channel := th.CreateChannel(th.Context, team) th.AddUserToChannel(user, channel) - th.App.UpdateChannelMemberSchemeRoles(channel.Id, user.Id, false, true, true) + th.App.UpdateChannelMemberSchemeRoles(th.Context, channel.Id, user.Id, false, true, true) - channelMember, err := th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, err := th.App.GetChannelMember(th.Context, channel.Id, user.Id) assert.Nil(t, err) assert.True(t, channelMember.SchemeUser) assert.True(t, channelMember.SchemeAdmin) assert.False(t, channelMember.SchemeGuest) - err = th.App.DemoteUserToGuest(user) + err = th.App.DemoteUserToGuest(th.Context, user) require.Nil(t, err) user, err = th.App.GetUser(user.Id) @@ -1561,7 +1561,7 @@ func TestDemoteUserToGuest(t *testing.T) { assert.False(t, teamMember.SchemeAdmin) assert.True(t, teamMember.SchemeGuest) - channelMember, err = th.App.GetChannelMember(context.Background(), channel.Id, user.Id) + channelMember, err = th.App.GetChannelMember(th.Context, channel.Id, user.Id) assert.Nil(t, err) assert.False(t, channelMember.SchemeUser) assert.False(t, channelMember.SchemeAdmin) @@ -1682,7 +1682,7 @@ func TestUpdateThreadReadForUser(t *testing.T) { require.Nil(t, appErr) require.Zero(t, threads.Total) - _, appErr = th.App.UpdateThreadReadForUser("currentSessionId", th.BasicUser.Id, th.BasicChannel.TeamId, rootPost.Id, replyPost.CreateAt) + _, appErr = th.App.UpdateThreadReadForUser(th.Context, "currentSessionId", th.BasicUser.Id, th.BasicChannel.TeamId, rootPost.Id, replyPost.CreateAt) require.Nil(t, appErr) threads, appErr = th.App.GetThreadsForUser(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{}) @@ -1719,7 +1719,7 @@ func TestUpdateThreadReadForUser(t *testing.T) { mockStore.On("User").Return(&mockUserStore) mockStore.On("Thread").Return(&mockThreadStore) - _, err = th.App.UpdateThreadReadForUser("currentSessionId", "user1", "team1", "postid", 100) + _, err = th.App.UpdateThreadReadForUser(th.Context, "currentSessionId", "user1", "team1", "postid", 100) require.Error(t, err) }) } diff --git a/app/user_viewmembers_test.go b/app/user_viewmembers_test.go index 26a11fc7b0..1c3e4309aa 100644 --- a/app/user_viewmembers_test.go +++ b/app/user_viewmembers_test.go @@ -44,9 +44,9 @@ func TestRestrictedViewMembers(t *testing.T) { team1 := th.CreateTeam() team2 := th.CreateTeam() - channel1 := th.CreateChannel(team1) - channel2 := th.CreateChannel(team1) - channel3 := th.CreateChannel(team2) + channel1 := th.CreateChannel(th.Context, team1) + channel2 := th.CreateChannel(th.Context, team1) + channel3 := th.CreateChannel(th.Context, team2) th.LinkUserToTeam(user1, team1) th.LinkUserToTeam(user2, team1) diff --git a/app/web_conn_test.go b/app/web_conn_test.go index 5fdcb29ee8..67c9306b7c 100644 --- a/app/web_conn_test.go +++ b/app/web_conn_test.go @@ -103,7 +103,7 @@ func TestWebConnShouldSendEvent(t *testing.T) { th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam) // Create another channel with just BasicUser (implicitly) and SystemAdminUser to test channel broadcast - channel2 := th.CreateChannel(th.BasicTeam) + channel2 := th.CreateChannel(th.Context, th.BasicTeam) th.AddUserToChannel(th.SystemAdminUser, channel2) cases := []struct { diff --git a/app/webhook.go b/app/webhook.go index 95794aa26e..37e68fd544 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -28,7 +28,7 @@ const ( MaxIntegrationResponseSize = 1024 * 1024 // Posts can be <100KB at most, so this is likely more than enough ) -func (a *App) handleWebhookEvents(c *request.Context, post *model.Post, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { +func (a *App) handleWebhookEvents(c request.CTX, post *model.Post, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { if !*a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil } @@ -94,7 +94,7 @@ func (a *App) handleWebhookEvents(c *request.Context, post *model.Post, team *mo return nil } -func (a *App) TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { +func (a *App) TriggerWebhook(c request.CTX, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { var body io.Reader var contentType string if hook.ContentType == "application/json" { @@ -262,7 +262,7 @@ func SplitWebhookPost(post *model.Post, maxPostSize int) ([]*model.Post, *model. return splits, nil } -func (a *App) CreateWebhookPost(c *request.Context, userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { +func (a *App) CreateWebhookPost(c request.CTX, userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError) { // parse links into Markdown format linkWithTextRegex := regexp.MustCompile(`<([^\n<\|>]+)\|([^\n>]+)>`) text = linkWithTextRegex.ReplaceAllString(text, "[${2}](${1})") @@ -514,13 +514,13 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin return webhook, nil } -func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { +func (a *App) UpdateOutgoingWebhook(c request.CTX, oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { if !*a.Config().ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("UpdateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } if updatedHook.ChannelId != "" { - channel, err := a.GetChannel(updatedHook.ChannelId) + channel, err := a.GetChannel(c, updatedHook.ChannelId) if err != nil { return nil, err } @@ -775,7 +775,7 @@ func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *mode return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.user.app_error", nil, result.NErr.Error(), http.StatusForbidden) } - if channel.Type != model.ChannelTypeOpen && !a.HasPermissionToChannel(hook.UserId, channel.Id, model.PermissionReadChannel) { + if channel.Type != model.ChannelTypeOpen && !a.HasPermissionToChannel(c, hook.UserId, channel.Id, model.PermissionReadChannel) { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.permissions.app_error", nil, "", http.StatusForbidden) } diff --git a/app/webhook_test.go b/app/webhook_test.go index d307eba373..f0a1249172 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -681,7 +681,7 @@ func TestTriggerOutGoingWebhookWithUsernameAndIconURL(t *testing.T) { })) defer ts.Close() - channel := th.CreateChannel(th.BasicTeam) + channel := th.CreateChannel(th.Context, th.BasicTeam) hook, _ := createOutgoingWebhook(channel, ts.URL, th) payload := getPayload(hook, th, channel) diff --git a/services/sharedchannel/attachment.go b/services/sharedchannel/attachment.go index aec5d311f0..6b40dd7e1e 100644 --- a/services/sharedchannel/attachment.go +++ b/services/sharedchannel/attachment.go @@ -10,6 +10,7 @@ import ( "fmt" "sync" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/services/remotecluster" "github.com/mattermost/mattermost-server/v6/shared/mlog" @@ -156,7 +157,7 @@ func (scs *Service) onReceiveUploadCreate(msg model.RemoteClusterMsg, rc *model. us.RemoteId = rc.RemoteId // don't let remotes try to impersonate each other // create upload session. - usSaved, appErr := scs.app.CreateUploadSession(&us) + usSaved, appErr := scs.app.CreateUploadSession(request.EmptyContext(scs.server.GetLogger()), &us) if appErr != nil { return appErr } diff --git a/services/sharedchannel/channelinvite.go b/services/sharedchannel/channelinvite.go index 0ac7e0df64..5c204c3d6a 100644 --- a/services/sharedchannel/channelinvite.go +++ b/services/sharedchannel/channelinvite.go @@ -158,7 +158,7 @@ func (scs *Service) onReceiveChannelInvite(msg model.RemoteClusterMsg, rc *model } if _, err := scs.server.GetStore().SharedChannel().Save(sharedChannel); err != nil { - scs.app.PermanentDeleteChannel(channel) + scs.app.PermanentDeleteChannel(request.EmptyContext(scs.server.GetLogger()), channel) return fmt.Errorf("cannot create shared channel (channel_id=%s): %w", invite.ChannelId, err) } @@ -172,7 +172,7 @@ func (scs *Service) onReceiveChannelInvite(msg model.RemoteClusterMsg, rc *model } if _, err := scs.server.GetStore().SharedChannel().SaveRemote(sharedChannelRemote); err != nil { - scs.app.PermanentDeleteChannel(channel) + scs.app.PermanentDeleteChannel(request.EmptyContext(scs.server.GetLogger()), channel) scs.server.GetStore().SharedChannel().Delete(sharedChannel.ChannelId) return fmt.Errorf("cannot create shared channel remote (channel_id=%s): %w", invite.ChannelId, err) } @@ -197,7 +197,7 @@ func (scs *Service) handleChannelCreation(invite channelInviteMsg, rc *model.Rem } // check user perms? - channel, appErr := scs.app.CreateChannelWithUser(request.EmptyContext(), channelNew, rc.CreatorId) + channel, appErr := scs.app.CreateChannelWithUser(request.EmptyContext(scs.server.GetLogger()), channelNew, rc.CreatorId) if appErr != nil { return nil, fmt.Errorf("cannot create channel `%s`: %w", invite.ChannelId, appErr) } @@ -210,7 +210,7 @@ func (scs *Service) createDirectChannel(invite channelInviteMsg) (*model.Channel return nil, fmt.Errorf("cannot create direct channel `%s` insufficient participant count `%d`", invite.ChannelId, len(invite.DirectParticipantIDs)) } - channel, err := scs.app.GetOrCreateDirectChannel(request.EmptyContext(), invite.DirectParticipantIDs[0], invite.DirectParticipantIDs[1], model.WithID(invite.ChannelId)) + channel, err := scs.app.GetOrCreateDirectChannel(request.EmptyContext(scs.server.GetLogger()), invite.DirectParticipantIDs[0], invite.DirectParticipantIDs[1], model.WithID(invite.ChannelId)) if err != nil { return nil, fmt.Errorf("cannot create direct channel `%s`: %w", invite.ChannelId, err) } diff --git a/services/sharedchannel/channelinvite_test.go b/services/sharedchannel/channelinvite_test.go index d1ee9978ad..485cc3ac54 100644 --- a/services/sharedchannel/channelinvite_test.go +++ b/services/sharedchannel/channelinvite_test.go @@ -101,7 +101,7 @@ func TestOnReceiveChannelInvite(t *testing.T) { Roles: &updateMap, }, } - mockApp.On("PatchChannelModerationsForChannel", channel, readonlyChannelModerations).Return(nil, nil) + mockApp.On("PatchChannelModerationsForChannel", mock.Anything, channel, readonlyChannelModerations).Return(nil, nil) defer mockApp.AssertExpectations(t) err = scs.onReceiveChannelInvite(msg, remoteCluster, nil) @@ -142,7 +142,7 @@ func TestOnReceiveChannelInvite(t *testing.T) { mockServer.On("GetStore").Return(mockStore) appErr := model.NewAppError("foo", "bar", nil, "boom", http.StatusBadRequest) - mockApp.On("PatchChannelModerationsForChannel", channel, mock.Anything).Return(nil, appErr) + mockApp.On("PatchChannelModerationsForChannel", mock.Anything, channel, mock.Anything).Return(nil, appErr) defer mockApp.AssertExpectations(t) err = scs.onReceiveChannelInvite(msg, remoteCluster, nil) diff --git a/services/sharedchannel/mock_AppIface_test.go b/services/sharedchannel/mock_AppIface_test.go index 75b3f810b4..2a3613cad2 100644 --- a/services/sharedchannel/mock_AppIface_test.go +++ b/services/sharedchannel/mock_AppIface_test.go @@ -18,13 +18,13 @@ type MockAppIface struct { mock.Mock } -// AddUserToChannel provides a mock function with given fields: user, channel, skipTeamMemberIntegrityCheck -func (_m *MockAppIface) AddUserToChannel(user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) { - ret := _m.Called(user, channel, skipTeamMemberIntegrityCheck) +// AddUserToChannel provides a mock function with given fields: c, user, channel, skipTeamMemberIntegrityCheck +func (_m *MockAppIface) AddUserToChannel(c request.CTX, user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) { + ret := _m.Called(c, user, channel, skipTeamMemberIntegrityCheck) var r0 *model.ChannelMember - if rf, ok := ret.Get(0).(func(*model.User, *model.Channel, bool) *model.ChannelMember); ok { - r0 = rf(user, channel, skipTeamMemberIntegrityCheck) + if rf, ok := ret.Get(0).(func(request.CTX, *model.User, *model.Channel, bool) *model.ChannelMember); ok { + r0 = rf(c, user, channel, skipTeamMemberIntegrityCheck) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.ChannelMember) @@ -32,8 +32,8 @@ func (_m *MockAppIface) AddUserToChannel(user *model.User, channel *model.Channe } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*model.User, *model.Channel, bool) *model.AppError); ok { - r1 = rf(user, channel, skipTeamMemberIntegrityCheck) + if rf, ok := ret.Get(1).(func(request.CTX, *model.User, *model.Channel, bool) *model.AppError); ok { + r1 = rf(c, user, channel, skipTeamMemberIntegrityCheck) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -60,11 +60,11 @@ func (_m *MockAppIface) AddUserToTeamByTeamId(c *request.Context, teamId string, } // CreateChannelWithUser provides a mock function with given fields: c, channel, userId -func (_m *MockAppIface) CreateChannelWithUser(c *request.Context, channel *model.Channel, userId string) (*model.Channel, *model.AppError) { +func (_m *MockAppIface) CreateChannelWithUser(c request.CTX, channel *model.Channel, userId string) (*model.Channel, *model.AppError) { ret := _m.Called(c, channel, userId) var r0 *model.Channel - if rf, ok := ret.Get(0).(func(*request.Context, *model.Channel, string) *model.Channel); ok { + if rf, ok := ret.Get(0).(func(request.CTX, *model.Channel, string) *model.Channel); ok { r0 = rf(c, channel, userId) } else { if ret.Get(0) != nil { @@ -73,7 +73,7 @@ func (_m *MockAppIface) CreateChannelWithUser(c *request.Context, channel *model } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*request.Context, *model.Channel, string) *model.AppError); ok { + if rf, ok := ret.Get(1).(func(request.CTX, *model.Channel, string) *model.AppError); ok { r1 = rf(c, channel, userId) } else { if ret.Get(1) != nil { @@ -85,11 +85,11 @@ func (_m *MockAppIface) CreateChannelWithUser(c *request.Context, channel *model } // CreatePost provides a mock function with given fields: c, post, channel, triggerWebhooks, setOnline -func (_m *MockAppIface) CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (*model.Post, *model.AppError) { +func (_m *MockAppIface) CreatePost(c request.CTX, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (*model.Post, *model.AppError) { ret := _m.Called(c, post, channel, triggerWebhooks, setOnline) var r0 *model.Post - if rf, ok := ret.Get(0).(func(*request.Context, *model.Post, *model.Channel, bool, bool) *model.Post); ok { + if rf, ok := ret.Get(0).(func(request.CTX, *model.Post, *model.Channel, bool, bool) *model.Post); ok { r0 = rf(c, post, channel, triggerWebhooks, setOnline) } else { if ret.Get(0) != nil { @@ -98,7 +98,7 @@ func (_m *MockAppIface) CreatePost(c *request.Context, post *model.Post, channel } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*request.Context, *model.Post, *model.Channel, bool, bool) *model.AppError); ok { + if rf, ok := ret.Get(1).(func(request.CTX, *model.Post, *model.Channel, bool, bool) *model.AppError); ok { r1 = rf(c, post, channel, triggerWebhooks, setOnline) } else { if ret.Get(1) != nil { @@ -109,13 +109,13 @@ func (_m *MockAppIface) CreatePost(c *request.Context, post *model.Post, channel return r0, r1 } -// CreateUploadSession provides a mock function with given fields: us -func (_m *MockAppIface) CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) { - ret := _m.Called(us) +// CreateUploadSession provides a mock function with given fields: c, us +func (_m *MockAppIface) CreateUploadSession(c request.CTX, us *model.UploadSession) (*model.UploadSession, *model.AppError) { + ret := _m.Called(c, us) var r0 *model.UploadSession - if rf, ok := ret.Get(0).(func(*model.UploadSession) *model.UploadSession); ok { - r0 = rf(us) + if rf, ok := ret.Get(0).(func(request.CTX, *model.UploadSession) *model.UploadSession); ok { + r0 = rf(c, us) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.UploadSession) @@ -123,8 +123,8 @@ func (_m *MockAppIface) CreateUploadSession(us *model.UploadSession) (*model.Upl } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*model.UploadSession) *model.AppError); ok { - r1 = rf(us) + if rf, ok := ret.Get(1).(func(request.CTX, *model.UploadSession) *model.AppError); ok { + r1 = rf(c, us) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -134,13 +134,13 @@ func (_m *MockAppIface) CreateUploadSession(us *model.UploadSession) (*model.Upl return r0, r1 } -// DeletePost provides a mock function with given fields: postID, deleteByID -func (_m *MockAppIface) DeletePost(postID string, deleteByID string) (*model.Post, *model.AppError) { - ret := _m.Called(postID, deleteByID) +// DeletePost provides a mock function with given fields: c, postID, deleteByID +func (_m *MockAppIface) DeletePost(c request.CTX, postID string, deleteByID string) (*model.Post, *model.AppError) { + ret := _m.Called(c, postID, deleteByID) var r0 *model.Post - if rf, ok := ret.Get(0).(func(string, string) *model.Post); ok { - r0 = rf(postID, deleteByID) + if rf, ok := ret.Get(0).(func(request.CTX, string, string) *model.Post); ok { + r0 = rf(c, postID, deleteByID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Post) @@ -148,8 +148,8 @@ func (_m *MockAppIface) DeletePost(postID string, deleteByID string) (*model.Pos } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(string, string) *model.AppError); ok { - r1 = rf(postID, deleteByID) + if rf, ok := ret.Get(1).(func(request.CTX, string, string) *model.AppError); ok { + r1 = rf(c, postID, deleteByID) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -201,7 +201,7 @@ func (_m *MockAppIface) FileReader(path string) (filestore.ReadCloseSeeker, *mod } // GetOrCreateDirectChannel provides a mock function with given fields: c, userId, otherUserId, channelOptions -func (_m *MockAppIface) GetOrCreateDirectChannel(c *request.Context, userId string, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { +func (_m *MockAppIface) GetOrCreateDirectChannel(c request.CTX, userId string, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { _va := make([]interface{}, len(channelOptions)) for _i := range channelOptions { _va[_i] = channelOptions[_i] @@ -212,7 +212,7 @@ func (_m *MockAppIface) GetOrCreateDirectChannel(c *request.Context, userId stri ret := _m.Called(_ca...) var r0 *model.Channel - if rf, ok := ret.Get(0).(func(*request.Context, string, string, ...model.ChannelOption) *model.Channel); ok { + if rf, ok := ret.Get(0).(func(request.CTX, string, string, ...model.ChannelOption) *model.Channel); ok { r0 = rf(c, userId, otherUserId, channelOptions...) } else { if ret.Get(0) != nil { @@ -221,7 +221,7 @@ func (_m *MockAppIface) GetOrCreateDirectChannel(c *request.Context, userId stri } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*request.Context, string, string, ...model.ChannelOption) *model.AppError); ok { + if rf, ok := ret.Get(1).(func(request.CTX, string, string, ...model.ChannelOption) *model.AppError); ok { r1 = rf(c, userId, otherUserId, channelOptions...) } else { if ret.Get(1) != nil { @@ -290,13 +290,13 @@ func (_m *MockAppIface) NotifySharedChannelUserUpdate(user *model.User) { _m.Called(user) } -// PatchChannelModerationsForChannel provides a mock function with given fields: channel, channelModerationsPatch -func (_m *MockAppIface) PatchChannelModerationsForChannel(channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) { - ret := _m.Called(channel, channelModerationsPatch) +// PatchChannelModerationsForChannel provides a mock function with given fields: c, channel, channelModerationsPatch +func (_m *MockAppIface) PatchChannelModerationsForChannel(c request.CTX, channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) { + ret := _m.Called(c, channel, channelModerationsPatch) var r0 []*model.ChannelModeration - if rf, ok := ret.Get(0).(func(*model.Channel, []*model.ChannelModerationPatch) []*model.ChannelModeration); ok { - r0 = rf(channel, channelModerationsPatch) + if rf, ok := ret.Get(0).(func(request.CTX, *model.Channel, []*model.ChannelModerationPatch) []*model.ChannelModeration); ok { + r0 = rf(c, channel, channelModerationsPatch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*model.ChannelModeration) @@ -304,8 +304,8 @@ func (_m *MockAppIface) PatchChannelModerationsForChannel(channel *model.Channel } var r1 *model.AppError - if rf, ok := ret.Get(1).(func(*model.Channel, []*model.ChannelModerationPatch) *model.AppError); ok { - r1 = rf(channel, channelModerationsPatch) + if rf, ok := ret.Get(1).(func(request.CTX, *model.Channel, []*model.ChannelModerationPatch) *model.AppError); ok { + r1 = rf(c, channel, channelModerationsPatch) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*model.AppError) @@ -315,13 +315,13 @@ func (_m *MockAppIface) PatchChannelModerationsForChannel(channel *model.Channel return r0, r1 } -// PermanentDeleteChannel provides a mock function with given fields: channel -func (_m *MockAppIface) PermanentDeleteChannel(channel *model.Channel) *model.AppError { - ret := _m.Called(channel) +// PermanentDeleteChannel provides a mock function with given fields: c, channel +func (_m *MockAppIface) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *model.AppError { + ret := _m.Called(c, channel) var r0 *model.AppError - if rf, ok := ret.Get(0).(func(*model.Channel) *model.AppError); ok { - r0 = rf(channel) + if rf, ok := ret.Get(0).(func(request.CTX, *model.Channel) *model.AppError); ok { + r0 = rf(c, channel) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.AppError) @@ -356,13 +356,13 @@ func (_m *MockAppIface) SaveReactionForPost(c *request.Context, reaction *model. return r0, r1 } -// SendEphemeralPost provides a mock function with given fields: userId, post -func (_m *MockAppIface) SendEphemeralPost(userId string, post *model.Post) *model.Post { - ret := _m.Called(userId, post) +// SendEphemeralPost provides a mock function with given fields: c, userId, post +func (_m *MockAppIface) SendEphemeralPost(c request.CTX, userId string, post *model.Post) *model.Post { + ret := _m.Called(c, userId, post) var r0 *model.Post - if rf, ok := ret.Get(0).(func(string, *model.Post) *model.Post); ok { - r0 = rf(userId, post) + if rf, ok := ret.Get(0).(func(request.CTX, string, *model.Post) *model.Post); ok { + r0 = rf(c, userId, post) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*model.Post) diff --git a/services/sharedchannel/permalink_test.go b/services/sharedchannel/permalink_test.go index 27d858abae..05b1789b2f 100644 --- a/services/sharedchannel/permalink_test.go +++ b/services/sharedchannel/permalink_test.go @@ -12,6 +12,7 @@ import ( "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/plugin/plugintest/mock" + "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store/storetest/mocks" "github.com/mattermost/mattermost-server/v6/utils" ) @@ -33,9 +34,10 @@ func TestProcessPermalinkToRemote(t *testing.T) { mockServer := scs.server.(*MockServerIface) mockServer.On("GetStore").Return(mockStore) + mockServer.On("GetLogger").Return(mlog.NewLogger()) mockApp := scs.app.(*MockAppIface) - mockApp.On("SendEphemeralPost", "user", mock.AnythingOfType("*model.Post")).Return(&model.Post{}).Times(1) + mockApp.On("SendEphemeralPost", mock.Anything, "user", mock.AnythingOfType("*model.Post")).Return(&model.Post{}).Times(1) defer mockApp.AssertExpectations(t) t.Run("same channel", func(t *testing.T) { diff --git a/services/sharedchannel/service.go b/services/sharedchannel/service.go index 8c7c4115c0..c8af3c02a1 100644 --- a/services/sharedchannel/service.go +++ b/services/sharedchannel/service.go @@ -45,19 +45,19 @@ type ServerIface interface { } type AppIface interface { - SendEphemeralPost(userId string, post *model.Post) *model.Post - CreateChannelWithUser(c *request.Context, channel *model.Channel, userId string) (*model.Channel, *model.AppError) - GetOrCreateDirectChannel(c *request.Context, userId, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) - AddUserToChannel(user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) + SendEphemeralPost(c request.CTX, userId string, post *model.Post) *model.Post + CreateChannelWithUser(c request.CTX, channel *model.Channel, userId string) (*model.Channel, *model.AppError) + GetOrCreateDirectChannel(c request.CTX, userId, otherUserId string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) + AddUserToChannel(c request.CTX, user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) AddUserToTeamByTeamId(c *request.Context, teamId string, user *model.User) *model.AppError - PermanentDeleteChannel(channel *model.Channel) *model.AppError - CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) + PermanentDeleteChannel(c request.CTX, channel *model.Channel) *model.AppError + CreatePost(c request.CTX, post *model.Post, channel *model.Channel, triggerWebhooks bool, setOnline bool) (savedPost *model.Post, err *model.AppError) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) - DeletePost(postID, deleteByID string) (*model.Post, *model.AppError) + DeletePost(c request.CTX, postID, deleteByID string) (*model.Post, *model.AppError) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError - PatchChannelModerationsForChannel(channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) - CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError) + PatchChannelModerationsForChannel(c request.CTX, channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError) + CreateUploadSession(c request.CTX, us *model.UploadSession) (*model.UploadSession, *model.AppError) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) MentionsToTeamMembers(message, teamID string) model.UserMentionMap GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) @@ -166,7 +166,7 @@ func (scs *Service) sendEphemeralPost(channelId string, userId string, text stri Message: text, CreateAt: model.GetMillis(), } - scs.app.SendEphemeralPost(userId, ephemeral) + scs.app.SendEphemeralPost(request.EmptyContext(scs.server.GetLogger()), userId, ephemeral) } // onClusterLeaderChange is called whenever the cluster leader may have changed. @@ -229,7 +229,7 @@ func (scs *Service) makeChannelReadOnly(channel *model.Channel) *model.AppError }, } - _, err := scs.app.PatchChannelModerationsForChannel(channel, readonlyChannelModerations) + _, err := scs.app.PatchChannelModerationsForChannel(request.EmptyContext(scs.server.GetLogger()), channel, readonlyChannelModerations) return err } diff --git a/services/sharedchannel/sync_recv.go b/services/sharedchannel/sync_recv.go index f8618f3dda..1e1fefae7f 100644 --- a/services/sharedchannel/sync_recv.go +++ b/services/sharedchannel/sync_recv.go @@ -38,10 +38,10 @@ func (scs *Service) onReceiveSyncMessage(msg model.RemoteClusterMsg, rc *model.R if err := json.Unmarshal(msg.Payload, &sm); err != nil { return fmt.Errorf("invalid sync message: %w", err) } - return scs.processSyncMessage(&sm, rc, response) + return scs.processSyncMessage(request.EmptyContext(scs.server.GetLogger()), &sm, rc, response) } -func (scs *Service) processSyncMessage(syncMsg *syncMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { +func (scs *Service) processSyncMessage(c request.CTX, syncMsg *syncMsg, rc *model.RemoteCluster, response *remotecluster.Response) error { var channel *model.Channel var team *model.Team @@ -68,7 +68,7 @@ func (scs *Service) processSyncMessage(syncMsg *syncMsg, rc *model.RemoteCluster // add/update users before posts for _, user := range syncMsg.Users { - if userSaved, err := scs.upsertSyncUser(user, channel, rc); err != nil { + if userSaved, err := scs.upsertSyncUser(c, user, channel, rc); err != nil { scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceError, "Error upserting sync user", mlog.String("remote", rc.Name), mlog.String("channel_id", syncMsg.ChannelId), @@ -165,7 +165,7 @@ func (scs *Service) processSyncMessage(syncMsg *syncMsg, rc *model.RemoteCluster return nil } -func (scs *Service) upsertSyncUser(user *model.User, channel *model.Channel, rc *model.RemoteCluster) (*model.User, error) { +func (scs *Service) upsertSyncUser(c request.CTX, user *model.User, channel *model.Channel, rc *model.RemoteCluster) (*model.User, error) { var err error if user.RemoteId == nil || *user.RemoteId == "" { user.RemoteId = model.NewString(rc.RemoteId) @@ -208,12 +208,12 @@ func (scs *Service) upsertSyncUser(user *model.User, channel *model.Channel, rc // Instead of undoing what succeeded on any failure we simply do all steps each // time. AddUserToChannel & AddUserToTeamByTeamId do not error if user was already // added and exit quickly. - if err := scs.app.AddUserToTeamByTeamId(request.EmptyContext(), channel.TeamId, userSaved); err != nil { + if err := scs.app.AddUserToTeamByTeamId(request.EmptyContext(scs.server.GetLogger()), channel.TeamId, userSaved); err != nil { return nil, fmt.Errorf("error adding sync user to Team: %w", err) } // add user to channel - if _, err := scs.app.AddUserToChannel(userSaved, channel, false); err != nil { + if _, err := scs.app.AddUserToChannel(c, userSaved, channel, false); err != nil { return nil, fmt.Errorf("error adding sync user to ChannelMembers: %w", err) } return userSaved, nil @@ -339,7 +339,7 @@ func (scs *Service) upsertSyncPost(post *model.Post, channel *model.Channel, rc if rpost == nil { // post doesn't exist; create new one - rpost, appErr = scs.app.CreatePost(request.EmptyContext(), post, channel, true, true) + rpost, appErr = scs.app.CreatePost(request.EmptyContext(scs.server.GetLogger()), post, channel, true, true) if appErr == nil { scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceDebug, "Created sync post", mlog.String("post_id", post.Id), @@ -348,7 +348,7 @@ func (scs *Service) upsertSyncPost(post *model.Post, channel *model.Channel, rc } } else if post.DeleteAt > 0 { // delete post - rpost, appErr = scs.app.DeletePost(post.Id, post.UserId) + rpost, appErr = scs.app.DeletePost(request.EmptyContext(scs.server.GetLogger()), post.Id, post.UserId) if appErr == nil { scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceDebug, "Deleted sync post", mlog.String("post_id", post.Id), @@ -357,7 +357,7 @@ func (scs *Service) upsertSyncPost(post *model.Post, channel *model.Channel, rc } } else if post.EditAt > rpost.EditAt || post.Message != rpost.Message { // update post - rpost, appErr = scs.app.UpdatePost(request.EmptyContext(), post, false) + rpost, appErr = scs.app.UpdatePost(request.EmptyContext(scs.server.GetLogger()), post, false) if appErr == nil { scs.server.GetLogger().Log(mlog.LvlSharedChannelServiceDebug, "Updated sync post", mlog.String("post_id", post.Id), @@ -386,9 +386,9 @@ func (scs *Service) upsertSyncReaction(reaction *model.Reaction, rc *model.Remot reaction.RemoteId = model.NewString(rc.RemoteId) if reaction.DeleteAt == 0 { - savedReaction, appErr = scs.app.SaveReactionForPost(request.EmptyContext(), reaction) + savedReaction, appErr = scs.app.SaveReactionForPost(request.EmptyContext(scs.server.GetLogger()), reaction) } else { - appErr = scs.app.DeleteReactionForPost(request.EmptyContext(), reaction) + appErr = scs.app.DeleteReactionForPost(request.EmptyContext(scs.server.GetLogger()), reaction) } var err error diff --git a/services/sharedchannel/sync_send.go b/services/sharedchannel/sync_send.go index 285d764505..a4ce41821a 100644 --- a/services/sharedchannel/sync_send.go +++ b/services/sharedchannel/sync_send.go @@ -8,6 +8,7 @@ import ( "fmt" "time" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/services/remotecluster" "github.com/mattermost/mattermost-server/v6/shared/i18n" @@ -330,7 +331,7 @@ func (scs *Service) notifyRemoteOffline(posts []*model.Post, rc *model.RemoteClu Message: T("sharedchannel.cannot_deliver_post", map[string]any{"Remote": rc.DisplayName}), CreateAt: post.CreateAt + 1, } - scs.app.SendEphemeralPost(post.UserId, ephemeral) + scs.app.SendEphemeralPost(request.EmptyContext(scs.server.GetLogger()), post.UserId, ephemeral) notified[post.UserId] = true } diff --git a/services/slackimport/slackimport.go b/services/slackimport/slackimport.go index f290370332..30e32afa37 100644 --- a/services/slackimport/slackimport.go +++ b/services/slackimport/slackimport.go @@ -18,6 +18,7 @@ import ( "time" "unicode/utf8" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/i18n" "github.com/mattermost/mattermost-server/v6/shared/mlog" @@ -84,10 +85,10 @@ type slackComment struct { // Actions provides the actions that needs to be used for import slack data type Actions struct { UpdateActive func(*model.User, bool) (*model.User, *model.AppError) - AddUserToChannel func(*model.User, *model.Channel, bool) (*model.ChannelMember, *model.AppError) + AddUserToChannel func(request.CTX, *model.User, *model.Channel, bool) (*model.ChannelMember, *model.AppError) JoinUserToTeam func(*model.Team, *model.User, string) (*model.TeamMember, *model.AppError) - CreateDirectChannel func(string, string, ...model.ChannelOption) (*model.Channel, *model.AppError) - CreateGroupChannel func([]string) (*model.Channel, *model.AppError) + CreateDirectChannel func(request.CTX, string, string, ...model.ChannelOption) (*model.Channel, *model.AppError) + CreateGroupChannel func(request.CTX, []string) (*model.Channel, *model.AppError) CreateChannel func(*model.Channel, bool) (*model.Channel, *model.AppError) DoUploadFile func(time.Time, string, string, string, string, []byte) (*model.FileInfo, *model.AppError) GenerateThumbnailImage func(image.Image, string) @@ -114,7 +115,7 @@ func New(store store.Store, actions Actions, config *model.Config) *SlackImporte } } -func (si *SlackImporter) SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { +func (si *SlackImporter) SlackImport(c request.CTX, fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { // Create log file log := bytes.NewBufferString(i18n.T("api.slackimport.slack_import.log")) @@ -201,7 +202,7 @@ func (si *SlackImporter) SlackImport(fileData multipart.File, fileSize int64, te addedUsers := si.slackAddUsers(teamID, users, log) botUser := si.slackAddBotUser(teamID, log) - si.slackAddChannels(teamID, channels, posts, addedUsers, uploads, botUser, log) + si.slackAddChannels(c, teamID, channels, posts, addedUsers, uploads, botUser, log) if botUser != nil { si.deactivateSlackBotUser(botUser) @@ -549,14 +550,14 @@ func (si *SlackImporter) deactivateSlackBotUser(user *model.User) { } } -func (si *SlackImporter) addSlackUsersToChannel(members []string, users map[string]*model.User, channel *model.Channel, log *bytes.Buffer) { +func (si *SlackImporter) addSlackUsersToChannel(c request.CTX, members []string, users map[string]*model.User, channel *model.Channel, log *bytes.Buffer) { for _, member := range members { user, ok := users[member] if !ok { log.WriteString(i18n.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]any{"Username": "?"})) continue } - if _, err := si.actions.AddUserToChannel(user, channel, false); err != nil { + if _, err := si.actions.AddUserToChannel(c, user, channel, false); err != nil { log.WriteString(i18n.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]any{"Username": user.Username})) } } @@ -586,7 +587,7 @@ func slackSanitiseChannelProperties(channel model.Channel) model.Channel { return channel } -func (si *SlackImporter) slackAddChannels(teamId string, slackchannels []slackChannel, posts map[string][]slackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, importerLog *bytes.Buffer) map[string]*model.Channel { +func (si *SlackImporter) slackAddChannels(c request.CTX, teamId string, slackchannels []slackChannel, posts map[string][]slackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, importerLog *bytes.Buffer) map[string]*model.Channel { // Write Header importerLog.WriteString(i18n.T("api.slackimport.slack_add_channels.added")) importerLog.WriteString("=================\r\n\r\n") @@ -622,7 +623,7 @@ func (si *SlackImporter) slackAddChannels(teamId string, slackchannels []slackCh if mChannel == nil { // Haven't found an existing channel to merge with. Try importing it as a new one. - mChannel = si.oldImportChannel(&newChannel, sChannel, users) + mChannel = si.oldImportChannel(c, &newChannel, sChannel, users) if mChannel == nil { mlog.Warn("Slack Import: Unable to import Slack channel.", mlog.String("channel_display_name", newChannel.DisplayName)) importerLog.WriteString(i18n.T("api.slackimport.slack_add_channels.import_failed", map[string]any{"DisplayName": newChannel.DisplayName})) @@ -632,7 +633,7 @@ func (si *SlackImporter) slackAddChannels(teamId string, slackchannels []slackCh // Members for direct and group channels are added during the creation of the channel in the oldImportChannel function if sChannel.Type == model.ChannelTypeOpen || sChannel.Type == model.ChannelTypePrivate { - si.addSlackUsersToChannel(sChannel.Members, users, mChannel, importerLog) + si.addSlackUsersToChannel(c, sChannel.Members, users, mChannel, importerLog) } importerLog.WriteString(newChannel.DisplayName + "\r\n") addedChannels[sChannel.Id] = mChannel @@ -722,7 +723,7 @@ func (si *SlackImporter) oldImportUser(team *model.Team, user *model.User) *mode return ruser } -func (si *SlackImporter) oldImportChannel(channel *model.Channel, sChannel slackChannel, users map[string]*model.User) *model.Channel { +func (si *SlackImporter) oldImportChannel(c request.CTX, channel *model.Channel, sChannel slackChannel, users map[string]*model.User) *model.Channel { switch { case channel.Type == model.ChannelTypeDirect: if len(sChannel.Members) < 2 { @@ -734,7 +735,7 @@ func (si *SlackImporter) oldImportChannel(channel *model.Channel, sChannel slack mlog.Warn("Either or both of user ids not found in users.json. Ignoring.", mlog.String("id1", sChannel.Members[0]), mlog.String("id2", sChannel.Members[1])) return nil } - sc, err := si.actions.CreateDirectChannel(u1.Id, u2.Id) + sc, err := si.actions.CreateDirectChannel(c, u1.Id, u2.Id) if err != nil { return nil } @@ -757,7 +758,7 @@ func (si *SlackImporter) oldImportChannel(channel *model.Channel, sChannel slack if creator == nil { return nil } - sc, err := si.actions.CreateGroupChannel(members) + sc, err := si.actions.CreateGroupChannel(c, members) if err != nil { return nil } diff --git a/services/slackimport/slackimport_test.go b/services/slackimport/slackimport_test.go index c48e4d47a2..32f0c32561 100644 --- a/services/slackimport/slackimport_test.go +++ b/services/slackimport/slackimport_test.go @@ -11,7 +11,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store/storetest/mocks" ) @@ -325,6 +327,8 @@ func TestOldImportChannel(t *testing.T) { store := &mocks.Store{} config := &model.Config{} config.SetDefaults() + ctx := &request.Context{} + ctx.SetLogger(mlog.CreateConsoleTestLogger(true, mlog.LvlDebug)) t.Run("No panic on direct channel", func(t *testing.T) { // ch := th.CreateDmChannel(u1) @@ -344,7 +348,7 @@ func TestOldImportChannel(t *testing.T) { actions := Actions{} importer := New(store, actions, config) - _ = importer.oldImportChannel(ch, sCh, users) + _ = importer.oldImportChannel(ctx, ch, sCh, users) }) t.Run("No panic on direct channel with 1 member", func(t *testing.T) { @@ -364,7 +368,7 @@ func TestOldImportChannel(t *testing.T) { actions := Actions{} importer := New(store, actions, config) - _ = importer.oldImportChannel(ch, sCh, users) + _ = importer.oldImportChannel(ctx, ch, sCh, users) }) t.Run("No panic on group channel", func(t *testing.T) { @@ -383,6 +387,6 @@ func TestOldImportChannel(t *testing.T) { actions := Actions{} importer := New(store, actions, config) - _ = importer.oldImportChannel(ch, sCh, users) + _ = importer.oldImportChannel(ctx, ch, sCh, users) }) } diff --git a/web/handlers.go b/web/handlers.go index 9a37fc4b35..777a8ebcad 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -168,6 +168,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.AppContext.SetUserAgent(r.UserAgent()) c.AppContext.SetAcceptLanguage(r.Header.Get("Accept-Language")) c.AppContext.SetPath(r.URL.Path) + c.AppContext.SetContext(context.Background()) c.Params = ParamsFromRequest(r) c.Logger = c.App.Log() @@ -305,6 +306,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { mlog.String("user_id", c.AppContext.Session().UserId), mlog.String("method", r.Method), ) + c.AppContext.SetLogger(c.Logger) if c.Err == nil && h.RequireSession { c.SessionRequired() diff --git a/web/saml.go b/web/saml.go index ba4d11634b..24ff06c530 100644 --- a/web/saml.go +++ b/web/saml.go @@ -152,7 +152,7 @@ func completeSaml(c *Context, w http.ResponseWriter, r *http.Request) { c.LogErrorByCode(err) break } - c.App.AddDirectChannels(teamId, user) + c.App.AddDirectChannels(c.AppContext, teamId, user) } case model.OAuthActionEmailToSSO: if err = c.App.RevokeAllSessions(user.Id); err != nil { diff --git a/web/web_test.go b/web/web_test.go index 87cc3ec519..303c1840cd 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -119,7 +119,6 @@ func setupTestHelper(tb testing.TB, includeCacheLayer bool) *TestHelper { *cfg.PasswordSettings.Number = false }) - ctx := &request.Context{} a := app.New(app.ServerConnector(s.Channels())) web := New(s) @@ -134,12 +133,13 @@ func setupTestHelper(tb testing.TB, includeCacheLayer bool) *TestHelper { th := &TestHelper{ App: a, - Context: ctx, + Context: request.EmptyContext(testLogger), Server: s, Web: web, IncludeCacheLayer: includeCacheLayer, TestLogger: testLogger, } + th.Context.SetLogger(testLogger) return th } diff --git a/wsapi/user.go b/wsapi/user.go index e3f24dd397..9cbcdbe78e 100644 --- a/wsapi/user.go +++ b/wsapi/user.go @@ -4,6 +4,7 @@ package wsapi import ( + "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" ) @@ -26,7 +27,7 @@ func (api *API) userTyping(req *model.WebSocketRequest) (map[string]any, *model. return nil, NewInvalidWebSocketParamError(req.Action, "channel_id") } - if !api.App.SessionHasPermissionToChannel(req.Session, channelId, model.PermissionCreatePost) { + if !api.App.SessionHasPermissionToChannel(request.EmptyContext(api.App.Log()), req.Session, channelId, model.PermissionCreatePost) { return nil, NewInvalidWebSocketParamError(req.Action, "channel_id") }