more global config ref cleanup (#7802)

Этот коммит содержится в:
Chris
2017-11-09 14:46:20 -06:00
коммит произвёл GitHub
родитель b0c18ece09
Коммит 10c5a927cb
49 изменённых файлов: 216 добавлений и 217 удалений

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

@@ -189,7 +189,7 @@ func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request
return return
} }
reportBytes, err := app.GetComplianceFile(job) reportBytes, err := c.App.GetComplianceFile(job)
if err != nil { if err != nil {
c.Err = err c.Err = err
return return

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

@@ -332,5 +332,5 @@ func getPublicLink(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
w.Write([]byte(model.StringToJson(app.GeneratePublicLinkV3(c.GetSiteURLHeader(), info)))) w.Write([]byte(model.StringToJson(c.App.GeneratePublicLinkV3(c.GetSiteURLHeader(), info))))
} }

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

@@ -8,7 +8,6 @@ import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -21,7 +20,7 @@ func (api *API) InitStatus() {
} }
func getStatusesHttp(c *Context, w http.ResponseWriter, r *http.Request) { func getStatusesHttp(c *Context, w http.ResponseWriter, r *http.Request) {
statusMap := model.StatusMapToInterfaceMap(app.GetAllStatuses()) statusMap := model.StatusMapToInterfaceMap(c.App.GetAllStatuses())
w.Write([]byte(model.StringInterfaceToJson(statusMap))) w.Write([]byte(model.StringInterfaceToJson(statusMap)))
} }

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

@@ -689,19 +689,20 @@ func s3New(endpoint, accessKey, secretKey string, secure bool, signV2 bool, regi
return s3.NewWithCredentials(endpoint, creds, secure, region) return s3.NewWithCredentials(endpoint, creds, secure, region)
} }
func cleanupTestFile(info *model.FileInfo) error { func (me *TestHelper) cleanupTestFile(info *model.FileInfo) error {
if *utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 { cfg := me.App.Config()
endpoint := utils.Cfg.FileSettings.AmazonS3Endpoint if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
accessKey := utils.Cfg.FileSettings.AmazonS3AccessKeyId endpoint := cfg.FileSettings.AmazonS3Endpoint
secretKey := utils.Cfg.FileSettings.AmazonS3SecretAccessKey accessKey := cfg.FileSettings.AmazonS3AccessKeyId
secure := *utils.Cfg.FileSettings.AmazonS3SSL secretKey := cfg.FileSettings.AmazonS3SecretAccessKey
signV2 := *utils.Cfg.FileSettings.AmazonS3SignV2 secure := *cfg.FileSettings.AmazonS3SSL
region := utils.Cfg.FileSettings.AmazonS3Region signV2 := *cfg.FileSettings.AmazonS3SignV2
region := cfg.FileSettings.AmazonS3Region
s3Clnt, err := s3New(endpoint, accessKey, secretKey, secure, signV2, region) s3Clnt, err := s3New(endpoint, accessKey, secretKey, secure, signV2, region)
if err != nil { if err != nil {
return err return err
} }
bucket := utils.Cfg.FileSettings.AmazonS3Bucket bucket := cfg.FileSettings.AmazonS3Bucket
if err := s3Clnt.RemoveObject(bucket, info.Path); err != nil { if err := s3Clnt.RemoveObject(bucket, info.Path); err != nil {
return err return err
} }
@@ -717,19 +718,19 @@ func cleanupTestFile(info *model.FileInfo) error {
return err return err
} }
} }
} else if *utils.Cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL { } else if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
if err := os.Remove(utils.Cfg.FileSettings.Directory + info.Path); err != nil { if err := os.Remove(cfg.FileSettings.Directory + info.Path); err != nil {
return err return err
} }
if info.ThumbnailPath != "" { if info.ThumbnailPath != "" {
if err := os.Remove(utils.Cfg.FileSettings.Directory + info.ThumbnailPath); err != nil { if err := os.Remove(cfg.FileSettings.Directory + info.ThumbnailPath); err != nil {
return err return err
} }
} }
if info.PreviewPath != "" { if info.PreviewPath != "" {
if err := os.Remove(utils.Cfg.FileSettings.Directory + info.PreviewPath); err != nil { if err := os.Remove(cfg.FileSettings.Directory + info.PreviewPath); err != nil {
return err return err
} }
} }

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

@@ -8,7 +8,6 @@ import (
"strconv" "strconv"
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
"github.com/mssola/user_agent" "github.com/mssola/user_agent"
@@ -100,7 +99,7 @@ func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request
return return
} }
reportBytes, err := app.GetComplianceFile(job) reportBytes, err := c.App.GetComplianceFile(job)
if err != nil { if err != nil {
c.Err = err c.Err = err
return return

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

@@ -201,7 +201,7 @@ func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) {
} }
resp := make(map[string]string) resp := make(map[string]string)
resp["link"] = app.GeneratePublicLink(c.GetSiteURLHeader(), info) resp["link"] = c.App.GeneratePublicLink(c.GetSiteURLHeader(), info)
w.Write([]byte(model.MapToJson(resp))) w.Write([]byte(model.MapToJson(resp)))
} }

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

