* Removing some other fake apps

* More FakeApp removed

* Removing entirely FakeApp

* Fixing some tests

* Fixing get Cluster id from get plugin status

* Fixing failing tests

* Fixing tests

* Fixing test initialization for web

* Fixing InitServer for server tests

* Fixing InitServer for server tests

* Reverting go.sum and go.mod

* Removing unneded HTMLTemplates function in App layer

* Moving back some functions to its old place to easy the review

* Moving back some functions to its old place to easy the review

* Using the last struct2interface version

* Generating store layers

* Fixing merge problems

* Addressing PR comments

* Small fix

* Fixing app tests build

* Fixing tests

* fixing tests

* Fix tests

* Fixing tests

* Fixing tests

* Fixing tests

* Moving license to server struct

* Adding some fixes to the test compilation

* Fixing cluster and some jobs initialization

* Fixing some license tests compilation problems

* Fixing recursive cache invalidation

* Regenerating app layers

* Fix test compilation

Co-authored-by: mattermod <mattermod@users.noreply.github.com>
Этот коммит содержится в:
Jesús Espino
2020-06-12 13:43:50 +02:00
коммит произвёл GitHub
родитель f3ac33e6dc
Коммит f5eab1271b
88 изменённых файлов: 973 добавлений и 1177 удалений

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

@@ -102,7 +102,7 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent
} }
th := &TestHelper{ th := &TestHelper{
App: s.FakeApp(), App: app.New(app.ServerConnector(s)),
Server: s, Server: s,
ConfigStore: memoryStore, ConfigStore: memoryStore,
IncludeCacheLayer: includeCache, IncludeCacheLayer: includeCache,
@@ -131,7 +131,7 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent
Init(th.Server, th.Server.AppOptions, th.App.Srv().Router) Init(th.Server, th.Server.AppOptions, th.App.Srv().Router)
InitLocal(th.Server, th.Server.AppOptions, th.App.Srv().LocalRouter) InitLocal(th.Server, th.Server.AppOptions, th.App.Srv().LocalRouter)
web.New(th.Server, th.Server.AppOptions, th.App.Srv().Router) web.New(th.Server, th.Server.AppOptions, th.App.Srv().Router)
wsapi.Init(th.App, th.App.Srv().WebSocketRouter) wsapi.Init(th.App.Srv())
th.App.DoAppMigrations() th.App.DoAppMigrations()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true })
@@ -146,9 +146,9 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent
}) })
if enterprise { if enterprise {
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
} else { } else {
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
} }
th.Client = th.CreateClient() th.Client = th.CreateClient()
@@ -170,6 +170,8 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent
th.tempWorkspace = tempWorkspace th.tempWorkspace = tempWorkspace
} }
th.App.InitServer()
return th return th
} }
@@ -265,7 +267,7 @@ func (me *TestHelper) TearDown() {
utils.DisableDebugLogForTest() utils.DisableDebugLogForTest()
if me.IncludeCacheLayer { if me.IncludeCacheLayer {
// Clean all the caches // Clean all the caches
me.App.InvalidateAllCaches() me.App.Srv().InvalidateAllCaches()
} }
me.ShutdownApp() me.ShutdownApp()

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

@@ -1546,7 +1546,7 @@ func updateChannelScheme(c *Context, w http.ResponseWriter, r *http.Request) {
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
auditRec.AddMeta("new_scheme_id", schemeID) auditRec.AddMeta("new_scheme_id", schemeID)
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("Api4.UpdateChannelScheme", "api.channel.update_channel_scheme.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.UpdateChannelScheme", "api.channel.update_channel_scheme.license.error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -1640,7 +1640,7 @@ func channelMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http.
} }
func channelMemberCountsByGroup(c *Context, w http.ResponseWriter, r *http.Request) { func channelMemberCountsByGroup(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("Api4.channelMemberCountsByGroup", "api.channel.channel_member_counts_by_group.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.channelMemberCountsByGroup", "api.channel.channel_member_counts_by_group.license.error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -1673,7 +1673,7 @@ func channelMemberCountsByGroup(c *Context, w http.ResponseWriter, r *http.Reque
} }
func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("Api4.GetChannelModerations", "api.channel.get_channel_moderations.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.GetChannelModerations", "api.channel.get_channel_moderations.license.error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -1710,7 +1710,7 @@ func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) {
} }
func patchChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { func patchChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("Api4.patchChannelModerations", "api.channel.patch_channel_moderations.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.patchChannelModerations", "api.channel.patch_channel_moderations.license.error", nil, "", http.StatusNotImplemented)
return return
} }

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

@@ -430,10 +430,10 @@ func TestCreateDirectChannelAsGuest(t *testing.T) {
enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
defer func() { defer func() {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
th.App.RemoveLicense() th.App.Srv().RemoveLicense()
}() }()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
id := model.NewId() id := model.NewId()
guest := &model.User{ guest := &model.User{
@@ -557,10 +557,10 @@ func TestCreateGroupChannelAsGuest(t *testing.T) {
enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
defer func() { defer func() {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
th.App.RemoveLicense() th.App.Srv().RemoveLicense()
}() }()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
id := model.NewId() id := model.NewId()
guest := &model.User{ guest := &model.User{
@@ -2373,7 +2373,7 @@ func TestAddChannelMember(t *testing.T) {
Client.Logout() Client.Logout()
th.MakeUserChannelAdmin(user, privateChannel) th.MakeUserChannelAdmin(user, privateChannel)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
Client.Login(user.Username, user.Password) Client.Login(user.Username, user.Password)
_, resp = Client.AddChannelMember(privateChannel.Id, user3.Id) _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id)
@@ -2622,7 +2622,7 @@ func TestRemoveChannelMember(t *testing.T) {
th.LoginBasic() th.LoginBasic()
th.UpdateUserToNonTeamAdmin(user1, team) th.UpdateUserToNonTeamAdmin(user1, team)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
// Check the appropriate permissions are enforced. // Check the appropriate permissions are enforced.
defaultRolePermissions := th.SaveDefaultRolePermissions() defaultRolePermissions := th.SaveDefaultRolePermissions()
@@ -2660,7 +2660,7 @@ func TestRemoveChannelMember(t *testing.T) {
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)
th.MakeUserChannelAdmin(user1, privateChannel) th.MakeUserChannelAdmin(user1, privateChannel)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
_, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id) _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id)
CheckNoError(t, resp) CheckNoError(t, resp)
@@ -2902,10 +2902,10 @@ func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) {
enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
defer func() { defer func() {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
th.App.RemoveLicense() th.App.Srv().RemoveLicense()
}() }()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
id := model.NewId() id := model.NewId()
guest := &model.User{ guest := &model.User{
@@ -3028,7 +3028,7 @@ func TestUpdateChannelScheme(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -3085,10 +3085,10 @@ func TestUpdateChannelScheme(t *testing.T) {
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)
// Test that a license is required. // Test that a license is required.
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id) _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id)
CheckNotImplementedStatus(t, resp) CheckNotImplementedStatus(t, resp)
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
// Test an invalid scheme scope. // Test an invalid scheme scope.
_, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, teamScheme.Id) _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, teamScheme.Id)
@@ -3251,14 +3251,14 @@ func TestGetChannelModerations(t *testing.T) {
require.Equal(t, "api.channel.get_channel_moderations.license.error", res.Error.Id) require.Equal(t, "api.channel.get_channel_moderations.license.error", res.Error.Id)
}) })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
t.Run("Errors as a non sysadmin", func(t *testing.T) { t.Run("Errors as a non sysadmin", func(t *testing.T) {
_, res := th.Client.GetChannelModerations(channel.Id, "") _, res := th.Client.GetChannelModerations(channel.Id, "")
require.Equal(t, "api.context.permissions.app_error", res.Error.Id) require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
}) })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
t.Run("Returns default moderations with default roles", func(t *testing.T) { t.Run("Returns default moderations with default roles", func(t *testing.T) {
moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "") moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "")
@@ -3420,14 +3420,14 @@ func TestPatchChannelModerations(t *testing.T) {
require.Equal(t, "api.channel.patch_channel_moderations.license.error", res.Error.Id) require.Equal(t, "api.channel.patch_channel_moderations.license.error", res.Error.Id)
}) })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
t.Run("Errors as a non sysadmin", func(t *testing.T) { t.Run("Errors as a non sysadmin", func(t *testing.T) {
_, res := th.Client.PatchChannelModerations(channel.Id, emptyPatch) _, res := th.Client.PatchChannelModerations(channel.Id, emptyPatch)
require.Equal(t, "api.context.permissions.app_error", res.Error.Id) require.Equal(t, "api.context.permissions.app_error", res.Error.Id)
}) })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
t.Run("Returns default moderations with empty patch", func(t *testing.T) { t.Run("Returns default moderations with empty patch", func(t *testing.T) {
moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch) moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch)
@@ -3592,7 +3592,7 @@ func TestGetChannelMemberCountsByGroup(t *testing.T) {
require.Equal(t, "api.channel.channel_member_counts_by_group.license.error", res.Error.Id) require.Equal(t, "api.channel.channel_member_counts_by_group.license.error", res.Error.Id)
}) })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
t.Run("Errors without read permission to the channel", func(t *testing.T) { t.Run("Errors without read permission to the channel", func(t *testing.T) {
_, res := th.Client.GetChannelMemberCountsByGroup(model.NewId(), false, "") _, res := th.Client.GetChannelMemberCountsByGroup(model.NewId(), false, "")

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

@@ -9,6 +9,7 @@ import (
"testing" "testing"
"github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/store/storetest/mocks"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@@ -125,6 +126,12 @@ func TestCORSRequestHandling(t *testing.T) {
*cfg.ServiceSettings.CorsAllowCredentials = testcase.CorsAllowCredentials *cfg.ServiceSettings.CorsAllowCredentials = testcase.CorsAllowCredentials
}) })
defer th.TearDown() defer th.TearDown()
systemStore := mocks.SystemStore{}
systemStore.On("Get").Return(make(model.StringMap), nil)
licenseStore := mocks.LicenseStore{}
licenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil)
th.App.Srv().Store.(*mocks.Store).On("System").Return(&systemStore)
th.App.Srv().Store.(*mocks.Store).On("License").Return(&licenseStore)
port := th.App.Srv().ListenAddr.Port port := th.App.Srv().ListenAddr.Port
host := fmt.Sprintf("http://localhost:%v", port) host := fmt.Sprintf("http://localhost:%v", port)

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

@@ -79,7 +79,7 @@ func getGroup(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -119,7 +119,7 @@ func patchGroup(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec := c.MakeAuditRecord("patchGroup", audit.Fail) auditRec := c.MakeAuditRecord("patchGroup", audit.Fail)
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.patchGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.patchGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -219,7 +219,7 @@ func linkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.createGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.createGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -275,7 +275,7 @@ func getGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) {
} }
syncableType := c.Params.SyncableType syncableType := c.Params.SyncableType
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -312,7 +312,7 @@ func getGroupSyncables(c *Context, w http.ResponseWriter, r *http.Request) {
} }
syncableType := c.Params.SyncableType syncableType := c.Params.SyncableType
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroupSyncables", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroupSyncables", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -374,7 +374,7 @@ func patchGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.patchGroupSyncable", "api.ldap_groups.license_error", nil, "", c.Err = model.NewAppError("Api4.patchGroupSyncable", "api.ldap_groups.license_error", nil, "",
http.StatusNotImplemented) http.StatusNotImplemented)
return return
@@ -440,7 +440,7 @@ func unlinkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec.AddMeta("syncable_id", syncableID) auditRec.AddMeta("syncable_id", syncableID)
auditRec.AddMeta("syncable_type", syncableType) auditRec.AddMeta("syncable_type", syncableType)
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.unlinkGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.unlinkGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -499,7 +499,7 @@ func getGroupMembers(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroupMembers", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroupMembers", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -541,7 +541,7 @@ func getGroupsByUserId(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroupsByUserId", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroupsByUserId", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -567,7 +567,7 @@ func getGroupsByChannel(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroupsByChannel", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroupsByChannel", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -625,7 +625,7 @@ func getGroupsByTeam(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroupsByTeam", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroupsByTeam", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -667,7 +667,7 @@ func getGroupsAssociatedToChannelsByTeam(c *Context, w http.ResponseWriter, r *h
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroupsAssociatedToChannelsByTeam", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroupsAssociatedToChannelsByTeam", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -702,7 +702,7 @@ func getGroupsAssociatedToChannelsByTeam(c *Context, w http.ResponseWriter, r *h
} }
func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { func getGroups(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getGroups", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getGroups", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }

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

@@ -34,7 +34,7 @@ func TestGetGroup(t *testing.T) {
_, response = th.SystemAdminClient.GetGroup(g.Id, "") _, response = th.SystemAdminClient.GetGroup(g.Id, "")
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
group, response := th.SystemAdminClient.GetGroup(g.Id, "") group, response := th.SystemAdminClient.GetGroup(g.Id, "")
CheckNoError(t, response) CheckNoError(t, response)
@@ -91,7 +91,7 @@ func TestPatchGroup(t *testing.T) {
_, response = th.SystemAdminClient.PatchGroup(g.Id, gp) _, response = th.SystemAdminClient.PatchGroup(g.Id, gp)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
group2, response := th.SystemAdminClient.PatchGroup(g.Id, gp) group2, response := th.SystemAdminClient.PatchGroup(g.Id, gp)
CheckOKStatus(t, response) CheckOKStatus(t, response)
@@ -149,7 +149,7 @@ func TestLinkGroupTeam(t *testing.T) {
_, response = th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) _, response = th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response = th.Client.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) _, response = th.Client.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch)
assert.NotNil(t, response.Error) assert.NotNil(t, response.Error)
@@ -187,7 +187,7 @@ func TestLinkGroupChannel(t *testing.T) {
_, response = th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) _, response = th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
groupTeam, response := th.Client.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) groupTeam, response := th.Client.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch)
assert.Equal(t, http.StatusCreated, response.StatusCode) assert.Equal(t, http.StatusCreated, response.StatusCode)
@@ -220,12 +220,12 @@ func TestUnlinkGroupTeam(t *testing.T) {
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
} }
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) _, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch)
assert.Equal(t, http.StatusCreated, response.StatusCode) assert.Equal(t, http.StatusCreated, response.StatusCode)
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam) response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
@@ -233,7 +233,7 @@ func TestUnlinkGroupTeam(t *testing.T) {
response = th.SystemAdminClient.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam) response = th.SystemAdminClient.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam) response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam)
assert.NotNil(t, response.Error) assert.NotNil(t, response.Error)
@@ -267,12 +267,12 @@ func TestUnlinkGroupChannel(t *testing.T) {
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
} }
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) _, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch)
assert.Equal(t, http.StatusCreated, response.StatusCode) assert.Equal(t, http.StatusCreated, response.StatusCode)
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel) response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
@@ -280,7 +280,7 @@ func TestUnlinkGroupChannel(t *testing.T) {
response = th.SystemAdminClient.UnlinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel) response = th.SystemAdminClient.UnlinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response = th.SystemAdminClient.UpdateChannelRoles(th.BasicChannel.Id, th.BasicUser.Id, "") _, response = th.SystemAdminClient.UpdateChannelRoles(th.BasicChannel.Id, th.BasicUser.Id, "")
require.Nil(t, response.Error) require.Nil(t, response.Error)
@@ -319,7 +319,7 @@ func TestGetGroupTeam(t *testing.T) {
_, response = th.SystemAdminClient.GetGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, "") _, response = th.SystemAdminClient.GetGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, "")
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
patch := &model.GroupSyncablePatch{ patch := &model.GroupSyncablePatch{
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
@@ -373,7 +373,7 @@ func TestGetGroupChannel(t *testing.T) {
_, response = th.SystemAdminClient.GetGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, "") _, response = th.SystemAdminClient.GetGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, "")
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
patch := &model.GroupSyncablePatch{ patch := &model.GroupSyncablePatch{
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
@@ -421,7 +421,7 @@ func TestGetGroupTeams(t *testing.T) {
}) })
assert.Nil(t, err) assert.Nil(t, err)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
patch := &model.GroupSyncablePatch{ patch := &model.GroupSyncablePatch{
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
@@ -433,7 +433,7 @@ func TestGetGroupTeams(t *testing.T) {
assert.Equal(t, http.StatusCreated, response.StatusCode) assert.Equal(t, http.StatusCreated, response.StatusCode)
} }
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, response := th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "") _, response := th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "")
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
@@ -441,7 +441,7 @@ func TestGetGroupTeams(t *testing.T) {
_, response = th.SystemAdminClient.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "") _, response = th.SystemAdminClient.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "")
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response = th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "") _, response = th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "")
assert.Equal(t, http.StatusForbidden, response.StatusCode) assert.Equal(t, http.StatusForbidden, response.StatusCode)
@@ -470,7 +470,7 @@ func TestGetGroupChannels(t *testing.T) {
}) })
assert.Nil(t, err) assert.Nil(t, err)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
patch := &model.GroupSyncablePatch{ patch := &model.GroupSyncablePatch{
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
@@ -482,7 +482,7 @@ func TestGetGroupChannels(t *testing.T) {
assert.Equal(t, http.StatusCreated, response.StatusCode) assert.Equal(t, http.StatusCreated, response.StatusCode)
} }
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, response := th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "") _, response := th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "")
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
@@ -490,7 +490,7 @@ func TestGetGroupChannels(t *testing.T) {
_, response = th.SystemAdminClient.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "") _, response = th.SystemAdminClient.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "")
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response = th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "") _, response = th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "")
assert.Equal(t, http.StatusForbidden, response.StatusCode) assert.Equal(t, http.StatusForbidden, response.StatusCode)
@@ -523,7 +523,7 @@ func TestPatchGroupTeam(t *testing.T) {
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
} }
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
groupSyncable, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) groupSyncable, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch)
assert.Equal(t, http.StatusCreated, response.StatusCode) assert.Equal(t, http.StatusCreated, response.StatusCode)
@@ -533,12 +533,12 @@ func TestPatchGroupTeam(t *testing.T) {
_, response = th.Client.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) _, response = th.Client.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch)
assert.Equal(t, http.StatusForbidden, response.StatusCode) assert.Equal(t, http.StatusForbidden, response.StatusCode)
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) _, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
patch.AutoAdd = model.NewBool(false) patch.AutoAdd = model.NewBool(false)
groupSyncable, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) groupSyncable, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch)
@@ -588,7 +588,7 @@ func TestPatchGroupChannel(t *testing.T) {
AutoAdd: model.NewBool(true), AutoAdd: model.NewBool(true),
} }
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
groupSyncable, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) groupSyncable, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch)
assert.Equal(t, http.StatusCreated, response.StatusCode) assert.Equal(t, http.StatusCreated, response.StatusCode)
@@ -607,12 +607,12 @@ func TestPatchGroupChannel(t *testing.T) {
_, err = th.App.PatchRole(role, &model.RolePatch{Permissions: &originalPermissions}) _, err = th.App.PatchRole(role, &model.RolePatch{Permissions: &originalPermissions})
require.Nil(t, err) require.Nil(t, err)
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) _, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
patch.AutoAdd = model.NewBool(false) patch.AutoAdd = model.NewBool(false)
groupSyncable, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) groupSyncable, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch)
@@ -678,14 +678,14 @@ func TestGetGroupsByChannel(t *testing.T) {
CheckBadRequestStatus(t, response) CheckBadRequestStatus(t, response)
}) })
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, _, response := client.GetGroupsByChannel(th.BasicChannel.Id, opts) _, _, response := client.GetGroupsByChannel(th.BasicChannel.Id, opts)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
}) })
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)
@@ -751,12 +751,12 @@ func TestGetGroupsAssociatedToChannelsByTeam(t *testing.T) {
_, response := th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam("asdfasdf", opts) _, response := th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam("asdfasdf", opts)
CheckBadRequestStatus(t, response) CheckBadRequestStatus(t, response)
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, response = th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam(th.BasicTeam.Id, opts) _, response = th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam(th.BasicTeam.Id, opts)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
groups, response := th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam(th.BasicTeam.Id, opts) groups, response := th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam(th.BasicTeam.Id, opts)
assert.Nil(t, response.Error) assert.Nil(t, response.Error)
@@ -827,14 +827,14 @@ func TestGetGroupsByTeam(t *testing.T) {
CheckBadRequestStatus(t, response) CheckBadRequestStatus(t, response)
}) })
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, _, response := client.GetGroupsByTeam(th.BasicTeam.Id, opts) _, _, response := client.GetGroupsByTeam(th.BasicTeam.Id, opts)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
}) })
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
groups, _, response := client.GetGroupsByTeam(th.BasicTeam.Id, opts) groups, _, response := client.GetGroupsByTeam(th.BasicTeam.Id, opts)
@@ -887,12 +887,12 @@ func TestGetGroups(t *testing.T) {
}, },
} }
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, response := th.SystemAdminClient.GetGroups(opts) _, response := th.SystemAdminClient.GetGroups(opts)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response = th.SystemAdminClient.GetGroups(opts) _, response = th.SystemAdminClient.GetGroups(opts)
require.Nil(t, response.Error) require.Nil(t, response.Error)
@@ -995,11 +995,11 @@ func TestGetGroupsByUserId(t *testing.T) {
_, err = th.App.UpsertGroupMember(group2.Id, user1.Id) _, err = th.App.UpsertGroupMember(group2.Id, user1.Id)
assert.Nil(t, err) assert.Nil(t, err)
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, response := th.SystemAdminClient.GetGroupsByUserId(user1.Id) _, response := th.SystemAdminClient.GetGroupsByUserId(user1.Id)
CheckNotImplementedStatus(t, response) CheckNotImplementedStatus(t, response)
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
_, response = th.SystemAdminClient.GetGroupsByUserId("") _, response = th.SystemAdminClient.GetGroupsByUserId("")
CheckBadRequestStatus(t, response) CheckBadRequestStatus(t, response)
@@ -1028,7 +1028,7 @@ func TestGetGroupsGroupConstrainedParentTeam(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
var groups []*model.Group var groups []*model.Group
for i := 0; i < 4; i++ { for i := 0; i < 4; i++ {

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

@@ -34,7 +34,7 @@ func (api *API) InitLdap() {
} }
func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) { func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.License() == nil || !*c.App.License().Features.LDAP { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAP {
c.Err = model.NewAppError("Api4.syncLdap", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.syncLdap", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -54,7 +54,7 @@ func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) {
} }
func testLdap(c *Context, w http.ResponseWriter, r *http.Request) { func testLdap(c *Context, w http.ResponseWriter, r *http.Request) {
if c.App.License() == nil || !*c.App.License().Features.LDAP { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAP {
c.Err = model.NewAppError("Api4.testLdap", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.testLdap", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -78,7 +78,7 @@ func getLdapGroups(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.getLdapGroups", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.getLdapGroups", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -139,7 +139,7 @@ func linkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) {
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
auditRec.AddMeta("remote_id", c.Params.RemoteId) auditRec.AddMeta("remote_id", c.Params.RemoteId)
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.linkLdapGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.linkLdapGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -236,7 +236,7 @@ func unlinkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups {
c.Err = model.NewAppError("Api4.unlinkLdapGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.unlinkLdapGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented)
return return
} }

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

@@ -20,7 +20,7 @@ func TestTestLdap(t *testing.T) {
require.NotNil(t, resp.Error) require.NotNil(t, resp.Error)
require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id) require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id)
th.App.SetLicense(model.NewTestLicense("ldap_groups")) th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups"))
_, resp = th.Client.TestLdap() _, resp = th.Client.TestLdap()
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)
@@ -42,7 +42,7 @@ func TestSyncLdap(t *testing.T) {
require.NotNil(t, resp.Error) require.NotNil(t, resp.Error)
require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id) require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id)
th.App.SetLicense(model.NewTestLicense("ldap_groups")) th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups"))
_, resp = th.SystemAdminClient.SyncLdap() _, resp = th.SystemAdminClient.SyncLdap()
CheckNoError(t, resp) CheckNoError(t, resp)

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

@@ -37,9 +37,9 @@ func getClientLicense(c *Context, w http.ResponseWriter, r *http.Request) {
var clientLicense map[string]string var clientLicense map[string]string
if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) {
clientLicense = c.App.ClientLicense() clientLicense = c.App.Srv().ClientLicense()
} else { } else {
clientLicense = c.App.GetSanitizedClientLicense() clientLicense = c.App.Srv().GetSanitizedClientLicense()
} }
w.Write([]byte(model.MapToJson(clientLicense))) w.Write([]byte(model.MapToJson(clientLicense)))
@@ -92,7 +92,7 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) {
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
io.Copy(buf, file) io.Copy(buf, file)
license, appErr := c.App.SaveLicense(buf.Bytes()) license, appErr := c.App.Srv().SaveLicense(buf.Bytes())
if appErr != nil { if appErr != nil {
if appErr.Id == model.EXPIRED_LICENSE_ERROR { if appErr.Id == model.EXPIRED_LICENSE_ERROR {
c.LogAudit("failed - expired or non-started license") c.LogAudit("failed - expired or non-started license")
@@ -131,7 +131,7 @@ func removeLicense(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if err := c.App.RemoveLicense(); err != nil { if err := c.App.Srv().RemoveLicense(); err != nil {
c.Err = err c.Err = err
return return
} }
@@ -187,7 +187,7 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) {
Users: usersNumber.Users, Users: usersNumber.Users,
} }
if err := c.App.RequestTrialLicense(trialLicenseRequest); err != nil { if err := c.App.Srv().RequestTrialLicense(trialLicenseRequest); err != nil {
c.Err = err c.Err = err
return return
} }

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

@@ -54,7 +54,7 @@ func localAddLicense(c *Context, w http.ResponseWriter, r *http.Request) {
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
io.Copy(buf, file) io.Copy(buf, file)
license, appErr := c.App.SaveLicense(buf.Bytes()) license, appErr := c.App.Srv().SaveLicense(buf.Bytes())
if appErr != nil { if appErr != nil {
if appErr.Id == model.EXPIRED_LICENSE_ERROR { if appErr.Id == model.EXPIRED_LICENSE_ERROR {
c.LogAudit("failed - expired or non-started license") c.LogAudit("failed - expired or non-started license")
@@ -83,7 +83,7 @@ func localRemoveLicense(c *Context, w http.ResponseWriter, r *http.Request) {
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
c.LogAudit("attempt") c.LogAudit("attempt")
if err := c.App.RemoveLicense(); err != nil { if err := c.App.Srv().RemoveLicense(); err != nil {
c.Err = err c.Err = err
return return
} }

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

@@ -602,7 +602,7 @@ func TestGetMarketplacePlugins(t *testing.T) {
l := model.NewTestLicense() l := model.NewTestLicense()
// model.NewTestLicense generates a E20 license // model.NewTestLicense generates a E20 license
*l.Features.EnterprisePlugins = false *l.Features.EnterprisePlugins = false
th.App.SetLicense(l) th.App.Srv().SetLicense(l)
plugins, resp := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) plugins, resp := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{})
CheckNoError(t, resp) CheckNoError(t, resp)
@@ -628,7 +628,7 @@ func TestGetMarketplacePlugins(t *testing.T) {
*cfg.PluginSettings.MarketplaceUrl = testServer.URL *cfg.PluginSettings.MarketplaceUrl = testServer.URL
}) })
th.App.SetLicense(model.NewTestLicense("enterprise_plugins")) th.App.Srv().SetLicense(model.NewTestLicense("enterprise_plugins"))
plugins, resp := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) plugins, resp := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{})
CheckNoError(t, resp) CheckNoError(t, resp)

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

@@ -682,7 +682,7 @@ func saveIsPinnedPost(c *Context, w http.ResponseWriter, r *http.Request, isPinn
return return
} }
if c.App.License() != nil && if c.App.Srv().License() != nil &&
*c.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && *c.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly &&
channel.Name == model.DEFAULT_CHANNEL && channel.Name == model.DEFAULT_CHANNEL &&
!c.App.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { !c.App.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) {

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

@@ -444,7 +444,7 @@ func TestCreatePostPublic(t *testing.T) {
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)
th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_PUBLIC_ROLE_ID, false) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_PUBLIC_ROLE_ID, false)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
Client.Login(user.Email, user.Password) Client.Login(user.Email, user.Password)
@@ -458,7 +458,7 @@ func TestCreatePostPublic(t *testing.T) {
th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false)
th.App.JoinUserToTeam(th.BasicTeam, ruser, "") th.App.JoinUserToTeam(th.BasicTeam, ruser, "")
th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_PUBLIC_ROLE_ID) th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_PUBLIC_ROLE_ID)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
Client.Login(user.Email, user.Password) Client.Login(user.Email, user.Password)
@@ -491,7 +491,7 @@ func TestCreatePostAll(t *testing.T) {
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)
th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_ROLE_ID, false) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_ROLE_ID, false)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
Client.Login(user.Email, user.Password) Client.Login(user.Email, user.Password)
@@ -509,7 +509,7 @@ func TestCreatePostAll(t *testing.T) {
th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false)
th.App.JoinUserToTeam(th.BasicTeam, ruser, "") th.App.JoinUserToTeam(th.BasicTeam, ruser, "")
th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_ROLE_ID) th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_ROLE_ID)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
Client.Login(user.Email, user.Password) Client.Login(user.Email, user.Password)
@@ -667,7 +667,7 @@ func TestUpdatePost(t *testing.T) {
Client := th.Client Client := th.Client
channel := th.BasicChannel channel := th.BasicChannel
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
fileIds := make([]string, 3) fileIds := make([]string, 3)
data, err := testutils.ReadTestFile("test.png") data, err := testutils.ReadTestFile("test.png")
@@ -850,7 +850,7 @@ func TestPatchPost(t *testing.T) {
Client := th.Client Client := th.Client
channel := th.BasicChannel channel := th.BasicChannel
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
fileIds := make([]string, 3) fileIds := make([]string, 3)
data, err := testutils.ReadTestFile("test.png") data, err := testutils.ReadTestFile("test.png")
@@ -976,10 +976,10 @@ func TestPinPost(t *testing.T) {
t.Run("unable-to-pin-post-in-read-only-town-square", func(t *testing.T) { t.Run("unable-to-pin-post-in-read-only-town-square", func(t *testing.T) {
townSquareIsReadOnly := *th.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly townSquareIsReadOnly := *th.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })
defer th.App.RemoveLicense() defer th.App.Srv().RemoveLicense()
defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = townSquareIsReadOnly }) defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = townSquareIsReadOnly })
channel, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true) channel, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true)

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

@@ -161,7 +161,7 @@ func TestSaveReaction(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
post := th.CreatePostWithClient(th.Client, channel) post := th.CreatePostWithClient(th.Client, channel)
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })
reaction := &model.Reaction{ reaction := &model.Reaction{
@@ -177,7 +177,7 @@ func TestSaveReaction(t *testing.T) {
require.Nil(t, err) require.Nil(t, err)
require.Equal(t, 0, len(reactions), "should have not created a reaction") require.Equal(t, 0, len(reactions), "should have not created a reaction")
th.App.RemoveLicense() th.App.Srv().RemoveLicense()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = false })
}) })
@@ -486,7 +486,7 @@ func TestDeleteReaction(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
post := th.CreatePostWithClient(th.Client, channel) post := th.CreatePostWithClient(th.Client, channel)
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
reaction := &model.Reaction{ reaction := &model.Reaction{
UserId: userId, UserId: userId,
@@ -510,7 +510,7 @@ func TestDeleteReaction(t *testing.T) {
require.Nil(t, err) require.Nil(t, err)
require.Equal(t, 1, len(reactions), "should have not deleted a reaction") require.Equal(t, 1, len(reactions), "should have not deleted a reaction")
th.App.RemoveLicense() th.App.Srv().RemoveLicense()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = false })
}) })

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

