[MM-55595] Use annotated logger in search layer (#25468)

Этот коммит содержится в:
Ben Schumacher
2023-12-04 18:34:57 +01:00
коммит произвёл GitHub
родитель 5a4dba8809
Коммит b2ec1ff8ae
130 изменённых файлов: 2107 добавлений и 1930 удалений

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

@@ -142,7 +142,7 @@ type AppIface interface {
// any ensureBotOptions hence it is not required for now.
// TODO: Once the focalboard migration completed, we should add this logic to the app and
// let plugin-api use the same code
EnsureBot(c request.CTX, productID string, bot *model.Bot) (string, error)
EnsureBot(rctx request.CTX, productID string, bot *model.Bot) (string, error)
// Expand announcements in incoming webhooks from Slack. Those announcements
// can be found in the text attribute, or in the pretext, text, title and value
// attributes of the attachment structure. The Slack attachment structure is
@@ -273,7 +273,7 @@ type AppIface interface {
// so that it points to the URL (relative) of the emoji - static if emoji is default, /api if custom.
OverrideIconURLIfEmoji(c request.CTX, post *model.Post)
// PatchBot applies the given patch to the bot and corresponding user.
PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError)
PatchBot(rctx request.CTX, 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(c request.CTX, channel *model.Channel, channelModerationsPatch []*model.ChannelModerationPatch) ([]*model.ChannelModeration, *model.AppError)
// Perform an HTTP POST request to an integration's action endpoint.
@@ -434,8 +434,8 @@ type AppIface interface {
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)
AutocompleteUsersInChannel(rctx request.CTX, teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError)
AutocompleteUsersInTeam(rctx request.CTX, teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError)
BuildPostReactions(ctx request.CTX, postID string) (*[]ReactionImportData, *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)
@@ -477,7 +477,7 @@ type AppIface interface {
Compliance() einterfaces.ComplianceInterface
Config() *model.Config
ConvertGroupMessageToChannel(c request.CTX, convertedByUserId string, gmConversionRequest *model.GroupMessageConversionRequestBody) (*model.Channel, *model.AppError)
CopyFileInfos(userID string, fileIDs []string) ([]string, *model.AppError)
CopyFileInfos(rctx request.CTX, userID string, fileIDs []string) ([]string, *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)
@@ -952,8 +952,8 @@ type AppIface interface {
ProcessSlackText(text string) string
Publish(message *model.WebSocketEvent)
PublishUserTyping(userID, channelID, parentId string) *model.AppError
PurgeBleveIndexes() *model.AppError
PurgeElasticsearchIndexes() *model.AppError
PurgeBleveIndexes(c request.CTX) *model.AppError
PurgeElasticsearchIndexes(c request.CTX) *model.AppError
QueryLogs(rctx request.CTX, page, perPage int, logFilter *model.LogFilter) (map[string][]string, *model.AppError)
ReadFile(path string) ([]byte, *model.AppError)
RecycleDatabaseConnection(rctx request.CTX)
@@ -1027,10 +1027,10 @@ type AppIface interface {
SearchPrivateTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError)
SearchPublicTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError)
SearchUserAccessTokens(term string) ([]*model.UserAccessToken, *model.AppError)
SearchUsers(props *model.UserSearch, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsers(rctx request.CTX, props *model.UserSearch, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsersInChannel(channelID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsersInGroup(groupID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsersInTeam(teamID, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsersInTeam(rctx request.CTX, teamID, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsersNotInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsersNotInGroup(groupID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
SearchUsersNotInTeam(notInTeamId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
@@ -1065,7 +1065,7 @@ type AppIface interface {
SetChannels(ch *Channels)
SetCustomStatus(c request.CTX, userID string, cs *model.CustomStatus) *model.AppError
SetDefaultProfileImage(c request.CTX, user *model.User) *model.AppError
SetFileSearchableContent(fileID string, data string) *model.AppError
SetFileSearchableContent(rctx request.CTX, fileID string, data string) *model.AppError
SetPhase2PermissionsMigrationStatus(isComplete bool) error
SetPluginKey(pluginID string, key string, value []byte) *model.AppError
SetPluginKeyWithExpiry(pluginID string, key string, value []byte, expireInSeconds int64) *model.AppError
@@ -1096,7 +1096,7 @@ type AppIface interface {
SwitchOAuthToEmail(c request.CTX, email, password, requesterId string) (string, *model.AppError)
TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.AppError)
TelemetryId() string
TestElasticsearch(cfg *model.Config) *model.AppError
TestElasticsearch(rctx request.CTX, cfg *model.Config) *model.AppError
TestEmail(rctx request.CTX, userID string, cfg *model.Config) *model.AppError
TestFileStoreConnection() *model.AppError
TestFileStoreConnectionWithConfig(cfg *model.FileSettings) *model.AppError

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

@@ -120,7 +120,7 @@ func (s *Server) configureAudit(adt *audit.Audit, bAllowAdvancedLogging bool) er
if err != nil {
return fmt.Errorf("invalid config source for audit, %w", err)
}
mlog.Debug("Loaded audit configuration", mlog.String("source", dsn))
s.Log().Debug("Loaded audit configuration", mlog.String("source", dsn))
} else {
s.Log().Debug("Advanced logging config not provided for audit")
}
@@ -136,10 +136,10 @@ func (s *Server) configureAudit(adt *audit.Audit, bAllowAdvancedLogging bool) er
}
func (s *Server) onAuditTargetQueueFull(qname string, maxQSize int) bool {
mlog.Error("Audit queue full, dropping record.", mlog.String("qname", qname), mlog.Int("queueSize", maxQSize))
s.Log().Error("Audit queue full, dropping record.", mlog.String("qname", qname), mlog.Int("queueSize", maxQSize))
return true // drop it
}
func (s *Server) onAuditError(err error) {
mlog.Error("Audit Error", mlog.Err(err))
s.Log().Error("Audit Error", mlog.Err(err))
}

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

@@ -218,7 +218,7 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
// Clean up all posts from this user.
// There are some dummy messages like "user joined team" etc.
// which needs to be cleaned up.
require.NoError(t, th.GetSqlStore().Post().PermanentDeleteByUser(th.BasicUser.Id))
require.NoError(t, th.GetSqlStore().Post().PermanentDeleteByUser(th.Context, th.BasicUser.Id))
savedPost, err := th.App.CreatePost(th.Context, &model.Post{
ChannelId: channel.Id,

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

@@ -39,7 +39,7 @@ func (w *botServiceWrapper) EnsureBot(c request.CTX, productID string, bot *mode
// any ensureBotOptions hence it is not required for now.
// TODO: Once the focalboard migration completed, we should add this logic to the app and
// let plugin-api use the same code
func (a *App) EnsureBot(c request.CTX, productID string, bot *model.Bot) (string, error) {
func (a *App) EnsureBot(rctx request.CTX, productID string, bot *model.Bot) (string, error) {
if bot == nil {
return "", errors.New("passed a nil bot")
}
@@ -64,7 +64,7 @@ func (a *App) EnsureBot(c request.CTX, productID string, bot *model.Bot) (string
Description: &bot.Description,
}
if _, err = a.PatchBot(botID, botPatch); err != nil {
if _, err = a.PatchBot(rctx, botID, botPatch); err != nil {
return "", fmt.Errorf("failed to patch bot: %w", err)
}
@@ -78,7 +78,7 @@ func (a *App) EnsureBot(c request.CTX, productID string, bot *model.Bot) (string
return "", fmt.Errorf("failed to set plugin key: %w", err)
}
} else {
c.Logger().Error("Product attempted to use an account that already exists. Convert user to a bot "+
rctx.Logger().Error("Product attempted to use an account that already exists. Convert user to a bot "+
"account in the CLI by running 'mattermost user convert <username> --bot'. If the user is an "+
"existing user account you want to preserve, change its username and restart the Mattermost server, "+
"after which the plugin will create a bot account with that name. For more information about bot "+
@@ -91,7 +91,7 @@ func (a *App) EnsureBot(c request.CTX, productID string, bot *model.Bot) (string
return user.Id, nil
}
createdBot, err := a.CreateBot(c, bot)
createdBot, err := a.CreateBot(rctx, bot)
if err != nil {
return "", fmt.Errorf("failed to create bot: %w", err)
}
@@ -294,7 +294,7 @@ func (a *App) getOrCreateBot(botDef *model.Bot) (*model.Bot, *model.AppError) {
}
// PatchBot applies the given patch to the bot and corresponding user.
func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
func (a *App) PatchBot(rctx request.CTX, botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
bot, err := a.GetBot(botUserId, true)
if err != nil {
return nil, err
@@ -323,7 +323,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot,
user.Email = patchedUser.Email
user.FirstName = patchedUser.FirstName
userUpdate, nErr := a.Srv().Store().User().Update(user, true)
userUpdate, nErr := a.Srv().Store().User().Update(rctx, user, true)
if nErr != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput

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

@@ -131,7 +131,7 @@ func TestPatchBot(t *testing.T) {
Description: sToP("updated bot"),
}
_, err = th.App.PatchBot(bot.UserId, botPatch)
_, err = th.App.PatchBot(th.Context, bot.UserId, botPatch)
require.NotNil(t, err)
require.Equal(t, "model.user.is_valid.username.app_error", err.Id)
})
@@ -154,7 +154,7 @@ func TestPatchBot(t *testing.T) {
Description: sToP(strings.Repeat("x", 1025)),
}
_, err = th.App.PatchBot(bot.UserId, botPatch)
_, err = th.App.PatchBot(th.Context, bot.UserId, botPatch)
require.NotNil(t, err)
require.Equal(t, "model.bot.is_valid.description.app_error", err.Id)
})
@@ -180,7 +180,7 @@ func TestPatchBot(t *testing.T) {
Description: sToP("an updated bot"),
}
patchedBot, err := th.App.PatchBot(createdBot.UserId, botPatch)
patchedBot, err := th.App.PatchBot(th.Context, createdBot.UserId, botPatch)
require.Nil(t, err)
// patchedBot should create a new .UpdateAt time
@@ -210,7 +210,7 @@ func TestPatchBot(t *testing.T) {
Username: sToP(th.BasicUser2.Username),
}
_, err = th.App.PatchBot(bot.UserId, botPatch)
_, err = th.App.PatchBot(th.Context, bot.UserId, botPatch)
require.NotNil(t, err)
require.Equal(t, "app.user.save.username_exists.app_error", err.Id)
})

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

@@ -503,7 +503,7 @@ func (a *App) createDirectChannel(c request.CTX, userID string, otherUserID stri
}
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...)
channel, nErr := a.Srv().Store().Channel().CreateDirectChannel(c, user, otherUser, channelOptions...)
if nErr != nil {
var invErr *store.ErrInvalidInput
var cErr *store.ErrConflict
@@ -691,7 +691,7 @@ func (a *App) GetGroupChannel(c request.CTX, userIDs []string) (*model.Channel,
// UpdateChannel updates a given channel by its Id. It also publishes the CHANNEL_UPDATED event.
func (a *App) UpdateChannel(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) {
_, err := a.Srv().Store().Channel().Update(channel)
_, err := a.Srv().Store().Channel().Update(c, channel)
if err != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput
@@ -1372,7 +1372,7 @@ func (a *App) UpdateChannelMemberNotifyProps(c request.CTX, data map[string]stri
}
func (a *App) updateChannelMember(c request.CTX, member *model.ChannelMember) (*model.ChannelMember, *model.AppError) {
member, err := a.Srv().Store().Channel().UpdateMember(member)
member, err := a.Srv().Store().Channel().UpdateMember(c, member)
if err != nil {
var appErr *model.AppError
var nfErr *store.ErrNotFound
@@ -2526,7 +2526,7 @@ func (a *App) removeUserFromChannel(c request.CTX, userIDToRemove string, remove
return err
}
if err := a.Srv().Store().Channel().RemoveMember(channel.Id, userIDToRemove); err != nil {
if err := a.Srv().Store().Channel().RemoveMember(c, channel.Id, userIDToRemove); err != nil {
return model.NewAppError("removeUserFromChannel", "app.channel.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
if err := a.Srv().Store().ChannelMemberHistory().LogLeaveEvent(userIDToRemove, channel.Id, model.GetMillis()); err != nil {
@@ -2547,7 +2547,7 @@ func (a *App) removeUserFromChannel(c request.CTX, userIDToRemove string, remove
return model.NewAppError("removeUserFromChannel", "api.team.remove_user_from_team.missing.app_error", nil, "", http.StatusBadRequest).Wrap(err)
}
if err := a.ch.srv.teamService.RemoveTeamMember(teamMember); err != nil {
if err := a.ch.srv.teamService.RemoveTeamMember(c, teamMember); err != nil {
return model.NewAppError("removeUserFromChannel", "api.team.remove_user_from_team.missing.app_error", nil, "", http.StatusBadRequest).Wrap(err)
}
@@ -2675,7 +2675,7 @@ func (a *App) ValidateUserPermissionsOnChannels(c request.CTX, userId string, ch
for _, channelId := range channelIds {
channel, err := a.GetChannel(c, channelId)
if err != nil {
mlog.Info("Invite users to team - couldn't get channel " + channelId)
c.Logger().Info("Invite users to team - couldn't get channel " + channelId)
continue
}
@@ -2684,7 +2684,7 @@ func (a *App) ValidateUserPermissionsOnChannels(c request.CTX, userId string, ch
} else if channel.Type == model.ChannelTypeOpen && a.HasPermissionToChannel(c, userId, channelId, model.PermissionManagePublicChannelMembers) {
allowedChannelIds = append(allowedChannelIds, channelId)
} else {
mlog.Info("Invite users to team - no permission to add members to that channel. UserId: " + userId + " ChannelId: " + channelId)
c.Logger().Info("Invite users to team - no permission to add members to that channel. UserId: " + userId + " ChannelId: " + channelId)
}
}
return allowedChannelIds
@@ -2852,7 +2852,7 @@ func (a *App) AutocompleteChannels(c request.CTX, userID, term string) (model.Ch
return nil, appErr
}
channelList, err := a.Srv().Store().Channel().Autocomplete(userID, term, includeDeleted, user.IsGuest())
channelList, err := a.Srv().Store().Channel().Autocomplete(c, userID, term, includeDeleted, user.IsGuest())
if err != nil {
return nil, model.NewAppError("AutocompleteChannels", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -2869,7 +2869,7 @@ func (a *App) AutocompleteChannelsForTeam(c request.CTX, teamID, userID, term st
return nil, appErr
}
channelList, err := a.Srv().Store().Channel().AutocompleteInTeam(teamID, userID, term, includeDeleted, user.IsGuest())
channelList, err := a.Srv().Store().Channel().AutocompleteInTeam(c, teamID, userID, term, includeDeleted, user.IsGuest())
if err != nil {
return nil, model.NewAppError("AutocompleteChannels", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -3064,11 +3064,11 @@ func (a *App) ViewChannel(c request.CTX, view *model.ChannelView, userID string,
}
func (a *App) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *model.AppError {
if err := a.Srv().Store().Post().PermanentDeleteByChannel(channel.Id); err != nil {
if err := a.Srv().Store().Post().PermanentDeleteByChannel(c, channel.Id); err != nil {
return model.NewAppError("PermanentDeleteChannel", "app.post.permanent_delete_by_channel.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
if err := a.Srv().Store().Channel().PermanentDeleteMembersByChannel(channel.Id); err != nil {
if err := a.Srv().Store().Channel().PermanentDeleteMembersByChannel(c, channel.Id); err != nil {
return model.NewAppError("PermanentDeleteChannel", "app.channel.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -3086,7 +3086,7 @@ func (a *App) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *mod
deleteAt := model.GetMillis()
if nErr := a.Srv().Store().Channel().PermanentDelete(channel.Id); nErr != nil {
if nErr := a.Srv().Store().Channel().PermanentDelete(c, channel.Id); nErr != nil {
return model.NewAppError("PermanentDeleteChannel", "app.channel.permanent_delete.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
@@ -3101,7 +3101,7 @@ func (a *App) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *mod
}
func (a *App) RemoveAllDeactivatedMembersFromChannel(c request.CTX, channel *model.Channel) *model.AppError {
err := a.Srv().Store().Channel().RemoveAllDeactivatedMembers(channel.Id)
err := a.Srv().Store().Channel().RemoveAllDeactivatedMembers(c, channel.Id)
if err != nil {
return model.NewAppError("RemoveAllDeactivatedMembersFromChannel", "app.channel.remove_all_deactivated_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -3160,7 +3160,7 @@ func (a *App) MoveChannel(c request.CTX, team *model.Team, channel *model.Channe
}
channel.TeamId = team.Id
if _, err := a.Srv().Store().Channel().Update(channel); err != nil {
if _, err := a.Srv().Store().Channel().Update(c, channel); err != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput
switch {
@@ -3594,7 +3594,7 @@ func (a *App) setSidebarCategoriesForConvertedGroupMessage(c request.CTX, gmConv
})
if appErr != nil {
mlog.Error("Failed to search sidebar categories for user for adding converted GM")
c.Logger().Error("Failed to search sidebar categories for user for adding converted GM")
continue
}
@@ -3613,7 +3613,7 @@ func (a *App) setSidebarCategoriesForConvertedGroupMessage(c request.CTX, gmConv
channelsCategory := categories.Categories[0]
_, appErr = a.UpdateSidebarCategories(c, user.Id, gmConversionRequest.TeamID, []*model.SidebarCategoryWithChannels{channelsCategory})
if appErr != nil {
mlog.Error("Failed to add converted GM to default sidebar category for user", mlog.String("user_id", user.Id), mlog.Err(err))
c.Logger().Error("Failed to add converted GM to default sidebar category for user", mlog.String("user_id", user.Id), mlog.Err(err))
}
}
@@ -3708,7 +3708,7 @@ func (a *App) postMessageForConvertGroupMessageToChannel(c request.CTX, channelI
}
if _, appErr := a.CreatePost(c, post, channel, false, true); appErr != nil {
mlog.Error("Failed to create post for notifying about GM converted to private channel", mlog.Err(appErr))
c.Logger().Error("Failed to create post for notifying about GM converted to private channel", mlog.Err(appErr))
return model.NewAppError(
"postMessageForConvertGroupMessageToChannel",

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

@@ -2537,13 +2537,13 @@ func TestConvertGroupMessageToChannel(t *testing.T) {
UpdateAt: time.Now().Unix(),
Type: model.ChannelTypeGroup,
}, nil)
mockChannelStore.On("Update", mock.AnythingOfType("*model.Channel")).Return(&model.Channel{}, nil)
mockChannelStore.On("Update", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("*model.Channel")).Return(&model.Channel{}, nil)
mockChannelStore.On("InvalidateChannel", "channelidchannelidchanneli")
mockChannelStore.On("InvalidateChannelByName", "team_id_1", "new_name").Times(1)
mockChannelStore.On("InvalidateChannelByName", "dm", "")
mockChannelStore.On("GetMember", sqlstore.WithMaster(context.Background()), "channelidchannelidchanneli", "user_id_1").Return(&model.ChannelMember{}, nil).Times(1)
mockChannelStore.On("GetMember", context.Background(), "channelidchannelidchanneli", "user_id_1").Return(&model.ChannelMember{}, nil).Times(2)
mockChannelStore.On("UpdateMember", mock.AnythingOfType("*model.ChannelMember")).Return(&model.ChannelMember{UserId: "user_id_1"}, nil)
mockChannelStore.On("UpdateMember", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("*model.ChannelMember")).Return(&model.ChannelMember{UserId: "user_id_1"}, nil)
mockChannelStore.On("InvalidateAllChannelMembersForUser", "user_id_1").Return()
mockChannelStore.On("InvalidatePinnedPostCount", "channelidchannelidchanneli")
mockChannelStore.On("GetAllChannelMembersNotifyPropsForChannel", "channelidchannelidchanneli", true).Return(map[string]model.StringMap{}, nil)

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

@@ -14,7 +14,7 @@ import (
func (s *Server) clusterInstallPluginHandler(msg *model.ClusterMessage) {
var data model.PluginEventData
if jsonErr := json.Unmarshal(msg.Data, &data); jsonErr != nil {
mlog.Warn("Failed to decode from JSON", mlog.Err(jsonErr))
s.Log().Warn("Failed to decode from JSON", mlog.Err(jsonErr))
}
s.Channels().installPluginFromClusterMessage(data.Id)
}
@@ -22,14 +22,14 @@ func (s *Server) clusterInstallPluginHandler(msg *model.ClusterMessage) {
func (s *Server) clusterRemovePluginHandler(msg *model.ClusterMessage) {
var data model.PluginEventData
if jsonErr := json.Unmarshal(msg.Data, &data); jsonErr != nil {
mlog.Warn("Failed to decode from JSON", mlog.Err(jsonErr))
s.Log().Warn("Failed to decode from JSON", mlog.Err(jsonErr))
}
s.Channels().removePluginFromClusterMessage(data.Id)
}
func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) {
if msg.Props == nil {
mlog.Warn("ClusterMessage.Props for plugin event should not be nil")
s.Log().Warn("ClusterMessage.Props for plugin event should not be nil")
return
}
pluginID := msg.Props["PluginID"]
@@ -39,8 +39,10 @@ func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) {
}
eventID := msg.Props["EventID"]
if pluginID == "" || eventID == "" {
mlog.Warn("Invalid ClusterMessage.Props values for plugin event",
mlog.String("plugin_id", pluginID), mlog.String("event_id", eventID))
s.Log().Warn("Invalid ClusterMessage.Props values for plugin event",
mlog.String("plugin_id", pluginID),
mlog.String("event_id", eventID),
)
return
}
@@ -51,7 +53,7 @@ func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) {
hooks, err := channels.HooksForPluginOrProduct(pluginID)
if err != nil {
mlog.Warn("Getting hooks for plugin failed", mlog.String("plugin_id", pluginID), mlog.Err(err))
s.Log().Warn("Getting hooks for plugin failed", mlog.String("plugin_id", pluginID), mlog.Err(err))
return
}

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

@@ -547,7 +547,7 @@ func (a *App) HandleCommandResponse(c request.CTX, command *model.Command, args
_, err := a.HandleCommandResponsePost(c, command, args, response, builtIn)
if err != nil {
mlog.Debug("Error occurred in handling command response post", mlog.Err(err))
c.Logger().Debug("Error occurred in handling command response post", mlog.Err(err))
lastError = err
}
@@ -556,7 +556,7 @@ func (a *App) HandleCommandResponse(c request.CTX, command *model.Command, args
_, err := a.HandleCommandResponsePost(c, command, args, resp, builtIn)
if err != nil {
mlog.Debug("Error occurred in handling command response post", mlog.Err(err))
c.Logger().Debug("Error occurred in handling command response post", mlog.Err(err))
lastError = err
}
}

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

@@ -93,7 +93,7 @@ func TestCheckPendingNotifications(t *testing.T) {
channelMember, err := th.store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id)
require.NoError(t, err)
channelMember.LastViewedAt = 9999999
_, err = th.store.Channel().UpdateMember(channelMember)
_, err = th.store.Channel().UpdateMember(th.Context, channelMember)
require.NoError(t, err)
nErr := th.store.Preference().Save(model.Preferences{{
@@ -114,7 +114,7 @@ func TestCheckPendingNotifications(t *testing.T) {
channelMember, err = th.store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id)
require.NoError(t, err)
channelMember.LastViewedAt = 10001000
_, err = th.store.Channel().UpdateMember(channelMember)
_, err = th.store.Channel().UpdateMember(th.Context, channelMember)
require.NoError(t, err)
// We reset the interval to something shorter
@@ -208,7 +208,7 @@ func TestCheckPendingNotificationsDefaultInterval(t *testing.T) {
channelMember, err := th.store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id)
require.NoError(t, err)
channelMember.LastViewedAt = 9999000
_, err = th.store.Channel().UpdateMember(channelMember)
_, err = th.store.Channel().UpdateMember(th.Context, channelMember)
require.NoError(t, err)
job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{
@@ -250,7 +250,7 @@ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) {
channelMember, err := th.store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id)
require.NoError(t, err)
channelMember.LastViewedAt = 9999000
_, err = th.store.Channel().UpdateMember(channelMember)
_, err = th.store.Channel().UpdateMember(th.Context, channelMember)
require.NoError(t, err)
// preference value is not an integer, so we'll fall back to the default 15min value

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

@@ -4,7 +4,6 @@
package email
import (
"bytes"
"os"
"path/filepath"
"testing"
@@ -12,6 +11,7 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/plugin/plugintest/mock"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app/users"
"github.com/mattermost/mattermost/server/v8/channels/store"
"github.com/mattermost/mattermost/server/v8/channels/store/storetest/mocks"
@@ -32,7 +32,8 @@ type TestHelper struct {
BasicUser2 *model.User
SystemAdminUser *model.User
LogBuffer *bytes.Buffer
Context request.CTX
}
func Setup(tb testing.TB) *TestHelper {
@@ -132,8 +133,8 @@ func setupTestHelper(s store.Store, tb testing.TB) *TestHelper {
service: service,
configStore: configStore,
store: s,
LogBuffer: &bytes.Buffer{},
workspace: tempWorkspace,
Context: request.TestContext(tb),
}
}

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

@@ -176,8 +176,8 @@ func (a *App) DeleteEmoji(c request.CTX, emoji *model.Emoji) *model.AppError {
}
}
a.deleteEmojiImage(emoji.Id)
a.deleteReactionsForEmoji(emoji.Name)
a.deleteEmojiImage(c, emoji.Id)
a.deleteReactionsForEmoji(c, emoji.Name)
return nil
}
@@ -355,14 +355,14 @@ func imageToPaletted(img image.Image) *image.Paletted {
return pm
}
func (a *App) deleteEmojiImage(id string) {
func (a *App) deleteEmojiImage(rctx request.CTX, id string) {
if err := a.MoveFile(getEmojiImagePath(id), "emoji/"+id+"/image_deleted"); err != nil {
mlog.Warn("Failed to rename image when deleting emoji", mlog.String("emoji_id", id))
rctx.Logger().Warn("Failed to rename image when deleting emoji", mlog.String("emoji_id", id))
}
}
func (a *App) deleteReactionsForEmoji(emojiName string) {
func (a *App) deleteReactionsForEmoji(rctx request.CTX, emojiName string) {
if err := a.Srv().Store().Reaction().DeleteAllWithEmojiName(emojiName); err != nil {
mlog.Warn("Unable to delete reactions when deleting emoji", mlog.String("emoji_name", emojiName), mlog.Err(err))
rctx.Logger().Warn("Unable to delete reactions when deleting emoji", mlog.String("emoji_name", emojiName), mlog.Err(err))
}
}

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

@@ -672,7 +672,7 @@ func TestBuildPostReplies(t *testing.T) {
createPostWithAttachments := func(th *TestHelper, n int, rootID string) *model.Post {
var fileIDs []string
for i := 0; i < n; i++ {
info, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{
info, err := th.App.Srv().Store().FileInfo().Save(th.Context, &model.FileInfo{
CreatorId: th.BasicUser.Id,
Name: fmt.Sprintf("file%d", i),
Path: fmt.Sprintf("/data/file%d", i),

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

@@ -505,7 +505,7 @@ func (a *App) MigrateFilenamesToFileInfos(rctx request.CTX, post *model.Post) []
savedInfos := make([]*model.FileInfo, 0, len(infos))
fileIDs := make([]string, 0, len(filenames))
for _, info := range infos {
if _, nErr = a.Srv().Store().FileInfo().Save(info); nErr != nil {
if _, nErr = a.Srv().Store().FileInfo().Save(rctx, info); nErr != nil {
rctx.Logger().Error(
"Unable to save file info when migrating post to use FileInfos",
mlog.String("post_id", post.Id),
@@ -527,7 +527,7 @@ func (a *App) MigrateFilenamesToFileInfos(rctx request.CTX, post *model.Post) []
newPost.FileIds = fileIDs
// Update Posts to clear Filenames and set FileIds
if _, nErr = a.Srv().Store().Post().Update(newPost, post); nErr != nil {
if _, nErr = a.Srv().Store().Post().Update(rctx, newPost, post); nErr != nil {
rctx.Logger().Error(
"Unable to save migrated post when migrating to use FileInfos",
mlog.String("new_file_ids", strings.Join(newPost.FileIds, ",")),
@@ -678,7 +678,7 @@ type UploadFileTask struct {
// Testing: overridable dependency functions
pluginsEnvironment *plugin.Environment
writeFile func(io.Reader, string) (int64, *model.AppError)
saveToDatabase func(*model.FileInfo) (*model.FileInfo, error)
saveToDatabase func(request.CTX, *model.FileInfo) (*model.FileInfo, error)
imgDecoder *imaging.Decoder
imgEncoder *imaging.Encoder
@@ -722,7 +722,7 @@ func (t *UploadFileTask) init(a *App) {
// contained the last "good" FileInfo before the execution of that plugin.
func (a *App) UploadFileX(c request.CTX, channelID, name string, input io.Reader,
opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError) {
c.WithLogger(c.Logger().With(
c = c.WithLogger(c.Logger().With(
mlog.String("file_name", name),
))
@@ -791,7 +791,7 @@ func (a *App) UploadFileX(c request.CTX, channelID, name string, input io.Reader
t.postprocessImage(file)
}
if _, err := t.saveToDatabase(t.fileinfo); err != nil {
if _, err := t.saveToDatabase(c, t.fileinfo); err != nil {
var appErr *model.AppError
switch {
case errors.As(err, &appErr):
@@ -1042,7 +1042,7 @@ func (a *App) DoUploadFileExpectModification(c request.CTX, now time.Time, rawTe
return nil, data, err
}
if _, err := a.Srv().Store().FileInfo().Save(info); err != nil {
if _, err := a.Srv().Store().FileInfo().Save(c, info); err != nil {
var appErr *model.AppError
switch {
case errors.As(err, &appErr):
@@ -1177,7 +1177,7 @@ func (a *App) generateMiniPreview(rctx request.CTX, fi *model.FileInfo) {
} else {
fi.MiniPreview = &miniPreview
}
if _, err = a.Srv().Store().FileInfo().Upsert(fi); err != nil {
if _, err = a.Srv().Store().FileInfo().Upsert(rctx, fi); err != nil {
rctx.Logger().Debug("Creating mini preview failed", mlog.Err(err))
} else {
a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(fi.PostId, false)
@@ -1230,13 +1230,13 @@ func (a *App) GetFileInfo(rctx request.CTX, fileID string) (*model.FileInfo, *mo
return fileInfo, appErr
}
func (a *App) SetFileSearchableContent(fileID string, data string) *model.AppError {
func (a *App) SetFileSearchableContent(rctx request.CTX, fileID string, data string) *model.AppError {
fileInfo, appErr := a.Srv().getFileInfo(fileID)
if appErr != nil {
return appErr
}
err := a.Srv().Store().FileInfo().SetContent(fileInfo.Id, data)
err := a.Srv().Store().FileInfo().SetContent(rctx, fileInfo.Id, data)
if err != nil {
var nfErr *store.ErrNotFound
switch {
@@ -1317,7 +1317,7 @@ func (a *App) getFileIgnoreCloudLimit(rctx request.CTX, fileID string) ([]byte,
return data, nil
}
func (a *App) CopyFileInfos(userID string, fileIDs []string) ([]string, *model.AppError) {
func (a *App) CopyFileInfos(rctx request.CTX, userID string, fileIDs []string) ([]string, *model.AppError) {
var newFileIds []string
now := model.GetMillis()
@@ -1341,7 +1341,7 @@ func (a *App) CopyFileInfos(userID string, fileIDs []string) ([]string, *model.A
fileInfo.PostId = ""
fileInfo.ChannelId = ""
if _, err := a.Srv().Store().FileInfo().Save(fileInfo); err != nil {
if _, err := a.Srv().Store().FileInfo().Save(rctx, fileInfo); err != nil {
var appErr *model.AppError
switch {
case errors.As(err, &appErr):
@@ -1428,8 +1428,8 @@ func (a *App) SearchFilesInTeamForUser(c request.CTX, terms string, userId strin
params.ExcludedChannels = a.convertChannelNamesToChannelIds(c, params.ExcludedChannels, userId, teamId, includeDeletedChannels)
// Convert usernames to user IDs
params.FromUsers = a.convertUserNameToUserIds(params.FromUsers)
params.ExcludedUsers = a.convertUserNameToUserIds(params.ExcludedUsers)
params.FromUsers = a.convertUserNameToUserIds(c, params.FromUsers)
params.ExcludedUsers = a.convertUserNameToUserIds(c, params.ExcludedUsers)
finalParamsList = append(finalParamsList, params)
}
@@ -1440,7 +1440,7 @@ func (a *App) SearchFilesInTeamForUser(c request.CTX, terms string, userId strin
return model.NewFileInfoList(), nil
}
fileInfoSearchResults, nErr := a.Srv().Store().FileInfo().Search(finalParamsList, userId, teamId, page, perPage)
fileInfoSearchResults, nErr := a.Srv().Store().FileInfo().Search(c, finalParamsList, userId, teamId, page, perPage)
if nErr != nil {
var appErr *model.AppError
switch {
@@ -1475,7 +1475,7 @@ func (a *App) ExtractContentFromFileInfo(rctx request.CTX, fileInfo *model.FileI
if len(text) > maxContentExtractionSize {
text = text[0:maxContentExtractionSize]
}
if storeErr := a.Srv().Store().FileInfo().SetContent(fileInfo.Id, text); storeErr != nil {
if storeErr := a.Srv().Store().FileInfo().SetContent(rctx, fileInfo.Id, text); storeErr != nil {
return errors.Wrap(storeErr, "failed to save the extracted file content")
}
reloadFileInfo, storeErr := a.Srv().Store().FileInfo().Get(fileInfo.Id)

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

@@ -87,7 +87,7 @@ func BenchmarkUploadFile(b *testing.B) {
if err != nil {
b.Fatal(err)
}
th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info1.Id)
th.App.RemoveFile(info1.Path)
},
},
@@ -105,7 +105,7 @@ func BenchmarkUploadFile(b *testing.B) {
if aerr != nil {
b.Fatal(aerr)
}
th.App.Srv().Store().FileInfo().PermanentDelete(info.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info.Id)
th.App.RemoveFile(info.Path)
},
},
@@ -123,7 +123,7 @@ func BenchmarkUploadFile(b *testing.B) {
if aerr != nil {
b.Fatal(aerr)
}
th.App.Srv().Store().FileInfo().PermanentDelete(info.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info.Id)
th.App.RemoveFile(info.Path)
},
},
@@ -140,7 +140,7 @@ func BenchmarkUploadFile(b *testing.B) {
if aerr != nil {
b.Fatal(aerr)
}
th.App.Srv().Store().FileInfo().PermanentDelete(info.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info.Id)
th.App.RemoveFile(info.Path)
},
},
@@ -157,7 +157,7 @@ func BenchmarkUploadFile(b *testing.B) {
if aerr != nil {
b.Fatal(aerr)
}
th.App.Srv().Store().FileInfo().PermanentDelete(info.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info.Id)
th.App.RemoveFile(info.Path)
},
},

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

@@ -60,7 +60,7 @@ func TestDoUploadFile(t *testing.T) {
info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
require.Nil(t, err, "DoUploadFile should succeed with valid data")
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info1.Id)
th.App.RemoveFile(info1.Path)
}()
@@ -70,7 +70,7 @@ func TestDoUploadFile(t *testing.T) {
info2, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
require.Nil(t, err, "DoUploadFile should succeed with valid data")
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info2.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info2.Id)
th.App.RemoveFile(info2.Path)
}()
@@ -80,7 +80,7 @@ func TestDoUploadFile(t *testing.T) {
info3, err := th.App.DoUploadFile(th.Context, time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
require.Nil(t, err, "DoUploadFile should succeed with valid data")
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info3.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info3.Id)
th.App.RemoveFile(info3.Path)
}()
@@ -90,7 +90,7 @@ func TestDoUploadFile(t *testing.T) {
info4, err := th.App.DoUploadFile(th.Context, time.Date(2009, 3, 5, 1, 2, 3, 4, time.Local), "../../"+teamID, "../../"+channelID, "../../"+userID, "../../"+filename, data)
require.Nil(t, err, "DoUploadFile should succeed with valid data")
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info4.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info4.Id)
th.App.RemoveFile(info4.Path)
}()
@@ -117,7 +117,7 @@ func TestUploadFile(t *testing.T) {
info1, err = th.App.UploadFile(th.Context, data, channelID, filename)
require.Nil(t, err, "UploadFile should succeed with valid data")
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info1.Id)
th.App.RemoveFile(info1.Path)
}()
@@ -348,17 +348,17 @@ func TestCopyFileInfos(t *testing.T) {
info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info1.Id)
th.App.RemoveFile(info1.Path)
}()
infoIds, err := th.App.CopyFileInfos(userID, []string{info1.Id})
infoIds, err := th.App.CopyFileInfos(th.Context, userID, []string{info1.Id})
require.Nil(t, err)
info2, err := th.App.GetFileInfo(th.Context, infoIds[0])
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info2.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info2.Id)
th.App.RemoveFile(info2.Path)
}()
@@ -404,15 +404,16 @@ func TestSearchFilesInTeamForUser(t *testing.T) {
fileInfos := make([]*model.FileInfo, 7)
for i := 0; i < cap(fileInfos); i++ {
fileInfo, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{
CreatorId: th.BasicUser.Id,
PostId: th.BasicPost.Id,
ChannelId: th.BasicPost.ChannelId,
Name: searchTerm,
Path: searchTerm,
Extension: "jpg",
MimeType: "image/jpeg",
})
fileInfo, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
PostId: th.BasicPost.Id,
ChannelId: th.BasicPost.ChannelId,
Name: searchTerm,
Path: searchTerm,
Extension: "jpg",
MimeType: "image/jpeg",
})
time.Sleep(1 * time.Millisecond)
require.NoError(t, err)
@@ -693,22 +694,23 @@ func TestSetFileSearchableContent(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
fileInfo, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{
CreatorId: th.BasicUser.Id,
PostId: th.BasicPost.Id,
ChannelId: th.BasicPost.ChannelId,
Name: "test",
Path: "test",
Extension: "jpg",
MimeType: "image/jpeg",
})
fileInfo, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
PostId: th.BasicPost.Id,
ChannelId: th.BasicPost.ChannelId,
Name: "test",
Path: "test",
Extension: "jpg",
MimeType: "image/jpeg",
})
require.NoError(t, err)
result, appErr := th.App.SearchFilesInTeamForUser(th.Context, "searchable", th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, 0, 60)
require.Nil(t, appErr)
assert.Equal(t, 0, len(result.Order))
appErr = th.App.SetFileSearchableContent(fileInfo.Id, "searchable")
appErr = th.App.SetFileSearchableContent(th.Context, fileInfo.Id, "searchable")
require.Nil(t, appErr)
result, appErr = th.App.SearchFilesInTeamForUser(th.Context, "searchable", th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, 0, 60)

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

@@ -1216,7 +1216,7 @@ func (a *App) importReplies(rctx request.CTX, data []imports.ReplyImportData, po
fileIDs := a.uploadAttachments(rctx, replyData.Attachments, reply, teamID)
for _, fileID := range reply.FileIds {
if _, ok := fileIDs[fileID]; !ok {
a.Srv().Store().FileInfo().PermanentDelete(fileID)
a.Srv().Store().FileInfo().PermanentDelete(rctx, fileID)
}
}
reply.FileIds = make([]string, 0)
@@ -1519,7 +1519,7 @@ func (a *App) importMultiplePostLines(rctx request.CTX, lines []imports.LineImpo
fileIDs := a.uploadAttachments(rctx, line.Post.Attachments, post, team.Id)
for _, fileID := range post.FileIds {
if _, ok := fileIDs[fileID]; !ok {
a.Srv().Store().FileInfo().PermanentDelete(fileID)
a.Srv().Store().FileInfo().PermanentDelete(rctx, fileID)
}
}
post.FileIds = make([]string, 0)
@@ -1642,7 +1642,7 @@ func (a *App) uploadAttachments(rctx request.CTX, attachments *[]imports.Attachm
func (a *App) updateFileInfoWithPostId(rctx request.CTX, post *model.Post) {
for _, fileID := range post.FileIds {
if err := a.Srv().Store().FileInfo().AttachToPost(fileID, post.Id, post.ChannelId, post.UserId); err != nil {
if err := a.Srv().Store().FileInfo().AttachToPost(rctx, fileID, post.Id, post.ChannelId, post.UserId); err != nil {
rctx.Logger().Error("Error attaching files to post.", mlog.String("post_id", post.Id), mlog.Array("post_file_ids", post.FileIds), mlog.Err(err))
}
}
@@ -1718,7 +1718,7 @@ func (a *App) importDirectChannel(rctx request.CTX, data *imports.DirectChannelI
if data.Header != nil {
channel.Header = *data.Header
if _, appErr := a.Srv().Store().Channel().Update(channel); appErr != nil {
if _, appErr := a.Srv().Store().Channel().Update(rctx, channel); appErr != nil {
return model.NewAppError("BulkImport", "app.import.import_direct_channel.update_header_failed.error", nil, "", http.StatusBadRequest).Wrap(appErr)
}
}
@@ -1832,7 +1832,7 @@ func (a *App) importMultipleDirectPostLines(rctx request.CTX, lines []imports.Li
fileIDs := a.uploadAttachments(rctx, line.DirectPost.Attachments, post, "noteam")
for _, fileID := range post.FileIds {
if _, ok := fileIDs[fileID]; !ok {
a.Srv().Store().FileInfo().PermanentDelete(fileID)
a.Srv().Store().FileInfo().PermanentDelete(rctx, fileID)
}
}
post.FileIds = make([]string, 0)

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

@@ -456,7 +456,7 @@ func (a *App) doLocalWarnMetricsRequest(c request.CTX, rawURL string, upstreamRe
license := a.Srv().License()
if license != nil {
mlog.Debug("License is present, skip this call")
c.Logger().Debug("License is present, skip this call")
return nil
}
@@ -554,7 +554,7 @@ func (a *App) buildWarnMetricMailtoLink(rctx request.CTX, warnMetricId string, u
registeredUsersCount, err := a.Srv().Store().User().Count(model.UserCountOptions{})
if err != nil {
mlog.Warn("Error retrieving the number of registered users", mlog.Err(err))
rctx.Logger().Warn("Error retrieving the number of registered users", mlog.Err(err))
} else {
mailBody += i18n.T("api.server.warn_metric.bot_response.mailto_registered_users_header", map[string]any{"NoRegisteredUsers": registeredUsersCount})
mailBody += "\r\n"

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

@@ -72,7 +72,7 @@ func (a *App) AuthenticateUserForLogin(c request.CTX, id, loginId, password, mfa
}
token, err := a.Srv().Store().Token().GetByToken(cwsToken)
if nfErr := new(store.ErrNotFound); err != nil && !errors.As(err, &nfErr) {
mlog.Debug("Error retrieving the cws token from the store", mlog.Err(err))
c.Logger().Debug("Error retrieving the cws token from the store", mlog.Err(err))
return nil, model.NewAppError("AuthenticateUserForLogin",
"api.user.login_by_cws.invalid_token.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -90,7 +90,7 @@ func (a *App) AuthenticateUserForLogin(c request.CTX, id, loginId, password, mfa
}
err := a.Srv().Store().Token().Save(token)
if err != nil {
mlog.Debug("Error storing the cws token in the store", mlog.Err(err))
c.Logger().Debug("Error storing the cws token in the store", mlog.Err(err))
return nil, model.NewAppError("AuthenticateUserForLogin",
"api.user.login_by_cws.invalid_token.app_error", nil, "", http.StatusInternalServerError)
}

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

@@ -139,7 +139,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea
go func() {
_, 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))
c.Logger().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))
}
}()
@@ -262,7 +262,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea
nErr := a.Srv().Store().Channel().IncrementMentionCount(post.ChannelId, mentionedUsersList, post.RootId == "", post.IsUrgent())
if nErr != nil {
mlog.Warn(
c.Logger().Warn(
"Failed to update mention count",
mlog.String("post_id", post.Id),
mlog.String("channel_id", post.ChannelId),
@@ -273,7 +273,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea
// Log the problems that might have occurred while auto following the thread
for _, mac := range mentionAutofollowChans {
if err := <-mac; err != nil {
mlog.Warn(
c.Logger().Warn(
"Failed to update thread autofollow from mention",
mlog.String("post_id", post.Id),
mlog.String("channel_id", post.ChannelId),
@@ -317,7 +317,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea
//If email verification is required and user email is not verified don't send email.
if *a.Config().EmailSettings.RequireEmailVerification && !profileMap[id].EmailVerified {
mlog.Debug("Skipped sending notification email, address not verified.", mlog.String("user_email", profileMap[id].Email), mlog.String("user_id", id))
c.Logger().Debug("Skipped sending notification email, address not verified.", mlog.String("user_email", profileMap[id].Email), mlog.String("user_id", id))
continue
}
@@ -327,7 +327,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea
a.Log().Warn("Unable to get the sender user profile image.", mlog.String("user_id", sender.Id), mlog.Err(err))
}
if err := a.sendNotificationEmail(c, notification, profileMap[id], team, senderProfileImage); err != nil {
mlog.Warn("Unable to send notification email.", mlog.Err(err))
c.Logger().Warn("Unable to send notification email.", mlog.Err(err))
}
}
}
@@ -504,7 +504,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea
var infos []*model.FileInfo
if fResult := <-fchan; fResult.NErr != nil {
mlog.Warn("Unable to get fileInfo for push notifications.", mlog.String("post_id", post.Id), mlog.Err(fResult.NErr))
c.Logger().Warn("Unable to get fileInfo for push notifications.", mlog.String("post_id", post.Id), mlog.Err(fResult.NErr))
} else {
infos = fResult.Data
}
@@ -596,7 +596,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea
payload, jsonErr := json.Marshal(userThread)
if jsonErr != nil {
mlog.Warn("Failed to encode thread to JSON")
c.Logger().Warn("Failed to encode thread to JSON")
}
message.Add("thread", string(payload))
message.Add("previous_unread_mentions", previousUnreadMentions)
@@ -735,7 +735,7 @@ func (a *App) RemoveNotifications(c request.CTX, post *model.Post, channel *mode
payload, jsonErr := json.Marshal(userThread)
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, team.Id, "", userID, nil, "")
@@ -849,7 +849,7 @@ func (a *App) userAllowsEmail(c request.CTX, user *model.User, channelMemberNoti
// Remove the user as recipient when the user has muted the channel.
if channelMuted, ok := channelMemberNotificationProps[model.MarkUnreadNotifyProp]; ok {
if channelMuted == model.ChannelMarkUnreadMention {
mlog.Debug("Channel muted for user", mlog.String("user_id", user.Id), mlog.String("channel_mute", channelMuted))
c.Logger().Debug("Channel muted for user", mlog.String("user_id", user.Id), mlog.String("channel_mute", channelMuted))
userAllowsEmails = false
}
}

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

@@ -133,7 +133,7 @@ func (a *App) sendNotificationEmail(c request.CTX, notification *PostNotificatio
a.Srv().Go(func() {
if nErr := a.Srv().EmailService.SendMailWithEmbeddedFiles(user.Email, html.UnescapeString(subjectText), bodyText, embeddedFiles, messageID, inReplyTo, references, "Notification"); nErr != nil {
mlog.Error("Error while sending the email", mlog.String("user_email", user.Email), mlog.Err(nErr))
c.Logger().Error("Error while sending the email", mlog.String("user_email", user.Email), mlog.Err(nErr))
}
})
@@ -238,13 +238,13 @@ func (a *App) getNotificationEmailBody(c request.CTX, recipient *model.User, pos
postMessage = html.EscapeString(postMessage)
mdPostMessage, mdErr := utils.MarkdownToHTML(postMessage, a.GetSiteURL())
if mdErr != nil {
mlog.Warn("Encountered error while converting markdown to HTML", mlog.Err(mdErr))
c.Logger().Warn("Encountered error while converting markdown to HTML", mlog.Err(mdErr))
mdPostMessage = postMessage
}
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))
c.Logger().Warn("Encountered error while generating hyperlink for channels", mlog.String("team_name", teamName), mlog.Err(err))
normalizedPostMessage = mdPostMessage
}
pData.Message = template.HTML(normalizedPostMessage)

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

@@ -377,11 +377,11 @@ func (hub *PushNotificationsHub) start(c request.CTX) {
case notificationTypeUpdateBadge:
err = hub.app.updateMobileAppBadgeSync(c, notification.userID)
default:
mlog.Debug("Invalid notification type", mlog.String("notification_type", notification.notificationType))
c.Logger().Debug("Invalid notification type", mlog.String("notification_type", notification.notificationType))
}
if err != nil {
mlog.Error("Unable to send push notification", mlog.String("notification_type", notification.notificationType), mlog.Err(err))
c.Logger().Error("Unable to send push notification", mlog.String("notification_type", notification.notificationType), mlog.Err(err))
}
}(notification)
case <-hub.stopChan:
@@ -717,7 +717,7 @@ func (a *App) buildFullPushNotificationMessage(c request.CTX, contentsConfig str
postMessage := post.Message
stripped, err := utils.StripMarkdown(postMessage)
if err != nil {
mlog.Warn("Failed parse to markdown", mlog.String("post_id", post.Id), mlog.Err(err))
c.Logger().Warn("Failed parse to markdown", mlog.String("post_id", post.Id), mlog.Err(err))
} else {
postMessage = stripped
}

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

@@ -220,7 +220,7 @@ func (a *App) AllowOAuthAppAccessToUser(c request.CTX, userID string, authReques
}
if err != nil {
mlog.Warn("error getting oauth redirect uri", mlog.Err(err))
c.Logger().Warn("error getting oauth redirect uri", mlog.Err(err))
return authRequest.RedirectURI + "?error=server_error&state=" + authRequest.State, nil
}
@@ -233,7 +233,7 @@ func (a *App) AllowOAuthAppAccessToUser(c request.CTX, userID string, authReques
}
if nErr := a.Srv().Store().Preference().Save(model.Preferences{authorizedApp}); nErr != nil {
mlog.Warn("error saving store preference", mlog.Err(nErr))
c.Logger().Warn("error saving store preference", mlog.Err(nErr))
return authRequest.RedirectURI + "?error=server_error&state=" + authRequest.State, nil
}
@@ -295,7 +295,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(c request.CTX, clientId, grantType,
if authData.IsExpired() {
if nErr = a.Srv().Store().OAuth().RemoveAuthData(authData.Code); nErr != nil {
mlog.Warn("unable to remove auth data", mlog.Err(nErr))
c.Logger().Warn("unable to remove auth data", mlog.Err(nErr))
}
return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusForbidden)
}
@@ -358,7 +358,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(c request.CTX, clientId, grantType,
}
if nErr = a.Srv().Store().OAuth().RemoveAuthData(authData.Code); nErr != nil {
mlog.Warn("unable to remove auth data", mlog.Err(nErr))
c.Logger().Warn("unable to remove auth data", mlog.Err(nErr))
}
} else {
// When grantType is refresh_token
@@ -406,7 +406,7 @@ func (a *App) newSession(c request.CTX, app *model.OAuthApp, user *model.User) (
func (a *App) newSessionUpdateToken(c request.CTX, app *model.OAuthApp, accessData *model.AccessData, user *model.User) (*model.AccessResponse, *model.AppError) {
// Remove the previous session
if err := a.Srv().Store().Session().Remove(accessData.Token); err != nil {
mlog.Warn("error removing access data token from session", mlog.Err(err))
c.Logger().Warn("error removing access data token from session", mlog.Err(err))
}
session, err := a.newSession(c, app, user)
@@ -694,7 +694,7 @@ func (a *App) CompleteSwitchWithOAuth(c request.CTX, service string, userData io
a.Srv().Go(func() {
if err := a.Srv().EmailService.SendSignInChangeEmail(user.Email, strings.Title(service)+" SSO", user.Locale, a.GetSiteURL()); err != nil {
mlog.Error("error sending signin change email", mlog.Err(err))
c.Logger().Error("error sending signin change email", mlog.Err(err))
}
})
@@ -837,7 +837,7 @@ func (a *App) AuthorizeOAuthUser(c request.CTX, w http.ResponseWriter, r *http.R
appErr = a.DeleteToken(expectedToken)
if appErr != nil {
mlog.Warn("error deleting token", mlog.Err(appErr))
c.Logger().Warn("error deleting token", mlog.Err(appErr))
}
subpath, _ := utils.GetSubpathFromConfig(a.Config())
@@ -921,7 +921,7 @@ func (a *App) AuthorizeOAuthUser(c request.CTX, w http.ResponseWriter, r *http.R
bodyBytes, _ := io.ReadAll(resp.Body)
bodyString := string(bodyBytes)
mlog.Error("Error getting OAuth user", mlog.Int("response", resp.StatusCode), mlog.String("body_string", bodyString))
c.Logger().Error("Error getting OAuth user", mlog.Int("response", resp.StatusCode), mlog.String("body_string", bodyString))
if service == model.ServiceGitlab && resp.StatusCode == http.StatusForbidden && strings.Contains(bodyString, "Terms of Service") {
url, err := url.Parse(*sso.UserAPIEndpoint)

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

@@ -31,7 +31,7 @@ func (a *App) CompleteOnboarding(c request.CTX, request *model.CompleteOnboardin
isCloud := a.Srv().License() != nil && *a.Srv().License().Features.Cloud
if !isCloud && request.Organization == "" {
mlog.Error("No organization name provided for self hosted onboarding")
c.Logger().Error("No organization name provided for self hosted onboarding")
return model.NewAppError("CompleteOnboarding", "api.error_no_organization_name_provided_for_self_hosted_onboarding", nil, "", http.StatusBadRequest)
}
@@ -59,19 +59,19 @@ func (a *App) CompleteOnboarding(c request.CTX, request *model.CompleteOnboardin
}
_, appErr := a.Channels().InstallMarketplacePlugin(installRequest)
if appErr != nil {
mlog.Error("Failed to install plugin for onboarding", mlog.String("id", id), mlog.Err(appErr))
c.Logger().Error("Failed to install plugin for onboarding", mlog.String("id", id), mlog.Err(appErr))
return
}
appErr = a.EnablePlugin(id)
if appErr != nil {
mlog.Error("Failed to enable plugin for onboarding", mlog.String("id", id), mlog.Err(appErr))
c.Logger().Error("Failed to enable plugin for onboarding", mlog.String("id", id), mlog.Err(appErr))
return
}
hooks, err := a.ch.HooksForPluginOrProduct(id)
if err != nil {
mlog.Warn("Getting hooks for plugin failed", mlog.String("plugin_id", id), mlog.Err(err))
c.Logger().Warn("Getting hooks for plugin failed", mlog.String("plugin_id", id), mlog.Err(err))
return
}
@@ -79,7 +79,7 @@ func (a *App) CompleteOnboarding(c request.CTX, request *model.CompleteOnboardin
UserId: c.Session().UserId,
}
if err = hooks.OnInstall(pluginContext, event); err != nil {
mlog.Error("Plugin OnInstall hook failed", mlog.String("plugin_id", id), mlog.Err(err))
c.Logger().Error("Plugin OnInstall hook failed", mlog.String("plugin_id", id), mlog.Err(err))
}
}(pluginID)
}

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

@@ -881,7 +881,7 @@ func (a *OpenTracingAppLayer) AutocompleteChannelsForTeam(c request.CTX, teamID
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) AutocompleteUsersInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) {
func (a *OpenTracingAppLayer) AutocompleteUsersInChannel(rctx request.CTX, teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteUsersInChannel")
@@ -893,7 +893,7 @@ func (a *OpenTracingAppLayer) AutocompleteUsersInChannel(teamID string, channelI
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.AutocompleteUsersInChannel(teamID, channelID, term, options)
resultVar0, resultVar1 := a.app.AutocompleteUsersInChannel(rctx, teamID, channelID, term, options)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -903,7 +903,7 @@ func (a *OpenTracingAppLayer) AutocompleteUsersInChannel(teamID string, channelI
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) AutocompleteUsersInTeam(teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) {
func (a *OpenTracingAppLayer) AutocompleteUsersInTeam(rctx request.CTX, teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteUsersInTeam")
@@ -915,7 +915,7 @@ func (a *OpenTracingAppLayer) AutocompleteUsersInTeam(teamID string, term string
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.AutocompleteUsersInTeam(teamID, term, options)
resultVar0, resultVar1 := a.app.AutocompleteUsersInTeam(rctx, teamID, term, options)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -1862,7 +1862,7 @@ func (a *OpenTracingAppLayer) ConvertUserToBot(user *model.User) (*model.Bot, *m
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) CopyFileInfos(userID string, fileIDs []string) ([]string, *model.AppError) {
func (a *OpenTracingAppLayer) CopyFileInfos(rctx request.CTX, userID string, fileIDs []string) ([]string, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CopyFileInfos")
@@ -1874,7 +1874,7 @@ func (a *OpenTracingAppLayer) CopyFileInfos(userID string, fileIDs []string) ([]
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.CopyFileInfos(userID, fileIDs)
resultVar0, resultVar1 := a.app.CopyFileInfos(rctx, userID, fileIDs)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -4063,7 +4063,7 @@ func (a *OpenTracingAppLayer) EnableUserAccessToken(c request.CTX, token *model.
return resultVar0
}
func (a *OpenTracingAppLayer) EnsureBot(c request.CTX, productID string, bot *model.Bot) (string, error) {
func (a *OpenTracingAppLayer) EnsureBot(rctx request.CTX, productID string, bot *model.Bot) (string, error) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.EnsureBot")
@@ -4075,7 +4075,7 @@ func (a *OpenTracingAppLayer) EnsureBot(c request.CTX, productID string, bot *mo
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.EnsureBot(c, productID, bot)
resultVar0, resultVar1 := a.app.EnsureBot(rctx, productID, bot)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -12809,7 +12809,7 @@ func (a *OpenTracingAppLayer) OverrideIconURLIfEmoji(c request.CTX, post *model.
a.app.OverrideIconURLIfEmoji(c, post)
}
func (a *OpenTracingAppLayer) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
func (a *OpenTracingAppLayer) PatchBot(rctx request.CTX, botUserId string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchBot")
@@ -12821,7 +12821,7 @@ func (a *OpenTracingAppLayer) PatchBot(botUserId string, botPatch *model.BotPatc
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.PatchBot(botUserId, botPatch)
resultVar0, resultVar1 := a.app.PatchBot(rctx, botUserId, botPatch)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -13461,7 +13461,7 @@ func (a *OpenTracingAppLayer) PublishUserTyping(userID string, channelID string,
return resultVar0
}
func (a *OpenTracingAppLayer) PurgeBleveIndexes() *model.AppError {
func (a *OpenTracingAppLayer) PurgeBleveIndexes(c request.CTX) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PurgeBleveIndexes")
@@ -13473,7 +13473,7 @@ func (a *OpenTracingAppLayer) PurgeBleveIndexes() *model.AppError {
}()
defer span.Finish()
resultVar0 := a.app.PurgeBleveIndexes()
resultVar0 := a.app.PurgeBleveIndexes(c)
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
@@ -13483,7 +13483,7 @@ func (a *OpenTracingAppLayer) PurgeBleveIndexes() *model.AppError {
return resultVar0
}
func (a *OpenTracingAppLayer) PurgeElasticsearchIndexes() *model.AppError {
func (a *OpenTracingAppLayer) PurgeElasticsearchIndexes(c request.CTX) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PurgeElasticsearchIndexes")
@@ -13495,7 +13495,7 @@ func (a *OpenTracingAppLayer) PurgeElasticsearchIndexes() *model.AppError {
}()
defer span.Finish()
resultVar0 := a.app.PurgeElasticsearchIndexes()
resultVar0 := a.app.PurgeElasticsearchIndexes(c)
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
@@ -15212,7 +15212,7 @@ func (a *OpenTracingAppLayer) SearchUserAccessTokens(term string) ([]*model.User
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) SearchUsers(props *model.UserSearch, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
func (a *OpenTracingAppLayer) SearchUsers(rctx request.CTX, props *model.UserSearch, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsers")
@@ -15224,7 +15224,7 @@ func (a *OpenTracingAppLayer) SearchUsers(props *model.UserSearch, options *mode
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.SearchUsers(props, options)
resultVar0, resultVar1 := a.app.SearchUsers(rctx, props, options)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -15278,7 +15278,7 @@ func (a *OpenTracingAppLayer) SearchUsersInGroup(groupID string, term string, op
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) SearchUsersInTeam(teamID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
func (a *OpenTracingAppLayer) SearchUsersInTeam(rctx request.CTX, teamID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersInTeam")
@@ -15290,7 +15290,7 @@ func (a *OpenTracingAppLayer) SearchUsersInTeam(teamID string, term string, opti
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.SearchUsersInTeam(teamID, term, options)
resultVar0, resultVar1 := a.app.SearchUsersInTeam(rctx, teamID, term, options)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -16079,7 +16079,7 @@ func (a *OpenTracingAppLayer) SetDefaultProfileImage(c request.CTX, user *model.
return resultVar0
}
func (a *OpenTracingAppLayer) SetFileSearchableContent(fileID string, data string) *model.AppError {
func (a *OpenTracingAppLayer) SetFileSearchableContent(rctx request.CTX, fileID string, data string) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetFileSearchableContent")
@@ -16091,7 +16091,7 @@ func (a *OpenTracingAppLayer) SetFileSearchableContent(fileID string, data strin
}()
defer span.Finish()
resultVar0 := a.app.SetFileSearchableContent(fileID, data)
resultVar0 := a.app.SetFileSearchableContent(rctx, fileID, data)
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
@@ -16833,7 +16833,7 @@ func (a *OpenTracingAppLayer) TelemetryId() string {
return resultVar0
}
func (a *OpenTracingAppLayer) TestElasticsearch(cfg *model.Config) *model.AppError {
func (a *OpenTracingAppLayer) TestElasticsearch(rctx request.CTX, cfg *model.Config) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TestElasticsearch")
@@ -16845,7 +16845,7 @@ func (a *OpenTracingAppLayer) TestElasticsearch(cfg *model.Config) *model.AppErr
}()
defer span.Finish()
resultVar0 := a.app.TestElasticsearch(cfg)
resultVar0 := a.app.TestElasticsearch(rctx, cfg)
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))

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

@@ -5,7 +5,6 @@ package platform
import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
)
func (ps *PlatformService) StartSearchEngine() (string, string) {
@@ -26,23 +25,23 @@ func (ps *PlatformService) StartSearchEngine() (string, string) {
if ps.SearchEngine.ElasticsearchEngine != nil && !*oldConfig.ElasticsearchSettings.EnableIndexing && *newConfig.ElasticsearchSettings.EnableIndexing {
ps.Go(func() {
if err := ps.SearchEngine.ElasticsearchEngine.Start(); err != nil {
mlog.Error(err.Error())
ps.Log().Error(err.Error())
}
})
} else if ps.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.EnableIndexing && !*newConfig.ElasticsearchSettings.EnableIndexing {
ps.Go(func() {
if err := ps.SearchEngine.ElasticsearchEngine.Stop(); err != nil {
mlog.Error(err.Error())
ps.Log().Error(err.Error())
}
})
} else if ps.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.Password != *newConfig.ElasticsearchSettings.Password || *oldConfig.ElasticsearchSettings.Username != *newConfig.ElasticsearchSettings.Username || *oldConfig.ElasticsearchSettings.ConnectionURL != *newConfig.ElasticsearchSettings.ConnectionURL || *oldConfig.ElasticsearchSettings.Sniff != *newConfig.ElasticsearchSettings.Sniff {
ps.Go(func() {
if *oldConfig.ElasticsearchSettings.EnableIndexing {
if err := ps.SearchEngine.ElasticsearchEngine.Stop(); err != nil {
mlog.Error(err.Error())
ps.Log().Error(err.Error())
}
if err := ps.SearchEngine.ElasticsearchEngine.Start(); err != nil {
mlog.Error(err.Error())
ps.Log().Error(err.Error())
}
}
})
@@ -57,7 +56,7 @@ func (ps *PlatformService) StartSearchEngine() (string, string) {
if ps.SearchEngine.ElasticsearchEngine != nil && ps.SearchEngine.ElasticsearchEngine.IsActive() {
ps.Go(func() {
if err := ps.SearchEngine.ElasticsearchEngine.Start(); err != nil {
mlog.Error(err.Error())
ps.Log().Error(err.Error())
}
})
}
@@ -65,7 +64,7 @@ func (ps *PlatformService) StartSearchEngine() (string, string) {
if ps.SearchEngine.ElasticsearchEngine != nil {
ps.Go(func() {
if err := ps.SearchEngine.ElasticsearchEngine.Stop(); err != nil {
mlog.Error(err.Error())
ps.Log().Error(err.Error())
}
})
}

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

@@ -205,7 +205,7 @@ func New(sc ServiceConfig, options ...Option) (*PlatformService, error) {
// |
// Cache layer
var err error
ps.sqlStore, err = sqlstore.New(ps.Config().SqlSettings, ps.metricsIFace)
ps.sqlStore, err = sqlstore.New(ps.Config().SqlSettings, ps.Log(), ps.metricsIFace)
if err != nil {
return nil, err
}

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

@@ -512,7 +512,7 @@ func (api *PluginAPI) SearchUsers(search *model.UserSearch) ([]*model.User, *mod
AllowInactive: search.AllowInactive,
Limit: search.Limit,
}
return api.app.SearchUsers(search, pluginSearchUsersOptions)
return api.app.SearchUsers(api.ctx, search, pluginSearchUsersOptions)
}
func (api *PluginAPI) SearchPostsInTeam(teamID string, paramsList []*model.SearchParams) ([]*model.Post, *model.AppError) {
@@ -763,7 +763,7 @@ func (api *PluginAPI) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) {
}
func (api *PluginAPI) CopyFileInfos(userID string, fileIDs []string) ([]string, *model.AppError) {
return api.app.CopyFileInfos(userID, fileIDs)
return api.app.CopyFileInfos(api.ctx, userID, fileIDs)
}
func (api *PluginAPI) GetFileInfo(fileID string) (*model.FileInfo, *model.AppError) {
@@ -771,7 +771,7 @@ func (api *PluginAPI) GetFileInfo(fileID string) (*model.FileInfo, *model.AppErr
}
func (api *PluginAPI) SetFileSearchableContent(fileID string, content string) *model.AppError {
return api.app.SetFileSearchableContent(fileID, content)
return api.app.SetFileSearchableContent(api.ctx, fileID, content)
}
func (api *PluginAPI) GetFileInfos(page, perPage int, opt *model.GetFileInfosOptions) ([]*model.FileInfo, *model.AppError) {
@@ -1008,7 +1008,7 @@ func (api *PluginAPI) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) {
}
func (api *PluginAPI) PatchBot(userID string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
return api.app.PatchBot(userID, botPatch)
return api.app.PatchBot(api.ctx, userID, botPatch)
}
func (api *PluginAPI) GetBot(userID string, includeDeleted bool) (*model.Bot, *model.AppError) {

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

@@ -564,7 +564,7 @@ func TestPluginAPIGetFile(t *testing.T) {
info, err := th.App.DoUploadFile(th.Context, uploadTime, th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, filename, fileData)
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info.Id)
th.App.RemoveFile(info.Path)
}()
@@ -593,7 +593,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) {
)
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo1.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, fileInfo1.Id)
th.App.RemoveFile(fileInfo1.Path)
}()
@@ -607,7 +607,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) {
)
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo2.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, fileInfo2.Id)
th.App.RemoveFile(fileInfo2.Path)
}()
@@ -621,7 +621,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) {
)
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo3.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, fileInfo3.Id)
th.App.RemoveFile(fileInfo3.Path)
}()
@@ -1354,7 +1354,7 @@ func TestPluginCreatePostWithUploadedFile(t *testing.T) {
fileInfo, err := api.UploadFile(data, channelID, filename)
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, fileInfo.Id)
th.App.RemoveFile(fileInfo.Path)
}()

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

@@ -33,7 +33,7 @@ func (p *MyPlugin) MessageWillBePosted(_ *plugin.Context, _ *model.Post) (*model
rctx := request.TestContext(p.t)
settings := p.API.GetUnsanitizedConfig().SqlSettings
settings.Trace = model.NewBool(false)
store, err := sqlstore.New(settings, nil)
store, err := sqlstore.New(settings, rctx.Logger(), nil)
if err != nil {
panic(err)
}

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

@@ -170,7 +170,7 @@ func (a *App) tryExecutePluginCommand(c request.CTX, args *model.CommandArgs) (*
// This is a response from the plugin, which may set an incorrect status code;
// e.g setting a status code of 0 will crash the server. So we always bucket everything under 500.
if appErr != nil && (appErr.StatusCode < 100 || appErr.StatusCode > 999) {
mlog.Warn("Invalid status code returned from plugin. Converting to internal server error.", mlog.String("plugin_id", matched.PluginId), mlog.Int("status_code", appErr.StatusCode))
c.Logger().Warn("Invalid status code returned from plugin. Converting to internal server error.", mlog.String("plugin_id", matched.PluginId), mlog.Int("status_code", appErr.StatusCode))
appErr.StatusCode = http.StatusInternalServerError
}

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

@@ -361,7 +361,7 @@ func (a *App) CreatePost(c request.CTX, post *model.Post, channel *model.Channel
}
if len(post.FileIds) > 0 {
if err = a.attachFilesToPost(post); err != nil {
if err = a.attachFilesToPost(c, post); err != nil {
c.Logger().Warn("Encountered error attaching files to post", mlog.String("post_id", post.Id), mlog.Array("file_ids", post.FileIds), mlog.Err(err))
}
@@ -422,23 +422,23 @@ func (a *App) CreatePost(c request.CTX, post *model.Post, channel *model.Channel
return rpost, nil
}
func (a *App) addPostPreviewProp(post *model.Post) (*model.Post, error) {
func (a *App) addPostPreviewProp(rctx request.CTX, post *model.Post) (*model.Post, error) {
previewPost := post.GetPreviewPost()
if previewPost != nil {
updatedPost := post.Clone()
updatedPost.AddProp(model.PostPropsPreviewedPost, previewPost.PostID)
updatedPost, err := a.Srv().Store().Post().Update(updatedPost, post)
updatedPost, err := a.Srv().Store().Post().Update(rctx, updatedPost, post)
return updatedPost, err
}
return post, nil
}
func (a *App) attachFilesToPost(post *model.Post) *model.AppError {
func (a *App) attachFilesToPost(rctx request.CTX, post *model.Post) *model.AppError {
var attachedIds []string
for _, fileID := range post.FileIds {
err := a.Srv().Store().FileInfo().AttachToPost(fileID, post.Id, post.ChannelId, post.UserId)
err := a.Srv().Store().FileInfo().AttachToPost(rctx, fileID, post.Id, post.ChannelId, post.UserId)
if err != nil {
mlog.Warn("Failed to attach file to post", mlog.String("file_id", fileID), mlog.String("post_id", post.Id), mlog.Err(err))
rctx.Logger().Warn("Failed to attach file to post", mlog.String("file_id", fileID), mlog.String("post_id", post.Id), mlog.Err(err))
continue
}
@@ -449,7 +449,7 @@ func (a *App) attachFilesToPost(post *model.Post) *model.AppError {
// We couldn't attach all files to the post, so ensure that post.FileIds reflects what was actually attached
post.FileIds = attachedIds
if _, err := a.Srv().Store().Post().Overwrite(post); err != nil {
if _, err := a.Srv().Store().Post().Overwrite(rctx, post); err != nil {
return model.NewAppError("attachFilesToPost", "app.post.overwrite.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
}
@@ -483,7 +483,7 @@ func (a *App) FillInPostProps(c request.CTX, post *model.Post, channel *model.Ch
if mentioned.Type == model.ChannelTypeOpen {
team, err := a.Srv().Store().Team().Get(mentioned.TeamId)
if err != nil {
mlog.Warn("Failed to get team of the channel mention", mlog.String("team_id", channel.TeamId), mlog.String("channel_id", channel.Id), mlog.Err(err))
c.Logger().Warn("Failed to get team of the channel mention", mlog.String("team_id", channel.TeamId), mlog.String("channel_id", channel.Id), mlog.Err(err))
continue
}
channelMentionsProp[mentioned.Name] = map[string]any{
@@ -579,7 +579,7 @@ func (a *App) SendEphemeralPost(c request.CTX, userID string, post *model.Post)
postJSON, jsonErr := post.ToJSON()
if jsonErr != nil {
mlog.Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
c.Logger().Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
}
message.Add("post", postJSON)
a.Publish(message)
@@ -601,7 +601,7 @@ func (a *App) UpdateEphemeralPost(c request.CTX, userID string, post *model.Post
post = model.AddPostActionCookies(post, a.PostActionCookieSecret())
postJSON, jsonErr := post.ToJSON()
if jsonErr != nil {
mlog.Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
c.Logger().Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
}
message.Add("post", postJSON)
a.Publish(message)
@@ -711,7 +711,7 @@ func (a *App) UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, safeUpd
// the last known good.
newPost.Metadata = oldPost.Metadata
rpost, nErr := a.Srv().Store().Post().Update(newPost, oldPost)
rpost, nErr := a.Srv().Store().Post().Update(c, newPost, oldPost)
if nErr != nil {
var appErr *model.AppError
switch {
@@ -738,7 +738,7 @@ func (a *App) UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, safeUpd
// individually.
rpost.IsFollowing = nil
rpost, nErr = a.addPostPreviewProp(rpost)
rpost, nErr = a.addPostPreviewProp(c, rpost)
if nErr != nil {
return nil, model.NewAppError("UpdatePost", "app.post.update.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
@@ -783,14 +783,14 @@ func (a *App) publishWebsocketEventForPermalinkPost(c request.CTX, post *model.P
}
if !model.IsValidId(previewedPostID) {
mlog.Warn("invalid post prop value", mlog.String("prop_key", model.PostPropsPreviewedPost), mlog.String("prop_value", previewedPostID))
c.Logger().Warn("invalid post prop value", mlog.String("prop_key", model.PostPropsPreviewedPost), mlog.String("prop_value", previewedPostID))
return false, nil
}
previewedPost, err := a.GetSinglePost(previewedPostID, false)
if err != nil {
if err.StatusCode == http.StatusNotFound {
mlog.Warn("permalinked post not found", mlog.String("referenced_post_id", previewedPostID))
c.Logger().Warn("permalinked post not found", mlog.String("referenced_post_id", previewedPostID))
return false, nil
}
return false, err
@@ -804,7 +804,7 @@ func (a *App) publishWebsocketEventForPermalinkPost(c request.CTX, post *model.P
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))
c.Logger().Warn("channel containing permalinked post not found", mlog.String("referenced_channel_id", previewedPost.ChannelId))
return false, nil
}
return false, err
@@ -830,7 +830,7 @@ func (a *App) publishWebsocketEventForPermalinkPost(c request.CTX, post *model.P
postJSON, jsonErr := postForUser.ToJSON()
if jsonErr != nil {
mlog.Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
c.Logger().Warn("Failed to encode post to JSON", mlog.Err(jsonErr))
}
messageCopy.Add("post", postJSON)
a.Publish(messageCopy)
@@ -1343,7 +1343,7 @@ func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post,
return nil, appErr
}
err = a.Srv().Store().Post().Delete(postID, model.GetMillis(), deleteByID)
err = a.Srv().Store().Post().Delete(c, postID, model.GetMillis(), deleteByID)
if err != nil {
var nfErr *store.ErrNotFound
switch {
@@ -1378,13 +1378,13 @@ func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post,
if len(post.FileIds) > 0 {
a.Srv().Go(func() {
a.deletePostFiles(post.Id)
a.deletePostFiles(c, post.Id)
})
a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(postID, true)
a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(postID, false)
}
a.Srv().Go(func() {
a.deleteFlaggedPosts(post.Id)
a.deleteFlaggedPosts(c, post.Id)
})
pluginPost := post.ForPlugin()
@@ -1407,16 +1407,16 @@ func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post,
return post, nil
}
func (a *App) deleteFlaggedPosts(postID string) {
func (a *App) deleteFlaggedPosts(c request.CTX, postID string) {
if err := a.Srv().Store().Preference().DeleteCategoryAndName(model.PreferenceCategoryFlaggedPost, postID); err != nil {
a.Log().Warn("Unable to delete flagged post preference when deleting post.", mlog.Err(err))
c.Logger().Warn("Unable to delete flagged post preference when deleting post.", mlog.Err(err))
return
}
}
func (a *App) deletePostFiles(postID string) {
if _, err := a.Srv().Store().FileInfo().DeleteForPost(postID); err != nil {
a.Log().Warn("Encountered error when deleting files for post", mlog.String("post_id", postID), mlog.Err(err))
func (a *App) deletePostFiles(c request.CTX, postID string) {
if _, err := a.Srv().Store().FileInfo().DeleteForPost(c, postID); err != nil {
c.Logger().Warn("Encountered error when deleting files for post", mlog.String("post_id", postID), mlog.Err(err))
}
}
@@ -1500,7 +1500,7 @@ func (a *App) convertChannelNamesToChannelIds(c request.CTX, channels []string,
for idx, channelName := range channels {
channel, err := a.parseAndFetchChannelIdByNameFromInFilter(c, channelName, userID, teamID, includeDeletedChannels)
if err != nil {
a.Log().Warn("error getting channel id by name from in filter", mlog.Err(err))
c.Logger().Warn("error getting channel id by name from in filter", mlog.Err(err))
continue
}
channels[idx] = channel.Id
@@ -1508,11 +1508,11 @@ func (a *App) convertChannelNamesToChannelIds(c request.CTX, channels []string,
return channels
}
func (a *App) convertUserNameToUserIds(usernames []string) []string {
func (a *App) convertUserNameToUserIds(c request.CTX, usernames []string) []string {
for idx, username := range usernames {
user, err := a.GetUserByUsername(username)
if err != nil {
a.Log().Warn("error getting user by username", mlog.String("user_name", username), mlog.Err(err))
c.Logger().Warn("error getting user by username", mlog.String("user_name", username), mlog.Err(err))
continue
}
usernames[idx] = user.Id
@@ -1651,8 +1651,8 @@ func (a *App) SearchPostsForUser(c request.CTX, terms string, userID string, tea
params.ExcludedChannels = a.convertChannelNamesToChannelIds(c, params.ExcludedChannels, userID, teamID, includeDeletedChannels)
// Convert usernames to user IDs
params.FromUsers = a.convertUserNameToUserIds(params.FromUsers)
params.ExcludedUsers = a.convertUserNameToUserIds(params.ExcludedUsers)
params.FromUsers = a.convertUserNameToUserIds(c, params.FromUsers)
params.ExcludedUsers = a.convertUserNameToUserIds(c, params.ExcludedUsers)
finalParamsList = append(finalParamsList, params)
}
@@ -1663,7 +1663,7 @@ func (a *App) SearchPostsForUser(c request.CTX, terms string, userID string, tea
return model.MakePostSearchResults(model.NewPostList(), nil), nil
}
postSearchResults, err := a.Srv().Store().Post().SearchPostsForUser(finalParamsList, userID, teamID, page, perPage)
postSearchResults, err := a.Srv().Store().Post().SearchPostsForUser(c, finalParamsList, userID, teamID, page, perPage)
if err != nil {
var appErr *model.AppError
switch {

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

@@ -102,7 +102,7 @@ func (a *App) OverrideIconURLIfEmoji(c request.CTX, post *model.Post) {
if emojiURL, err := a.GetEmojiStaticURL(c, emojiName); err == nil {
post.AddProp(model.PostPropsOverrideIconURL, emojiURL)
} else {
mlog.Warn("Failed to retrieve URL for overridden profile icon (emoji)", mlog.String("emojiName", emojiName), mlog.Err(err))
c.Logger().Warn("Failed to retrieve URL for overridden profile icon (emoji)", mlog.String("emojiName", emojiName), mlog.Err(err))
}
}
@@ -181,7 +181,7 @@ func (a *App) getEmbedsAndImages(c request.CTX, post *model.Post, isNewPost bool
isNotFound := ok && appErr.StatusCode == http.StatusNotFound
// Ignore NotFound errors.
if !isNotFound {
mlog.Debug("Failed to get embedded content for a post", mlog.String("post_id", post.Id), mlog.Err(err))
c.Logger().Debug("Failed to get embedded content for a post", mlog.String("post_id", post.Id), mlog.Err(err))
}
} else if embed != nil {
post.Metadata.Embeds = append(post.Metadata.Embeds, embed)
@@ -359,8 +359,10 @@ func (a *App) getImagesForPost(c request.CTX, post *model.Post, imageURLs []stri
case model.PostEmbedOpengraph:
openGraph, ok := embed.Data.(*opengraph.OpenGraph)
if !ok {
mlog.Warn("Could not read the image data: the data could not be casted to OpenGraph",
mlog.String("post_id", post.Id), mlog.String("data type", fmt.Sprintf("%t", embed.Data)))
c.Logger().Warn("Could not read the image data: the data could not be casted to OpenGraph",
mlog.String("post_id", post.Id),
mlog.String("data type", fmt.Sprintf("%t", embed.Data)),
)
continue
}
for _, image := range openGraph.Images {
@@ -397,8 +399,11 @@ func (a *App) getImagesForPost(c request.CTX, post *model.Post, imageURLs []stri
isNotFound := ok && appErr.StatusCode == http.StatusNotFound
// Ignore NotFound errors.
if !isNotFound {
mlog.Debug("Failed to get dimensions of an image in a post",
mlog.String("post_id", post.Id), mlog.String("image_url", imageURL), mlog.Err(err))
c.Logger().Debug("Failed to get dimensions of an image in a post",
mlog.String("post_id", post.Id),
mlog.String("image_url", imageURL),
mlog.Err(err),
)
}
} else if image != nil {
images[imageURL] = image
@@ -684,7 +689,7 @@ func (a *App) getLinkMetadata(c request.CTX, requestURL string, timestamp int64,
var res *http.Response
res, err = client.Do(request)
if err != nil {
mlog.Warn("error fetching OG image data", mlog.Err(err))
c.Logger().Warn("error fetching OG image data", mlog.Err(err))
}
if res != nil {

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

@@ -203,22 +203,24 @@ func TestAttachFilesToPost(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
info1, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
info1, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
info2, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
info2, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
post := th.BasicPost
post.FileIds = []string{info1.Id, info2.Id}
appErr := th.App.attachFilesToPost(post)
appErr := th.App.attachFilesToPost(th.Context, post)
assert.Nil(t, appErr)
infos, _, appErr := th.App.GetFileInfosForPost(th.Context, post.Id, false, false)
@@ -230,23 +232,25 @@ func TestAttachFilesToPost(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
info1, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
PostId: model.NewId(),
})
info1, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
PostId: model.NewId(),
})
require.NoError(t, err)
info2, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
info2, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
post := th.BasicPost
post.FileIds = []string{info1.Id, info2.Id}
appErr := th.App.attachFilesToPost(post)
appErr := th.App.attachFilesToPost(th.Context, post)
assert.Nil(t, appErr)
infos, _, appErr := th.App.GetFileInfosForPost(th.Context, post.Id, false, false)
@@ -790,7 +794,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) {
info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
require.Nil(t, err)
defer func() {
th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id)
th.App.Srv().Store().FileInfo().PermanentDelete(th.Context, info1.Id)
th.App.RemoveFile(info1.Path)
}()
@@ -2781,7 +2785,7 @@ func TestCollapsedThreadFetch(t *testing.T) {
wg.Add(1)
go func() {
defer wg.Done()
th.Server.Store().Post().PermanentDeleteByUser(user1.Id)
th.Server.Store().Post().PermanentDeleteByUser(th.Context, user1.Id)
}()
require.NotPanics(t, func() {

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

@@ -7,10 +7,11 @@ import (
"net/http"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/platform/services/searchengine"
)
func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError {
func (a *App) TestElasticsearch(rctx request.CTX, cfg *model.Config) *model.AppError {
if *cfg.ElasticsearchSettings.Password == model.FakeSetting {
if *cfg.ElasticsearchSettings.ConnectionURL == *a.Config().ElasticsearchSettings.ConnectionURL && *cfg.ElasticsearchSettings.Username == *a.Config().ElasticsearchSettings.Username {
*cfg.ElasticsearchSettings.Password = *a.Config().ElasticsearchSettings.Password
@@ -24,7 +25,7 @@ func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError {
err := model.NewAppError("TestElasticsearch", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented)
return err
}
if err := seI.TestConfig(cfg); err != nil {
if err := seI.TestConfig(rctx, cfg); err != nil {
return err
}
@@ -35,27 +36,27 @@ func (a *App) SetSearchEngine(se *searchengine.Broker) {
a.ch.srv.platform.SearchEngine = se
}
func (a *App) PurgeElasticsearchIndexes() *model.AppError {
func (a *App) PurgeElasticsearchIndexes(c request.CTX) *model.AppError {
engine := a.SearchEngine().ElasticsearchEngine
if engine == nil {
err := model.NewAppError("PurgeElasticsearchIndexes", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented)
return err
}
if err := engine.PurgeIndexes(); err != nil {
if err := engine.PurgeIndexes(c); err != nil {
return err
}
return nil
}
func (a *App) PurgeBleveIndexes() *model.AppError {
func (a *App) PurgeBleveIndexes(c request.CTX) *model.AppError {
engine := a.SearchEngine().BleveEngine
if engine == nil {
err := model.NewAppError("PurgeBleveIndexes", "searchengine.bleve.disabled.error", nil, "", http.StatusNotImplemented)
return err
}
if err := engine.PurgeIndexes(); err != nil {
if err := engine.PurgeIndexes(c); err != nil {
return err
}
return nil

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

@@ -274,13 +274,17 @@ func (a *App) ExtendSessionExpiryIfNeeded(rctx request.CTX, session *model.Sessi
newExpiry := now + sessionLength
if err := a.ch.srv.platform.ExtendSessionExpiry(session, newExpiry); err != nil {
mlog.Error("Failed to update ExpiresAt", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id), mlog.Err(err))
rctx.Logger().Error("Failed to update ExpiresAt", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id), mlog.Err(err))
auditRec.AddMeta("err", err.Error())
return false
}
mlog.Debug("Session extended", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id),
mlog.Int("newExpiry", newExpiry), mlog.Int("session_length", sessionLength))
rctx.Logger().Debug("Session extended",
mlog.String("user_id", session.UserId),
mlog.String("session_id", session.Id),
mlog.Int("newExpiry", newExpiry),
mlog.Int("session_length", sessionLength),
)
auditRec.Success()
auditRec.AddEventResultState(session)

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

@@ -127,7 +127,7 @@ func (cfg *AutoUserCreator) createRandomUser(c request.CTX) (*model.User, error)
return nil, appErr
}
teamMember.CreateAt = cfg.JoinTime
_, err := cfg.app.Srv().Store().Team().UpdateMember(teamMember)
_, err := cfg.app.Srv().Store().Team().UpdateMember(c, teamMember)
if err != nil {
return nil, err
}

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

@@ -10,7 +10,6 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app"
)
@@ -49,7 +48,7 @@ func (*CustomStatusProvider) DoCommand(a *app.App, c request.CTX, args *model.Co
message = strings.TrimSpace(message)
if message == CmdCustomStatusClear {
if err := a.RemoveCustomStatus(c, args.UserId); err != nil {
mlog.Debug(err.Error())
c.Logger().Debug(err.Error())
return &model.CommandResponse{Text: args.T("api.command_custom_status.clear.app_error"), ResponseType: model.CommandResponseTypeEphemeral}
}
@@ -62,7 +61,7 @@ func (*CustomStatusProvider) DoCommand(a *app.App, c request.CTX, args *model.Co
customStatus := GetCustomStatus(message)
customStatus.PreSave()
if err := a.SetCustomStatus(c, args.UserId, customStatus); err != nil {
mlog.Debug(err.Error())
c.Logger().Debug(err.Error())
return &model.CommandResponse{Text: args.T("api.command_custom_status.app_error"), ResponseType: model.CommandResponseTypeEphemeral}
}

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

@@ -90,7 +90,7 @@ func (*EchoProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArg
time.Sleep(time.Duration(delay) * time.Second)
if _, err := a.CreatePostMissingChannel(c, post, true, true); err != nil {
mlog.Error("Unable to create /echo post.", mlog.Err(err))
c.Logger().Error("Unable to create /echo post.", mlog.Err(err))
}
})

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

@@ -9,7 +9,6 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app"
)
@@ -112,7 +111,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, c request.CTX, args *model.Comman
if a.HasPermissionTo(args.UserId, model.PermissionCreateGroupChannel) {
groupChannel, channelErr = a.CreateGroupChannel(c, targetUsersSlice, args.UserId)
if channelErr != nil {
mlog.Error(channelErr.Error())
c.Logger().Error(channelErr.Error())
return &model.CommandResponse{Text: args.T("api.command_groupmsg.group_fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral}
}
} else {

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

@@ -312,7 +312,7 @@ func (i *InviteProvider) addUserToChannel(a *app.App, c request.CTX, args *model
err.Id == "api.channel.add_user.to.channel.failed.deleted.app_error" {
return UserNotInTeam
}
mlog.Warn("addUserToChannel had unexpected error.", mlog.String("UserId", userProfile.Id), mlog.Err(err))
c.Logger().Warn("addUserToChannel had unexpected error.", mlog.String("UserId", userProfile.Id), mlog.Err(err))
return Unknown
}

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

@@ -8,7 +8,6 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app"
)
@@ -77,7 +76,7 @@ func (*InvitePeopleProvider) DoCommand(a *app.App, c request.CTX, args *model.Co
}
if err := a.InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil {
mlog.Error(err.Error())
c.Logger().Error(err.Error())
return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command.invite_people.fail")}
}

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

@@ -9,7 +9,6 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app"
"github.com/mattermost/mattermost/server/v8/channels/store"
@@ -54,7 +53,7 @@ func (*msgProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArgs
userProfile, nErr := a.Srv().Store().User().GetByUsername(targetUsername)
if nErr != nil {
mlog.Error(nErr.Error())
c.Logger().Error(nErr.Error())
return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.CommandResponseTypeEphemeral}
}
@@ -64,7 +63,7 @@ func (*msgProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArgs
canSee, err := a.UserCanSeeOtherUser(c, args.UserId, userProfile.Id)
if err != nil {
mlog.Error(err.Error())
c.Logger().Error(err.Error())
return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral}
}
if !canSee {
@@ -84,12 +83,12 @@ func (*msgProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArgs
var directChannel *model.Channel
if directChannel, err = a.GetOrCreateDirectChannel(c, args.UserId, userProfile.Id); err != nil {
mlog.Error(err.Error())
c.Logger().Error(err.Error())
return &model.CommandResponse{Text: args.T(err.Id), ResponseType: model.CommandResponseTypeEphemeral}
}
targetChannelId = directChannel.Id
} else {
mlog.Error(channelErr.Error())
c.Logger().Error(channelErr.Error())
return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.CommandResponseTypeEphemeral}
}
} else {

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

@@ -8,7 +8,6 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app"
)
@@ -110,7 +109,7 @@ func doCommand(a *app.App, c request.CTX, args *model.CommandArgs, message strin
userProfile, nErr := a.Srv().Store().User().GetByUsername(targetUsername)
if nErr != nil {
mlog.Error(nErr.Error())
c.Logger().Error(nErr.Error())
return &model.CommandResponse{
Text: args.T("api.command_remove.missing.app_error"),
ResponseType: model.CommandResponseTypeEphemeral,

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

@@ -49,14 +49,14 @@ func TestCustomStatusErrors(t *testing.T) {
tests := map[string]struct {
customStatus string
successFn string
failFn string
getFails bool
updateFails bool
expectedErr string
}{
"set custom status fails on get user": {customStatus: "set", successFn: "Update", failFn: "Get", expectedErr: MissingAccountError},
"set custom status fails on update user": {customStatus: "set", successFn: "Get", failFn: "Update", expectedErr: "app.user.update.finding.app_error"},
"remove custom status fails on get user": {customStatus: "remove", successFn: "Update", failFn: "Get", expectedErr: MissingAccountError},
"remove custom status fails on update user": {customStatus: "remove", successFn: "Get", failFn: "Update", expectedErr: "app.user.update.finding.app_error"},
"set custom status fails on get user": {customStatus: "set", getFails: true, updateFails: false, expectedErr: MissingAccountError},
"set custom status fails on update user": {customStatus: "set", getFails: false, updateFails: true, expectedErr: "app.user.update.finding.app_error"},
"remove custom status fails on get user": {customStatus: "remove", getFails: true, updateFails: false, expectedErr: MissingAccountError},
"remove custom status fails on update user": {customStatus: "remove", getFails: false, updateFails: true, expectedErr: "app.user.update.finding.app_error"},
}
for name, tc := range tests {
@@ -66,8 +66,17 @@ func TestCustomStatusErrors(t *testing.T) {
mockUserStore := mocks.UserStore{}
mockUserStore.On(tc.successFn, mock.Anything, mock.Anything).Return(mockUser, nil)
mockUserStore.On(tc.failFn, mock.Anything, mock.Anything).Return(nil, mockErr)
if tc.getFails {
mockUserStore.On("Get", mock.Anything, mock.Anything).Return(nil, mockErr)
} else {
mockUserStore.On("Get", mock.Anything, mock.Anything).Return(mockUser, nil)
}
if tc.updateFails {
mockUserStore.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(nil, mockErr)
} else {
mockUserStore.On("Update", mock.Anything, mock.Anything, mock.Anything).Return(mockUser, nil)
}
var err error
mockSessionStore := mocks.SessionStore{}

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

@@ -484,7 +484,7 @@ func (a *App) UpdateTeamMemberRoles(c request.CTX, teamID string, userID string,
member.ExplicitRoles = strings.Join(newExplicitRoles, " ")
member, nErr = a.Srv().Store().Team().UpdateMember(member)
member, nErr = a.Srv().Store().Team().UpdateMember(c, member)
if nErr != nil {
var appErr *model.AppError
switch {
@@ -523,7 +523,7 @@ func (a *App) UpdateTeamMemberSchemeRoles(c request.CTX, teamID string, userID s
member.ExplicitRoles = RemoveRoles([]string{model.TeamGuestRoleId, model.TeamUserRoleId, model.TeamAdminRoleId}, member.ExplicitRoles)
}
member, nErr := a.Srv().Store().Team().UpdateMember(member)
member, nErr := a.Srv().Store().Team().UpdateMember(c, member)
if nErr != nil {
var appErr *model.AppError
switch {
@@ -699,13 +699,13 @@ func (a *App) AddUserToTeamByToken(c request.CTX, userID string, tokenID string)
for _, channel := range channels {
_, err := a.AddUserToChannel(c, user, channel, false)
if err != nil {
mlog.Warn("Error adding user to channel", mlog.Err(err))
c.Logger().Warn("Error adding user to channel", mlog.Err(err))
}
}
}
if err := a.DeleteToken(token); err != nil {
mlog.Warn("Error while deleting token", mlog.Err(err))
c.Logger().Warn("Error while deleting token", mlog.Err(err))
}
return team, teamMember, nil
@@ -794,7 +794,7 @@ func (a *App) JoinUserToTeam(c request.CTX, team *model.Team, user *model.User,
ExcludeTeam: false,
}
if _, err := a.createInitialSidebarCategories(c, user.Id, opts); err != nil {
mlog.Warn(
c.Logger().Warn(
"Encountered an issue creating default sidebar categories.",
mlog.String("user_id", user.Id),
mlog.String("team_id", team.Id),
@@ -807,7 +807,7 @@ func (a *App) JoinUserToTeam(c request.CTX, team *model.Team, user *model.User,
if !user.IsGuest() {
// Soft error if there is an issue joining the default channels
if err := a.JoinDefaultChannels(c, team.Id, user, shouldBeAdmin, userRequestorId); err != nil {
mlog.Warn(
c.Logger().Warn(
"Encountered an issue joining default channels.",
mlog.String("user_id", user.Id),
mlog.String("team_id", team.Id),
@@ -1259,7 +1259,7 @@ func (a *App) LeaveTeam(c request.CTX, team *model.Team, user *model.User, reque
for _, channel := range channelList {
if !channel.IsGroupOrDirect() {
a.invalidateCacheForChannelMembers(channel.Id)
if nErr = a.Srv().Store().Channel().RemoveMember(channel.Id, user.Id); nErr != nil {
if nErr = a.Srv().Store().Channel().RemoveMember(c, channel.Id, user.Id); nErr != nil {
return model.NewAppError("LeaveTeam", "app.channel.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr)
}
}
@@ -1288,7 +1288,7 @@ func (a *App) LeaveTeam(c request.CTX, team *model.Team, user *model.User, reque
}
}
if err := a.ch.srv.teamService.RemoveTeamMember(teamMember); err != nil {
if err := a.ch.srv.teamService.RemoveTeamMember(c, teamMember); err != nil {
return model.NewAppError("RemoveTeamMemberFromTeam", "app.team.save_member.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}

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

@@ -327,14 +327,14 @@ func TestAddUserToTeamByToken(t *testing.T) {
)
guestEmail := rguest.Email
rguest.Email = "test@restricted.com"
_, err := th.App.Srv().Store().User().Update(rguest, false)
_, err := th.App.Srv().Store().User().Update(th.Context, rguest, false)
th.App.InvalidateCacheForUser(rguest.Id)
require.NoError(t, err)
require.NoError(t, th.App.Srv().Store().Token().Save(token))
_, _, appErr := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token)
require.Nil(t, appErr)
rguest.Email = guestEmail
_, err = th.App.Srv().Store().User().Update(rguest, false)
_, err = th.App.Srv().Store().User().Update(th.Context, rguest, false)
require.NoError(t, err)
})
@@ -351,7 +351,7 @@ func TestAddUserToTeamByToken(t *testing.T) {
TokenTypeGuestInvitation,
model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}),
)
_, err = th.App.Srv().Store().User().Update(rguest, false)
_, err = th.App.Srv().Store().User().Update(th.Context, rguest, false)
require.NoError(t, err)
require.NoError(t, th.App.Srv().Store().Token().Save(token))
_, _, appErr := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token)
@@ -1034,7 +1034,7 @@ func TestLeaveTeamPanic(t *testing.T) {
sqlstore.HasMaster(c.Context())
})
mockTeamStore.On("UpdateMember", mock.Anything).Return(nil, errors.New("repro error")) // This is the line that triggers the error
mockTeamStore.On("UpdateMember", mock.Anything, mock.Anything).Return(nil, errors.New("repro error")) // This is the line that triggers the error
mockStore.On("Channel").Return(&mockChannelStore)
mockStore.On("Preference").Return(&mockPreferenceStore)

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

@@ -179,7 +179,7 @@ func (ts *TeamService) JoinUserToTeam(c request.CTX, team *model.Team, user *mod
return nil, false, MaxMemberCountError
}
member, nErr := ts.store.UpdateMember(tm)
member, nErr := ts.store.UpdateMember(c, tm)
if nErr != nil {
return nil, false, nErr
}
@@ -189,7 +189,7 @@ func (ts *TeamService) JoinUserToTeam(c request.CTX, team *model.Team, user *mod
// RemoveTeamMember removes the team member from the team. This method sends
// the websocket message before actually removing so the user being removed gets it.
func (ts *TeamService) RemoveTeamMember(teamMember *model.TeamMember) error {
func (ts *TeamService) RemoveTeamMember(rctx request.CTX, teamMember *model.TeamMember) error {
/*
MM-43850: send leave_team event to user using `ReliableClusterSend` to improve safety
*/
@@ -212,7 +212,7 @@ func (ts *TeamService) RemoveTeamMember(teamMember *model.TeamMember) error {
teamMember.Roles = ""
teamMember.DeleteAt = model.GetMillis()
if _, nErr := ts.store.UpdateMember(teamMember); nErr != nil {
if _, nErr := ts.store.UpdateMember(rctx, teamMember); nErr != nil {
return nErr
}

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

@@ -84,7 +84,7 @@ func TestJoinUserToTeam(t *testing.T) {
member, _, err := th.service.JoinUserToTeam(th.Context, team, ruser)
require.NoError(t, err)
err = th.service.RemoveTeamMember(member)
err = th.service.RemoveTeamMember(th.Context, member)
require.NoError(t, err)
_, alreadyAdded, err := th.service.JoinUserToTeam(th.Context, team, ruser)
@@ -120,7 +120,7 @@ func TestJoinUserToTeam(t *testing.T) {
member, _, err := th.service.JoinUserToTeam(th.Context, team, ruser1)
require.NoError(t, err)
err = th.service.RemoveTeamMember(member)
err = th.service.RemoveTeamMember(th.Context, member)
require.NoError(t, err)
_, _, err = th.service.JoinUserToTeam(th.Context, team, ruser2)
require.NoError(t, err)

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

@@ -115,7 +115,7 @@ func (a *App) runPluginsHook(c request.CTX, info *model.FileInfo, file io.Reader
}
} else {
if fileErr := a.RemoveFile(tmpPath); fileErr != nil {
mlog.Warn("Failed to remove file", mlog.Err(fileErr))
c.Logger().Warn("Failed to remove file", mlog.Err(fileErr))
}
}
@@ -306,7 +306,7 @@ func (a *App) UploadData(c request.CTX, us *model.UploadSession, rd io.Reader) (
}
var storeErr error
if info, storeErr = a.Srv().Store().FileInfo().Save(info); storeErr != nil {
if info, storeErr = a.Srv().Store().FileInfo().Save(c, info); storeErr != nil {
var appErr *model.AppError
switch {
case errors.As(storeErr, &appErr):

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

@@ -885,7 +885,7 @@ func (a *App) SetProfileImageFromFile(c request.CTX, userID string, file io.Read
if err := a.Srv().Store().User().UpdateLastPictureUpdate(userID); err != nil {
c.Logger().Warn("Error with updating last picture update", mlog.Err(err))
}
a.invalidateUserCacheAndPublish(userID)
a.invalidateUserCacheAndPublish(c, userID)
a.onUserProfileChange(userID)
return nil
@@ -937,7 +937,7 @@ func (a *App) userDeactivated(c request.CTX, userID string) *model.AppError {
}
if nErr := a.Srv().Store().OAuth().RemoveAuthDataByUserId(userID); nErr != nil {
mlog.Warn("unable to remove auth data by user id", mlog.Err(nErr))
c.Logger().Warn("unable to remove auth data by user id", mlog.Err(nErr))
}
return nil
@@ -974,7 +974,7 @@ func (a *App) UpdateActive(c request.CTX, user *model.User, active bool) (*model
user.DeleteAt = user.UpdateAt
}
userUpdate, err := a.ch.srv.userService.UpdateUser(user, true)
userUpdate, err := a.ch.srv.userService.UpdateUser(c, user, true)
if err != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput
@@ -1222,7 +1222,7 @@ func (a *App) UpdateUser(c request.CTX, user *model.User, sendNotifications bool
}
}
userUpdate, err := a.ch.srv.userService.UpdateUser(user, false)
userUpdate, err := a.ch.srv.userService.UpdateUser(c, user, false)
if err != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput
@@ -1606,7 +1606,7 @@ func (a *App) UpdateUserRolesWithUser(c request.CTX, user *model.User, newRoles
user.Roles = newRoles
uchan := make(chan store.GenericStoreResult[*model.UserUpdate], 1)
go func() {
userUpdate, err := a.Srv().Store().User().Update(user, true)
userUpdate, err := a.Srv().Store().User().Update(c, user, true)
uchan <- store.GenericStoreResult[*model.UserUpdate]{Data: userUpdate, NErr: err}
close(uchan)
}()
@@ -1689,7 +1689,7 @@ func (a *App) PermanentDeleteUser(c request.CTX, user *model.User) *model.AppErr
return model.NewAppError("PermanentDeleteUser", "app.preference.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
if err := a.Srv().Store().Channel().PermanentDeleteMembersByUser(user.Id); err != nil {
if err := a.Srv().Store().Channel().PermanentDeleteMembersByUser(c, user.Id); err != nil {
return model.NewAppError("PermanentDeleteUser", "app.channel.permanent_delete_members_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -1697,7 +1697,7 @@ func (a *App) PermanentDeleteUser(c request.CTX, user *model.User) *model.AppErr
return model.NewAppError("PermanentDeleteUser", "app.group.permanent_delete_members_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
if err := a.Srv().Store().Post().PermanentDeleteByUser(user.Id); err != nil {
if err := a.Srv().Store().Post().PermanentDeleteByUser(c, user.Id); err != nil {
return model.NewAppError("PermanentDeleteUser", "app.post.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -1756,7 +1756,7 @@ func (a *App) PermanentDeleteUser(c request.CTX, user *model.User) *model.AppErr
if errProfileImageExists != nil {
fileHandlingErrorsFound = true
mlog.Warn(
c.Logger().Warn(
"Error checking existence of profile image.",
mlog.String("path", profileImagePath),
mlog.Err(errProfileImageExists),
@@ -1768,7 +1768,7 @@ func (a *App) PermanentDeleteUser(c request.CTX, user *model.User) *model.AppErr
if errRemoveDirectory != nil {
fileHandlingErrorsFound = true
mlog.Warn(
c.Logger().Warn(
"Unable to remove profile image directory",
mlog.String("path", profileImageDirectory),
mlog.Err(errRemoveDirectory),
@@ -1776,7 +1776,7 @@ func (a *App) PermanentDeleteUser(c request.CTX, user *model.User) *model.AppErr
}
}
if _, err := a.Srv().Store().FileInfo().PermanentDeleteByUser(user.Id); err != nil {
if _, err := a.Srv().Store().FileInfo().PermanentDeleteByUser(c, user.Id); err != nil {
return model.NewAppError("PermanentDeleteUser", "app.file_info.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -1788,7 +1788,7 @@ func (a *App) PermanentDeleteUser(c request.CTX, user *model.User) *model.AppErr
return model.NewAppError("PermanentDeleteUser", "app.audit.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
if err := a.Srv().Store().Team().RemoveAllMembersByUser(user.Id); err != nil {
if err := a.Srv().Store().Team().RemoveAllMembersByUser(c, user.Id); err != nil {
return model.NewAppError("PermanentDeleteUser", "app.team.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -1877,7 +1877,7 @@ func (a *App) VerifyEmailFromToken(c request.CTX, userSuppliedTokenString string
if user.Email != tokenData.Email {
a.Srv().Go(func() {
if err := a.Srv().EmailService.SendEmailChangeEmail(user.Email, tokenData.Email, user.Locale, a.GetSiteURL()); err != nil {
mlog.Error("Failed to send email change email", mlog.Err(err))
c.Logger().Error("Failed to send email change email", mlog.Err(err))
}
})
}
@@ -1945,7 +1945,7 @@ func (a *App) VerifyUserEmail(userID, email string) *model.AppError {
return nil
}
func (a *App) SearchUsers(props *model.UserSearch, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
func (a *App) SearchUsers(rctx request.CTX, props *model.UserSearch, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
if props.WithoutTeam {
return a.SearchUsersWithoutTeam(props.Term, options)
}
@@ -1964,7 +1964,7 @@ func (a *App) SearchUsers(props *model.UserSearch, options *model.UserSearchOpti
if props.NotInGroupId != "" {
return a.SearchUsersNotInGroup(props.NotInGroupId, props.Term, options)
}
return a.SearchUsersInTeam(props.TeamId, props.Term, options)
return a.SearchUsersInTeam(rctx, props.TeamId, props.Term, options)
}
func (a *App) SearchUsersInChannel(channelID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
@@ -1994,10 +1994,10 @@ func (a *App) SearchUsersNotInChannel(teamID string, channelID string, term stri
return users, nil
}
func (a *App) SearchUsersInTeam(teamID, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
func (a *App) SearchUsersInTeam(rctx request.CTX, teamID, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) {
term = strings.TrimSpace(term)
users, err := a.Srv().Store().User().Search(teamID, term, options)
users, err := a.Srv().Store().User().Search(rctx, teamID, term, options)
if err != nil {
return nil, model.NewAppError("SearchUsersInTeam", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -2065,10 +2065,10 @@ func (a *App) SearchUsersNotInGroup(groupID string, term string, options *model.
return users, nil
}
func (a *App) AutocompleteUsersInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) {
func (a *App) AutocompleteUsersInChannel(rctx request.CTX, teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) {
term = strings.TrimSpace(term)
autocomplete, err := a.Srv().Store().User().AutocompleteUsersInChannel(teamID, channelID, term, options)
autocomplete, err := a.Srv().Store().User().AutocompleteUsersInChannel(rctx, teamID, channelID, term, options)
if err != nil {
return nil, model.NewAppError("AutocompleteUsersInChannel", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -2084,10 +2084,10 @@ func (a *App) AutocompleteUsersInChannel(teamID string, channelID string, term s
return autocomplete, nil
}
func (a *App) AutocompleteUsersInTeam(teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) {
func (a *App) AutocompleteUsersInTeam(rctx request.CTX, teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) {
term = strings.TrimSpace(term)
users, err := a.Srv().Store().User().Search(teamID, term, options)
users, err := a.Srv().Store().User().Search(rctx, teamID, term, options)
if err != nil {
return nil, model.NewAppError("AutocompleteUsersInTeam", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}
@@ -2136,7 +2136,7 @@ func (a *App) UpdateOAuthUserAttrs(c request.CTX, userData io.Reader, user *mode
}
if userAttrsChanged {
users, err := a.Srv().Store().User().Update(user, true)
users, err := a.Srv().Store().User().Update(c, user, true)
if err != nil {
var appErr *model.AppError
var invErr *store.ErrInvalidInput
@@ -2417,12 +2417,12 @@ func (a *App) PublishUserTyping(userID, channelID, parentId string) *model.AppEr
}
// invalidateUserCacheAndPublish Invalidates cache for a user and publishes user updated event
func (a *App) invalidateUserCacheAndPublish(userID string) {
func (a *App) invalidateUserCacheAndPublish(rctx request.CTX, userID string) {
a.InvalidateCacheForUser(userID)
user, userErr := a.GetUser(userID)
if userErr != nil {
mlog.Error("Error in getting users profile", mlog.String("user_id", userID), mlog.Err(userErr))
rctx.Logger().Error("Error in getting users profile", mlog.String("user_id", userID), mlog.Err(userErr))
return
}

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

@@ -131,7 +131,7 @@ func TestRestrictedViewMembers(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
options := model.UserSearchOptions{Limit: 100, ViewRestrictions: tc.Restrictions}
results, err := th.App.SearchUsers(&tc.Search, &options)
results, err := th.App.SearchUsers(th.Context, &tc.Search, &options)
require.Nil(t, err)
ids := []string{}
for _, result := range results {
@@ -207,7 +207,7 @@ func TestRestrictedViewMembers(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
options := model.UserSearchOptions{Limit: 100, ViewRestrictions: tc.Restrictions}
results, err := th.App.SearchUsersInTeam(tc.TeamId, "test", &options)
results, err := th.App.SearchUsersInTeam(th.Context, tc.TeamId, "test", &options)
require.Nil(t, err)
ids := []string{}
for _, result := range results {
@@ -283,7 +283,7 @@ func TestRestrictedViewMembers(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
options := model.UserSearchOptions{Limit: 100, ViewRestrictions: tc.Restrictions}
results, err := th.App.AutocompleteUsersInTeam(tc.TeamId, "tes", &options)
results, err := th.App.AutocompleteUsersInTeam(th.Context, tc.TeamId, "tes", &options)
require.Nil(t, err)
ids := []string{}
for _, result := range results.InTeam {
@@ -367,7 +367,7 @@ func TestRestrictedViewMembers(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
options := model.UserSearchOptions{Limit: 100, ViewRestrictions: tc.Restrictions}
results, err := th.App.AutocompleteUsersInChannel(tc.TeamId, tc.ChannelId, "tes", &options)
results, err := th.App.AutocompleteUsersInChannel(th.Context, tc.TeamId, tc.ChannelId, "tes", &options)
require.Nil(t, err)
ids := []string{}
for _, result := range results.InChannel {

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

@@ -11,6 +11,7 @@ import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/i18n"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/store"
"github.com/mattermost/mattermost/server/v8/platform/shared/mfa"
@@ -197,8 +198,8 @@ func (us *UserService) GetUsersWithoutTeam(options *model.UserGetOptions) ([]*mo
return users, nil
}
func (us *UserService) UpdateUser(user *model.User, allowRoleUpdate bool) (*model.UserUpdate, error) {
return us.store.Update(user, allowRoleUpdate)
func (us *UserService) UpdateUser(rctx request.CTX, user *model.User, allowRoleUpdate bool) (*model.UserUpdate, error) {
return us.store.Update(rctx, user, allowRoleUpdate)
}
func (us *UserService) UpdateUserNotifyProps(userID string, props map[string]string) error {