@@ -10,7 +10,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store"
) )
@@ -94,7 +93,7 @@ func TestUploadFile(t *testing.T) {
// Wait a bit for files to ready // Wait a bit for files to ready
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
if err := cleanupTestFile(info); err != nil { if err := th.cleanupTestFile(info); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -363,7 +362,7 @@ func TestGetFileLink(t *testing.T) {
if result := <-th.App.Srv.Store.FileInfo().Get(fileId); result.Err != nil { if result := <-th.App.Srv.Store.FileInfo().Get(fileId); result.Err != nil {
t.Fatal(result.Err) t.Fatal(result.Err)
} else { } else {
cleanupTestFile(result.Data.(*model.FileInfo)) th.cleanupTestFile(result.Data.(*model.FileInfo))
} }
} }
@@ -520,7 +519,7 @@ func TestGetPublicFile(t *testing.T) {
result := <-th.App.Srv.Store.FileInfo().Get(fileId) result := <-th.App.Srv.Store.FileInfo().Get(fileId)
info := result.Data.(*model.FileInfo) info := result.Data.(*model.FileInfo)
link := app.GeneratePublicLink(Client.Url, info) link := th.App.GeneratePublicLink(Client.Url, info)
// Wait a bit for files to ready // Wait a bit for files to ready
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
@@ -551,9 +550,9 @@ func TestGetPublicFile(t *testing.T) {
t.Fatal("should've failed to get image with public link after salt changed") t.Fatal("should've failed to get image with public link after salt changed")
} }
if err := cleanupTestFile(store.Must(th.App.Srv.Store.FileInfo().Get(fileId)).(*model.FileInfo)); err != nil { if err := th.cleanupTestFile(store.Must(th.App.Srv.Store.FileInfo().Get(fileId)).(*model.FileInfo)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
cleanupTestFile(info) th.cleanupTestFile(info)
} }

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

@@ -841,7 +841,7 @@ func TestGetProfileImage(t *testing.T) {
CheckNoError(t, resp) CheckNoError(t, resp)
info := &model.FileInfo{Path: "/users/" + user.Id + "/profile.png"} info := &model.FileInfo{Path: "/users/" + user.Id + "/profile.png"}
if err := cleanupTestFile(info); err != nil { if err := th.cleanupTestFile(info); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
@@ -2089,7 +2089,7 @@ func TestSetProfileImage(t *testing.T) {
assert.True(t, buser.LastPictureUpdate < ruser.LastPictureUpdate, "Picture should have updated for user") assert.True(t, buser.LastPictureUpdate < ruser.LastPictureUpdate, "Picture should have updated for user")
info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"} info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"}
if err := cleanupTestFile(info); err != nil { if err := th.cleanupTestFile(info); err != nil {
t.Fatal(err) t.Fatal(err)
} }
} }
@@ -2381,11 +2381,9 @@ func TestDisableUserAccessToken(t *testing.T) {
testDescription := "test token" testDescription := "test token"
enableUserAccessTokens := *utils.Cfg.ServiceSettings.EnableUserAccessTokens enableUserAccessTokens := *th.App.Config().ServiceSettings.EnableUserAccessTokens
defer func() { defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens })
*utils.Cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens *th.App.Config().ServiceSettings.EnableUserAccessTokens = true
}()
*utils.Cfg.ServiceSettings.EnableUserAccessTokens = true
th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id, false) th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id, false)
token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)
@@ -2428,11 +2426,9 @@ func TestEnableUserAccessToken(t *testing.T) {
testDescription := "test token" testDescription := "test token"
enableUserAccessTokens := *utils.Cfg.ServiceSettings.EnableUserAccessTokens enableUserAccessTokens := *th.App.Config().ServiceSettings.EnableUserAccessTokens
defer func() { defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens })
*utils.Cfg.ServiceSettings.EnableUserAccessTokens = enableUserAccessTokens *th.App.Config().ServiceSettings.EnableUserAccessTokens = true
}()
*utils.Cfg.ServiceSettings.EnableUserAccessTokens = true
th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id, false) th.App.UpdateUserRoles(th.BasicUser.Id, model.ROLE_SYSTEM_USER.Id+" "+model.ROLE_SYSTEM_USER_ACCESS_TOKEN.Id, false)
token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription)

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