@@ -101,7 +101,7 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) {
} }
auditRec.AddMeta("role", oldRole) auditRec.AddMeta("role", oldRole)
if c.App.License() == nil && patch.Permissions != nil { if c.App.Srv().License() == nil && patch.Permissions != nil {
if oldRole.Name == "system_guest" || oldRole.Name == "team_guest" || oldRole.Name == "channel_guest" { if oldRole.Name == "system_guest" || oldRole.Name == "team_guest" || oldRole.Name == "channel_guest" {
c.Err = model.NewAppError("Api4.PatchRoles", "api.roles.patch_roles.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.PatchRoles", "api.roles.patch_roles.license.error", nil, "", http.StatusNotImplemented)
return return
@@ -134,7 +134,7 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) {
} }
} }
if c.App.License() != nil && (oldRole.Name == "system_guest" || oldRole.Name == "team_guest" || oldRole.Name == "channel_guest") && !*c.App.License().Features.GuestAccountsPermissions { if c.App.Srv().License() != nil && (oldRole.Name == "system_guest" || oldRole.Name == "team_guest" || oldRole.Name == "channel_guest") && !*c.App.Srv().License().Features.GuestAccountsPermissions {
c.Err = model.NewAppError("Api4.PatchRoles", "api.roles.patch_roles.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.PatchRoles", "api.roles.patch_roles.license.error", nil, "", http.StatusNotImplemented)
return return
} }

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

