Этот коммит содержится в:
Chris
2017-09-14 12:01:44 -05:00
коммит произвёл Harrison Healey
родитель af81f7e48b
Коммит b6fb98a431
36 изменённых файлов: 252 добавлений и 241 удалений

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

@@ -19,7 +19,7 @@ import (
type CommandProvider interface { type CommandProvider interface {
GetTrigger() string GetTrigger() string
GetCommand(T goi18n.TranslateFunc) *model.Command GetCommand(T goi18n.TranslateFunc) *model.Command
DoCommand(args *model.CommandArgs, message string) *model.CommandResponse DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse
} }
var commandProviders = make(map[string]CommandProvider) var commandProviders = make(map[string]CommandProvider)
@@ -140,7 +140,7 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *
provider := GetCommandProvider(trigger) provider := GetCommandProvider(trigger)
if provider != nil { if provider != nil {
response := provider.DoCommand(args, message) response := provider.DoCommand(a, args, message)
return a.HandleCommandResponse(provider.GetCommand(args.T), args, response, true) return a.HandleCommandResponse(provider.GetCommand(args.T), args, response, true)
} else { } else {
if !*utils.Cfg.ServiceSettings.EnableCommands { if !*utils.Cfg.ServiceSettings.EnableCommands {

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

@@ -32,8 +32,8 @@ func (me *AwayProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *AwayProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *AwayProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
Global().SetStatusAwayIfNeeded(args.UserId, true) a.SetStatusAwayIfNeeded(args.UserId, true)
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")}
} }

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

@@ -34,17 +34,17 @@ func (me *HeaderProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *HeaderProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *HeaderProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
channel, err := Global().GetChannel(args.ChannelId) channel, err := a.GetChannel(args.ChannelId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_channel_header.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_header.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { if channel.Type == model.CHANNEL_OPEN && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) {
return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { if channel.Type == model.CHANNEL_PRIVATE && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) {
return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
@@ -57,7 +57,7 @@ func (me *HeaderProvider) DoCommand(args *model.CommandArgs, message string) *mo
} }
*patch.Header = message *patch.Header = message
_, err = Global().PatchChannel(channel, patch, args.UserId) _, err = a.PatchChannel(channel, patch, args.UserId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_channel_header.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_header.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -33,17 +33,17 @@ func (me *PurposeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *PurposeProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *PurposeProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
channel, err := Global().GetChannel(args.ChannelId) channel, err := a.GetChannel(args.ChannelId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_channel_purpose.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_purpose.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { if channel.Type == model.CHANNEL_OPEN && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) {
return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { if channel.Type == model.CHANNEL_PRIVATE && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) {
return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
@@ -60,7 +60,7 @@ func (me *PurposeProvider) DoCommand(args *model.CommandArgs, message string) *m
} }
*patch.Purpose = message *patch.Purpose = message
_, err = Global().PatchChannel(channel, patch, args.UserId) _, err = a.PatchChannel(channel, patch, args.UserId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_channel_purpose.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_purpose.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -33,17 +33,17 @@ func (me *RenameProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *RenameProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *RenameProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
channel, err := Global().GetChannel(args.ChannelId) channel, err := a.GetChannel(args.ChannelId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_channel_rename.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_rename.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { if channel.Type == model.CHANNEL_OPEN && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) {
return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { if channel.Type == model.CHANNEL_PRIVATE && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) {
return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
@@ -64,7 +64,7 @@ func (me *RenameProvider) DoCommand(args *model.CommandArgs, message string) *mo
} }
*patch.DisplayName = message *patch.DisplayName = message
_, err = Global().PatchChannel(channel, patch, args.UserId) _, err = a.PatchChannel(channel, patch, args.UserId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_channel_rename.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_channel_rename.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -25,7 +25,7 @@ func TestRenameProviderDoCommand(t *testing.T) {
"1234567890123456789012": "", "1234567890123456789012": "",
"12345678901234567890123": "api.command_channel_rename.too_long.app_error", "12345678901234567890123": "api.command_channel_rename.too_long.app_error",
} { } {
actual := rp.DoCommand(args, msg).Text actual := rp.DoCommand(th.App, args, msg).Text
assert.Equal(t, expected, actual) assert.Equal(t, expected, actual)
} }
} }

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

@@ -35,7 +35,7 @@ func (me *CodeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *CodeProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *CodeProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
if len(message) == 0 { if len(message) == 0 {
return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -18,7 +18,7 @@ func TestCodeProviderDoCommand(t *testing.T) {
"foo\nbar": " foo\n bar", "foo\nbar": " foo\n bar",
"foo\nbar\n": " foo\n bar\n ", "foo\nbar\n": " foo\n bar\n ",
} { } {
actual := cp.DoCommand(args, msg).Text actual := cp.DoCommand(nil, args, msg).Text
if actual != expected { if actual != expected {
t.Errorf("expected `%v`, got `%v`", expected, actual) t.Errorf("expected `%v`, got `%v`", expected, actual)
} }

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

@@ -40,7 +40,7 @@ func (me *EchoProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *EchoProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *EchoProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
if len(message) == 0 { if len(message) == 0 {
return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
@@ -88,7 +88,7 @@ func (me *EchoProvider) DoCommand(args *model.CommandArgs, message string) *mode
time.Sleep(time.Duration(delay) * time.Second) time.Sleep(time.Duration(delay) * time.Second)
if _, err := Global().CreatePostMissingChannel(post, true); err != nil { if _, err := a.CreatePostMissingChannel(post, true); err != nil {
l4g.Error(args.T("api.command_echo.create.app_error"), err) l4g.Error(args.T("api.command_echo.create.app_error"), err)
} }
}() }()

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

@@ -52,12 +52,12 @@ func (me *CollapseProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *ExpandProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *ExpandProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
return Global().setCollapsePreference(args, false) return a.setCollapsePreference(args, false)
} }
func (me *CollapseProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *CollapseProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
return Global().setCollapsePreference(args, true) return a.setCollapsePreference(args, true)
} }
func (a *App) setCollapsePreference(args *model.CommandArgs, isCollapse bool) *model.CommandResponse { func (a *App) setCollapsePreference(args *model.CommandArgs, isCollapse bool) *model.CommandResponse {

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

@@ -33,7 +33,7 @@ func (h *HelpProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (h *HelpProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (h *HelpProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
helpLink := *utils.Cfg.SupportSettings.HelpLink helpLink := *utils.Cfg.SupportSettings.HelpLink
if helpLink == "" { if helpLink == "" {

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

@@ -41,7 +41,7 @@ func (me *InvitePeopleProvider) GetCommand(T goi18n.TranslateFunc) *model.Comman
} }
} }
func (me *InvitePeopleProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *InvitePeopleProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
if !utils.Cfg.EmailSettings.SendEmailNotifications { if !utils.Cfg.EmailSettings.SendEmailNotifications {
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_off")} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_off")}
} }
@@ -63,7 +63,7 @@ func (me *InvitePeopleProvider) DoCommand(args *model.CommandArgs, message strin
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.no_email")} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.no_email")}
} }
if err := Global().InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil { if err := a.InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil {
l4g.Error(err.Error()) l4g.Error(err.Error())
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.fail")} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.fail")}
} }

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

@@ -33,15 +33,15 @@ func (me *JoinProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *JoinProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *JoinProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
if result := <-Global().Srv.Store.Channel().GetByName(args.TeamId, message, true); result.Err != nil { if result := <-a.Srv.Store.Channel().GetByName(args.TeamId, message, true); result.Err != nil {
return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} else { } else {
channel := result.Data.(*model.Channel) channel := result.Data.(*model.Channel)
if channel.Name == message { if channel.Name == message {
allowed := false allowed := false
if (channel.Type == model.CHANNEL_PRIVATE && Global().SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_READ_CHANNEL)) || channel.Type == model.CHANNEL_OPEN { if (channel.Type == model.CHANNEL_PRIVATE && a.SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_READ_CHANNEL)) || channel.Type == model.CHANNEL_OPEN {
allowed = true allowed = true
} }
@@ -49,11 +49,11 @@ func (me *JoinProvider) DoCommand(args *model.CommandArgs, message string) *mode
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if err := Global().JoinChannel(channel, args.UserId); err != nil { if err := a.JoinChannel(channel, args.UserId); err != nil {
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
team, err := Global().GetTeam(channel.TeamId) team, err := a.GetTeam(channel.TeamId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -32,21 +32,21 @@ func (me *LeaveProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *LeaveProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LeaveProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
var channel *model.Channel var channel *model.Channel
var noChannelErr *model.AppError var noChannelErr *model.AppError
if channel, noChannelErr = Global().GetChannel(args.ChannelId); noChannelErr != nil { if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil {
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
if channel.Name == model.DEFAULT_CHANNEL { if channel.Name == model.DEFAULT_CHANNEL {
return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
err := Global().LeaveChannel(args.ChannelId, args.UserId) err := a.LeaveChannel(args.ChannelId, args.UserId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
team, err := Global().GetTeam(args.TeamId) team, err := a.GetTeam(args.TeamId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -85,33 +85,33 @@ func (me *LoadTestProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *LoadTestProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LoadTestProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
//This command is only available when EnableTesting is true //This command is only available when EnableTesting is true
if !utils.Cfg.ServiceSettings.EnableTesting { if !utils.Cfg.ServiceSettings.EnableTesting {
return &model.CommandResponse{} return &model.CommandResponse{}
} }
if strings.HasPrefix(message, "setup") { if strings.HasPrefix(message, "setup") {
return me.SetupCommand(args, message) return me.SetupCommand(a, args, message)
} }
if strings.HasPrefix(message, "users") { if strings.HasPrefix(message, "users") {
return me.UsersCommand(args, message) return me.UsersCommand(a, args, message)
} }
if strings.HasPrefix(message, "channels") { if strings.HasPrefix(message, "channels") {
return me.ChannelsCommand(args, message) return me.ChannelsCommand(a, args, message)
} }
if strings.HasPrefix(message, "posts") { if strings.HasPrefix(message, "posts") {
return me.PostsCommand(args, message) return me.PostsCommand(a, args, message)
} }
if strings.HasPrefix(message, "url") { if strings.HasPrefix(message, "url") {
return me.UrlCommand(args, message) return me.UrlCommand(a, args, message)
} }
if strings.HasPrefix(message, "json") { if strings.HasPrefix(message, "json") {
return me.JsonCommand(args, message) return me.JsonCommand(a, args, message)
} }
return me.HelpCommand(args, message) return me.HelpCommand(args, message)
} }
@@ -120,7 +120,7 @@ func (me *LoadTestProvider) HelpCommand(args *model.CommandArgs, message string)
return &model.CommandResponse{Text: usage, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: usage, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LoadTestProvider) SetupCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
tokens := strings.Fields(strings.TrimPrefix(message, "setup")) tokens := strings.Fields(strings.TrimPrefix(message, "setup"))
doTeams := contains(tokens, "teams") doTeams := contains(tokens, "teams")
doFuzz := contains(tokens, "fuzz") doFuzz := contains(tokens, "fuzz")
@@ -161,7 +161,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string
client := model.NewClient(args.SiteURL) client := model.NewClient(args.SiteURL)
if doTeams { if doTeams {
if err := Global().CreateBasicUser(client); err != nil { if err := a.CreateBasicUser(client); err != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
client.Login(BTEST_USER_EMAIL, BTEST_USER_PASSWORD) client.Login(BTEST_USER_EMAIL, BTEST_USER_PASSWORD)
@@ -184,7 +184,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string
} else { } else {
var team *model.Team var team *model.Team
if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { if tr := <-a.Srv.Store.Team().Get(args.TeamId); tr.Err != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} else { } else {
team = tr.Data.(*model.Team) team = tr.Data.(*model.Team)
@@ -204,7 +204,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string
return &model.CommandResponse{Text: "Created enviroment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Created enviroment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
func (me *LoadTestProvider) UsersCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LoadTestProvider) UsersCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
cmd := strings.TrimSpace(strings.TrimPrefix(message, "users")) cmd := strings.TrimSpace(strings.TrimPrefix(message, "users"))
doFuzz := false doFuzz := false
@@ -219,7 +219,7 @@ func (me *LoadTestProvider) UsersCommand(args *model.CommandArgs, message string
} }
var team *model.Team var team *model.Team
if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { if tr := <-a.Srv.Store.Team().Get(args.TeamId); tr.Err != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} else { } else {
team = tr.Data.(*model.Team) team = tr.Data.(*model.Team)
@@ -234,7 +234,7 @@ func (me *LoadTestProvider) UsersCommand(args *model.CommandArgs, message string
return &model.CommandResponse{Text: "Added users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Added users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
func (me *LoadTestProvider) ChannelsCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LoadTestProvider) ChannelsCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels")) cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels"))
doFuzz := false doFuzz := false
@@ -249,7 +249,7 @@ func (me *LoadTestProvider) ChannelsCommand(args *model.CommandArgs, message str
} }
var team *model.Team var team *model.Team
if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { if tr := <-a.Srv.Store.Team().Get(args.TeamId); tr.Err != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} else { } else {
team = tr.Data.(*model.Team) team = tr.Data.(*model.Team)
@@ -265,7 +265,7 @@ func (me *LoadTestProvider) ChannelsCommand(args *model.CommandArgs, message str
return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
func (me *LoadTestProvider) PostsCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LoadTestProvider) PostsCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
cmd := strings.TrimSpace(strings.TrimPrefix(message, "posts")) cmd := strings.TrimSpace(strings.TrimPrefix(message, "posts"))
doFuzz := false doFuzz := false
@@ -288,7 +288,7 @@ func (me *LoadTestProvider) PostsCommand(args *model.CommandArgs, message string
} }
var usernames []string var usernames []string
if result := <-Global().Srv.Store.User().GetProfiles(args.TeamId, 0, 1000); result.Err == nil { if result := <-a.Srv.Store.User().GetProfiles(args.TeamId, 0, 1000); result.Err == nil {
profileUsers := result.Data.([]*model.User) profileUsers := result.Data.([]*model.User)
usernames = make([]string, len(profileUsers)) usernames = make([]string, len(profileUsers))
i := 0 i := 0
@@ -315,7 +315,7 @@ func (me *LoadTestProvider) PostsCommand(args *model.CommandArgs, message string
return &model.CommandResponse{Text: "Added posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Added posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
func (me *LoadTestProvider) UrlCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LoadTestProvider) UrlCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
url := strings.TrimSpace(strings.TrimPrefix(message, "url")) url := strings.TrimSpace(strings.TrimPrefix(message, "url"))
if len(url) == 0 { if len(url) == 0 {
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
@@ -357,7 +357,7 @@ func (me *LoadTestProvider) UrlCommand(args *model.CommandArgs, message string)
post.ChannelId = args.ChannelId post.ChannelId = args.ChannelId
post.UserId = args.UserId post.UserId = args.UserId
if _, err := Global().CreatePostMissingChannel(post, false); err != nil { if _, err := a.CreatePostMissingChannel(post, false); err != nil {
return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
} }
@@ -365,7 +365,7 @@ func (me *LoadTestProvider) UrlCommand(args *model.CommandArgs, message string)
return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
func (me *LoadTestProvider) JsonCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LoadTestProvider) JsonCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
url := strings.TrimSpace(strings.TrimPrefix(message, "json")) url := strings.TrimSpace(strings.TrimPrefix(message, "json"))
if len(url) == 0 { if len(url) == 0 {
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
@@ -396,7 +396,7 @@ func (me *LoadTestProvider) JsonCommand(args *model.CommandArgs, message string)
post.Message = message post.Message = message
} }
if _, err := Global().CreatePostMissingChannel(post, false); err != nil { if _, err := a.CreatePostMissingChannel(post, false); err != nil {
return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}

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

@@ -33,13 +33,13 @@ func (me *LogoutProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *LogoutProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *LogoutProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
FAIL := &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_logout.fail_message")} FAIL := &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_logout.fail_message")}
SUCCESS := &model.CommandResponse{GotoLocation: "/login"} SUCCESS := &model.CommandResponse{GotoLocation: "/login"}
// We can't actually remove the user's cookie from here so we just dump their session and let the browser figure it out // We can't actually remove the user's cookie from here so we just dump their session and let the browser figure it out
if args.Session.Id != "" { if args.Session.Id != "" {
if err := Global().RevokeSessionById(args.Session.Id); err != nil { if err := a.RevokeSessionById(args.Session.Id); err != nil {
return FAIL return FAIL
} }
return SUCCESS return SUCCESS

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

@@ -33,6 +33,6 @@ func (me *MeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *MeProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *MeProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Text: "*" + message + "*"} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Text: "*" + message + "*"}
} }

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

@@ -36,7 +36,7 @@ func (me *msgProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *msgProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
splitMessage := strings.SplitN(message, " ", 2) splitMessage := strings.SplitN(message, " ", 2)
@@ -51,7 +51,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model
targetUsername = strings.TrimPrefix(targetUsername, "@") targetUsername = strings.TrimPrefix(targetUsername, "@")
var userProfile *model.User var userProfile *model.User
if result := <-Global().Srv.Store.User().GetByUsername(targetUsername); result.Err != nil { if result := <-a.Srv.Store.User().GetByUsername(targetUsername); result.Err != nil {
l4g.Error(result.Err.Error()) l4g.Error(result.Err.Error())
return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} else { } else {
@@ -66,9 +66,9 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model
channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id) channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id)
targetChannelId := "" targetChannelId := ""
if channel := <-Global().Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channel.Err != nil { if channel := <-a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channel.Err != nil {
if channel.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { if channel.Err.Id == "store.sql_channel.get_by_name.missing.app_error" {
if directChannel, err := Global().CreateDirectChannel(args.UserId, userProfile.Id); err != nil { if directChannel, err := a.CreateDirectChannel(args.UserId, userProfile.Id); err != nil {
l4g.Error(err.Error()) l4g.Error(err.Error())
return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} else { } else {
@@ -89,7 +89,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model
post.Message = parsedMessage post.Message = parsedMessage
post.ChannelId = targetChannelId post.ChannelId = targetChannelId
post.UserId = args.UserId post.UserId = args.UserId
if _, err := Global().CreatePostMissingChannel(post, true); err != nil { if _, err := a.CreatePostMissingChannel(post, true); err != nil {
return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }
} }
@@ -101,7 +101,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model
teamId = args.Session.TeamMembers[0].TeamId teamId = args.Session.TeamMembers[0].TeamId
} }
team, err := Global().GetTeam(teamId) team, err := a.GetTeam(teamId)
if err != nil { if err != nil {
return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -32,8 +32,8 @@ func (me *OfflineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *OfflineProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *OfflineProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
Global().SetStatusOffline(args.UserId, true) a.SetStatusOffline(args.UserId, true)
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_offline.success")} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_offline.success")}
} }

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

@@ -32,8 +32,8 @@ func (me *OnlineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *OnlineProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *OnlineProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
Global().SetStatusOnline(args.UserId, args.Session.Id, true) a.SetStatusOnline(args.UserId, args.Session.Id, true)
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_online.success")} return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_online.success")}
} }

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

@@ -33,7 +33,7 @@ func (search *SearchProvider) GetCommand(T goi18n.TranslateFunc) *model.Command
} }
} }
func (search *SearchProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (search *SearchProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
// This command is handled client-side and shouldn't hit the server. // This command is handled client-side and shouldn't hit the server.
return &model.CommandResponse{ return &model.CommandResponse{
Text: args.T("api.command_search.unsupported.app_error"), Text: args.T("api.command_search.unsupported.app_error"),

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

@@ -33,7 +33,7 @@ func (settings *SettingsProvider) GetCommand(T goi18n.TranslateFunc) *model.Comm
} }
} }
func (settings *SettingsProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (settings *SettingsProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
// This command is handled client-side and shouldn't hit the server. // This command is handled client-side and shouldn't hit the server.
return &model.CommandResponse{ return &model.CommandResponse{
Text: args.T("api.command_settings.unsupported.app_error"), Text: args.T("api.command_settings.unsupported.app_error"),

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

@@ -33,7 +33,7 @@ func (me *ShortcutsProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *ShortcutsProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *ShortcutsProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
// This command is handled client-side and shouldn't hit the server. // This command is handled client-side and shouldn't hit the server.
return &model.CommandResponse{ return &model.CommandResponse{
Text: args.T("api.command_shortcuts.unsupported.app_error"), Text: args.T("api.command_shortcuts.unsupported.app_error"),

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

@@ -33,7 +33,7 @@ func (me *ShrugProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *ShrugProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { func (me *ShrugProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
rmsg := `¯\\\_(ツ)\_/¯` rmsg := `¯\\\_(ツ)\_/¯`
if len(message) > 0 { if len(message) > 0 {
rmsg = message + " " + rmsg rmsg = message + " " + rmsg

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

@@ -128,8 +128,8 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
var user, user2 *model.User var user, user2 *model.User
var gitlabUserObj oauthgitlab.GitLabUser var gitlabUserObj oauthgitlab.GitLabUser
user, gitlabUserObj = createGitlabUser(t, username, email) user, gitlabUserObj = createGitlabUser(t, th.App, username, email)
user2, _ = createGitlabUser(t, username2, email2) user2, _ = createGitlabUser(t, th.App, username2, email2)
t.Run("UpdateUsername", func(t *testing.T) { t.Run("UpdateUsername", func(t *testing.T) {
t.Run("NoExistingUserWithSameUsername", func(t *testing.T) { t.Run("NoExistingUserWithSameUsername", func(t *testing.T) {
@@ -137,9 +137,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
gitlabUser := getGitlabUserPayload(gitlabUserObj, t) gitlabUser := getGitlabUserPayload(gitlabUserObj, t)
data := bytes.NewReader(gitlabUser) data := bytes.NewReader(gitlabUser)
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab")
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
if user.Username != gitlabUserObj.Username { if user.Username != gitlabUserObj.Username {
t.Fatal("user's username is not updated") t.Fatal("user's username is not updated")
@@ -152,9 +152,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
gitlabUser := getGitlabUserPayload(gitlabUserObj, t) gitlabUser := getGitlabUserPayload(gitlabUserObj, t)
data := bytes.NewReader(gitlabUser) data := bytes.NewReader(gitlabUser)
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab")
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
if user.Username == gitlabUserObj.Username { if user.Username == gitlabUserObj.Username {
t.Fatal("user's username is updated though there already exists another user with the same username") t.Fatal("user's username is updated though there already exists another user with the same username")
@@ -168,9 +168,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
gitlabUser := getGitlabUserPayload(gitlabUserObj, t) gitlabUser := getGitlabUserPayload(gitlabUserObj, t)
data := bytes.NewReader(gitlabUser) data := bytes.NewReader(gitlabUser)
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab")
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
if user.Email != gitlabUserObj.Email { if user.Email != gitlabUserObj.Email {
t.Fatal("user's email is not updated") t.Fatal("user's email is not updated")
@@ -187,9 +187,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
gitlabUser := getGitlabUserPayload(gitlabUserObj, t) gitlabUser := getGitlabUserPayload(gitlabUserObj, t)
data := bytes.NewReader(gitlabUser) data := bytes.NewReader(gitlabUser)
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab")
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
if user.Email == gitlabUserObj.Email { if user.Email == gitlabUserObj.Email {
t.Fatal("user's email is updated though there already exists another user with the same email") t.Fatal("user's email is updated though there already exists another user with the same email")
@@ -202,9 +202,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
gitlabUser := getGitlabUserPayload(gitlabUserObj, t) gitlabUser := getGitlabUserPayload(gitlabUserObj, t)
data := bytes.NewReader(gitlabUser) data := bytes.NewReader(gitlabUser)
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab")
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
if user.FirstName != "Updated" { if user.FirstName != "Updated" {
t.Fatal("user's first name is not updated") t.Fatal("user's first name is not updated")
@@ -216,9 +216,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
gitlabUser := getGitlabUserPayload(gitlabUserObj, t) gitlabUser := getGitlabUserPayload(gitlabUserObj, t)
data := bytes.NewReader(gitlabUser) data := bytes.NewReader(gitlabUser)
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab")
user = getUserFromDB(user.Id, t) user = getUserFromDB(th.App, user.Id, t)
if user.LastName != "Lastname" { if user.LastName != "Lastname" {
t.Fatal("user's last name is not updated") t.Fatal("user's last name is not updated")
@@ -226,8 +226,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) {
}) })
} }
func getUserFromDB(id string, t *testing.T) *model.User { func getUserFromDB(a *App, id string, t *testing.T) *model.User {
a := Global()
if user, err := a.GetUser(id); err != nil { if user, err := a.GetUser(id); err != nil {
t.Fatal("user is not found") t.Fatal("user is not found")
return nil return nil
@@ -246,8 +245,7 @@ func getGitlabUserPayload(gitlabUser oauthgitlab.GitLabUser, t *testing.T) []byt
return payload return payload
} }
func createGitlabUser(t *testing.T, email string, username string) (*model.User, oauthgitlab.GitLabUser) { func createGitlabUser(t *testing.T, a *App, email string, username string) (*model.User, oauthgitlab.GitLabUser) {
a := Global()
r := rand.New(rand.NewSource(time.Now().UnixNano())) r := rand.New(rand.NewSource(time.Now().UnixNano()))
gitlabUserObj := oauthgitlab.GitLabUser{Id: int64(r.Intn(1000)) + 1, Username: username, Login: "user1", Email: email, Name: "Test User"} gitlabUserObj := oauthgitlab.GitLabUser{Id: int64(r.Intn(1000)) + 1, Username: username, Login: "user1", Email: email, Name: "Test User"}
gitlabUser := getGitlabUserPayload(gitlabUserObj, t) gitlabUser := getGitlabUserPayload(gitlabUserObj, t)

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

@@ -30,6 +30,7 @@ const (
type WebConn struct { type WebConn struct {
sessionExpiresAt int64 // This should stay at the top for 64-bit alignment of 64-bit words accessed atomically sessionExpiresAt int64 // This should stay at the top for 64-bit alignment of 64-bit words accessed atomically
App *App
WebSocket *websocket.Conn WebSocket *websocket.Conn
Send chan model.WebSocketMessage Send chan model.WebSocketMessage
sessionToken atomic.Value sessionToken atomic.Value
@@ -51,6 +52,7 @@ func (a *App) NewWebConn(ws *websocket.Conn, session model.Session, t goi18n.Tra
} }
wc := &WebConn{ wc := &WebConn{
App: a,
Send: make(chan model.WebSocketMessage, SEND_QUEUE_SIZE), Send: make(chan model.WebSocketMessage, SEND_QUEUE_SIZE),
WebSocket: ws, WebSocket: ws,
UserId: session.UserId, UserId: session.UserId,
@@ -103,7 +105,7 @@ func (c *WebConn) ReadPump() {
c.WebSocket.SetPongHandler(func(string) error { c.WebSocket.SetPongHandler(func(string) error {
c.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) c.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT))
if c.IsAuthenticated() { if c.IsAuthenticated() {
go Global().SetStatusAwayIfNeeded(c.UserId, false) go c.App.SetStatusAwayIfNeeded(c.UserId, false)
} }
return nil return nil
}) })
@@ -120,7 +122,7 @@ func (c *WebConn) ReadPump() {
return return
} else { } else {
Global().Srv.WebSocketRouter.ServeWebSocket(c, &req) c.App.Srv.WebSocketRouter.ServeWebSocket(c, &req)
} }
} }
} }
@@ -231,7 +233,7 @@ func (webCon *WebConn) IsAuthenticated() bool {
return false return false
} }
session, err := Global().GetSession(webCon.GetSessionToken()) session, err := webCon.App.GetSession(webCon.GetSessionToken())
if err != nil { if err != nil {
l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error()) l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error())
webCon.SetSessionToken("") webCon.SetSessionToken("")
@@ -283,7 +285,7 @@ func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool {
} }
if webCon.AllChannelMembers == nil { if webCon.AllChannelMembers == nil {
if result := <-Global().Srv.Store.Channel().GetAllChannelMembersForUser(webCon.UserId, true); result.Err != nil { if result := <-webCon.App.Srv.Store.Channel().GetAllChannelMembersForUser(webCon.UserId, true); result.Err != nil {
l4g.Error("webhub.shouldSendEvent: " + result.Err.Error()) l4g.Error("webhub.shouldSendEvent: " + result.Err.Error())
return false return false
} else { } else {
@@ -313,7 +315,7 @@ func (webCon *WebConn) IsMemberOfTeam(teamId string) bool {
currentSession := webCon.GetSession() currentSession := webCon.GetSession()
if currentSession == nil || len(currentSession.Token) == 0 { if currentSession == nil || len(currentSession.Token) == 0 {
session, err := Global().GetSession(webCon.GetSessionToken()) session, err := webCon.App.GetSession(webCon.GetSessionToken())
if err != nil { if err != nil {
l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error()) l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error())
return false return false

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

@@ -7,6 +7,7 @@ import (
"context" "context"
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
) )
@@ -26,8 +27,8 @@ type LayeredStore struct {
func NewLayeredStore() Store { func NewLayeredStore() Store {
store := &LayeredStore{ store := &LayeredStore{
TmpContext: context.TODO(), TmpContext: context.TODO(),
DatabaseLayer: NewSqlSupplier(), DatabaseLayer: NewSqlSupplier(einterfaces.GetMetricsInterface()),
LocalCacheLayer: NewLocalCacheSupplier(), LocalCacheLayer: NewLocalCacheSupplier(einterfaces.GetMetricsInterface(), einterfaces.GetClusterInterface()),
} }
store.ReactionStore = &LayeredReactionStore{store} store.ReactionStore = &LayeredReactionStore{store}

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

@@ -21,11 +21,15 @@ const (
type LocalCacheSupplier struct { type LocalCacheSupplier struct {
next LayeredStoreSupplier next LayeredStoreSupplier
reactionCache *utils.Cache reactionCache *utils.Cache
metrics einterfaces.MetricsInterface
cluster einterfaces.ClusterInterface
} }
func NewLocalCacheSupplier() *LocalCacheSupplier { func NewLocalCacheSupplier(metrics einterfaces.MetricsInterface, cluster einterfaces.ClusterInterface) *LocalCacheSupplier {
supplier := &LocalCacheSupplier{ supplier := &LocalCacheSupplier{
reactionCache: utils.NewLruWithParams(REACTION_CACHE_SIZE, "Reaction", REACTION_CACHE_SEC, model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_REACTIONS), reactionCache: utils.NewLruWithParams(REACTION_CACHE_SIZE, "Reaction", REACTION_CACHE_SEC, model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_REACTIONS),
metrics: metrics,
cluster: cluster,
} }
registerClusterHandlers(supplier) registerClusterHandlers(supplier)
@@ -47,58 +51,56 @@ func (s *LocalCacheSupplier) Next() LayeredStoreSupplier {
return s.next return s.next
} }
func doStandardReadCache(ctx context.Context, cache utils.ObjectCache, key string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *LocalCacheSupplier) doStandardReadCache(ctx context.Context, cache utils.ObjectCache, key string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult {
metrics := einterfaces.GetMetricsInterface()
if hintsContains(hints, LSH_NO_CACHE) { if hintsContains(hints, LSH_NO_CACHE) {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter(cache.Name()) s.metrics.IncrementMemCacheMissCounter(cache.Name())
} }
return nil return nil
} }
if cacheItem, ok := cache.Get(key); ok { if cacheItem, ok := cache.Get(key); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter(cache.Name()) s.metrics.IncrementMemCacheHitCounter(cache.Name())
} }
result := NewSupplierResult() result := NewSupplierResult()
result.Data = cacheItem result.Data = cacheItem
return result return result
} }
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter(cache.Name()) s.metrics.IncrementMemCacheMissCounter(cache.Name())
} }
return nil return nil
} }
func doStandardAddToCache(ctx context.Context, cache utils.ObjectCache, key string, result *LayeredStoreSupplierResult, hints ...LayeredStoreHint) { func (s *LocalCacheSupplier) doStandardAddToCache(ctx context.Context, cache utils.ObjectCache, key string, result *LayeredStoreSupplierResult, hints ...LayeredStoreHint) {
if result.Err == nil && result.Data != nil { if result.Err == nil && result.Data != nil {
cache.AddWithDefaultExpires(key, result.Data) cache.AddWithDefaultExpires(key, result.Data)
} }
} }
func doInvalidateCacheCluster(cache utils.ObjectCache, key string) { func (s *LocalCacheSupplier) doInvalidateCacheCluster(cache utils.ObjectCache, key string) {
cache.Remove(key) cache.Remove(key)
if einterfaces.GetClusterInterface() != nil { if s.cluster != nil {
msg := &model.ClusterMessage{ msg := &model.ClusterMessage{
Event: cache.GetInvalidateClusterEvent(), Event: cache.GetInvalidateClusterEvent(),
SendType: model.CLUSTER_SEND_BEST_EFFORT, SendType: model.CLUSTER_SEND_BEST_EFFORT,
Data: key, Data: key,
} }
einterfaces.GetClusterInterface().SendClusterMessage(msg) s.cluster.SendClusterMessage(msg)
} }
} }
func doClearCacheCluster(cache utils.ObjectCache) { func (s *LocalCacheSupplier) doClearCacheCluster(cache utils.ObjectCache) {
cache.Purge() cache.Purge()
if einterfaces.GetClusterInterface() != nil { if s.cluster != nil {
msg := &model.ClusterMessage{ msg := &model.ClusterMessage{
Event: cache.GetInvalidateClusterEvent(), Event: cache.GetInvalidateClusterEvent(),
SendType: model.CLUSTER_SEND_BEST_EFFORT, SendType: model.CLUSTER_SEND_BEST_EFFORT,
Data: CLEAR_CACHE_MESSAGE_DATA, Data: CLEAR_CACHE_MESSAGE_DATA,
} }
einterfaces.GetClusterInterface().SendClusterMessage(msg) s.cluster.SendClusterMessage(msg)
} }
} }

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

@@ -18,23 +18,23 @@ func (s *LocalCacheSupplier) handleClusterInvalidateReaction(msg *model.ClusterM
} }
func (s *LocalCacheSupplier) ReactionSave(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *LocalCacheSupplier) ReactionSave(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult {
doInvalidateCacheCluster(s.reactionCache, reaction.PostId) s.doInvalidateCacheCluster(s.reactionCache, reaction.PostId)
return s.Next().ReactionSave(ctx, reaction, hints...) return s.Next().ReactionSave(ctx, reaction, hints...)
} }
func (s *LocalCacheSupplier) ReactionDelete(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *LocalCacheSupplier) ReactionDelete(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult {
doInvalidateCacheCluster(s.reactionCache, reaction.PostId) s.doInvalidateCacheCluster(s.reactionCache, reaction.PostId)
return s.Next().ReactionDelete(ctx, reaction, hints...) return s.Next().ReactionDelete(ctx, reaction, hints...)
} }
func (s *LocalCacheSupplier) ReactionGetForPost(ctx context.Context, postId string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *LocalCacheSupplier) ReactionGetForPost(ctx context.Context, postId string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult {
if result := doStandardReadCache(ctx, s.reactionCache, postId, hints...); result != nil { if result := s.doStandardReadCache(ctx, s.reactionCache, postId, hints...); result != nil {
return result return result
} }
result := s.Next().ReactionGetForPost(ctx, postId, hints...) result := s.Next().ReactionGetForPost(ctx, postId, hints...)
doStandardAddToCache(ctx, s.reactionCache, postId, result, hints...) s.doStandardAddToCache(ctx, s.reactionCache, postId, result, hints...)
return result return result
} }
@@ -42,6 +42,6 @@ func (s *LocalCacheSupplier) ReactionGetForPost(ctx context.Context, postId stri
func (s *LocalCacheSupplier) ReactionDeleteAllWithEmojiName(ctx context.Context, emojiName string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { func (s *LocalCacheSupplier) ReactionDeleteAllWithEmojiName(ctx context.Context, emojiName string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult {
// This could be improved. Right now we just clear the whole // This could be improved. Right now we just clear the whole
// cache because we don't have a way find what post Ids have this emoji name. // cache because we don't have a way find what post Ids have this emoji name.
doClearCacheCluster(s.reactionCache) s.doClearCacheCluster(s.reactionCache)
return s.Next().ReactionDeleteAllWithEmojiName(ctx, emojiName, hints...) return s.Next().ReactionDeleteAllWithEmojiName(ctx, emojiName, hints...)
} }

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

@@ -36,6 +36,7 @@ const (
type SqlChannelStore struct { type SqlChannelStore struct {
SqlStore SqlStore
metrics einterfaces.MetricsInterface
} }
var channelMemberCountsCache = utils.NewLru(CHANNEL_MEMBERS_COUNTS_CACHE_SIZE) var channelMemberCountsCache = utils.NewLru(CHANNEL_MEMBERS_COUNTS_CACHE_SIZE)
@@ -52,8 +53,11 @@ func ClearChannelCaches() {
channelByNameCache.Purge() channelByNameCache.Purge()
} }
func NewSqlChannelStore(sqlStore SqlStore) ChannelStore { func NewSqlChannelStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) ChannelStore {
s := &SqlChannelStore{sqlStore} s := &SqlChannelStore{
SqlStore: sqlStore,
metrics: metrics,
}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.Channel{}, "Channels").SetKeys(false, "Id") table := db.AddTableWithName(model.Channel{}, "Channels").SetKeys(false, "Id")
@@ -391,7 +395,6 @@ func (s SqlChannelStore) get(id string, master bool, allowFromCache bool) StoreC
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
var db *gorp.DbMap var db *gorp.DbMap
if master { if master {
@@ -402,21 +405,21 @@ func (s SqlChannelStore) get(id string, master bool, allowFromCache bool) StoreC
if allowFromCache { if allowFromCache {
if cacheItem, ok := channelCache.Get(id); ok { if cacheItem, ok := channelCache.Get(id); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Channel") s.metrics.IncrementMemCacheHitCounter("Channel")
} }
result.Data = (cacheItem.(*model.Channel)).DeepCopy() result.Data = (cacheItem.(*model.Channel)).DeepCopy()
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Channel") s.metrics.IncrementMemCacheMissCounter("Channel")
} }
} }
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Channel") s.metrics.IncrementMemCacheMissCounter("Channel")
} }
} }
@@ -758,18 +761,17 @@ func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bo
channel := model.Channel{} channel := model.Channel{}
if allowFromCache { if allowFromCache {
metrics := einterfaces.GetMetricsInterface()
if cacheItem, ok := channelByNameCache.Get(teamId + name); ok { if cacheItem, ok := channelByNameCache.Get(teamId + name); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Channel By Name") s.metrics.IncrementMemCacheHitCounter("Channel By Name")
} }
result.Data = cacheItem.(*model.Channel) result.Data = cacheItem.(*model.Channel)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Channel By Name") s.metrics.IncrementMemCacheMissCounter("Channel By Name")
} }
} }
} }
@@ -978,10 +980,9 @@ func (us SqlChannelStore) InvalidateAllChannelMembersForUser(userId string) {
} }
func (us SqlChannelStore) IsUserInChannelUseCache(userId string, channelId string) bool { func (us SqlChannelStore) IsUserInChannelUseCache(userId string, channelId string) bool {
metrics := einterfaces.GetMetricsInterface()
if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok { if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok {
if metrics != nil { if us.metrics != nil {
metrics.IncrementMemCacheHitCounter("All Channel Members for User") us.metrics.IncrementMemCacheHitCounter("All Channel Members for User")
} }
ids := cacheItem.(map[string]string) ids := cacheItem.(map[string]string)
if _, ok := ids[channelId]; ok { if _, ok := ids[channelId]; ok {
@@ -990,8 +991,8 @@ func (us SqlChannelStore) IsUserInChannelUseCache(userId string, channelId strin
return false return false
} }
} else { } else {
if metrics != nil { if us.metrics != nil {
metrics.IncrementMemCacheMissCounter("All Channel Members for User") us.metrics.IncrementMemCacheMissCounter("All Channel Members for User")
} }
} }
@@ -1048,25 +1049,24 @@ func (s SqlChannelStore) GetAllChannelMembersForUser(userId string, allowFromCac
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if allowFromCache { if allowFromCache {
if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok { if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("All Channel Members for User") s.metrics.IncrementMemCacheHitCounter("All Channel Members for User")
} }
result.Data = cacheItem.(map[string]string) result.Data = cacheItem.(map[string]string)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("All Channel Members for User") s.metrics.IncrementMemCacheMissCounter("All Channel Members for User")
} }
} }
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("All Channel Members for User") s.metrics.IncrementMemCacheMissCounter("All Channel Members for User")
} }
} }
@@ -1110,25 +1110,24 @@ func (s SqlChannelStore) GetAllChannelMembersNotifyPropsForChannel(channelId str
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if allowFromCache { if allowFromCache {
if cacheItem, ok := allChannelMembersNotifyPropsForChannelCache.Get(channelId); ok { if cacheItem, ok := allChannelMembersNotifyPropsForChannelCache.Get(channelId); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("All Channel Members Notify Props for Channel") s.metrics.IncrementMemCacheHitCounter("All Channel Members Notify Props for Channel")
} }
result.Data = cacheItem.(map[string]model.StringMap) result.Data = cacheItem.(map[string]model.StringMap)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel") s.metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel")
} }
} }
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel") s.metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel")
} }
} }
@@ -1164,16 +1163,14 @@ func (us SqlChannelStore) InvalidateMemberCount(channelId string) {
} }
func (s SqlChannelStore) GetMemberCountFromCache(channelId string) int64 { func (s SqlChannelStore) GetMemberCountFromCache(channelId string) int64 {
metrics := einterfaces.GetMetricsInterface()
if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok { if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Channel Member Counts") s.metrics.IncrementMemCacheHitCounter("Channel Member Counts")
} }
return cacheItem.(int64) return cacheItem.(int64)
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Channel Member Counts") s.metrics.IncrementMemCacheMissCounter("Channel Member Counts")
} }
} }
@@ -1186,28 +1183,27 @@ func (s SqlChannelStore) GetMemberCountFromCache(channelId string) int64 {
func (s SqlChannelStore) GetMemberCount(channelId string, allowFromCache bool) StoreChannel { func (s SqlChannelStore) GetMemberCount(channelId string, allowFromCache bool) StoreChannel {
storeChannel := make(StoreChannel, 1) storeChannel := make(StoreChannel, 1)
metrics := einterfaces.GetMetricsInterface()
go func() { go func() {
result := StoreResult{} result := StoreResult{}
if allowFromCache { if allowFromCache {
if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok { if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Channel Member Counts") s.metrics.IncrementMemCacheHitCounter("Channel Member Counts")
} }
result.Data = cacheItem.(int64) result.Data = cacheItem.(int64)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Channel Member Counts") s.metrics.IncrementMemCacheMissCounter("Channel Member Counts")
} }
} }
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Channel Member Counts") s.metrics.IncrementMemCacheMissCounter("Channel Member Counts")
} }
} }

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

@@ -20,10 +20,14 @@ var emojiCache *utils.Cache = utils.NewLru(EMOJI_CACHE_SIZE)
type SqlEmojiStore struct { type SqlEmojiStore struct {
SqlStore SqlStore
metrics einterfaces.MetricsInterface
} }
func NewSqlEmojiStore(sqlStore SqlStore) EmojiStore { func NewSqlEmojiStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) EmojiStore {
s := &SqlEmojiStore{sqlStore} s := &SqlEmojiStore{
SqlStore: sqlStore,
metrics: metrics,
}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.Emoji{}, "Emoji").SetKeys(false, "Id") table := db.AddTableWithName(model.Emoji{}, "Emoji").SetKeys(false, "Id")
@@ -74,25 +78,24 @@ func (es SqlEmojiStore) Get(id string, allowFromCache bool) StoreChannel {
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if allowFromCache { if allowFromCache {
if cacheItem, ok := emojiCache.Get(id); ok { if cacheItem, ok := emojiCache.Get(id); ok {
if metrics != nil { if es.metrics != nil {
metrics.IncrementMemCacheHitCounter("Emoji") es.metrics.IncrementMemCacheHitCounter("Emoji")
} }
result.Data = cacheItem.(*model.Emoji) result.Data = cacheItem.(*model.Emoji)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if es.metrics != nil {
metrics.IncrementMemCacheMissCounter("Emoji") es.metrics.IncrementMemCacheMissCounter("Emoji")
} }
} }
} else { } else {
if metrics != nil { if es.metrics != nil {
metrics.IncrementMemCacheMissCounter("Emoji") es.metrics.IncrementMemCacheMissCounter("Emoji")
} }
} }

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

@@ -13,6 +13,7 @@ import (
type SqlFileInfoStore struct { type SqlFileInfoStore struct {
SqlStore SqlStore
metrics einterfaces.MetricsInterface
} }
const ( const (
@@ -26,8 +27,11 @@ func ClearFileCaches() {
fileInfoCache.Purge() fileInfoCache.Purge()
} }
func NewSqlFileInfoStore(sqlStore SqlStore) FileInfoStore { func NewSqlFileInfoStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) FileInfoStore {
s := &SqlFileInfoStore{sqlStore} s := &SqlFileInfoStore{
SqlStore: sqlStore,
metrics: metrics,
}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.FileInfo{}, "FileInfo").SetKeys(false, "Id") table := db.AddTableWithName(model.FileInfo{}, "FileInfo").SetKeys(false, "Id")
@@ -149,12 +153,10 @@ func (fs SqlFileInfoStore) GetForPost(postId string, readFromMaster bool, allowF
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if allowFromCache { if allowFromCache {
if cacheItem, ok := fileInfoCache.Get(postId); ok { if cacheItem, ok := fileInfoCache.Get(postId); ok {
if metrics != nil { if fs.metrics != nil {
metrics.IncrementMemCacheHitCounter("File Info Cache") fs.metrics.IncrementMemCacheHitCounter("File Info Cache")
} }
result.Data = cacheItem.([]*model.FileInfo) result.Data = cacheItem.([]*model.FileInfo)
@@ -162,13 +164,13 @@ func (fs SqlFileInfoStore) GetForPost(postId string, readFromMaster bool, allowF
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if fs.metrics != nil {
metrics.IncrementMemCacheMissCounter("File Info Cache") fs.metrics.IncrementMemCacheMissCounter("File Info Cache")
} }
} }
} else { } else {
if metrics != nil { if fs.metrics != nil {
metrics.IncrementMemCacheMissCounter("File Info Cache") fs.metrics.IncrementMemCacheMissCounter("File Info Cache")
} }
} }

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

@@ -18,6 +18,7 @@ import (
type SqlPostStore struct { type SqlPostStore struct {
SqlStore SqlStore
metrics einterfaces.MetricsInterface
} }
const ( const (
@@ -36,8 +37,11 @@ func ClearPostCaches() {
lastPostsCache.Purge() lastPostsCache.Purge()
} }
func NewSqlPostStore(sqlStore SqlStore) PostStore { func NewSqlPostStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) PostStore {
s := &SqlPostStore{sqlStore} s := &SqlPostStore{
SqlStore: sqlStore,
metrics: metrics,
}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.Post{}, "Posts").SetKeys(false, "Id") table := db.AddTableWithName(model.Post{}, "Posts").SetKeys(false, "Id")
@@ -398,25 +402,24 @@ func (s SqlPostStore) GetEtag(channelId string, allowFromCache bool) StoreChanne
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if allowFromCache { if allowFromCache {
if cacheItem, ok := lastPostTimeCache.Get(channelId); ok { if cacheItem, ok := lastPostTimeCache.Get(channelId); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Last Post Time") s.metrics.IncrementMemCacheHitCounter("Last Post Time")
} }
result.Data = fmt.Sprintf("%v.%v", model.CurrentVersion, cacheItem.(int64)) result.Data = fmt.Sprintf("%v.%v", model.CurrentVersion, cacheItem.(int64))
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Last Post Time") s.metrics.IncrementMemCacheMissCounter("Last Post Time")
} }
} }
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Last Post Time") s.metrics.IncrementMemCacheMissCounter("Last Post Time")
} }
} }
@@ -570,7 +573,6 @@ func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFro
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if limit > 1000 { if limit > 1000 {
result.Err = model.NewLocAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_posts.app_error", nil, "channelId="+channelId) result.Err = model.NewLocAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_posts.app_error", nil, "channelId="+channelId)
@@ -581,8 +583,8 @@ func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFro
if allowFromCache && offset == 0 && limit == 60 { if allowFromCache && offset == 0 && limit == 60 {
if cacheItem, ok := lastPostsCache.Get(channelId); ok { if cacheItem, ok := lastPostsCache.Get(channelId); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Last Posts Cache") s.metrics.IncrementMemCacheHitCounter("Last Posts Cache")
} }
result.Data = cacheItem.(*model.PostList) result.Data = cacheItem.(*model.PostList)
@@ -590,13 +592,13 @@ func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFro
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Last Posts Cache") s.metrics.IncrementMemCacheMissCounter("Last Posts Cache")
} }
} }
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Last Posts Cache") s.metrics.IncrementMemCacheMissCounter("Last Posts Cache")
} }
} }
@@ -643,14 +645,13 @@ func (s SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if allowFromCache { if allowFromCache {
// If the last post in the channel's time is less than or equal to the time we are getting posts since, // If the last post in the channel's time is less than or equal to the time we are getting posts since,
// we can safely return no posts. // we can safely return no posts.
if cacheItem, ok := lastPostTimeCache.Get(channelId); ok && cacheItem.(int64) <= time { if cacheItem, ok := lastPostTimeCache.Get(channelId); ok && cacheItem.(int64) <= time {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Last Post Time") s.metrics.IncrementMemCacheHitCounter("Last Post Time")
} }
list := model.NewPostList() list := model.NewPostList()
result.Data = list result.Data = list
@@ -658,13 +659,13 @@ func (s SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Last Post Time") s.metrics.IncrementMemCacheMissCounter("Last Post Time")
} }
} }
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Last Post Time") s.metrics.IncrementMemCacheMissCounter("Last Post Time")
} }
} }

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

@@ -19,6 +19,7 @@ import (
"github.com/go-sql-driver/mysql" "github.com/go-sql-driver/mysql"
"github.com/lib/pq" "github.com/lib/pq"
"github.com/mattermost/gorp" "github.com/mattermost/gorp"
"github.com/mattermost/mattermost-server/einterfaces"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -96,7 +97,7 @@ type SqlSupplier struct {
oldStores SqlSupplierOldStores oldStores SqlSupplierOldStores
} }
func NewSqlSupplier() *SqlSupplier { func NewSqlSupplier(metrics einterfaces.MetricsInterface) *SqlSupplier {
supplier := &SqlSupplier{ supplier := &SqlSupplier{
rrCounter: 0, rrCounter: 0,
srCounter: 0, srCounter: 0,
@@ -105,24 +106,24 @@ func NewSqlSupplier() *SqlSupplier {
supplier.initConnection() supplier.initConnection()
supplier.oldStores.team = NewSqlTeamStore(supplier) supplier.oldStores.team = NewSqlTeamStore(supplier)
supplier.oldStores.channel = NewSqlChannelStore(supplier) supplier.oldStores.channel = NewSqlChannelStore(supplier, metrics)
supplier.oldStores.post = NewSqlPostStore(supplier) supplier.oldStores.post = NewSqlPostStore(supplier, metrics)
supplier.oldStores.user = NewSqlUserStore(supplier) supplier.oldStores.user = NewSqlUserStore(supplier, metrics)
supplier.oldStores.audit = NewSqlAuditStore(supplier) supplier.oldStores.audit = NewSqlAuditStore(supplier)
supplier.oldStores.cluster = NewSqlClusterDiscoveryStore(supplier) supplier.oldStores.cluster = NewSqlClusterDiscoveryStore(supplier)
supplier.oldStores.compliance = NewSqlComplianceStore(supplier) supplier.oldStores.compliance = NewSqlComplianceStore(supplier)
supplier.oldStores.session = NewSqlSessionStore(supplier) supplier.oldStores.session = NewSqlSessionStore(supplier)
supplier.oldStores.oauth = NewSqlOAuthStore(supplier) supplier.oldStores.oauth = NewSqlOAuthStore(supplier)
supplier.oldStores.system = NewSqlSystemStore(supplier) supplier.oldStores.system = NewSqlSystemStore(supplier)
supplier.oldStores.webhook = NewSqlWebhookStore(supplier) supplier.oldStores.webhook = NewSqlWebhookStore(supplier, metrics)
supplier.oldStores.command = NewSqlCommandStore(supplier) supplier.oldStores.command = NewSqlCommandStore(supplier)
supplier.oldStores.commandWebhook = NewSqlCommandWebhookStore(supplier) supplier.oldStores.commandWebhook = NewSqlCommandWebhookStore(supplier)
supplier.oldStores.preference = NewSqlPreferenceStore(supplier) supplier.oldStores.preference = NewSqlPreferenceStore(supplier)
supplier.oldStores.license = NewSqlLicenseStore(supplier) supplier.oldStores.license = NewSqlLicenseStore(supplier)
supplier.oldStores.token = NewSqlTokenStore(supplier) supplier.oldStores.token = NewSqlTokenStore(supplier)
supplier.oldStores.emoji = NewSqlEmojiStore(supplier) supplier.oldStores.emoji = NewSqlEmojiStore(supplier, metrics)
supplier.oldStores.status = NewSqlStatusStore(supplier) supplier.oldStores.status = NewSqlStatusStore(supplier)
supplier.oldStores.fileInfo = NewSqlFileInfoStore(supplier) supplier.oldStores.fileInfo = NewSqlFileInfoStore(supplier, metrics)
supplier.oldStores.job = NewSqlJobStore(supplier) supplier.oldStores.job = NewSqlJobStore(supplier)
supplier.oldStores.userAccessToken = NewSqlUserAccessTokenStore(supplier) supplier.oldStores.userAccessToken = NewSqlUserAccessTokenStore(supplier)

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

@@ -34,6 +34,7 @@ const (
type SqlUserStore struct { type SqlUserStore struct {
SqlStore SqlStore
metrics einterfaces.MetricsInterface
} }
var profilesInChannelCache *utils.Cache = utils.NewLru(PROFILES_IN_CHANNEL_CACHE_SIZE) var profilesInChannelCache *utils.Cache = utils.NewLru(PROFILES_IN_CHANNEL_CACHE_SIZE)
@@ -48,8 +49,11 @@ func (us SqlUserStore) InvalidatProfileCacheForUser(userId string) {
profileByIdsCache.Remove(userId) profileByIdsCache.Remove(userId)
} }
func NewSqlUserStore(sqlStore SqlStore) UserStore { func NewSqlUserStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) UserStore {
us := &SqlUserStore{sqlStore} us := &SqlUserStore{
SqlStore: sqlStore,
metrics: metrics,
}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.User{}, "Users").SetKeys(false, "Id") table := db.AddTableWithName(model.User{}, "Users").SetKeys(false, "Id")
@@ -572,25 +576,24 @@ func (us SqlUserStore) GetAllProfilesInChannel(channelId string, allowFromCache
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
if allowFromCache { if allowFromCache {
if cacheItem, ok := profilesInChannelCache.Get(channelId); ok { if cacheItem, ok := profilesInChannelCache.Get(channelId); ok {
if metrics != nil { if us.metrics != nil {
metrics.IncrementMemCacheHitCounter("Profiles in Channel") us.metrics.IncrementMemCacheHitCounter("Profiles in Channel")
} }
result.Data = cacheItem.(map[string]*model.User) result.Data = cacheItem.(map[string]*model.User)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if us.metrics != nil {
metrics.IncrementMemCacheMissCounter("Profiles in Channel") us.metrics.IncrementMemCacheMissCounter("Profiles in Channel")
} }
} }
} else { } else {
if metrics != nil { if us.metrics != nil {
metrics.IncrementMemCacheMissCounter("Profiles in Channel") us.metrics.IncrementMemCacheMissCounter("Profiles in Channel")
} }
} }
@@ -838,7 +841,6 @@ func (us SqlUserStore) GetProfileByIds(userIds []string, allowFromCache bool) St
go func() { go func() {
result := StoreResult{} result := StoreResult{}
metrics := einterfaces.GetMetricsInterface()
users := []*model.User{} users := []*model.User{}
props := make(map[string]interface{}) props := make(map[string]interface{})
@@ -855,14 +857,14 @@ func (us SqlUserStore) GetProfileByIds(userIds []string, allowFromCache bool) St
remainingUserIds = append(remainingUserIds, userId) remainingUserIds = append(remainingUserIds, userId)
} }
} }
if metrics != nil { if us.metrics != nil {
metrics.AddMemCacheHitCounter("Profile By Ids", float64(len(users))) us.metrics.AddMemCacheHitCounter("Profile By Ids", float64(len(users)))
metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds))) us.metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds)))
} }
} else { } else {
remainingUserIds = userIds remainingUserIds = userIds
if metrics != nil { if us.metrics != nil {
metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds))) us.metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds)))
} }
} }

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

@@ -15,6 +15,7 @@ import (
type SqlWebhookStore struct { type SqlWebhookStore struct {
SqlStore SqlStore
metrics einterfaces.MetricsInterface
} }
const ( const (
@@ -28,8 +29,11 @@ func ClearWebhookCaches() {
webhookCache.Purge() webhookCache.Purge()
} }
func NewSqlWebhookStore(sqlStore SqlStore) WebhookStore { func NewSqlWebhookStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) WebhookStore {
s := &SqlWebhookStore{sqlStore} s := &SqlWebhookStore{
SqlStore: sqlStore,
metrics: metrics,
}
for _, db := range sqlStore.GetAllConns() { for _, db := range sqlStore.GetAllConns() {
table := db.AddTableWithName(model.IncomingWebhook{}, "IncomingWebhooks").SetKeys(false, "Id") table := db.AddTableWithName(model.IncomingWebhook{}, "IncomingWebhooks").SetKeys(false, "Id")
@@ -137,18 +141,17 @@ func (s SqlWebhookStore) GetIncoming(id string, allowFromCache bool) StoreChanne
result := StoreResult{} result := StoreResult{}
if allowFromCache { if allowFromCache {
metrics := einterfaces.GetMetricsInterface()
if cacheItem, ok := webhookCache.Get(id); ok { if cacheItem, ok := webhookCache.Get(id); ok {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheHitCounter("Webhook") s.metrics.IncrementMemCacheHitCounter("Webhook")
} }
result.Data = cacheItem.(*model.IncomingWebhook) result.Data = cacheItem.(*model.IncomingWebhook)
storeChannel <- result storeChannel <- result
close(storeChannel) close(storeChannel)
return return
} else { } else {
if metrics != nil { if s.metrics != nil {
metrics.IncrementMemCacheMissCounter("Webhook") s.metrics.IncrementMemCacheMissCounter("Webhook")
} }
} }
} }