@@ -18,7 +18,7 @@ import (
type CommandProvider interface { type CommandProvider interface {
GetTrigger() string GetTrigger() string
GetCommand(T goi18n.TranslateFunc) *model.Command GetCommand(a *App, T goi18n.TranslateFunc) *model.Command
DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse
} }
@@ -65,11 +65,13 @@ func (a *App) ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([
commands := make([]*model.Command, 0, 32) commands := make([]*model.Command, 0, 32)
seen := make(map[string]bool) seen := make(map[string]bool)
for _, value := range commandProviders { for _, value := range commandProviders {
cpy := *value.GetCommand(T) if cmd := value.GetCommand(a, T); cmd != nil {
if cpy.AutoComplete && !seen[cpy.Id] { cpy := *cmd
cpy.Sanitize() if cpy.AutoComplete && !seen[cpy.Id] {
seen[cpy.Trigger] = true cpy.Sanitize()
commands = append(commands, &cpy) seen[cpy.Trigger] = true
commands = append(commands, &cpy)
}
} }
} }
@@ -107,11 +109,13 @@ func (a *App) ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.C
commands := make([]*model.Command, 0, 32) commands := make([]*model.Command, 0, 32)
seen := make(map[string]bool) seen := make(map[string]bool)
for _, value := range commandProviders { for _, value := range commandProviders {
cpy := *value.GetCommand(T) if cmd := value.GetCommand(a, T); cmd != nil {
if cpy.AutoComplete && !seen[cpy.Id] { cpy := *cmd
cpy.Sanitize() if cpy.AutoComplete && !seen[cpy.Id] {
seen[cpy.Trigger] = true cpy.Sanitize()
commands = append(commands, &cpy) seen[cpy.Trigger] = true
commands = append(commands, &cpy)
}
} }
} }
@@ -141,94 +145,96 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *
provider := GetCommandProvider(trigger) provider := GetCommandProvider(trigger)
if provider != nil { if provider != nil {
response := provider.DoCommand(a, args, message) if cmd := provider.GetCommand(a, args.T); cmd != nil {
return a.HandleCommandResponse(provider.GetCommand(args.T), args, response, true) response := provider.DoCommand(a, args, message)
return a.HandleCommandResponse(cmd, args, response, true)
}
}
if !*a.Config().ServiceSettings.EnableCommands {
return nil, model.NewAppError("ExecuteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented)
}
chanChan := a.Srv.Store.Channel().Get(args.ChannelId, true)
teamChan := a.Srv.Store.Team().Get(args.TeamId)
userChan := a.Srv.Store.User().Get(args.UserId)
if result := <-a.Srv.Store.Command().GetByTeam(args.TeamId); result.Err != nil {
return nil, result.Err
} else { } else {
if !*a.Config().ServiceSettings.EnableCommands {
return nil, model.NewAppError("ExecuteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) var team *model.Team
if tr := <-teamChan; tr.Err != nil {
return nil, tr.Err
} else {
team = tr.Data.(*model.Team)
} }
chanChan := a.Srv.Store.Channel().Get(args.ChannelId, true) var user *model.User
teamChan := a.Srv.Store.Team().Get(args.TeamId) if ur := <-userChan; ur.Err != nil {
userChan := a.Srv.Store.User().Get(args.UserId) return nil, ur.Err
if result := <-a.Srv.Store.Command().GetByTeam(args.TeamId); result.Err != nil {
return nil, result.Err
} else { } else {
user = ur.Data.(*model.User)
}
var team *model.Team var channel *model.Channel
if tr := <-teamChan; tr.Err != nil { if cr := <-chanChan; cr.Err != nil {
return nil, tr.Err return nil, cr.Err
} else { } else {
team = tr.Data.(*model.Team) channel = cr.Data.(*model.Channel)
} }
var user *model.User teamCmds := result.Data.([]*model.Command)
if ur := <-userChan; ur.Err != nil { for _, cmd := range teamCmds {
return nil, ur.Err if trigger == cmd.Trigger {
} else { l4g.Debug(fmt.Sprintf(utils.T("api.command.execute_command.debug"), trigger, args.UserId))
user = ur.Data.(*model.User)
}
var channel *model.Channel p := url.Values{}
if cr := <-chanChan; cr.Err != nil { p.Set("token", cmd.Token)
return nil, cr.Err
} else {
channel = cr.Data.(*model.Channel)
}
teamCmds := result.Data.([]*model.Command) p.Set("team_id", cmd.TeamId)
for _, cmd := range teamCmds { p.Set("team_domain", team.Name)
if trigger == cmd.Trigger {
l4g.Debug(fmt.Sprintf(utils.T("api.command.execute_command.debug"), trigger, args.UserId))
p := url.Values{} p.Set("channel_id", args.ChannelId)
p.Set("token", cmd.Token) p.Set("channel_name", channel.Name)
p.Set("team_id", cmd.TeamId) p.Set("user_id", args.UserId)
p.Set("team_domain", team.Name) p.Set("user_name", user.Username)
p.Set("channel_id", args.ChannelId) p.Set("command", "/"+trigger)
p.Set("channel_name", channel.Name) p.Set("text", message)
p.Set("user_id", args.UserId) if hook, err := a.CreateCommandWebhook(cmd.Id, args); err != nil {
p.Set("user_name", user.Username) return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError)
} else {
p.Set("response_url", args.SiteURL+"/hooks/commands/"+hook.Id)
}
p.Set("command", "/"+trigger) method := "POST"
p.Set("text", message) if cmd.Method == model.COMMAND_METHOD_GET {
method = "GET"
}
if hook, err := a.CreateCommandWebhook(cmd.Id, args); err != nil { req, _ := http.NewRequest(method, cmd.URL, strings.NewReader(p.Encode()))
return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError) req.Header.Set("Accept", "application/json")
} else { if cmd.Method == model.COMMAND_METHOD_POST {
p.Set("response_url", args.SiteURL+"/hooks/commands/"+hook.Id) req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} }
method := "POST" if resp, err := utils.HttpClient(false).Do(req); err != nil {
if cmd.Method == model.COMMAND_METHOD_GET { return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError)
method = "GET" } else {
} if resp.StatusCode == http.StatusOK {
response := model.CommandResponseFromHTTPBody(resp.Header.Get("Content-Type"), resp.Body)
req, _ := http.NewRequest(method, cmd.URL, strings.NewReader(p.Encode())) if response == nil {
req.Header.Set("Accept", "application/json") return nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusInternalServerError)
if cmd.Method == model.COMMAND_METHOD_POST {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if resp, err := utils.HttpClient(false).Do(req); err != nil {
return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError)
} else {
if resp.StatusCode == http.StatusOK {
response := model.CommandResponseFromHTTPBody(resp.Header.Get("Content-Type"), resp.Body)
if response == nil {
return nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusInternalServerError)
} else {
return a.HandleCommandResponse(cmd, args, response, false)
}
} else { } else {
defer resp.Body.Close() return a.HandleCommandResponse(cmd, args, response, false)
body, _ := ioutil.ReadAll(resp.Body)
return nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]interface{}{"Trigger": trigger, "Status": resp.Status}, string(body), http.StatusInternalServerError)
} }
} else {
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]interface{}{"Trigger": trigger, "Status": resp.Status}, string(body), http.StatusInternalServerError)
} }
} }
} }
@@ -293,8 +299,8 @@ func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError
} }
} }
for _, builtInProvider := range commandProviders { for _, builtInProvider := range commandProviders {
builtInCommand := *builtInProvider.GetCommand(utils.T) builtInCommand := builtInProvider.GetCommand(a, utils.T)
if cmd.Trigger == builtInCommand.Trigger { if builtInCommand != nil && cmd.Trigger == builtInCommand.Trigger {
return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("CreateCommand", "api.command.duplicate_trigger.app_error", nil, "", http.StatusBadRequest)
} }
} }

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