@@ -196,7 +196,7 @@ func TestPatchRole(t *testing.T) {
// Add a license. // Add a license.
license := model.NewTestLicense() license := model.NewTestLicense()
license.Features.GuestAccountsPermissions = model.NewBool(false) license.Features.GuestAccountsPermissions = model.NewBool(false)
th.App.SetLicense(license) th.App.Srv().SetLicense(license)
// Try again, should succeed // Try again, should succeed
received, resp = th.SystemAdminClient.PatchRole(role.Id, patch) received, resp = th.SystemAdminClient.PatchRole(role.Id, patch)
@@ -212,7 +212,7 @@ func TestPatchRole(t *testing.T) {
t.Run("Check guest permissions editing without E20 license", func(t *testing.T) { t.Run("Check guest permissions editing without E20 license", func(t *testing.T) {
license := model.NewTestLicense() license := model.NewTestLicense()
license.Features.GuestAccountsPermissions = model.NewBool(false) license.Features.GuestAccountsPermissions = model.NewBool(false)
th.App.SetLicense(license) th.App.Srv().SetLicense(license)
guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest") guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest")
require.Nil(t, err) require.Nil(t, err)
@@ -223,7 +223,7 @@ func TestPatchRole(t *testing.T) {
t.Run("Check guest permissions editing with E20 license", func(t *testing.T) { t.Run("Check guest permissions editing with E20 license", func(t *testing.T) {
license := model.NewTestLicense() license := model.NewTestLicense()
license.Features.GuestAccountsPermissions = model.NewBool(true) license.Features.GuestAccountsPermissions = model.NewBool(true)
th.App.SetLicense(license) th.App.Srv().SetLicense(license)
guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest") guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest")
require.Nil(t, err) require.Nil(t, err)
_, resp = th.SystemAdminClient.PatchRole(guestRole.Id, patch) _, resp = th.SystemAdminClient.PatchRole(guestRole.Id, patch)

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

@@ -31,7 +31,7 @@ func createScheme(c *Context, w http.ResponseWriter, r *http.Request) {
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
auditRec.AddMeta("scheme", scheme) auditRec.AddMeta("scheme", scheme)
if c.App.License() == nil || !*c.App.License().Features.CustomPermissionsSchemes { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.CustomPermissionsSchemes {
c.Err = model.NewAppError("Api4.CreateScheme", "api.scheme.create_scheme.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.CreateScheme", "api.scheme.create_scheme.license.error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -172,7 +172,7 @@ func patchScheme(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec := c.MakeAuditRecord("patchScheme", audit.Fail) auditRec := c.MakeAuditRecord("patchScheme", audit.Fail)
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
if c.App.License() == nil || !*c.App.License().Features.CustomPermissionsSchemes { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.CustomPermissionsSchemes {
c.Err = model.NewAppError("Api4.PatchScheme", "api.scheme.patch_scheme.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.PatchScheme", "api.scheme.patch_scheme.license.error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -211,7 +211,7 @@ func deleteScheme(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec := c.MakeAuditRecord("deleteScheme", audit.Fail) auditRec := c.MakeAuditRecord("deleteScheme", audit.Fail)
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
if c.App.License() == nil || !*c.App.License().Features.CustomPermissionsSchemes { if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.CustomPermissionsSchemes {
c.Err = model.NewAppError("Api4.DeleteScheme", "api.scheme.delete_scheme.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.DeleteScheme", "api.scheme.delete_scheme.license.error", nil, "", http.StatusNotImplemented)
return return
} }

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

@@ -17,7 +17,7 @@ func TestCreateScheme(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -135,7 +135,7 @@ func TestCreateScheme(t *testing.T) {
CheckForbiddenStatus(t, r5) CheckForbiddenStatus(t, r5)
// Try and create a scheme without a license. // Try and create a scheme without a license.
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
scheme6 := &model.Scheme{ scheme6 := &model.Scheme{
DisplayName: model.NewId(), DisplayName: model.NewId(),
Name: model.NewId(), Name: model.NewId(),
@@ -148,7 +148,7 @@ func TestCreateScheme(t *testing.T) {
th.App.SetPhase2PermissionsMigrationStatus(false) th.App.SetPhase2PermissionsMigrationStatus(false)
th.LoginSystemAdmin() th.LoginSystemAdmin()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
scheme7 := &model.Scheme{ scheme7 := &model.Scheme{
DisplayName: model.NewId(), DisplayName: model.NewId(),
@@ -164,7 +164,7 @@ func TestGetScheme(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
// Basic test of creating a team scheme. // Basic test of creating a team scheme.
scheme1 := &model.Scheme{ scheme1 := &model.Scheme{
@@ -209,7 +209,7 @@ func TestGetScheme(t *testing.T) {
CheckUnauthorizedStatus(t, r5) CheckUnauthorizedStatus(t, r5)
th.SystemAdminClient.Login(th.SystemAdminUser.Username, th.SystemAdminUser.Password) th.SystemAdminClient.Login(th.SystemAdminUser.Username, th.SystemAdminUser.Password)
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, r6 := th.SystemAdminClient.GetScheme(s1.Id) _, r6 := th.SystemAdminClient.GetScheme(s1.Id)
CheckNoError(t, r6) CheckNoError(t, r6)
@@ -226,7 +226,7 @@ func TestGetSchemes(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
scheme1 := &model.Scheme{ scheme1 := &model.Scheme{
DisplayName: model.NewId(), DisplayName: model.NewId(),
@@ -289,7 +289,7 @@ func TestGetTeamsForScheme(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -381,7 +381,7 @@ func TestGetChannelsForScheme(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -475,7 +475,7 @@ func TestPatchScheme(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -565,14 +565,14 @@ func TestPatchScheme(t *testing.T) {
CheckForbiddenStatus(t, r10) CheckForbiddenStatus(t, r10)
// Test without license. // Test without license.
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, r11 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch) _, r11 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
CheckNotImplementedStatus(t, r11) CheckNotImplementedStatus(t, r11)
th.App.SetPhase2PermissionsMigrationStatus(false) th.App.SetPhase2PermissionsMigrationStatus(false)
th.LoginSystemAdmin() th.LoginSystemAdmin()
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
_, r12 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch) _, r12 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
CheckNotImplementedStatus(t, r12) CheckNotImplementedStatus(t, r12)
@@ -583,7 +583,7 @@ func TestDeleteScheme(t *testing.T) {
defer th.TearDown() defer th.TearDown()
t.Run("ValidTeamScheme", func(t *testing.T) { t.Run("ValidTeamScheme", func(t *testing.T) {
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -661,7 +661,7 @@ func TestDeleteScheme(t *testing.T) {
}) })
t.Run("ValidChannelScheme", func(t *testing.T) { t.Run("ValidChannelScheme", func(t *testing.T) {
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -721,7 +721,7 @@ func TestDeleteScheme(t *testing.T) {
}) })
t.Run("FailureCases", func(t *testing.T) { t.Run("FailureCases", func(t *testing.T) {
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -748,13 +748,13 @@ func TestDeleteScheme(t *testing.T) {
CheckForbiddenStatus(t, r4) CheckForbiddenStatus(t, r4)
// Test without license. // Test without license.
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, r5 := th.SystemAdminClient.DeleteScheme(s1.Id) _, r5 := th.SystemAdminClient.DeleteScheme(s1.Id)
CheckNotImplementedStatus(t, r5) CheckNotImplementedStatus(t, r5)
th.App.SetPhase2PermissionsMigrationStatus(false) th.App.SetPhase2PermissionsMigrationStatus(false)
th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
_, r6 := th.SystemAdminClient.DeleteScheme(s1.Id) _, r6 := th.SystemAdminClient.DeleteScheme(s1.Id)
CheckNotImplementedStatus(t, r6) CheckNotImplementedStatus(t, r6)

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

@@ -108,7 +108,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) {
filestoreStatusKey := "filestore_status" filestoreStatusKey := "filestore_status"
s[filestoreStatusKey] = model.STATUS_OK s[filestoreStatusKey] = model.STATUS_OK
license := c.App.License() license := c.App.Srv().License()
backend, appErr := filesstore.NewFileBackend(&c.App.Config().FileSettings, license != nil && *license.Features.Compliance) backend, appErr := filesstore.NewFileBackend(&c.App.Config().FileSettings, license != nil && *license.Features.Compliance)
if appErr == nil { if appErr == nil {
appErr = backend.TestConnection() appErr = backend.TestConnection()
@@ -240,7 +240,7 @@ func invalidateCaches(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
err := c.App.InvalidateAllCaches() err := c.App.Srv().InvalidateAllCaches()
if err != nil { if err != nil {
c.Err = err c.Err = err
return return
@@ -379,7 +379,7 @@ func testS3(c *Context, w http.ResponseWriter, r *http.Request) {
cfg.FileSettings.AmazonS3SecretAccessKey = c.App.Config().FileSettings.AmazonS3SecretAccessKey cfg.FileSettings.AmazonS3SecretAccessKey = c.App.Config().FileSettings.AmazonS3SecretAccessKey
} }
license := c.App.License() license := c.App.Srv().License()
backend, appErr := filesstore.NewFileBackend(&cfg.FileSettings, license != nil && *license.Features.Compliance) backend, appErr := filesstore.NewFileBackend(&cfg.FileSettings, license != nil && *license.Features.Compliance)
if appErr == nil { if appErr == nil {
appErr = backend.TestConnection() appErr = backend.TestConnection()

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

@@ -1220,7 +1220,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) {
func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) { func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) {
graceful := r.URL.Query().Get("graceful") != "" graceful := r.URL.Query().Get("graceful") != ""
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("Api4.InviteGuestsToChannels", "api.team.invate_guests_to_channels.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.InviteGuestsToChannels", "api.team.invate_guests_to_channels.license.error", nil, "", http.StatusNotImplemented)
return return
} }
@@ -1455,7 +1455,7 @@ func updateTeamScheme(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec := c.MakeAuditRecord("updateTeamScheme", audit.Fail) auditRec := c.MakeAuditRecord("updateTeamScheme", audit.Fail)
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("Api4.UpdateTeamScheme", "api.team.update_team_scheme.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.UpdateTeamScheme", "api.team.update_team_scheme.license.error", nil, "", http.StatusNotImplemented)
return return
} }

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

@@ -1647,8 +1647,8 @@ func TestAddTeamMember(t *testing.T) {
team := th.BasicTeam team := th.BasicTeam
otherUser := th.CreateUser() otherUser := th.CreateUser()
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
defer th.App.SetLicense(nil) defer th.App.Srv().SetLicense(nil)
enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
defer func() { defer func() {
@@ -1731,7 +1731,7 @@ func TestAddTeamMember(t *testing.T) {
// Update user to team admin // Update user to team admin
th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam) th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
th.LoginBasic() th.LoginBasic()
// Should work as a team admin. // Should work as a team admin.
@@ -1745,7 +1745,7 @@ func TestAddTeamMember(t *testing.T) {
th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID)
th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
th.LoginBasic() th.LoginBasic()
// Should work as a regular user. // Should work as a regular user.
@@ -1800,8 +1800,8 @@ func TestAddTeamMember(t *testing.T) {
th.App.DeleteToken(token) th.App.DeleteToken(token)
// by invite_id // by invite_id
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
defer th.App.SetLicense(nil) defer th.App.Srv().SetLicense(nil)
_, resp = Client.Login(guest.Email, guest.Password) _, resp = Client.Login(guest.Email, guest.Password)
CheckNoError(t, resp) CheckNoError(t, resp)
@@ -2094,7 +2094,7 @@ func TestAddTeamMembers(t *testing.T) {
// Update user to team admin // Update user to team admin
th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam) th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
th.LoginBasic() th.LoginBasic()
// Should work as a team admin. // Should work as a team admin.
@@ -2108,7 +2108,7 @@ func TestAddTeamMembers(t *testing.T) {
th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID)
th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam)
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
th.LoginBasic() th.LoginBasic()
// Should work as a regular user. // Should work as a regular user.
@@ -2755,7 +2755,7 @@ func TestInviteGuestsToTeam(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { cfg.GuestAccountsSettings.Enable = &enableGuestAccounts }) th.App.UpdateConfig(func(cfg *model.Config) { cfg.GuestAccountsSettings.Enable = &enableGuestAccounts })
}() }()
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = false })
_, resp := th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message") _, resp := th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message")
@@ -2768,13 +2768,13 @@ func TestInviteGuestsToTeam(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableEmailInvitations = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableEmailInvitations = true })
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, resp = th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message") _, resp = th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message")
require.NotNil(t, resp.Error, "Should be disabled") require.NotNil(t, resp.Error, "Should be disabled")
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
defer th.App.SetLicense(nil) defer th.App.Srv().SetLicense(nil)
okMsg, resp := th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message") okMsg, resp := th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message")
CheckNoError(t, resp) CheckNoError(t, resp)
@@ -2973,7 +2973,7 @@ func TestUpdateTeamScheme(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
@@ -3025,10 +3025,10 @@ func TestUpdateTeamScheme(t *testing.T) {
CheckForbiddenStatus(t, resp) CheckForbiddenStatus(t, resp)
// Test that a license is required. // Test that a license is required.
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
_, resp = th.SystemAdminClient.UpdateTeamScheme(team.Id, teamScheme.Id) _, resp = th.SystemAdminClient.UpdateTeamScheme(team.Id, teamScheme.Id)
CheckNotImplementedStatus(t, resp) CheckNotImplementedStatus(t, resp)
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
// Test an invalid scheme scope. // Test an invalid scheme scope.
_, resp = th.SystemAdminClient.UpdateTeamScheme(team.Id, channelScheme.Id) _, resp = th.SystemAdminClient.UpdateTeamScheme(team.Id, channelScheme.Id)

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

@@ -32,7 +32,7 @@ func createTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if license := c.App.License(); license == nil || !*license.Features.CustomTermsOfService { if license := c.App.Srv().License(); license == nil || !*license.Features.CustomTermsOfService {
c.Err = model.NewAppError("createTermsOfService", "api.create_terms_of_service.custom_terms_of_service_disabled.app_error", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("createTermsOfService", "api.create_terms_of_service.custom_terms_of_service_disabled.app_error", nil, "", http.StatusBadRequest)
return return
} }

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

@@ -45,7 +45,7 @@ func TestCreateTermsOfServiceAdminUser(t *testing.T) {
termsOfService, resp := Client.CreateTermsOfService("terms of service new", th.SystemAdminUser.Id) termsOfService, resp := Client.CreateTermsOfService("terms of service new", th.SystemAdminUser.Id)
CheckErrorMessage(t, resp, "api.create_terms_of_service.custom_terms_of_service_disabled.app_error") CheckErrorMessage(t, resp, "api.create_terms_of_service.custom_terms_of_service_disabled.app_error")
th.App.SetLicense(model.NewTestLicense("EnableCustomTermsOfService")) th.App.Srv().SetLicense(model.NewTestLicense("EnableCustomTermsOfService"))
termsOfService, resp = Client.CreateTermsOfService("terms of service new_2", th.SystemAdminUser.Id) termsOfService, resp = Client.CreateTermsOfService("terms of service new_2", th.SystemAdminUser.Id)
CheckNoError(t, resp) CheckNoError(t, resp)

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

@@ -113,7 +113,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec.AddMeta("token_type", token.Type) auditRec.AddMeta("token_type", token.Type)
if token.Type == app.TOKEN_TYPE_GUEST_INVITATION { if token.Type == app.TOKEN_TYPE_GUEST_INVITATION {
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("CreateUserWithToken", "api.user.create_user.guest_accounts.license.app_error", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("CreateUserWithToken", "api.user.create_user.guest_accounts.license.app_error", nil, "", http.StatusBadRequest)
return return
} }
@@ -1469,7 +1469,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) {
ldapOnly := props["ldap_only"] == "true" ldapOnly := props["ldap_only"] == "true"
if *c.App.Config().ExperimentalSettings.ClientSideCertEnable { if *c.App.Config().ExperimentalSettings.ClientSideCertEnable {
if license := c.App.License(); license == nil || !*license.Features.SAML { if license := c.App.Srv().License(); license == nil || !*license.Features.SAML {
c.Err = model.NewAppError("ClientSideCertNotAllowed", "api.user.login.client_side_cert.license.app_error", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("ClientSideCertNotAllowed", "api.user.login.client_side_cert.license.app_error", nil, "", http.StatusBadRequest)
return return
} }
@@ -1503,7 +1503,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec.AddMeta("user", user) auditRec.AddMeta("user", user)
if user.IsGuest() { if user.IsGuest() {
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("login", "api.user.login.guest_accounts.license.error", nil, "", http.StatusUnauthorized) c.Err = model.NewAppError("login", "api.user.login.guest_accounts.license.error", nil, "", http.StatusUnauthorized)
return return
} }
@@ -2232,7 +2232,7 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
if c.App.License() == nil { if c.App.Srv().License() == nil {
c.Err = model.NewAppError("Api4.demoteUserToGuest", "api.team.demote_user_to_guest.license.error", nil, "", http.StatusNotImplemented) c.Err = model.NewAppError("Api4.demoteUserToGuest", "api.team.demote_user_to_guest.license.error", nil, "", http.StatusNotImplemented)
return return
} }

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

@@ -337,7 +337,7 @@ func TestCreateUserWebSocketEvent(t *testing.T) {
defer th.TearDown() defer th.TearDown()
t.Run("guest should not received new_user event but user should", func(t *testing.T) { t.Run("guest should not received new_user event but user should", func(t *testing.T) {
th.App.SetLicense(model.NewTestLicense("guests")) th.App.Srv().SetLicense(model.NewTestLicense("guests"))
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.AllowEmailAccounts = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.AllowEmailAccounts = true })
@@ -2332,7 +2332,7 @@ func TestUpdateUserMfa(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("mfa")) th.App.Srv().SetLicense(model.NewTestLicense("mfa"))
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
session, _ := th.App.GetSession(th.Client.AuthToken) session, _ := th.App.GetSession(th.Client.AuthToken)
@@ -2372,7 +2372,7 @@ func TestCheckUserMfa(t *testing.T) {
require.False(t, required, "mfa not active") require.False(t, required, "mfa not active")
th.App.SetLicense(model.NewTestLicense("mfa")) th.App.Srv().SetLicense(model.NewTestLicense("mfa"))
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
th.LoginBasic() th.LoginBasic()
@@ -2478,7 +2478,7 @@ func TestGenerateMfaSecret(t *testing.T) {
_, resp = th.Client.GenerateMfaSecret("junk") _, resp = th.Client.GenerateMfaSecret("junk")
CheckBadRequestStatus(t, resp) CheckBadRequestStatus(t, resp)
th.App.SetLicense(model.NewTestLicense("mfa")) th.App.Srv().SetLicense(model.NewTestLicense("mfa"))
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true })
_, resp = th.Client.GenerateMfaSecret(model.NewId()) _, resp = th.Client.GenerateMfaSecret(model.NewId())
@@ -3130,7 +3130,7 @@ func TestCBALogin(t *testing.T) {
t.Run("primary", func(t *testing.T) { t.Run("primary", func(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("saml")) th.App.Srv().SetLicense(model.NewTestLicense("saml"))
th.App.UpdateConfig(func(cfg *model.Config) { th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.EnableBotAccountCreation = true *cfg.ServiceSettings.EnableBotAccountCreation = true
@@ -3188,7 +3188,7 @@ func TestCBALogin(t *testing.T) {
t.Run("secondary", func(t *testing.T) { t.Run("secondary", func(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("saml")) th.App.Srv().SetLicense(model.NewTestLicense("saml"))
th.App.UpdateConfig(func(cfg *model.Config) { th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.EnableBotAccountCreation = true *cfg.ServiceSettings.EnableBotAccountCreation = true
@@ -3256,7 +3256,7 @@ func TestSwitchAccount(t *testing.T) {
require.NotEmpty(t, link, "bad link") require.NotEmpty(t, link, "bad link")
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false })
sr = &model.SwitchRequest{ sr = &model.SwitchRequest{
@@ -4607,10 +4607,10 @@ func TestDemoteUserToGuest(t *testing.T) {
enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
defer func() { defer func() {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
th.App.RemoveLicense() th.App.Srv().RemoveLicense()
}() }()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
_, respErr := th.SystemAdminClient.GetUser(user.Id, "") _, respErr := th.SystemAdminClient.GetUser(user.Id, "")
CheckNoError(t, respErr) CheckNoError(t, respErr)
_, respErr = th.SystemAdminClient.DemoteUserToGuest(user.Id) _, respErr = th.SystemAdminClient.DemoteUserToGuest(user.Id)
@@ -4660,10 +4660,10 @@ func TestPromoteGuestToUser(t *testing.T) {
enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable
defer func() { defer func() {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts })
th.App.RemoveLicense() th.App.Srv().RemoveLicense()
}() }()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
_, respErr := th.SystemAdminClient.GetUser(user.Id, "") _, respErr := th.SystemAdminClient.GetUser(user.Id, "")
CheckNoError(t, respErr) CheckNoError(t, respErr)
_, respErr = th.SystemAdminClient.PromoteGuestToUser(user.Id) _, respErr = th.SystemAdminClient.PromoteGuestToUser(user.Id)

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

@@ -20,25 +20,25 @@ import (
"github.com/mattermost/mattermost-server/v5/utils" "github.com/mattermost/mattermost-server/v5/utils"
) )
func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { func (s *Server) GetLogs(page, perPage int) ([]string, *model.AppError) {
var lines []string var lines []string
if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { if s.Cluster != nil && *s.Config().ClusterSettings.Enable {
lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------")
lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------")
lines = append(lines, a.Cluster().GetMyClusterInfo().Hostname) lines = append(lines, s.Cluster.GetMyClusterInfo().Hostname)
lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------")
lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------")
} }
melines, err := a.GetLogsSkipSend(page, perPage) melines, err := s.GetLogsSkipSend(page, perPage)
if err != nil { if err != nil {
return nil, err return nil, err
} }
lines = append(lines, melines...) lines = append(lines, melines...)
if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { if s.Cluster != nil && *s.Config().ClusterSettings.Enable {
clines, err := a.Cluster().GetLogs(page, perPage) clines, err := s.Cluster.GetLogs(page, perPage)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -49,11 +49,15 @@ func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) {
return lines, nil return lines, nil
} }
func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) {
return a.Srv().GetLogs(page, perPage)
}
func (s *Server) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) {
var lines []string var lines []string
if *a.Config().LogSettings.EnableFile { if *s.Config().LogSettings.EnableFile {
logFile := utils.GetLogFileLocation(*a.Config().LogSettings.FileLocation) logFile := utils.GetLogFileLocation(*s.Config().LogSettings.FileLocation)
file, err := os.Open(logFile) file, err := os.Open(logFile)
if err != nil { if err != nil {
return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, err.Error(), http.StatusInternalServerError)
@@ -120,6 +124,10 @@ func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) {
return lines, nil return lines, nil
} }
func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) {
return a.Srv().GetLogsSkipSend(page, perPage)
}
func (a *App) GetClusterStatus() []*model.ClusterInfo { func (a *App) GetClusterStatus() []*model.ClusterInfo {
infos := make([]*model.ClusterInfo, 0) infos := make([]*model.ClusterInfo, 0)
@@ -130,11 +138,11 @@ func (a *App) GetClusterStatus() []*model.ClusterInfo {
return infos return infos
} }
func (a *App) InvalidateAllCaches() *model.AppError { func (s *Server) InvalidateAllCaches() *model.AppError {
debug.FreeOSMemory() debug.FreeOSMemory()
a.InvalidateAllCachesSkipSend() s.InvalidateAllCachesSkipSend()
if a.Cluster() != nil { if s.Cluster != nil {
msg := &model.ClusterMessage{ msg := &model.ClusterMessage{
Event: model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, Event: model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES,
@@ -142,23 +150,23 @@ func (a *App) InvalidateAllCaches() *model.AppError {
WaitForAllToSend: true, WaitForAllToSend: true,
} }
a.Cluster().SendClusterMessage(msg) s.Cluster.SendClusterMessage(msg)
} }
return nil return nil
} }
func (a *App) InvalidateAllCachesSkipSend() { func (s *Server) InvalidateAllCachesSkipSend() {
mlog.Info("Purging all caches") mlog.Info("Purging all caches")
a.Srv().sessionCache.Purge() s.sessionCache.Purge()
a.Srv().statusCache.Purge() s.statusCache.Purge()
a.Srv().Store.Team().ClearCaches() s.Store.Team().ClearCaches()
a.Srv().Store.Channel().ClearCaches() s.Store.Channel().ClearCaches()
a.Srv().Store.User().ClearCaches() s.Store.User().ClearCaches()
a.Srv().Store.Post().ClearCaches() s.Store.Post().ClearCaches()
a.Srv().Store.FileInfo().ClearCaches() s.Store.FileInfo().ClearCaches()
a.Srv().Store.Webhook().ClearCaches() s.Store.Webhook().ClearCaches()
a.LoadLicense() s.LoadLicense()
} }
func (a *App) RecycleDatabaseConnection() { func (a *App) RecycleDatabaseConnection() {
@@ -212,7 +220,7 @@ func (a *App) TestEmail(userId string, cfg *model.Config) *model.AppError {
} }
T := utils.GetUserTranslations(user.Locale) T := utils.GetUserTranslations(user.Locale)
license := a.License() license := a.Srv().License()
if err := mailservice.SendMailUsingConfig(user.Email, T("api.admin.test_email.subject"), T("api.admin.test_email.body"), cfg, license != nil && *license.Features.Compliance); err != nil { if err := mailservice.SendMailUsingConfig(user.Email, T("api.admin.test_email.subject"), T("api.admin.test_email.body"), cfg, license != nil && *license.Features.Compliance); err != nil {
return model.NewAppError("testEmail", "app.admin.test_email.failure", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError) return model.NewAppError("testEmail", "app.admin.test_email.failure", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError)
} }

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

@@ -11,7 +11,6 @@ import (
goi18n "github.com/mattermost/go-i18n/i18n" goi18n "github.com/mattermost/go-i18n/i18n"
"github.com/mattermost/mattermost-server/v5/einterfaces" "github.com/mattermost/mattermost-server/v5/einterfaces"
"github.com/mattermost/mattermost-server/v5/jobs"
"github.com/mattermost/mattermost-server/v5/mlog" "github.com/mattermost/mattermost-server/v5/mlog"
"github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/services/httpservice" "github.com/mattermost/mattermost-server/v5/services/httpservice"
@@ -63,6 +62,68 @@ func New(options ...AppOption) *App {
return app return app
} }
func (a *App) InitServer() {
a.srv.AppInitializedOnce.Do(func() {
a.initEnterprise()
a.accountMigration = a.srv.AccountMigration
a.ldap = a.srv.Ldap
a.notification = a.srv.Notification
a.saml = a.srv.Saml
a.StartPushNotificationsHubWorkers()
a.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) {
if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable {
if appErr := a.DeactivateGuests(); appErr != nil {
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
}
}
})
// Disable active guest accounts on first run if guest accounts are disabled
if !*a.Config().GuestAccountsSettings.Enable {
if appErr := a.DeactivateGuests(); appErr != nil {
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
}
}
pluginsRoute := a.srv.Router.PathPrefix("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter()
pluginsRoute.HandleFunc("", a.ServePluginRequest)
pluginsRoute.HandleFunc("/public/{public_file:.*}", a.ServePluginPublicRequest)
pluginsRoute.HandleFunc("/{anything:.*}", a.ServePluginRequest)
a.srv.Router.NotFoundHandler = http.HandlerFunc(a.Handle404)
// Scheduler must be started before cluster.
a.initJobs()
if a.srv.joinCluster && a.srv.Cluster != nil {
a.registerAllClusterMessageHandlers()
}
a.DoAppMigrations()
a.InitPostMetadata()
a.InitPlugins(*a.Config().PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory)
a.AddConfigListener(func(prevCfg, cfg *model.Config) {
if *cfg.PluginSettings.Enable {
a.InitPlugins(*cfg.PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory)
} else {
a.srv.ShutDownPlugins()
}
})
if a.Srv().runjobs {
a.Srv().Go(func() {
runLicenseExpirationCheckJob(a)
})
}
a.srv.RunJobs()
})
a.accountMigration = a.srv.AccountMigration
a.ldap = a.srv.Ldap
a.notification = a.srv.Notification
a.saml = a.srv.Saml
}
// DO NOT CALL THIS. // DO NOT CALL THIS.
// This is to avoid having to change all the code in cmd/mattermost/commands/* for now // This is to avoid having to change all the code in cmd/mattermost/commands/* for now
// shutdown should be called directly on the server // shutdown should be called directly on the server
@@ -71,38 +132,18 @@ func (a *App) Shutdown() {
a.srv = nil a.srv = nil
} }
func (a *App) configOrLicenseListener() { func (a *App) initJobs() {
a.regenerateClientConfig()
}
func (s *Server) initJobs() {
s.Jobs = jobs.NewJobServer(s, s.Store)
if jobsDataRetentionJobInterface != nil {
s.Jobs.DataRetentionJob = jobsDataRetentionJobInterface(s)
}
if jobsMessageExportJobInterface != nil {
s.Jobs.MessageExportJob = jobsMessageExportJobInterface(s)
}
if jobsElasticsearchAggregatorInterface != nil {
s.Jobs.ElasticsearchAggregator = jobsElasticsearchAggregatorInterface(s)
}
if jobsElasticsearchIndexerInterface != nil {
s.Jobs.ElasticsearchIndexer = jobsElasticsearchIndexerInterface(s)
}
if jobsLdapSyncInterface != nil { if jobsLdapSyncInterface != nil {
s.Jobs.LdapSync = jobsLdapSyncInterface(s.FakeApp()) a.srv.Jobs.LdapSync = jobsLdapSyncInterface(a)
} }
if jobsMigrationsInterface != nil { if jobsMigrationsInterface != nil {
s.Jobs.Migrations = jobsMigrationsInterface(s.FakeApp()) a.srv.Jobs.Migrations = jobsMigrationsInterface(a)
} }
if jobsPluginsInterface != nil { if jobsPluginsInterface != nil {
s.Jobs.Plugins = jobsPluginsInterface(s.FakeApp()) a.srv.Jobs.Plugins = jobsPluginsInterface(a)
} }
if jobsBleveIndexerInterface != nil { a.srv.Jobs.Workers = a.srv.Jobs.InitWorkers()
s.Jobs.BleveIndexer = jobsBleveIndexerInterface(s) a.srv.Jobs.Schedulers = a.srv.Jobs.InitSchedulers()
}
s.Jobs.Workers = s.Jobs.InitWorkers()
s.Jobs.Schedulers = s.Jobs.InitSchedulers()
} }
func (a *App) DiagnosticId() string { func (a *App) DiagnosticId() string {
@@ -113,9 +154,9 @@ func (a *App) SetDiagnosticId(id string) {
a.Srv().diagnosticId = id a.Srv().diagnosticId = id
} }
func (a *App) HTMLTemplates() *template.Template { func (s *Server) HTMLTemplates() *template.Template {
if a.Srv().htmlTemplateWatcher != nil { if s.htmlTemplateWatcher != nil {
return a.Srv().htmlTemplateWatcher.Templates() return s.htmlTemplateWatcher.Templates()
} }
return nil return nil
@@ -133,8 +174,8 @@ func (a *App) Handle404(w http.ResponseWriter, r *http.Request) {
utils.RenderWebAppError(a.Config(), w, r, model.NewAppError("Handle404", "api.context.404.app_error", nil, "", http.StatusNotFound), a.AsymmetricSigningKey()) utils.RenderWebAppError(a.Config(), w, r, model.NewAppError("Handle404", "api.context.404.app_error", nil, "", http.StatusNotFound), a.AsymmetricSigningKey())
} }
func (a *App) getSystemInstallDate() (int64, *model.AppError) { func (s *Server) getSystemInstallDate() (int64, *model.AppError) {
systemData, appErr := a.Srv().Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) systemData, appErr := s.Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY)
if appErr != nil { if appErr != nil {
return 0, appErr return 0, appErr
} }
@@ -145,8 +186,8 @@ func (a *App) getSystemInstallDate() (int64, *model.AppError) {
return value, nil return value, nil
} }
func (a *App) getFirstServerRunTimestamp() (int64, *model.AppError) { func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) {
systemData, appErr := a.Srv().Store.System().GetByName(model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY) systemData, appErr := s.Store.System().GetByName(model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY)
if appErr != nil { if appErr != nil {
return 0, appErr return 0, appErr
} }

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

@@ -11,7 +11,6 @@ import (
"bytes" "bytes"
"context" "context"
"crypto/ecdsa" "crypto/ecdsa"
"html/template"
"io" "io"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
@@ -160,8 +159,6 @@ type AppIface interface {
GetEnvironmentConfig() map[string]interface{} GetEnvironmentConfig() map[string]interface{}
// GetGroupsByTeam returns the paged list and the total count of group associated to the given team. // GetGroupsByTeam returns the paged list and the total count of group associated to the given team.
GetGroupsByTeam(teamId string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) GetGroupsByTeam(teamId string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError)
// GetHubForUserId returns the hub for a given user id.
GetHubForUserId(userId string) *Hub
// GetKnownUsers returns the list of user ids of users with any direct // GetKnownUsers returns the list of user ids of users with any direct
// relationship with a user. That means any user sharing any channel, including // relationship with a user. That means any user sharing any channel, including
// direct and group channels. // direct and group channels.
@@ -204,8 +201,6 @@ type AppIface interface {
HubRegister(webConn *WebConn) HubRegister(webConn *WebConn)
// HubStart starts all the hubs. // HubStart starts all the hubs.
HubStart() HubStart()
// HubStop stops all the hubs.
HubStop()
// HubUnregister unregisters a connection from a hub. // HubUnregister unregisters a connection from a hub.
HubUnregister(webConn *WebConn) HubUnregister(webConn *WebConn)
// InstallMarketplacePlugin installs a plugin listed in the marketplace server. It will get the plugin bundle // InstallMarketplacePlugin installs a plugin listed in the marketplace server. It will get the plugin bundle
@@ -217,8 +212,6 @@ type AppIface interface {
InstallPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError) InstallPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError)
// IsUsernameTaken checks if the username is already used by another user. Return false if the username is invalid. // IsUsernameTaken checks if the username is already used by another user. Return false if the username is invalid.
IsUsernameTaken(name string) bool IsUsernameTaken(name string) bool
// License returns the currently active license or nil if the application is unlicensed.
License() *model.License
// LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client. // LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client.
LimitedClientConfigWithComputed() map[string]string LimitedClientConfigWithComputed() map[string]string
// LogAuditRec logs an audit record using default CLILevel. // LogAuditRec logs an audit record using default CLILevel.
@@ -253,8 +246,6 @@ type AppIface interface {
RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError)
// RenameTeam is used to rename the team Name and the DisplayName fields // RenameTeam is used to rename the team Name and the DisplayName fields
RenameTeam(team *model.Team, newTeamName string, newDisplayName string) (*model.Team, *model.AppError) RenameTeam(team *model.Team, newTeamName string, newDisplayName string) (*model.Team, *model.AppError)
// RequestTrialLicense request a trial license from the mattermost offical license server
RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError
// RevokeSessionsFromAllUsers will go through all the sessions active // RevokeSessionsFromAllUsers will go through all the sessions active
// in the server and revoke them // in the server and revoke them
RevokeSessionsFromAllUsers() *model.AppError RevokeSessionsFromAllUsers() *model.AppError
@@ -341,7 +332,6 @@ type AppIface interface {
AddChannelMember(userId string, channel *model.Channel, userRequestorId string, postRootId string) (*model.ChannelMember, *model.AppError) AddChannelMember(userId string, channel *model.Channel, userRequestorId string, postRootId string) (*model.ChannelMember, *model.AppError)
AddConfigListener(listener func(*model.Config, *model.Config)) string AddConfigListener(listener func(*model.Config, *model.Config)) string
AddDirectChannels(teamId string, user *model.User) *model.AppError AddDirectChannels(teamId string, user *model.User) *model.AppError
AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string
AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError
AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppError AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppError
AddSamlPrivateCertificate(fileData *multipart.FileHeader) *model.AppError AddSamlPrivateCertificate(fileData *multipart.FileHeader) *model.AppError
@@ -394,7 +384,6 @@ type AppIface interface {
ClearTeamMembersCache(teamID string) ClearTeamMembersCache(teamID string)
ClientConfig() map[string]string ClientConfig() map[string]string
ClientConfigHash() string ClientConfigHash() string
ClientLicense() map[string]string
Cluster() einterfaces.ClusterInterface Cluster() einterfaces.ClusterInterface
CompareAndDeletePluginKey(pluginId string, key string, oldValue []byte) (bool, *model.AppError) CompareAndDeletePluginKey(pluginId string, key string, oldValue []byte) (bool, *model.AppError)
CompareAndSetPluginKey(pluginId string, key string, oldValue, newValue []byte) (bool, *model.AppError) CompareAndSetPluginKey(pluginId string, key string, oldValue, newValue []byte) (bool, *model.AppError)
@@ -560,6 +549,7 @@ type AppIface interface {
GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError) GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError)
GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, *model.AppError) GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, *model.AppError)
GetGroupsByUserId(userId string) ([]*model.Group, *model.AppError) GetGroupsByUserId(userId string) ([]*model.Group, *model.AppError)
GetHubForUserId(userId string) *Hub
GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model.AppError) GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model.AppError)
GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError)
GetIncomingWebhooksForTeamPageByUser(teamId string, userId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) GetIncomingWebhooksForTeamPageByUser(teamId string, userId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError)
@@ -631,7 +621,6 @@ type AppIface interface {
GetSamlMetadata() (string, *model.AppError) GetSamlMetadata() (string, *model.AppError)
GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError) GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError)
GetSanitizeOptions(asAdmin bool) map[string]bool GetSanitizeOptions(asAdmin bool) map[string]bool
GetSanitizedClientLicense() map[string]string
GetScheme(id string) (*model.Scheme, *model.AppError) GetScheme(id string) (*model.Scheme, *model.AppError)
GetSchemeByName(name string) (*model.Scheme, *model.AppError) GetSchemeByName(name string) (*model.Scheme, *model.AppError)
GetSchemeRolesForTeam(teamId string) (string, string, string, *model.AppError) GetSchemeRolesForTeam(teamId string) (string, string, string, *model.AppError)
@@ -696,7 +685,6 @@ type AppIface interface {
GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError)
GetVerifyEmailToken(token string) (*model.Token, *model.AppError) GetVerifyEmailToken(token string) (*model.Token, *model.AppError)
GetViewUsersRestrictions(userId string) (*model.ViewUsersRestrictions, *model.AppError) GetViewUsersRestrictions(userId string) (*model.ViewUsersRestrictions, *model.AppError)
HTMLTemplates() *template.Template
HTTPService() httpservice.HTTPService HTTPService() httpservice.HTTPService
Handle404(w http.ResponseWriter, r *http.Request) Handle404(w http.ResponseWriter, r *http.Request)
HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError)
@@ -710,15 +698,15 @@ type AppIface interface {
HasPermissionToChannelByPost(askingUserId string, postId string, permission *model.Permission) bool HasPermissionToChannelByPost(askingUserId string, postId string, permission *model.Permission) bool
HasPermissionToTeam(askingUserId string, teamId string, permission *model.Permission) bool HasPermissionToTeam(askingUserId string, teamId string, permission *model.Permission) bool
HasPermissionToUser(askingUserId string, userId string) bool HasPermissionToUser(askingUserId string, userId string) bool
HubStop()
ImageProxy() *imageproxy.ImageProxy ImageProxy() *imageproxy.ImageProxy
ImageProxyAdder() func(string) string ImageProxyAdder() func(string) string
ImageProxyRemover() (f func(string) string) ImageProxyRemover() (f func(string) string)
ImportPermissions(jsonl io.Reader) error ImportPermissions(jsonl io.Reader) error
InitPlugins(pluginDir, webappPluginDir string) InitPlugins(pluginDir, webappPluginDir string)
InitPostMetadata() InitPostMetadata()
InitServer()
InstallPluginFromData(data model.PluginEventData) InstallPluginFromData(data model.PluginEventData)
InvalidateAllCaches() *model.AppError
InvalidateAllCachesSkipSend()
InvalidateAllEmailInvites() *model.AppError InvalidateAllEmailInvites() *model.AppError
InvalidateCacheForUser(userId string) InvalidateCacheForUser(userId string)
InvalidateWebConnSessionCacheForUser(userId string) InvalidateWebConnSessionCacheForUser(userId string)
@@ -744,7 +732,6 @@ type AppIface interface {
ListDirectory(path string) ([]string, *model.AppError) ListDirectory(path string) ([]string, *model.AppError)
ListPluginKeys(pluginId string, page, perPage int) ([]string, *model.AppError) ListPluginKeys(pluginId string, page, perPage int) ([]string, *model.AppError)
ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) ListTeamCommands(teamId string) ([]*model.Command, *model.AppError)
LoadLicense()
Log() *mlog.Logger Log() *mlog.Logger
LoginByOAuth(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) LoginByOAuth(service string, userData io.Reader, teamId string) (*model.User, *model.AppError)
MakePermissionError(permission *model.Permission) *model.AppError MakePermissionError(permission *model.Permission) *model.AppError
@@ -799,8 +786,6 @@ type AppIface interface {
ReloadConfig() error ReloadConfig() error
RemoveConfigListener(id string) RemoveConfigListener(id string)
RemoveFile(path string) *model.AppError RemoveFile(path string) *model.AppError
RemoveLicense() *model.AppError
RemoveLicenseListener(id string)
RemovePlugin(id string) *model.AppError RemovePlugin(id string) *model.AppError
RemovePluginFromData(data model.PluginEventData) RemovePluginFromData(data model.PluginEventData)
RemoveSamlIdpCertificate() *model.AppError RemoveSamlIdpCertificate() *model.AppError
@@ -831,7 +816,6 @@ type AppIface interface {
SaveAndBroadcastStatus(status *model.Status) SaveAndBroadcastStatus(status *model.Status)
SaveBrandImage(imageData *multipart.FileHeader) *model.AppError SaveBrandImage(imageData *multipart.FileHeader) *model.AppError
SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError)
SaveLicense(licenseBytes []byte) (*model.License, *model.AppError)
SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError)
SaveUserTermsOfService(userId, termsOfServiceId string, accepted bool) *model.AppError SaveUserTermsOfService(userId, termsOfServiceId string, accepted bool) *model.AppError
SchemesIterator(scope string, batchSize int) func() []*model.Scheme SchemesIterator(scope string, batchSize int) func() []*model.Scheme
@@ -856,9 +840,7 @@ type AppIface interface {
SendAckToPushProxy(ack *model.PushNotificationAck) error SendAckToPushProxy(ack *model.PushNotificationAck) error
SendAutoResponse(channel *model.Channel, receiver *model.User) (bool, *model.AppError) SendAutoResponse(channel *model.Channel, receiver *model.User) (bool, *model.AppError)
SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User) (bool, *model.AppError) SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User) (bool, *model.AppError)
SendDailyDiagnostics()
SendDeactivateAccountEmail(email string, locale, siteURL string) *model.AppError SendDeactivateAccountEmail(email string, locale, siteURL string) *model.AppError
SendDiagnostic(event string, properties map[string]interface{})
SendEmailVerification(user *model.User, newEmail string) *model.AppError SendEmailVerification(user *model.User, newEmail string) *model.AppError
SendEphemeralPost(userId string, post *model.Post) *model.Post SendEphemeralPost(userId string, post *model.Post) *model.Post
SendInviteEmails(team *model.Team, senderName string, senderUserId string, invites []string, siteURL string) SendInviteEmails(team *model.Team, senderName string, senderUserId string, invites []string, siteURL string)
@@ -880,12 +862,10 @@ type AppIface interface {
SetAcceptLanguage(s string) SetAcceptLanguage(s string)
SetActiveChannel(userId string, channelId string) *model.AppError SetActiveChannel(userId string, channelId string) *model.AppError
SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap) SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap)
SetClientLicense(m map[string]string)
SetContext(c context.Context) SetContext(c context.Context)
SetDefaultProfileImage(user *model.User) *model.AppError SetDefaultProfileImage(user *model.User) *model.AppError
SetDiagnosticId(id string) SetDiagnosticId(id string)
SetIpAddress(s string) SetIpAddress(s string)
SetLicense(license *model.License) bool
SetLog(l *mlog.Logger) SetLog(l *mlog.Logger)
SetPath(s string) SetPath(s string)
SetPhase2PermissionsMigrationStatus(isComplete bool) error SetPhase2PermissionsMigrationStatus(isComplete bool) error
@@ -911,8 +891,6 @@ type AppIface interface {
SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppError SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppError
SetTeamIconFromMultiPartFile(teamId string, file multipart.File) *model.AppError SetTeamIconFromMultiPartFile(teamId string, file multipart.File) *model.AppError
SetUserAgent(s string) SetUserAgent(s string)
SetupInviteEmailRateLimiting() error
ShutDownPlugins()
SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User
SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[string][]SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, importerLog *bytes.Buffer) map[string]*model.Channel SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[string][]SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, importerLog *bytes.Buffer) map[string]*model.Channel
SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User) SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User)
@@ -922,7 +900,6 @@ type AppIface interface {
SoftDeleteTeam(teamId string) *model.AppError SoftDeleteTeam(teamId string) *model.AppError
Srv() *Server Srv() *Server
StartPushNotificationsHubWorkers() StartPushNotificationsHubWorkers()
StopPushNotificationsHubWorkers()
SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError)
SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError)
SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError)
@@ -987,7 +964,6 @@ type AppIface interface {
UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError)
UserAgent() string UserAgent() string
UserCanSeeOtherUser(userId string, otherUserId string) (bool, *model.AppError) UserCanSeeOtherUser(userId string, otherUserId string) (bool, *model.AppError)
ValidateAndSetLicenseBytes(b []byte)
VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError
VerifyUserEmail(userId, email string) *model.AppError VerifyUserEmail(userId, email string) *model.AppError
ViewChannel(view *model.ChannelView, userId string, currentSessionId string) (map[string]int64, *model.AppError) ViewChannel(view *model.ChannelView, userId string, currentSessionId string) (map[string]int64, *model.AppError)

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

@@ -12,6 +12,7 @@ import (
"github.com/stretchr/testify/mock" "github.com/stretchr/testify/mock"
"github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/services/searchengine/bleveengine"
"github.com/mattermost/mattermost-server/v5/store/storetest/mocks" "github.com/mattermost/mattermost-server/v5/store/storetest/mocks"
) )
@@ -31,6 +32,9 @@ func TestAppRace(t *testing.T) {
func TestUnitUpdateConfig(t *testing.T) { func TestUnitUpdateConfig(t *testing.T) {
th := SetupWithStoreMock(t) th := SetupWithStoreMock(t)
defer th.TearDown() defer th.TearDown()
bleveEngine := bleveengine.NewBleveEngine(th.App.Config(), th.App.Srv().Jobs)
_ = bleveEngine.Start()
th.App.Srv().SearchEngine.RegisterBleveEngine(bleveEngine)
mockStore := th.App.Srv().Store.(*mocks.Store) mockStore := th.App.Srv().Store.(*mocks.Store)
mockUserStore := mocks.UserStore{} mockUserStore := mocks.UserStore{}
@@ -40,9 +44,13 @@ func TestUnitUpdateConfig(t *testing.T) {
mockSystemStore := mocks.SystemStore{} mockSystemStore := mocks.SystemStore{}
mockSystemStore.On("GetByName", "InstallationDate").Return(&model.System{Name: "InstallationDate", Value: "10"}, nil) mockSystemStore.On("GetByName", "InstallationDate").Return(&model.System{Name: "InstallationDate", Value: "10"}, nil)
mockSystemStore.On("GetByName", "FirstServerRunTimestamp").Return(&model.System{Name: "FirstServerRunTimestamp", Value: "10"}, nil) mockSystemStore.On("GetByName", "FirstServerRunTimestamp").Return(&model.System{Name: "FirstServerRunTimestamp", Value: "10"}, nil)
mockSystemStore.On("Get").Return(make(model.StringMap), nil)
mockLicenseStore := mocks.LicenseStore{}
mockLicenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil)
mockStore.On("User").Return(&mockUserStore) mockStore.On("User").Return(&mockUserStore)
mockStore.On("Post").Return(&mockPostStore) mockStore.On("Post").Return(&mockPostStore)
mockStore.On("System").Return(&mockSystemStore) mockStore.On("System").Return(&mockSystemStore)
mockStore.On("License").Return(&mockLicenseStore)
prev := *th.App.Config().ServiceSettings.SiteURL prev := *th.App.Config().ServiceSettings.SiteURL
@@ -251,7 +259,7 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN
}) })
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
// Check the migration doesn't change anything if run again. // Check the migration doesn't change anything if run again.
th.App.DoAdvancedPermissionsMigration() th.App.DoAdvancedPermissionsMigration()
@@ -427,7 +435,7 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) {
} }
// Remove the license. // Remove the license.
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
// Do the migration again. // Do the migration again.
th.ResetRoleMigration() th.ResetRoleMigration()

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

@@ -221,7 +221,7 @@ func checkUserNotBot(user *model.User) *model.AppError {
} }
func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) { func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) {
license := a.License() license := a.Srv().License()
ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP
if user.AuthService == model.USER_AUTH_SERVICE_LDAP { if user.AuthService == model.USER_AUTH_SERVICE_LDAP {

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

@@ -16,38 +16,42 @@ const (
type ClusterDiscoveryService struct { type ClusterDiscoveryService struct {
model.ClusterDiscovery model.ClusterDiscovery
app *App srv *Server
stop chan bool stop chan bool
} }
func (a *App) NewClusterDiscoveryService() *ClusterDiscoveryService { func (s *Server) NewClusterDiscoveryService() *ClusterDiscoveryService {
ds := &ClusterDiscoveryService{ ds := &ClusterDiscoveryService{
ClusterDiscovery: model.ClusterDiscovery{}, ClusterDiscovery: model.ClusterDiscovery{},
app: a, srv: s,
stop: make(chan bool), stop: make(chan bool),
} }
return ds return ds
} }
func (a *App) NewClusterDiscoveryService() *ClusterDiscoveryService {
return a.Srv().NewClusterDiscoveryService()
}
func (me *ClusterDiscoveryService) Start() { func (me *ClusterDiscoveryService) Start() {
err := me.app.Srv().Store.ClusterDiscovery().Cleanup() err := me.srv.Store.ClusterDiscovery().Cleanup()
if err != nil { if err != nil {
mlog.Error("ClusterDiscoveryService failed to cleanup the outdated cluster discovery information", mlog.Err(err)) mlog.Error("ClusterDiscoveryService failed to cleanup the outdated cluster discovery information", mlog.Err(err))
} }
exists, err := me.app.Srv().Store.ClusterDiscovery().Exists(&me.ClusterDiscovery) exists, err := me.srv.Store.ClusterDiscovery().Exists(&me.ClusterDiscovery)
if err != nil { if err != nil {
mlog.Error("ClusterDiscoveryService failed to check if row exists", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) mlog.Error("ClusterDiscoveryService failed to check if row exists", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err))
} else { } else {
if exists { if exists {
if _, err := me.app.Srv().Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { if _, err := me.srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil {
mlog.Error("ClusterDiscoveryService failed to start clean", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) mlog.Error("ClusterDiscoveryService failed to start clean", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err))
} }
} }
} }
if err := me.app.Srv().Store.ClusterDiscovery().Save(&me.ClusterDiscovery); err != nil { if err := me.srv.Store.ClusterDiscovery().Save(&me.ClusterDiscovery); err != nil {
mlog.Error("ClusterDiscoveryService failed to save", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) mlog.Error("ClusterDiscoveryService failed to save", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err))
return return
} }
@@ -57,7 +61,7 @@ func (me *ClusterDiscoveryService) Start() {
ticker := time.NewTicker(DISCOVERY_SERVICE_WRITE_PING) ticker := time.NewTicker(DISCOVERY_SERVICE_WRITE_PING)
defer func() { defer func() {
ticker.Stop() ticker.Stop()
if _, err := me.app.Srv().Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { if _, err := me.srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil {
mlog.Error("ClusterDiscoveryService failed to cleanup", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) mlog.Error("ClusterDiscoveryService failed to cleanup", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err))
} }
mlog.Debug("ClusterDiscoveryService ping writer stopped", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson())) mlog.Debug("ClusterDiscoveryService ping writer stopped", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()))
@@ -66,7 +70,7 @@ func (me *ClusterDiscoveryService) Start() {
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
if err := me.app.Srv().Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); err != nil { if err := me.srv.Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); err != nil {
mlog.Error("ClusterDiscoveryService failed to write ping", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) mlog.Error("ClusterDiscoveryService failed to write ping", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err))
} }
case <-me.stop: case <-me.stop:
@@ -80,13 +84,17 @@ func (me *ClusterDiscoveryService) Stop() {
me.stop <- true me.stop <- true
} }
func (a *App) IsLeader() bool { func (s *Server) IsLeader() bool {
if a.License() != nil && *a.Config().ClusterSettings.Enable && a.Cluster() != nil { if s.License() != nil && *s.Config().ClusterSettings.Enable && s.Cluster != nil {
return a.Cluster().IsLeader() return s.Cluster.IsLeader()
} }
return true return true
} }
func (a *App) IsLeader() bool {
return a.Srv().IsLeader()
}
func (a *App) GetClusterId() string { func (a *App) GetClusterId() string {
if a.Cluster() == nil { if a.Cluster() == nil {
return "" return ""

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

@@ -43,7 +43,7 @@ func (a *App) clusterUpdateStatusHandler(msg *model.ClusterMessage) {
} }
func (a *App) clusterInvalidateAllCachesHandler(msg *model.ClusterMessage) { func (a *App) clusterInvalidateAllCachesHandler(msg *model.ClusterMessage) {
a.InvalidateAllCachesSkipSend() a.Srv().InvalidateAllCachesSkipSend()
} }
func (a *App) clusterInvalidateCacheForChannelMembersNotifyPropHandler(msg *model.ClusterMessage) { func (a *App) clusterInvalidateCacheForChannelMembersNotifyPropHandler(msg *model.ClusterMessage) {

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

@@ -12,7 +12,7 @@ import (
) )
func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model.AppError) { func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model.AppError) {
if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance { if license := a.Srv().License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance {
return nil, model.NewAppError("GetComplianceReports", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetComplianceReports", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -20,7 +20,7 @@ func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model
} }
func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) { func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) {
if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { if license := a.Srv().License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil {
return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -39,7 +39,7 @@ func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *m
} }
func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) { func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) {
if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { if license := a.Srv().License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil {
return nil, model.NewAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented)
} }

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

@@ -76,7 +76,7 @@ func (a *App) ClientConfig() map[string]string {
} }
func (a *App) ClientConfigHash() string { func (a *App) ClientConfigHash() string {
return a.Srv().clientConfigHash.Load().(string) return a.Srv().ClientConfigHash()
} }
func (a *App) LimitedClientConfig() map[string]string { func (a *App) LimitedClientConfig() map[string]string {
@@ -106,14 +106,14 @@ func (a *App) RemoveConfigListener(id string) {
// ensurePostActionCookieSecret ensures that the key for encrypting PostActionCookie exists // ensurePostActionCookieSecret ensures that the key for encrypting PostActionCookie exists
// and future calls to PostActionCookieSecret will always return a valid key, same on all // and future calls to PostActionCookieSecret will always return a valid key, same on all
// servers in the cluster // servers in the cluster
func (a *App) ensurePostActionCookieSecret() error { func (s *Server) ensurePostActionCookieSecret() error {
if a.Srv().postActionCookieSecret != nil { if s.postActionCookieSecret != nil {
return nil return nil
} }
var secret *model.SystemPostActionCookieSecret var secret *model.SystemPostActionCookieSecret
value, err := a.Srv().Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET)
if err == nil { if err == nil {
if err := json.Unmarshal([]byte(value.Value), &secret); err != nil { if err := json.Unmarshal([]byte(value.Value), &secret); err != nil {
return err return err
@@ -139,7 +139,7 @@ func (a *App) ensurePostActionCookieSecret() error {
} }
system.Value = string(v) system.Value = string(v)
// If we were able to save the key, use it, otherwise log the error. // If we were able to save the key, use it, otherwise log the error.
if appErr := a.Srv().Store.System().Save(system); appErr != nil { if appErr := s.Store.System().Save(system); appErr != nil {
mlog.Error("Failed to save PostActionCookieSecret", mlog.Err(appErr)) mlog.Error("Failed to save PostActionCookieSecret", mlog.Err(appErr))
} else { } else {
secret = newSecret secret = newSecret
@@ -149,7 +149,7 @@ func (a *App) ensurePostActionCookieSecret() error {
// If we weren't able to save a new key above, another server must have beat us to it. Get the // If we weren't able to save a new key above, another server must have beat us to it. Get the
// key from the database, and if that fails, error out. // key from the database, and if that fails, error out.
if secret == nil { if secret == nil {
value, err := a.Srv().Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET)
if err != nil { if err != nil {
return err return err
} }
@@ -159,20 +159,20 @@ func (a *App) ensurePostActionCookieSecret() error {
} }
} }
a.Srv().postActionCookieSecret = secret.Secret s.postActionCookieSecret = secret.Secret
return nil return nil
} }
// EnsureAsymmetricSigningKey ensures that an asymmetric signing key exists and future calls to // ensureAsymmetricSigningKey ensures that an asymmetric signing key exists and future calls to
// AsymmetricSigningKey will always return a valid signing key. // AsymmetricSigningKey will always return a valid signing key.
func (a *App) ensureAsymmetricSigningKey() error { func (s *Server) ensureAsymmetricSigningKey() error {
if a.Srv().asymmetricSigningKey != nil { if s.asymmetricSigningKey != nil {
return nil return nil
} }
var key *model.SystemAsymmetricSigningKey var key *model.SystemAsymmetricSigningKey
value, err := a.Srv().Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY)
if err == nil { if err == nil {
if err := json.Unmarshal([]byte(value.Value), &key); err != nil { if err := json.Unmarshal([]byte(value.Value), &key); err != nil {
return err return err
@@ -202,7 +202,7 @@ func (a *App) ensureAsymmetricSigningKey() error {
} }
system.Value = string(v) system.Value = string(v)
// If we were able to save the key, use it, otherwise log the error. // If we were able to save the key, use it, otherwise log the error.
if appErr := a.Srv().Store.System().Save(system); appErr != nil { if appErr := s.Store.System().Save(system); appErr != nil {
mlog.Error("Failed to save AsymmetricSigningKey", mlog.Err(appErr)) mlog.Error("Failed to save AsymmetricSigningKey", mlog.Err(appErr))
} else { } else {
key = newKey key = newKey
@@ -212,7 +212,7 @@ func (a *App) ensureAsymmetricSigningKey() error {
// If we weren't able to save a new key above, another server must have beat us to it. Get the // If we weren't able to save a new key above, another server must have beat us to it. Get the
// key from the database, and if that fails, error out. // key from the database, and if that fails, error out.
if key == nil { if key == nil {
value, err := a.Srv().Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY)
if err != nil { if err != nil {
return err return err
} }
@@ -229,7 +229,7 @@ func (a *App) ensureAsymmetricSigningKey() error {
default: default:
return fmt.Errorf("unknown curve: " + key.ECDSAKey.Curve) return fmt.Errorf("unknown curve: " + key.ECDSAKey.Curve)
} }
a.Srv().asymmetricSigningKey = &ecdsa.PrivateKey{ s.asymmetricSigningKey = &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{ PublicKey: ecdsa.PublicKey{
Curve: curve, Curve: curve,
X: key.ECDSAKey.X, X: key.ECDSAKey.X,
@@ -237,17 +237,17 @@ func (a *App) ensureAsymmetricSigningKey() error {
}, },
D: key.ECDSAKey.D, D: key.ECDSAKey.D,
} }
a.regenerateClientConfig() s.regenerateClientConfig()
return nil return nil
} }
func (a *App) ensureInstallationDate() error { func (s *Server) ensureInstallationDate() error {
_, err := a.getSystemInstallDate() _, err := s.getSystemInstallDate()
if err == nil { if err == nil {
return nil return nil
} }
installDate, err := a.Srv().Store.User().InferSystemInstallDate() installDate, err := s.Store.User().InferSystemInstallDate()
var installationDate int64 var installationDate int64
if err == nil && installDate > 0 { if err == nil && installDate > 0 {
installationDate = installDate installationDate = installDate
@@ -255,7 +255,7 @@ func (a *App) ensureInstallationDate() error {
installationDate = utils.MillisFromTime(time.Now()) installationDate = utils.MillisFromTime(time.Now())
} }
err = a.Srv().Store.System().SaveOrUpdate(&model.System{ err = s.Store.System().SaveOrUpdate(&model.System{
Name: model.SYSTEM_INSTALLATION_DATE_KEY, Name: model.SYSTEM_INSTALLATION_DATE_KEY,
Value: strconv.FormatInt(installationDate, 10), Value: strconv.FormatInt(installationDate, 10),
}) })
@@ -265,13 +265,13 @@ func (a *App) ensureInstallationDate() error {
return nil return nil
} }
func (a *App) ensureFirstServerRunTimestamp() error { func (s *Server) ensureFirstServerRunTimestamp() error {
_, err := a.getFirstServerRunTimestamp() _, err := s.getFirstServerRunTimestamp()
if err == nil { if err == nil {
return nil return nil
} }
err = a.Srv().Store.System().SaveOrUpdate(&model.System{ err = s.Store.System().SaveOrUpdate(&model.System{
Name: model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY, Name: model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY,
Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10), Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10),
}) })
@@ -298,12 +298,12 @@ func (a *App) PostActionCookieSecret() []byte {
return a.Srv().PostActionCookieSecret() return a.Srv().PostActionCookieSecret()
} }
func (a *App) regenerateClientConfig() { func (s *Server) regenerateClientConfig() {
clientConfig := config.GenerateClientConfig(a.Config(), a.DiagnosticId(), a.License()) clientConfig := config.GenerateClientConfig(s.Config(), s.diagnosticId, s.License())
limitedClientConfig := config.GenerateLimitedClientConfig(a.Config(), a.DiagnosticId(), a.License()) limitedClientConfig := config.GenerateLimitedClientConfig(s.Config(), s.diagnosticId, s.License())
if clientConfig["EnableCustomTermsOfService"] == "true" { if clientConfig["EnableCustomTermsOfService"] == "true" {
termsOfService, err := a.GetLatestTermsOfService() termsOfService, err := s.Store.TermsOfService().GetLatest(true)
if err != nil { if err != nil {
mlog.Err(err) mlog.Err(err)
} else { } else {
@@ -312,16 +312,16 @@ func (a *App) regenerateClientConfig() {
} }
} }
if key := a.AsymmetricSigningKey(); key != nil { if key := s.AsymmetricSigningKey(); key != nil {
der, _ := x509.MarshalPKIXPublicKey(&key.PublicKey) der, _ := x509.MarshalPKIXPublicKey(&key.PublicKey)
clientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) clientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der)
limitedClientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) limitedClientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der)
} }
clientConfigJSON, _ := json.Marshal(clientConfig) clientConfigJSON, _ := json.Marshal(clientConfig)
a.Srv().clientConfig.Store(clientConfig) s.clientConfig.Store(clientConfig)
a.Srv().limitedClientConfig.Store(limitedClientConfig) s.limitedClientConfig.Store(limitedClientConfig)
a.Srv().clientConfigHash.Store(fmt.Sprintf("%x", md5.Sum(clientConfigJSON))) s.clientConfigHash.Store(fmt.Sprintf("%x", md5.Sum(clientConfigJSON)))
} }
func (a *App) GetCookieDomain() string { func (a *App) GetCookieDomain() string {
@@ -338,24 +338,29 @@ func (a *App) GetSiteURL() string {
} }
// ClientConfigWithComputed gets the configuration in a format suitable for sending to the client. // ClientConfigWithComputed gets the configuration in a format suitable for sending to the client.
func (a *App) ClientConfigWithComputed() map[string]string { func (s *Server) ClientConfigWithComputed() map[string]string {
respCfg := map[string]string{} respCfg := map[string]string{}
for k, v := range a.ClientConfig() { for k, v := range s.clientConfig.Load().(map[string]string) {
respCfg[k] = v respCfg[k] = v
} }
// These properties are not configurable, but nevertheless represent configuration expected // These properties are not configurable, but nevertheless represent configuration expected
// by the client. // by the client.
respCfg["NoAccounts"] = strconv.FormatBool(a.IsFirstUserAccount()) respCfg["NoAccounts"] = strconv.FormatBool(s.IsFirstUserAccount())
respCfg["MaxPostSize"] = strconv.Itoa(a.MaxPostSize()) respCfg["MaxPostSize"] = strconv.Itoa(s.MaxPostSize())
respCfg["InstallationDate"] = "" respCfg["InstallationDate"] = ""
if installationDate, err := a.getSystemInstallDate(); err == nil { if installationDate, err := s.getSystemInstallDate(); err == nil {
respCfg["InstallationDate"] = strconv.FormatInt(installationDate, 10) respCfg["InstallationDate"] = strconv.FormatInt(installationDate, 10)
} }
return respCfg return respCfg
} }
// ClientConfigWithComputed gets the configuration in a format suitable for sending to the client.
func (a *App) ClientConfigWithComputed() map[string]string {
return a.Srv().ClientConfigWithComputed()
}
// LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client. // LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client.
func (a *App) LimitedClientConfigWithComputed() map[string]string { func (a *App) LimitedClientConfigWithComputed() map[string]string {
respCfg := map[string]string{} respCfg := map[string]string{}
@@ -394,26 +399,26 @@ func (a *App) GetEnvironmentConfig() map[string]interface{} {
} }
// SaveConfig replaces the active configuration, optionally notifying cluster peers. // SaveConfig replaces the active configuration, optionally notifying cluster peers.
func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError { func (s *Server) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError {
oldCfg, err := a.Srv().configStore.Set(newCfg) oldCfg, err := s.configStore.Set(newCfg)
if errors.Cause(err) == config.ErrReadOnlyConfiguration { if errors.Cause(err) == config.ErrReadOnlyConfiguration {
return model.NewAppError("saveConfig", "ent.cluster.save_config.error", nil, err.Error(), http.StatusForbidden) return model.NewAppError("saveConfig", "ent.cluster.save_config.error", nil, err.Error(), http.StatusForbidden)
} else if err != nil { } else if err != nil {
return model.NewAppError("saveConfig", "app.save_config.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("saveConfig", "app.save_config.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
if a.Metrics() != nil { if s.Metrics != nil {
if *a.Config().MetricsSettings.Enable { if *s.Config().MetricsSettings.Enable {
a.Metrics().StartServer() s.Metrics.StartServer()
} else { } else {
a.Metrics().StopServer() s.Metrics.StopServer()
} }
} }
if a.Cluster() != nil { if s.Cluster != nil {
newCfg = a.Srv().configStore.RemoveEnvironmentOverrides(newCfg) newCfg = s.configStore.RemoveEnvironmentOverrides(newCfg)
oldCfg = a.Srv().configStore.RemoveEnvironmentOverrides(oldCfg) oldCfg = s.configStore.RemoveEnvironmentOverrides(oldCfg)
err := a.Cluster().ConfigChanged(oldCfg, newCfg, sendConfigChangeClusterMessage) err := s.Cluster.ConfigChanged(oldCfg, newCfg, sendConfigChangeClusterMessage)
if err != nil { if err != nil {
return err return err
} }
@@ -422,6 +427,11 @@ func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bo
return nil return nil
} }
// SaveConfig replaces the active configuration, optionally notifying cluster peers.
func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError {
return a.Srv().SaveConfig(newCfg, sendConfigChangeClusterMessage)
}
func (a *App) HandleMessageExportConfig(cfg *model.Config, appCfg *model.Config) { func (a *App) HandleMessageExportConfig(cfg *model.Config, appCfg *model.Config) {
// If the Message Export feature has been toggled in the System Console, rewrite the ExportFromTimestamp field to an // If the Message Export feature has been toggled in the System Console, rewrite the ExportFromTimestamp field to an
// appropriate value. The rewriting occurs here to ensure it doesn't affect values written to the config file // appropriate value. The rewriting occurs here to ensure it doesn't affect values written to the config file

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

@@ -142,7 +142,7 @@ func TestEnsureInstallationDate(t *testing.T) {
}) })
} }
err := th.App.ensureInstallationDate() err := th.App.Srv().ensureInstallationDate()
if tc.ExpectedInstallationDate == nil { if tc.ExpectedInstallationDate == nil {
assert.Error(t, err) assert.Error(t, err)

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

@@ -70,51 +70,51 @@ const (
// declaring this as var to allow overriding in tests // declaring this as var to allow overriding in tests
var SENTRY_DSN = "placeholder_sentry_dsn" var SENTRY_DSN = "placeholder_sentry_dsn"
func (a *App) SendDailyDiagnostics() { func (s *Server) SendDailyDiagnostics() {
a.sendDailyDiagnostics(false) s.sendDailyDiagnostics(false)
} }
func (a *App) sendDailyDiagnostics(override bool) { func (s *Server) sendDailyDiagnostics(override bool) {
if *a.Config().LogSettings.EnableDiagnostics && a.IsLeader() && (!strings.Contains(SEGMENT_KEY, "placeholder") || override) { if *s.Config().LogSettings.EnableDiagnostics && s.IsLeader() && (!strings.Contains(SEGMENT_KEY, "placeholder") || override) {
a.Srv().initDiagnostics("") s.initDiagnostics("")
a.trackActivity() s.trackActivity()
a.trackConfig() s.trackConfig()
a.trackLicense() s.trackLicense()
a.trackPlugins() s.trackPlugins()
a.trackServer() s.trackServer()
a.trackPermissions() s.trackPermissions()
a.trackElasticsearch() s.trackElasticsearch()
a.trackGroups() s.trackGroups()
a.trackChannelModeration() s.trackChannelModeration()
} }
if *a.Config().LogSettings.EnableDiagnostics && a.IsLeader() && ((!strings.Contains(RUDDER_KEY, "placeholder") && !strings.Contains(RUDDER_DATAPLANE_URL, "placeholder")) || override) { if *s.Config().LogSettings.EnableDiagnostics && s.IsLeader() && ((!strings.Contains(RUDDER_KEY, "placeholder") && !strings.Contains(RUDDER_DATAPLANE_URL, "placeholder")) || override) {
a.Srv().initRudder(RUDDER_DATAPLANE_URL) s.initRudder(RUDDER_DATAPLANE_URL)
a.trackActivity() s.trackActivity()
a.trackConfig() s.trackConfig()
a.trackLicense() s.trackLicense()
a.trackPlugins() s.trackPlugins()
a.trackServer() s.trackServer()
a.trackPermissions() s.trackPermissions()
a.trackElasticsearch() s.trackElasticsearch()
a.trackGroups() s.trackGroups()
a.trackChannelModeration() s.trackChannelModeration()
} }
} }
func (a *App) SendDiagnostic(event string, properties map[string]interface{}) { func (s *Server) SendDiagnostic(event string, properties map[string]interface{}) {
if a.Srv().diagnosticClient != nil { if s.diagnosticClient != nil {
a.Srv().diagnosticClient.Enqueue(analytics.Track{ s.diagnosticClient.Enqueue(analytics.Track{
Event: event, Event: event,
UserId: a.DiagnosticId(), UserId: s.diagnosticId,
Properties: properties, Properties: properties,
}) })
} }
if a.Srv().rudderClient != nil { if s.rudderClient != nil {
a.Srv().rudderClient.Enqueue(rudder.Track{ s.rudderClient.Enqueue(rudder.Track{
Event: event, Event: event,
UserId: a.DiagnosticId(), UserId: s.diagnosticId,
Properties: properties, Properties: properties,
}) })
} }
@@ -152,7 +152,7 @@ func pluginVersion(pluginsAvailable []*model.BundleInfo, pluginId string) string
return "" return ""
} }
func (a *App) trackActivity() { func (s *Server) trackActivity() {
var userCount int64 var userCount int64
var guestAccountsCount int64 var guestAccountsCount int64
var botAccountsCount int64 var botAccountsCount int64
@@ -171,82 +171,82 @@ func (a *App) trackActivity() {
activeUsersDailyCountChan := make(chan store.StoreResult, 1) activeUsersDailyCountChan := make(chan store.StoreResult, 1)
go func() { go func() {
count, err := a.Srv().Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) count, err := s.Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false})
activeUsersDailyCountChan <- store.StoreResult{Data: count, Err: err} activeUsersDailyCountChan <- store.StoreResult{Data: count, Err: err}
close(activeUsersDailyCountChan) close(activeUsersDailyCountChan)
}() }()
activeUsersMonthlyCountChan := make(chan store.StoreResult, 1) activeUsersMonthlyCountChan := make(chan store.StoreResult, 1)
go func() { go func() {
count, err := a.Srv().Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) count, err := s.Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false})
activeUsersMonthlyCountChan <- store.StoreResult{Data: count, Err: err} activeUsersMonthlyCountChan <- store.StoreResult{Data: count, Err: err}
close(activeUsersMonthlyCountChan) close(activeUsersMonthlyCountChan)
}() }()
if count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { if count, err := s.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil {
userCount = count userCount = count
} }
if count, err := a.Srv().Store.User().AnalyticsGetGuestCount(); err == nil { if count, err := s.Store.User().AnalyticsGetGuestCount(); err == nil {
guestAccountsCount = count guestAccountsCount = count
} }
if count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeBotAccounts: true, ExcludeRegularUsers: true}); err == nil { if count, err := s.Store.User().Count(model.UserCountOptions{IncludeBotAccounts: true, ExcludeRegularUsers: true}); err == nil {
botAccountsCount = count botAccountsCount = count
} }
if iucr, err := a.Srv().Store.User().AnalyticsGetInactiveUsersCount(); err == nil { if iucr, err := s.Store.User().AnalyticsGetInactiveUsersCount(); err == nil {
inactiveUserCount = iucr inactiveUserCount = iucr
} }
teamCount, err := a.Srv().Store.Team().AnalyticsTeamCount(false) teamCount, err := s.Store.Team().AnalyticsTeamCount(false)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
if ucc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "O"); err == nil { if ucc, err := s.Store.Channel().AnalyticsTypeCount("", "O"); err == nil {
publicChannelCount = ucc publicChannelCount = ucc
} }
if pcc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "P"); err == nil { if pcc, err := s.Store.Channel().AnalyticsTypeCount("", "P"); err == nil {
privateChannelCount = pcc privateChannelCount = pcc
} }
if dcc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "D"); err == nil { if dcc, err := s.Store.Channel().AnalyticsTypeCount("", "D"); err == nil {
directChannelCount = dcc directChannelCount = dcc
} }
if duccr, err := a.Srv().Store.Channel().AnalyticsDeletedTypeCount("", "O"); err == nil { if duccr, err := s.Store.Channel().AnalyticsDeletedTypeCount("", "O"); err == nil {
deletedPublicChannelCount = duccr deletedPublicChannelCount = duccr
} }
if dpccr, err := a.Srv().Store.Channel().AnalyticsDeletedTypeCount("", "P"); err == nil { if dpccr, err := s.Store.Channel().AnalyticsDeletedTypeCount("", "P"); err == nil {
deletedPrivateChannelCount = dpccr deletedPrivateChannelCount = dpccr
} }
postsCount, _ = a.Srv().Store.Post().AnalyticsPostCount("", false, false) postsCount, _ = s.Store.Post().AnalyticsPostCount("", false, false)
postCountsOptions := &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: false, YesterdayOnly: true} postCountsOptions := &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: false, YesterdayOnly: true}
postCountsYesterday, _ := a.Srv().Store.Post().AnalyticsPostCountsByDay(postCountsOptions) postCountsYesterday, _ := s.Store.Post().AnalyticsPostCountsByDay(postCountsOptions)
postsCountPreviousDay = 0 postsCountPreviousDay = 0
if len(postCountsYesterday) > 0 { if len(postCountsYesterday) > 0 {
postsCountPreviousDay = int64(postCountsYesterday[0].Value) postsCountPreviousDay = int64(postCountsYesterday[0].Value)
} }
postCountsOptions = &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: true, YesterdayOnly: true} postCountsOptions = &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: true, YesterdayOnly: true}
botPostCountsYesterday, _ := a.Srv().Store.Post().AnalyticsPostCountsByDay(postCountsOptions) botPostCountsYesterday, _ := s.Store.Post().AnalyticsPostCountsByDay(postCountsOptions)
botPostsCountPreviousDay = 0 botPostsCountPreviousDay = 0
if len(botPostCountsYesterday) > 0 { if len(botPostCountsYesterday) > 0 {
botPostsCountPreviousDay = int64(botPostCountsYesterday[0].Value) botPostsCountPreviousDay = int64(botPostCountsYesterday[0].Value)
} }
slashCommandsCount, _ = a.Srv().Store.Command().AnalyticsCommandCount("") slashCommandsCount, _ = s.Store.Command().AnalyticsCommandCount("")
if c, err := a.Srv().Store.Webhook().AnalyticsIncomingCount(""); err == nil { if c, err := s.Store.Webhook().AnalyticsIncomingCount(""); err == nil {
incomingWebhooksCount = c incomingWebhooksCount = c
} }
outgoingWebhooksCount, _ = a.Srv().Store.Webhook().AnalyticsOutgoingCount("") outgoingWebhooksCount, _ = s.Store.Webhook().AnalyticsOutgoingCount("")
var activeUsersDailyCount int64 var activeUsersDailyCount int64
if r := <-activeUsersDailyCountChan; r.Err == nil { if r := <-activeUsersDailyCountChan; r.Err == nil {
@@ -258,7 +258,7 @@ func (a *App) trackActivity() {
activeUsersMonthlyCount = r.Data.(int64) activeUsersMonthlyCount = r.Data.(int64)
} }
a.SendDiagnostic(TRACK_ACTIVITY, map[string]interface{}{ s.SendDiagnostic(TRACK_ACTIVITY, map[string]interface{}{
"registered_users": userCount, "registered_users": userCount,
"bot_accounts": botAccountsCount, "bot_accounts": botAccountsCount,
"guest_accounts": guestAccountsCount, "guest_accounts": guestAccountsCount,
@@ -280,9 +280,9 @@ func (a *App) trackActivity() {
}) })
} }
func (a *App) trackConfig() { func (s *Server) trackConfig() {
cfg := a.Config() cfg := s.Config()
a.SendDiagnostic(TRACK_CONFIG_SERVICE, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_SERVICE, map[string]interface{}{
"web_server_mode": *cfg.ServiceSettings.WebserverMode, "web_server_mode": *cfg.ServiceSettings.WebserverMode,
"enable_security_fix_alert": *cfg.ServiceSettings.EnableSecurityFixAlert, "enable_security_fix_alert": *cfg.ServiceSettings.EnableSecurityFixAlert,
"enable_insecure_outgoing_connections": *cfg.ServiceSettings.EnableInsecureOutgoingConnections, "enable_insecure_outgoing_connections": *cfg.ServiceSettings.EnableInsecureOutgoingConnections,
@@ -361,7 +361,7 @@ func (a *App) trackConfig() {
"enable_local_mode": *cfg.ServiceSettings.EnableLocalMode, "enable_local_mode": *cfg.ServiceSettings.EnableLocalMode,
}) })
a.SendDiagnostic(TRACK_CONFIG_TEAM, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_TEAM, map[string]interface{}{
"enable_user_creation": cfg.TeamSettings.EnableUserCreation, "enable_user_creation": cfg.TeamSettings.EnableUserCreation,
"enable_team_creation": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_EnableTeamCreation, "enable_team_creation": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_EnableTeamCreation,
"restrict_team_invite": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite, "restrict_team_invite": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite,
@@ -395,7 +395,7 @@ func (a *App) trackConfig() {
"experimental_default_channels": len(cfg.TeamSettings.ExperimentalDefaultChannels), "experimental_default_channels": len(cfg.TeamSettings.ExperimentalDefaultChannels),
}) })
a.SendDiagnostic(TRACK_CONFIG_CLIENT_REQ, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_CLIENT_REQ, map[string]interface{}{
"android_latest_version": cfg.ClientRequirements.AndroidLatestVersion, "android_latest_version": cfg.ClientRequirements.AndroidLatestVersion,
"android_min_version": cfg.ClientRequirements.AndroidMinVersion, "android_min_version": cfg.ClientRequirements.AndroidMinVersion,
"desktop_latest_version": cfg.ClientRequirements.DesktopLatestVersion, "desktop_latest_version": cfg.ClientRequirements.DesktopLatestVersion,
@@ -404,7 +404,7 @@ func (a *App) trackConfig() {
"ios_min_version": cfg.ClientRequirements.IosMinVersion, "ios_min_version": cfg.ClientRequirements.IosMinVersion,
}) })
a.SendDiagnostic(TRACK_CONFIG_SQL, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_SQL, map[string]interface{}{
"driver_name": *cfg.SqlSettings.DriverName, "driver_name": *cfg.SqlSettings.DriverName,
"trace": cfg.SqlSettings.Trace, "trace": cfg.SqlSettings.Trace,
"max_idle_conns": *cfg.SqlSettings.MaxIdleConns, "max_idle_conns": *cfg.SqlSettings.MaxIdleConns,
@@ -416,7 +416,7 @@ func (a *App) trackConfig() {
"disable_database_search": *cfg.SqlSettings.DisableDatabaseSearch, "disable_database_search": *cfg.SqlSettings.DisableDatabaseSearch,
}) })
a.SendDiagnostic(TRACK_CONFIG_LOG, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_LOG, map[string]interface{}{
"enable_console": cfg.LogSettings.EnableConsole, "enable_console": cfg.LogSettings.EnableConsole,
"console_level": cfg.LogSettings.ConsoleLevel, "console_level": cfg.LogSettings.ConsoleLevel,
"console_json": *cfg.LogSettings.ConsoleJson, "console_json": *cfg.LogSettings.ConsoleJson,
@@ -427,7 +427,7 @@ func (a *App) trackConfig() {
"isdefault_file_location": isDefault(cfg.LogSettings.FileLocation, ""), "isdefault_file_location": isDefault(cfg.LogSettings.FileLocation, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_AUDIT, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_AUDIT, map[string]interface{}{
"syslog_enabled": *cfg.ExperimentalAuditSettings.SysLogEnabled, "syslog_enabled": *cfg.ExperimentalAuditSettings.SysLogEnabled,
"syslog_insecure": *cfg.ExperimentalAuditSettings.SysLogInsecure, "syslog_insecure": *cfg.ExperimentalAuditSettings.SysLogInsecure,
"syslog_max_queue_size": *cfg.ExperimentalAuditSettings.SysLogMaxQueueSize, "syslog_max_queue_size": *cfg.ExperimentalAuditSettings.SysLogMaxQueueSize,
@@ -439,7 +439,7 @@ func (a *App) trackConfig() {
"file_max_queue_size": *cfg.ExperimentalAuditSettings.FileMaxQueueSize, "file_max_queue_size": *cfg.ExperimentalAuditSettings.FileMaxQueueSize,
}) })
a.SendDiagnostic(TRACK_CONFIG_NOTIFICATION_LOG, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_NOTIFICATION_LOG, map[string]interface{}{
"enable_console": *cfg.NotificationLogSettings.EnableConsole, "enable_console": *cfg.NotificationLogSettings.EnableConsole,
"console_level": *cfg.NotificationLogSettings.ConsoleLevel, "console_level": *cfg.NotificationLogSettings.ConsoleLevel,
"console_json": *cfg.NotificationLogSettings.ConsoleJson, "console_json": *cfg.NotificationLogSettings.ConsoleJson,
@@ -449,7 +449,7 @@ func (a *App) trackConfig() {
"isdefault_file_location": isDefault(*cfg.NotificationLogSettings.FileLocation, ""), "isdefault_file_location": isDefault(*cfg.NotificationLogSettings.FileLocation, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_PASSWORD, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_PASSWORD, map[string]interface{}{
"minimum_length": *cfg.PasswordSettings.MinimumLength, "minimum_length": *cfg.PasswordSettings.MinimumLength,
"lowercase": *cfg.PasswordSettings.Lowercase, "lowercase": *cfg.PasswordSettings.Lowercase,
"number": *cfg.PasswordSettings.Number, "number": *cfg.PasswordSettings.Number,
@@ -457,7 +457,7 @@ func (a *App) trackConfig() {
"symbol": *cfg.PasswordSettings.Symbol, "symbol": *cfg.PasswordSettings.Symbol,
}) })
a.SendDiagnostic(TRACK_CONFIG_FILE, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_FILE, map[string]interface{}{
"enable_public_links": cfg.FileSettings.EnablePublicLink, "enable_public_links": cfg.FileSettings.EnablePublicLink,
"driver_name": *cfg.FileSettings.DriverName, "driver_name": *cfg.FileSettings.DriverName,
"isdefault_directory": isDefault(*cfg.FileSettings.Directory, model.FILE_SETTINGS_DEFAULT_DIRECTORY), "isdefault_directory": isDefault(*cfg.FileSettings.Directory, model.FILE_SETTINGS_DEFAULT_DIRECTORY),
@@ -472,7 +472,7 @@ func (a *App) trackConfig() {
"enable_mobile_download": *cfg.FileSettings.EnableMobileDownload, "enable_mobile_download": *cfg.FileSettings.EnableMobileDownload,
}) })
a.SendDiagnostic(TRACK_CONFIG_EMAIL, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_EMAIL, map[string]interface{}{
"enable_sign_up_with_email": cfg.EmailSettings.EnableSignUpWithEmail, "enable_sign_up_with_email": cfg.EmailSettings.EnableSignUpWithEmail,
"enable_sign_in_with_email": *cfg.EmailSettings.EnableSignInWithEmail, "enable_sign_in_with_email": *cfg.EmailSettings.EnableSignInWithEmail,
"enable_sign_in_with_username": *cfg.EmailSettings.EnableSignInWithUsername, "enable_sign_in_with_username": *cfg.EmailSettings.EnableSignInWithUsername,
@@ -499,7 +499,7 @@ func (a *App) trackConfig() {
"smtp_server_timeout": *cfg.EmailSettings.SMTPServerTimeout, "smtp_server_timeout": *cfg.EmailSettings.SMTPServerTimeout,
}) })
a.SendDiagnostic(TRACK_CONFIG_RATE, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_RATE, map[string]interface{}{
"enable_rate_limiter": *cfg.RateLimitSettings.Enable, "enable_rate_limiter": *cfg.RateLimitSettings.Enable,
"vary_by_remote_address": *cfg.RateLimitSettings.VaryByRemoteAddr, "vary_by_remote_address": *cfg.RateLimitSettings.VaryByRemoteAddr,
"vary_by_user": *cfg.RateLimitSettings.VaryByUser, "vary_by_user": *cfg.RateLimitSettings.VaryByUser,
@@ -509,25 +509,25 @@ func (a *App) trackConfig() {
"isdefault_vary_by_header": isDefault(cfg.RateLimitSettings.VaryByHeader, ""), "isdefault_vary_by_header": isDefault(cfg.RateLimitSettings.VaryByHeader, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_PRIVACY, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_PRIVACY, map[string]interface{}{
"show_email_address": cfg.PrivacySettings.ShowEmailAddress, "show_email_address": cfg.PrivacySettings.ShowEmailAddress,
"show_full_name": cfg.PrivacySettings.ShowFullName, "show_full_name": cfg.PrivacySettings.ShowFullName,
}) })
a.SendDiagnostic(TRACK_CONFIG_THEME, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_THEME, map[string]interface{}{
"enable_theme_selection": *cfg.ThemeSettings.EnableThemeSelection, "enable_theme_selection": *cfg.ThemeSettings.EnableThemeSelection,
"isdefault_default_theme": isDefault(*cfg.ThemeSettings.DefaultTheme, model.TEAM_SETTINGS_DEFAULT_TEAM_TEXT), "isdefault_default_theme": isDefault(*cfg.ThemeSettings.DefaultTheme, model.TEAM_SETTINGS_DEFAULT_TEAM_TEXT),
"allow_custom_themes": *cfg.ThemeSettings.AllowCustomThemes, "allow_custom_themes": *cfg.ThemeSettings.AllowCustomThemes,
"allowed_themes": len(cfg.ThemeSettings.AllowedThemes), "allowed_themes": len(cfg.ThemeSettings.AllowedThemes),
}) })
a.SendDiagnostic(TRACK_CONFIG_OAUTH, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_OAUTH, map[string]interface{}{
"enable_gitlab": cfg.GitLabSettings.Enable, "enable_gitlab": cfg.GitLabSettings.Enable,
"enable_google": cfg.GoogleSettings.Enable, "enable_google": cfg.GoogleSettings.Enable,
"enable_office365": cfg.Office365Settings.Enable, "enable_office365": cfg.Office365Settings.Enable,
}) })
a.SendDiagnostic(TRACK_CONFIG_SUPPORT, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_SUPPORT, map[string]interface{}{
"isdefault_terms_of_service_link": isDefault(*cfg.SupportSettings.TermsOfServiceLink, model.SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK), "isdefault_terms_of_service_link": isDefault(*cfg.SupportSettings.TermsOfServiceLink, model.SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK),
"isdefault_privacy_policy_link": isDefault(*cfg.SupportSettings.PrivacyPolicyLink, model.SUPPORT_SETTINGS_DEFAULT_PRIVACY_POLICY_LINK), "isdefault_privacy_policy_link": isDefault(*cfg.SupportSettings.PrivacyPolicyLink, model.SUPPORT_SETTINGS_DEFAULT_PRIVACY_POLICY_LINK),
"isdefault_about_link": isDefault(*cfg.SupportSettings.AboutLink, model.SUPPORT_SETTINGS_DEFAULT_ABOUT_LINK), "isdefault_about_link": isDefault(*cfg.SupportSettings.AboutLink, model.SUPPORT_SETTINGS_DEFAULT_ABOUT_LINK),
@@ -538,7 +538,7 @@ func (a *App) trackConfig() {
"custom_terms_of_service_re_acceptance_period": *cfg.SupportSettings.CustomTermsOfServiceReAcceptancePeriod, "custom_terms_of_service_re_acceptance_period": *cfg.SupportSettings.CustomTermsOfServiceReAcceptancePeriod,
}) })
a.SendDiagnostic(TRACK_CONFIG_LDAP, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_LDAP, map[string]interface{}{
"enable": *cfg.LdapSettings.Enable, "enable": *cfg.LdapSettings.Enable,
"enable_sync": *cfg.LdapSettings.EnableSync, "enable_sync": *cfg.LdapSettings.EnableSync,
"enable_admin_filter": *cfg.LdapSettings.EnableAdminFilter, "enable_admin_filter": *cfg.LdapSettings.EnableAdminFilter,
@@ -567,18 +567,18 @@ func (a *App) trackConfig() {
"isnotempty_picture_attribute": !isDefault(*cfg.LdapSettings.PictureAttribute, ""), "isnotempty_picture_attribute": !isDefault(*cfg.LdapSettings.PictureAttribute, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_COMPLIANCE, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_COMPLIANCE, map[string]interface{}{
"enable": *cfg.ComplianceSettings.Enable, "enable": *cfg.ComplianceSettings.Enable,
"enable_daily": *cfg.ComplianceSettings.EnableDaily, "enable_daily": *cfg.ComplianceSettings.EnableDaily,
}) })
a.SendDiagnostic(TRACK_CONFIG_LOCALIZATION, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_LOCALIZATION, map[string]interface{}{
"default_server_locale": *cfg.LocalizationSettings.DefaultServerLocale, "default_server_locale": *cfg.LocalizationSettings.DefaultServerLocale,
"default_client_locale": *cfg.LocalizationSettings.DefaultClientLocale, "default_client_locale": *cfg.LocalizationSettings.DefaultClientLocale,
"available_locales": *cfg.LocalizationSettings.AvailableLocales, "available_locales": *cfg.LocalizationSettings.AvailableLocales,
}) })
a.SendDiagnostic(TRACK_CONFIG_SAML, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_SAML, map[string]interface{}{
"enable": *cfg.SamlSettings.Enable, "enable": *cfg.SamlSettings.Enable,
"enable_sync_with_ldap": *cfg.SamlSettings.EnableSyncWithLdap, "enable_sync_with_ldap": *cfg.SamlSettings.EnableSyncWithLdap,
"enable_sync_with_ldap_include_auth": *cfg.SamlSettings.EnableSyncWithLdapIncludeAuth, "enable_sync_with_ldap_include_auth": *cfg.SamlSettings.EnableSyncWithLdapIncludeAuth,
@@ -606,7 +606,7 @@ func (a *App) trackConfig() {
"isdefault_login_button_text_color": isDefault(*cfg.SamlSettings.LoginButtonTextColor, ""), "isdefault_login_button_text_color": isDefault(*cfg.SamlSettings.LoginButtonTextColor, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_CLUSTER, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_CLUSTER, map[string]interface{}{
"enable": *cfg.ClusterSettings.Enable, "enable": *cfg.ClusterSettings.Enable,
"network_interface": isDefault(*cfg.ClusterSettings.NetworkInterface, ""), "network_interface": isDefault(*cfg.ClusterSettings.NetworkInterface, ""),
"bind_address": isDefault(*cfg.ClusterSettings.BindAddress, ""), "bind_address": isDefault(*cfg.ClusterSettings.BindAddress, ""),
@@ -616,18 +616,18 @@ func (a *App) trackConfig() {
"read_only_config": *cfg.ClusterSettings.ReadOnlyConfig, "read_only_config": *cfg.ClusterSettings.ReadOnlyConfig,
}) })
a.SendDiagnostic(TRACK_CONFIG_METRICS, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_METRICS, map[string]interface{}{
"enable": *cfg.MetricsSettings.Enable, "enable": *cfg.MetricsSettings.Enable,
"block_profile_rate": *cfg.MetricsSettings.BlockProfileRate, "block_profile_rate": *cfg.MetricsSettings.BlockProfileRate,
}) })
a.SendDiagnostic(TRACK_CONFIG_NATIVEAPP, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_NATIVEAPP, map[string]interface{}{
"isdefault_app_download_link": isDefault(*cfg.NativeAppSettings.AppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_APP_DOWNLOAD_LINK), "isdefault_app_download_link": isDefault(*cfg.NativeAppSettings.AppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_APP_DOWNLOAD_LINK),
"isdefault_android_app_download_link": isDefault(*cfg.NativeAppSettings.AndroidAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_ANDROID_APP_DOWNLOAD_LINK), "isdefault_android_app_download_link": isDefault(*cfg.NativeAppSettings.AndroidAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_ANDROID_APP_DOWNLOAD_LINK),
"isdefault_iosapp_download_link": isDefault(*cfg.NativeAppSettings.IosAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_IOS_APP_DOWNLOAD_LINK), "isdefault_iosapp_download_link": isDefault(*cfg.NativeAppSettings.IosAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_IOS_APP_DOWNLOAD_LINK),
}) })
a.SendDiagnostic(TRACK_CONFIG_EXPERIMENTAL, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_EXPERIMENTAL, map[string]interface{}{
"client_side_cert_enable": *cfg.ExperimentalSettings.ClientSideCertEnable, "client_side_cert_enable": *cfg.ExperimentalSettings.ClientSideCertEnable,
"isdefault_client_side_cert_check": isDefault(*cfg.ExperimentalSettings.ClientSideCertCheck, model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH), "isdefault_client_side_cert_check": isDefault(*cfg.ExperimentalSettings.ClientSideCertCheck, model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH),
"link_metadata_timeout_milliseconds": *cfg.ExperimentalSettings.LinkMetadataTimeoutMilliseconds, "link_metadata_timeout_milliseconds": *cfg.ExperimentalSettings.LinkMetadataTimeoutMilliseconds,
@@ -636,18 +636,18 @@ func (a *App) trackConfig() {
"use_new_saml_library": *cfg.ExperimentalSettings.UseNewSAMLLibrary, "use_new_saml_library": *cfg.ExperimentalSettings.UseNewSAMLLibrary,
}) })
a.SendDiagnostic(TRACK_CONFIG_ANALYTICS, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_ANALYTICS, map[string]interface{}{
"isdefault_max_users_for_statistics": isDefault(*cfg.AnalyticsSettings.MaxUsersForStatistics, model.ANALYTICS_SETTINGS_DEFAULT_MAX_USERS_FOR_STATISTICS), "isdefault_max_users_for_statistics": isDefault(*cfg.AnalyticsSettings.MaxUsersForStatistics, model.ANALYTICS_SETTINGS_DEFAULT_MAX_USERS_FOR_STATISTICS),
}) })
a.SendDiagnostic(TRACK_CONFIG_ANNOUNCEMENT, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_ANNOUNCEMENT, map[string]interface{}{
"enable_banner": *cfg.AnnouncementSettings.EnableBanner, "enable_banner": *cfg.AnnouncementSettings.EnableBanner,
"isdefault_banner_color": isDefault(*cfg.AnnouncementSettings.BannerColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_COLOR), "isdefault_banner_color": isDefault(*cfg.AnnouncementSettings.BannerColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_COLOR),
"isdefault_banner_text_color": isDefault(*cfg.AnnouncementSettings.BannerTextColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_TEXT_COLOR), "isdefault_banner_text_color": isDefault(*cfg.AnnouncementSettings.BannerTextColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_TEXT_COLOR),
"allow_banner_dismissal": *cfg.AnnouncementSettings.AllowBannerDismissal, "allow_banner_dismissal": *cfg.AnnouncementSettings.AllowBannerDismissal,
}) })
a.SendDiagnostic(TRACK_CONFIG_ELASTICSEARCH, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_ELASTICSEARCH, map[string]interface{}{
"isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionUrl, model.ELASTICSEARCH_SETTINGS_DEFAULT_CONNECTION_URL), "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionUrl, model.ELASTICSEARCH_SETTINGS_DEFAULT_CONNECTION_URL),
"isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ELASTICSEARCH_SETTINGS_DEFAULT_USERNAME), "isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ELASTICSEARCH_SETTINGS_DEFAULT_USERNAME),
"isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ELASTICSEARCH_SETTINGS_DEFAULT_PASSWORD), "isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ELASTICSEARCH_SETTINGS_DEFAULT_PASSWORD),
@@ -700,7 +700,7 @@ func (a *App) trackConfig() {
"signature_public_key_files": len(cfg.PluginSettings.SignaturePublicKeyFiles), "signature_public_key_files": len(cfg.PluginSettings.SignaturePublicKeyFiles),
} }
pluginsEnvironment := a.GetPluginsEnvironment() pluginsEnvironment := s.GetPluginsEnvironment()
if pluginsEnvironment != nil { if pluginsEnvironment != nil {
if plugins, appErr := pluginsEnvironment.Available(); appErr != nil { if plugins, appErr := pluginsEnvironment.Available(); appErr != nil {
mlog.Error("Unable to add plugin versions to diagnostics", mlog.Err(appErr)) mlog.Error("Unable to add plugin versions to diagnostics", mlog.Err(appErr))
@@ -720,9 +720,9 @@ func (a *App) trackConfig() {
} }
} }
a.SendDiagnostic(TRACK_CONFIG_PLUGIN, pluginConfigData) s.SendDiagnostic(TRACK_CONFIG_PLUGIN, pluginConfigData)
a.SendDiagnostic(TRACK_CONFIG_DATA_RETENTION, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_DATA_RETENTION, map[string]interface{}{
"enable_message_deletion": *cfg.DataRetentionSettings.EnableMessageDeletion, "enable_message_deletion": *cfg.DataRetentionSettings.EnableMessageDeletion,
"enable_file_deletion": *cfg.DataRetentionSettings.EnableFileDeletion, "enable_file_deletion": *cfg.DataRetentionSettings.EnableFileDeletion,
"message_retention_days": *cfg.DataRetentionSettings.MessageRetentionDays, "message_retention_days": *cfg.DataRetentionSettings.MessageRetentionDays,
@@ -730,7 +730,7 @@ func (a *App) trackConfig() {
"deletion_job_start_time": *cfg.DataRetentionSettings.DeletionJobStartTime, "deletion_job_start_time": *cfg.DataRetentionSettings.DeletionJobStartTime,
}) })
a.SendDiagnostic(TRACK_CONFIG_MESSAGE_EXPORT, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_MESSAGE_EXPORT, map[string]interface{}{
"enable_message_export": *cfg.MessageExportSettings.EnableExport, "enable_message_export": *cfg.MessageExportSettings.EnableExport,
"export_format": *cfg.MessageExportSettings.ExportFormat, "export_format": *cfg.MessageExportSettings.ExportFormat,
"daily_run_time": *cfg.MessageExportSettings.DailyRunTime, "daily_run_time": *cfg.MessageExportSettings.DailyRunTime,
@@ -742,26 +742,26 @@ func (a *App) trackConfig() {
"is_default_global_relay_email_address": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.EmailAddress, ""), "is_default_global_relay_email_address": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.EmailAddress, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_DISPLAY, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_DISPLAY, map[string]interface{}{
"experimental_timezone": *cfg.DisplaySettings.ExperimentalTimezone, "experimental_timezone": *cfg.DisplaySettings.ExperimentalTimezone,
"isdefault_custom_url_schemes": len(cfg.DisplaySettings.CustomUrlSchemes) != 0, "isdefault_custom_url_schemes": len(cfg.DisplaySettings.CustomUrlSchemes) != 0,
}) })
a.SendDiagnostic(TRACK_CONFIG_GUEST_ACCOUNTS, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_GUEST_ACCOUNTS, map[string]interface{}{
"enable": *cfg.GuestAccountsSettings.Enable, "enable": *cfg.GuestAccountsSettings.Enable,
"allow_email_accounts": *cfg.GuestAccountsSettings.AllowEmailAccounts, "allow_email_accounts": *cfg.GuestAccountsSettings.AllowEmailAccounts,
"enforce_multifactor_authentication": *cfg.GuestAccountsSettings.EnforceMultifactorAuthentication, "enforce_multifactor_authentication": *cfg.GuestAccountsSettings.EnforceMultifactorAuthentication,
"isdefault_restrict_creation_to_domains": isDefault(*cfg.GuestAccountsSettings.RestrictCreationToDomains, ""), "isdefault_restrict_creation_to_domains": isDefault(*cfg.GuestAccountsSettings.RestrictCreationToDomains, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_IMAGE_PROXY, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_IMAGE_PROXY, map[string]interface{}{
"enable": *cfg.ImageProxySettings.Enable, "enable": *cfg.ImageProxySettings.Enable,
"image_proxy_type": *cfg.ImageProxySettings.ImageProxyType, "image_proxy_type": *cfg.ImageProxySettings.ImageProxyType,
"isdefault_remote_image_proxy_url": isDefault(*cfg.ImageProxySettings.RemoteImageProxyURL, ""), "isdefault_remote_image_proxy_url": isDefault(*cfg.ImageProxySettings.RemoteImageProxyURL, ""),
"isdefault_remote_image_proxy_options": isDefault(*cfg.ImageProxySettings.RemoteImageProxyOptions, ""), "isdefault_remote_image_proxy_options": isDefault(*cfg.ImageProxySettings.RemoteImageProxyOptions, ""),
}) })
a.SendDiagnostic(TRACK_CONFIG_BLEVE, map[string]interface{}{ s.SendDiagnostic(TRACK_CONFIG_BLEVE, map[string]interface{}{
"enable_indexing": *cfg.BleveSettings.EnableIndexing, "enable_indexing": *cfg.BleveSettings.EnableIndexing,
"enable_searching": *cfg.BleveSettings.EnableSearching, "enable_searching": *cfg.BleveSettings.EnableSearching,
"enable_autocomplete": *cfg.BleveSettings.EnableAutocomplete, "enable_autocomplete": *cfg.BleveSettings.EnableAutocomplete,
@@ -769,8 +769,8 @@ func (a *App) trackConfig() {
}) })
} }
func (a *App) trackLicense() { func (s *Server) trackLicense() {
if license := a.License(); license != nil { if license := s.License(); license != nil {
data := map[string]interface{}{ data := map[string]interface{}{
"customer_id": license.Customer.Id, "customer_id": license.Customer.Id,
"license_id": license.Id, "license_id": license.Id,
@@ -786,12 +786,12 @@ func (a *App) trackLicense() {
data["feature_"+featureName] = featureValue data["feature_"+featureName] = featureValue
} }
a.SendDiagnostic(TRACK_LICENSE, data) s.SendDiagnostic(TRACK_LICENSE, data)
} }
} }
func (a *App) trackPlugins() { func (s *Server) trackPlugins() {
pluginsEnvironment := a.GetPluginsEnvironment() pluginsEnvironment := s.GetPluginsEnvironment()
if pluginsEnvironment == nil { if pluginsEnvironment == nil {
return return
} }
@@ -805,7 +805,7 @@ func (a *App) trackPlugins() {
brokenManifestCount := 0 brokenManifestCount := 0
settingsCount := 0 settingsCount := 0
pluginStates := a.Config().PluginSettings.PluginStates pluginStates := s.Config().PluginSettings.PluginStates
plugins, _ := pluginsEnvironment.Available() plugins, _ := pluginsEnvironment.Available()
if pluginStates != nil && plugins != nil { if pluginStates != nil && plugins != nil {
@@ -841,7 +841,7 @@ func (a *App) trackPlugins() {
totalDisabledCount = -1 // -1 to indicate disabled or error totalDisabledCount = -1 // -1 to indicate disabled or error
} }
a.SendDiagnostic(TRACK_PLUGINS, map[string]interface{}{ s.SendDiagnostic(TRACK_PLUGINS, map[string]interface{}{
"enabled_plugins": totalEnabledCount, "enabled_plugins": totalEnabledCount,
"enabled_webapp_plugins": webappEnabledCount, "enabled_webapp_plugins": webappEnabledCount,
"enabled_backend_plugins": backendEnabledCount, "enabled_backend_plugins": backendEnabledCount,
@@ -853,82 +853,82 @@ func (a *App) trackPlugins() {
}) })
} }
func (a *App) trackServer() { func (s *Server) trackServer() {
data := map[string]interface{}{ data := map[string]interface{}{
"edition": model.BuildEnterpriseReady, "edition": model.BuildEnterpriseReady,
"version": model.CurrentVersion, "version": model.CurrentVersion,
"database_type": *a.Config().SqlSettings.DriverName, "database_type": *s.Config().SqlSettings.DriverName,
"operating_system": runtime.GOOS, "operating_system": runtime.GOOS,
} }
if scr, err := a.Srv().Store.User().AnalyticsGetSystemAdminCount(); err == nil { if scr, err := s.Store.User().AnalyticsGetSystemAdminCount(); err == nil {
data["system_admins"] = scr data["system_admins"] = scr
} }
if scr, err := a.Srv().Store.GetDbVersion(); err == nil { if scr, err := s.Store.GetDbVersion(); err == nil {
data["database_version"] = scr data["database_version"] = scr
} }
a.SendDiagnostic(TRACK_SERVER, data) s.SendDiagnostic(TRACK_SERVER, data)
} }
func (a *App) trackPermissions() { func (s *Server) trackPermissions() {
phase1Complete := false phase1Complete := false
if _, err := a.Srv().Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { if _, err := s.Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil {
phase1Complete = true phase1Complete = true
} }
phase2Complete := false phase2Complete := false
if _, err := a.Srv().Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err == nil { if _, err := s.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err == nil {
phase2Complete = true phase2Complete = true
} }
a.SendDiagnostic(TRACK_PERMISSIONS_GENERAL, map[string]interface{}{ s.SendDiagnostic(TRACK_PERMISSIONS_GENERAL, map[string]interface{}{
"phase_1_migration_complete": phase1Complete, "phase_1_migration_complete": phase1Complete,
"phase_2_migration_complete": phase2Complete, "phase_2_migration_complete": phase2Complete,
}) })
systemAdminPermissions := "" systemAdminPermissions := ""
if role, err := a.GetRoleByName(model.SYSTEM_ADMIN_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.SYSTEM_ADMIN_ROLE_ID); err == nil {
systemAdminPermissions = strings.Join(role.Permissions, " ") systemAdminPermissions = strings.Join(role.Permissions, " ")
} }
systemUserPermissions := "" systemUserPermissions := ""
if role, err := a.GetRoleByName(model.SYSTEM_USER_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.SYSTEM_USER_ROLE_ID); err == nil {
systemUserPermissions = strings.Join(role.Permissions, " ") systemUserPermissions = strings.Join(role.Permissions, " ")
} }
teamAdminPermissions := "" teamAdminPermissions := ""
if role, err := a.GetRoleByName(model.TEAM_ADMIN_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.TEAM_ADMIN_ROLE_ID); err == nil {
teamAdminPermissions = strings.Join(role.Permissions, " ") teamAdminPermissions = strings.Join(role.Permissions, " ")
} }
teamUserPermissions := "" teamUserPermissions := ""
if role, err := a.GetRoleByName(model.TEAM_USER_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.TEAM_USER_ROLE_ID); err == nil {
teamUserPermissions = strings.Join(role.Permissions, " ") teamUserPermissions = strings.Join(role.Permissions, " ")
} }
teamGuestPermissions := "" teamGuestPermissions := ""
if role, err := a.GetRoleByName(model.TEAM_GUEST_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.TEAM_GUEST_ROLE_ID); err == nil {
teamGuestPermissions = strings.Join(role.Permissions, " ") teamGuestPermissions = strings.Join(role.Permissions, " ")
} }
channelAdminPermissions := "" channelAdminPermissions := ""
if role, err := a.GetRoleByName(model.CHANNEL_ADMIN_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.CHANNEL_ADMIN_ROLE_ID); err == nil {
channelAdminPermissions = strings.Join(role.Permissions, " ") channelAdminPermissions = strings.Join(role.Permissions, " ")
} }
channelUserPermissions := "" channelUserPermissions := ""
if role, err := a.GetRoleByName(model.CHANNEL_USER_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.CHANNEL_USER_ROLE_ID); err == nil {
channelUserPermissions = strings.Join(role.Permissions, " ") channelUserPermissions = strings.Join(role.Permissions, " ")
} }
channelGuestPermissions := "" channelGuestPermissions := ""
if role, err := a.GetRoleByName(model.CHANNEL_GUEST_ROLE_ID); err == nil { if role, err := s.GetRoleByName(model.CHANNEL_GUEST_ROLE_ID); err == nil {
channelGuestPermissions = strings.Join(role.Permissions, " ") channelGuestPermissions = strings.Join(role.Permissions, " ")
} }
a.SendDiagnostic(TRACK_PERMISSIONS_SYSTEM_SCHEME, map[string]interface{}{ s.SendDiagnostic(TRACK_PERMISSIONS_SYSTEM_SCHEME, map[string]interface{}{
"system_admin_permissions": systemAdminPermissions, "system_admin_permissions": systemAdminPermissions,
"system_user_permissions": systemUserPermissions, "system_user_permissions": systemUserPermissions,
"team_admin_permissions": teamAdminPermissions, "team_admin_permissions": teamAdminPermissions,
@@ -939,41 +939,41 @@ func (a *App) trackPermissions() {
"channel_guest_permissions": channelGuestPermissions, "channel_guest_permissions": channelGuestPermissions,
}) })
if schemes, err := a.GetSchemes(model.SCHEME_SCOPE_TEAM, 0, 100); err == nil { if schemes, err := s.GetSchemes(model.SCHEME_SCOPE_TEAM, 0, 100); err == nil {
for _, scheme := range schemes { for _, scheme := range schemes {
teamAdminPermissions := "" teamAdminPermissions := ""
if role, err := a.GetRoleByName(scheme.DefaultTeamAdminRole); err == nil { if role, err := s.GetRoleByName(scheme.DefaultTeamAdminRole); err == nil {
teamAdminPermissions = strings.Join(role.Permissions, " ") teamAdminPermissions = strings.Join(role.Permissions, " ")
} }
teamUserPermissions := "" teamUserPermissions := ""
if role, err := a.GetRoleByName(scheme.DefaultTeamUserRole); err == nil { if role, err := s.GetRoleByName(scheme.DefaultTeamUserRole); err == nil {
teamUserPermissions = strings.Join(role.Permissions, " ") teamUserPermissions = strings.Join(role.Permissions, " ")
} }
teamGuestPermissions := "" teamGuestPermissions := ""
if role, err := a.GetRoleByName(scheme.DefaultTeamGuestRole); err == nil { if role, err := s.GetRoleByName(scheme.DefaultTeamGuestRole); err == nil {
teamGuestPermissions = strings.Join(role.Permissions, " ") teamGuestPermissions = strings.Join(role.Permissions, " ")
} }
channelAdminPermissions := "" channelAdminPermissions := ""
if role, err := a.GetRoleByName(scheme.DefaultChannelAdminRole); err == nil { if role, err := s.GetRoleByName(scheme.DefaultChannelAdminRole); err == nil {
channelAdminPermissions = strings.Join(role.Permissions, " ") channelAdminPermissions = strings.Join(role.Permissions, " ")
} }
channelUserPermissions := "" channelUserPermissions := ""
if role, err := a.GetRoleByName(scheme.DefaultChannelUserRole); err == nil { if role, err := s.GetRoleByName(scheme.DefaultChannelUserRole); err == nil {
channelUserPermissions = strings.Join(role.Permissions, " ") channelUserPermissions = strings.Join(role.Permissions, " ")
} }
channelGuestPermissions := "" channelGuestPermissions := ""
if role, err := a.GetRoleByName(scheme.DefaultChannelGuestRole); err == nil { if role, err := s.GetRoleByName(scheme.DefaultChannelGuestRole); err == nil {
channelGuestPermissions = strings.Join(role.Permissions, " ") channelGuestPermissions = strings.Join(role.Permissions, " ")
} }
count, _ := a.Srv().Store.Team().AnalyticsGetTeamCountForScheme(scheme.Id) count, _ := s.Store.Team().AnalyticsGetTeamCountForScheme(scheme.Id)
a.SendDiagnostic(TRACK_PERMISSIONS_TEAM_SCHEMES, map[string]interface{}{ s.SendDiagnostic(TRACK_PERMISSIONS_TEAM_SCHEMES, map[string]interface{}{
"scheme_id": scheme.Id, "scheme_id": scheme.Id,
"team_admin_permissions": teamAdminPermissions, "team_admin_permissions": teamAdminPermissions,
"team_user_permissions": teamUserPermissions, "team_user_permissions": teamUserPermissions,
@@ -987,60 +987,60 @@ func (a *App) trackPermissions() {
} }
} }
func (a *App) trackElasticsearch() { func (s *Server) trackElasticsearch() {
data := map[string]interface{}{} data := map[string]interface{}{}
for _, engine := range a.SearchEngine().GetActiveEngines() { for _, engine := range s.SearchEngine.GetActiveEngines() {
if engine.GetVersion() != 0 && engine.GetName() == "elasticsearch" { if engine.GetVersion() != 0 && engine.GetName() == "elasticsearch" {
data["elasticsearch_server_version"] = engine.GetVersion() data["elasticsearch_server_version"] = engine.GetVersion()
} }
} }
a.SendDiagnostic(TRACK_ELASTICSEARCH, data) s.SendDiagnostic(TRACK_ELASTICSEARCH, data)
} }
func (a *App) trackGroups() { func (s *Server) trackGroups() {
groupCount, err := a.Srv().Store.Group().GroupCount() groupCount, err := s.Store.Group().GroupCount()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
groupTeamCount, err := a.Srv().Store.Group().GroupTeamCount() groupTeamCount, err := s.Store.Group().GroupTeamCount()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
groupChannelCount, err := a.Srv().Store.Group().GroupChannelCount() groupChannelCount, err := s.Store.Group().GroupChannelCount()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
groupSyncedTeamCount, err := a.Srv().Store.Team().GroupSyncedTeamCount() groupSyncedTeamCount, err := s.Store.Team().GroupSyncedTeamCount()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
groupSyncedChannelCount, err := a.Srv().Store.Channel().GroupSyncedChannelCount() groupSyncedChannelCount, err := s.Store.Channel().GroupSyncedChannelCount()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
groupMemberCount, err := a.Srv().Store.Group().GroupMemberCount() groupMemberCount, err := s.Store.Group().GroupMemberCount()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
distinctGroupMemberCount, err := a.Srv().Store.Group().DistinctGroupMemberCount() distinctGroupMemberCount, err := s.Store.Group().DistinctGroupMemberCount()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
groupCountWithAllowReference, err := a.Srv().Store.Group().GroupCountWithAllowReference() groupCountWithAllowReference, err := s.Store.Group().GroupCountWithAllowReference()
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
a.SendDiagnostic(TRACK_GROUPS, map[string]interface{}{ s.SendDiagnostic(TRACK_GROUPS, map[string]interface{}{
"group_count": groupCount, "group_count": groupCount,
"group_team_count": groupTeamCount, "group_team_count": groupTeamCount,
"group_channel_count": groupChannelCount, "group_channel_count": groupChannelCount,
@@ -1052,50 +1052,50 @@ func (a *App) trackGroups() {
}) })
} }
func (a *App) trackChannelModeration() { func (s *Server) trackChannelModeration() {
channelSchemeCount, err := a.Srv().Store.Scheme().CountByScope(model.SCHEME_SCOPE_CHANNEL) channelSchemeCount, err := s.Store.Scheme().CountByScope(model.SCHEME_SCOPE_CHANNEL)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
createPostUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeUser) createPostUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
createPostGuest, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeGuest) createPostGuest, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeGuest)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
// only need to track one of 'add_reaction' or 'remove_reaction` because they're both toggled together by the channel moderation feature // only need to track one of 'add_reaction' or 'remove_reaction` because they're both toggled together by the channel moderation feature
postReactionsUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeUser) postReactionsUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
postReactionsGuest, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeGuest) postReactionsGuest, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeGuest)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
// only need to track one of 'manage_public_channel_members' or 'manage_private_channel_members` because they're both toggled together by the channel moderation feature // only need to track one of 'manage_public_channel_members' or 'manage_private_channel_members` because they're both toggled together by the channel moderation feature
manageMembersUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, model.RoleScopeChannel, model.RoleTypeUser) manageMembersUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
useChannelMentionsUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeUser) useChannelMentionsUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeUser)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
useChannelMentionsGuest, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeGuest) useChannelMentionsGuest, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeGuest)
if err != nil { if err != nil {
mlog.Error(err.Error()) mlog.Error(err.Error())
} }
a.SendDiagnostic(TRACK_CHANNEL_MODERATION, map[string]interface{}{ s.SendDiagnostic(TRACK_CHANNEL_MODERATION, map[string]interface{}{
"channel_scheme_count": channelSchemeCount, "channel_scheme_count": channelSchemeCount,
"create_post_user_disabled_count": createPostUser, "create_post_user_disabled_count": createPostUser,

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

@@ -136,7 +136,7 @@ func TestSegmentDiagnostics(t *testing.T) {
t.Run("Send", func(t *testing.T) { t.Run("Send", func(t *testing.T) {
testValue := "test-send-value-6789" testValue := "test-send-value-6789"
th.App.SendDiagnostic("Testing Diagnostic", map[string]interface{}{ th.App.Srv().SendDiagnostic("Testing Diagnostic", map[string]interface{}{
"hey": testValue, "hey": testValue,
}) })
select { select {
@@ -151,7 +151,7 @@ func TestSegmentDiagnostics(t *testing.T) {
// Plugins remain disabled at this point // Plugins remain disabled at this point
t.Run("SendDailyDiagnosticsPluginsDisabled", func(t *testing.T) { t.Run("SendDailyDiagnosticsPluginsDisabled", func(t *testing.T) {
th.App.sendDailyDiagnostics(true) th.App.Srv().sendDailyDiagnostics(true)
var info []string var info []string
// Collect the info sent. // Collect the info sent.
@@ -203,7 +203,7 @@ func TestSegmentDiagnostics(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true })
t.Run("SendDailyDiagnostics", func(t *testing.T) { t.Run("SendDailyDiagnostics", func(t *testing.T) {
th.App.sendDailyDiagnostics(true) th.App.Srv().sendDailyDiagnostics(true)
var info []string var info []string
// Collect the info sent. // Collect the info sent.
@@ -252,7 +252,7 @@ func TestSegmentDiagnostics(t *testing.T) {
}) })
t.Run("SendDailyDiagnosticsNoSegmentKey", func(t *testing.T) { t.Run("SendDailyDiagnosticsNoSegmentKey", func(t *testing.T) {
th.App.SendDailyDiagnostics() th.App.Srv().SendDailyDiagnostics()
select { select {
case <-data: case <-data:
@@ -265,7 +265,7 @@ func TestSegmentDiagnostics(t *testing.T) {
t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) { t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = false })
th.App.sendDailyDiagnostics(true) th.App.Srv().sendDailyDiagnostics(true)
select { select {
case <-data: case <-data:
@@ -363,7 +363,7 @@ func TestRudderDiagnostics(t *testing.T) {
t.Run("Send", func(t *testing.T) { t.Run("Send", func(t *testing.T) {
testValue := "test-send-value-6789" testValue := "test-send-value-6789"
th.App.SendDiagnostic("Testing Diagnostic", map[string]interface{}{ th.App.Srv().SendDiagnostic("Testing Diagnostic", map[string]interface{}{
"hey": testValue, "hey": testValue,
}) })
select { select {
@@ -378,7 +378,7 @@ func TestRudderDiagnostics(t *testing.T) {
// Plugins remain disabled at this point // Plugins remain disabled at this point
t.Run("SendDailyDiagnosticsPluginsDisabled", func(t *testing.T) { t.Run("SendDailyDiagnosticsPluginsDisabled", func(t *testing.T) {
th.App.sendDailyDiagnostics(true) th.App.Srv().sendDailyDiagnostics(true)
var info []string var info []string
// Collect the info sent. // Collect the info sent.
@@ -420,7 +420,7 @@ func TestRudderDiagnostics(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true })
t.Run("SendDailyDiagnostics", func(t *testing.T) { t.Run("SendDailyDiagnostics", func(t *testing.T) {
th.App.sendDailyDiagnostics(true) th.App.Srv().sendDailyDiagnostics(true)
var info []string var info []string
// Collect the info sent. // Collect the info sent.
@@ -459,7 +459,7 @@ func TestRudderDiagnostics(t *testing.T) {
}) })
t.Run("SendDailyDiagnosticsNoRudderKey", func(t *testing.T) { t.Run("SendDailyDiagnosticsNoRudderKey", func(t *testing.T) {
th.App.SendDailyDiagnostics() th.App.Srv().SendDailyDiagnostics()
select { select {
case <-data: case <-data:
@@ -472,7 +472,7 @@ func TestRudderDiagnostics(t *testing.T) {
t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) { t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = false })
th.App.sendDailyDiagnostics(true) th.App.Srv().sendDailyDiagnostics(true)
select { select {
case <-data: case <-data:

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

@@ -39,7 +39,7 @@ func condenseSiteURL(siteURL string) string {
return path.Join(parsedSiteURL.Host, parsedSiteURL.Path) return path.Join(parsedSiteURL.Host, parsedSiteURL.Path)
} }
func (a *App) SetupInviteEmailRateLimiting() error { func (s *Server) setupInviteEmailRateLimiting() error {
store, err := memstore.New(emailRateLimitingMemstoreSize) store, err := memstore.New(emailRateLimitingMemstoreSize)
if err != nil { if err != nil {
return errors.Wrap(err, "Unable to setup email rate limiting memstore.") return errors.Wrap(err, "Unable to setup email rate limiting memstore.")
@@ -55,7 +55,7 @@ func (a *App) SetupInviteEmailRateLimiting() error {
return errors.Wrap(err, "Unable to setup email rate limiting GCRA rate limiter.") return errors.Wrap(err, "Unable to setup email rate limiting GCRA rate limiter.")
} }
a.Srv().EmailRateLimiter = rateLimiter s.EmailRateLimiter = rateLimiter
return nil return nil
} }
@@ -463,8 +463,8 @@ func (a *App) sendGuestInviteEmails(team *model.Team, channels []*model.Channel,
} }
} }
func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate { func (s *Server) newEmailTemplate(name, locale string) *utils.HTMLTemplate {
t := utils.NewHTMLTemplate(a.HTMLTemplates(), name) t := utils.NewHTMLTemplate(s.HTMLTemplates(), name)
var localT i18n.TranslateFunc var localT i18n.TranslateFunc
if locale != "" { if locale != "" {
@@ -475,8 +475,8 @@ func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate {
t.Props["Footer"] = localT("api.templates.email_footer") t.Props["Footer"] = localT("api.templates.email_footer")
if *a.Config().EmailSettings.FeedbackOrganization != "" { if *s.Config().EmailSettings.FeedbackOrganization != "" {
t.Props["Organization"] = localT("api.templates.email_organization") + *a.Config().EmailSettings.FeedbackOrganization t.Props["Organization"] = localT("api.templates.email_organization") + *s.Config().EmailSettings.FeedbackOrganization
} else { } else {
t.Props["Organization"] = "" t.Props["Organization"] = ""
} }
@@ -484,12 +484,16 @@ func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate {
t.Props["EmailInfo1"] = localT("api.templates.email_info1") t.Props["EmailInfo1"] = localT("api.templates.email_info1")
t.Props["EmailInfo2"] = localT("api.templates.email_info2") t.Props["EmailInfo2"] = localT("api.templates.email_info2")
t.Props["EmailInfo3"] = localT("api.templates.email_info3", t.Props["EmailInfo3"] = localT("api.templates.email_info3",
map[string]interface{}{"SiteName": a.Config().TeamSettings.SiteName}) map[string]interface{}{"SiteName": s.Config().TeamSettings.SiteName})
t.Props["SupportEmail"] = *a.Config().SupportSettings.SupportEmail t.Props["SupportEmail"] = *s.Config().SupportSettings.SupportEmail
return t return t
} }
func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate {
return a.Srv().newEmailTemplate(name, locale)
}
func (a *App) SendDeactivateAccountEmail(email string, locale, siteURL string) *model.AppError { func (a *App) SendDeactivateAccountEmail(email string, locale, siteURL string) *model.AppError {
T := utils.GetUserTranslations(locale) T := utils.GetUserTranslations(locale)
@@ -531,21 +535,33 @@ func (a *App) SendRemoveExpiredLicenseEmail(email string, locale, siteURL string
return nil return nil
} }
func (a *App) sendNotificationMail(to, subject, htmlBody string) *model.AppError { func (s *Server) sendNotificationMail(to, subject, htmlBody string) *model.AppError {
if !*a.Config().EmailSettings.SendEmailNotifications { if !*s.Config().EmailSettings.SendEmailNotifications {
return nil return nil
} }
return a.sendMail(to, subject, htmlBody) return s.sendMail(to, subject, htmlBody)
}
func (a *App) sendNotificationMail(to, subject, htmlBody string) *model.AppError {
return a.Srv().sendNotificationMail(to, subject, htmlBody)
}
func (s *Server) sendMail(to, subject, htmlBody string) *model.AppError {
license := s.License()
return mailservice.SendMailUsingConfig(to, subject, htmlBody, s.Config(), license != nil && *license.Features.Compliance)
} }
func (a *App) sendMail(to, subject, htmlBody string) *model.AppError { func (a *App) sendMail(to, subject, htmlBody string) *model.AppError {
license := a.License() return a.Srv().sendMail(to, subject, htmlBody)
return mailservice.SendMailUsingConfig(to, subject, htmlBody, a.Config(), license != nil && *license.Features.Compliance)
} }
func (a *App) sendMailWithEmbeddedFiles(to, subject, htmlBody string, embeddedFiles map[string]io.Reader) *model.AppError { func (s *Server) sendMailWithEmbeddedFiles(to, subject, htmlBody string, embeddedFiles map[string]io.Reader) *model.AppError {
license := a.License() license := s.License()
config := a.Config() config := s.Config()
return mailservice.SendMailWithEmbeddedFilesUsingConfig(to, subject, htmlBody, embeddedFiles, config, license != nil && *license.Features.Compliance) return mailservice.SendMailWithEmbeddedFilesUsingConfig(to, subject, htmlBody, embeddedFiles, config, license != nil && *license.Features.Compliance)
} }
func (a *App) sendMailWithEmbeddedFiles(to, subject, htmlBody string, embeddedFiles map[string]io.Reader) *model.AppError {
return a.Srv().sendMailWithEmbeddedFiles(to, subject, htmlBody, embeddedFiles)
}

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

@@ -235,12 +235,12 @@ func (s *Server) sendBatchedEmailNotification(userId string, notifications []*ba
"Day": tm.Day(), "Day": tm.Day(),
}) })
body := s.FakeApp().newEmailTemplate("post_batched_body", user.Locale) body := s.newEmailTemplate("post_batched_body", user.Locale)
body.Props["SiteURL"] = *s.Config().ServiceSettings.SiteURL body.Props["SiteURL"] = *s.Config().ServiceSettings.SiteURL
body.Props["Posts"] = template.HTML(contents) body.Props["Posts"] = template.HTML(contents)
body.Props["BodyText"] = translateFunc("api.email_batching.send_batched_email_notification.body_text", len(notifications)) body.Props["BodyText"] = translateFunc("api.email_batching.send_batched_email_notification.body_text", len(notifications))
if err := s.FakeApp().sendNotificationMail(user.Email, subject, body.Render()); err != nil { if err := s.sendNotificationMail(user.Email, subject, body.Render()); err != nil {
mlog.Warn("Unable to send batched email notification", mlog.String("email", user.Email), mlog.Err(err)) mlog.Warn("Unable to send batched email notification", mlog.String("email", user.Email), mlog.Err(err))
} }
} }
@@ -249,13 +249,13 @@ func (s *Server) renderBatchedPost(notification *batchedNotification, channel *m
// don't include message contents if email notification contents type is set to generic // don't include message contents if email notification contents type is set to generic
var template *utils.HTMLTemplate var template *utils.HTMLTemplate
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
template = s.FakeApp().newEmailTemplate("post_batched_post_full", userLocale) template = s.newEmailTemplate("post_batched_post_full", userLocale)
} else { } else {
template = s.FakeApp().newEmailTemplate("post_batched_post_generic", userLocale) template = s.newEmailTemplate("post_batched_post_generic", userLocale)
} }
template.Props["Button"] = translateFunc("api.email_batching.render_batched_post.go_to_post") template.Props["Button"] = translateFunc("api.email_batching.render_batched_post.go_to_post")
template.Props["PostMessage"] = s.FakeApp().GetMessageForNotification(notification.post, translateFunc) template.Props["PostMessage"] = s.GetMessageForNotification(notification.post, translateFunc)
template.Props["PostLink"] = siteURL + "/" + notification.teamName + "/pl/" + notification.post.Id template.Props["PostLink"] = siteURL + "/" + notification.teamName + "/pl/" + notification.post.Id
template.Props["SenderName"] = sender.GetDisplayName(displayNameFormat) template.Props["SenderName"] = sender.GetDisplayName(displayNameFormat)

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

@@ -12,9 +12,9 @@ import (
"github.com/mattermost/mattermost-server/v5/services/searchengine" "github.com/mattermost/mattermost-server/v5/services/searchengine"
) )
var accountMigrationInterface func(*Server) einterfaces.AccountMigrationInterface var accountMigrationInterface func(*App) einterfaces.AccountMigrationInterface
func RegisterAccountMigrationInterface(f func(*Server) einterfaces.AccountMigrationInterface) { func RegisterAccountMigrationInterface(f func(*App) einterfaces.AccountMigrationInterface) {
accountMigrationInterface = f accountMigrationInterface = f
} }
@@ -130,43 +130,45 @@ func (s *Server) initEnterprise() {
if metricsInterface != nil { if metricsInterface != nil {
s.Metrics = metricsInterface(s) s.Metrics = metricsInterface(s)
} }
if accountMigrationInterface != nil {
s.AccountMigration = accountMigrationInterface(s)
}
if complianceInterface != nil { if complianceInterface != nil {
s.Compliance = complianceInterface(s) s.Compliance = complianceInterface(s)
} }
if ldapInterface != nil {
s.Ldap = ldapInterface(s.FakeApp())
}
if messageExportInterface != nil { if messageExportInterface != nil {
s.MessageExport = messageExportInterface(s) s.MessageExport = messageExportInterface(s)
} }
if notificationInterface != nil {
s.Notification = notificationInterface(s.FakeApp())
}
if samlInterface != nil {
if *s.FakeApp().Config().ExperimentalSettings.UseNewSAMLLibrary && samlInterfaceNew != nil {
mlog.Debug("Loading new SAML2 library")
s.Saml = samlInterfaceNew(s.FakeApp())
} else {
mlog.Debug("Loading original SAML library")
s.Saml = samlInterface(s.FakeApp())
}
s.AddConfigListener(func(_, cfg *model.Config) {
if err := s.Saml.ConfigureSP(); err != nil {
mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
}
})
}
if dataRetentionInterface != nil { if dataRetentionInterface != nil {
s.DataRetention = dataRetentionInterface(s) s.DataRetention = dataRetentionInterface(s)
} }
if clusterInterface != nil { if clusterInterface != nil {
s.Cluster = clusterInterface(s) s.Cluster = clusterInterface(s)
} }
if elasticsearchInterface != nil { if elasticsearchInterface != nil {
s.SearchEngine.RegisterElasticsearchEngine(elasticsearchInterface(s)) s.SearchEngine.RegisterElasticsearchEngine(elasticsearchInterface(s))
} }
} }
func (a *App) initEnterprise() {
if accountMigrationInterface != nil {
a.srv.AccountMigration = accountMigrationInterface(a)
}
if ldapInterface != nil {
a.srv.Ldap = ldapInterface(a)
}
if notificationInterface != nil {
a.srv.Notification = notificationInterface(a)
}
if samlInterface != nil {
if *a.Config().ExperimentalSettings.UseNewSAMLLibrary && samlInterfaceNew != nil {
mlog.Debug("Loading new SAML2 library")
a.srv.Saml = samlInterfaceNew(a)
} else {
mlog.Debug("Loading original SAML library")
a.srv.Saml = samlInterface(a)
}
a.AddConfigListener(func(_, cfg *model.Config) {
if err := a.srv.Saml.ConfigureSP(); err != nil {
mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
}
})
}
}

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

@@ -118,6 +118,7 @@ func TestSAMLSettings(t *testing.T) {
} }
th.Server.initEnterprise() th.Server.initEnterprise()
th.App.initEnterprise()
if tc.isNil { if tc.isNil {
assert.Nil(t, th.App.Srv().Saml) assert.Nil(t, th.App.Srv().Saml)
} else { } else {

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

@@ -80,7 +80,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
} }
th := &TestHelper{ th := &TestHelper{
App: s.FakeApp(), App: New(ServerConnector(s)),
Server: s, Server: s,
LogBuffer: buffer, LogBuffer: buffer,
IncludeCacheLayer: includeCacheLayer, IncludeCacheLayer: includeCacheLayer,
@@ -113,15 +113,17 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
}) })
if enterprise { if enterprise {
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
} else { } else {
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
} }
if th.tempWorkspace == "" { if th.tempWorkspace == "" {
th.tempWorkspace = tempWorkspace th.tempWorkspace = tempWorkspace
} }
th.App.InitServer()
return th return th
} }
@@ -584,7 +586,7 @@ func (me *TestHelper) ShutdownApp() {
func (me *TestHelper) TearDown() { func (me *TestHelper) TearDown() {
if me.IncludeCacheLayer { if me.IncludeCacheLayer {
// Clean all the caches // Clean all the caches
me.App.InvalidateAllCaches() me.App.Srv().InvalidateAllCaches()
} }
me.ShutdownApp() me.ShutdownApp()
if me.tempWorkspace != "" { if me.tempWorkspace != "" {

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

@@ -14,7 +14,7 @@ import (
func (a *App) SyncLdap() { func (a *App) SyncLdap() {
a.Srv().Go(func() { a.Srv().Go(func() {
if license := a.License(); license != nil && *license.Features.LDAP && *a.Config().LdapSettings.EnableSync { if license := a.Srv().License(); license != nil && *license.Features.LDAP && *a.Config().LdapSettings.EnableSync {
if ldapI := a.Ldap(); ldapI != nil { if ldapI := a.Ldap(); ldapI != nil {
ldapI.StartSynchronizeJob(false) ldapI.StartSynchronizeJob(false)
} else { } else {
@@ -25,7 +25,7 @@ func (a *App) SyncLdap() {
} }
func (a *App) TestLdap() *model.AppError { func (a *App) TestLdap() *model.AppError {
license := a.License() license := a.Srv().License()
if ldapI := a.Ldap(); ldapI != nil && license != nil && *license.Features.LDAP && (*a.Config().LdapSettings.Enable || *a.Config().LdapSettings.EnableSync) { if ldapI := a.Ldap(); ldapI != nil && license != nil && *license.Features.LDAP && (*a.Config().LdapSettings.Enable || *a.Config().LdapSettings.EnableSync) {
if err := ldapI.RunTest(); err != nil { if err := ldapI.RunTest(); err != nil {
err.StatusCode = 500 err.StatusCode = 500
@@ -80,7 +80,7 @@ func (a *App) GetAllLdapGroupsPage(page int, perPage int, opts model.LdapGroupSe
} }
func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) { func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) {
if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer {
return "", model.NewAppError("emailToLdap", "api.user.email_to_ldap.not_available.app_error", nil, "", http.StatusForbidden) return "", model.NewAppError("emailToLdap", "api.user.email_to_ldap.not_available.app_error", nil, "", http.StatusForbidden)
} }
@@ -116,7 +116,7 @@ func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword
} }
func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) { func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) {
if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer {
return "", model.NewAppError("ldapToEmail", "api.user.ldap_to_email.not_available.app_error", nil, "", http.StatusForbidden) return "", model.NewAppError("ldapToEmail", "api.user.ldap_to_email.not_available.app_error", nil, "", http.StatusForbidden)
} }

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

@@ -15,19 +15,19 @@ import (
const requestTrialURL = "https://customers.mattermost.com/api/v1/trials" const requestTrialURL = "https://customers.mattermost.com/api/v1/trials"
func (a *App) LoadLicense() { func (s *Server) LoadLicense() {
licenseId := "" licenseId := ""
props, err := a.Srv().Store.System().Get() props, err := s.Store.System().Get()
if err == nil { if err == nil {
licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID] licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID]
} }
if !model.IsValidId(licenseId) { if !model.IsValidId(licenseId) {
// Lets attempt to load the file from disk since it was missing from the DB // Lets attempt to load the file from disk since it was missing from the DB
license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk(*a.Config().ServiceSettings.LicenseFileLocation) license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk(*s.Config().ServiceSettings.LicenseFileLocation)
if license != nil { if license != nil {
if _, err = a.SaveLicense(licenseBytes); err != nil { if _, err = s.SaveLicense(licenseBytes); err != nil {
mlog.Info("Failed to save license key loaded from disk.", mlog.Err(err)) mlog.Info("Failed to save license key loaded from disk.", mlog.Err(err))
} else { } else {
licenseId = license.Id licenseId = license.Id
@@ -35,25 +35,25 @@ func (a *App) LoadLicense() {
} }
} }
record, err := a.Srv().Store.License().Get(licenseId) record, err := s.Store.License().Get(licenseId)
if err != nil { if err != nil {
mlog.Info("License key from https://mattermost.com required to unlock enterprise features.") mlog.Info("License key from https://mattermost.com required to unlock enterprise features.")
a.SetLicense(nil) s.SetLicense(nil)
return return
} }
a.ValidateAndSetLicenseBytes([]byte(record.Bytes)) s.ValidateAndSetLicenseBytes([]byte(record.Bytes))
mlog.Info("License key valid unlocking enterprise features.") mlog.Info("License key valid unlocking enterprise features.")
} }
func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) {
success, licenseStr := utils.ValidateLicense(licenseBytes) success, licenseStr := utils.ValidateLicense(licenseBytes)
if !success { if !success {
return nil, model.NewAppError("addLicense", model.INVALID_LICENSE_ERROR, nil, "", http.StatusBadRequest) return nil, model.NewAppError("addLicense", model.INVALID_LICENSE_ERROR, nil, "", http.StatusBadRequest)
} }
license := model.LicenseFromJson(strings.NewReader(licenseStr)) license := model.LicenseFromJson(strings.NewReader(licenseStr))
uniqueUserCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) uniqueUserCount, err := s.Store.User().Count(model.UserCountOptions{})
if err != nil { if err != nil {
return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, err.Error(), http.StatusBadRequest) return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, err.Error(), http.StatusBadRequest)
} }
@@ -66,7 +66,7 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError)
return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest) return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest)
} }
if ok := a.SetLicense(license); !ok { if ok := s.SetLicense(license); !ok {
return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest) return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest)
} }
@@ -74,46 +74,41 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError)
record.Id = license.Id record.Id = license.Id
record.Bytes = string(licenseBytes) record.Bytes = string(licenseBytes)
_, err = a.Srv().Store.License().Save(record) _, err = s.Store.License().Save(record)
if err != nil { if err != nil {
a.RemoveLicense() s.RemoveLicense()
return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "err="+err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "err="+err.Error(), http.StatusInternalServerError)
} }
sysVar := &model.System{} sysVar := &model.System{}
sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID
sysVar.Value = license.Id sysVar.Value = license.Id
if err := a.Srv().Store.System().SaveOrUpdate(sysVar); err != nil { if err := s.Store.System().SaveOrUpdate(sysVar); err != nil {
a.RemoveLicense() s.RemoveLicense()
return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError) return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError)
} }
a.ReloadConfig() s.ReloadConfig()
a.InvalidateAllCaches() s.InvalidateAllCaches()
// start job server if necessary - this handles the edge case where a license file is uploaded, but the job server // start job server if necessary - this handles the edge case where a license file is uploaded, but the job server
// doesn't start until the server is restarted, which prevents the 'run job now' buttons in system console from // doesn't start until the server is restarted, which prevents the 'run job now' buttons in system console from
// functioning as expected // functioning as expected
if *a.Config().JobSettings.RunJobs && a.Srv().Jobs != nil && a.Srv().Jobs.Workers != nil { if *s.Config().JobSettings.RunJobs && s.Jobs != nil && s.Jobs.Workers != nil {
a.Srv().Jobs.StartWorkers() s.Jobs.StartWorkers()
} }
if *a.Config().JobSettings.RunScheduler && a.Srv().Jobs != nil && a.Srv().Jobs.Schedulers != nil { if *s.Config().JobSettings.RunScheduler && s.Jobs != nil && s.Jobs.Schedulers != nil {
a.Srv().Jobs.StartSchedulers() s.Jobs.StartSchedulers()
} }
return license, nil return license, nil
} }
// License returns the currently active license or nil if the application is unlicensed. func (s *Server) SetLicense(license *model.License) bool {
func (a *App) License() *model.License { oldLicense := s.licenseValue.Load()
return a.Srv().License()
}
func (a *App) SetLicense(license *model.License) bool {
oldLicense := a.Srv().licenseValue.Load()
defer func() { defer func() {
for _, listener := range a.Srv().licenseListeners { for _, listener := range s.licenseListeners {
if oldLicense == nil { if oldLicense == nil {
listener(nil, license) listener(nil, license)
} else { } else {
@@ -125,39 +120,39 @@ func (a *App) SetLicense(license *model.License) bool {
if license != nil { if license != nil {
license.Features.SetDefaults() license.Features.SetDefaults()
a.Srv().licenseValue.Store(license) s.licenseValue.Store(license)
a.Srv().clientLicenseValue.Store(utils.GetClientLicense(license)) s.clientLicenseValue.Store(utils.GetClientLicense(license))
return true return true
} }
a.Srv().licenseValue.Store((*model.License)(nil)) s.licenseValue.Store((*model.License)(nil))
a.Srv().clientLicenseValue.Store(map[string]string(nil)) s.clientLicenseValue.Store(map[string]string(nil))
return false return false
} }
func (a *App) ValidateAndSetLicenseBytes(b []byte) { func (s *Server) ValidateAndSetLicenseBytes(b []byte) {
if success, licenseStr := utils.ValidateLicense(b); success { if success, licenseStr := utils.ValidateLicense(b); success {
license := model.LicenseFromJson(strings.NewReader(licenseStr)) license := model.LicenseFromJson(strings.NewReader(licenseStr))
a.SetLicense(license) s.SetLicense(license)
return return
} }
mlog.Warn("No valid enterprise license found") mlog.Warn("No valid enterprise license found")
} }
func (a *App) SetClientLicense(m map[string]string) { func (s *Server) SetClientLicense(m map[string]string) {
a.Srv().clientLicenseValue.Store(m) s.clientLicenseValue.Store(m)
} }
func (a *App) ClientLicense() map[string]string { func (s *Server) ClientLicense() map[string]string {
if clientLicense, _ := a.Srv().clientLicenseValue.Load().(map[string]string); clientLicense != nil { if clientLicense, _ := s.clientLicenseValue.Load().(map[string]string); clientLicense != nil {
return clientLicense return clientLicense
} }
return map[string]string{"IsLicensed": "false"} return map[string]string{"IsLicensed": "false"}
} }
func (a *App) RemoveLicense() *model.AppError { func (s *Server) RemoveLicense() *model.AppError {
if license, _ := a.Srv().licenseValue.Load().(*model.License); license == nil { if license, _ := s.licenseValue.Load().(*model.License); license == nil {
return nil return nil
} }
@@ -167,14 +162,13 @@ func (a *App) RemoveLicense() *model.AppError {
sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID
sysVar.Value = "" sysVar.Value = ""
if err := a.Srv().Store.System().SaveOrUpdate(sysVar); err != nil { if err := s.Store.System().SaveOrUpdate(sysVar); err != nil {
return err return err
} }
a.SetLicense(nil) s.SetLicense(nil)
a.ReloadConfig() s.ReloadConfig()
s.InvalidateAllCaches()
a.InvalidateAllCaches()
return nil return nil
} }
@@ -185,24 +179,14 @@ func (s *Server) AddLicenseListener(listener func(oldLicense, newLicense *model.
return id return id
} }
func (a *App) AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string {
id := model.NewId()
a.Srv().licenseListeners[id] = listener
return id
}
func (s *Server) RemoveLicenseListener(id string) { func (s *Server) RemoveLicenseListener(id string) {
delete(s.licenseListeners, id) delete(s.licenseListeners, id)
} }
func (a *App) RemoveLicenseListener(id string) { func (s *Server) GetSanitizedClientLicense() map[string]string {
delete(a.Srv().licenseListeners, id)
}
func (a *App) GetSanitizedClientLicense() map[string]string {
sanitizedLicense := make(map[string]string) sanitizedLicense := make(map[string]string)
for k, v := range a.ClientLicense() { for k, v := range s.ClientLicense() {
sanitizedLicense[k] = v sanitizedLicense[k] = v
} }
@@ -219,7 +203,7 @@ func (a *App) GetSanitizedClientLicense() map[string]string {
} }
// RequestTrialLicense request a trial license from the mattermost offical license server // RequestTrialLicense request a trial license from the mattermost offical license server
func (a *App) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError { func (s *Server) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError {
resp, err := http.Post(requestTrialURL, "application/json", bytes.NewBuffer([]byte(trialRequest.ToJson()))) resp, err := http.Post(requestTrialURL, "application/json", bytes.NewBuffer([]byte(trialRequest.ToJson())))
if err != nil { if err != nil {
return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, err.Error(), http.StatusBadRequest) return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, err.Error(), http.StatusBadRequest)
@@ -227,12 +211,12 @@ func (a *App) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *mode
defer resp.Body.Close() defer resp.Body.Close()
licenseResponse := model.MapFromJson(resp.Body) licenseResponse := model.MapFromJson(resp.Body)
if _, err := a.SaveLicense([]byte(licenseResponse["license"])); err != nil { if _, err := s.SaveLicense([]byte(licenseResponse["license"])); err != nil {
return err return err
} }
a.ReloadConfig() s.ReloadConfig()
a.InvalidateAllCaches() s.InvalidateAllCaches()
return nil return nil
} }

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

@@ -15,8 +15,8 @@ func TestLoadLicense(t *testing.T) {
th := Setup(t) th := Setup(t)
defer th.TearDown() defer th.TearDown()
th.App.LoadLicense() th.App.Srv().LoadLicense()
require.Nil(t, th.App.License(), "shouldn't have a valid license") require.Nil(t, th.App.Srv().License(), "shouldn't have a valid license")
} }
func TestSaveLicense(t *testing.T) { func TestSaveLicense(t *testing.T) {
@@ -25,7 +25,7 @@ func TestSaveLicense(t *testing.T) {
b1 := []byte("junk") b1 := []byte("junk")
_, err := th.App.SaveLicense(b1) _, err := th.App.Srv().SaveLicense(b1)
require.NotNil(t, err, "shouldn't have saved license") require.NotNil(t, err, "shouldn't have saved license")
} }
@@ -33,7 +33,7 @@ func TestRemoveLicense(t *testing.T) {
th := Setup(t) th := Setup(t)
defer th.TearDown() defer th.TearDown()
err := th.App.RemoveLicense() err := th.App.Srv().RemoveLicense()
require.Nil(t, err, "should have removed license") require.Nil(t, err, "should have removed license")
} }
@@ -46,7 +46,7 @@ func TestSetLicense(t *testing.T) {
l1.Customer = &model.Customer{} l1.Customer = &model.Customer{}
l1.StartsAt = model.GetMillis() - 1000 l1.StartsAt = model.GetMillis() - 1000
l1.ExpiresAt = model.GetMillis() + 100000 l1.ExpiresAt = model.GetMillis() + 100000
ok := th.App.SetLicense(l1) ok := th.App.Srv().SetLicense(l1)
require.True(t, ok, "license should have worked") require.True(t, ok, "license should have worked")
l3 := &model.License{} l3 := &model.License{}
@@ -54,7 +54,7 @@ func TestSetLicense(t *testing.T) {
l3.Customer = &model.Customer{} l3.Customer = &model.Customer{}
l3.StartsAt = model.GetMillis() + 10000 l3.StartsAt = model.GetMillis() + 10000
l3.ExpiresAt = model.GetMillis() + 100000 l3.ExpiresAt = model.GetMillis() + 100000
ok = th.App.SetLicense(l3) ok = th.App.Srv().SetLicense(l3)
require.True(t, ok, "license should have passed") require.True(t, ok, "license should have passed")
} }
@@ -70,9 +70,9 @@ func TestGetSanitizedClientLicense(t *testing.T) {
l1.SkuShortName = "SKU SHORT NAME" l1.SkuShortName = "SKU SHORT NAME"
l1.StartsAt = model.GetMillis() - 1000 l1.StartsAt = model.GetMillis() - 1000
l1.ExpiresAt = model.GetMillis() + 100000 l1.ExpiresAt = model.GetMillis() + 100000
th.App.SetLicense(l1) th.App.Srv().SetLicense(l1)
m := th.App.GetSanitizedClientLicense() m := th.App.Srv().GetSanitizedClientLicense()
_, ok := m["Name"] _, ok := m["Name"]
assert.False(t, ok) assert.False(t, ok)

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

@@ -25,7 +25,7 @@ func (a *App) DoAdvancedPermissionsMigration() {
mlog.Info("Migrating roles to database.") mlog.Info("Migrating roles to database.")
roles := model.MakeDefaultRoles() roles := model.MakeDefaultRoles()
roles = utils.SetRolePermissionsFromConfig(roles, a.Config(), a.License() != nil) roles = utils.SetRolePermissionsFromConfig(roles, a.Config(), a.Srv().License() != nil)
allSucceeded := true allSucceeded := true

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

@@ -250,7 +250,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
sendPushNotifications := false sendPushNotifications := false
if *a.Config().EmailSettings.SendPushNotifications { if *a.Config().EmailSettings.SendPushNotifications {
pushServer := *a.Config().EmailSettings.PushNotificationServer pushServer := *a.Config().EmailSettings.PushNotificationServer
if license := a.License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) { if license := a.Srv().License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) {
mlog.Warn("Push notifications are disabled. Go to System Console > Notifications > Mobile Push to enable them.") mlog.Warn("Push notifications are disabled. Go to System Console > Notifications > Mobile Push to enable them.")
sendPushNotifications = false sendPushNotifications = false
} else { } else {
@@ -737,7 +737,7 @@ func (a *App) allowChannelMentions(post *model.Post, numProfiles int) bool {
// allowGroupMentions returns whether or not the group mentions are allowed for the given post. // allowGroupMentions returns whether or not the group mentions are allowed for the given post.
func (a *App) allowGroupMentions(post *model.Post) bool { func (a *App) allowGroupMentions(post *model.Post) bool {
if license := a.License(); license == nil || !*license.Features.LDAPGroups { if license := a.Srv().License(); license == nil || !*license.Features.LDAPGroups {
return false return false
} }

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

@@ -80,7 +80,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model.
senderName := notification.GetSenderName(nameFormat, *a.Config().ServiceSettings.EnablePostUsernameOverride) senderName := notification.GetSenderName(nameFormat, *a.Config().ServiceSettings.EnablePostUsernameOverride)
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
if license := a.License(); license != nil && *license.Features.EmailNotificationContents { if license := a.Srv().License(); license != nil && *license.Features.EmailNotificationContents {
emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType
} }
@@ -312,13 +312,13 @@ func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string
return postMessage return postMessage
} }
func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string { func (s *Server) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string {
if len(strings.TrimSpace(post.Message)) != 0 || len(post.FileIds) == 0 { if len(strings.TrimSpace(post.Message)) != 0 || len(post.FileIds) == 0 {
return post.Message return post.Message
} }
// extract the filenames from their paths and determine what type of files are attached // extract the filenames from their paths and determine what type of files are attached
infos, err := a.Srv().Store.FileInfo().GetForPost(post.Id, true, false, true) infos, err := s.Store.FileInfo().GetForPost(post.Id, true, false, true)
if err != nil { if err != nil {
mlog.Warn("Encountered error when getting files for notification message", mlog.String("post_id", post.Id), mlog.Err(err)) mlog.Warn("Encountered error when getting files for notification message", mlog.String("post_id", post.Id), mlog.Err(err))
} }
@@ -343,3 +343,7 @@ func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.Tra
} }
return translateFunc("api.post.get_message_for_notification.files_sent", len(filenames), props) return translateFunc("api.post.get_message_for_notification.files_sent", len(filenames), props)
} }
func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string {
return a.Srv().GetMessageForNotification(post, translateFunc)
}

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

@@ -252,14 +252,14 @@ func (a *App) UpdateMobileAppBadge(userId string) {
} }
} }
func (a *App) createPushNotificationsHub() { func (s *Server) createPushNotificationsHub() {
hub := PushNotificationsHub{ hub := PushNotificationsHub{
Channels: []chan PushNotification{}, Channels: []chan PushNotification{},
} }
for x := 0; x < PUSH_NOTIFICATION_HUB_WORKERS; x++ { for x := 0; x < PUSH_NOTIFICATION_HUB_WORKERS; x++ {
hub.Channels = append(hub.Channels, make(chan PushNotification, PUSH_NOTIFICATIONS_HUB_BUFFER_PER_WORKER)) hub.Channels = append(hub.Channels, make(chan PushNotification, PUSH_NOTIFICATIONS_HUB_BUFFER_PER_WORKER))
} }
a.Srv().PushNotificationsHub = hub s.PushNotificationsHub = hub
} }
func (a *App) pushNotificationWorker(notifications chan PushNotification) { func (a *App) pushNotificationWorker(notifications chan PushNotification) {
@@ -298,8 +298,8 @@ func (a *App) StartPushNotificationsHubWorkers() {
} }
} }
func (a *App) StopPushNotificationsHubWorkers() { func (s *Server) StopPushNotificationsHubWorkers() {
for _, channel := range a.Srv().PushNotificationsHub.Channels { for _, channel := range s.PushNotificationsHub.Channels {
close(channel) close(channel)
} }
} }

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

@@ -50,7 +50,7 @@ func TestSendNotifications(t *testing.T) {
_, appErr = th.App.UpdateActive(th.BasicUser2, false) _, appErr = th.App.UpdateActive(th.BasicUser2, false)
require.Nil(t, appErr) require.Nil(t, appErr)
appErr = th.App.InvalidateAllCaches() appErr = th.App.Srv().InvalidateAllCaches()
require.Nil(t, appErr) require.Nil(t, appErr)
post3, appErr := th.App.CreatePostMissingChannel(&model.Post{ post3, appErr := th.App.CreatePostMissingChannel(&model.Post{
@@ -1004,7 +1004,7 @@ func TestAllowGroupMentions(t *testing.T) {
assert.False(t, allowGroupMentions) assert.False(t, allowGroupMentions)
}) })
th.App.SetLicense(model.NewTestLicense("ldap_groups")) th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups"))
t.Run("should return true for a regular post with few channel members", func(t *testing.T) { t.Run("should return true for a regular post with few channel members", func(t *testing.T) {
allowGroupMentions := th.App.allowGroupMentions(post) allowGroupMentions := th.App.allowGroupMentions(post)

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

@@ -66,7 +66,7 @@ func (a *App) DeleteOAuthApp(appId string) *model.AppError {
return err return err
} }
if err := a.InvalidateAllCaches(); err != nil { if err := a.Srv().InvalidateAllCaches(); err != nil {
mlog.Error("error in invalidating cache", mlog.Err(err)) mlog.Error("error in invalidating cache", mlog.Err(err))
} }
@@ -801,7 +801,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
} }
func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) { func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) {
if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer {
return "", model.NewAppError("emailToOAuth", "api.user.email_to_oauth.not_available.app_error", nil, "", http.StatusForbidden) return "", model.NewAppError("emailToOAuth", "api.user.email_to_oauth.not_available.app_error", nil, "", http.StatusForbidden)
} }
@@ -831,7 +831,7 @@ func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email,
} }
func (a *App) SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) { func (a *App) SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) {
if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer {
return "", model.NewAppError("oauthToEmail", "api.user.oauth_to_email.not_available.app_error", nil, "", http.StatusForbidden) return "", model.NewAppError("oauthToEmail", "api.user.oauth_to_email.not_available.app_error", nil, "", http.StatusForbidden)
} }

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

@@ -11,7 +11,6 @@ import (
"bytes" "bytes"
"context" "context"
"crypto/ecdsa" "crypto/ecdsa"
"html/template"
"io" "io"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
@@ -171,23 +170,6 @@ func (a *OpenTracingAppLayer) AddDirectChannels(teamId string, user *model.User)
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddLicenseListener")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.AddLicenseListener(listener)
return resultVar0
}
func (a *OpenTracingAppLayer) AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError { func (a *OpenTracingAppLayer) AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddNotificationEmailToBatch") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddNotificationEmailToBatch")
@@ -1296,23 +1278,6 @@ func (a *OpenTracingAppLayer) ClientConfigWithComputed() map[string]string {
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) ClientLicense() map[string]string {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClientLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.ClientLicense()
return resultVar0
}
func (a *OpenTracingAppLayer) CompareAndDeletePluginKey(pluginId string, key string, oldValue []byte) (bool, *model.AppError) { func (a *OpenTracingAppLayer) CompareAndDeletePluginKey(pluginId string, key string, oldValue []byte) (bool, *model.AppError) {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompareAndDeletePluginKey") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompareAndDeletePluginKey")
@@ -7298,23 +7263,6 @@ func (a *OpenTracingAppLayer) GetSanitizeOptions(asAdmin bool) map[string]bool {
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) GetSanitizedClientLicense() map[string]string {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSanitizedClientLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.GetSanitizedClientLicense()
return resultVar0
}
func (a *OpenTracingAppLayer) GetSanitizedConfig() *model.Config { func (a *OpenTracingAppLayer) GetSanitizedConfig() *model.Config {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSanitizedConfig") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSanitizedConfig")
@@ -8837,23 +8785,6 @@ func (a *OpenTracingAppLayer) GetViewUsersRestrictions(userId string) (*model.Vi
return resultVar0, resultVar1 return resultVar0, resultVar1
} }
func (a *OpenTracingAppLayer) HTMLTemplates() *template.Template {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HTMLTemplates")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.HTMLTemplates()
return resultVar0
}
func (a *OpenTracingAppLayer) Handle404(w http.ResponseWriter, r *http.Request) { func (a *OpenTracingAppLayer) Handle404(w http.ResponseWriter, r *http.Request) {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Handle404") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Handle404")
@@ -9218,6 +9149,21 @@ func (a *OpenTracingAppLayer) InitPostMetadata() {
a.app.InitPostMetadata() a.app.InitPostMetadata()
} }
func (a *OpenTracingAppLayer) InitServer() {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InitServer")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.InitServer()
}
func (a *OpenTracingAppLayer) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) { func (a *OpenTracingAppLayer) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InstallMarketplacePlugin") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InstallMarketplacePlugin")
@@ -9299,43 +9245,6 @@ func (a *OpenTracingAppLayer) InstallPluginWithSignature(pluginFile io.ReadSeeke
return resultVar0, resultVar1 return resultVar0, resultVar1
} }
func (a *OpenTracingAppLayer) InvalidateAllCaches() *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllCaches")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.InvalidateAllCaches()
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
ext.Error.Set(span, true)
}
return resultVar0
}
func (a *OpenTracingAppLayer) InvalidateAllCachesSkipSend() {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllCachesSkipSend")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.InvalidateAllCachesSkipSend()
}
func (a *OpenTracingAppLayer) InvalidateAllEmailInvites() *model.AppError { func (a *OpenTracingAppLayer) InvalidateAllEmailInvites() *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllEmailInvites") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllEmailInvites")
@@ -9720,23 +9629,6 @@ func (a *OpenTracingAppLayer) LeaveTeam(team *model.Team, user *model.User, requ
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) License() *model.License {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.License")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.License()
return resultVar0
}
func (a *OpenTracingAppLayer) LimitedClientConfig() map[string]string { func (a *OpenTracingAppLayer) LimitedClientConfig() map[string]string {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LimitedClientConfig") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LimitedClientConfig")
@@ -9883,21 +9775,6 @@ func (a *OpenTracingAppLayer) ListTeamCommands(teamId string) ([]*model.Command,
return resultVar0, resultVar1 return resultVar0, resultVar1
} }
func (a *OpenTracingAppLayer) LoadLicense() {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LoadLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.LoadLicense()
}
func (a *OpenTracingAppLayer) LogAuditRec(rec *audit.Record, err error) { func (a *OpenTracingAppLayer) LogAuditRec(rec *audit.Record, err error) {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LogAuditRec") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LogAuditRec")
@@ -11123,43 +11000,6 @@ func (a *OpenTracingAppLayer) RemoveFile(path string) *model.AppError {
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) RemoveLicense() *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.RemoveLicense()
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
ext.Error.Set(span, true)
}
return resultVar0
}
func (a *OpenTracingAppLayer) RemoveLicenseListener(id string) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveLicenseListener")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.RemoveLicenseListener(id)
}
func (a *OpenTracingAppLayer) RemovePlugin(id string) *model.AppError { func (a *OpenTracingAppLayer) RemovePlugin(id string) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemovePlugin") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemovePlugin")
@@ -11395,28 +11235,6 @@ func (a *OpenTracingAppLayer) RenameTeam(team *model.Team, newTeamName string, n
return resultVar0, resultVar1 return resultVar0, resultVar1
} }
func (a *OpenTracingAppLayer) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RequestTrialLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.RequestTrialLicense(trialRequest)
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
ext.Error.Set(span, true)
}
return resultVar0
}
func (a *OpenTracingAppLayer) ResetPasswordFromToken(userSuppliedTokenString string, newPassword string) *model.AppError { func (a *OpenTracingAppLayer) ResetPasswordFromToken(userSuppliedTokenString string, newPassword string) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ResetPasswordFromToken") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ResetPasswordFromToken")
@@ -11850,28 +11668,6 @@ func (a *OpenTracingAppLayer) SaveConfig(newCfg *model.Config, sendConfigChangeC
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.SaveLicense(licenseBytes)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
ext.Error.Set(span, true)
}
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) { func (a *OpenTracingAppLayer) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveReactionForPost") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveReactionForPost")
@@ -12434,21 +12230,6 @@ func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(channel *model.Channel
return resultVar0, resultVar1 return resultVar0, resultVar1
} }
func (a *OpenTracingAppLayer) SendDailyDiagnostics() {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDailyDiagnostics")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.SendDailyDiagnostics()
}
func (a *OpenTracingAppLayer) SendDeactivateAccountEmail(email string, locale string, siteURL string) *model.AppError { func (a *OpenTracingAppLayer) SendDeactivateAccountEmail(email string, locale string, siteURL string) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDeactivateAccountEmail") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDeactivateAccountEmail")
@@ -12471,21 +12252,6 @@ func (a *OpenTracingAppLayer) SendDeactivateAccountEmail(email string, locale st
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) SendDiagnostic(event string, properties map[string]interface{}) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDiagnostic")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.SendDiagnostic(event, properties)
}
func (a *OpenTracingAppLayer) SendEmailVerification(user *model.User, newEmail string) *model.AppError { func (a *OpenTracingAppLayer) SendEmailVerification(user *model.User, newEmail string) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendEmailVerification") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendEmailVerification")
@@ -12949,21 +12715,6 @@ func (a *OpenTracingAppLayer) SetBotIconImageFromMultiPartFile(botUserId string,
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) SetClientLicense(m map[string]string) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetClientLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.SetClientLicense(m)
}
func (a *OpenTracingAppLayer) SetDefaultProfileImage(user *model.User) *model.AppError { func (a *OpenTracingAppLayer) SetDefaultProfileImage(user *model.User) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetDefaultProfileImage") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetDefaultProfileImage")
@@ -13001,23 +12752,6 @@ func (a *OpenTracingAppLayer) SetDiagnosticId(id string) {
a.app.SetDiagnosticId(id) a.app.SetDiagnosticId(id)
} }
func (a *OpenTracingAppLayer) SetLicense(license *model.License) bool {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetLicense")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.SetLicense(license)
return resultVar0
}
func (a *OpenTracingAppLayer) SetLog(l *mlog.Logger) { func (a *OpenTracingAppLayer) SetLog(l *mlog.Logger) {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetLog") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetLog")
@@ -13395,43 +13129,6 @@ func (a *OpenTracingAppLayer) SetTeamIconFromMultiPartFile(teamId string, file m
return resultVar0 return resultVar0
} }
func (a *OpenTracingAppLayer) SetupInviteEmailRateLimiting() error {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetupInviteEmailRateLimiting")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0 := a.app.SetupInviteEmailRateLimiting()
if resultVar0 != nil {
span.LogFields(spanlog.Error(resultVar0))
ext.Error.Set(span, true)
}
return resultVar0
}
func (a *OpenTracingAppLayer) ShutDownPlugins() {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ShutDownPlugins")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.ShutDownPlugins()
}
func (a *OpenTracingAppLayer) Shutdown() { func (a *OpenTracingAppLayer) Shutdown() {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Shutdown") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Shutdown")
@@ -13589,21 +13286,6 @@ func (a *OpenTracingAppLayer) StartPushNotificationsHubWorkers() {
a.app.StartPushNotificationsHubWorkers() a.app.StartPushNotificationsHubWorkers()
} }
func (a *OpenTracingAppLayer) StopPushNotificationsHubWorkers() {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.StopPushNotificationsHubWorkers")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.StopPushNotificationsHubWorkers()
}
func (a *OpenTracingAppLayer) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) { func (a *OpenTracingAppLayer) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SubmitInteractiveDialog") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SubmitInteractiveDialog")
@@ -15140,21 +14822,6 @@ func (a *OpenTracingAppLayer) UserIsInAdminRoleGroup(userID string, syncableID s
return resultVar0, resultVar1 return resultVar0, resultVar1
} }
func (a *OpenTracingAppLayer) ValidateAndSetLicenseBytes(b []byte) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ValidateAndSetLicenseBytes")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
a.app.ValidateAndSetLicenseBytes(b)
}
func (a *OpenTracingAppLayer) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError { func (a *OpenTracingAppLayer) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError {
origCtx := a.ctx origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.VerifyEmailFromToken") span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.VerifyEmailFromToken")

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

@@ -105,11 +105,8 @@ func ServerConnector(s *Server) AppOption {
a.compliance = s.Compliance a.compliance = s.Compliance
a.dataRetention = s.DataRetention a.dataRetention = s.DataRetention
a.searchEngine = s.SearchEngine a.searchEngine = s.SearchEngine
a.ldap = s.Ldap
a.messageExport = s.MessageExport a.messageExport = s.MessageExport
a.metrics = s.Metrics a.metrics = s.Metrics
a.notification = s.Notification
a.saml = s.Saml
a.httpService = s.HTTPService a.httpService = s.HTTPService
a.imageProxy = s.ImageProxy a.imageProxy = s.ImageProxy

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

@@ -40,15 +40,24 @@ type pluginSignaturePath struct {
// //
// To get the plugins environment when the plugins are disabled, manually acquire the plugins // To get the plugins environment when the plugins are disabled, manually acquire the plugins
// lock instead. // lock instead.
func (a *App) GetPluginsEnvironment() *plugin.Environment { func (s *Server) GetPluginsEnvironment() *plugin.Environment {
if !*a.Config().PluginSettings.Enable { if !*s.Config().PluginSettings.Enable {
return nil return nil
} }
a.Srv().PluginsLock.RLock() s.PluginsLock.RLock()
defer a.Srv().PluginsLock.RUnlock() defer s.PluginsLock.RUnlock()
return a.Srv().PluginsEnvironment return s.PluginsEnvironment
}
// GetPluginsEnvironment returns the plugin environment for use if plugins are enabled and
// initialized.
//
// To get the plugins environment when the plugins are disabled, manually acquire the plugins
// lock instead.
func (a *App) GetPluginsEnvironment() *plugin.Environment {
return a.Srv().GetPluginsEnvironment()
} }
func (a *App) SetPluginsEnvironment(pluginsEnvironment *plugin.Environment) { func (a *App) SetPluginsEnvironment(pluginsEnvironment *plugin.Environment) {
@@ -270,8 +279,8 @@ func (a *App) SyncPlugins() *model.AppError {
return nil return nil
} }
func (a *App) ShutDownPlugins() { func (s *Server) ShutDownPlugins() {
pluginsEnvironment := a.GetPluginsEnvironment() pluginsEnvironment := s.GetPluginsEnvironment()
if pluginsEnvironment == nil { if pluginsEnvironment == nil {
return return
} }
@@ -280,14 +289,14 @@ func (a *App) ShutDownPlugins() {
pluginsEnvironment.Shutdown() pluginsEnvironment.Shutdown()
a.RemoveConfigListener(a.Srv().PluginConfigListenerId) s.RemoveConfigListener(s.PluginConfigListenerId)
a.Srv().PluginConfigListenerId = "" s.PluginConfigListenerId = ""
// Acquiring lock manually before cleaning up PluginsEnvironment. // Acquiring lock manually before cleaning up PluginsEnvironment.
a.Srv().PluginsLock.Lock() s.PluginsLock.Lock()
defer a.Srv().PluginsLock.Unlock() defer s.PluginsLock.Unlock()
if a.Srv().PluginsEnvironment == pluginsEnvironment { if s.PluginsEnvironment == pluginsEnvironment {
a.Srv().PluginsEnvironment = nil s.PluginsEnvironment = nil
} else { } else {
mlog.Warn("Another PluginsEnvironment detected while shutting down plugins.") mlog.Warn("Another PluginsEnvironment detected while shutting down plugins.")
} }
@@ -519,7 +528,7 @@ func (a *App) getRemotePlugins() (map[string]*model.MarketplacePlugin, *model.Ap
ServerVersion: model.CurrentVersion, ServerVersion: model.CurrentVersion,
} }
license := a.License() license := a.Srv().License()
if license != nil && *license.Features.EnterprisePlugins { if license != nil && *license.Features.EnterprisePlugins {
filter.EnterprisePlugins = true filter.EnterprisePlugins = true
} }

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

@@ -117,7 +117,7 @@ func (api *PluginAPI) GetBundlePath() (string, error) {
} }
func (api *PluginAPI) GetLicense() *model.License { func (api *PluginAPI) GetLicense() *model.License {
return api.app.License() return api.app.Srv().License()
} }
func (api *PluginAPI) GetServerVersion() string { func (api *PluginAPI) GetServerVersion() string {
@@ -125,7 +125,7 @@ func (api *PluginAPI) GetServerVersion() string {
} }
func (api *PluginAPI) GetSystemInstallDate() (int64, *model.AppError) { func (api *PluginAPI) GetSystemInstallDate() (int64, *model.AppError) {
return api.app.getSystemInstallDate() return api.app.Srv().getSystemInstallDate()
} }
func (api *PluginAPI) GetDiagnosticId() string { func (api *PluginAPI) GetDiagnosticId() string {

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

@@ -63,7 +63,7 @@ func TestPluginShutdownTest(t *testing.T) {
done := make(chan bool) done := make(chan bool)
go func() { go func() {
defer close(done) defer close(done)
th.App.ShutDownPlugins() th.App.Srv().ShutDownPlugins()
}() }()
select { select {

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

@@ -10,8 +10,8 @@ import (
) )
// GetPluginStatus returns the status for a plugin installed on this server. // GetPluginStatus returns the status for a plugin installed on this server.
func (a *App) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) { func (s *Server) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) {
pluginsEnvironment := a.GetPluginsEnvironment() pluginsEnvironment := s.GetPluginsEnvironment()
if pluginsEnvironment == nil { if pluginsEnvironment == nil {
return nil, model.NewAppError("GetPluginStatus", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetPluginStatus", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -23,17 +23,22 @@ func (a *App) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError)
// Add our cluster ID // Add our cluster ID
for _, status := range pluginStatuses { for _, status := range pluginStatuses {
if status.PluginId == id { if status.PluginId == id && s.Cluster != nil {
status.ClusterId = a.GetClusterId() status.ClusterId = s.Cluster.GetClusterId()
return status, nil return status, nil
} }
} }
return nil, model.NewAppError("GetPluginStatus", "app.plugin.not_installed.app_error", nil, "", http.StatusNotFound) return nil, model.NewAppError("GetPluginStatus", "app.plugin.not_installed.app_error", nil, "", http.StatusNotFound)
} }
// GetPluginStatus returns the status for a plugin installed on this server.
func (a *App) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) {
return a.Srv().GetPluginStatus(id)
}
// GetPluginStatuses returns the status for plugins installed on this server. // GetPluginStatuses returns the status for plugins installed on this server.
func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { func (s *Server) GetPluginStatuses() (model.PluginStatuses, *model.AppError) {
pluginsEnvironment := a.GetPluginsEnvironment() pluginsEnvironment := s.GetPluginsEnvironment()
if pluginsEnvironment == nil { if pluginsEnvironment == nil {
return nil, model.NewAppError("GetPluginStatuses", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetPluginStatuses", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
@@ -45,12 +50,21 @@ func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) {
// Add our cluster ID // Add our cluster ID
for _, status := range pluginStatuses { for _, status := range pluginStatuses {
status.ClusterId = a.GetClusterId() if s.Cluster != nil {
status.ClusterId = s.Cluster.GetClusterId()
} else {
status.ClusterId = ""
}
} }
return pluginStatuses, nil return pluginStatuses, nil
} }
// GetPluginStatuses returns the status for plugins installed on this server.
func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) {
return a.Srv().GetPluginStatuses()
}
// GetClusterPluginStatuses returns the status for plugins installed anywhere in the cluster. // GetClusterPluginStatuses returns the status for plugins installed anywhere in the cluster.
func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) { func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) {
pluginStatuses, err := a.GetPluginStatuses() pluginStatuses, err := a.GetPluginStatuses()

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

@@ -194,7 +194,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
post.AddProp("from_bot", "true") post.AddProp("from_bot", "true")
} }
if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly &&
!post.IsSystemMessage() && !post.IsSystemMessage() &&
channel.Name == model.DEFAULT_CHANNEL && channel.Name == model.DEFAULT_CHANNEL &&
!a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) {
@@ -406,7 +406,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A
} }
matched := model.AT_MENTION_PATTEN.MatchString(post.Message) matched := model.AT_MENTION_PATTEN.MatchString(post.Message)
if a.License() != nil && *a.License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) { if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) {
post.AddProp(model.POST_PROPS_GROUP_HIGHLIGHT_DISABLED, true) post.AddProp(model.POST_PROPS_GROUP_HIGHLIGHT_DISABLED, true)
} }
@@ -533,7 +533,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model
return nil, err return nil, err
} }
if a.License() != nil { if a.Srv().License() != nil {
if *a.Config().ServiceSettings.PostEditTimeLimit != -1 && model.GetMillis() > oldPost.CreateAt+int64(*a.Config().ServiceSettings.PostEditTimeLimit*1000) && post.Message != oldPost.Message { if *a.Config().ServiceSettings.PostEditTimeLimit != -1 && model.GetMillis() > oldPost.CreateAt+int64(*a.Config().ServiceSettings.PostEditTimeLimit*1000) && post.Message != oldPost.Message {
err = model.NewAppError("UpdatePost", "api.post.update_post.permissions_time_limit.app_error", map[string]interface{}{"timeLimit": *a.Config().ServiceSettings.PostEditTimeLimit}, "", http.StatusBadRequest) err = model.NewAppError("UpdatePost", "api.post.update_post.permissions_time_limit.app_error", map[string]interface{}{"timeLimit": *a.Config().ServiceSettings.PostEditTimeLimit}, "", http.StatusBadRequest)
return nil, err return nil, err
@@ -1120,8 +1120,8 @@ func (a *App) ImageProxyRemover() (f func(string) string) {
} }
} }
func (a *App) MaxPostSize() int { func (s *Server) MaxPostSize() int {
maxPostSize := a.Srv().Store.Post().GetMaxPostSize() maxPostSize := s.Store.Post().GetMaxPostSize()
if maxPostSize == 0 { if maxPostSize == 0 {
return model.POST_MESSAGE_MAX_RUNES_V1 return model.POST_MESSAGE_MAX_RUNES_V1
} }
@@ -1129,6 +1129,10 @@ func (a *App) MaxPostSize() int {
return maxPostSize return maxPostSize
} }
func (a *App) MaxPostSize() int {
return a.Srv().MaxPostSize()
}
// countMentionsFromPost returns the number of posts in the post's channel that mention the user after and including the // countMentionsFromPost returns the number of posts in the post's channel that mention the user after and including the
// given post. // given post.
func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, *model.AppError) { func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, *model.AppError) {

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

@@ -283,7 +283,7 @@ func TestUpdatePostTimeLimit(t *testing.T) {
post := &model.Post{} post := &model.Post{}
post = th.BasicPost.Clone() post = th.BasicPost.Clone()
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
th.App.UpdateConfig(func(cfg *model.Config) { th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.PostEditTimeLimit = -1 *cfg.ServiceSettings.PostEditTimeLimit = -1
@@ -1017,7 +1017,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
} }
if enableElasticsearch { if enableElasticsearch {
th.App.SetLicense(model.NewTestLicense("elastic_search")) th.App.Srv().SetLicense(model.NewTestLicense("elastic_search"))
th.App.UpdateConfig(func(cfg *model.Config) { th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ElasticsearchSettings.EnableIndexing = true *cfg.ElasticsearchSettings.EnableIndexing = true
@@ -1761,7 +1761,7 @@ func TestFillInPostProps(t *testing.T) {
t.Run("should not add disable group highlight to post props for user with group mention permissions", func(t *testing.T) { t.Run("should not add disable group highlight to post props for user with group mention permissions", func(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
user1 := th.BasicUser user1 := th.BasicUser
@@ -1815,7 +1815,7 @@ func TestFillInPostProps(t *testing.T) {
t.Run("should add disable group highlight to post props for guest user", func(t *testing.T) { t.Run("should add disable group highlight to post props for guest user", func(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("ldap")) th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
id := model.NewId() id := model.NewId()
guest := &model.User{ guest := &model.User{

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

@@ -24,7 +24,7 @@ func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *m
return nil, model.NewAppError("deleteReactionForPost", "api.reaction.save.archived_channel.app_error", nil, "", http.StatusForbidden) return nil, model.NewAppError("deleteReactionForPost", "api.reaction.save.archived_channel.app_error", nil, "", http.StatusForbidden)
} }
if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL {
var user *model.User var user *model.User
user, err = a.GetUser(reaction.UserId) user, err = a.GetUser(reaction.UserId)
if err != nil { if err != nil {
@@ -98,7 +98,7 @@ func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError {
return model.NewAppError("deleteReactionForPost", "api.reaction.delete.archived_channel.app_error", nil, "", http.StatusForbidden) return model.NewAppError("deleteReactionForPost", "api.reaction.delete.archived_channel.app_error", nil, "", http.StatusForbidden)
} }
if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL {
user, err := a.GetUser(reaction.UserId) user, err := a.GetUser(reaction.UserId)
if err != nil { if err != nil {
return err return err

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

@@ -20,13 +20,13 @@ func (a *App) GetAllRoles() ([]*model.Role, *model.AppError) {
return a.Srv().Store.Role().GetAll() return a.Srv().Store.Role().GetAll()
} }
func (a *App) GetRoleByName(name string) (*model.Role, *model.AppError) { func (s *Server) GetRoleByName(name string) (*model.Role, *model.AppError) {
role, err := a.Srv().Store.Role().GetByName(name) role, err := s.Store.Role().GetByName(name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = a.mergeChannelHigherScopedPermissions([]*model.Role{role}) err = s.mergeChannelHigherScopedPermissions([]*model.Role{role})
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -34,6 +34,10 @@ func (a *App) GetRoleByName(name string) (*model.Role, *model.AppError) {
return role, nil return role, nil
} }
func (a *App) GetRoleByName(name string) (*model.Role, *model.AppError) {
return a.Srv().GetRoleByName(name)
}
func (a *App) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) { func (a *App) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) {
roles, err := a.Srv().Store.Role().GetByNames(names) roles, err := a.Srv().Store.Role().GetByNames(names)
if err != nil { if err != nil {
@@ -50,7 +54,7 @@ func (a *App) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) {
// mergeChannelHigherScopedPermissions updates the permissions based on the role type, whether the permission is // mergeChannelHigherScopedPermissions updates the permissions based on the role type, whether the permission is
// moderated, and the value of the permission on the higher-scoped scheme. // moderated, and the value of the permission on the higher-scoped scheme.
func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.AppError { func (s *Server) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.AppError {
var higherScopeNamesToQuery []string var higherScopeNamesToQuery []string
for _, role := range roles { for _, role := range roles {
@@ -63,7 +67,7 @@ func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.Ap
return nil return nil
} }
higherScopedPermissionsMap, err := a.Srv().Store.Role().ChannelHigherScopedPermissions(higherScopeNamesToQuery) higherScopedPermissionsMap, err := s.Store.Role().ChannelHigherScopedPermissions(higherScopeNamesToQuery)
if err != nil { if err != nil {
return err return err
} }
@@ -79,6 +83,12 @@ func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.Ap
return nil return nil
} }
// mergeChannelHigherScopedPermissions updates the permissions based on the role type, whether the permission is
// moderated, and the value of the permission on the higher-scoped scheme.
func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.AppError {
return a.Srv().mergeChannelHigherScopedPermissions(roles)
}
func (a *App) PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError) { func (a *App) PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError) {
// If patch is a no-op then short-circuit the store. // If patch is a no-op then short-circuit the store.
if patch.Permissions != nil && reflect.DeepEqual(*patch.Permissions, role.Permissions) { if patch.Permissions != nil && reflect.DeepEqual(*patch.Permissions, role.Permissions) {

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

@@ -54,7 +54,7 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense("")) th.App.Srv().SetLicense(model.NewTestLicense(""))
th.App.SetPhase2PermissionsMigrationStatus(true) th.App.SetPhase2PermissionsMigrationStatus(true)
permissionsDefault := []string{ permissionsDefault := []string{

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

@@ -33,12 +33,16 @@ func (a *App) GetSchemesPage(scope string, page int, perPage int) ([]*model.Sche
return a.GetSchemes(scope, page*perPage, perPage) return a.GetSchemes(scope, page*perPage, perPage)
} }
func (a *App) GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) { func (s *Server) GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) {
if err := a.IsPhase2MigrationCompleted(); err != nil { if err := s.IsPhase2MigrationCompleted(); err != nil {
return nil, err return nil, err
} }
return a.Srv().Store.Scheme().GetAllPage(scope, offset, limit) return s.Store.Scheme().GetAllPage(scope, offset, limit)
}
func (a *App) GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) {
return a.Srv().GetSchemes(scope, offset, limit)
} }
func (a *App) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) { func (a *App) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) {
@@ -125,20 +129,24 @@ func (a *App) GetChannelsForScheme(scheme *model.Scheme, offset int, limit int)
return a.Srv().Store.Channel().GetChannelsByScheme(scheme.Id, offset, limit) return a.Srv().Store.Channel().GetChannelsByScheme(scheme.Id, offset, limit)
} }
func (a *App) IsPhase2MigrationCompleted() *model.AppError { func (s *Server) IsPhase2MigrationCompleted() *model.AppError {
if a.Srv().phase2PermissionsMigrationComplete { if s.phase2PermissionsMigrationComplete {
return nil return nil
} }
if _, err := a.Srv().Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { if _, err := s.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil {
return model.NewAppError("App.IsPhase2MigrationCompleted", "app.schemes.is_phase_2_migration_completed.not_completed.app_error", nil, err.Error(), http.StatusNotImplemented) return model.NewAppError("App.IsPhase2MigrationCompleted", "app.schemes.is_phase_2_migration_completed.not_completed.app_error", nil, err.Error(), http.StatusNotImplemented)
} }
a.Srv().phase2PermissionsMigrationComplete = true s.phase2PermissionsMigrationComplete = true
return nil return nil
} }
func (a *App) IsPhase2MigrationCompleted() *model.AppError {
return a.Srv().IsPhase2MigrationCompleted()
}
func (a *App) SchemesIterator(scope string, batchSize int) func() []*model.Scheme { func (a *App) SchemesIterator(scope string, batchSize int) func() []*model.Scheme {
offset := 0 offset := 0
return func() []*model.Scheme { return func() []*model.Scheme {

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

@@ -53,9 +53,10 @@ import (
var MaxNotificationsPerChannelDefault int64 = 1000000 var MaxNotificationsPerChannelDefault int64 = 1000000
type Server struct { type Server struct {
sqlStore *sqlstore.SqlSupplier sqlStore *sqlstore.SqlSupplier
Store store.Store Store store.Store
WebSocketRouter *WebSocketRouter WebSocketRouter *WebSocketRouter
AppInitializedOnce sync.Once
// RootRouter is the starting point for all HTTP requests to the server. // RootRouter is the starting point for all HTTP requests to the server.
RootRouter *mux.Router RootRouter *mux.Router
@@ -345,33 +346,19 @@ func NewServer(options ...Option) (*Server, error) {
mlog.Error("Error to reset the server status.", mlog.Err(err)) mlog.Error("Error to reset the server status.", mlog.Err(err))
} }
// Scheduler must be started before cluster.
s.initJobs()
if s.joinCluster && s.Cluster != nil {
s.FakeApp().registerAllClusterMessageHandlers()
s.Cluster.StartInterNodeCommunication()
}
if s.startMetrics && s.Metrics != nil { if s.startMetrics && s.Metrics != nil {
s.Metrics.StartServer() s.Metrics.StartServer()
} }
s.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { s.SearchEngine.UpdateConfig(s.Config())
if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable { searchConfigListenerId, searchLicenseListenerId := s.StartSearchEngine()
if appErr := s.FakeApp().DeactivateGuests(); appErr != nil { s.searchConfigListenerId = searchConfigListenerId
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) s.searchLicenseListenerId = searchLicenseListenerId
}
}
})
// Disable active guest accounts on first run if guest accounts are disabled return s, nil
if !*s.Config().GuestAccountsSettings.Enable { }
if appErr := s.FakeApp().DeactivateGuests(); appErr != nil {
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
}
}
func (s *Server) RunJobs() {
if s.runjobs { if s.runjobs {
s.Go(func() { s.Go(func() {
runSecurityJob(s) runSecurityJob(s)
@@ -388,9 +375,6 @@ func NewServer(options ...Option) (*Server, error) {
s.Go(func() { s.Go(func() {
runCommandWebhookCleanupJob(s) runCommandWebhookCleanupJob(s)
}) })
s.Go(func() {
runLicenseExpirationCheckJob(s)
})
if complianceI := s.Compliance; complianceI != nil { if complianceI := s.Compliance; complianceI != nil {
complianceI.StartComplianceDailyJob() complianceI.StartComplianceDailyJob()
@@ -403,13 +387,6 @@ func NewServer(options ...Option) (*Server, error) {
s.Jobs.StartSchedulers() s.Jobs.StartSchedulers()
} }
} }
s.SearchEngine.UpdateConfig(s.Config())
searchConfigListenerId, searchLicenseListenerId := s.StartSearchEngine()
s.searchConfigListenerId = searchConfigListenerId
s.searchLicenseListenerId = searchLicenseListenerId
return s, nil
} }
// Global app options that should be applied to apps created by this server // Global app options that should be applied to apps created by this server
@@ -448,7 +425,11 @@ func (s *Server) Shutdown() error {
defer sentry.Flush(2 * time.Second) defer sentry.Flush(2 * time.Second)
s.RunOldAppShutdown() s.HubStop()
s.StopPushNotificationsHubWorkers()
s.ShutDownPlugins()
s.RemoveLicenseListener(s.licenseListenerId)
s.RemoveClusterLeaderChangedListener(s.clusterLeaderListenerId)
if s.tracer != nil { if s.tracer != nil {
if err := s.tracer.Close(); err != nil { if err := s.tracer.Close(); err != nil {
@@ -842,10 +823,10 @@ func doDiagnosticsIfNeeded(s *Server, firstRun time.Time) {
func runDiagnosticsJob(s *Server) { func runDiagnosticsJob(s *Server) {
// Send on boot // Send on boot
doDiagnostics(s) doDiagnostics(s)
firstRun, err := s.FakeApp().getFirstServerRunTimestamp() firstRun, err := s.getFirstServerRunTimestamp()
if err != nil { if err != nil {
mlog.Warn("Fetching time of first server run failed. Setting to 'now'.") mlog.Warn("Fetching time of first server run failed. Setting to 'now'.")
s.FakeApp().ensureFirstServerRunTimestamp() s.ensureFirstServerRunTimestamp()
firstRun = utils.MillisFromTime(time.Now()) firstRun = utils.MillisFromTime(time.Now())
} }
model.CreateRecurringTask("Diagnostics", func() { model.CreateRecurringTask("Diagnostics", func() {
@@ -874,10 +855,10 @@ func runSessionCleanupJob(s *Server) {
}, time.Hour*24) }, time.Hour*24)
} }
func runLicenseExpirationCheckJob(s *Server) { func runLicenseExpirationCheckJob(a *App) {
doLicenseExpirationCheck(s) doLicenseExpirationCheck(a)
model.CreateRecurringTask("License Expiration Check", func() { model.CreateRecurringTask("License Expiration Check", func() {
doLicenseExpirationCheck(s) doLicenseExpirationCheck(a)
}, time.Hour*24) }, time.Hour*24)
} }
@@ -888,7 +869,7 @@ func doSecurity(s *Server) {
func doDiagnostics(s *Server) { func doDiagnostics(s *Server) {
if *s.Config().LogSettings.EnableDiagnostics { if *s.Config().LogSettings.EnableDiagnostics {
s.timestampLastDiagnosticSent = time.Now() s.timestampLastDiagnosticSent = time.Now()
s.FakeApp().SendDailyDiagnostics() s.SendDailyDiagnostics()
} }
} }
@@ -908,9 +889,9 @@ func doSessionCleanup(s *Server) {
s.Store.Session().Cleanup(model.GetMillis(), SESSIONS_CLEANUP_BATCH_SIZE) s.Store.Session().Cleanup(model.GetMillis(), SESSIONS_CLEANUP_BATCH_SIZE)
} }
func doLicenseExpirationCheck(s *Server) { func doLicenseExpirationCheck(a *App) {
s.FakeApp().LoadLicense() a.Srv().LoadLicense()
license := s.License() license := a.Srv().License()
if license == nil { if license == nil {
mlog.Debug("License cannot be found.") mlog.Debug("License cannot be found.")
@@ -922,7 +903,7 @@ func doLicenseExpirationCheck(s *Server) {
return return
} }
users, err := s.Store.User().GetSystemAdminProfiles() users, err := a.Srv().Store.User().GetSystemAdminProfiles()
if err != nil { if err != nil {
mlog.Error("Failed to get system admins for license expired message from Mattermost.") mlog.Error("Failed to get system admins for license expired message from Mattermost.")
return return
@@ -937,15 +918,15 @@ func doLicenseExpirationCheck(s *Server) {
} }
mlog.Debug("Sending license expired email.", mlog.String("user_email", user.Email)) mlog.Debug("Sending license expired email.", mlog.String("user_email", user.Email))
s.Go(func() { a.Srv().Go(func() {
if err := s.FakeApp().SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *s.Config().ServiceSettings.SiteURL, license.Id); err != nil { if err := a.SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *a.Config().ServiceSettings.SiteURL, license.Id); err != nil {
mlog.Error("Error while sending the license expired email.", mlog.String("user_email", user.Email), mlog.Err(err)) mlog.Error("Error while sending the license expired email.", mlog.String("user_email", user.Email), mlog.Err(err))
} }
}) })
} }
//remove the license //remove the license
s.FakeApp().RemoveLicense() a.Srv().RemoveLicense()
} }
func (s *Server) StartSearchEngine() (string, string) { func (s *Server) StartSearchEngine() (string, string) {
@@ -1159,3 +1140,30 @@ func (s *Server) ensureDiagnosticId() {
s.diagnosticId = id s.diagnosticId = id
} }
func (s *Server) configOrLicenseListener() {
s.regenerateClientConfig()
}
func (s *Server) ClientConfigHash() string {
return s.clientConfigHash.Load().(string)
}
func (s *Server) initJobs() {
s.Jobs = jobs.NewJobServer(s, s.Store)
if jobsDataRetentionJobInterface != nil {
s.Jobs.DataRetentionJob = jobsDataRetentionJobInterface(s)
}
if jobsMessageExportJobInterface != nil {
s.Jobs.MessageExportJob = jobsMessageExportJobInterface(s)
}
if jobsElasticsearchAggregatorInterface != nil {
s.Jobs.ElasticsearchAggregator = jobsElasticsearchAggregatorInterface(s)
}
if jobsElasticsearchIndexerInterface != nil {
s.Jobs.ElasticsearchIndexer = jobsElasticsearchIndexerInterface(s)
}
if jobsBleveIndexerInterface != nil {
s.Jobs.BleveIndexer = jobsBleveIndexerInterface(s)
}
}

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

@@ -24,34 +24,34 @@ import (
// Don't add anything new here, new initialization should be done in the server and // Don't add anything new here, new initialization should be done in the server and
// performed in the NewServer function. // performed in the NewServer function.
func (s *Server) RunOldAppInitialization() error { func (s *Server) RunOldAppInitialization() error {
s.FakeApp().createPushNotificationsHub() s.createPushNotificationsHub()
if err := utils.InitTranslations(s.Config().LocalizationSettings); err != nil { if err := utils.InitTranslations(s.Config().LocalizationSettings); err != nil {
return errors.Wrapf(err, "unable to load Mattermost translation files") return errors.Wrapf(err, "unable to load Mattermost translation files")
} }
s.configListenerId = s.AddConfigListener(func(_, _ *model.Config) { s.configListenerId = s.AddConfigListener(func(_, _ *model.Config) {
s.FakeApp().configOrLicenseListener() s.configOrLicenseListener()
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CONFIG_CHANGED, "", "", "", nil) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CONFIG_CHANGED, "", "", "", nil)
message.Add("config", s.FakeApp().ClientConfigWithComputed()) message.Add("config", s.ClientConfigWithComputed())
s.Go(func() { s.Go(func() {
s.FakeApp().Publish(message) s.Publish(message)
}) })
}) })
s.licenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) { s.licenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) {
s.FakeApp().configOrLicenseListener() s.configOrLicenseListener()
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LICENSE_CHANGED, "", "", "", nil) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LICENSE_CHANGED, "", "", "", nil)
message.Add("license", s.FakeApp().GetSanitizedClientLicense()) message.Add("license", s.GetSanitizedClientLicense())
s.Go(func() { s.Go(func() {
s.FakeApp().Publish(message) s.Publish(message)
}) })
}) })
if err := s.FakeApp().SetupInviteEmailRateLimiting(); err != nil { if err := s.setupInviteEmailRateLimiting(); err != nil {
return err return err
} }
@@ -96,31 +96,40 @@ func (s *Server) RunOldAppInitialization() error {
} }
s.Store = s.newStore() s.Store = s.newStore()
s.FakeApp().StartPushNotificationsHubWorkers()
if err := s.FakeApp().ensureAsymmetricSigningKey(); err != nil { if model.BuildEnterpriseReady == "true" {
s.LoadLicense()
}
s.initJobs()
if s.joinCluster && s.Cluster != nil {
s.Cluster.StartInterNodeCommunication()
}
if err := s.ensureAsymmetricSigningKey(); err != nil {
return errors.Wrapf(err, "unable to ensure asymmetric signing key") return errors.Wrapf(err, "unable to ensure asymmetric signing key")
} }
if err := s.FakeApp().ensurePostActionCookieSecret(); err != nil { if err := s.ensurePostActionCookieSecret(); err != nil {
return errors.Wrapf(err, "unable to ensure PostAction cookie secret") return errors.Wrapf(err, "unable to ensure PostAction cookie secret")
} }
if err := s.FakeApp().ensureInstallationDate(); err != nil { if err := s.ensureInstallationDate(); err != nil {
return errors.Wrapf(err, "unable to ensure installation date") return errors.Wrapf(err, "unable to ensure installation date")
} }
if err := s.FakeApp().ensureFirstServerRunTimestamp(); err != nil { if err := s.ensureFirstServerRunTimestamp(); err != nil {
return errors.Wrapf(err, "unable to ensure first run timestamp") return errors.Wrapf(err, "unable to ensure first run timestamp")
} }
s.ensureDiagnosticId() s.ensureDiagnosticId()
s.FakeApp().regenerateClientConfig() s.regenerateClientConfig()
s.clusterLeaderListenerId = s.AddClusterLeaderChangedListener(func() { s.clusterLeaderListenerId = s.AddClusterLeaderChangedListener(func() {
mlog.Info("Cluster leader changed. Determining if job schedulers should be running:", mlog.Bool("isLeader", s.FakeApp().IsLeader())) mlog.Info("Cluster leader changed. Determining if job schedulers should be running:", mlog.Bool("isLeader", s.IsLeader()))
if s.Jobs != nil && s.Jobs.Schedulers != nil { if s.Jobs != nil && s.Jobs.Schedulers != nil {
s.Jobs.Schedulers.HandleClusterLeaderChange(s.FakeApp().IsLeader()) s.Jobs.Schedulers.HandleClusterLeaderChange(s.IsLeader())
} }
}) })
@@ -129,10 +138,6 @@ func (s *Server) RunOldAppInitialization() error {
return errors.Wrap(err, "failed to parse SiteURL subpath") return errors.Wrap(err, "failed to parse SiteURL subpath")
} }
s.Router = s.RootRouter.PathPrefix(subpath).Subrouter() s.Router = s.RootRouter.PathPrefix(subpath).Subrouter()
pluginsRoute := s.Router.PathPrefix("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter()
pluginsRoute.HandleFunc("", s.FakeApp().ServePluginRequest)
pluginsRoute.HandleFunc("/public/{public_file:.*}", s.FakeApp().ServePluginPublicRequest)
pluginsRoute.HandleFunc("/{anything:.*}", s.FakeApp().ServePluginRequest)
// If configured with a subpath, redirect 404s at the root back into the subpath. // If configured with a subpath, redirect 404s at the root back into the subpath.
if subpath != "/" { if subpath != "/" {
@@ -141,10 +146,9 @@ func (s *Server) RunOldAppInitialization() error {
http.Redirect(w, r, r.URL.String(), http.StatusFound) http.Redirect(w, r, r.URL.String(), http.StatusFound)
}) })
} }
s.Router.NotFoundHandler = http.HandlerFunc(s.FakeApp().Handle404)
s.WebSocketRouter = &WebSocketRouter{ s.WebSocketRouter = &WebSocketRouter{
app: s.FakeApp(), server: s,
handlers: make(map[string]webSocketHandler), handlers: make(map[string]webSocketHandler),
} }
@@ -164,39 +168,5 @@ func (s *Server) RunOldAppInitialization() error {
mlog.Error("Problem with file storage settings", mlog.Err(appErr)) mlog.Error("Problem with file storage settings", mlog.Err(appErr))
} }
if model.BuildEnterpriseReady == "true" {
s.FakeApp().LoadLicense()
}
s.FakeApp().DoAppMigrations()
s.FakeApp().InitPostMetadata()
s.FakeApp().InitPlugins(*s.Config().PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory)
s.FakeApp().AddConfigListener(func(prevCfg, cfg *model.Config) {
if *cfg.PluginSettings.Enable {
s.FakeApp().InitPlugins(*cfg.PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory)
} else {
s.FakeApp().ShutDownPlugins()
}
})
return nil return nil
} }
func (s *Server) RunOldAppShutdown() {
s.FakeApp().HubStop()
s.FakeApp().StopPushNotificationsHubWorkers()
s.FakeApp().ShutDownPlugins()
s.FakeApp().RemoveLicenseListener(s.licenseListenerId)
s.RemoveClusterLeaderChangedListener(s.clusterLeaderListenerId)
}
// A temporary bridge to deal with cases where the code is so tighly coupled that
// this is easier as a temporary solution
func (s *Server) FakeApp() *App {
a := New(
ServerConnector(s),
)
return a
}

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

@@ -60,7 +60,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) {
session, _ = th.App.CreateSession(session) session, _ = th.App.CreateSession(session)
th.App.SetLicense(model.NewTestLicense("compliance")) th.App.Srv().SetLicense(model.NewTestLicense("compliance"))
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 5 }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 5 })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExtendSessionLengthWithActivity = false }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExtendSessionLengthWithActivity = false })
@@ -110,7 +110,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) {
_, err = th.App.GetSession(session.Token) _, err = th.App.GetSession(session.Token)
assert.Nil(t, err) assert.Nil(t, err)
th.App.SetLicense(model.NewTestLicense("compliance")) th.App.Srv().SetLicense(model.NewTestLicense("compliance"))
// Test regular session with timeout set to 0, should not timeout // Test regular session with timeout set to 0, should not timeout
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 0 }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 0 })
@@ -133,7 +133,7 @@ func TestUpdateSessionOnPromoteDemote(t *testing.T) {
th := Setup(t).InitBasic() th := Setup(t).InitBasic()
defer th.TearDown() defer th.TearDown()
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
t.Run("Promote Guest to User updates the session", func(t *testing.T) { t.Run("Promote Guest to User updates the session", func(t *testing.T) {
guest := th.CreateGuest() guest := th.CreateGuest()

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

@@ -751,7 +751,7 @@ func (a *App) SlackImport(fileData multipart.File, fileSize int64, teamID string
a.deactivateSlackBotUser(botUser) a.deactivateSlackBotUser(botUser)
} }
a.InvalidateAllCaches() a.Srv().InvalidateAllCaches()
log.WriteString(utils.T("api.slackimport.slack_import.notes")) log.WriteString(utils.T("api.slackimport.slack_import.notes"))
log.WriteString("=======\r\n\r\n") log.WriteString("=======\r\n\r\n")

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

@@ -191,9 +191,13 @@ func (a *App) IsUserSignUpAllowed() *model.AppError {
return nil return nil
} }
func (a *App) IsFirstUserAccount() bool { func (s *Server) IsFirstUserAccount() bool {
if a.SessionCacheLength() == 0 { cachedSessions, err := s.sessionCache.Len()
count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) if err != nil {
return false
}
if cachedSessions == 0 {
count, err := s.Store.User().Count(model.UserCountOptions{IncludeDeleted: true})
if err != nil { if err != nil {
mlog.Error("There was a error fetching if first user account", mlog.Err(err)) mlog.Error("There was a error fetching if first user account", mlog.Err(err))
return false return false
@@ -206,6 +210,10 @@ func (a *App) IsFirstUserAccount() bool {
return false return false
} }
func (a *App) IsFirstUserAccount() bool {
return a.Srv().IsFirstUserAccount()
}
// CreateUser creates a user and sets several fields of the returned User struct to // CreateUser creates a user and sets several fields of the returned User struct to
// their zero values. // their zero values.
func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) { func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) {

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

@@ -286,7 +286,7 @@ func (wc *WebConn) IsAuthenticated() bool {
func (wc *WebConn) createHelloMessage() *model.WebSocketEvent { func (wc *WebConn) createHelloMessage() *model.WebSocketEvent {
msg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_HELLO, "", "", wc.UserId, nil) msg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_HELLO, "", "", wc.UserId, nil)
msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, wc.App.ClientConfigHash(), wc.App.License() != nil)) msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, wc.App.ClientConfigHash(), wc.App.Srv().License() != nil))
return msg return msg
} }

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

@@ -96,19 +96,6 @@ func (a *App) HubStart() {
} }
} }
func (a *App) PublishSkipClusterSend(message *model.WebSocketEvent) {
if message.GetBroadcast().UserId != "" {
hub := a.GetHubForUserId(message.GetBroadcast().UserId)
if hub != nil {
hub.Broadcast(message)
}
return
}
for _, hub := range a.Srv().GetHubs() {
hub.Broadcast(message)
}
}
func (a *App) invalidateCacheForUserSkipClusterSend(userId string) { func (a *App) invalidateCacheForUserSkipClusterSend(userId string) {
a.Srv().Store.Channel().InvalidateAllChannelMembersForUser(userId) a.Srv().Store.Channel().InvalidateAllChannelMembersForUser(userId)
a.InvalidateWebConnSessionCacheForUser(userId) a.InvalidateWebConnSessionCacheForUser(userId)
@@ -126,26 +113,30 @@ func (a *App) InvalidateWebConnSessionCacheForUser(userId string) {
} }
// HubStop stops all the hubs. // HubStop stops all the hubs.
func (a *App) HubStop() { func (s *Server) HubStop() {
mlog.Info("stopping websocket hub connections") mlog.Info("stopping websocket hub connections")
for _, hub := range a.Srv().GetHubs() { for _, hub := range s.GetHubs() {
hub.Stop() hub.Stop()
} }
a.Srv().SetHubs([]*Hub{}) s.SetHubs([]*Hub{})
}
func (a *App) HubStop() {
a.Srv().HubStop()
} }
// GetHubForUserId returns the hub for a given user id. // GetHubForUserId returns the hub for a given user id.
func (a *App) GetHubForUserId(userId string) *Hub { func (s *Server) GetHubForUserId(userId string) *Hub {
if len(a.Srv().GetHubs()) == 0 { if len(s.GetHubs()) == 0 {
return nil return nil
} }
hash := fnv.New32a() hash := fnv.New32a()
hash.Write([]byte(userId)) hash.Write([]byte(userId))
index := hash.Sum32() % uint32(len(a.Srv().GetHubs())) index := hash.Sum32() % uint32(len(s.GetHubs()))
hub, err := a.Srv().GetHub(int(index)) hub, err := s.GetHub(int(index))
if err != nil { if err != nil {
mlog.Warn("Requested hub doesn't exist", mlog.Int("hub_index", int(index))) mlog.Warn("Requested hub doesn't exist", mlog.Int("hub_index", int(index)))
return nil return nil
@@ -153,6 +144,10 @@ func (a *App) GetHubForUserId(userId string) *Hub {
return hub return hub
} }
func (a *App) GetHubForUserId(userId string) *Hub {
return a.Srv().GetHubForUserId(userId)
}
// HubRegister registers a connection to a hub. // HubRegister registers a connection to a hub.
func (a *App) HubRegister(webConn *WebConn) { func (a *App) HubRegister(webConn *WebConn) {
hub := a.GetHubForUserId(webConn.UserId) hub := a.GetHubForUserId(webConn.UserId)
@@ -175,14 +170,14 @@ func (a *App) HubUnregister(webConn *WebConn) {
} }
} }
func (a *App) Publish(message *model.WebSocketEvent) { func (s *Server) Publish(message *model.WebSocketEvent) {
if metrics := a.Metrics(); metrics != nil { if s.Metrics != nil {
metrics.IncrementWebsocketEvent(message.EventType()) s.Metrics.IncrementWebsocketEvent(message.EventType())
} }
a.PublishSkipClusterSend(message) s.PublishSkipClusterSend(message)
if a.Cluster() != nil { if s.Cluster != nil {
cm := &model.ClusterMessage{ cm := &model.ClusterMessage{
Event: model.CLUSTER_EVENT_PUBLISH, Event: model.CLUSTER_EVENT_PUBLISH,
SendType: model.CLUSTER_SEND_BEST_EFFORT, SendType: model.CLUSTER_SEND_BEST_EFFORT,
@@ -197,10 +192,31 @@ func (a *App) Publish(message *model.WebSocketEvent) {
cm.SendType = model.CLUSTER_SEND_RELIABLE cm.SendType = model.CLUSTER_SEND_RELIABLE
} }
a.Cluster().SendClusterMessage(cm) s.Cluster.SendClusterMessage(cm)
} }
} }
func (a *App) Publish(message *model.WebSocketEvent) {
a.Srv().Publish(message)
}
func (s *Server) PublishSkipClusterSend(message *model.WebSocketEvent) {
if message.GetBroadcast().UserId != "" {
hub := s.GetHubForUserId(message.GetBroadcast().UserId)
if hub != nil {
hub.Broadcast(message)
}
} else {
for _, hub := range s.GetHubs() {
hub.Broadcast(message)
}
}
}
func (a *App) PublishSkipClusterSend(message *model.WebSocketEvent) {
a.Srv().PublishSkipClusterSend(message)
}
func (a *App) invalidateCacheForChannel(channel *model.Channel) { func (a *App) invalidateCacheForChannel(channel *model.Channel) {
a.Srv().Store.Channel().InvalidateChannel(channel.Id) a.Srv().Store.Channel().InvalidateChannel(channel.Id)
a.invalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name) a.invalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name)

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

@@ -673,7 +673,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq
user = result.Data.(*model.User) user = result.Data.(*model.User)
} }
if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly &&
channel.Name == model.DEFAULT_CHANNEL && !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { channel.Name == model.DEFAULT_CHANNEL && !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) {
return model.NewAppError("HandleIncomingWebhook", "api.post.create_post.town_square_read_only", nil, "", http.StatusForbidden) return model.NewAppError("HandleIncomingWebhook", "api.post.create_post.town_square_read_only", nil, "", http.StatusForbidden)
} }

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

@@ -16,6 +16,7 @@ type webSocketHandler interface {
} }
type WebSocketRouter struct { type WebSocketRouter struct {
server *Server
app *App app *App
handlers map[string]webSocketHandler handlers map[string]webSocketHandler
} }
@@ -25,6 +26,9 @@ func (wr *WebSocketRouter) Handle(action string, handler webSocketHandler) {
} }
func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) { func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) {
wr.app = New(ServerConnector(wr.server))
wr.app.InitServer()
if r.Action == "" { if r.Action == "" {
err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest) err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest)
returnWebSocketError(wr.app, conn, r, err) returnWebSocketError(wr.app, conn, r, err)

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

@@ -19,6 +19,7 @@ import (
"github.com/mattermost/mattermost-server/v5/api4" "github.com/mattermost/mattermost-server/v5/api4"
"github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/store/storetest/mocks"
"github.com/mattermost/mattermost-server/v5/testlib" "github.com/mattermost/mattermost-server/v5/testlib"
) )
@@ -65,6 +66,12 @@ func SetupWithStoreMock(t testing.TB) *testHelper {
} }
api4TestHelper := api4.SetupWithStoreMock(t) api4TestHelper := api4.SetupWithStoreMock(t)
systemStore := mocks.SystemStore{}
systemStore.On("Get").Return(make(model.StringMap), nil)
licenseStore := mocks.LicenseStore{}
licenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil)
api4TestHelper.App.Srv().Store.(*mocks.Store).On("System").Return(&systemStore)
api4TestHelper.App.Srv().Store.(*mocks.Store).On("License").Return(&licenseStore)
testHelper := &testHelper{ testHelper := &testHelper{
TestHelper: api4TestHelper, TestHelper: api4TestHelper,

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

@@ -145,7 +145,7 @@ func scheduleExportCmdF(command *cobra.Command, args []string) error {
func buildExportCmdF(format string) func(command *cobra.Command, args []string) error { func buildExportCmdF(format string) func(command *cobra.Command, args []string) error {
return func(command *cobra.Command, args []string) error { return func(command *cobra.Command, args []string) error {
a, err := InitDBCommandContextCobra(command) a, err := InitDBCommandContextCobra(command)
license := a.License() license := a.Srv().License()
if err != nil { if err != nil {
return err return err
} }

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

@@ -41,10 +41,10 @@ func InitDBCommandContext(configDSN string) (*app.App, error) {
return nil, err return nil, err
} }
a := s.FakeApp() a := app.New(app.ServerConnector(s))
if model.BuildEnterpriseReady == "true" { if model.BuildEnterpriseReady == "true" {
a.LoadLicense() a.Srv().LoadLicense()
} }
return a, nil return a, nil

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

@@ -41,7 +41,7 @@ func jobserverCmdF(command *cobra.Command, args []string) error {
} }
defer a.Shutdown() defer a.Shutdown()
a.LoadLicense() a.Srv().LoadLicense()
// Run jobs // Run jobs
mlog.Info("Starting Mattermost job server") mlog.Info("Starting Mattermost job server")

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

@@ -45,7 +45,7 @@ func uploadLicenseCmdF(command *cobra.Command, args []string) error {
return err return err
} }
if _, err := a.SaveLicense(fileBytes); err != nil { if _, err := a.Srv().SaveLicense(fileBytes); err != nil {
return err return err
} }

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

@@ -100,7 +100,7 @@ func exportPermissionsCmdF(command *cobra.Command, args []string) error {
} }
defer a.Shutdown() defer a.Shutdown()
if license := a.License(); license == nil { if license := a.Srv().License(); license == nil {
return errors.New(utils.T("cli.license.critical")) return errors.New(utils.T("cli.license.critical"))
} }
@@ -121,7 +121,7 @@ func importPermissionsCmdF(command *cobra.Command, args []string) error {
} }
defer a.Shutdown() defer a.Shutdown()
if license := a.License(); license == nil { if license := a.Srv().License(); license == nil {
return errors.New(utils.T("cli.license.critical")) return errors.New(utils.T("cli.license.critical"))
} }

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

@@ -73,7 +73,7 @@ func runServer(configStore config.Store, disableConfigWatch bool, usedPlatform b
} }
api := api4.Init(server, server.AppOptions, server.Router) api := api4.Init(server, server.AppOptions, server.Router)
wsapi.Init(server.FakeApp(), server.WebSocketRouter) wsapi.Init(server)
web.New(server, server.AppOptions, server.Router) web.New(server, server.AppOptions, server.Router)
api4.InitLocal(server, server.AppOptions, server.LocalRouter) api4.InitLocal(server, server.AppOptions, server.LocalRouter)

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

@@ -59,7 +59,7 @@ func webClientTestsCmdF(command *cobra.Command, args []string) error {
} }
api4.Init(a, a.Srv().AppOptions, a.Srv().Router) api4.Init(a, a.Srv().AppOptions, a.Srv().Router)
wsapi.Init(a, a.Srv().WebSocketRouter) wsapi.Init(a.Srv())
a.UpdateConfig(setupClientTests) a.UpdateConfig(setupClientTests)
runWebClientTests() runWebClientTests()
@@ -80,7 +80,7 @@ func serverForWebClientTestsCmdF(command *cobra.Command, args []string) error {
} }
api4.Init(a, a.Srv().AppOptions, a.Srv().Router) api4.Init(a, a.Srv().AppOptions, a.Srv().Router)
wsapi.Init(a, a.Srv().WebSocketRouter) wsapi.Init(a.Srv())
a.UpdateConfig(setupClientTests) a.UpdateConfig(setupClientTests)
c := make(chan os.Signal, 1) c := make(chan os.Signal, 1)

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

@@ -50,7 +50,7 @@ func setupTestHelper(enterprise bool) *TestHelper {
s.Store = localcachelayer.NewLocalCacheLayer(s.Store, s.Metrics, s.Cluster, s.CacheProvider) s.Store = localcachelayer.NewLocalCacheLayer(s.Store, s.Metrics, s.Cluster, s.CacheProvider)
th := &TestHelper{ th := &TestHelper{
App: s.FakeApp(), App: app.New(app.ServerConnector(s)),
Server: s, Server: s,
} }
@@ -73,9 +73,9 @@ func setupTestHelper(enterprise bool) *TestHelper {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true })
if enterprise { if enterprise {
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
} else { } else {
th.App.SetLicense(nil) th.App.Srv().SetLicense(nil)
} }
return th return th
@@ -248,7 +248,7 @@ func (me *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel)
func (me *TestHelper) TearDown() { func (me *TestHelper) TearDown() {
// Clean all the caches // Clean all the caches
me.App.InvalidateAllCaches() me.App.Srv().InvalidateAllCaches()
me.Server.Shutdown() me.Server.Shutdown()
if me.tempWorkspace != "" { if me.tempWorkspace != "" {
os.RemoveAll(me.tempWorkspace) os.RemoveAll(me.tempWorkspace)

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

@@ -46,6 +46,9 @@ type BleveIndexerWorker struct {
} }
func (bi *BleveIndexerInterfaceImpl) MakeWorker() model.Worker { func (bi *BleveIndexerInterfaceImpl) MakeWorker() model.Worker {
if bi.Server.SearchEngine.BleveEngine == nil {
return nil
}
return &BleveIndexerWorker{ return &BleveIndexerWorker{
name: "BleveIndexer", name: "BleveIndexer",
stop: make(chan bool, 1), stop: make(chan bool, 1),

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

@@ -141,7 +141,7 @@ func (c *Context) SessionRequired() {
func (c *Context) MfaRequired() { func (c *Context) MfaRequired() {
// Must be licensed for MFA and have it configured for enforcement // Must be licensed for MFA and have it configured for enforcement
if license := c.App.License(); license == nil || !*license.Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication || !*c.App.Config().ServiceSettings.EnforceMultifactorAuthentication { if license := c.App.Srv().License(); license == nil || !*license.Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication || !*c.App.Config().ServiceSettings.EnforceMultifactorAuthentication {
return return
} }

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

@@ -92,6 +92,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.App = app.New( c.App = app.New(
h.GetGlobalAppOptions()..., h.GetGlobalAppOptions()...,
) )
c.App.InitServer()
t, _ := utils.GetTranslationsAndLocale(w, r) t, _ := utils.GetTranslationsAndLocale(w, r)
c.App.SetT(t) c.App.SetT(t)
@@ -143,7 +144,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.SetSiteURLHeader(siteURLHeader) c.SetSiteURLHeader(siteURLHeader)
w.Header().Set(model.HEADER_REQUEST_ID, c.App.RequestId()) w.Header().Set(model.HEADER_REQUEST_ID, c.App.RequestId())
w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.License() != nil)) w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.Srv().License() != nil))
if *c.App.Config().ServiceSettings.TLSStrictTransport { if *c.App.Config().ServiceSettings.TLSStrictTransport {
w.Header().Set("Strict-Transport-Security", fmt.Sprintf("max-age=%d", *c.App.Config().ServiceSettings.TLSStrictTransportMaxAge)) w.Header().Set("Strict-Transport-Security", fmt.Sprintf("max-age=%d", *c.App.Config().ServiceSettings.TLSStrictTransportMaxAge))

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

@@ -46,7 +46,7 @@ type SystemBrowser struct {
func renderUnsupportedBrowser(app app.AppIface, w http.ResponseWriter, r *http.Request) { func renderUnsupportedBrowser(app app.AppIface, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store") w.Header().Set("Cache-Control", "no-store")
page := utils.NewHTMLTemplate(app.HTMLTemplates(), "unsupported_browser") page := utils.NewHTMLTemplate(app.Srv().HTMLTemplates(), "unsupported_browser")
// User Agent info // User Agent info
ua := uasurfer.Parse(r.UserAgent()) ua := uasurfer.Parse(r.UserAgent())

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

@@ -85,17 +85,16 @@ func setupTestHelper(t testing.TB, store store.Store, includeCacheLayer bool) *T
s.Store = localcachelayer.NewLocalCacheLayer(s.Store, s.Metrics, s.Cluster, s.CacheProvider) s.Store = localcachelayer.NewLocalCacheLayer(s.Store, s.Metrics, s.Cluster, s.CacheProvider)
} }
a := s.FakeApp() prevListenAddress := *s.Config().ServiceSettings.ListenAddress
prevListenAddress := *a.Config().ServiceSettings.ListenAddress s.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" })
a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" })
serverErr := s.Start() serverErr := s.Start()
if serverErr != nil { if serverErr != nil {
panic(serverErr) panic(serverErr)
} }
a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) s.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress })
// Disable strict password requirements for test // Disable strict password requirements for test
a.UpdateConfig(func(cfg *model.Config) { s.UpdateConfig(func(cfg *model.Config) {
*cfg.PasswordSettings.MinimumLength = 5 *cfg.PasswordSettings.MinimumLength = 5
*cfg.PasswordSettings.Lowercase = false *cfg.PasswordSettings.Lowercase = false
*cfg.PasswordSettings.Uppercase = false *cfg.PasswordSettings.Uppercase = false
@@ -103,15 +102,16 @@ func setupTestHelper(t testing.TB, store store.Store, includeCacheLayer bool) *T
*cfg.PasswordSettings.Number = false *cfg.PasswordSettings.Number = false
}) })
a := app.New(app.ServerConnector(s))
a.InitServer()
web := New(s, s.AppOptions, s.Router) web := New(s, s.AppOptions, s.Router)
URL = fmt.Sprintf("http://localhost:%v", a.Srv().ListenAddr.Port) URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port)
ApiClient = model.NewAPIv4Client(URL) ApiClient = model.NewAPIv4Client(URL)
a.DoAppMigrations() s.Store.MarkSystemRanUnitTests()
a.Srv().Store.MarkSystemRanUnitTests() s.UpdateConfig(func(cfg *model.Config) {
a.UpdateConfig(func(cfg *model.Config) {
*cfg.TeamSettings.EnableOpenServer = true *cfg.TeamSettings.EnableOpenServer = true
}) })
@@ -155,7 +155,7 @@ func (th *TestHelper) InitBasic() *TestHelper {
func (th *TestHelper) TearDown() { func (th *TestHelper) TearDown() {
if th.IncludeCacheLayer { if th.IncludeCacheLayer {
// Clean all the caches // Clean all the caches
th.App.InvalidateAllCaches() th.App.Srv().InvalidateAllCaches()
} }
th.Server.Shutdown() th.Server.Shutdown()
} }

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

@@ -130,7 +130,7 @@ func TestIncomingWebhook(t *testing.T) {
}) })
t.Run("WebhookExperimentalReadOnly", func(t *testing.T) { t.Run("WebhookExperimentalReadOnly", func(t *testing.T) {
th.App.SetLicense(model.NewTestLicense()) th.App.Srv().SetLicense(model.NewTestLicense())
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })
// Read only default channel should fail. // Read only default channel should fail.

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

@@ -12,10 +12,11 @@ type API struct {
Router *app.WebSocketRouter Router *app.WebSocketRouter
} }
func Init(a *app.App, router *app.WebSocketRouter) { func Init(s *app.Server) {
a := app.New(app.ServerConnector(s))
api := &API{ api := &API{
App: a, App: a,
Router: router, Router: s.WebSocketRouter,
} }
api.InitUser() api.InitUser()