@@ -23,7 +23,7 @@ func (me *AwayProvider) GetTrigger() string {
return CMD_AWAY return CMD_AWAY
} }
func (me *AwayProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *AwayProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_AWAY, Trigger: CMD_AWAY,
AutoComplete: true, AutoComplete: true,

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

@@ -24,7 +24,7 @@ func (me *HeaderProvider) GetTrigger() string {
return CMD_HEADER return CMD_HEADER
} }
func (me *HeaderProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *HeaderProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_HEADER, Trigger: CMD_HEADER,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *PurposeProvider) GetTrigger() string {
return CMD_PURPOSE return CMD_PURPOSE
} }
func (me *PurposeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *PurposeProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_PURPOSE, Trigger: CMD_PURPOSE,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *RenameProvider) GetTrigger() string {
return CMD_RENAME return CMD_RENAME
} }
func (me *RenameProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *RenameProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_RENAME, Trigger: CMD_RENAME,
AutoComplete: true, AutoComplete: true,

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

@@ -25,7 +25,7 @@ func (me *CodeProvider) GetTrigger() string {
return CMD_CODE return CMD_CODE
} }
func (me *CodeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *CodeProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_CODE, Trigger: CMD_CODE,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *DndProvider) GetTrigger() string {
return CMD_DND return CMD_DND
} }
func (me *DndProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *DndProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_DND, Trigger: CMD_DND,
AutoComplete: true, AutoComplete: true,

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

@@ -30,7 +30,7 @@ func (me *EchoProvider) GetTrigger() string {
return CMD_ECHO return CMD_ECHO
} }
func (me *EchoProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *EchoProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_ECHO, Trigger: CMD_ECHO,
AutoComplete: true, AutoComplete: true,

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

@@ -34,7 +34,7 @@ func (me *CollapseProvider) GetTrigger() string {
return CMD_COLLAPSE return CMD_COLLAPSE
} }
func (me *ExpandProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *ExpandProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_EXPAND, Trigger: CMD_EXPAND,
AutoComplete: true, AutoComplete: true,
@@ -43,7 +43,7 @@ func (me *ExpandProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *CollapseProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *CollapseProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_COLLAPSE, Trigger: CMD_COLLAPSE,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (h *HelpProvider) GetTrigger() string {
return CMD_HELP return CMD_HELP
} }
func (h *HelpProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (h *HelpProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_HELP, Trigger: CMD_HELP,
AutoComplete: true, AutoComplete: true,

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

@@ -8,7 +8,6 @@ import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
goi18n "github.com/nicksnyder/go-i18n/i18n" goi18n "github.com/nicksnyder/go-i18n/i18n"
) )
@@ -27,9 +26,9 @@ func (me *InvitePeopleProvider) GetTrigger() string {
return CMD_INVITE_PEOPLE return CMD_INVITE_PEOPLE
} }
func (me *InvitePeopleProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *InvitePeopleProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
autoComplete := true autoComplete := true
if !utils.Cfg.EmailSettings.SendEmailNotifications || !utils.Cfg.TeamSettings.EnableUserCreation { if !a.Config().EmailSettings.SendEmailNotifications || !a.Config().TeamSettings.EnableUserCreation {
autoComplete = false autoComplete = false
} }
return &model.Command{ return &model.Command{

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

@@ -23,7 +23,7 @@ func (me *JoinProvider) GetTrigger() string {
return CMD_JOIN return CMD_JOIN
} }
func (me *JoinProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *JoinProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_JOIN, Trigger: CMD_JOIN,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *LeaveProvider) GetTrigger() string {
return CMD_LEAVE return CMD_LEAVE
} }
func (me *LeaveProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *LeaveProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_LEAVE, Trigger: CMD_LEAVE,
AutoComplete: true, AutoComplete: true,

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

@@ -66,16 +66,17 @@ type LoadTestProvider struct {
} }
func init() { func init() {
if !utils.Cfg.ServiceSettings.EnableTesting { RegisterCommandProvider(&LoadTestProvider{})
RegisterCommandProvider(&LoadTestProvider{})
}
} }
func (me *LoadTestProvider) GetTrigger() string { func (me *LoadTestProvider) GetTrigger() string {
return CMD_TEST return CMD_TEST
} }
func (me *LoadTestProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *LoadTestProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
if !a.Config().ServiceSettings.EnableTesting {
return nil
}
return &model.Command{ return &model.Command{
Trigger: CMD_TEST, Trigger: CMD_TEST,
AutoComplete: false, AutoComplete: false,

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

@@ -23,7 +23,7 @@ func (me *LogoutProvider) GetTrigger() string {
return CMD_LOGOUT return CMD_LOGOUT
} }
func (me *LogoutProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *LogoutProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_LOGOUT, Trigger: CMD_LOGOUT,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *MeProvider) GetTrigger() string {
return CMD_ME return CMD_ME
} }
func (me *MeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *MeProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_ME, Trigger: CMD_ME,
AutoComplete: true, AutoComplete: true,

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

@@ -26,7 +26,7 @@ func (me *msgProvider) GetTrigger() string {
return CMD_MSG return CMD_MSG
} }
func (me *msgProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *msgProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_MSG, Trigger: CMD_MSG,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *OfflineProvider) GetTrigger() string {
return CMD_OFFLINE return CMD_OFFLINE
} }
func (me *OfflineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *OfflineProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_OFFLINE, Trigger: CMD_OFFLINE,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *OnlineProvider) GetTrigger() string {
return CMD_ONLINE return CMD_ONLINE
} }
func (me *OnlineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *OnlineProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_ONLINE, Trigger: CMD_ONLINE,
AutoComplete: true, AutoComplete: true,

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

@@ -24,8 +24,8 @@ func (open *OpenProvider) GetTrigger() string {
return CMD_OPEN return CMD_OPEN
} }
func (open *OpenProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (open *OpenProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
cmd := open.JoinProvider.GetCommand(T) cmd := open.JoinProvider.GetCommand(a, T)
cmd.Trigger = CMD_OPEN cmd.Trigger = CMD_OPEN
cmd.DisplayName = T("api.command_open.name") cmd.DisplayName = T("api.command_open.name")
return cmd return cmd

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

@@ -10,7 +10,6 @@ import (
goi18n "github.com/nicksnyder/go-i18n/i18n" goi18n "github.com/nicksnyder/go-i18n/i18n"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils"
) )
type RemoveProvider struct { type RemoveProvider struct {
@@ -37,7 +36,7 @@ func (me *KickProvider) GetTrigger() string {
return CMD_KICK return CMD_KICK
} }
func (me *RemoveProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *RemoveProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_REMOVE, Trigger: CMD_REMOVE,
AutoComplete: true, AutoComplete: true,
@@ -47,7 +46,7 @@ func (me *RemoveProvider) GetCommand(T goi18n.TranslateFunc) *model.Command {
} }
} }
func (me *KickProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *KickProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_KICK, Trigger: CMD_KICK,
AutoComplete: true, AutoComplete: true,
@@ -102,7 +101,7 @@ func doCommand(a *App, args *model.CommandArgs, message string) *model.CommandRe
_, err = a.GetChannelMember(args.ChannelId, userProfile.Id) _, err = a.GetChannelMember(args.ChannelId, userProfile.Id)
if err != nil { if err != nil {
nameFormat := *utils.Cfg.TeamSettings.TeammateNameDisplay nameFormat := *a.Config().TeamSettings.TeammateNameDisplay
return &model.CommandResponse{Text: args.T("api.command_remove.user_not_in_channel", map[string]interface{}{"Username": userProfile.GetDisplayName(nameFormat)}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} return &model.CommandResponse{Text: args.T("api.command_remove.user_not_in_channel", map[string]interface{}{"Username": userProfile.GetDisplayName(nameFormat)}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
} }

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

@@ -23,7 +23,7 @@ func (search *SearchProvider) GetTrigger() string {
return CMD_SEARCH return CMD_SEARCH
} }
func (search *SearchProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (search *SearchProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_SEARCH, Trigger: CMD_SEARCH,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (settings *SettingsProvider) GetTrigger() string {
return CMD_SETTINGS return CMD_SETTINGS
} }
func (settings *SettingsProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (settings *SettingsProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_SETTINGS, Trigger: CMD_SETTINGS,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *ShortcutsProvider) GetTrigger() string {
return CMD_SHORTCUTS return CMD_SHORTCUTS
} }
func (me *ShortcutsProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *ShortcutsProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_SHORTCUTS, Trigger: CMD_SHORTCUTS,
AutoComplete: true, AutoComplete: true,

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

@@ -23,7 +23,7 @@ func (me *ShrugProvider) GetTrigger() string {
return CMD_SHRUG return CMD_SHRUG
} }
func (me *ShrugProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *ShrugProvider) GetCommand(a *App, T goi18n.TranslateFunc) *model.Command {
return &model.Command{ return &model.Command{
Trigger: CMD_SHRUG, Trigger: CMD_SHRUG,
AutoComplete: true, AutoComplete: true,

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

@@ -55,10 +55,9 @@ func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.Ap
} }
} }
func GetComplianceFile(job *model.Compliance) ([]byte, *model.AppError) { func (a *App) GetComplianceFile(job *model.Compliance) ([]byte, *model.AppError) {
if f, err := ioutil.ReadFile(*utils.Cfg.ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip"); err != nil { if f, err := ioutil.ReadFile(*a.Config().ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip"); err != nil {
return nil, model.NewAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error(), http.StatusNotImplemented) return nil, model.NewAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error(), http.StatusNotImplemented)
} else { } else {
return f, nil return f, nil
} }

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

@@ -458,8 +458,8 @@ func (a *App) trackConfig() {
SendDiagnostic(TRACK_CONFIG_PLUGIN, map[string]interface{}{ SendDiagnostic(TRACK_CONFIG_PLUGIN, map[string]interface{}{
"enable_jira": pluginSetting(&cfg.PluginSettings, "jira", "enabled", false), "enable_jira": pluginSetting(&cfg.PluginSettings, "jira", "enabled", false),
"enable": *utils.Cfg.PluginSettings.Enable, "enable": *cfg.PluginSettings.Enable,
"enable_uploads": *utils.Cfg.PluginSettings.EnableUploads, "enable_uploads": *cfg.PluginSettings.EnableUploads,
}) })
SendDiagnostic(TRACK_CONFIG_DATA_RETENTION, map[string]interface{}{ SendDiagnostic(TRACK_CONFIG_DATA_RETENTION, map[string]interface{}{

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

@@ -144,11 +144,9 @@ func TestDiagnostics(t *testing.T) {
}) })
t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) { t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) {
oldSetting := *utils.Cfg.LogSettings.EnableDiagnostics oldSetting := *th.App.Config().LogSettings.EnableDiagnostics
*utils.Cfg.LogSettings.EnableDiagnostics = false th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = false })
defer func() { defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = oldSetting })
*utils.Cfg.LogSettings.EnableDiagnostics = oldSetting
}()
th.App.SendDailyDiagnostics() th.App.SendDailyDiagnostics()

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

@@ -72,8 +72,8 @@ func (job *EmailBatchingJob) Start() {
task.Cancel() task.Cancel()
} }
l4g.Debug(utils.T("api.email_batching.start.starting"), *utils.Cfg.EmailSettings.EmailBatchingInterval) l4g.Debug(utils.T("api.email_batching.start.starting"), *job.app.Config().EmailSettings.EmailBatchingInterval)
model.CreateRecurringTask(EMAIL_BATCHING_TASK_NAME, job.CheckPendingEmails, time.Duration(*utils.Cfg.EmailSettings.EmailBatchingInterval)*time.Second) model.CreateRecurringTask(EMAIL_BATCHING_TASK_NAME, job.CheckPendingEmails, time.Duration(*job.app.Config().EmailSettings.EmailBatchingInterval)*time.Second)
} }
func (job *EmailBatchingJob) Add(user *model.User, post *model.Post, team *model.Team) bool { func (job *EmailBatchingJob) Add(user *model.User, post *model.Post, team *model.Team) bool {

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

@@ -225,13 +225,13 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo {
} }
} }
func GeneratePublicLink(siteURL string, info *model.FileInfo) string { func (a *App) GeneratePublicLink(siteURL string, info *model.FileInfo) string {
hash := GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt) hash := GeneratePublicLinkHash(info.Id, *a.Config().FileSettings.PublicLinkSalt)
return fmt.Sprintf("%s/files/%v/public?h=%s", siteURL, info.Id, hash) return fmt.Sprintf("%s/files/%v/public?h=%s", siteURL, info.Id, hash)
} }
func GeneratePublicLinkV3(siteURL string, info *model.FileInfo) string { func (a *App) GeneratePublicLinkV3(siteURL string, info *model.FileInfo) string {
hash := GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt) hash := GeneratePublicLinkHash(info.Id, *a.Config().FileSettings.PublicLinkSalt)
return fmt.Sprintf("%s%s/public/files/%v/get?h=%s", siteURL, model.API_URL_SUFFIX_V3, info.Id, hash) return fmt.Sprintf("%s%s/public/files/%v/get?h=%s", siteURL, model.API_URL_SUFFIX_V3, info.Id, hash)
} }

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

@@ -10,7 +10,6 @@ import (
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store" "github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils"
) )
func ptrStr(s string) *string { func ptrStr(s string) *string {
@@ -1344,7 +1343,7 @@ func TestImportImportUser(t *testing.T) {
t.Fatalf("Expected EmailVerified to be true.") t.Fatalf("Expected EmailVerified to be true.")
} }
if user.Locale != *utils.Cfg.LocalizationSettings.DefaultClientLocale { if user.Locale != *th.App.Config().LocalizationSettings.DefaultClientLocale {
t.Fatalf("Expected Locale to be the default.") t.Fatalf("Expected Locale to be the default.")
} }

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

@@ -69,7 +69,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
mentionedUserIds[post.UserId] = true mentionedUserIds[post.UserId] = true
} }
} else { } else {
keywords := GetMentionKeywordsInChannel(profileMap, post.Type != model.POST_HEADER_CHANGE && post.Type != model.POST_PURPOSE_CHANGE) keywords := a.GetMentionKeywordsInChannel(profileMap, post.Type != model.POST_HEADER_CHANGE && post.Type != model.POST_PURPOSE_CHANGE)
var potentialOtherMentions []string var potentialOtherMentions []string
mentionedUserIds, potentialOtherMentions, hereNotification, channelNotification, allNotification = GetExplicitMentions(post.Message, keywords) mentionedUserIds, potentialOtherMentions, hereNotification, channelNotification, allNotification = GetExplicitMentions(post.Message, keywords)
@@ -909,7 +909,7 @@ func removeCodeFromMessage(message string) string {
// Given a map of user IDs to profiles, returns a list of mention // Given a map of user IDs to profiles, returns a list of mention
// keywords for all users in the channel. // keywords for all users in the channel.
func GetMentionKeywordsInChannel(profiles map[string]*model.User, lookForSpecialMentions bool) map[string][]string { func (a *App) GetMentionKeywordsInChannel(profiles map[string]*model.User, lookForSpecialMentions bool) map[string][]string {
keywords := make(map[string][]string) keywords := make(map[string][]string)
for id, profile := range profiles { for id, profile := range profiles {
@@ -933,7 +933,7 @@ func GetMentionKeywordsInChannel(profiles map[string]*model.User, lookForSpecial
// Add @channel and @all to keywords if user has them turned on // Add @channel and @all to keywords if user has them turned on
if lookForSpecialMentions { if lookForSpecialMentions {
if int64(len(profiles)) < *utils.Cfg.TeamSettings.MaxNotificationsPerChannel && profile.NotifyProps["channel"] == "true" { if int64(len(profiles)) < *a.Config().TeamSettings.MaxNotificationsPerChannel && profile.NotifyProps["channel"] == "true" {
keywords["@channel"] = append(keywords["@channel"], profile.Id) keywords["@channel"] = append(keywords["@channel"], profile.Id)
keywords["@all"] = append(keywords["@all"], profile.Id) keywords["@all"] = append(keywords["@all"], profile.Id)

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

@@ -447,7 +447,7 @@ func TestGetMentionKeywords(t *testing.T) {
} }
profiles := map[string]*model.User{user1.Id: user1} profiles := map[string]*model.User{user1.Id: user1}
mentions := GetMentionKeywordsInChannel(profiles, true) mentions := th.App.GetMentionKeywordsInChannel(profiles, true)
if len(mentions) != 3 { if len(mentions) != 3 {
t.Fatal("should've returned three mention keywords") t.Fatal("should've returned three mention keywords")
} else if ids, ok := mentions["user"]; !ok || ids[0] != user1.Id { } else if ids, ok := mentions["user"]; !ok || ids[0] != user1.Id {
@@ -469,7 +469,7 @@ func TestGetMentionKeywords(t *testing.T) {
} }
profiles = map[string]*model.User{user2.Id: user2} profiles = map[string]*model.User{user2.Id: user2}
mentions = GetMentionKeywordsInChannel(profiles, true) mentions = th.App.GetMentionKeywordsInChannel(profiles, true)
if len(mentions) != 2 { if len(mentions) != 2 {
t.Fatal("should've returned two mention keyword") t.Fatal("should've returned two mention keyword")
} else if ids, ok := mentions["First"]; !ok || ids[0] != user2.Id { } else if ids, ok := mentions["First"]; !ok || ids[0] != user2.Id {
@@ -487,7 +487,7 @@ func TestGetMentionKeywords(t *testing.T) {
} }
profiles = map[string]*model.User{user3.Id: user3} profiles = map[string]*model.User{user3.Id: user3}
mentions = GetMentionKeywordsInChannel(profiles, true) mentions = th.App.GetMentionKeywordsInChannel(profiles, true)
if len(mentions) != 3 { if len(mentions) != 3 {
t.Fatal("should've returned three mention keywords") t.Fatal("should've returned three mention keywords")
} else if ids, ok := mentions["@channel"]; !ok || ids[0] != user3.Id { } else if ids, ok := mentions["@channel"]; !ok || ids[0] != user3.Id {
@@ -509,7 +509,7 @@ func TestGetMentionKeywords(t *testing.T) {
} }
profiles = map[string]*model.User{user4.Id: user4} profiles = map[string]*model.User{user4.Id: user4}
mentions = GetMentionKeywordsInChannel(profiles, true) mentions = th.App.GetMentionKeywordsInChannel(profiles, true)
if len(mentions) != 6 { if len(mentions) != 6 {
t.Fatal("should've returned six mention keywords") t.Fatal("should've returned six mention keywords")
} else if ids, ok := mentions["user"]; !ok || ids[0] != user4.Id { } else if ids, ok := mentions["user"]; !ok || ids[0] != user4.Id {
@@ -551,7 +551,7 @@ func TestGetMentionKeywords(t *testing.T) {
user3.Id: user3, user3.Id: user3,
user4.Id: user4, user4.Id: user4,
} }
mentions = GetMentionKeywordsInChannel(profiles, true) mentions = th.App.GetMentionKeywordsInChannel(profiles, true)
if len(mentions) != 6 { if len(mentions) != 6 {
t.Fatal("should've returned six mention keywords") t.Fatal("should've returned six mention keywords")
} else if ids, ok := mentions["user"]; !ok || len(ids) != 2 || (ids[0] != user1.Id && ids[1] != user1.Id) || (ids[0] != user4.Id && ids[1] != user4.Id) { } else if ids, ok := mentions["user"]; !ok || len(ids) != 2 || (ids[0] != user1.Id && ids[1] != user1.Id) || (ids[0] != user4.Id && ids[1] != user4.Id) {
@@ -572,7 +572,7 @@ func TestGetMentionKeywords(t *testing.T) {
profiles = map[string]*model.User{ profiles = map[string]*model.User{
user1.Id: user1, user1.Id: user1,
} }
mentions = GetMentionKeywordsInChannel(profiles, false) mentions = th.App.GetMentionKeywordsInChannel(profiles, false)
if len(mentions) != 3 { if len(mentions) != 3 {
t.Fatal("should've returned three mention keywords") t.Fatal("should've returned three mention keywords")
} else if ids, ok := mentions["user"]; !ok || len(ids) != 1 || ids[0] != user1.Id { } else if ids, ok := mentions["user"]; !ok || len(ids) != 1 || ids[0] != user1.Id {

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

@@ -50,17 +50,17 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) {
isLicensed := utils.IsLicensed() isLicensed := utils.IsLicensed()
license := utils.License() license := utils.License()
timeout := *utils.Cfg.ServiceSettings.SessionIdleTimeoutInMinutes timeout := *th.App.Config().ServiceSettings.SessionIdleTimeoutInMinutes
defer func() { defer func() {
utils.SetIsLicensed(isLicensed) utils.SetIsLicensed(isLicensed)
utils.SetLicense(license) utils.SetLicense(license)
*utils.Cfg.ServiceSettings.SessionIdleTimeoutInMinutes = timeout th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = timeout })
}() }()
utils.SetIsLicensed(true) utils.SetIsLicensed(true)
utils.SetLicense(&model.License{Features: &model.Features{}}) utils.SetLicense(&model.License{Features: &model.Features{}})
utils.License().Features.SetDefaults() utils.License().Features.SetDefaults()
*utils.License().Features.Compliance = true *utils.License().Features.Compliance = true
*utils.Cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 5 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 5 })
rsession, err := th.App.GetSession(session.Token) rsession, err := th.App.GetSession(session.Token)
require.Nil(t, err) require.Nil(t, err)
@@ -139,7 +139,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) {
*utils.License().Features.Compliance = true *utils.License().Features.Compliance = true
// Test regular session with timeout set to 0, should not timeout // Test regular session with timeout set to 0, should not timeout
*utils.Cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 0 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 0 })
session = &model.Session{ session = &model.Session{
UserId: model.NewId(), UserId: model.NewId(),

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

@@ -34,8 +34,8 @@ func (a *App) AddStatusCache(status *model.Status) {
} }
} }
func GetAllStatuses() map[string]*model.Status { func (a *App) GetAllStatuses() map[string]*model.Status {
if !*utils.Cfg.ServiceSettings.EnableUserStatuses { if !*a.Config().ServiceSettings.EnableUserStatuses {
return map[string]*model.Status{} return map[string]*model.Status{}
} }
@@ -272,7 +272,7 @@ func (a *App) SetStatusAwayIfNeeded(userId string, manual bool) {
return return
} }
if !IsUserAway(status.LastActivityAt) { if !a.IsUserAway(status.LastActivityAt) {
return return
} }
} }
@@ -351,6 +351,6 @@ func (a *App) GetStatus(userId string) (*model.Status, *model.AppError) {
} }
} }
func IsUserAway(lastActivityAt int64) bool { func (a *App) IsUserAway(lastActivityAt int64) bool {
return model.GetMillis()-lastActivityAt >= *utils.Cfg.TeamSettings.UserStatusAwayTimeout*1000 return model.GetMillis()-lastActivityAt >= *a.Config().TeamSettings.UserStatusAwayTimeout*1000
} }

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

@@ -39,7 +39,7 @@ func (a *App) CreateTeamWithUser(team *model.Team, userId string) (*model.Team,
team.Email = user.Email team.Email = user.Email
} }
if !isTeamEmailAllowed(user) { if !a.isTeamEmailAllowed(user) {
return nil, model.NewAppError("isTeamEmailAllowed", "api.team.is_team_creation_allowed.domain.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("isTeamEmailAllowed", "api.team.is_team_creation_allowed.domain.app_error", nil, "", http.StatusBadRequest)
} }
@@ -55,11 +55,11 @@ func (a *App) CreateTeamWithUser(team *model.Team, userId string) (*model.Team,
return rteam, nil return rteam, nil
} }
func isTeamEmailAddressAllowed(email string) bool { func (a *App) isTeamEmailAddressAllowed(email string) bool {
email = strings.ToLower(email) email = strings.ToLower(email)
// commas and @ signs are optional // commas and @ signs are optional
// can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org // can be in the form of "@corp.mattermost.com, mattermost.com mattermost.org" -> corp.mattermost.com mattermost.com mattermost.org
domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(utils.Cfg.TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1)))) domains := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(a.Config().TeamSettings.RestrictCreationToDomains, "@", " ", -1), ",", " ", -1))))
matched := false matched := false
for _, d := range domains { for _, d := range domains {
@@ -69,21 +69,21 @@ func isTeamEmailAddressAllowed(email string) bool {
} }
} }
if len(utils.Cfg.TeamSettings.RestrictCreationToDomains) > 0 && !matched { if len(a.Config().TeamSettings.RestrictCreationToDomains) > 0 && !matched {
return false return false
} }
return true return true
} }
func isTeamEmailAllowed(user *model.User) bool { func (a *App) isTeamEmailAllowed(user *model.User) bool {
email := strings.ToLower(user.Email) email := strings.ToLower(user.Email)
if len(user.AuthService) > 0 && len(*user.AuthData) > 0 { if len(user.AuthService) > 0 && len(*user.AuthData) > 0 {
return true return true
} }
return isTeamEmailAddressAllowed(email) return a.isTeamEmailAddressAllowed(email)
} }
func (a *App) UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { func (a *App) UpdateTeam(team *model.Team) (*model.Team, *model.AppError) {
@@ -646,7 +646,7 @@ func (a *App) InviteNewUsersToTeam(emailList []string, teamId, senderId string)
var invalidEmailList []string var invalidEmailList []string
for _, email := range emailList { for _, email := range emailList {
if !isTeamEmailAddressAllowed(email) { if !a.isTeamEmailAddressAllowed(email) {
invalidEmailList = append(invalidEmailList, email) invalidEmailList = append(invalidEmailList, email)
} }
} }

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

@@ -743,7 +743,7 @@ func (a *App) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError)
var img []byte var img []byte
readFailed := false readFailed := false
if len(*utils.Cfg.FileSettings.DriverName) == 0 { if len(*a.Config().FileSettings.DriverName) == 0 {
var err *model.AppError var err *model.AppError
if img, err = CreateProfileImage(user.Username, user.Id, a.Config().FileSettings.InitialFont); err != nil { if img, err = CreateProfileImage(user.Username, user.Id, a.Config().FileSettings.InitialFont); err != nil {
return nil, false, err return nil, false, err

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

@@ -18,12 +18,12 @@ func TestCreateWebhookPost(t *testing.T) {
th := Setup().InitBasic() th := Setup().InitBasic()
defer th.TearDown() defer th.TearDown()
enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks enableIncomingHooks := th.App.Config().ServiceSettings.EnableIncomingWebhooks
defer func() { defer func() {
utils.Cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = enableIncomingHooks })
utils.SetDefaultRolesBasedOnConfig() utils.SetDefaultRolesBasedOnConfig()
}() }()
utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.EnableIncomingWebhooks = true })
utils.SetDefaultRolesBasedOnConfig() utils.SetDefaultRolesBasedOnConfig()
hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id}) hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id})

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

@@ -90,26 +90,30 @@ func runServer(configFileLocation string) {
wsapi.Init(a, a.Srv.WebSocketRouter) wsapi.Init(a, a.Srv.WebSocketRouter)
web.Init(api3) web.Init(api3)
if !utils.IsLicensed() && len(utils.Cfg.SqlSettings.DataSourceReplicas) > 1 { if !utils.IsLicensed() && len(a.Config().SqlSettings.DataSourceReplicas) > 1 {
l4g.Warn(utils.T("store.sql.read_replicas_not_licensed.critical")) l4g.Warn(utils.T("store.sql.read_replicas_not_licensed.critical"))
utils.Cfg.SqlSettings.DataSourceReplicas = utils.Cfg.SqlSettings.DataSourceReplicas[:1] a.UpdateConfig(func(cfg *model.Config) {
cfg.SqlSettings.DataSourceReplicas = cfg.SqlSettings.DataSourceReplicas[:1]
})
} }
if !utils.IsLicensed() { if !utils.IsLicensed() {
utils.Cfg.TeamSettings.MaxNotificationsPerChannel = &MaxNotificationsPerChannelDefault a.UpdateConfig(func(cfg *model.Config) {
cfg.TeamSettings.MaxNotificationsPerChannel = &MaxNotificationsPerChannelDefault
})
} }
a.ReloadConfig() a.ReloadConfig()
// Enable developer settings if this is a "dev" build // Enable developer settings if this is a "dev" build
if model.BuildNumber == "dev" { if model.BuildNumber == "dev" {
*utils.Cfg.ServiceSettings.EnableDeveloper = true a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableDeveloper = true })
} }
resetStatuses(a) resetStatuses(a)
// If we allow testing then listen for manual testing URL hits // If we allow testing then listen for manual testing URL hits
if utils.Cfg.ServiceSettings.EnableTesting { if a.Config().ServiceSettings.EnableTesting {
manualtesting.Init(api3) manualtesting.Init(api3)
} }
@@ -142,10 +146,10 @@ func runServer(configFileLocation string) {
}) })
} }
if *utils.Cfg.JobSettings.RunJobs { if *a.Config().JobSettings.RunJobs {
a.Jobs.StartWorkers() a.Jobs.StartWorkers()
} }
if *utils.Cfg.JobSettings.RunScheduler { if *a.Config().JobSettings.RunScheduler {
a.Jobs.StartSchedulers() a.Jobs.StartSchedulers()
} }

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

@@ -65,10 +65,10 @@ func (schedulers *Schedulers) Start() *Schedulers {
now := time.Now() now := time.Now()
for idx, scheduler := range schedulers.schedulers { for idx, scheduler := range schedulers.schedulers {
if !scheduler.Enabled(utils.Cfg) { if !scheduler.Enabled(schedulers.jobs.Config()) {
schedulers.nextRunTimes[idx] = nil schedulers.nextRunTimes[idx] = nil
} else { } else {
schedulers.setNextRunTime(utils.Cfg, idx, now, false) schedulers.setNextRunTime(schedulers.jobs.Config(), idx, now, false)
} }
} }
@@ -78,7 +78,7 @@ func (schedulers *Schedulers) Start() *Schedulers {
l4g.Debug("Schedulers received stop signal.") l4g.Debug("Schedulers received stop signal.")
return return
case now = <-time.After(1 * time.Minute): case now = <-time.After(1 * time.Minute):
cfg := utils.Cfg cfg := schedulers.jobs.Config()
for idx, nextTime := range schedulers.nextRunTimes { for idx, nextTime := range schedulers.nextRunTimes {
if nextTime == nil { if nextTime == nil {

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

@@ -5,7 +5,7 @@ package wsapi
import ( import (
l4g "github.com/alecthomas/log4go" l4g "github.com/alecthomas/log4go"
"github.com/mattermost/mattermost-server/app"
"github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/utils"
) )
@@ -13,12 +13,12 @@ import (
func (api *API) InitStatus() { func (api *API) InitStatus() {
l4g.Debug(utils.T("wsapi.status.init.debug")) l4g.Debug(utils.T("wsapi.status.init.debug"))
api.Router.Handle("get_statuses", api.ApiWebSocketHandler(getStatuses)) api.Router.Handle("get_statuses", api.ApiWebSocketHandler(api.getStatuses))
api.Router.Handle("get_statuses_by_ids", api.ApiWebSocketHandler(api.getStatusesByIds)) api.Router.Handle("get_statuses_by_ids", api.ApiWebSocketHandler(api.getStatusesByIds))
} }
func getStatuses(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) { func (api *API) getStatuses(req *model.WebSocketRequest) (map[string]interface{}, *model.AppError) {
statusMap := app.GetAllStatuses() statusMap := api.App.GetAllStatuses()
return model.StatusMapToInterfaceMap(statusMap), nil return model.StatusMapToInterfaceMap(statusMap), nil
} }