From 1adfd0e9be69a93c7f63bb7afc742c9fafe31aa3 Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 6 Sep 2017 17:12:54 -0500 Subject: app type transition (#7167) --- app/admin.go | 23 ++- app/analytics.go | 54 ++--- app/app.go | 10 + app/apptestlib.go | 46 ++--- app/audit.go | 8 +- app/authentication.go | 18 +- app/authorization.go | 52 ++--- app/authorization_test.go | 3 +- app/auto_environment.go | 5 +- app/auto_posts.go | 5 +- app/auto_users.go | 10 +- app/channel.go | 384 +++++++++++++++++----------------- app/channel_test.go | 50 ++--- app/cluster_discovery.go | 12 +- app/cluster_discovery_test.go | 3 +- app/cluster_handlers.go | 50 ++--- app/command.go | 58 +++--- app/command_away.go | 2 +- app/command_channel_header.go | 8 +- app/command_channel_purpose.go | 8 +- app/command_channel_rename.go | 8 +- app/command_channel_rename_test.go | 3 +- app/command_echo.go | 2 +- app/command_expand_collapse.go | 8 +- app/command_invite_people.go | 2 +- app/command_join.go | 8 +- app/command_leave.go | 6 +- app/command_loadtest.go | 14 +- app/command_logout.go | 2 +- app/command_msg.go | 10 +- app/command_offline.go | 2 +- app/command_online.go | 2 +- app/compliance.go | 15 +- app/diagnostics.go | 32 +-- app/diagnostics_test.go | 7 +- app/email.go | 7 +- app/email_batching.go | 25 +-- app/email_batching_test.go | 66 +++--- app/email_test.go | 38 ++-- app/emoji.go | 28 +-- app/file.go | 30 +-- app/file_test.go | 15 +- app/import.go | 166 +++++++-------- app/import_test.go | 386 ++++++++++++++++++----------------- app/job.go | 20 +- app/job_test.go | 32 +-- app/ldap.go | 16 +- app/license.go | 28 +-- app/license_test.go | 18 +- app/login.go | 14 +- app/notification.go | 64 +++--- app/notification_test.go | 72 ++++--- app/oauth.go | 170 ++++++++-------- app/oauth_test.go | 26 +-- app/plugins.go | 54 ++--- app/post.go | 164 +++++++-------- app/post_test.go | 25 ++- app/preference.go | 23 ++- app/reaction.go | 24 +-- app/saml.go | 3 +- app/security_update_check.go | 18 +- app/server.go | 36 ++-- app/session.go | 78 +++---- app/session_test.go | 3 +- app/slackimport.go | 77 +++---- app/status.go | 32 +-- app/team.go | 240 +++++++++++----------- app/team_test.go | 62 +++--- app/user.go | 408 ++++++++++++++++++------------------- app/user_test.go | 40 ++-- app/web_conn.go | 16 +- app/web_hub.go | 62 +++--- app/webhook.go | 112 +++++----- app/webhook_test.go | 11 +- app/websocket_router.go | 9 +- 75 files changed, 1869 insertions(+), 1779 deletions(-) (limited to 'app') diff --git a/app/admin.go b/app/admin.go index 609e37c96..577121915 100644 --- a/app/admin.go +++ b/app/admin.go @@ -11,13 +11,14 @@ import ( "runtime/debug" + "net/http" + l4g "github.com/alecthomas/log4go" "github.com/mattermost/platform/einterfaces" "github.com/mattermost/platform/jobs" "github.com/mattermost/platform/model" "github.com/mattermost/platform/store" "github.com/mattermost/platform/utils" - "net/http" ) func GetLogs(page, perPage int) ([]string, *model.AppError) { @@ -95,9 +96,9 @@ func GetClusterStatus() []*model.ClusterInfo { return infos } -func InvalidateAllCaches() *model.AppError { +func (a *App) InvalidateAllCaches() *model.AppError { debug.FreeOSMemory() - InvalidateAllCachesSkipSend() + a.InvalidateAllCachesSkipSend() if einterfaces.GetClusterInterface() != nil { @@ -113,7 +114,7 @@ func InvalidateAllCaches() *model.AppError { return nil } -func InvalidateAllCachesSkipSend() { +func (a *App) InvalidateAllCachesSkipSend() { l4g.Info(utils.T("api.context.invalidate_all_caches")) sessionCache.Purge() ClearStatusCache() @@ -121,7 +122,7 @@ func InvalidateAllCachesSkipSend() { store.ClearUserCaches() store.ClearPostCaches() store.ClearWebhookCaches() - LoadLicense() + a.LoadLicense() } func GetConfig() *model.Config { @@ -183,13 +184,13 @@ func SaveConfig(cfg *model.Config, sendConfigChangeClusterMessage bool) *model.A return nil } -func RecycleDatabaseConnection() { - oldStore := Srv.Store +func (a *App) RecycleDatabaseConnection() { + oldStore := a.Srv.Store l4g.Warn(utils.T("api.admin.recycle_db_start.warn")) - Srv.Store = store.NewLayeredStore() + a.Srv.Store = store.NewLayeredStore() - jobs.Srv.Store = Srv.Store + jobs.Srv.Store = a.Srv.Store time.Sleep(20 * time.Second) oldStore.Close() @@ -197,7 +198,7 @@ func RecycleDatabaseConnection() { l4g.Warn(utils.T("api.admin.recycle_db_end.warn")) } -func TestEmail(userId string, cfg *model.Config) *model.AppError { +func (a *App) TestEmail(userId string, cfg *model.Config) *model.AppError { if len(cfg.EmailSettings.SMTPServer) == 0 { return model.NewAppError("testEmail", "api.admin.test_email.missing_server", nil, utils.T("api.context.invalid_param.app_error", map[string]interface{}{"Name": "SMTPServer"}), http.StatusBadRequest) } @@ -213,7 +214,7 @@ func TestEmail(userId string, cfg *model.Config) *model.AppError { return model.NewAppError("testEmail", "api.admin.test_email.reenter_password", nil, "", http.StatusBadRequest) } } - if user, err := GetUser(userId); err != nil { + if user, err := a.GetUser(userId); err != nil { return err } else { T := utils.GetUserTranslations(user.Locale) diff --git a/app/analytics.go b/app/analytics.go index 35fbddd89..939abb71b 100644 --- a/app/analytics.go +++ b/app/analytics.go @@ -16,10 +16,10 @@ const ( MONTH_MILLISECONDS = 31 * DAY_MILLISECONDS ) -func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppError) { +func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppError) { skipIntensiveQueries := false var systemUserCount int64 - if r := <-Srv.Store.User().AnalyticsUniqueUserCount(""); r.Err != nil { + if r := <-a.Srv.Store.User().AnalyticsUniqueUserCount(""); r.Err != nil { return nil, r.Err } else { systemUserCount = r.Data.(int64) @@ -42,22 +42,22 @@ func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppEr rows[8] = &model.AnalyticsRow{Name: "daily_active_users", Value: 0} rows[9] = &model.AnalyticsRow{Name: "monthly_active_users", Value: 0} - openChan := Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) - privateChan := Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) - teamChan := Srv.Store.Team().AnalyticsTeamCount() + openChan := a.Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_OPEN) + privateChan := a.Srv.Store.Channel().AnalyticsTypeCount(teamId, model.CHANNEL_PRIVATE) + teamChan := a.Srv.Store.Team().AnalyticsTeamCount() var userChan store.StoreChannel if teamId != "" { - userChan = Srv.Store.User().AnalyticsUniqueUserCount(teamId) + userChan = a.Srv.Store.User().AnalyticsUniqueUserCount(teamId) } var postChan store.StoreChannel if !skipIntensiveQueries { - postChan = Srv.Store.Post().AnalyticsPostCount(teamId, false, false) + postChan = a.Srv.Store.Post().AnalyticsPostCount(teamId, false, false) } - dailyActiveChan := Srv.Store.User().AnalyticsActiveCount(DAY_MILLISECONDS) - monthlyActiveChan := Srv.Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS) + dailyActiveChan := a.Srv.Store.User().AnalyticsActiveCount(DAY_MILLISECONDS) + monthlyActiveChan := a.Srv.Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS) if r := <-openChan; r.Err != nil { return nil, r.Err @@ -105,8 +105,8 @@ func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppEr } totalSockets := TotalWebsocketConnections() - totalMasterDb := Srv.Store.TotalMasterDbConnections() - totalReadDb := Srv.Store.TotalReadDbConnections() + totalMasterDb := a.Srv.Store.TotalMasterDbConnections() + totalReadDb := a.Srv.Store.TotalReadDbConnections() for _, stat := range stats { totalSockets = totalSockets + stat.TotalWebsocketConnections @@ -120,8 +120,8 @@ func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppEr } else { rows[5].Value = float64(TotalWebsocketConnections()) - rows[6].Value = float64(Srv.Store.TotalMasterDbConnections()) - rows[7].Value = float64(Srv.Store.TotalReadDbConnections()) + rows[6].Value = float64(a.Srv.Store.TotalMasterDbConnections()) + rows[7].Value = float64(a.Srv.Store.TotalReadDbConnections()) } if r := <-dailyActiveChan; r.Err != nil { @@ -143,7 +143,7 @@ func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppEr return rows, nil } - if r := <-Srv.Store.Post().AnalyticsPostCountsByDay(teamId); r.Err != nil { + if r := <-a.Srv.Store.Post().AnalyticsPostCountsByDay(teamId); r.Err != nil { return nil, r.Err } else { return r.Data.(model.AnalyticsRows), nil @@ -154,7 +154,7 @@ func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppEr return rows, nil } - if r := <-Srv.Store.Post().AnalyticsUserCountsWithPostsByDay(teamId); r.Err != nil { + if r := <-a.Srv.Store.Post().AnalyticsUserCountsWithPostsByDay(teamId); r.Err != nil { return nil, r.Err } else { return r.Data.(model.AnalyticsRows), nil @@ -168,16 +168,16 @@ func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppEr rows[4] = &model.AnalyticsRow{Name: "command_count", Value: 0} rows[5] = &model.AnalyticsRow{Name: "session_count", Value: 0} - iHookChan := Srv.Store.Webhook().AnalyticsIncomingCount(teamId) - oHookChan := Srv.Store.Webhook().AnalyticsOutgoingCount(teamId) - commandChan := Srv.Store.Command().AnalyticsCommandCount(teamId) - sessionChan := Srv.Store.Session().AnalyticsSessionCount() + iHookChan := a.Srv.Store.Webhook().AnalyticsIncomingCount(teamId) + oHookChan := a.Srv.Store.Webhook().AnalyticsOutgoingCount(teamId) + commandChan := a.Srv.Store.Command().AnalyticsCommandCount(teamId) + sessionChan := a.Srv.Store.Session().AnalyticsSessionCount() var fileChan store.StoreChannel var hashtagChan store.StoreChannel if !skipIntensiveQueries { - fileChan = Srv.Store.Post().AnalyticsPostCount(teamId, true, false) - hashtagChan = Srv.Store.Post().AnalyticsPostCount(teamId, false, true) + fileChan = a.Srv.Store.Post().AnalyticsPostCount(teamId, true, false) + hashtagChan = a.Srv.Store.Post().AnalyticsPostCount(teamId, false, true) } if fileChan == nil { @@ -230,8 +230,8 @@ func GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppEr return nil, nil } -func GetRecentlyActiveUsersForTeam(teamId string) (map[string]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetRecentlyActiveUsersForTeam(teamId, 0, 100); result.Err != nil { +func (a *App) GetRecentlyActiveUsersForTeam(teamId string) (map[string]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetRecentlyActiveUsersForTeam(teamId, 0, 100); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -245,9 +245,9 @@ func GetRecentlyActiveUsersForTeam(teamId string) (map[string]*model.User, *mode } } -func GetRecentlyActiveUsersForTeamPage(teamId string, page, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { +func (a *App) GetRecentlyActiveUsersForTeamPage(teamId string, page, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { var users []*model.User - if result := <-Srv.Store.User().GetRecentlyActiveUsersForTeam(teamId, page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.User().GetRecentlyActiveUsersForTeam(teamId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { users = result.Data.([]*model.User) @@ -256,9 +256,9 @@ func GetRecentlyActiveUsersForTeamPage(teamId string, page, perPage int, asAdmin return sanitizeProfiles(users, asAdmin), nil } -func GetNewUsersForTeamPage(teamId string, page, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { +func (a *App) GetNewUsersForTeamPage(teamId string, page, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { var users []*model.User - if result := <-Srv.Store.User().GetNewUsersForTeam(teamId, page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.User().GetNewUsersForTeam(teamId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { users = result.Data.([]*model.User) diff --git a/app/app.go b/app/app.go index 2758add0e..ce812ed16 100644 --- a/app/app.go +++ b/app/app.go @@ -8,6 +8,16 @@ import ( "net/http" ) +type App struct { + Srv *Server +} + +var globalApp App + +func Global() *App { + return &globalApp +} + func CloseBody(r *http.Response) { if r.Body != nil { ioutil.ReadAll(r.Body) diff --git a/app/apptestlib.go b/app/apptestlib.go index 47fd6c727..1f84fa933 100644 --- a/app/apptestlib.go +++ b/app/apptestlib.go @@ -20,8 +20,8 @@ type TestHelper struct { BasicPost *model.Post } -func SetupEnterprise() *TestHelper { - if Srv == nil { +func (a *App) SetupEnterprise() *TestHelper { + if a.Srv == nil { utils.TranslationsPreInit() utils.LoadConfig("config.json") utils.InitTranslations(utils.Cfg.LocalizationSettings) @@ -29,12 +29,12 @@ func SetupEnterprise() *TestHelper { *utils.Cfg.RateLimitSettings.Enable = false utils.DisableDebugLogForTest() utils.License().Features.SetDefaults() - NewServer() - InitStores() - StartServer() + a.NewServer() + a.InitStores() + a.StartServer() utils.InitHTML() utils.EnableDebugLogForTest() - Srv.Store.MarkSystemRanUnitTests() + a.Srv.Store.MarkSystemRanUnitTests() *utils.Cfg.TeamSettings.EnableOpenServer = true } @@ -42,20 +42,20 @@ func SetupEnterprise() *TestHelper { return &TestHelper{} } -func Setup() *TestHelper { - if Srv == nil { +func (a *App) Setup() *TestHelper { + if a.Srv == nil { utils.TranslationsPreInit() utils.LoadConfig("config.json") utils.InitTranslations(utils.Cfg.LocalizationSettings) *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 *utils.Cfg.RateLimitSettings.Enable = false utils.DisableDebugLogForTest() - NewServer() - InitStores() - StartServer() + a.NewServer() + a.InitStores() + a.StartServer() utils.InitHTML() utils.EnableDebugLogForTest() - Srv.Store.MarkSystemRanUnitTests() + a.Srv.Store.MarkSystemRanUnitTests() *utils.Cfg.TeamSettings.EnableOpenServer = true } @@ -66,9 +66,9 @@ func Setup() *TestHelper { func (me *TestHelper) InitBasic() *TestHelper { me.BasicTeam = me.CreateTeam() me.BasicUser = me.CreateUser() - LinkUserToTeam(me.BasicUser, me.BasicTeam) + Global().LinkUserToTeam(me.BasicUser, me.BasicTeam) me.BasicUser2 = me.CreateUser() - LinkUserToTeam(me.BasicUser2, me.BasicTeam) + Global().LinkUserToTeam(me.BasicUser2, me.BasicTeam) me.BasicChannel = me.CreateChannel(me.BasicTeam) me.BasicPost = me.CreatePost(me.BasicChannel) @@ -94,7 +94,7 @@ func (me *TestHelper) CreateTeam() *model.Team { utils.DisableDebugLogForTest() var err *model.AppError - if team, err = CreateTeam(team); err != nil { + if team, err = Global().CreateTeam(team); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) @@ -117,7 +117,7 @@ func (me *TestHelper) CreateUser() *model.User { utils.DisableDebugLogForTest() var err *model.AppError - if user, err = CreateUser(user); err != nil { + if user, err = Global().CreateUser(user); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) @@ -148,7 +148,7 @@ func (me *TestHelper) createChannel(team *model.Team, channelType string) *model utils.DisableDebugLogForTest() var err *model.AppError - if channel, err = CreateChannel(channel, true); err != nil { + if channel, err = Global().CreateChannel(channel, true); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) @@ -169,7 +169,7 @@ func (me *TestHelper) CreatePost(channel *model.Channel) *model.Post { utils.DisableDebugLogForTest() var err *model.AppError - if post, err = CreatePost(post, channel, false); err != nil { + if post, err = Global().CreatePost(post, channel, false); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) @@ -179,10 +179,10 @@ func (me *TestHelper) CreatePost(channel *model.Channel) *model.Post { return post } -func LinkUserToTeam(user *model.User, team *model.Team) { +func (a *App) LinkUserToTeam(user *model.User, team *model.Team) { utils.DisableDebugLogForTest() - err := JoinUserToTeam(team, user, "") + err := a.JoinUserToTeam(team, user, "") if err != nil { l4g.Error(err.Error()) l4g.Close() @@ -193,8 +193,8 @@ func LinkUserToTeam(user *model.User, team *model.Team) { utils.EnableDebugLogForTest() } -func TearDown() { - if Srv != nil { - StopServer() +func (a *App) TearDown() { + if a.Srv != nil { + a.StopServer() } } diff --git a/app/audit.go b/app/audit.go index fdd152719..044aac9cb 100644 --- a/app/audit.go +++ b/app/audit.go @@ -7,16 +7,16 @@ import ( "github.com/mattermost/platform/model" ) -func GetAudits(userId string, limit int) (model.Audits, *model.AppError) { - if result := <-Srv.Store.Audit().Get(userId, 0, limit); result.Err != nil { +func (a *App) GetAudits(userId string, limit int) (model.Audits, *model.AppError) { + if result := <-a.Srv.Store.Audit().Get(userId, 0, limit); result.Err != nil { return nil, result.Err } else { return result.Data.(model.Audits), nil } } -func GetAuditsPage(userId string, page int, perPage int) (model.Audits, *model.AppError) { - if result := <-Srv.Store.Audit().Get(userId, page*perPage, perPage); result.Err != nil { +func (a *App) GetAuditsPage(userId string, page int, perPage int) (model.Audits, *model.AppError) { + if result := <-a.Srv.Store.Audit().Get(userId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.(model.Audits), nil diff --git a/app/authentication.go b/app/authentication.go index 5319e54e0..81aceaabb 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -12,12 +12,12 @@ import ( "github.com/mattermost/platform/utils" ) -func CheckPasswordAndAllCriteria(user *model.User, password string, mfaToken string) *model.AppError { +func (a *App) CheckPasswordAndAllCriteria(user *model.User, password string, mfaToken string) *model.AppError { if err := CheckUserAdditionalAuthenticationCriteria(user, mfaToken); err != nil { return err } - if err := checkUserPassword(user, password); err != nil { + if err := a.checkUserPassword(user, password); err != nil { return err } @@ -25,27 +25,27 @@ func CheckPasswordAndAllCriteria(user *model.User, password string, mfaToken str } // This to be used for places we check the users password when they are already logged in -func doubleCheckPassword(user *model.User, password string) *model.AppError { +func (a *App) doubleCheckPassword(user *model.User, password string) *model.AppError { if err := checkUserLoginAttempts(user); err != nil { return err } - if err := checkUserPassword(user, password); err != nil { + if err := a.checkUserPassword(user, password); err != nil { return err } return nil } -func checkUserPassword(user *model.User, password string) *model.AppError { +func (a *App) checkUserPassword(user *model.User, password string) *model.AppError { if !model.ComparePassword(user.Password, password) { - if result := <-Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); result.Err != nil { + if result := <-a.Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); result.Err != nil { return result.Err } return model.NewAppError("checkUserPassword", "api.user.check_user_password.invalid.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized) } else { - if result := <-Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, 0); result.Err != nil { + if result := <-a.Srv.Store.User().UpdateFailedPasswordAttempts(user.Id, 0); result.Err != nil { return result.Err } @@ -142,7 +142,7 @@ func checkUserNotDisabled(user *model.User) *model.AppError { return nil } -func 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) { ldapAvailable := *utils.Cfg.LdapSettings.Enable && einterfaces.GetLdapInterface() != nil && utils.IsLicensed() && *utils.License().Features.LDAP if user.AuthService == model.USER_AUTH_SERVICE_LDAP { @@ -164,7 +164,7 @@ func authenticateUser(user *model.User, password, mfaToken string) (*model.User, err := model.NewAppError("login", "api.user.login.use_auth_service.app_error", map[string]interface{}{"AuthService": authService}, "", http.StatusBadRequest) return user, err } else { - if err := CheckPasswordAndAllCriteria(user, password, mfaToken); err != nil { + if err := a.CheckPasswordAndAllCriteria(user, password, mfaToken); err != nil { err.StatusCode = http.StatusUnauthorized return user, err } else { diff --git a/app/authorization.go b/app/authorization.go index 28f968f68..90b9331f9 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -29,12 +29,12 @@ func SessionHasPermissionToTeam(session model.Session, teamId string, permission return SessionHasPermissionTo(session, permission) } -func SessionHasPermissionToChannel(session model.Session, channelId string, permission *model.Permission) bool { +func (a *App) SessionHasPermissionToChannel(session model.Session, channelId string, permission *model.Permission) bool { if channelId == "" { return false } - cmc := Srv.Store.Channel().GetAllChannelMembersForUser(session.UserId, true) + cmc := a.Srv.Store.Channel().GetAllChannelMembersForUser(session.UserId, true) var channelRoles []string if cmcresult := <-cmc; cmcresult.Err == nil { @@ -47,7 +47,7 @@ func SessionHasPermissionToChannel(session model.Session, channelId string, perm } } - channel, err := GetChannel(channelId) + channel, err := a.GetChannel(channelId) if err == nil && channel.TeamId != "" { return SessionHasPermissionToTeam(session, channel.TeamId, permission) } @@ -55,9 +55,9 @@ func SessionHasPermissionToChannel(session model.Session, channelId string, perm return SessionHasPermissionTo(session, permission) } -func SessionHasPermissionToChannelByPost(session model.Session, postId string, permission *model.Permission) bool { +func (a *App) SessionHasPermissionToChannelByPost(session model.Session, postId string, permission *model.Permission) bool { var channelMember *model.ChannelMember - if result := <-Srv.Store.Channel().GetMemberForPost(postId, session.UserId); result.Err == nil { + if result := <-a.Srv.Store.Channel().GetMemberForPost(postId, session.UserId); result.Err == nil { channelMember = result.Data.(*model.ChannelMember) if CheckIfRolesGrantPermission(channelMember.GetRoles(), permission.Id) { @@ -65,7 +65,7 @@ func SessionHasPermissionToChannelByPost(session model.Session, postId string, p } } - if result := <-Srv.Store.Channel().GetForPost(postId); result.Err == nil { + if result := <-a.Srv.Store.Channel().GetForPost(postId); result.Err == nil { channel := result.Data.(*model.Channel) return SessionHasPermissionToTeam(session, channel.TeamId, permission) } @@ -89,8 +89,8 @@ func SessionHasPermissionToUser(session model.Session, userId string) bool { return false } -func SessionHasPermissionToPost(session model.Session, postId string, permission *model.Permission) bool { - post, err := GetSinglePost(postId) +func (a *App) SessionHasPermissionToPost(session model.Session, postId string, permission *model.Permission) bool { + post, err := a.GetSinglePost(postId) if err != nil { return false } @@ -99,11 +99,11 @@ func SessionHasPermissionToPost(session model.Session, postId string, permission return true } - return SessionHasPermissionToChannel(session, post.ChannelId, permission) + return a.SessionHasPermissionToChannel(session, post.ChannelId, permission) } -func HasPermissionTo(askingUserId string, permission *model.Permission) bool { - user, err := GetUser(askingUserId) +func (a *App) HasPermissionTo(askingUserId string, permission *model.Permission) bool { + user, err := a.GetUser(askingUserId) if err != nil { return false } @@ -113,12 +113,12 @@ func HasPermissionTo(askingUserId string, permission *model.Permission) bool { return CheckIfRolesGrantPermission(roles, permission.Id) } -func HasPermissionToTeam(askingUserId string, teamId string, permission *model.Permission) bool { +func (a *App) HasPermissionToTeam(askingUserId string, teamId string, permission *model.Permission) bool { if teamId == "" || askingUserId == "" { return false } - teamMember, err := GetTeamMember(teamId, askingUserId) + teamMember, err := a.GetTeamMember(teamId, askingUserId) if err != nil { return false } @@ -129,15 +129,15 @@ func HasPermissionToTeam(askingUserId string, teamId string, permission *model.P return true } - return HasPermissionTo(askingUserId, permission) + return a.HasPermissionTo(askingUserId, permission) } -func HasPermissionToChannel(askingUserId string, channelId string, permission *model.Permission) bool { +func (a *App) HasPermissionToChannel(askingUserId string, channelId string, permission *model.Permission) bool { if channelId == "" || askingUserId == "" { return false } - channelMember, err := GetChannelMember(channelId, askingUserId) + channelMember, err := a.GetChannelMember(channelId, askingUserId) if err == nil { roles := channelMember.GetRoles() if CheckIfRolesGrantPermission(roles, permission.Id) { @@ -146,17 +146,17 @@ func HasPermissionToChannel(askingUserId string, channelId string, permission *m } var channel *model.Channel - channel, err = GetChannel(channelId) + channel, err = a.GetChannel(channelId) if err == nil { - return HasPermissionToTeam(askingUserId, channel.TeamId, permission) + return a.HasPermissionToTeam(askingUserId, channel.TeamId, permission) } - return HasPermissionTo(askingUserId, permission) + return a.HasPermissionTo(askingUserId, permission) } -func HasPermissionToChannelByPost(askingUserId string, postId string, permission *model.Permission) bool { +func (a *App) HasPermissionToChannelByPost(askingUserId string, postId string, permission *model.Permission) bool { var channelMember *model.ChannelMember - if result := <-Srv.Store.Channel().GetMemberForPost(postId, askingUserId); result.Err == nil { + if result := <-a.Srv.Store.Channel().GetMemberForPost(postId, askingUserId); result.Err == nil { channelMember = result.Data.(*model.ChannelMember) if CheckIfRolesGrantPermission(channelMember.GetRoles(), permission.Id) { @@ -164,20 +164,20 @@ func HasPermissionToChannelByPost(askingUserId string, postId string, permission } } - if result := <-Srv.Store.Channel().GetForPost(postId); result.Err == nil { + if result := <-a.Srv.Store.Channel().GetForPost(postId); result.Err == nil { channel := result.Data.(*model.Channel) - return HasPermissionToTeam(askingUserId, channel.TeamId, permission) + return a.HasPermissionToTeam(askingUserId, channel.TeamId, permission) } - return HasPermissionTo(askingUserId, permission) + return a.HasPermissionTo(askingUserId, permission) } -func HasPermissionToUser(askingUserId string, userId string) bool { +func (a *App) HasPermissionToUser(askingUserId string, userId string) bool { if askingUserId == userId { return true } - if HasPermissionTo(askingUserId, model.PERMISSION_EDIT_OTHER_USERS) { + if a.HasPermissionTo(askingUserId, model.PERMISSION_EDIT_OTHER_USERS) { return true } diff --git a/app/authorization_test.go b/app/authorization_test.go index 4d2fdd5a0..c090526c4 100644 --- a/app/authorization_test.go +++ b/app/authorization_test.go @@ -10,7 +10,8 @@ import ( ) func TestCheckIfRolesGrantPermission(t *testing.T) { - Setup() + a := Global() + a.Setup() cases := []struct { roles []string diff --git a/app/auto_environment.go b/app/auto_environment.go index 8827ddf87..5d6baa728 100644 --- a/app/auto_environment.go +++ b/app/auto_environment.go @@ -4,10 +4,11 @@ package app import ( - "github.com/mattermost/platform/model" - "github.com/mattermost/platform/utils" "math/rand" "time" + + "github.com/mattermost/platform/model" + "github.com/mattermost/platform/utils" ) type TestEnvironment struct { diff --git a/app/auto_posts.go b/app/auto_posts.go index 6a2a15908..8818a94f9 100644 --- a/app/auto_posts.go +++ b/app/auto_posts.go @@ -5,10 +5,11 @@ package app import ( "bytes" - "github.com/mattermost/platform/model" - "github.com/mattermost/platform/utils" "io" "os" + + "github.com/mattermost/platform/model" + "github.com/mattermost/platform/utils" ) type AutoPostCreator struct { diff --git a/app/auto_users.go b/app/auto_users.go index c96321846..770d12172 100644 --- a/app/auto_users.go +++ b/app/auto_users.go @@ -34,7 +34,7 @@ func NewAutoUserCreator(client *model.Client, team *model.Team) *AutoUserCreator } // Basic test team and user so you always know one -func CreateBasicUser(client *model.Client) *model.AppError { +func (a *App) CreateBasicUser(client *model.Client) *model.AppError { result, _ := client.FindTeamByName(BTEST_TEAM_NAME) if result.Data.(bool) == false { newteam := &model.Team{DisplayName: BTEST_TEAM_DISPLAY_NAME, Name: BTEST_TEAM_NAME, Email: BTEST_TEAM_EMAIL, Type: BTEST_TEAM_TYPE} @@ -49,8 +49,8 @@ func CreateBasicUser(client *model.Client) *model.AppError { return err } ruser := result.Data.(*model.User) - store.Must(Srv.Store.User().VerifyEmail(ruser.Id)) - store.Must(Srv.Store.Team().SaveMember(&model.TeamMember{TeamId: basicteam.Id, UserId: ruser.Id})) + store.Must(a.Srv.Store.User().VerifyEmail(ruser.Id)) + store.Must(a.Srv.Store.Team().SaveMember(&model.TeamMember{TeamId: basicteam.Id, UserId: ruser.Id})) } return nil } @@ -81,14 +81,14 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, bool) { ruser := result.Data.(*model.User) status := &model.Status{UserId: ruser.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} - if result := <-Srv.Store.Status().SaveOrUpdate(status); result.Err != nil { + if result := <-Global().Srv.Store.Status().SaveOrUpdate(status); result.Err != nil { result.Err.Translate(utils.T) l4g.Error(result.Err.Error()) return nil, false } // We need to cheat to verify the user's email - store.Must(Srv.Store.User().VerifyEmail(ruser.Id)) + store.Must(Global().Srv.Store.User().VerifyEmail(ruser.Id)) return result.Data.(*model.User), true } diff --git a/app/channel.go b/app/channel.go index 8da0ca61c..cb46d6a27 100644 --- a/app/channel.go +++ b/app/channel.go @@ -15,16 +15,16 @@ import ( "github.com/mattermost/platform/utils" ) -func CreateDefaultChannels(teamId string) ([]*model.Channel, *model.AppError) { +func (a *App) CreateDefaultChannels(teamId string) ([]*model.Channel, *model.AppError) { townSquare := &model.Channel{DisplayName: utils.T("api.channel.create_default_channels.town_square"), Name: "town-square", Type: model.CHANNEL_OPEN, TeamId: teamId} - if _, err := CreateChannel(townSquare, false); err != nil { + if _, err := a.CreateChannel(townSquare, false); err != nil { return nil, err } offTopic := &model.Channel{DisplayName: utils.T("api.channel.create_default_channels.off_topic"), Name: "off-topic", Type: model.CHANNEL_OPEN, TeamId: teamId} - if _, err := CreateChannel(offTopic, false); err != nil { + if _, err := a.CreateChannel(offTopic, false); err != nil { return nil, err } @@ -32,19 +32,19 @@ func CreateDefaultChannels(teamId string) ([]*model.Channel, *model.AppError) { return channels, nil } -func JoinDefaultChannels(teamId string, user *model.User, channelRole string, userRequestorId string) *model.AppError { +func (a *App) JoinDefaultChannels(teamId string, user *model.User, channelRole string, userRequestorId string) *model.AppError { var err *model.AppError = nil var requestor *model.User if userRequestorId != "" { - if u := <-Srv.Store.User().Get(userRequestorId); u.Err != nil { + if u := <-a.Srv.Store.User().Get(userRequestorId); u.Err != nil { return u.Err } else { requestor = u.Data.(*model.User) } } - if result := <-Srv.Store.Channel().GetByName(teamId, "town-square", true); result.Err != nil { + if result := <-a.Srv.Store.Channel().GetByName(teamId, "town-square", true); result.Err != nil { err = result.Err } else { townSquare := result.Data.(*model.Channel) @@ -52,24 +52,24 @@ func JoinDefaultChannels(teamId string, user *model.User, channelRole string, us cm := &model.ChannelMember{ChannelId: townSquare.Id, UserId: user.Id, Roles: channelRole, NotifyProps: model.GetDefaultChannelNotifyProps()} - if cmResult := <-Srv.Store.Channel().SaveMember(cm); cmResult.Err != nil { + if cmResult := <-a.Srv.Store.Channel().SaveMember(cm); cmResult.Err != nil { err = cmResult.Err } if requestor == nil { - if err := postJoinChannelMessage(user, townSquare); err != nil { + if err := a.postJoinChannelMessage(user, townSquare); err != nil { l4g.Error(utils.T("api.channel.post_user_add_remove_message_and_forget.error"), err) } } else { - if err := PostAddToChannelMessage(requestor, user, townSquare); err != nil { + if err := a.PostAddToChannelMessage(requestor, user, townSquare); err != nil { l4g.Error(utils.T("api.channel.post_user_add_remove_message_and_forget.error"), err) } } - InvalidateCacheForChannelMembers(result.Data.(*model.Channel).Id) + a.InvalidateCacheForChannelMembers(result.Data.(*model.Channel).Id) } - if result := <-Srv.Store.Channel().GetByName(teamId, "off-topic", true); result.Err != nil { + if result := <-a.Srv.Store.Channel().GetByName(teamId, "off-topic", true); result.Err != nil { err = result.Err } else { offTopic := result.Data.(*model.Channel) @@ -77,27 +77,27 @@ func JoinDefaultChannels(teamId string, user *model.User, channelRole string, us cm := &model.ChannelMember{ChannelId: offTopic.Id, UserId: user.Id, Roles: channelRole, NotifyProps: model.GetDefaultChannelNotifyProps()} - if cmResult := <-Srv.Store.Channel().SaveMember(cm); cmResult.Err != nil { + if cmResult := <-a.Srv.Store.Channel().SaveMember(cm); cmResult.Err != nil { err = cmResult.Err } if requestor == nil { - if err := postJoinChannelMessage(user, offTopic); err != nil { + if err := a.postJoinChannelMessage(user, offTopic); err != nil { l4g.Error(utils.T("api.channel.post_user_add_remove_message_and_forget.error"), err) } } else { - if err := PostAddToChannelMessage(requestor, user, offTopic); err != nil { + if err := a.PostAddToChannelMessage(requestor, user, offTopic); err != nil { l4g.Error(utils.T("api.channel.post_user_add_remove_message_and_forget.error"), err) } } - InvalidateCacheForChannelMembers(result.Data.(*model.Channel).Id) + a.InvalidateCacheForChannelMembers(result.Data.(*model.Channel).Id) } return err } -func CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channel, *model.AppError) { +func (a *App) CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channel, *model.AppError) { if channel.IsGroupOrDirect() { return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.direct_channel.app_error", nil, "", http.StatusBadRequest) } @@ -111,7 +111,7 @@ func CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channe } // Get total number of channels on current team - if count, err := GetNumberOfChannelsOnTeam(channel.TeamId); err != nil { + if count, err := a.GetNumberOfChannelsOnTeam(channel.TeamId); err != nil { return nil, err } else { if int64(count+1) > *utils.Cfg.TeamSettings.MaxChannelsPerTeam { @@ -121,17 +121,17 @@ func CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channe channel.CreatorId = userId - rchannel, err := CreateChannel(channel, true) + rchannel, err := a.CreateChannel(channel, true) if err != nil { return nil, err } var user *model.User - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return nil, err } - postJoinChannelMessage(user, channel) + a.postJoinChannelMessage(user, channel) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CREATED, "", "", userId, nil) message.Add("channel_id", channel.Id) @@ -141,8 +141,8 @@ func CreateChannelWithUser(channel *model.Channel, userId string) (*model.Channe return rchannel, nil } -func CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { - if result := <-Srv.Store.Channel().Save(channel); result.Err != nil { +func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { + if result := <-a.Srv.Store.Channel().Save(channel); result.Err != nil { return nil, result.Err } else { sc := result.Data.(*model.Channel) @@ -155,29 +155,29 @@ func CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *mod NotifyProps: model.GetDefaultChannelNotifyProps(), } - if cmresult := <-Srv.Store.Channel().SaveMember(cm); cmresult.Err != nil { + if cmresult := <-a.Srv.Store.Channel().SaveMember(cm); cmresult.Err != nil { return nil, cmresult.Err } - InvalidateCacheForUser(channel.CreatorId) + a.InvalidateCacheForUser(channel.CreatorId) } return sc, nil } } -func CreateDirectChannel(userId string, otherUserId string) (*model.Channel, *model.AppError) { - if channel, err := createDirectChannel(userId, otherUserId); err != nil { +func (a *App) CreateDirectChannel(userId string, otherUserId string) (*model.Channel, *model.AppError) { + if channel, err := a.createDirectChannel(userId, otherUserId); err != nil { if err.Id == store.CHANNEL_EXISTS_ERROR { return channel, nil } else { return nil, err } } else { - WaitForChannelMembership(channel.Id, userId) + a.WaitForChannelMembership(channel.Id, userId) - InvalidateCacheForUser(userId) - InvalidateCacheForUser(otherUserId) + a.InvalidateCacheForUser(userId) + a.InvalidateCacheForUser(otherUserId) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_DIRECT_ADDED, "", channel.Id, "", nil) message.Add("teammate_id", otherUserId) @@ -187,9 +187,9 @@ func CreateDirectChannel(userId string, otherUserId string) (*model.Channel, *mo } } -func createDirectChannel(userId string, otherUserId string) (*model.Channel, *model.AppError) { - uc1 := Srv.Store.User().Get(userId) - uc2 := Srv.Store.User().Get(otherUserId) +func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Channel, *model.AppError) { + uc1 := a.Srv.Store.User().Get(userId) + uc2 := a.Srv.Store.User().Get(otherUserId) if result := <-uc1; result.Err != nil { return nil, model.NewAppError("CreateDirectChannel", "api.channel.create_direct_channel.invalid_user.app_error", nil, userId, http.StatusBadRequest) @@ -199,7 +199,7 @@ func createDirectChannel(userId string, otherUserId string) (*model.Channel, *mo return nil, model.NewAppError("CreateDirectChannel", "api.channel.create_direct_channel.invalid_user.app_error", nil, otherUserId, http.StatusBadRequest) } - if result := <-Srv.Store.Channel().CreateDirectChannel(userId, otherUserId); result.Err != nil { + if result := <-a.Srv.Store.Channel().CreateDirectChannel(userId, otherUserId); result.Err != nil { if result.Err.Id == store.CHANNEL_EXISTS_ERROR { return result.Data.(*model.Channel), result.Err } else { @@ -211,7 +211,7 @@ func createDirectChannel(userId string, otherUserId string) (*model.Channel, *mo } } -func WaitForChannelMembership(channelId string, userId string) { +func (a *App) WaitForChannelMembership(channelId string, userId string) { if len(utils.Cfg.SqlSettings.DataSourceReplicas) > 0 { now := model.GetMillis() @@ -219,7 +219,7 @@ func WaitForChannelMembership(channelId string, userId string) { time.Sleep(100 * time.Millisecond) - result := <-Srv.Store.Channel().GetMember(channelId, userId) + result := <-a.Srv.Store.Channel().GetMember(channelId, userId) // If the membership was found then return if result.Err == nil { @@ -236,8 +236,8 @@ func WaitForChannelMembership(channelId string, userId string) { } } -func CreateGroupChannel(userIds []string, creatorId string) (*model.Channel, *model.AppError) { - if channel, err := createGroupChannel(userIds, creatorId); err != nil { +func (a *App) CreateGroupChannel(userIds []string, creatorId string) (*model.Channel, *model.AppError) { + if channel, err := a.createGroupChannel(userIds, creatorId); err != nil { if err.Id == store.CHANNEL_EXISTS_ERROR { return channel, nil } else { @@ -246,10 +246,10 @@ func CreateGroupChannel(userIds []string, creatorId string) (*model.Channel, *mo } else { for _, userId := range userIds { if userId == creatorId { - WaitForChannelMembership(channel.Id, creatorId) + a.WaitForChannelMembership(channel.Id, creatorId) } - InvalidateCacheForUser(userId) + a.InvalidateCacheForUser(userId) } message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_GROUP_ADDED, "", channel.Id, "", nil) @@ -260,13 +260,13 @@ func CreateGroupChannel(userIds []string, creatorId string) (*model.Channel, *mo } } -func createGroupChannel(userIds []string, creatorId string) (*model.Channel, *model.AppError) { +func (a *App) createGroupChannel(userIds []string, creatorId string) (*model.Channel, *model.AppError) { if len(userIds) > model.CHANNEL_GROUP_MAX_USERS || len(userIds) < model.CHANNEL_GROUP_MIN_USERS { return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } var users []*model.User - if result := <-Srv.Store.User().GetProfileByIds(userIds, true); result.Err != nil { + if result := <-a.Srv.Store.User().GetProfileByIds(userIds, true); result.Err != nil { return nil, result.Err } else { users = result.Data.([]*model.User) @@ -282,7 +282,7 @@ func createGroupChannel(userIds []string, creatorId string) (*model.Channel, *mo Type: model.CHANNEL_GROUP, } - if result := <-Srv.Store.Channel().Save(group); result.Err != nil { + if result := <-a.Srv.Store.Channel().Save(group); result.Err != nil { if result.Err.Id == store.CHANNEL_EXISTS_ERROR { return result.Data.(*model.Channel), result.Err } else { @@ -299,7 +299,7 @@ func createGroupChannel(userIds []string, creatorId string) (*model.Channel, *mo Roles: model.ROLE_CHANNEL_USER.Id, } - if result := <-Srv.Store.Channel().SaveMember(cm); result.Err != nil { + if result := <-a.Srv.Store.Channel().SaveMember(cm); result.Err != nil { return nil, result.Err } } @@ -308,11 +308,11 @@ func createGroupChannel(userIds []string, creatorId string) (*model.Channel, *mo } } -func UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) { - if result := <-Srv.Store.Channel().Update(channel); result.Err != nil { +func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) { + if result := <-a.Srv.Store.Channel().Update(channel); result.Err != nil { return nil, result.Err } else { - InvalidateCacheForChannel(channel) + a.InvalidateCacheForChannel(channel) messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_UPDATED, "", channel.Id, "", nil) messageWs.Add("channel", channel.ToJson()) @@ -322,39 +322,39 @@ func UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppError) { } } -func RestoreChannel(channel *model.Channel) (*model.Channel, *model.AppError) { - if result := <-Srv.Store.Channel().Restore(channel.Id, model.GetMillis()); result.Err != nil { +func (a *App) RestoreChannel(channel *model.Channel) (*model.Channel, *model.AppError) { + if result := <-a.Srv.Store.Channel().Restore(channel.Id, model.GetMillis()); result.Err != nil { return nil, result.Err } else { return channel, nil } } -func PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userId string) (*model.Channel, *model.AppError) { +func (a *App) PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userId string) (*model.Channel, *model.AppError) { oldChannelDisplayName := channel.DisplayName oldChannelHeader := channel.Header oldChannelPurpose := channel.Purpose channel.Patch(patch) - channel, err := UpdateChannel(channel) + channel, err := a.UpdateChannel(channel) if err != nil { return nil, err } if oldChannelDisplayName != channel.DisplayName { - if err := PostUpdateChannelDisplayNameMessage(userId, channel, oldChannelDisplayName, channel.DisplayName); err != nil { + if err := a.PostUpdateChannelDisplayNameMessage(userId, channel, oldChannelDisplayName, channel.DisplayName); err != nil { l4g.Error(err.Error()) } } if channel.Header != oldChannelHeader { - if err := PostUpdateChannelHeaderMessage(userId, channel, oldChannelHeader, channel.Header); err != nil { + if err := a.PostUpdateChannelHeaderMessage(userId, channel, oldChannelHeader, channel.Header); err != nil { l4g.Error(err.Error()) } } if channel.Purpose != oldChannelPurpose { - if err := PostUpdateChannelPurposeMessage(userId, channel, oldChannelPurpose, channel.Purpose); err != nil { + if err := a.PostUpdateChannelPurposeMessage(userId, channel, oldChannelPurpose, channel.Purpose); err != nil { l4g.Error(err.Error()) } } @@ -362,27 +362,27 @@ func PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userId stri return channel, err } -func UpdateChannelMemberRoles(channelId string, userId string, newRoles string) (*model.ChannelMember, *model.AppError) { +func (a *App) UpdateChannelMemberRoles(channelId string, userId string, newRoles string) (*model.ChannelMember, *model.AppError) { var member *model.ChannelMember var err *model.AppError - if member, err = GetChannelMember(channelId, userId); err != nil { + if member, err = a.GetChannelMember(channelId, userId); err != nil { return nil, err } member.Roles = newRoles - if result := <-Srv.Store.Channel().UpdateMember(member); result.Err != nil { + if result := <-a.Srv.Store.Channel().UpdateMember(member); result.Err != nil { return nil, result.Err } - InvalidateCacheForUser(userId) + a.InvalidateCacheForUser(userId) return member, nil } -func UpdateChannelMemberNotifyProps(data map[string]string, channelId string, userId string) (*model.ChannelMember, *model.AppError) { +func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelId string, userId string) (*model.ChannelMember, *model.AppError) { var member *model.ChannelMember var err *model.AppError - if member, err = GetChannelMember(channelId, userId); err != nil { + if member, err = a.GetChannelMember(channelId, userId); err != nil { return nil, err } @@ -403,19 +403,19 @@ func UpdateChannelMemberNotifyProps(data map[string]string, channelId string, us member.NotifyProps[model.PUSH_NOTIFY_PROP] = push } - if result := <-Srv.Store.Channel().UpdateMember(member); result.Err != nil { + if result := <-a.Srv.Store.Channel().UpdateMember(member); result.Err != nil { return nil, result.Err } else { - InvalidateCacheForUser(userId) - InvalidateCacheForChannelMembersNotifyProps(channelId) + a.InvalidateCacheForUser(userId) + a.InvalidateCacheForChannelMembersNotifyProps(channelId) return member, nil } } -func DeleteChannel(channel *model.Channel, userId string) *model.AppError { - uc := Srv.Store.User().Get(userId) - ihc := Srv.Store.Webhook().GetIncomingByChannel(channel.Id) - ohc := Srv.Store.Webhook().GetOutgoingByChannel(channel.Id, -1, -1) +func (a *App) DeleteChannel(channel *model.Channel, userId string) *model.AppError { + uc := a.Srv.Store.User().Get(userId) + ihc := a.Srv.Store.Webhook().GetIncomingByChannel(channel.Id) + ohc := a.Srv.Store.Webhook().GetOutgoingByChannel(channel.Id, -1, -1) if uresult := <-uc; uresult.Err != nil { return uresult.Err @@ -450,28 +450,28 @@ func DeleteChannel(channel *model.Channel, userId string) *model.AppError { }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { l4g.Error(utils.T("api.channel.delete_channel.failed_post.error"), err) } now := model.GetMillis() for _, hook := range incomingHooks { - if result := <-Srv.Store.Webhook().DeleteIncoming(hook.Id, now); result.Err != nil { + if result := <-a.Srv.Store.Webhook().DeleteIncoming(hook.Id, now); result.Err != nil { l4g.Error(utils.T("api.channel.delete_channel.incoming_webhook.error"), hook.Id) } - InvalidateCacheForWebhook(hook.Id) + a.InvalidateCacheForWebhook(hook.Id) } for _, hook := range outgoingHooks { - if result := <-Srv.Store.Webhook().DeleteOutgoing(hook.Id, now); result.Err != nil { + if result := <-a.Srv.Store.Webhook().DeleteOutgoing(hook.Id, now); result.Err != nil { l4g.Error(utils.T("api.channel.delete_channel.outgoing_webhook.error"), hook.Id) } } - if dresult := <-Srv.Store.Channel().Delete(channel.Id, model.GetMillis()); dresult.Err != nil { + if dresult := <-a.Srv.Store.Channel().Delete(channel.Id, model.GetMillis()); dresult.Err != nil { return dresult.Err } - InvalidateCacheForChannel(channel) + a.InvalidateCacheForChannel(channel) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_DELETED, channel.TeamId, "", "", nil) message.Add("channel_id", channel.Id) @@ -482,7 +482,7 @@ func DeleteChannel(channel *model.Channel, userId string) *model.AppError { return nil } -func addUserToChannel(user *model.User, channel *model.Channel, teamMember *model.TeamMember) (*model.ChannelMember, *model.AppError) { +func (a *App) addUserToChannel(user *model.User, channel *model.Channel, teamMember *model.TeamMember) (*model.ChannelMember, *model.AppError) { if channel.DeleteAt > 0 { return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user_to_channel.deleted.app_error", nil, "", http.StatusBadRequest) } @@ -491,7 +491,7 @@ func addUserToChannel(user *model.User, channel *model.Channel, teamMember *mode return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest) } - cmchan := Srv.Store.Channel().GetMember(channel.Id, user.Id) + cmchan := a.Srv.Store.Channel().GetMember(channel.Id, user.Id) if result := <-cmchan; result.Err != nil { if result.Err.Id != store.MISSING_CHANNEL_MEMBER_ERROR { @@ -508,21 +508,21 @@ func addUserToChannel(user *model.User, channel *model.Channel, teamMember *mode NotifyProps: model.GetDefaultChannelNotifyProps(), Roles: model.ROLE_CHANNEL_USER.Id, } - if result := <-Srv.Store.Channel().SaveMember(newMember); result.Err != nil { + if result := <-a.Srv.Store.Channel().SaveMember(newMember); result.Err != nil { l4g.Error("Failed to add member user_id=%v channel_id=%v err=%v", user.Id, channel.Id, result.Err) return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user.to.channel.failed.app_error", nil, "", http.StatusInternalServerError) } - WaitForChannelMembership(channel.Id, user.Id) + a.WaitForChannelMembership(channel.Id, user.Id) - InvalidateCacheForUser(user.Id) - InvalidateCacheForChannelMembers(channel.Id) + a.InvalidateCacheForUser(user.Id) + a.InvalidateCacheForChannelMembers(channel.Id) return newMember, nil } -func AddUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) { - tmchan := Srv.Store.Team().GetMember(channel.TeamId, user.Id) +func (a *App) AddUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) { + tmchan := a.Srv.Store.Team().GetMember(channel.TeamId, user.Id) var teamMember *model.TeamMember if result := <-tmchan; result.Err != nil { @@ -534,7 +534,7 @@ func AddUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelM } } - newMember, err := addUserToChannel(user, channel, teamMember) + newMember, err := a.addUserToChannel(user, channel, teamMember) if err != nil { return nil, err } @@ -547,8 +547,8 @@ func AddUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelM return newMember, nil } -func AddChannelMember(userId string, channel *model.Channel, userRequestorId string) (*model.ChannelMember, *model.AppError) { - if result := <-Srv.Store.Channel().GetMember(channel.Id, userId); result.Err != nil { +func (a *App) AddChannelMember(userId string, channel *model.Channel, userRequestorId string) (*model.ChannelMember, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetMember(channel.Id, userId); result.Err != nil { if result.Err.Id != store.MISSING_CHANNEL_MEMBER_ERROR { return nil, result.Err } @@ -559,34 +559,34 @@ func AddChannelMember(userId string, channel *model.Channel, userRequestorId str var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return nil, err } var userRequestor *model.User - if userRequestor, err = GetUser(userRequestorId); err != nil { + if userRequestor, err = a.GetUser(userRequestorId); err != nil { return nil, err } - cm, err := AddUserToChannel(user, channel) + cm, err := a.AddUserToChannel(user, channel) if err != nil { return nil, err } if userId == userRequestorId { - postJoinChannelMessage(user, channel) + a.postJoinChannelMessage(user, channel) } else { - go PostAddToChannelMessage(userRequestor, user, channel) + go a.PostAddToChannelMessage(userRequestor, user, channel) } - UpdateChannelLastViewedAt([]string{channel.Id}, userRequestor.Id) + a.UpdateChannelLastViewedAt([]string{channel.Id}, userRequestor.Id) return cm, nil } -func AddDirectChannels(teamId string, user *model.User) *model.AppError { +func (a *App) AddDirectChannels(teamId string, user *model.User) *model.AppError { var profiles []*model.User - if result := <-Srv.Store.User().GetProfiles(teamId, 0, 100); result.Err != nil { + if result := <-a.Srv.Store.User().GetProfiles(teamId, 0, 100); result.Err != nil { return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]interface{}{"UserId": user.Id, "TeamId": teamId, "Error": result.Err.Error()}, "", http.StatusInternalServerError) } else { profiles = result.Data.([]*model.User) @@ -613,15 +613,15 @@ func AddDirectChannels(teamId string, user *model.User) *model.AppError { } } - if result := <-Srv.Store.Preference().Save(&preferences); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&preferences); result.Err != nil { return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]interface{}{"UserId": user.Id, "TeamId": teamId, "Error": result.Err.Error()}, "", http.StatusInternalServerError) } return nil } -func PostUpdateChannelHeaderMessage(userId string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { - uc := Srv.Store.User().Get(userId) +func (a *App) PostUpdateChannelHeaderMessage(userId string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { + uc := a.Srv.Store.User().Get(userId) if uresult := <-uc; uresult.Err != nil { return model.NewAppError("PostUpdateChannelHeaderMessage", "api.channel.post_update_channel_header_message_and_forget.retrieve_user.error", nil, uresult.Err.Error(), http.StatusBadRequest) @@ -649,7 +649,7 @@ func PostUpdateChannelHeaderMessage(userId string, channel *model.Channel, oldCh }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { return model.NewAppError("", "api.channel.post_update_channel_header_message_and_forget.post.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -657,8 +657,8 @@ func PostUpdateChannelHeaderMessage(userId string, channel *model.Channel, oldCh return nil } -func PostUpdateChannelPurposeMessage(userId string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { - uc := Srv.Store.User().Get(userId) +func (a *App) PostUpdateChannelPurposeMessage(userId string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { + uc := a.Srv.Store.User().Get(userId) if uresult := <-uc; uresult.Err != nil { return model.NewAppError("PostUpdateChannelPurposeMessage", "app.channel.post_update_channel_purpose_message.retrieve_user.error", nil, uresult.Err.Error(), http.StatusBadRequest) @@ -685,7 +685,7 @@ func PostUpdateChannelPurposeMessage(userId string, channel *model.Channel, oldC "new_purpose": newChannelPurpose, }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { return model.NewAppError("", "app.channel.post_update_channel_purpose_message.post.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -693,8 +693,8 @@ func PostUpdateChannelPurposeMessage(userId string, channel *model.Channel, oldC return nil } -func PostUpdateChannelDisplayNameMessage(userId string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { - uc := Srv.Store.User().Get(userId) +func (a *App) PostUpdateChannelDisplayNameMessage(userId string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { + uc := a.Srv.Store.User().Get(userId) if uresult := <-uc; uresult.Err != nil { return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.retrieve_user.error", nil, uresult.Err.Error(), http.StatusBadRequest) @@ -715,7 +715,7 @@ func PostUpdateChannelDisplayNameMessage(userId string, channel *model.Channel, }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.create_post.error", nil, err.Error(), http.StatusInternalServerError) } } @@ -723,8 +723,8 @@ func PostUpdateChannelDisplayNameMessage(userId string, channel *model.Channel, return nil } -func GetChannel(channelId string) (*model.Channel, *model.AppError) { - if result := <-Srv.Store.Channel().Get(channelId, true); result.Err != nil && result.Err.Id == "store.sql_channel.get.existing.app_error" { +func (a *App) GetChannel(channelId string) (*model.Channel, *model.AppError) { + if result := <-a.Srv.Store.Channel().Get(channelId, true); result.Err != nil && result.Err.Id == "store.sql_channel.get.existing.app_error" { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else if result.Err != nil { @@ -735,8 +735,8 @@ func GetChannel(channelId string) (*model.Channel, *model.AppError) { } } -func GetChannelByName(channelName, teamId string) (*model.Channel, *model.AppError) { - if result := <-Srv.Store.Channel().GetByName(teamId, channelName, true); result.Err != nil && result.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { +func (a *App) GetChannelByName(channelName, teamId string) (*model.Channel, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetByName(teamId, channelName, true); result.Err != nil && result.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else if result.Err != nil { @@ -747,17 +747,17 @@ func GetChannelByName(channelName, teamId string) (*model.Channel, *model.AppErr } } -func GetChannelByNameForTeamName(channelName, teamName string) (*model.Channel, *model.AppError) { +func (a *App) GetChannelByNameForTeamName(channelName, teamName string) (*model.Channel, *model.AppError) { var team *model.Team - if result := <-Srv.Store.Team().GetByName(teamName); result.Err != nil { + if result := <-a.Srv.Store.Team().GetByName(teamName); result.Err != nil { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else { team = result.Data.(*model.Team) } - if result := <-Srv.Store.Channel().GetByName(team.Id, channelName, true); result.Err != nil && result.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { + if result := <-a.Srv.Store.Channel().GetByName(team.Id, channelName, true); result.Err != nil && result.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else if result.Err != nil { @@ -768,96 +768,96 @@ func GetChannelByNameForTeamName(channelName, teamName string) (*model.Channel, } } -func GetChannelsForUser(teamId string, userId string) (*model.ChannelList, *model.AppError) { - if result := <-Srv.Store.Channel().GetChannels(teamId, userId); result.Err != nil { +func (a *App) GetChannelsForUser(teamId string, userId string) (*model.ChannelList, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetChannels(teamId, userId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelList), nil } } -func GetDeletedChannels(teamId string, offset int, limit int) (*model.ChannelList, *model.AppError) { - if result := <-Srv.Store.Channel().GetDeleted(teamId, offset, limit); result.Err != nil { +func (a *App) GetDeletedChannels(teamId string, offset int, limit int) (*model.ChannelList, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetDeleted(teamId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelList), nil } } -func GetChannelsUserNotIn(teamId string, userId string, offset int, limit int) (*model.ChannelList, *model.AppError) { - if result := <-Srv.Store.Channel().GetMoreChannels(teamId, userId, offset, limit); result.Err != nil { +func (a *App) GetChannelsUserNotIn(teamId string, userId string, offset int, limit int) (*model.ChannelList, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetMoreChannels(teamId, userId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelList), nil } } -func GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) (*model.ChannelList, *model.AppError) { - if result := <-Srv.Store.Channel().GetPublicChannelsByIdsForTeam(teamId, channelIds); result.Err != nil { +func (a *App) GetPublicChannelsByIdsForTeam(teamId string, channelIds []string) (*model.ChannelList, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetPublicChannelsByIdsForTeam(teamId, channelIds); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelList), nil } } -func GetPublicChannelsForTeam(teamId string, offset int, limit int) (*model.ChannelList, *model.AppError) { - if result := <-Srv.Store.Channel().GetPublicChannelsForTeam(teamId, offset, limit); result.Err != nil { +func (a *App) GetPublicChannelsForTeam(teamId string, offset int, limit int) (*model.ChannelList, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetPublicChannelsForTeam(teamId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelList), nil } } -func GetChannelMember(channelId string, userId string) (*model.ChannelMember, *model.AppError) { - if result := <-Srv.Store.Channel().GetMember(channelId, userId); result.Err != nil { +func (a *App) GetChannelMember(channelId string, userId string) (*model.ChannelMember, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetMember(channelId, userId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelMember), nil } } -func GetChannelMembersPage(channelId string, page, perPage int) (*model.ChannelMembers, *model.AppError) { - if result := <-Srv.Store.Channel().GetMembers(channelId, page*perPage, perPage); result.Err != nil { +func (a *App) GetChannelMembersPage(channelId string, page, perPage int) (*model.ChannelMembers, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetMembers(channelId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelMembers), nil } } -func GetChannelMembersByIds(channelId string, userIds []string) (*model.ChannelMembers, *model.AppError) { - if result := <-Srv.Store.Channel().GetMembersByIds(channelId, userIds); result.Err != nil { +func (a *App) GetChannelMembersByIds(channelId string, userIds []string) (*model.ChannelMembers, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetMembersByIds(channelId, userIds); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelMembers), nil } } -func GetChannelMembersForUser(teamId string, userId string) (*model.ChannelMembers, *model.AppError) { - if result := <-Srv.Store.Channel().GetMembersForUser(teamId, userId); result.Err != nil { +func (a *App) GetChannelMembersForUser(teamId string, userId string) (*model.ChannelMembers, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetMembersForUser(teamId, userId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelMembers), nil } } -func GetChannelMemberCount(channelId string) (int64, *model.AppError) { - if result := <-Srv.Store.Channel().GetMemberCount(channelId, true); result.Err != nil { +func (a *App) GetChannelMemberCount(channelId string) (int64, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetMemberCount(channelId, true); result.Err != nil { return 0, result.Err } else { return result.Data.(int64), nil } } -func GetChannelCounts(teamId string, userId string) (*model.ChannelCounts, *model.AppError) { - if result := <-Srv.Store.Channel().GetChannelCounts(teamId, userId); result.Err != nil { +func (a *App) GetChannelCounts(teamId string, userId string) (*model.ChannelCounts, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetChannelCounts(teamId, userId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelCounts), nil } } -func GetChannelUnread(channelId, userId string) (*model.ChannelUnread, *model.AppError) { - result := <-Srv.Store.Channel().GetChannelUnread(channelId, userId) +func (a *App) GetChannelUnread(channelId, userId string) (*model.ChannelUnread, *model.AppError) { + result := <-a.Srv.Store.Channel().GetChannelUnread(channelId, userId) if result.Err != nil { return nil, result.Err } @@ -870,13 +870,13 @@ func GetChannelUnread(channelId, userId string) (*model.ChannelUnread, *model.Ap return channelUnread, nil } -func JoinChannel(channel *model.Channel, userId string) *model.AppError { +func (a *App) JoinChannel(channel *model.Channel, userId string) *model.AppError { if channel.DeleteAt > 0 { return model.NewAppError("JoinChannel", "api.channel.join_channel.already_deleted.app_error", nil, "", http.StatusBadRequest) } - userChan := Srv.Store.User().Get(userId) - memberChan := Srv.Store.Channel().GetMember(channel.Id, userId) + userChan := a.Srv.Store.User().Get(userId) + memberChan := a.Srv.Store.Channel().GetMember(channel.Id, userId) if uresult := <-userChan; uresult.Err != nil { return uresult.Err @@ -887,11 +887,11 @@ func JoinChannel(channel *model.Channel, userId string) *model.AppError { user := uresult.Data.(*model.User) if channel.Type == model.CHANNEL_OPEN { - if _, err := AddUserToChannel(user, channel); err != nil { + if _, err := a.AddUserToChannel(user, channel); err != nil { return err } - if err := postJoinChannelMessage(user, channel); err != nil { + if err := a.postJoinChannelMessage(user, channel); err != nil { return err } } else { @@ -902,7 +902,7 @@ func JoinChannel(channel *model.Channel, userId string) *model.AppError { return nil } -func postJoinChannelMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postJoinChannelMessage(user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(utils.T("api.channel.join_channel.post_and_forget"), user.Username), @@ -913,17 +913,17 @@ func postJoinChannelMessage(user *model.User, channel *model.Channel) *model.App }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { return model.NewAppError("postJoinChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func LeaveChannel(channelId string, userId string) *model.AppError { - sc := Srv.Store.Channel().Get(channelId, true) - uc := Srv.Store.User().Get(userId) - ccm := Srv.Store.Channel().GetMemberCount(channelId, false) +func (a *App) LeaveChannel(channelId string, userId string) *model.AppError { + sc := a.Srv.Store.Channel().Get(channelId, true) + uc := a.Srv.Store.User().Get(userId) + ccm := a.Srv.Store.Channel().GetMemberCount(channelId, false) if cresult := <-sc; cresult.Err != nil { return cresult.Err @@ -946,17 +946,17 @@ func LeaveChannel(channelId string, userId string) *model.AppError { return err } - if err := removeUserFromChannel(userId, userId, channel); err != nil { + if err := a.removeUserFromChannel(userId, userId, channel); err != nil { return err } - go postLeaveChannelMessage(user, channel) + go a.postLeaveChannelMessage(user, channel) } return nil } -func postLeaveChannelMessage(user *model.User, channel *model.Channel) *model.AppError { +func (a *App) postLeaveChannelMessage(user *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(utils.T("api.channel.leave.left"), user.Username), @@ -967,14 +967,14 @@ func postLeaveChannelMessage(user *model.User, channel *model.Channel) *model.Ap }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { return model.NewAppError("postLeaveChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *model.Channel) *model.AppError { +func (a *App) PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(utils.T("api.channel.add_member.added"), addedUser.Username, user.Username), @@ -986,14 +986,14 @@ func PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *m }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { return model.NewAppError("postAddToChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func PostRemoveFromChannelMessage(removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError { +func (a *App) PostRemoveFromChannelMessage(removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError { post := &model.Post{ ChannelId: channel.Id, Message: fmt.Sprintf(utils.T("api.channel.remove_member.removed"), removedUser.Username), @@ -1004,14 +1004,14 @@ func PostRemoveFromChannelMessage(removerUserId string, removedUser *model.User, }, } - if _, err := CreatePost(post, channel, false); err != nil { + if _, err := a.CreatePost(post, channel, false); err != nil { return model.NewAppError("postRemoveFromChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError) } return nil } -func removeUserFromChannel(userIdToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *App) removeUserFromChannel(userIdToRemove string, removerUserId string, channel *model.Channel) *model.AppError { if channel.DeleteAt > 0 { err := model.NewAppError("RemoveUserFromChannel", "api.channel.remove_user_from_channel.deleted.app_error", nil, "", http.StatusBadRequest) return err @@ -1021,12 +1021,12 @@ func removeUserFromChannel(userIdToRemove string, removerUserId string, channel return model.NewAppError("RemoveUserFromChannel", "api.channel.remove.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest) } - if cmresult := <-Srv.Store.Channel().RemoveMember(channel.Id, userIdToRemove); cmresult.Err != nil { + if cmresult := <-a.Srv.Store.Channel().RemoveMember(channel.Id, userIdToRemove); cmresult.Err != nil { return cmresult.Err } - InvalidateCacheForUser(userIdToRemove) - InvalidateCacheForChannelMembers(channel.Id) + a.InvalidateCacheForUser(userIdToRemove) + a.InvalidateCacheForChannelMembers(channel.Id) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_REMOVED, "", channel.Id, "", nil) message.Add("user_id", userIdToRemove) @@ -1042,37 +1042,37 @@ func removeUserFromChannel(userIdToRemove string, removerUserId string, channel return nil } -func RemoveUserFromChannel(userIdToRemove string, removerUserId string, channel *model.Channel) *model.AppError { +func (a *App) RemoveUserFromChannel(userIdToRemove string, removerUserId string, channel *model.Channel) *model.AppError { var err *model.AppError - if err = removeUserFromChannel(userIdToRemove, removerUserId, channel); err != nil { + if err = a.removeUserFromChannel(userIdToRemove, removerUserId, channel); err != nil { return err } var user *model.User - if user, err = GetUser(userIdToRemove); err != nil { + if user, err = a.GetUser(userIdToRemove); err != nil { return err } if userIdToRemove == removerUserId { - postLeaveChannelMessage(user, channel) + a.postLeaveChannelMessage(user, channel) } else { - go PostRemoveFromChannelMessage(removerUserId, user, channel) + go a.PostRemoveFromChannelMessage(removerUserId, user, channel) } return nil } -func GetNumberOfChannelsOnTeam(teamId string) (int, *model.AppError) { +func (a *App) GetNumberOfChannelsOnTeam(teamId string) (int, *model.AppError) { // Get total number of channels on current team - if result := <-Srv.Store.Channel().GetTeamChannels(teamId); result.Err != nil { + if result := <-a.Srv.Store.Channel().GetTeamChannels(teamId); result.Err != nil { return 0, result.Err } else { return len(*result.Data.(*model.ChannelList)), nil } } -func SetActiveChannel(userId string, channelId string) *model.AppError { - status, err := GetStatus(userId) +func (a *App) SetActiveChannel(userId string, channelId string) *model.AppError { + status, err := a.GetStatus(userId) oldStatus := model.STATUS_OFFLINE @@ -1096,8 +1096,8 @@ func SetActiveChannel(userId string, channelId string) *model.AppError { return nil } -func UpdateChannelLastViewedAt(channelIds []string, userId string) *model.AppError { - if result := <-Srv.Store.Channel().UpdateLastViewedAt(channelIds, userId); result.Err != nil { +func (a *App) UpdateChannelLastViewedAt(channelIds []string, userId string) *model.AppError { + if result := <-a.Srv.Store.Channel().UpdateLastViewedAt(channelIds, userId); result.Err != nil { return result.Err } @@ -1112,24 +1112,24 @@ func UpdateChannelLastViewedAt(channelIds []string, userId string) *model.AppErr return nil } -func SearchChannels(teamId string, term string) (*model.ChannelList, *model.AppError) { - if result := <-Srv.Store.Channel().SearchInTeam(teamId, term); result.Err != nil { +func (a *App) SearchChannels(teamId string, term string) (*model.ChannelList, *model.AppError) { + if result := <-a.Srv.Store.Channel().SearchInTeam(teamId, term); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelList), nil } } -func SearchChannelsUserNotIn(teamId string, userId string, term string) (*model.ChannelList, *model.AppError) { - if result := <-Srv.Store.Channel().SearchMore(userId, teamId, term); result.Err != nil { +func (a *App) SearchChannelsUserNotIn(teamId string, userId string, term string) (*model.ChannelList, *model.AppError) { + if result := <-a.Srv.Store.Channel().SearchMore(userId, teamId, term); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.ChannelList), nil } } -func ViewChannel(view *model.ChannelView, userId string, clearPushNotifications bool) *model.AppError { - if err := SetActiveChannel(userId, view.ChannelId); err != nil { +func (a *App) ViewChannel(view *model.ChannelView, userId string, clearPushNotifications bool) *model.AppError { + if err := a.SetActiveChannel(userId, view.ChannelId); err != nil { return err } @@ -1144,7 +1144,7 @@ func ViewChannel(view *model.ChannelView, userId string, clearPushNotifications channelIds = append(channelIds, view.PrevChannelId) if *utils.Cfg.EmailSettings.SendPushNotifications && clearPushNotifications && len(view.ChannelId) > 0 { - pchan = Srv.Store.User().GetUnreadCountForChannel(userId, view.ChannelId) + pchan = a.Srv.Store.User().GetUnreadCountForChannel(userId, view.ChannelId) } } @@ -1152,14 +1152,14 @@ func ViewChannel(view *model.ChannelView, userId string, clearPushNotifications return nil } - uchan := Srv.Store.Channel().UpdateLastViewedAt(channelIds, userId) + uchan := a.Srv.Store.Channel().UpdateLastViewedAt(channelIds, userId) if pchan != nil { if result := <-pchan; result.Err != nil { return result.Err } else { if result.Data.(int64) > 0 { - ClearPushNotification(userId, view.ChannelId) + a.ClearPushNotification(userId, view.ChannelId) } } } @@ -1177,24 +1177,24 @@ func ViewChannel(view *model.ChannelView, userId string, clearPushNotifications return nil } -func PermanentDeleteChannel(channel *model.Channel) *model.AppError { - if result := <-Srv.Store.Post().PermanentDeleteByChannel(channel.Id); result.Err != nil { +func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError { + if result := <-a.Srv.Store.Post().PermanentDeleteByChannel(channel.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Channel().PermanentDeleteMembersByChannel(channel.Id); result.Err != nil { + if result := <-a.Srv.Store.Channel().PermanentDeleteMembersByChannel(channel.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Webhook().PermanentDeleteIncomingByChannel(channel.Id); result.Err != nil { + if result := <-a.Srv.Store.Webhook().PermanentDeleteIncomingByChannel(channel.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Webhook().PermanentDeleteOutgoingByChannel(channel.Id); result.Err != nil { + if result := <-a.Srv.Store.Webhook().PermanentDeleteOutgoingByChannel(channel.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Channel().PermanentDelete(channel.Id); result.Err != nil { + if result := <-a.Srv.Store.Channel().PermanentDelete(channel.Id); result.Err != nil { return result.Err } @@ -1203,9 +1203,9 @@ func PermanentDeleteChannel(channel *model.Channel) *model.AppError { // This function is intended for use from the CLI. It is not robust against people joining the channel while the move // is in progress, and therefore should not be used from the API without first fixing this potential race condition. -func MoveChannel(team *model.Team, channel *model.Channel) *model.AppError { +func (a *App) MoveChannel(team *model.Team, channel *model.Channel) *model.AppError { // Check that all channel members are in the destination team. - if channelMembers, err := GetChannelMembersPage(channel.Id, 0, 10000000); err != nil { + if channelMembers, err := a.GetChannelMembersPage(channel.Id, 0, 10000000); err != nil { return err } else { channelMemberIds := []string{} @@ -1213,7 +1213,7 @@ func MoveChannel(team *model.Team, channel *model.Channel) *model.AppError { channelMemberIds = append(channelMemberIds, channelMember.UserId) } - if teamMembers, err2 := GetTeamMembersByIds(team.Id, channelMemberIds); err != nil { + if teamMembers, err2 := a.GetTeamMembersByIds(team.Id, channelMemberIds); err != nil { return err2 } else { if len(teamMembers) != len(*channelMembers) { @@ -1224,30 +1224,30 @@ func MoveChannel(team *model.Team, channel *model.Channel) *model.AppError { // Change the Team ID of the channel. channel.TeamId = team.Id - if result := <-Srv.Store.Channel().Update(channel); result.Err != nil { + if result := <-a.Srv.Store.Channel().Update(channel); result.Err != nil { return result.Err } return nil } -func GetPinnedPosts(channelId string) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Channel().GetPinnedPosts(channelId); result.Err != nil { +func (a *App) GetPinnedPosts(channelId string) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Channel().GetPinnedPosts(channelId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetDirectChannel(userId1, userId2 string) (*model.Channel, *model.AppError) { - result := <-Srv.Store.Channel().GetByName("", model.GetDMNameFromIds(userId1, userId2), true) +func (a *App) GetDirectChannel(userId1, userId2 string) (*model.Channel, *model.AppError) { + result := <-a.Srv.Store.Channel().GetByName("", model.GetDMNameFromIds(userId1, userId2), true) if result.Err != nil && result.Err.Id == store.MISSING_CHANNEL_ERROR { - result := <-Srv.Store.Channel().CreateDirectChannel(userId1, userId2) + result := <-a.Srv.Store.Channel().CreateDirectChannel(userId1, userId2) if result.Err != nil { return nil, model.NewAppError("GetOrCreateDMChannel", "web.incoming_webhook.channel.app_error", nil, "err="+result.Err.Message, http.StatusBadRequest) } - InvalidateCacheForUser(userId1) - InvalidateCacheForUser(userId2) + a.InvalidateCacheForUser(userId1) + a.InvalidateCacheForUser(userId2) return result.Data.(*model.Channel), nil } else if result.Err != nil { return nil, model.NewAppError("GetOrCreateDMChannel", "web.incoming_webhook.channel.app_error", nil, "err="+result.Err.Message, result.Err.StatusCode) diff --git a/app/channel_test.go b/app/channel_test.go index b43207b00..7eabafeb8 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -8,7 +8,8 @@ import ( ) func TestPermanentDeleteChannel(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() incomingWasEnabled := utils.Cfg.ServiceSettings.EnableIncomingWebhooks outgoingWasEnabled := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks @@ -19,25 +20,25 @@ func TestPermanentDeleteChannel(t *testing.T) { utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = outgoingWasEnabled }() - channel, err := CreateChannel(&model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channel, err := a.CreateChannel(&model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) if err != nil { t.Fatal(err.Error()) } defer func() { - PermanentDeleteChannel(channel) + a.PermanentDeleteChannel(channel) }() - incoming, err := CreateIncomingWebhookForChannel(th.BasicUser.Id, channel, &model.IncomingWebhook{ChannelId: channel.Id}) + incoming, err := a.CreateIncomingWebhookForChannel(th.BasicUser.Id, channel, &model.IncomingWebhook{ChannelId: channel.Id}) if err != nil { t.Fatal(err.Error()) } - defer DeleteIncomingWebhook(incoming.Id) + defer a.DeleteIncomingWebhook(incoming.Id) - if incoming, err = GetIncomingWebhook(incoming.Id); incoming == nil || err != nil { + if incoming, err = a.GetIncomingWebhook(incoming.Id); incoming == nil || err != nil { t.Fatal("unable to get new incoming webhook") } - outgoing, err := CreateOutgoingWebhook(&model.OutgoingWebhook{ + outgoing, err := a.CreateOutgoingWebhook(&model.OutgoingWebhook{ ChannelId: channel.Id, TeamId: channel.TeamId, CreatorId: th.BasicUser.Id, @@ -46,64 +47,65 @@ func TestPermanentDeleteChannel(t *testing.T) { if err != nil { t.Fatal(err.Error()) } - defer DeleteOutgoingWebhook(outgoing.Id) + defer a.DeleteOutgoingWebhook(outgoing.Id) - if outgoing, err = GetOutgoingWebhook(outgoing.Id); outgoing == nil || err != nil { + if outgoing, err = a.GetOutgoingWebhook(outgoing.Id); outgoing == nil || err != nil { t.Fatal("unable to get new outgoing webhook") } - if err := PermanentDeleteChannel(channel); err != nil { + if err := a.PermanentDeleteChannel(channel); err != nil { t.Fatal(err.Error()) } - if incoming, err = GetIncomingWebhook(incoming.Id); incoming != nil || err == nil { + if incoming, err = a.GetIncomingWebhook(incoming.Id); incoming != nil || err == nil { t.Error("incoming webhook wasn't deleted") } - if outgoing, err = GetOutgoingWebhook(outgoing.Id); outgoing != nil || err == nil { + if outgoing, err = a.GetOutgoingWebhook(outgoing.Id); outgoing != nil || err == nil { t.Error("outgoing webhook wasn't deleted") } } func TestMoveChannel(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() sourceTeam := th.CreateTeam() targetTeam := th.CreateTeam() channel1 := th.CreateChannel(sourceTeam) defer func() { - PermanentDeleteChannel(channel1) - PermanentDeleteTeam(sourceTeam) - PermanentDeleteTeam(targetTeam) + a.PermanentDeleteChannel(channel1) + a.PermanentDeleteTeam(sourceTeam) + a.PermanentDeleteTeam(targetTeam) }() - if _, err := AddUserToTeam(sourceTeam.Id, th.BasicUser.Id, ""); err != nil { + if _, err := a.AddUserToTeam(sourceTeam.Id, th.BasicUser.Id, ""); err != nil { t.Fatal(err) } - if _, err := AddUserToTeam(sourceTeam.Id, th.BasicUser2.Id, ""); err != nil { + if _, err := a.AddUserToTeam(sourceTeam.Id, th.BasicUser2.Id, ""); err != nil { t.Fatal(err) } - if _, err := AddUserToTeam(targetTeam.Id, th.BasicUser.Id, ""); err != nil { + if _, err := a.AddUserToTeam(targetTeam.Id, th.BasicUser.Id, ""); err != nil { t.Fatal(err) } - if _, err := AddUserToChannel(th.BasicUser, channel1); err != nil { + if _, err := a.AddUserToChannel(th.BasicUser, channel1); err != nil { t.Fatal(err) } - if _, err := AddUserToChannel(th.BasicUser2, channel1); err != nil { + if _, err := a.AddUserToChannel(th.BasicUser2, channel1); err != nil { t.Fatal(err) } - if err := MoveChannel(targetTeam, channel1); err == nil { + if err := a.MoveChannel(targetTeam, channel1); err == nil { t.Fatal("Should have failed due to mismatched members.") } - if _, err := AddUserToTeam(targetTeam.Id, th.BasicUser2.Id, ""); err != nil { + if _, err := a.AddUserToTeam(targetTeam.Id, th.BasicUser2.Id, ""); err != nil { t.Fatal(err) } - if err := MoveChannel(targetTeam, channel1); err != nil { + if err := a.MoveChannel(targetTeam, channel1); err != nil { t.Fatal(err) } } diff --git a/app/cluster_discovery.go b/app/cluster_discovery.go index 6584418f1..2d79aa7cc 100644 --- a/app/cluster_discovery.go +++ b/app/cluster_discovery.go @@ -31,19 +31,19 @@ func NewClusterDiscoveryService() *ClusterDiscoveryService { func (me *ClusterDiscoveryService) Start() { - <-Srv.Store.ClusterDiscovery().Cleanup() + <-Global().Srv.Store.ClusterDiscovery().Cleanup() - if cresult := <-Srv.Store.ClusterDiscovery().Exists(&me.ClusterDiscovery); cresult.Err != nil { + if cresult := <-Global().Srv.Store.ClusterDiscovery().Exists(&me.ClusterDiscovery); cresult.Err != nil { l4g.Error(fmt.Sprintf("ClusterDiscoveryService failed to check if row exists for %v with err=%v", me.ClusterDiscovery.ToJson(), cresult.Err)) } else { if cresult.Data.(bool) { - if u := <-Srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); u.Err != nil { + if u := <-Global().Srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); u.Err != nil { l4g.Error(fmt.Sprintf("ClusterDiscoveryService failed to start clean for %v with err=%v", me.ClusterDiscovery.ToJson(), u.Err)) } } } - if result := <-Srv.Store.ClusterDiscovery().Save(&me.ClusterDiscovery); result.Err != nil { + if result := <-Global().Srv.Store.ClusterDiscovery().Save(&me.ClusterDiscovery); result.Err != nil { l4g.Error(fmt.Sprintf("ClusterDiscoveryService failed to save for %v with err=%v", me.ClusterDiscovery.ToJson(), result.Err)) return } @@ -53,7 +53,7 @@ func (me *ClusterDiscoveryService) Start() { ticker := time.NewTicker(DISCOVERY_SERVICE_WRITE_PING) defer func() { ticker.Stop() - if u := <-Srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); u.Err != nil { + if u := <-Global().Srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); u.Err != nil { l4g.Error(fmt.Sprintf("ClusterDiscoveryService failed to cleanup for %v with err=%v", me.ClusterDiscovery.ToJson(), u.Err)) } l4g.Debug(fmt.Sprintf("ClusterDiscoveryService ping writer stopped for %v", me.ClusterDiscovery.ToJson())) @@ -62,7 +62,7 @@ func (me *ClusterDiscoveryService) Start() { for { select { case <-ticker.C: - if u := <-Srv.Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); u.Err != nil { + if u := <-Global().Srv.Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); u.Err != nil { l4g.Error(fmt.Sprintf("ClusterDiscoveryService failed to write ping for %v with err=%v", me.ClusterDiscovery.ToJson(), u.Err)) } case <-me.stop: diff --git a/app/cluster_discovery_test.go b/app/cluster_discovery_test.go index ca5b1bfa4..3a5c7a3b1 100644 --- a/app/cluster_discovery_test.go +++ b/app/cluster_discovery_test.go @@ -12,7 +12,8 @@ import ( ) func TestClusterDiscoveryService(t *testing.T) { - Setup() + a := Global() + a.Setup() ds := NewClusterDiscoveryService() ds.Type = model.CDS_TYPE_APP diff --git a/app/cluster_handlers.go b/app/cluster_handlers.go index 892bf00d3..f8bd8fe0e 100644 --- a/app/cluster_handlers.go +++ b/app/cluster_handlers.go @@ -10,17 +10,17 @@ import ( "github.com/mattermost/platform/model" ) -func RegisterAllClusterMessageHandlers() { +func (a *App) RegisterAllClusterMessageHandlers() { einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_PUBLISH, ClusterPublishHandler) einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_UPDATE_STATUS, ClusterUpdateStatusHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, ClusterInvalidateAllCachesHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_WEBHOOK, ClusterInvalidateCacheForWebhookHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_POSTS, ClusterInvalidateCacheForChannelPostsHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, ClusterInvalidateCacheForChannelMembersNotifyPropHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS, ClusterInvalidateCacheForChannelMembersHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, ClusterInvalidateCacheForChannelByNameHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL, ClusterInvalidateCacheForChannelHandler) - einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, ClusterInvalidateCacheForUserHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, a.ClusterInvalidateAllCachesHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_WEBHOOK, a.ClusterInvalidateCacheForWebhookHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_POSTS, a.ClusterInvalidateCacheForChannelPostsHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, a.ClusterInvalidateCacheForChannelMembersNotifyPropHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS, a.ClusterInvalidateCacheForChannelMembersHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, a.ClusterInvalidateCacheForChannelByNameHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL, a.ClusterInvalidateCacheForChannelHandler) + einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, a.ClusterInvalidateCacheForUserHandler) einterfaces.GetClusterInterface().RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, ClusterClearSessionCacheForUserHandler) } @@ -35,36 +35,36 @@ func ClusterUpdateStatusHandler(msg *model.ClusterMessage) { AddStatusCacheSkipClusterSend(status) } -func ClusterInvalidateAllCachesHandler(msg *model.ClusterMessage) { - InvalidateAllCachesSkipSend() +func (a *App) ClusterInvalidateAllCachesHandler(msg *model.ClusterMessage) { + a.InvalidateAllCachesSkipSend() } -func ClusterInvalidateCacheForWebhookHandler(msg *model.ClusterMessage) { - InvalidateCacheForWebhookSkipClusterSend(msg.Data) +func (a *App) ClusterInvalidateCacheForWebhookHandler(msg *model.ClusterMessage) { + a.InvalidateCacheForWebhookSkipClusterSend(msg.Data) } -func ClusterInvalidateCacheForChannelPostsHandler(msg *model.ClusterMessage) { - InvalidateCacheForChannelPostsSkipClusterSend(msg.Data) +func (a *App) ClusterInvalidateCacheForChannelPostsHandler(msg *model.ClusterMessage) { + a.InvalidateCacheForChannelPostsSkipClusterSend(msg.Data) } -func ClusterInvalidateCacheForChannelMembersNotifyPropHandler(msg *model.ClusterMessage) { - InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(msg.Data) +func (a *App) ClusterInvalidateCacheForChannelMembersNotifyPropHandler(msg *model.ClusterMessage) { + a.InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(msg.Data) } -func ClusterInvalidateCacheForChannelMembersHandler(msg *model.ClusterMessage) { - InvalidateCacheForChannelMembersSkipClusterSend(msg.Data) +func (a *App) ClusterInvalidateCacheForChannelMembersHandler(msg *model.ClusterMessage) { + a.InvalidateCacheForChannelMembersSkipClusterSend(msg.Data) } -func ClusterInvalidateCacheForChannelByNameHandler(msg *model.ClusterMessage) { - InvalidateCacheForChannelByNameSkipClusterSend(msg.Props["id"], msg.Props["name"]) +func (a *App) ClusterInvalidateCacheForChannelByNameHandler(msg *model.ClusterMessage) { + a.InvalidateCacheForChannelByNameSkipClusterSend(msg.Props["id"], msg.Props["name"]) } -func ClusterInvalidateCacheForChannelHandler(msg *model.ClusterMessage) { - InvalidateCacheForChannelSkipClusterSend(msg.Data) +func (a *App) ClusterInvalidateCacheForChannelHandler(msg *model.ClusterMessage) { + a.InvalidateCacheForChannelSkipClusterSend(msg.Data) } -func ClusterInvalidateCacheForUserHandler(msg *model.ClusterMessage) { - InvalidateCacheForUserSkipClusterSend(msg.Data) +func (a *App) ClusterInvalidateCacheForUserHandler(msg *model.ClusterMessage) { + a.InvalidateCacheForUserSkipClusterSend(msg.Data) } func ClusterClearSessionCacheForUserHandler(msg *model.ClusterMessage) { diff --git a/app/command.go b/app/command.go index a2e63a3d4..a69716f39 100644 --- a/app/command.go +++ b/app/command.go @@ -37,7 +37,7 @@ func GetCommandProvider(name string) CommandProvider { return nil } -func CreateCommandPost(post *model.Post, teamId string, response *model.CommandResponse) (*model.Post, *model.AppError) { +func (a *App) CreateCommandPost(post *model.Post, teamId string, response *model.CommandResponse) (*model.Post, *model.AppError) { post.Message = parseSlackLinksToMarkdown(response.Text) post.CreateAt = model.GetMillis() @@ -46,7 +46,7 @@ func CreateCommandPost(post *model.Post, teamId string, response *model.CommandR } if response.ResponseType == model.COMMAND_RESPONSE_TYPE_IN_CHANNEL { - return CreatePostMissingChannel(post, true) + return a.CreatePostMissingChannel(post, true) } else if response.ResponseType == "" || response.ResponseType == model.COMMAND_RESPONSE_TYPE_EPHEMERAL { if response.Text == "" { return post, nil @@ -60,7 +60,7 @@ func CreateCommandPost(post *model.Post, teamId string, response *model.CommandR } // previous ListCommands now ListAutocompleteCommands -func ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) { +func (a *App) ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) { commands := make([]*model.Command, 0, 32) seen := make(map[string]bool) for _, value := range commandProviders { @@ -73,7 +73,7 @@ func ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([]*model.C } if *utils.Cfg.ServiceSettings.EnableCommands { - if result := <-Srv.Store.Command().GetByTeam(teamId); result.Err != nil { + if result := <-a.Srv.Store.Command().GetByTeam(teamId); result.Err != nil { return nil, result.Err } else { teamCmds := result.Data.([]*model.Command) @@ -90,19 +90,19 @@ func ListAutocompleteCommands(teamId string, T goi18n.TranslateFunc) ([]*model.C return commands, nil } -func ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) { +func (a *App) ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableCommands { return nil, model.NewAppError("ListTeamCommands", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Command().GetByTeam(teamId); result.Err != nil { + if result := <-a.Srv.Store.Command().GetByTeam(teamId); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Command), nil } } -func ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) { +func (a *App) ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, *model.AppError) { commands := make([]*model.Command, 0, 32) seen := make(map[string]bool) for _, value := range commandProviders { @@ -115,7 +115,7 @@ func ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, * } if *utils.Cfg.ServiceSettings.EnableCommands { - if result := <-Srv.Store.Command().GetByTeam(teamId); result.Err != nil { + if result := <-a.Srv.Store.Command().GetByTeam(teamId); result.Err != nil { return nil, result.Err } else { teamCmds := result.Data.([]*model.Command) @@ -132,7 +132,7 @@ func ListAllCommands(teamId string, T goi18n.TranslateFunc) ([]*model.Command, * return commands, nil } -func ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { +func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) { parts := strings.Split(args.Command, " ") trigger := parts[0][1:] trigger = strings.ToLower(trigger) @@ -141,17 +141,17 @@ func ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.App if provider != nil { response := provider.DoCommand(args, message) - return HandleCommandResponse(provider.GetCommand(args.T), args, response, true) + return a.HandleCommandResponse(provider.GetCommand(args.T), args, response, true) } else { if !*utils.Cfg.ServiceSettings.EnableCommands { return nil, model.NewAppError("ExecuteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - chanChan := Srv.Store.Channel().Get(args.ChannelId, true) - teamChan := Srv.Store.Team().Get(args.TeamId) - userChan := Srv.Store.User().Get(args.UserId) + chanChan := a.Srv.Store.Channel().Get(args.ChannelId, true) + teamChan := a.Srv.Store.Team().Get(args.TeamId) + userChan := a.Srv.Store.User().Get(args.UserId) - if result := <-Srv.Store.Command().GetByTeam(args.TeamId); result.Err != nil { + if result := <-a.Srv.Store.Command().GetByTeam(args.TeamId); result.Err != nil { return nil, result.Err } else { @@ -196,7 +196,7 @@ func ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.App p.Set("command", "/"+trigger) p.Set("text", message) - if hook, err := CreateCommandWebhook(cmd.Id, args); err != nil { + if hook, err := a.CreateCommandWebhook(cmd.Id, args); err != nil { return nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": trigger}, err.Error(), http.StatusInternalServerError) } else { p.Set("response_url", args.SiteURL+"/hooks/commands/"+hook.Id) @@ -221,7 +221,7 @@ func ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.App if response == nil { return nil, model.NewAppError("command", "api.command.execute_command.failed_empty.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusInternalServerError) } else { - return HandleCommandResponse(cmd, args, response, false) + return a.HandleCommandResponse(cmd, args, response, false) } } else { defer resp.Body.Close() @@ -237,7 +237,7 @@ func ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.App return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusNotFound) } -func HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) { +func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) { post := &model.Post{} post.ChannelId = args.ChannelId post.RootId = args.RootId @@ -266,21 +266,21 @@ func HandleCommandResponse(command *model.Command, args *model.CommandArgs, resp } } - if _, err := CreateCommandPost(post, args.TeamId, response); err != nil { + if _, err := a.CreateCommandPost(post, args.TeamId, response); err != nil { l4g.Error(err.Error()) } return response, nil } -func CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) { +func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableCommands { return nil, model.NewAppError("CreateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } cmd.Trigger = strings.ToLower(cmd.Trigger) - if result := <-Srv.Store.Command().GetByTeam(cmd.TeamId); result.Err != nil { + if result := <-a.Srv.Store.Command().GetByTeam(cmd.TeamId); result.Err != nil { return nil, result.Err } else { teamCmds := result.Data.([]*model.Command) @@ -297,19 +297,19 @@ func CreateCommand(cmd *model.Command) (*model.Command, *model.AppError) { } } - if result := <-Srv.Store.Command().Save(cmd); result.Err != nil { + if result := <-a.Srv.Store.Command().Save(cmd); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Command), nil } } -func GetCommand(commandId string) (*model.Command, *model.AppError) { +func (a *App) GetCommand(commandId string) (*model.Command, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableCommands { return nil, model.NewAppError("GetCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Command().Get(commandId); result.Err != nil { + if result := <-a.Srv.Store.Command().Get(commandId); result.Err != nil { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else { @@ -317,7 +317,7 @@ func GetCommand(commandId string) (*model.Command, *model.AppError) { } } -func UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) { +func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableCommands { return nil, model.NewAppError("UpdateCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -331,33 +331,33 @@ func UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.Ap updatedCmd.CreatorId = oldCmd.CreatorId updatedCmd.TeamId = oldCmd.TeamId - if result := <-Srv.Store.Command().Update(updatedCmd); result.Err != nil { + if result := <-a.Srv.Store.Command().Update(updatedCmd); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Command), nil } } -func RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppError) { +func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableCommands { return nil, model.NewAppError("RegenCommandToken", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } cmd.Token = model.NewId() - if result := <-Srv.Store.Command().Update(cmd); result.Err != nil { + if result := <-a.Srv.Store.Command().Update(cmd); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Command), nil } } -func DeleteCommand(commandId string) *model.AppError { +func (a *App) DeleteCommand(commandId string) *model.AppError { if !*utils.Cfg.ServiceSettings.EnableCommands { return model.NewAppError("DeleteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - if err := (<-Srv.Store.Command().Delete(commandId, model.GetMillis())).Err; err != nil { + if err := (<-a.Srv.Store.Command().Delete(commandId, model.GetMillis())).Err; err != nil { return err } diff --git a/app/command_away.go b/app/command_away.go index 77f5cc7f3..4bb53a425 100644 --- a/app/command_away.go +++ b/app/command_away.go @@ -33,7 +33,7 @@ func (me *AwayProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *AwayProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - SetStatusAwayIfNeeded(args.UserId, true) + Global().SetStatusAwayIfNeeded(args.UserId, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")} } diff --git a/app/command_channel_header.go b/app/command_channel_header.go index e552f9282..02a31cd65 100644 --- a/app/command_channel_header.go +++ b/app/command_channel_header.go @@ -35,16 +35,16 @@ func (me *HeaderProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *HeaderProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := GetChannel(args.ChannelId) + channel, err := Global().GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_header.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_OPEN && !SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_PRIVATE && !SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -57,7 +57,7 @@ func (me *HeaderProvider) DoCommand(args *model.CommandArgs, message string) *mo } *patch.Header = message - _, err = PatchChannel(channel, patch, args.UserId) + _, err = Global().PatchChannel(channel, patch, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_header.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_channel_purpose.go b/app/command_channel_purpose.go index db3ab541a..563b96be7 100644 --- a/app/command_channel_purpose.go +++ b/app/command_channel_purpose.go @@ -34,16 +34,16 @@ func (me *PurposeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *PurposeProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := GetChannel(args.ChannelId) + channel, err := Global().GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_OPEN && !SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_PRIVATE && !SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -60,7 +60,7 @@ func (me *PurposeProvider) DoCommand(args *model.CommandArgs, message string) *m } *patch.Purpose = message - _, err = PatchChannel(channel, patch, args.UserId) + _, err = Global().PatchChannel(channel, patch, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_channel_rename.go b/app/command_channel_rename.go index 596f8b38c..731b5d54a 100644 --- a/app/command_channel_rename.go +++ b/app/command_channel_rename.go @@ -34,16 +34,16 @@ func (me *RenameProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *RenameProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := GetChannel(args.ChannelId) + channel, err := Global().GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_rename.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_OPEN && !SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_PRIVATE && !SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -64,7 +64,7 @@ func (me *RenameProvider) DoCommand(args *model.CommandArgs, message string) *mo } *patch.DisplayName = message - _, err = PatchChannel(channel, patch, args.UserId) + _, err = Global().PatchChannel(channel, patch, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_rename.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_channel_rename_test.go b/app/command_channel_rename_test.go index 95a4f1500..94725ef3c 100644 --- a/app/command_channel_rename_test.go +++ b/app/command_channel_rename_test.go @@ -8,7 +8,8 @@ import ( ) func TestRenameProviderDoCommand(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() rp := RenameProvider{} args := &model.CommandArgs{ diff --git a/app/command_echo.go b/app/command_echo.go index 3ab5a7873..f89aab378 100644 --- a/app/command_echo.go +++ b/app/command_echo.go @@ -88,7 +88,7 @@ func (me *EchoProvider) DoCommand(args *model.CommandArgs, message string) *mode time.Sleep(time.Duration(delay) * time.Second) - if _, err := CreatePostMissingChannel(post, true); err != nil { + if _, err := Global().CreatePostMissingChannel(post, true); err != nil { l4g.Error(args.T("api.command_echo.create.app_error"), err) } }() diff --git a/app/command_expand_collapse.go b/app/command_expand_collapse.go index 314a54b2a..7ea90cdb5 100644 --- a/app/command_expand_collapse.go +++ b/app/command_expand_collapse.go @@ -53,14 +53,14 @@ func (me *CollapseProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *ExpandProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - return setCollapsePreference(args, false) + return Global().setCollapsePreference(args, false) } func (me *CollapseProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - return setCollapsePreference(args, true) + return Global().setCollapsePreference(args, true) } -func setCollapsePreference(args *model.CommandArgs, isCollapse bool) *model.CommandResponse { +func (a *App) setCollapsePreference(args *model.CommandArgs, isCollapse bool) *model.CommandResponse { pref := model.Preference{ UserId: args.UserId, Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, @@ -68,7 +68,7 @@ func setCollapsePreference(args *model.CommandArgs, isCollapse bool) *model.Comm Value: strconv.FormatBool(isCollapse), } - if result := <-Srv.Store.Preference().Save(&model.Preferences{pref}); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&model.Preferences{pref}); result.Err != nil { return &model.CommandResponse{Text: args.T("api.command_expand_collapse.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_invite_people.go b/app/command_invite_people.go index 6f2bac445..01e3db4bc 100644 --- a/app/command_invite_people.go +++ b/app/command_invite_people.go @@ -63,7 +63,7 @@ func (me *InvitePeopleProvider) DoCommand(args *model.CommandArgs, message strin return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.no_email")} } - if err := InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil { + if err := Global().InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil { l4g.Error(err.Error()) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.fail")} } diff --git a/app/command_join.go b/app/command_join.go index 07ae391ae..7b79f77e9 100644 --- a/app/command_join.go +++ b/app/command_join.go @@ -34,14 +34,14 @@ func (me *JoinProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *JoinProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - if result := <-Srv.Store.Channel().GetByName(args.TeamId, message, true); result.Err != nil { + if result := <-Global().Srv.Store.Channel().GetByName(args.TeamId, message, true); result.Err != nil { return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { channel := result.Data.(*model.Channel) if channel.Name == message { allowed := false - if (channel.Type == model.CHANNEL_PRIVATE && SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_READ_CHANNEL)) || channel.Type == model.CHANNEL_OPEN { + if (channel.Type == model.CHANNEL_PRIVATE && Global().SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_READ_CHANNEL)) || channel.Type == model.CHANNEL_OPEN { allowed = true } @@ -49,11 +49,11 @@ func (me *JoinProvider) DoCommand(args *model.CommandArgs, message string) *mode return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if err := JoinChannel(channel, args.UserId); err != nil { + if err := Global().JoinChannel(channel, args.UserId); err != nil { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - team, err := GetTeam(channel.TeamId) + team, err := Global().GetTeam(channel.TeamId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_leave.go b/app/command_leave.go index 963172e86..f8f3fa013 100644 --- a/app/command_leave.go +++ b/app/command_leave.go @@ -35,18 +35,18 @@ func (me *LeaveProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { func (me *LeaveProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { var channel *model.Channel var noChannelErr *model.AppError - if channel, noChannelErr = GetChannel(args.ChannelId); noChannelErr != nil { + if channel, noChannelErr = Global().GetChannel(args.ChannelId); noChannelErr != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } if channel.Name == model.DEFAULT_CHANNEL { return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - err := LeaveChannel(args.ChannelId, args.UserId) + err := Global().LeaveChannel(args.ChannelId, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - team, err := GetTeam(args.TeamId) + team, err := Global().GetTeam(args.TeamId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_loadtest.go b/app/command_loadtest.go index 8a37014fa..a07a16cf7 100644 --- a/app/command_loadtest.go +++ b/app/command_loadtest.go @@ -161,7 +161,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string client := model.NewClient(args.SiteURL) if doTeams { - if err := CreateBasicUser(client); err != nil { + if err := Global().CreateBasicUser(client); err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } client.Login(BTEST_USER_EMAIL, BTEST_USER_PASSWORD) @@ -184,7 +184,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string } else { var team *model.Team - if tr := <-Srv.Store.Team().Get(args.TeamId); tr.Err != nil { + if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { team = tr.Data.(*model.Team) @@ -219,7 +219,7 @@ func (me *LoadTestProvider) UsersCommand(args *model.CommandArgs, message string } var team *model.Team - if tr := <-Srv.Store.Team().Get(args.TeamId); tr.Err != nil { + if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { team = tr.Data.(*model.Team) @@ -249,7 +249,7 @@ func (me *LoadTestProvider) ChannelsCommand(args *model.CommandArgs, message str } var team *model.Team - if tr := <-Srv.Store.Team().Get(args.TeamId); tr.Err != nil { + if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { team = tr.Data.(*model.Team) @@ -288,7 +288,7 @@ func (me *LoadTestProvider) PostsCommand(args *model.CommandArgs, message string } var usernames []string - if result := <-Srv.Store.User().GetProfiles(args.TeamId, 0, 1000); result.Err == nil { + if result := <-Global().Srv.Store.User().GetProfiles(args.TeamId, 0, 1000); result.Err == nil { profileUsers := result.Data.([]*model.User) usernames = make([]string, len(profileUsers)) i := 0 @@ -357,7 +357,7 @@ func (me *LoadTestProvider) UrlCommand(args *model.CommandArgs, message string) post.ChannelId = args.ChannelId post.UserId = args.UserId - if _, err := CreatePostMissingChannel(post, false); err != nil { + if _, err := Global().CreatePostMissingChannel(post, false); err != nil { return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } } @@ -396,7 +396,7 @@ func (me *LoadTestProvider) JsonCommand(args *model.CommandArgs, message string) post.Message = message } - if _, err := CreatePostMissingChannel(post, false); err != nil { + if _, err := Global().CreatePostMissingChannel(post, false); err != nil { return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} diff --git a/app/command_logout.go b/app/command_logout.go index cc59d2686..af28b9a16 100644 --- a/app/command_logout.go +++ b/app/command_logout.go @@ -39,7 +39,7 @@ func (me *LogoutProvider) DoCommand(args *model.CommandArgs, message string) *mo // We can't actually remove the user's cookie from here so we just dump their session and let the browser figure it out if args.Session.Id != "" { - if err := RevokeSessionById(args.Session.Id); err != nil { + if err := Global().RevokeSessionById(args.Session.Id); err != nil { return FAIL } return SUCCESS diff --git a/app/command_msg.go b/app/command_msg.go index 67bb425d2..1e5228a78 100644 --- a/app/command_msg.go +++ b/app/command_msg.go @@ -51,7 +51,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model targetUsername = strings.TrimPrefix(targetUsername, "@") var userProfile *model.User - if result := <-Srv.Store.User().GetByUsername(targetUsername); result.Err != nil { + if result := <-Global().Srv.Store.User().GetByUsername(targetUsername); result.Err != nil { l4g.Error(result.Err.Error()) return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { @@ -66,9 +66,9 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id) targetChannelId := "" - if channel := <-Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channel.Err != nil { + if channel := <-Global().Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channel.Err != nil { if channel.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { - if directChannel, err := CreateDirectChannel(args.UserId, userProfile.Id); err != nil { + if directChannel, err := Global().CreateDirectChannel(args.UserId, userProfile.Id); err != nil { l4g.Error(err.Error()) return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { @@ -89,7 +89,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model post.Message = parsedMessage post.ChannelId = targetChannelId post.UserId = args.UserId - if _, err := CreatePostMissingChannel(post, true); err != nil { + if _, err := Global().CreatePostMissingChannel(post, true); err != nil { return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } } @@ -101,7 +101,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model teamId = args.Session.TeamMembers[0].TeamId } - team, err := GetTeam(teamId) + team, err := Global().GetTeam(teamId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_offline.go b/app/command_offline.go index a8c4352ad..014676974 100644 --- a/app/command_offline.go +++ b/app/command_offline.go @@ -33,7 +33,7 @@ func (me *OfflineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *OfflineProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - SetStatusOffline(args.UserId, true) + Global().SetStatusOffline(args.UserId, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_offline.success")} } diff --git a/app/command_online.go b/app/command_online.go index c98f1649b..16501e09c 100644 --- a/app/command_online.go +++ b/app/command_online.go @@ -33,7 +33,7 @@ func (me *OnlineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } func (me *OnlineProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - SetStatusOnline(args.UserId, args.Session.Id, true) + Global().SetStatusOnline(args.UserId, args.Session.Id, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_online.success")} } diff --git a/app/compliance.go b/app/compliance.go index 9c6d8985b..b6317fa1e 100644 --- a/app/compliance.go +++ b/app/compliance.go @@ -6,32 +6,33 @@ package app import ( "io/ioutil" + "net/http" + "github.com/mattermost/platform/einterfaces" "github.com/mattermost/platform/model" "github.com/mattermost/platform/utils" - "net/http" ) -func GetComplianceReports(page, perPage int) (model.Compliances, *model.AppError) { +func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model.AppError) { if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance { return nil, model.NewAppError("GetComplianceReports", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Compliance().GetAll(page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.Compliance().GetAll(page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.(model.Compliances), nil } } -func SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) { +func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) { if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance || einterfaces.GetComplianceInterface() == nil { return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } job.Type = model.COMPLIANCE_TYPE_ADHOC - if result := <-Srv.Store.Compliance().Save(job); result.Err != nil { + if result := <-a.Srv.Store.Compliance().Save(job); result.Err != nil { return nil, result.Err } else { job = result.Data.(*model.Compliance) @@ -41,12 +42,12 @@ func SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppE return job, nil } -func GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) { +func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) { if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed() || !*utils.License().Features.Compliance || einterfaces.GetComplianceInterface() == nil { return nil, model.NewAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Compliance().Get(reportId); result.Err != nil { + if result := <-a.Srv.Store.Compliance().Get(reportId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Compliance), nil diff --git a/app/diagnostics.go b/app/diagnostics.go index 98043d0a0..55c765ac0 100644 --- a/app/diagnostics.go +++ b/app/diagnostics.go @@ -50,13 +50,13 @@ const ( var client *analytics.Client -func SendDailyDiagnostics() { +func (a *App) SendDailyDiagnostics() { if *utils.Cfg.LogSettings.EnableDiagnostics && utils.IsLeader() { initDiagnostics("") - trackActivity() + a.trackActivity() trackConfig() trackLicense() - trackServer() + a.trackServer() } } @@ -108,7 +108,7 @@ func pluginSetting(plugin, key string, defaultValue interface{}) interface{} { return defaultValue } -func trackActivity() { +func (a *App) trackActivity() { var userCount int64 var activeUserCount int64 var inactiveUserCount int64 @@ -120,43 +120,43 @@ func trackActivity() { var deletedPrivateChannelCount int64 var postsCount int64 - if ucr := <-Srv.Store.User().GetTotalUsersCount(); ucr.Err == nil { + if ucr := <-a.Srv.Store.User().GetTotalUsersCount(); ucr.Err == nil { userCount = ucr.Data.(int64) } - if ucr := <-Srv.Store.Status().GetTotalActiveUsersCount(); ucr.Err == nil { + if ucr := <-a.Srv.Store.Status().GetTotalActiveUsersCount(); ucr.Err == nil { activeUserCount = ucr.Data.(int64) } - if iucr := <-Srv.Store.Status().GetTotalActiveUsersCount(); iucr.Err == nil { + if iucr := <-a.Srv.Store.Status().GetTotalActiveUsersCount(); iucr.Err == nil { inactiveUserCount = iucr.Data.(int64) } - if tcr := <-Srv.Store.Team().AnalyticsTeamCount(); tcr.Err == nil { + if tcr := <-a.Srv.Store.Team().AnalyticsTeamCount(); tcr.Err == nil { teamCount = tcr.Data.(int64) } - if ucc := <-Srv.Store.Channel().AnalyticsTypeCount("", "O"); ucc.Err == nil { + if ucc := <-a.Srv.Store.Channel().AnalyticsTypeCount("", "O"); ucc.Err == nil { publicChannelCount = ucc.Data.(int64) } - if pcc := <-Srv.Store.Channel().AnalyticsTypeCount("", "P"); pcc.Err == nil { + if pcc := <-a.Srv.Store.Channel().AnalyticsTypeCount("", "P"); pcc.Err == nil { privateChannelCount = pcc.Data.(int64) } - if dcc := <-Srv.Store.Channel().AnalyticsTypeCount("", "D"); dcc.Err == nil { + if dcc := <-a.Srv.Store.Channel().AnalyticsTypeCount("", "D"); dcc.Err == nil { directChannelCount = dcc.Data.(int64) } - if duccr := <-Srv.Store.Channel().AnalyticsDeletedTypeCount("", "O"); duccr.Err == nil { + if duccr := <-a.Srv.Store.Channel().AnalyticsDeletedTypeCount("", "O"); duccr.Err == nil { deletedPublicChannelCount = duccr.Data.(int64) } - if dpccr := <-Srv.Store.Channel().AnalyticsDeletedTypeCount("", "P"); dpccr.Err == nil { + if dpccr := <-a.Srv.Store.Channel().AnalyticsDeletedTypeCount("", "P"); dpccr.Err == nil { deletedPrivateChannelCount = dpccr.Data.(int64) } - if pcr := <-Srv.Store.Post().AnalyticsPostCount("", false, false); pcr.Err == nil { + if pcr := <-a.Srv.Store.Post().AnalyticsPostCount("", false, false); pcr.Err == nil { postsCount = pcr.Data.(int64) } @@ -467,7 +467,7 @@ func trackLicense() { } } -func trackServer() { +func (a *App) trackServer() { data := map[string]interface{}{ "edition": model.BuildEnterpriseReady, "version": model.CurrentVersion, @@ -475,7 +475,7 @@ func trackServer() { "operating_system": runtime.GOOS, } - if scr := <-Srv.Store.User().AnalyticsGetSystemAdminCount(); scr.Err == nil { + if scr := <-a.Srv.Store.User().AnalyticsGetSystemAdminCount(); scr.Err == nil { data["system_admins"] = scr.Data.(int64) } diff --git a/app/diagnostics_test.go b/app/diagnostics_test.go index 57e9eaf79..3fc1a0396 100644 --- a/app/diagnostics_test.go +++ b/app/diagnostics_test.go @@ -47,7 +47,8 @@ func TestPluginSetting(t *testing.T) { } func TestDiagnostics(t *testing.T) { - Setup().InitBasic() + a := Global() + a.Setup().InitBasic() if testing.Short() { t.SkipNow() @@ -91,7 +92,7 @@ func TestDiagnostics(t *testing.T) { }) t.Run("SendDailyDiagnostics", func(t *testing.T) { - SendDailyDiagnostics() + a.SendDailyDiagnostics() info := "" // Collect the info sent. @@ -151,7 +152,7 @@ func TestDiagnostics(t *testing.T) { *utils.Cfg.LogSettings.EnableDiagnostics = oldSetting }() - SendDailyDiagnostics() + a.SendDailyDiagnostics() select { case <-data: diff --git a/app/email.go b/app/email.go index bf9043de5..9397d298c 100644 --- a/app/email.go +++ b/app/email.go @@ -7,10 +7,11 @@ import ( "fmt" "net/url" + "net/http" + l4g "github.com/alecthomas/log4go" "github.com/mattermost/platform/model" "github.com/mattermost/platform/utils" - "net/http" ) func SendChangeUsernameEmail(oldUsername, newUsername, email, locale, siteURL string) *model.AppError { @@ -120,7 +121,7 @@ func SendSignInChangeEmail(email, method, locale, siteURL string) *model.AppErro return nil } -func SendWelcomeEmail(userId string, email string, verified bool, locale, siteURL string) *model.AppError { +func (a *App) SendWelcomeEmail(userId string, email string, verified bool, locale, siteURL string) *model.AppError { T := utils.GetUserTranslations(locale) rawUrl, _ := url.Parse(siteURL) @@ -144,7 +145,7 @@ func SendWelcomeEmail(userId string, email string, verified bool, locale, siteUR } if !verified { - token, err := CreateVerifyEmailToken(userId) + token, err := a.CreateVerifyEmailToken(userId) if err != nil { return err } diff --git a/app/email_batching.go b/app/email_batching.go index 4b557c678..1b60d5296 100644 --- a/app/email_batching.go +++ b/app/email_batching.go @@ -12,9 +12,10 @@ import ( "github.com/mattermost/platform/model" "github.com/mattermost/platform/utils" + "net/http" + l4g "github.com/alecthomas/log4go" "github.com/nicksnyder/go-i18n/i18n" - "net/http" ) const ( @@ -96,7 +97,7 @@ func (job *EmailBatchingJob) CheckPendingEmails() { // it's a bit weird to pass the send email function through here, but it makes it so that we can test // without actually sending emails - job.checkPendingNotifications(time.Now(), sendBatchedEmailNotification) + job.checkPendingNotifications(time.Now(), Global().sendBatchedEmailNotification) l4g.Debug(utils.T("api.email_batching.check_pending_emails.finished_running"), len(job.pendingNotifications)) } @@ -130,7 +131,7 @@ func (job *EmailBatchingJob) checkPendingNotifications(now time.Time, handler fu if inspectedTeamNames[notification.teamName] != "" { continue } - tchan := Srv.Store.Team().GetByName(notifications[0].teamName) + tchan := Global().Srv.Store.Team().GetByName(notifications[0].teamName) if result := <-tchan; result.Err != nil { l4g.Error("Unable to find Team id for notification", result.Err) continue @@ -140,7 +141,7 @@ func (job *EmailBatchingJob) checkPendingNotifications(now time.Time, handler fu // if the user has viewed any channels in this team since the notification was queued, delete // all queued notifications - mchan := Srv.Store.Channel().GetMembersForUser(inspectedTeamNames[notification.teamName], userId) + mchan := Global().Srv.Store.Channel().GetMembersForUser(inspectedTeamNames[notification.teamName], userId) if result := <-mchan; result.Err != nil { l4g.Error("Unable to find ChannelMembers for user", result.Err) continue @@ -157,7 +158,7 @@ func (job *EmailBatchingJob) checkPendingNotifications(now time.Time, handler fu // get how long we need to wait to send notifications to the user var interval int64 - pchan := Srv.Store.Preference().Get(userId, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL) + pchan := Global().Srv.Store.Preference().Get(userId, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL) if result := <-pchan; result.Err != nil { // use the default batching interval if an error ocurrs while fetching user preferences interval, _ = strconv.ParseInt(model.PREFERENCE_EMAIL_INTERVAL_BATCHING_SECONDS, 10, 64) @@ -180,8 +181,8 @@ func (job *EmailBatchingJob) checkPendingNotifications(now time.Time, handler fu } } -func sendBatchedEmailNotification(userId string, notifications []*batchedNotification) { - uchan := Srv.Store.User().Get(userId) +func (a *App) sendBatchedEmailNotification(userId string, notifications []*batchedNotification) { + uchan := a.Srv.Store.User().Get(userId) var user *model.User if result := <-uchan; result.Err != nil { @@ -197,7 +198,7 @@ func sendBatchedEmailNotification(userId string, notifications []*batchedNotific var contents string for _, notification := range notifications { var sender *model.User - schan := Srv.Store.User().Get(notification.post.UserId) + schan := a.Srv.Store.User().Get(notification.post.UserId) if result := <-schan; result.Err != nil { l4g.Warn(utils.T("api.email_batching.render_batched_post.sender.app_error")) continue @@ -206,7 +207,7 @@ func sendBatchedEmailNotification(userId string, notifications []*batchedNotific } var channel *model.Channel - cchan := Srv.Store.Channel().Get(notification.post.ChannelId, true) + cchan := a.Srv.Store.Channel().Get(notification.post.ChannelId, true) if result := <-cchan; result.Err != nil { l4g.Warn(utils.T("api.email_batching.render_batched_post.channel.app_error")) continue @@ -219,7 +220,7 @@ func sendBatchedEmailNotification(userId string, notifications []*batchedNotific emailNotificationContentsType = *utils.Cfg.EmailSettings.EmailNotificationContentsType } - contents += renderBatchedPost(notification, channel, sender, *utils.Cfg.ServiceSettings.SiteURL, displayNameFormat, translateFunc, user.Locale, emailNotificationContentsType) + contents += a.renderBatchedPost(notification, channel, sender, *utils.Cfg.ServiceSettings.SiteURL, displayNameFormat, translateFunc, user.Locale, emailNotificationContentsType) } tm := time.Unix(notifications[0].post.CreateAt/1000, 0) @@ -241,7 +242,7 @@ func sendBatchedEmailNotification(userId string, notifications []*batchedNotific } } -func renderBatchedPost(notification *batchedNotification, channel *model.Channel, sender *model.User, siteURL string, displayNameFormat string, translateFunc i18n.TranslateFunc, userLocale string, emailNotificationContentsType string) string { +func (a *App) renderBatchedPost(notification *batchedNotification, channel *model.Channel, sender *model.User, siteURL string, displayNameFormat string, translateFunc i18n.TranslateFunc, userLocale string, emailNotificationContentsType string) string { // don't include message contents if email notification contents type is set to generic var template *utils.HTMLTemplate if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { @@ -251,7 +252,7 @@ func renderBatchedPost(notification *batchedNotification, channel *model.Channel } template.Props["Button"] = translateFunc("api.email_batching.render_batched_post.go_to_post") - template.Props["PostMessage"] = GetMessageForNotification(notification.post, translateFunc) + template.Props["PostMessage"] = a.GetMessageForNotification(notification.post, translateFunc) template.Props["PostLink"] = siteURL + "/" + notification.teamName + "/pl/" + notification.post.Id template.Props["SenderName"] = sender.GetDisplayName(displayNameFormat) diff --git a/app/email_batching_test.go b/app/email_batching_test.go index 829bc11af..e30e0ac96 100644 --- a/app/email_batching_test.go +++ b/app/email_batching_test.go @@ -13,7 +13,8 @@ import ( ) func TestHandleNewNotifications(t *testing.T) { - Setup() + a := Global() + a.Setup() id1 := model.NewId() id2 := model.NewId() @@ -93,25 +94,26 @@ func TestHandleNewNotifications(t *testing.T) { } func TestCheckPendingNotifications(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() job := MakeEmailBatchingJob(128) job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{ { post: &model.Post{ - UserId: th.BasicUser.Id, + UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, - CreateAt: 10000000, + CreateAt: 10000000, }, teamName: th.BasicTeam.Name, }, } - channelMember := store.Must(Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember := store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 9999999 - store.Must(Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) - store.Must(Srv.Store.Preference().Save(&model.Preferences{{ + store.Must(a.Srv.Store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, @@ -126,9 +128,9 @@ func TestCheckPendingNotifications(t *testing.T) { } // test that notifications are cleared if the user has acted - channelMember = store.Must(Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember = store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 10001000 - store.Must(Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) job.checkPendingNotifications(time.Unix(10002, 0), func(string, []*batchedNotification) {}) @@ -140,19 +142,19 @@ func TestCheckPendingNotifications(t *testing.T) { job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{ { post: &model.Post{ - UserId: th.BasicUser.Id, + UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, - CreateAt: 10060000, - Message: "post1", + CreateAt: 10060000, + Message: "post1", }, teamName: th.BasicTeam.Name, }, { post: &model.Post{ - UserId: th.BasicUser.Id, + UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, - CreateAt: 10090000, - Message: "post2", + CreateAt: 10090000, + Message: "post2", }, teamName: th.BasicTeam.Name, }, @@ -200,20 +202,21 @@ func TestCheckPendingNotifications(t *testing.T) { * Ensures that email batch interval defaults to 15 minutes for users that haven't explicitly set this preference */ func TestCheckPendingNotificationsDefaultInterval(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() job := MakeEmailBatchingJob(128) // bypasses recent user activity check - channelMember := store.Must(Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember := store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 9999000 - store.Must(Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{ { post: &model.Post{ - UserId: th.BasicUser.Id, + UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, - CreateAt: 10000000, + CreateAt: 10000000, }, teamName: th.BasicTeam.Name, }, @@ -236,16 +239,17 @@ func TestCheckPendingNotificationsDefaultInterval(t *testing.T) { * Ensures that email batch interval defaults to 15 minutes if user preference is invalid */ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() job := MakeEmailBatchingJob(128) // bypasses recent user activity check - channelMember := store.Must(Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember := store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 9999000 - store.Must(Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) // preference value is not an integer, so we'll fall back to the default 15min value - store.Must(Srv.Store.Preference().Save(&model.Preferences{{ + store.Must(a.Srv.Store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, @@ -255,9 +259,9 @@ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) { job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{ { post: &model.Post{ - UserId: th.BasicUser.Id, + UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, - CreateAt: 10000000, + CreateAt: 10000000, }, teamName: th.BasicTeam.Name, }, @@ -280,7 +284,8 @@ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) { * Ensures that post contents are not included in notification email when email notification content type is set to generic */ func TestRenderBatchedPostGeneric(t *testing.T) { - Setup() + a := Global() + a.Setup() var post = &model.Post{} post.Message = "This is the message" var notification = &batchedNotification{} @@ -295,7 +300,7 @@ func TestRenderBatchedPostGeneric(t *testing.T) { return translationID } - var rendered = renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_GENERIC) + var rendered = a.renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_GENERIC) if strings.Contains(rendered, post.Message) { t.Fatal("Rendered email should not contain post contents when email notification contents type is set to Generic.") } @@ -305,7 +310,8 @@ func TestRenderBatchedPostGeneric(t *testing.T) { * Ensures that post contents included in notification email when email notification content type is set to full */ func TestRenderBatchedPostFull(t *testing.T) { - Setup() + a := Global() + a.Setup() var post = &model.Post{} post.Message = "This is the message" var notification = &batchedNotification{} @@ -320,7 +326,7 @@ func TestRenderBatchedPostFull(t *testing.T) { return translationID } - var rendered = renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_FULL) + var rendered = a.renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_FULL) if !strings.Contains(rendered, post.Message) { t.Fatal("Rendered email should contain post contents when email notification contents type is set to Full.") } diff --git a/app/email_test.go b/app/email_test.go index 449e81b75..c0333827b 100644 --- a/app/email_test.go +++ b/app/email_test.go @@ -12,10 +12,11 @@ import ( ) func TestSendChangeUsernameEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var emailTo string = "test@example.com" var oldUsername string = "myoldusername" @@ -63,10 +64,11 @@ func TestSendChangeUsernameEmail(t *testing.T) { } func TestSendEmailChangeVerifyEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var newUserEmail string = "newtest@example.com" var locale string = "en" @@ -117,10 +119,11 @@ func TestSendEmailChangeVerifyEmail(t *testing.T) { } func TestSendEmailChangeEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var oldEmail string = "test@example.com" var newUserEmail string = "newtest@example.com" @@ -167,10 +170,11 @@ func TestSendEmailChangeEmail(t *testing.T) { } func TestSendVerifyEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var userEmail string = "test@example.com" var locale string = "en" @@ -221,10 +225,11 @@ func TestSendVerifyEmail(t *testing.T) { } func TestSendSignInChangeEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var email string = "test@example.com" var locale string = "en" @@ -271,10 +276,11 @@ func TestSendSignInChangeEmail(t *testing.T) { } func TestSendWelcomeEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var userId string = "32432nkjnijn432uj32" var email string = "test@example.com" @@ -287,7 +293,7 @@ func TestSendWelcomeEmail(t *testing.T) { //Delete all the messages before check the sample email utils.DeleteMailBox(email) - if err := SendWelcomeEmail(userId, email, verified, locale, siteURL); err != nil { + if err := a.SendWelcomeEmail(userId, email, verified, locale, siteURL); err != nil { t.Log(err) t.Fatal("Should send change username email") } else { @@ -324,7 +330,7 @@ func TestSendWelcomeEmail(t *testing.T) { verified = false var expectedVerifyEmail string = "Please verify your email address by clicking below." - if err := SendWelcomeEmail(userId, email, verified, locale, siteURL); err != nil { + if err := a.SendWelcomeEmail(userId, email, verified, locale, siteURL); err != nil { t.Log(err) t.Fatal("Should send change username email") } else { @@ -367,10 +373,11 @@ func TestSendWelcomeEmail(t *testing.T) { } func TestSendPasswordChangeEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var email string = "test@example.com" var locale string = "en" @@ -417,10 +424,11 @@ func TestSendPasswordChangeEmail(t *testing.T) { } func TestSendMfaChangeEmail(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - Setup() + a.Setup() var email string = "test@example.com" var locale string = "en" @@ -504,10 +512,11 @@ func TestSendMfaChangeEmail(t *testing.T) { } func TestSendInviteEmails(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - th := Setup().InitBasic() + th := a.Setup().InitBasic() var email1 string = "test1@example.com" var email2 string = "test2@example.com" @@ -582,10 +591,11 @@ func TestSendInviteEmails(t *testing.T) { } func TestSendPasswordReset(t *testing.T) { + a := Global() if testing.Short() { t.SkipNow() } - th := Setup().InitBasic() + th := a.Setup().InitBasic() var siteURL string = "http://test.mattermost.io" // var locale string = "en" @@ -595,7 +605,7 @@ func TestSendPasswordReset(t *testing.T) { //Delete all the messages before check the sample email utils.DeleteMailBox(th.BasicUser.Email) - if _, err := SendPasswordReset(th.BasicUser.Email, siteURL); err != nil { + if _, err := a.SendPasswordReset(th.BasicUser.Email, siteURL); err != nil { t.Log(err) t.Fatal("Should send change username email") } else { @@ -620,7 +630,7 @@ func TestSendPasswordReset(t *testing.T) { loc += 6 recoveryTokenString := resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE] var recoveryToken *model.Token - if result := <-Srv.Store.Token().GetByToken(recoveryTokenString); result.Err != nil { + if result := <-a.Srv.Store.Token().GetByToken(recoveryTokenString); result.Err != nil { t.Log(recoveryTokenString) t.Fatal(result.Err) } else { diff --git a/app/emoji.go b/app/emoji.go index 0e0e8e53a..b07889f8d 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -29,7 +29,7 @@ const ( MaxEmojiHeight = 128 ) -func CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *multipart.Form) (*model.Emoji, *model.AppError) { +func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *multipart.Form) (*model.Emoji, *model.AppError) { // wipe the emoji id so that existing emojis can't get overwritten emoji.Id = "" @@ -44,7 +44,7 @@ func CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *m return nil, model.NewAppError("createEmoji", "api.emoji.create.other_user.app_error", nil, "", http.StatusForbidden) } - if result := <-Srv.Store.Emoji().GetByName(emoji.Name); result.Err == nil && result.Data != nil { + if result := <-a.Srv.Store.Emoji().GetByName(emoji.Name); result.Err == nil && result.Data != nil { return nil, model.NewAppError("createEmoji", "api.emoji.create.duplicate.app_error", nil, "", http.StatusBadRequest) } @@ -55,7 +55,7 @@ func CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *m return nil, err } - if result := <-Srv.Store.Emoji().Save(emoji); result.Err != nil { + if result := <-a.Srv.Store.Emoji().Save(emoji); result.Err != nil { return nil, result.Err } else { message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EMOJI_ADDED, "", "", "", nil) @@ -66,8 +66,8 @@ func CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *m } } -func GetEmojiList(page, perPage int) ([]*model.Emoji, *model.AppError) { - if result := <-Srv.Store.Emoji().GetList(page*perPage, perPage); result.Err != nil { +func (a *App) GetEmojiList(page, perPage int) ([]*model.Emoji, *model.AppError) { + if result := <-a.Srv.Store.Emoji().GetList(page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Emoji), nil @@ -126,17 +126,17 @@ func UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppErro return nil } -func DeleteEmoji(emoji *model.Emoji) *model.AppError { - if err := (<-Srv.Store.Emoji().Delete(emoji.Id, model.GetMillis())).Err; err != nil { +func (a *App) DeleteEmoji(emoji *model.Emoji) *model.AppError { + if err := (<-a.Srv.Store.Emoji().Delete(emoji.Id, model.GetMillis())).Err; err != nil { return err } deleteEmojiImage(emoji.Id) - deleteReactionsForEmoji(emoji.Name) + a.deleteReactionsForEmoji(emoji.Name) return nil } -func GetEmoji(emojiId string) (*model.Emoji, *model.AppError) { +func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableCustomEmoji { return nil, model.NewAppError("deleteEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -145,15 +145,15 @@ func GetEmoji(emojiId string) (*model.Emoji, *model.AppError) { return nil, model.NewAppError("deleteImage", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Emoji().Get(emojiId, false); result.Err != nil { + if result := <-a.Srv.Store.Emoji().Get(emojiId, false); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Emoji), nil } } -func GetEmojiImage(emojiId string) (imageByte []byte, imageType string, err *model.AppError) { - if result := <-Srv.Store.Emoji().Get(emojiId, true); result.Err != nil { +func (a *App) GetEmojiImage(emojiId string) (imageByte []byte, imageType string, err *model.AppError) { + if result := <-a.Srv.Store.Emoji().Get(emojiId, true); result.Err != nil { return nil, "", result.Err } else { var img []byte @@ -223,8 +223,8 @@ func deleteEmojiImage(id string) { } } -func deleteReactionsForEmoji(emojiName string) { - if result := <-Srv.Store.Reaction().DeleteAllWithEmojiName(emojiName); result.Err != nil { +func (a *App) deleteReactionsForEmoji(emojiName string) { + if result := <-a.Srv.Store.Reaction().DeleteAllWithEmojiName(emojiName); result.Err != nil { l4g.Warn(utils.T("api.emoji.delete.delete_reactions.app_error"), emojiName) l4g.Warn(result.Err) } diff --git a/app/file.go b/app/file.go index 3c2a2b3e4..32cb40323 100644 --- a/app/file.go +++ b/app/file.go @@ -107,13 +107,13 @@ func GetInfoForFilename(post *model.Post, teamId string, filename string) *model return info } -func FindTeamIdForFilename(post *model.Post, filename string) string { +func (a *App) FindTeamIdForFilename(post *model.Post, filename string) string { split := strings.SplitN(filename, "/", 5) id := split[3] name, _ := url.QueryUnescape(split[4]) // This post is in a direct channel so we need to figure out what team the files are stored under. - if result := <-Srv.Store.Team().GetTeamsByUserId(post.UserId); result.Err != nil { + if result := <-a.Srv.Store.Team().GetTeamsByUserId(post.UserId); result.Err != nil { l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.teams.app_error"), post.Id, result.Err) } else if teams := result.Data.([]*model.Team); len(teams) == 1 { // The user has only one team so the post must've been sent from it @@ -134,13 +134,13 @@ func FindTeamIdForFilename(post *model.Post, filename string) string { var fileMigrationLock sync.Mutex // Creates and stores FileInfos for a post created before the FileInfos table existed. -func MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { +func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { if len(post.Filenames) == 0 { l4g.Warn(utils.T("api.file.migrate_filenames_to_file_infos.no_filenames.warn"), post.Id) return []*model.FileInfo{} } - cchan := Srv.Store.Channel().Get(post.ChannelId, true) + cchan := a.Srv.Store.Channel().Get(post.ChannelId, true) // There's a weird bug that rarely happens where a post ends up with duplicate Filenames so remove those filenames := utils.RemoveDuplicatesFromStringArray(post.Filenames) @@ -157,7 +157,7 @@ func MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { var teamId string if channel.TeamId == "" { // This post was made in a cross-team DM channel so we need to find where its files were saved - teamId = FindTeamIdForFilename(post, filenames[0]) + teamId = a.FindTeamIdForFilename(post, filenames[0]) } else { teamId = channel.TeamId } @@ -181,12 +181,12 @@ func MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { fileMigrationLock.Lock() defer fileMigrationLock.Unlock() - if result := <-Srv.Store.Post().Get(post.Id); result.Err != nil { + if result := <-a.Srv.Store.Post().Get(post.Id); result.Err != nil { l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.get_post_again.app_error"), post.Id, result.Err) return []*model.FileInfo{} } else if newPost := result.Data.(*model.PostList).Posts[post.Id]; len(newPost.Filenames) != len(post.Filenames) { // Another thread has already created FileInfos for this post, so just return those - if result := <-Srv.Store.FileInfo().GetForPost(post.Id, true, false); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().GetForPost(post.Id, true, false); result.Err != nil { l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.get_post_file_infos_again.app_error"), post.Id, result.Err) return []*model.FileInfo{} } else { @@ -200,7 +200,7 @@ func MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { savedInfos := make([]*model.FileInfo, 0, len(infos)) fileIds := make([]string, 0, len(filenames)) for _, info := range infos { - if result := <-Srv.Store.FileInfo().Save(info); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil { l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.save_file_info.app_error"), post.Id, info.Id, info.Path, result.Err) continue } @@ -217,7 +217,7 @@ func MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { newPost.FileIds = fileIds // Update Posts to clear Filenames and set FileIds - if result := <-Srv.Store.Post().Update(newPost, post); result.Err != nil { + if result := <-a.Srv.Store.Post().Update(newPost, post); result.Err != nil { l4g.Error(utils.T("api.file.migrate_filenames_to_file_infos.save_post.app_error"), post.Id, newPost.FileIds, post.Filenames, result.Err) return []*model.FileInfo{} } else { @@ -243,7 +243,7 @@ func GeneratePublicLinkHash(fileId, salt string) string { return base64.RawURLEncoding.EncodeToString(hash.Sum(nil)) } -func UploadFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string) (*model.FileUploadResponse, *model.AppError) { +func (a *App) UploadFiles(teamId string, channelId string, userId string, fileHeaders []*multipart.FileHeader, clientIds []string) (*model.FileUploadResponse, *model.AppError) { if len(*utils.Cfg.FileSettings.DriverName) == 0 { return nil, model.NewAppError("uploadFile", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented) } @@ -268,7 +268,7 @@ func UploadFiles(teamId string, channelId string, userId string, fileHeaders []* io.Copy(buf, file) data := buf.Bytes() - info, err := DoUploadFile(time.Now(), teamId, channelId, userId, fileHeader.Filename, data) + info, err := a.DoUploadFile(time.Now(), teamId, channelId, userId, fileHeader.Filename, data) if err != nil { return nil, err } @@ -291,7 +291,7 @@ func UploadFiles(teamId string, channelId string, userId string, fileHeaders []* return resStruct, nil } -func DoUploadFile(now time.Time, teamId string, channelId string, userId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) { +func (a *App) DoUploadFile(now time.Time, teamId string, channelId string, userId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) { filename := filepath.Base(rawFilename) info, err := model.GetInfoForBytes(filename, data) @@ -323,7 +323,7 @@ func DoUploadFile(now time.Time, teamId string, channelId string, userId string, return nil, err } - if result := <-Srv.Store.FileInfo().Save(info); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().Save(info); result.Err != nil { return nil, result.Err } @@ -464,8 +464,8 @@ func generatePreviewImage(img image.Image, previewPath string, width int) { } } -func GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) { - if result := <-Srv.Store.FileInfo().Get(fileId); result.Err != nil { +func (a *App) GetFileInfo(fileId string) (*model.FileInfo, *model.AppError) { + if result := <-a.Srv.Store.FileInfo().Get(fileId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.FileInfo), nil diff --git a/app/file_test.go b/app/file_test.go index 962661039..52f42707c 100644 --- a/app/file_test.go +++ b/app/file_test.go @@ -36,7 +36,8 @@ func TestGeneratePublicLinkHash(t *testing.T) { } func TestDoUploadFile(t *testing.T) { - Setup() + a := Global() + a.Setup() teamId := model.NewId() channelId := model.NewId() @@ -44,12 +45,12 @@ func TestDoUploadFile(t *testing.T) { filename := "test" data := []byte("abcd") - info1, err := DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) + info1, err := a.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) if err != nil { t.Fatal(err) } else { defer func() { - <-Srv.Store.FileInfo().PermanentDelete(info1.Id) + <-a.Srv.Store.FileInfo().PermanentDelete(info1.Id) utils.RemoveFile(info1.Path) }() } @@ -58,12 +59,12 @@ func TestDoUploadFile(t *testing.T) { t.Fatal("stored file at incorrect path", info1.Path) } - info2, err := DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) + info2, err := a.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) if err != nil { t.Fatal(err) } else { defer func() { - <-Srv.Store.FileInfo().PermanentDelete(info2.Id) + <-a.Srv.Store.FileInfo().PermanentDelete(info2.Id) utils.RemoveFile(info2.Path) }() } @@ -72,12 +73,12 @@ func TestDoUploadFile(t *testing.T) { t.Fatal("stored file at incorrect path", info2.Path) } - info3, err := DoUploadFile(time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) + info3, err := a.DoUploadFile(time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) if err != nil { t.Fatal(err) } else { defer func() { - <-Srv.Store.FileInfo().PermanentDelete(info3.Id) + <-a.Srv.Store.FileInfo().PermanentDelete(info3.Id) utils.RemoveFile(info3.Path) }() } diff --git a/app/import.go b/app/import.go index c6afd1634..3c952b9c1 100644 --- a/app/import.go +++ b/app/import.go @@ -155,16 +155,16 @@ type LineImportWorkerError struct { // still enforced. // -func bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan LineImportWorkerData, errors chan<- LineImportWorkerError) { +func (a *App) bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan LineImportWorkerData, errors chan<- LineImportWorkerError) { for line := range lines { - if err := ImportLine(line.LineImportData, dryRun); err != nil { + if err := a.ImportLine(line.LineImportData, dryRun); err != nil { errors <- LineImportWorkerError{err, line.LineNumber} } } wg.Done() } -func BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) { +func (a *App) BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) { scanner := bufio.NewScanner(fileReader) lineNumber := 0 @@ -209,7 +209,7 @@ func BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError linesChan = make(chan LineImportWorkerData, workers) for i := 0; i < workers; i++ { wg.Add(1) - go bulkImportWorker(dryRun, &wg, linesChan, errorsChan) + go a.bulkImportWorker(dryRun, &wg, linesChan, errorsChan) } } @@ -249,50 +249,50 @@ func processImportDataFileVersionLine(line LineImportData) (int, *model.AppError return *line.Version, nil } -func ImportLine(line LineImportData, dryRun bool) *model.AppError { +func (a *App) ImportLine(line LineImportData, dryRun bool) *model.AppError { switch { case line.Type == "team": if line.Team == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_team.error", nil, "", http.StatusBadRequest) } else { - return ImportTeam(line.Team, dryRun) + return a.ImportTeam(line.Team, dryRun) } case line.Type == "channel": if line.Channel == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_channel.error", nil, "", http.StatusBadRequest) } else { - return ImportChannel(line.Channel, dryRun) + return a.ImportChannel(line.Channel, dryRun) } case line.Type == "user": if line.User == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_user.error", nil, "", http.StatusBadRequest) } else { - return ImportUser(line.User, dryRun) + return a.ImportUser(line.User, dryRun) } case line.Type == "post": if line.Post == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_post.error", nil, "", http.StatusBadRequest) } else { - return ImportPost(line.Post, dryRun) + return a.ImportPost(line.Post, dryRun) } case line.Type == "direct_channel": if line.DirectChannel == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_direct_channel.error", nil, "", http.StatusBadRequest) } else { - return ImportDirectChannel(line.DirectChannel, dryRun) + return a.ImportDirectChannel(line.DirectChannel, dryRun) } case line.Type == "direct_post": if line.DirectPost == nil { return model.NewAppError("BulkImport", "app.import.import_line.null_direct_post.error", nil, "", http.StatusBadRequest) } else { - return ImportDirectPost(line.DirectPost, dryRun) + return a.ImportDirectPost(line.DirectPost, dryRun) } default: return model.NewAppError("BulkImport", "app.import.import_line.unknown_line_type.error", map[string]interface{}{"Type": line.Type}, "", http.StatusBadRequest) } } -func ImportTeam(data *TeamImportData, dryRun bool) *model.AppError { +func (a *App) ImportTeam(data *TeamImportData, dryRun bool) *model.AppError { if err := validateTeamImportData(data); err != nil { return err } @@ -303,7 +303,7 @@ func ImportTeam(data *TeamImportData, dryRun bool) *model.AppError { } var team *model.Team - if result := <-Srv.Store.Team().GetByName(*data.Name); result.Err == nil { + if result := <-a.Srv.Store.Team().GetByName(*data.Name); result.Err == nil { team = result.Data.(*model.Team) } else { team = &model.Team{} @@ -322,11 +322,11 @@ func ImportTeam(data *TeamImportData, dryRun bool) *model.AppError { } if team.Id == "" { - if _, err := CreateTeam(team); err != nil { + if _, err := a.CreateTeam(team); err != nil { return err } } else { - if _, err := UpdateTeam(team); err != nil { + if _, err := a.UpdateTeam(team); err != nil { return err } } @@ -365,7 +365,7 @@ func validateTeamImportData(data *TeamImportData) *model.AppError { return nil } -func ImportChannel(data *ChannelImportData, dryRun bool) *model.AppError { +func (a *App) ImportChannel(data *ChannelImportData, dryRun bool) *model.AppError { if err := validateChannelImportData(data); err != nil { return err } @@ -376,14 +376,14 @@ func ImportChannel(data *ChannelImportData, dryRun bool) *model.AppError { } var team *model.Team - if result := <-Srv.Store.Team().GetByName(*data.Team); result.Err != nil { + if result := <-a.Srv.Store.Team().GetByName(*data.Team); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_channel.team_not_found.error", map[string]interface{}{"TeamName": *data.Team}, "", http.StatusBadRequest) } else { team = result.Data.(*model.Team) } var channel *model.Channel - if result := <-Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); result.Err == nil { + if result := <-a.Srv.Store.Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); result.Err == nil { channel = result.Data.(*model.Channel) } else { channel = &model.Channel{} @@ -403,11 +403,11 @@ func ImportChannel(data *ChannelImportData, dryRun bool) *model.AppError { } if channel.Id == "" { - if _, err := CreateChannel(channel, false); err != nil { + if _, err := a.CreateChannel(channel, false); err != nil { return err } } else { - if _, err := UpdateChannel(channel); err != nil { + if _, err := a.UpdateChannel(channel); err != nil { return err } } @@ -452,7 +452,7 @@ func validateChannelImportData(data *ChannelImportData) *model.AppError { return nil } -func ImportUser(data *UserImportData, dryRun bool) *model.AppError { +func (a *App) ImportUser(data *UserImportData, dryRun bool) *model.AppError { if err := validateUserImportData(data); err != nil { return err } @@ -470,7 +470,7 @@ func ImportUser(data *UserImportData, dryRun bool) *model.AppError { hasUserEmailVerifiedChanged := false var user *model.User - if result := <-Srv.Store.User().GetByUsername(*data.Username); result.Err == nil { + if result := <-a.Srv.Store.User().GetByUsername(*data.Username); result.Err == nil { user = result.Data.(*model.User) } else { user = &model.User{} @@ -645,39 +645,39 @@ func ImportUser(data *UserImportData, dryRun bool) *model.AppError { } if user.Id == "" { - if _, err := createUser(user); err != nil { + if _, err := a.createUser(user); err != nil { return err } } else { if hasUserChanged { - if _, err := UpdateUser(user, false); err != nil { + if _, err := a.UpdateUser(user, false); err != nil { return err } } if hasUserRolesChanged { - if _, err := UpdateUserRoles(user.Id, roles); err != nil { + if _, err := a.UpdateUserRoles(user.Id, roles); err != nil { return err } } if hasNotifyPropsChanged { - if _, err := UpdateUserNotifyProps(user.Id, user.NotifyProps); err != nil { + if _, err := a.UpdateUserNotifyProps(user.Id, user.NotifyProps); err != nil { return err } } if len(password) > 0 { - if err := UpdatePassword(user, password); err != nil { + if err := a.UpdatePassword(user, password); err != nil { return err } } else { if hasUserAuthDataChanged { - if res := <-Srv.Store.User().UpdateAuthData(user.Id, authService, authData, user.Email, false); res.Err != nil { + if res := <-a.Srv.Store.User().UpdateAuthData(user.Id, authService, authData, user.Email, false); res.Err != nil { return res.Err } } } if emailVerified { if hasUserEmailVerifiedChanged { - if err := VerifyUserEmail(user.Id); err != nil { + if err := a.VerifyUserEmail(user.Id); err != nil { return err } } @@ -742,26 +742,26 @@ func ImportUser(data *UserImportData, dryRun bool) *model.AppError { } if len(preferences) > 0 { - if result := <-Srv.Store.Preference().Save(&preferences); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&preferences); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_user.save_preferences.error", nil, "", http.StatusInternalServerError) } } - return ImportUserTeams(*data.Username, data.Teams) + return a.ImportUserTeams(*data.Username, data.Teams) } -func ImportUserTeams(username string, data *[]UserTeamImportData) *model.AppError { +func (a *App) ImportUserTeams(username string, data *[]UserTeamImportData) *model.AppError { if data == nil { return nil } - user, err := GetUserByUsername(username) + user, err := a.GetUserByUsername(username) if err != nil { return err } for _, tdata := range *data { - team, err := GetTeamByName(*tdata.Name) + team, err := a.GetTeamByName(*tdata.Name) if err != nil { return err } @@ -773,22 +773,22 @@ func ImportUserTeams(username string, data *[]UserTeamImportData) *model.AppErro roles = *tdata.Roles } - if _, err := joinUserToTeam(team, user); err != nil { + if _, err := a.joinUserToTeam(team, user); err != nil { return err } var member *model.TeamMember - if member, err = GetTeamMember(team.Id, user.Id); err != nil { + if member, err = a.GetTeamMember(team.Id, user.Id); err != nil { return err } else { if member.Roles != roles { - if _, err := UpdateTeamMemberRoles(team.Id, user.Id, roles); err != nil { + if _, err := a.UpdateTeamMemberRoles(team.Id, user.Id, roles); err != nil { return err } } } - if err := ImportUserChannels(user, team, member, tdata.Channels); err != nil { + if err := a.ImportUserChannels(user, team, member, tdata.Channels); err != nil { return err } } @@ -796,7 +796,7 @@ func ImportUserTeams(username string, data *[]UserTeamImportData) *model.AppErro return nil } -func ImportUserChannels(user *model.User, team *model.Team, teamMember *model.TeamMember, data *[]UserChannelImportData) *model.AppError { +func (a *App) ImportUserChannels(user *model.User, team *model.Team, teamMember *model.TeamMember, data *[]UserChannelImportData) *model.AppError { if data == nil { return nil } @@ -805,7 +805,7 @@ func ImportUserChannels(user *model.User, team *model.Team, teamMember *model.Te // Loop through all channels. for _, cdata := range *data { - channel, err := GetChannelByName(*cdata.Name, team.Id) + channel, err := a.GetChannelByName(*cdata.Name, team.Id) if err != nil { return err } @@ -818,16 +818,16 @@ func ImportUserChannels(user *model.User, team *model.Team, teamMember *model.Te } var member *model.ChannelMember - member, err = GetChannelMember(channel.Id, user.Id) + member, err = a.GetChannelMember(channel.Id, user.Id) if err != nil { - member, err = addUserToChannel(user, channel, teamMember) + member, err = a.addUserToChannel(user, channel, teamMember) if err != nil { return err } } if member.Roles != roles { - if _, err := UpdateChannelMemberRoles(channel.Id, user.Id, roles); err != nil { + if _, err := a.UpdateChannelMemberRoles(channel.Id, user.Id, roles); err != nil { return err } } @@ -847,7 +847,7 @@ func ImportUserChannels(user *model.User, team *model.Team, teamMember *model.Te notifyProps[model.MARK_UNREAD_NOTIFY_PROP] = *cdata.NotifyProps.MarkUnread } - if _, err := UpdateChannelMemberNotifyProps(notifyProps, channel.Id, user.Id); err != nil { + if _, err := a.UpdateChannelMemberNotifyProps(notifyProps, channel.Id, user.Id); err != nil { return err } } @@ -863,7 +863,7 @@ func ImportUserChannels(user *model.User, team *model.Team, teamMember *model.Te } if len(preferences) > 0 { - if result := <-Srv.Store.Preference().Save(&preferences); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&preferences); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_user_channels.save_preferences.error", nil, "", http.StatusInternalServerError) } } @@ -1022,7 +1022,7 @@ func validateUserChannelsImportData(data *[]UserChannelImportData) *model.AppErr return nil } -func ImportPost(data *PostImportData, dryRun bool) *model.AppError { +func (a *App) ImportPost(data *PostImportData, dryRun bool) *model.AppError { if err := validatePostImportData(data); err != nil { return err } @@ -1033,21 +1033,21 @@ func ImportPost(data *PostImportData, dryRun bool) *model.AppError { } var team *model.Team - if result := <-Srv.Store.Team().GetByName(*data.Team); result.Err != nil { + if result := <-a.Srv.Store.Team().GetByName(*data.Team); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_post.team_not_found.error", map[string]interface{}{"TeamName": *data.Team}, "", http.StatusBadRequest) } else { team = result.Data.(*model.Team) } var channel *model.Channel - if result := <-Srv.Store.Channel().GetByName(team.Id, *data.Channel, false); result.Err != nil { + if result := <-a.Srv.Store.Channel().GetByName(team.Id, *data.Channel, false); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_post.channel_not_found.error", map[string]interface{}{"ChannelName": *data.Channel}, "", http.StatusBadRequest) } else { channel = result.Data.(*model.Channel) } var user *model.User - if result := <-Srv.Store.User().GetByUsername(*data.User); result.Err != nil { + if result := <-a.Srv.Store.User().GetByUsername(*data.User); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": *data.User}, "", http.StatusBadRequest) } else { user = result.Data.(*model.User) @@ -1055,7 +1055,7 @@ func ImportPost(data *PostImportData, dryRun bool) *model.AppError { // Check if this post already exists. var posts []*model.Post - if result := <-Srv.Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt); result.Err != nil { return result.Err } else { posts = result.Data.([]*model.Post) @@ -1081,11 +1081,11 @@ func ImportPost(data *PostImportData, dryRun bool) *model.AppError { post.Hashtags, _ = model.ParseHashtags(post.Message) if post.Id == "" { - if result := <-Srv.Store.Post().Save(post); result.Err != nil { + if result := <-a.Srv.Store.Post().Save(post); result.Err != nil { return result.Err } } else { - if result := <-Srv.Store.Post().Overwrite(post); result.Err != nil { + if result := <-a.Srv.Store.Post().Overwrite(post); result.Err != nil { return result.Err } } @@ -1096,7 +1096,7 @@ func ImportPost(data *PostImportData, dryRun bool) *model.AppError { for _, username := range *data.FlaggedBy { var user *model.User - if result := <-Srv.Store.User().GetByUsername(username); result.Err != nil { + if result := <-a.Srv.Store.User().GetByUsername(username); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]interface{}{"Username": username}, "", http.StatusBadRequest) } else { user = result.Data.(*model.User) @@ -1111,7 +1111,7 @@ func ImportPost(data *PostImportData, dryRun bool) *model.AppError { } if len(preferences) > 0 { - if result := <-Srv.Store.Preference().Save(&preferences); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&preferences); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_post.save_preferences.error", nil, "", http.StatusInternalServerError) } } @@ -1148,7 +1148,7 @@ func validatePostImportData(data *PostImportData) *model.AppError { return nil } -func ImportDirectChannel(data *DirectChannelImportData, dryRun bool) *model.AppError { +func (a *App) ImportDirectChannel(data *DirectChannelImportData, dryRun bool) *model.AppError { if err := validateDirectChannelImportData(data); err != nil { return err } @@ -1161,7 +1161,7 @@ func ImportDirectChannel(data *DirectChannelImportData, dryRun bool) *model.AppE var userIds []string userMap := make(map[string]string) for _, username := range *data.Members { - if result := <-Srv.Store.User().GetByUsername(username); result.Err == nil { + if result := <-a.Srv.Store.User().GetByUsername(username); result.Err == nil { user := result.Data.(*model.User) userIds = append(userIds, user.Id) userMap[username] = user.Id @@ -1173,14 +1173,14 @@ func ImportDirectChannel(data *DirectChannelImportData, dryRun bool) *model.AppE var channel *model.Channel if len(userIds) == 2 { - ch, err := createDirectChannel(userIds[0], userIds[1]) + ch, err := a.createDirectChannel(userIds[0], userIds[1]) if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_direct_channel.error", nil, "", http.StatusBadRequest) } else { channel = ch } } else { - ch, err := createGroupChannel(userIds, userIds[0]) + ch, err := a.createGroupChannel(userIds, userIds[0]) if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_group_channel.error", nil, "", http.StatusBadRequest) } else { @@ -1210,14 +1210,14 @@ func ImportDirectChannel(data *DirectChannelImportData, dryRun bool) *model.AppE } } - if result := <-Srv.Store.Preference().Save(&preferences); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&preferences); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return result.Err } if data.Header != nil { channel.Header = *data.Header - if result := <-Srv.Store.Channel().Update(channel); result.Err != nil { + if result := <-a.Srv.Store.Channel().Update(channel); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_channel.update_header_failed.error", nil, "", http.StatusBadRequest) } } @@ -1260,7 +1260,7 @@ func validateDirectChannelImportData(data *DirectChannelImportData) *model.AppEr return nil } -func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { +func (a *App) ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { if err := validateDirectPostImportData(data); err != nil { return err } @@ -1272,7 +1272,7 @@ func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { var userIds []string for _, username := range *data.ChannelMembers { - if result := <-Srv.Store.User().GetByUsername(username); result.Err == nil { + if result := <-a.Srv.Store.User().GetByUsername(username); result.Err == nil { user := result.Data.(*model.User) userIds = append(userIds, user.Id) } else { @@ -1282,14 +1282,14 @@ func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { var channel *model.Channel if len(userIds) == 2 { - ch, err := createDirectChannel(userIds[0], userIds[1]) + ch, err := a.createDirectChannel(userIds[0], userIds[1]) if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { return model.NewAppError("BulkImport", "app.import.import_direct_post.create_direct_channel.error", nil, "", http.StatusBadRequest) } else { channel = ch } } else { - ch, err := createGroupChannel(userIds, userIds[0]) + ch, err := a.createGroupChannel(userIds, userIds[0]) if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { return model.NewAppError("BulkImport", "app.import.import_direct_post.create_group_channel.error", nil, "", http.StatusBadRequest) } else { @@ -1298,7 +1298,7 @@ func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { } var user *model.User - if result := <-Srv.Store.User().GetByUsername(*data.User); result.Err != nil { + if result := <-a.Srv.Store.User().GetByUsername(*data.User); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_post.user_not_found.error", map[string]interface{}{"Username": *data.User}, "", http.StatusBadRequest) } else { user = result.Data.(*model.User) @@ -1306,7 +1306,7 @@ func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { // Check if this post already exists. var posts []*model.Post - if result := <-Srv.Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, *data.CreateAt); result.Err != nil { return result.Err } else { posts = result.Data.([]*model.Post) @@ -1332,11 +1332,11 @@ func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { post.Hashtags, _ = model.ParseHashtags(post.Message) if post.Id == "" { - if result := <-Srv.Store.Post().Save(post); result.Err != nil { + if result := <-a.Srv.Store.Post().Save(post); result.Err != nil { return result.Err } } else { - if result := <-Srv.Store.Post().Overwrite(post); result.Err != nil { + if result := <-a.Srv.Store.Post().Overwrite(post); result.Err != nil { return result.Err } } @@ -1347,7 +1347,7 @@ func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { for _, username := range *data.FlaggedBy { var user *model.User - if result := <-Srv.Store.User().GetByUsername(username); result.Err != nil { + if result := <-a.Srv.Store.User().GetByUsername(username); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_post.user_not_found.error", map[string]interface{}{"Username": username}, "", http.StatusBadRequest) } else { user = result.Data.(*model.User) @@ -1362,7 +1362,7 @@ func ImportDirectPost(data *DirectPostImportData, dryRun bool) *model.AppError { } if len(preferences) > 0 { - if result := <-Srv.Store.Preference().Save(&preferences); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&preferences); result.Err != nil { return model.NewAppError("BulkImport", "app.import.import_direct_post.save_preferences.error", nil, "", http.StatusInternalServerError) } } @@ -1424,7 +1424,7 @@ func validateDirectPostImportData(data *DirectPostImportData) *model.AppError { // some of the usual checks. (IsValid is still run) // -func OldImportPost(post *model.Post) { +func (a *App) OldImportPost(post *model.Post) { // Workaround for empty messages, which may be the case if they are webhook posts. firstIteration := true for messageRuneCount := utf8.RuneCountInString(post.Message); messageRuneCount > 0 || firstIteration; messageRuneCount = utf8.RuneCountInString(post.Message) { @@ -1439,12 +1439,12 @@ func OldImportPost(post *model.Post) { post.Hashtags, _ = model.ParseHashtags(post.Message) - if result := <-Srv.Store.Post().Save(post); result.Err != nil { + if result := <-a.Srv.Store.Post().Save(post); result.Err != nil { l4g.Debug(utils.T("api.import.import_post.saving.debug"), post.UserId, post.Message) } for _, fileId := range post.FileIds { - if result := <-Srv.Store.FileInfo().AttachToPost(fileId, post.Id); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().AttachToPost(fileId, post.Id); result.Err != nil { l4g.Error(utils.T("api.import.import_post.attach_files.error"), post.Id, post.FileIds, result.Err) } } @@ -1455,22 +1455,22 @@ func OldImportPost(post *model.Post) { } } -func OldImportUser(team *model.Team, user *model.User) *model.User { +func (a *App) OldImportUser(team *model.Team, user *model.User) *model.User { user.MakeNonNil() user.Roles = model.ROLE_SYSTEM_USER.Id - if result := <-Srv.Store.User().Save(user); result.Err != nil { + if result := <-a.Srv.Store.User().Save(user); result.Err != nil { l4g.Error(utils.T("api.import.import_user.saving.error"), result.Err) return nil } else { ruser := result.Data.(*model.User) - if cresult := <-Srv.Store.User().VerifyEmail(ruser.Id); cresult.Err != nil { + if cresult := <-a.Srv.Store.User().VerifyEmail(ruser.Id); cresult.Err != nil { l4g.Error(utils.T("api.import.import_user.set_email.error"), cresult.Err) } - if err := JoinUserToTeam(team, user, ""); err != nil { + if err := a.JoinUserToTeam(team, user, ""); err != nil { l4g.Error(utils.T("api.import.import_user.join_team.error"), err) } @@ -1478,8 +1478,8 @@ func OldImportUser(team *model.Team, user *model.User) *model.User { } } -func OldImportChannel(channel *model.Channel) *model.Channel { - if result := <-Srv.Store.Channel().Save(channel); result.Err != nil { +func (a *App) OldImportChannel(channel *model.Channel) *model.Channel { + if result := <-a.Srv.Store.Channel().Save(channel); result.Err != nil { return nil } else { sc := result.Data.(*model.Channel) @@ -1488,12 +1488,12 @@ func OldImportChannel(channel *model.Channel) *model.Channel { } } -func OldImportFile(timestamp time.Time, file io.Reader, teamId string, channelId string, userId string, fileName string) (*model.FileInfo, error) { +func (a *App) OldImportFile(timestamp time.Time, file io.Reader, teamId string, channelId string, userId string, fileName string) (*model.FileInfo, error) { buf := bytes.NewBuffer(nil) io.Copy(buf, file) data := buf.Bytes() - fileInfo, err := DoUploadFile(timestamp, teamId, channelId, userId, fileName, data) + fileInfo, err := a.DoUploadFile(timestamp, teamId, channelId, userId, fileName, data) if err != nil { return nil, err } @@ -1507,7 +1507,7 @@ func OldImportFile(timestamp time.Time, file io.Reader, teamId string, channelId return fileInfo, nil } -func OldImportIncomingWebhookPost(post *model.Post, props model.StringInterface) { +func (a *App) OldImportIncomingWebhookPost(post *model.Post, props model.StringInterface) { linkWithTextRegex := regexp.MustCompile(`<([^<\|]+)\|([^>]+)>`) post.Message = linkWithTextRegex.ReplaceAllString(post.Message, "[${2}](${1})") @@ -1529,5 +1529,5 @@ func OldImportIncomingWebhookPost(post *model.Post, props model.StringInterface) } } - OldImportPost(post) + a.OldImportPost(post) } diff --git a/app/import_test.go b/app/import_test.go index 70a36f272..59e767706 100644 --- a/app/import_test.go +++ b/app/import_test.go @@ -30,7 +30,8 @@ func ptrBool(b bool) *bool { } func checkPreference(t *testing.T, userId string, category string, name string, value string) { - if res := <-Srv.Store.Preference().GetCategory(userId, category); res.Err != nil { + a := Global() + if res := <-a.Srv.Store.Preference().GetCategory(userId, category); res.Err != nil { debug.PrintStack() t.Fatalf("Failed to get preferences for user %v with category %v", userId, category) } else { @@ -965,11 +966,12 @@ func TestImportValidateDirectPostImportData(t *testing.T) { } func TestImportImportTeam(t *testing.T) { - _ = Setup() + a := Global() + _ = a.Setup() // Check how many teams are in the database. var teamsCount int64 - if r := <-Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { teamsCount = r.Data.(int64) } else { t.Fatalf("Failed to get team count.") @@ -984,18 +986,18 @@ func TestImportImportTeam(t *testing.T) { } // Try importing an invalid team in dryRun mode. - if err := ImportTeam(&data, true); err == nil { + if err := a.ImportTeam(&data, true); err == nil { t.Fatalf("Should have received an error importing an invalid team.") } // Do a valid team in dry-run mode. data.Type = ptrStr("O") - if err := ImportTeam(&data, true); err != nil { + if err := a.ImportTeam(&data, true); err != nil { t.Fatalf("Received an error validating valid team.") } // Check that no more teams are in the DB. - if r := <-Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64) != teamsCount { t.Fatalf("Teams got persisted in dry run mode.") } @@ -1005,12 +1007,12 @@ func TestImportImportTeam(t *testing.T) { // Do an invalid team in apply mode, check db changes. data.Type = ptrStr("XYZ") - if err := ImportTeam(&data, false); err == nil { + if err := a.ImportTeam(&data, false); err == nil { t.Fatalf("Import should have failed on invalid team.") } // Check that no more teams are in the DB. - if r := <-Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64) != teamsCount { t.Fatalf("Invalid team got persisted.") } @@ -1020,12 +1022,12 @@ func TestImportImportTeam(t *testing.T) { // Do a valid team in apply mode, check db changes. data.Type = ptrStr("O") - if err := ImportTeam(&data, false); err != nil { + if err := a.ImportTeam(&data, false); err != nil { t.Fatalf("Received an error importing valid team.") } // Check that one more team is in the DB. - if r := <-Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64)-1 != teamsCount { t.Fatalf("Team did not get saved in apply run mode. analytics=%v teamcount=%v", r.Data.(int64), teamsCount) } @@ -1034,7 +1036,7 @@ func TestImportImportTeam(t *testing.T) { } // Get the team and check that all the fields are correct. - if team, err := GetTeamByName(*data.Name); err != nil { + if team, err := a.GetTeamByName(*data.Name); err != nil { t.Fatalf("Failed to get team from database.") } else { if team.DisplayName != *data.DisplayName || team.Type != *data.Type || team.Description != *data.Description || team.AllowOpenInvite != *data.AllowOpenInvite { @@ -1050,11 +1052,11 @@ func TestImportImportTeam(t *testing.T) { // Check that the original number of teams are again in the DB (because this query doesn't include deleted). data.Type = ptrStr("O") - if err := ImportTeam(&data, false); err != nil { + if err := a.ImportTeam(&data, false); err != nil { t.Fatalf("Received an error importing updated valid team.") } - if r := <-Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64)-1 != teamsCount { t.Fatalf("Team alterations did not get saved in apply run mode. analytics=%v teamcount=%v", r.Data.(int64), teamsCount) } @@ -1063,7 +1065,7 @@ func TestImportImportTeam(t *testing.T) { } // Get the team and check that all fields are correct. - if team, err := GetTeamByName(*data.Name); err != nil { + if team, err := a.GetTeamByName(*data.Name); err != nil { t.Fatalf("Failed to get team from database.") } else { if team.DisplayName != *data.DisplayName || team.Type != *data.Type || team.Description != *data.Description || team.AllowOpenInvite != *data.AllowOpenInvite { @@ -1073,23 +1075,24 @@ func TestImportImportTeam(t *testing.T) { } func TestImportImportChannel(t *testing.T) { - _ = Setup() + a := Global() + _ = a.Setup() // Import a Team. teamName := model.NewId() - ImportTeam(&TeamImportData{ + a.ImportTeam(&TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - team, err := GetTeamByName(teamName) + team, err := a.GetTeamByName(teamName) if err != nil { t.Fatalf("Failed to get team from database.") } // Check how many channels are in the database. var channelCount int64 - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { channelCount = r.Data.(int64) } else { t.Fatalf("Failed to get team count.") @@ -1103,12 +1106,12 @@ func TestImportImportChannel(t *testing.T) { Header: ptrStr("Channe Header"), Purpose: ptrStr("Channel Purpose"), } - if err := ImportChannel(&data, true); err == nil { + if err := a.ImportChannel(&data, true); err == nil { t.Fatalf("Expected error due to invalid name.") } // Check that no more channels are in the DB. - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Channels got persisted in dry run mode.") } @@ -1119,12 +1122,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel with a nonexistent team in dry-run mode. data.Name = ptrStr("channelname") data.Team = ptrStr(model.NewId()) - if err := ImportChannel(&data, true); err != nil { + if err := a.ImportChannel(&data, true); err != nil { t.Fatalf("Expected success as cannot validate channel name in dry run mode.") } // Check that no more channels are in the DB. - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Channels got persisted in dry run mode.") } @@ -1134,12 +1137,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in dry-run mode. data.Team = &teamName - if err := ImportChannel(&data, true); err != nil { + if err := a.ImportChannel(&data, true); err != nil { t.Fatalf("Expected success as valid team.") } // Check that no more channels are in the DB. - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Channels got persisted in dry run mode.") } @@ -1149,12 +1152,12 @@ func TestImportImportChannel(t *testing.T) { // Do an invalid channel in apply mode. data.Name = nil - if err := ImportChannel(&data, false); err == nil { + if err := a.ImportChannel(&data, false); err == nil { t.Fatalf("Expected error due to invalid name (apply mode).") } // Check that no more channels are in the DB. - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Invalid channel got persisted in apply mode.") } @@ -1165,12 +1168,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in apply mode with a nonexistant team. data.Name = ptrStr("channelname") data.Team = ptrStr(model.NewId()) - if err := ImportChannel(&data, false); err == nil { + if err := a.ImportChannel(&data, false); err == nil { t.Fatalf("Expected error due to non-existant team (apply mode).") } // Check that no more channels are in the DB. - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Invalid team channel got persisted in apply mode.") } @@ -1180,12 +1183,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in apply mode. data.Team = &teamName - if err := ImportChannel(&data, false); err != nil { + if err := a.ImportChannel(&data, false); err != nil { t.Fatalf("Expected success in apply mode: %v", err.Error()) } // Check that no more channels are in the DB. - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount+1 { t.Fatalf("Channels did not get persisted in apply mode: found %v expected %v + 1", r.Data.(int64), channelCount) } @@ -1194,7 +1197,7 @@ func TestImportImportChannel(t *testing.T) { } // Get the Channel and check all the fields are correct. - if channel, err := GetChannelByName(*data.Name, team.Id); err != nil { + if channel, err := a.GetChannelByName(*data.Name, team.Id); err != nil { t.Fatalf("Failed to get channel from database.") } else { if channel.Name != *data.Name || channel.DisplayName != *data.DisplayName || channel.Type != *data.Type || channel.Header != *data.Header || channel.Purpose != *data.Purpose { @@ -1207,12 +1210,12 @@ func TestImportImportChannel(t *testing.T) { data.Type = ptrStr(model.CHANNEL_PRIVATE) data.Header = ptrStr("New Header") data.Purpose = ptrStr("New Purpose") - if err := ImportChannel(&data, false); err != nil { + if err := a.ImportChannel(&data, false); err != nil { t.Fatalf("Expected success in apply mode: %v", err.Error()) } // Check channel count the same. - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Updated channel did not get correctly persisted in apply mode.") } @@ -1221,7 +1224,7 @@ func TestImportImportChannel(t *testing.T) { } // Get the Channel and check all the fields are correct. - if channel, err := GetChannelByName(*data.Name, team.Id); err != nil { + if channel, err := a.GetChannelByName(*data.Name, team.Id); err != nil { t.Fatalf("Failed to get channel from database.") } else { if channel.Name != *data.Name || channel.DisplayName != *data.DisplayName || channel.Type != *data.Type || channel.Header != *data.Header || channel.Purpose != *data.Purpose { @@ -1232,11 +1235,12 @@ func TestImportImportChannel(t *testing.T) { } func TestImportImportUser(t *testing.T) { - _ = Setup() + a := Global() + _ = a.Setup() // Check how many users are in the database. var userCount int64 - if r := <-Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { userCount = r.Data.(int64) } else { t.Fatalf("Failed to get user count.") @@ -1246,12 +1250,12 @@ func TestImportImportUser(t *testing.T) { data := UserImportData{ Username: ptrStr(model.NewId()), } - if err := ImportUser(&data, true); err == nil { + if err := a.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed to import invalid user.") } // Check that no more users are in the DB. - if r := <-Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount { t.Fatalf("Unexpected number of users") } @@ -1264,12 +1268,12 @@ func TestImportImportUser(t *testing.T) { Username: ptrStr(model.NewId()), Email: ptrStr(model.NewId() + "@example.com"), } - if err := ImportUser(&data, true); err != nil { + if err := a.ImportUser(&data, true); err != nil { t.Fatalf("Should have succeeded to import valid user.") } // Check that no more users are in the DB. - if r := <-Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount { t.Fatalf("Unexpected number of users") } @@ -1281,12 +1285,12 @@ func TestImportImportUser(t *testing.T) { data = UserImportData{ Username: ptrStr(model.NewId()), } - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } // Check that no more users are in the DB. - if r := <-Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount { t.Fatalf("Unexpected number of users") } @@ -1304,12 +1308,12 @@ func TestImportImportUser(t *testing.T) { LastName: ptrStr(model.NewId()), Position: ptrStr(model.NewId()), } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded to import valid user.") } // Check that one more user is in the DB. - if r := <-Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount+1 { t.Fatalf("Unexpected number of users") } @@ -1318,7 +1322,7 @@ func TestImportImportUser(t *testing.T) { } // Get the user and check all the fields are correct. - if user, err := GetUserByUsername(username); err != nil { + if user, err := a.GetUserByUsername(username); err != nil { t.Fatalf("Failed to get user from database.") } else { if user.Email != *data.Email || user.Nickname != *data.Nickname || user.FirstName != *data.FirstName || user.LastName != *data.LastName || user.Position != *data.Position { @@ -1360,12 +1364,12 @@ func TestImportImportUser(t *testing.T) { data.Position = ptrStr(model.NewId()) data.Roles = ptrStr("system_admin system_user") data.Locale = ptrStr("zh_CN") - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded to update valid user %v", err) } // Check user count the same. - if r := <-Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount+1 { t.Fatalf("Unexpected number of users") } @@ -1374,7 +1378,7 @@ func TestImportImportUser(t *testing.T) { } // Get the user and check all the fields are correct. - if user, err := GetUserByUsername(username); err != nil { + if user, err := a.GetUserByUsername(username); err != nil { t.Fatalf("Failed to get user from database.") } else { if user.Email != *data.Email || user.Nickname != *data.Nickname || user.FirstName != *data.FirstName || user.LastName != *data.LastName || user.Position != *data.Position { @@ -1408,22 +1412,22 @@ func TestImportImportUser(t *testing.T) { // Check Password and AuthData together. data.Password = ptrStr("PasswordTest") - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } data.AuthData = nil - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded to update valid user %v", err) } data.Password = ptrStr("") - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } data.Password = ptrStr(strings.Repeat("0123456789", 10)) - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } @@ -1431,24 +1435,24 @@ func TestImportImportUser(t *testing.T) { // Test team and channel memberships teamName := model.NewId() - ImportTeam(&TeamImportData{ + a.ImportTeam(&TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - team, err := GetTeamByName(teamName) + team, err := a.GetTeamByName(teamName) if err != nil { t.Fatalf("Failed to get team from database.") } channelName := model.NewId() - ImportChannel(&ChannelImportData{ + a.ImportChannel(&ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - channel, err := GetChannelByName(channelName, team.Id) + channel, err := a.GetChannelByName(channelName, team.Id) if err != nil { t.Fatalf("Failed to get channel from database.") } @@ -1463,13 +1467,13 @@ func TestImportImportUser(t *testing.T) { Position: ptrStr(model.NewId()), } - teamMembers, err := GetTeamMembers(team.Id, 0, 1000) + teamMembers, err := a.GetTeamMembers(team.Id, 0, 1000) if err != nil { t.Fatalf("Failed to get team member count") } teamMemberCount := len(teamMembers) - channelMemberCount, err := GetChannelMemberCount(channel.Id) + channelMemberCount, err := a.GetChannelMemberCount(channel.Id) if err != nil { t.Fatalf("Failed to get channel member count") } @@ -1485,7 +1489,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, true); err == nil { + if err := a.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed.") } @@ -1500,7 +1504,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, true); err == nil { + if err := a.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed.") } @@ -1515,7 +1519,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, true); err == nil { + if err := a.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed.") } @@ -1530,7 +1534,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, true); err != nil { + if err := a.ImportUser(&data, true); err != nil { t.Fatalf("Should have succeeded.") } @@ -1545,18 +1549,18 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, true); err != nil { + if err := a.ImportUser(&data, true); err != nil { t.Fatalf("Should have succeeded.") } // Check no new member objects were created because dry run mode. - if tmc, err := GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount { t.Fatalf("Number of team members not as expected") } - if cmc, err := GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount { t.Fatalf("Number of channel members not as expected") @@ -1573,7 +1577,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } @@ -1588,7 +1592,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } @@ -1603,18 +1607,18 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } // Check no new member objects were created because all tests should have failed so far. - if tmc, err := GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount { t.Fatalf("Number of team members not as expected") } - if cmc, err := GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount { t.Fatalf("Number of channel members not as expected") @@ -1631,29 +1635,29 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, false); err == nil { + if err := a.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } // Check only new team member object created because dry run mode. - if tmc, err := GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount+1 { t.Fatalf("Number of team members not as expected") } - if cmc, err := GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount { t.Fatalf("Number of channel members not as expected") } // Check team member properties. - user, err := GetUserByUsername(username) + user, err := a.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } - if teamMember, err := GetTeamMember(team.Id, user.Id); err != nil { + if teamMember, err := a.GetTeamMember(team.Id, user.Id); err != nil { t.Fatalf("Failed to get team member from database.") } else if teamMember.Roles != "team_user" { t.Fatalf("Team member properties not as expected") @@ -1670,25 +1674,25 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } // Check only new channel member object created because dry run mode. - if tmc, err := GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount+1 { t.Fatalf("Number of team members not as expected") } - if cmc, err := GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount+1 { t.Fatalf("Number of channel members not as expected") } // Check channel member properties. - if channelMember, err := GetChannelMember(channel.Id, user.Id); err != nil { + if channelMember, err := a.GetChannelMember(channel.Id, user.Id); err != nil { t.Fatalf("Failed to get channel member from database.") } else if channelMember.Roles != "channel_user" || channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP] != "default" || channelMember.NotifyProps[model.PUSH_NOTIFY_PROP] != "default" || channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != "all" { t.Fatalf("Channel member properties not as expected") @@ -1713,18 +1717,18 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } // Check both member properties. - if teamMember, err := GetTeamMember(team.Id, user.Id); err != nil { + if teamMember, err := a.GetTeamMember(team.Id, user.Id); err != nil { t.Fatalf("Failed to get team member from database.") } else if teamMember.Roles != "team_user team_admin" { t.Fatalf("Team member properties not as expected: %v", teamMember.Roles) } - if channelMember, err := GetChannelMember(channel.Id, user.Id); err != nil { + if channelMember, err := a.GetChannelMember(channel.Id, user.Id); err != nil { t.Fatalf("Failed to get channel member Desktop from database.") } else if channelMember.Roles != "channel_user channel_admin" || channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP] != model.USER_NOTIFY_MENTION || channelMember.NotifyProps[model.PUSH_NOTIFY_PROP] != model.USER_NOTIFY_MENTION || channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != model.USER_NOTIFY_MENTION { t.Fatalf("Channel member properties not as expected") @@ -1733,13 +1737,13 @@ func TestImportImportUser(t *testing.T) { checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") // No more new member objects. - if tmc, err := GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount+1 { t.Fatalf("Number of team members not as expected") } - if cmc, err := GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount+1 { t.Fatalf("Number of channel members not as expected") @@ -1757,12 +1761,12 @@ func TestImportImportUser(t *testing.T) { ChannelDisplayMode: ptrStr("centered"), TutorialStep: ptrStr("3"), } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } // Check their values. - user, err = GetUserByUsername(username) + user, err = a.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -1785,7 +1789,7 @@ func TestImportImportUser(t *testing.T) { ChannelDisplayMode: ptrStr("full"), TutorialStep: ptrStr("2"), } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } @@ -1809,11 +1813,11 @@ func TestImportImportUser(t *testing.T) { CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ROOT), MentionKeys: ptrStr("valid,misc"), } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } - user, err = GetUserByUsername(username) + user, err = a.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -1840,11 +1844,11 @@ func TestImportImportUser(t *testing.T) { CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY), MentionKeys: ptrStr("misc"), } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } - user, err = GetUserByUsername(username) + user, err = a.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -1862,8 +1866,8 @@ func TestImportImportUser(t *testing.T) { // Check Notify Props get set on *create* user. username = model.NewId() data = UserImportData{ - Username: &username, - Email: ptrStr(model.NewId() + "@example.com"), + Username: &username, + Email: ptrStr(model.NewId() + "@example.com"), } data.NotifyProps = &UserNotifyPropsImportData{ Desktop: ptrStr(model.USER_NOTIFY_MENTION), @@ -1877,11 +1881,11 @@ func TestImportImportUser(t *testing.T) { MentionKeys: ptrStr("misc"), } - if err := ImportUser(&data, false); err != nil { + if err := a.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } - user, err = GetUserByUsername(username) + user, err = a.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -1898,7 +1902,8 @@ func TestImportImportUser(t *testing.T) { } func AssertAllPostsCount(t *testing.T, initialCount int64, change int64, teamName string) { - if result := <-Srv.Store.Post().AnalyticsPostCount(teamName, false, false); result.Err != nil { + a := Global() + if result := <-a.Srv.Store.Post().AnalyticsPostCount(teamName, false, false); result.Err != nil { t.Fatal(result.Err) } else { if initialCount+change != result.Data.(int64) { @@ -1909,47 +1914,48 @@ func AssertAllPostsCount(t *testing.T, initialCount int64, change int64, teamNam } func TestImportImportPost(t *testing.T) { - _ = Setup() + a := Global() + _ = a.Setup() // Create a Team. teamName := model.NewId() - ImportTeam(&TeamImportData{ + a.ImportTeam(&TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - team, err := GetTeamByName(teamName) + team, err := a.GetTeamByName(teamName) if err != nil { t.Fatalf("Failed to get team from database.") } // Create a Channel. channelName := model.NewId() - ImportChannel(&ChannelImportData{ + a.ImportChannel(&ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - channel, err := GetChannelByName(channelName, team.Id) + channel, err := a.GetChannelByName(channelName, team.Id) if err != nil { t.Fatalf("Failed to get channel from database.") } // Create a user. username := model.NewId() - ImportUser(&UserImportData{ + a.ImportUser(&UserImportData{ Username: &username, Email: ptrStr(model.NewId() + "@example.com"), }, false) - user, err := GetUserByUsername(username) + user, err := a.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } // Count the number of posts in the testing team. var initialPostCount int64 - if result := <-Srv.Store.Post().AnalyticsPostCount(team.Id, false, false); result.Err != nil { + if result := <-a.Srv.Store.Post().AnalyticsPostCount(team.Id, false, false); result.Err != nil { t.Fatal(result.Err) } else { initialPostCount = result.Data.(int64) @@ -1961,7 +1967,7 @@ func TestImportImportPost(t *testing.T) { Channel: &channelName, User: &username, } - if err := ImportPost(data, true); err == nil { + if err := a.ImportPost(data, true); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, team.Id) @@ -1974,7 +1980,7 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Hello"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportPost(data, true); err != nil { + if err := a.ImportPost(data, true); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 0, team.Id) @@ -1986,7 +1992,7 @@ func TestImportImportPost(t *testing.T) { User: &username, CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportPost(data, false); err == nil { + if err := a.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, team.Id) @@ -1999,7 +2005,7 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportPost(data, false); err == nil { + if err := a.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, team.Id) @@ -2012,7 +2018,7 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportPost(data, false); err == nil { + if err := a.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, team.Id) @@ -2025,7 +2031,7 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportPost(data, false); err == nil { + if err := a.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, team.Id) @@ -2039,13 +2045,13 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: &time, } - if err := ImportPost(data, false); err != nil { + if err := a.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 1, team.Id) // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2066,13 +2072,13 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: &time, } - if err := ImportPost(data, false); err != nil { + if err := a.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 1, team.Id) // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2094,7 +2100,7 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: &newTime, } - if err := ImportPost(data, false); err != nil { + if err := a.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 2, team.Id) @@ -2107,7 +2113,7 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message 2"), CreateAt: &time, } - if err := ImportPost(data, false); err != nil { + if err := a.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 3, team.Id) @@ -2121,12 +2127,12 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message 2 #hashtagmashupcity"), CreateAt: &hashtagTime, } - if err := ImportPost(data, false); err != nil { + if err := a.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 4, team.Id) - if result := <-Srv.Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2144,11 +2150,11 @@ func TestImportImportPost(t *testing.T) { // Post with flags. username2 := model.NewId() - ImportUser(&UserImportData{ + a.ImportUser(&UserImportData{ Username: &username2, Email: ptrStr(model.NewId() + "@example.com"), }, false) - user2, err := GetUserByUsername(username2) + user2, err := a.GetUserByUsername(username2) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -2165,13 +2171,13 @@ func TestImportImportPost(t *testing.T) { username2, }, } - if err := ImportPost(data, false); err != nil { + if err := a.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 5, team.Id) // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(channel.Id, flagsTime); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, flagsTime); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2189,18 +2195,19 @@ func TestImportImportPost(t *testing.T) { } func TestImportImportDirectChannel(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() // Check how many channels are in the database. var directChannelCount int64 - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT); r.Err == nil { directChannelCount = r.Data.(int64) } else { t.Fatalf("Failed to get direct channel count.") } var groupChannelCount int64 - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP); r.Err == nil { + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP); r.Err == nil { groupChannelCount = r.Data.(int64) } else { t.Fatalf("Failed to get group channel count.") @@ -2213,7 +2220,7 @@ func TestImportImportDirectChannel(t *testing.T) { }, Header: ptrStr("Channel Header"), } - if err := ImportDirectChannel(&data, true); err == nil { + if err := a.ImportDirectChannel(&data, true); err == nil { t.Fatalf("Expected error due to invalid name.") } @@ -2226,7 +2233,7 @@ func TestImportImportDirectChannel(t *testing.T) { model.NewId(), model.NewId(), } - if err := ImportDirectChannel(&data, true); err != nil { + if err := a.ImportDirectChannel(&data, true); err != nil { t.Fatalf("Expected success as cannot validate existance of channel members in dry run mode.") } @@ -2240,7 +2247,7 @@ func TestImportImportDirectChannel(t *testing.T) { model.NewId(), model.NewId(), } - if err := ImportDirectChannel(&data, true); err != nil { + if err := a.ImportDirectChannel(&data, true); err != nil { t.Fatalf("Expected success as cannot validate existance of channel members in dry run mode.") } @@ -2252,7 +2259,7 @@ func TestImportImportDirectChannel(t *testing.T) { data.Members = &[]string{ model.NewId(), } - if err := ImportDirectChannel(&data, false); err == nil { + if err := a.ImportDirectChannel(&data, false); err == nil { t.Fatalf("Expected error due to invalid member (apply mode).") } @@ -2265,7 +2272,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser.Username, th.BasicUser2.Username, } - if err := ImportDirectChannel(&data, false); err != nil { + if err := a.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } @@ -2274,7 +2281,7 @@ func TestImportImportDirectChannel(t *testing.T) { AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) // Do the same DIRECT channel again. - if err := ImportDirectChannel(&data, false); err != nil { + if err := a.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } @@ -2284,7 +2291,7 @@ func TestImportImportDirectChannel(t *testing.T) { // Update the channel's HEADER data.Header = ptrStr("New Channel Header 2") - if err := ImportDirectChannel(&data, false); err != nil { + if err := a.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } @@ -2293,7 +2300,7 @@ func TestImportImportDirectChannel(t *testing.T) { AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) // Get the channel to check that the header was updated. - if channel, err := createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := a.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { if channel.Header != *data.Header { @@ -2309,7 +2316,7 @@ func TestImportImportDirectChannel(t *testing.T) { user3.Username, model.NewId(), } - if err := ImportDirectChannel(&data, false); err == nil { + if err := a.ImportDirectChannel(&data, false); err == nil { t.Fatalf("Should have failed due to invalid member in list.") } @@ -2323,7 +2330,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser2.Username, user3.Username, } - if err := ImportDirectChannel(&data, false); err != nil { + if err := a.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } @@ -2332,7 +2339,7 @@ func TestImportImportDirectChannel(t *testing.T) { AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount+1) // Do the same DIRECT channel again. - if err := ImportDirectChannel(&data, false); err != nil { + if err := a.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } @@ -2342,7 +2349,7 @@ func TestImportImportDirectChannel(t *testing.T) { // Update the channel's HEADER data.Header = ptrStr("New Channel Header 3") - if err := ImportDirectChannel(&data, false); err != nil { + if err := a.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } @@ -2356,7 +2363,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser2.Id, user3.Id, } - if channel, err := createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := a.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { if channel.Header != *data.Header { @@ -2373,11 +2380,11 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser.Username, th.BasicUser2.Username, } - if err := ImportDirectChannel(&data, false); err != nil { + if err := a.ImportDirectChannel(&data, false); err != nil { t.Fatal(err) } - if channel, err := createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := a.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { checkPreference(t, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") @@ -2386,7 +2393,8 @@ func TestImportImportDirectChannel(t *testing.T) { } func AssertChannelCount(t *testing.T, channelType string, expectedCount int64) { - if r := <-Srv.Store.Channel().AnalyticsTypeCount("", channelType); r.Err == nil { + a := Global() + if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", channelType); r.Err == nil { count := r.Data.(int64) if count != expectedCount { debug.PrintStack() @@ -2399,7 +2407,8 @@ func AssertChannelCount(t *testing.T, channelType string, expectedCount int64) { } func TestImportImportDirectPost(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() // Create the DIRECT channel. channelData := DirectChannelImportData{ @@ -2408,13 +2417,13 @@ func TestImportImportDirectPost(t *testing.T) { th.BasicUser2.Username, }, } - if err := ImportDirectChannel(&channelData, false); err != nil { + if err := a.ImportDirectChannel(&channelData, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } // Get the channel. var directChannel *model.Channel - if channel, err := createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := a.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { directChannel = channel @@ -2422,7 +2431,7 @@ func TestImportImportDirectPost(t *testing.T) { // Get the number of posts in the system. var initialPostCount int64 - if result := <-Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { + if result := <-a.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { t.Fatal(result.Err) } else { initialPostCount = result.Data.(int64) @@ -2437,7 +2446,7 @@ func TestImportImportDirectPost(t *testing.T) { User: ptrStr(th.BasicUser.Username), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, true); err == nil { + if err := a.ImportDirectPost(data, true); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, "") @@ -2452,7 +2461,7 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, true); err != nil { + if err := a.ImportDirectPost(data, true); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 0, "") @@ -2467,7 +2476,7 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, false); err == nil { + if err := a.ImportDirectPost(data, false); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, "") @@ -2482,13 +2491,13 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } AssertAllPostsCount(t, initialPostCount, 1, "") // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2502,13 +2511,13 @@ func TestImportImportDirectPost(t *testing.T) { } // Import the post again. - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 1, "") // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2523,14 +2532,14 @@ func TestImportImportDirectPost(t *testing.T) { // Save the post with a different time. data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 2, "") // Save the post with a different message. data.Message = ptrStr("Message 2") - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 3, "") @@ -2538,12 +2547,12 @@ func TestImportImportDirectPost(t *testing.T) { // Test with hashtags data.Message = ptrStr("Message 2 #hashtagmashupcity") data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 4, "") - if result := <-Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2574,12 +2583,12 @@ func TestImportImportDirectPost(t *testing.T) { CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2602,7 +2611,7 @@ func TestImportImportDirectPost(t *testing.T) { user3.Username, }, } - if err := ImportDirectChannel(&channelData, false); err != nil { + if err := a.ImportDirectChannel(&channelData, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } @@ -2613,14 +2622,14 @@ func TestImportImportDirectPost(t *testing.T) { th.BasicUser2.Id, user3.Id, } - if channel, err := createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := a.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { groupChannel = channel } // Get the number of posts in the system. - if result := <-Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { + if result := <-a.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { t.Fatal(result.Err) } else { initialPostCount = result.Data.(int64) @@ -2636,7 +2645,7 @@ func TestImportImportDirectPost(t *testing.T) { User: ptrStr(th.BasicUser.Username), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, true); err == nil { + if err := a.ImportDirectPost(data, true); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, "") @@ -2652,7 +2661,7 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, true); err != nil { + if err := a.ImportDirectPost(data, true); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 0, "") @@ -2669,7 +2678,7 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, false); err == nil { + if err := a.ImportDirectPost(data, false); err == nil { t.Fatalf("Expected error.") } AssertAllPostsCount(t, initialPostCount, 0, "") @@ -2685,13 +2694,13 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } AssertAllPostsCount(t, initialPostCount, 1, "") // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2705,13 +2714,13 @@ func TestImportImportDirectPost(t *testing.T) { } // Import the post again. - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 1, "") // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2726,14 +2735,14 @@ func TestImportImportDirectPost(t *testing.T) { // Save the post with a different time. data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 2, "") // Save the post with a different message. data.Message = ptrStr("Message 2") - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 3, "") @@ -2741,12 +2750,12 @@ func TestImportImportDirectPost(t *testing.T) { // Test with hashtags data.Message = ptrStr("Message 2 #hashtagmashupcity") data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } AssertAllPostsCount(t, initialPostCount, 4, "") - if result := <-Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2778,12 +2787,12 @@ func TestImportImportDirectPost(t *testing.T) { CreateAt: ptrInt64(model.GetMillis()), } - if err := ImportDirectPost(data, false); err != nil { + if err := a.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } // Check the post values. - if result := <-Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2797,56 +2806,58 @@ func TestImportImportDirectPost(t *testing.T) { } func TestImportImportLine(t *testing.T) { - _ = Setup() + a := Global() + _ = a.Setup() // Try import line with an invalid type. line := LineImportData{ Type: "gibberish", } - if err := ImportLine(line, false); err == nil { + if err := a.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with invalid type.") } // Try import line with team type but nil team. line.Type = "team" - if err := ImportLine(line, false); err == nil { + if err := a.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line of type team with a nil team.") } // Try import line with channel type but nil channel. line.Type = "channel" - if err := ImportLine(line, false); err == nil { + if err := a.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type channel with a nil channel.") } // Try import line with user type but nil user. line.Type = "user" - if err := ImportLine(line, false); err == nil { + if err := a.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type uesr with a nil user.") } // Try import line with post type but nil post. line.Type = "post" - if err := ImportLine(line, false); err == nil { + if err := a.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type post with a nil post.") } // Try import line with direct_channel type but nil direct_channel. line.Type = "direct_channel" - if err := ImportLine(line, false); err == nil { + if err := a.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type direct_channel with a nil direct_channel.") } // Try import line with direct_post type but nil direct_post. line.Type = "direct_post" - if err := ImportLine(line, false); err == nil { + if err := a.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type direct_post with a nil direct_post.") } } func TestImportBulkImport(t *testing.T) { - _ = Setup() + a := Global() + _ = a.Setup() teamName := model.NewId() channelName := model.NewId() @@ -2867,13 +2878,13 @@ func TestImportBulkImport(t *testing.T) { {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `"], "user": "` + username + `", "message": "Hello Direct Channel", "create_at": 123456789013}} {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `", "` + username3 + `"], "user": "` + username + `", "message": "Hello Group Channel", "create_at": 123456789014}}` - if err, line := BulkImport(strings.NewReader(data1), false, 2); err != nil || line != 0 { + if err, line := a.BulkImport(strings.NewReader(data1), false, 2); err != nil || line != 0 { t.Fatalf("BulkImport should have succeeded: %v, %v", err.Error(), line) } // Run bulk import using a string that contains a line with invalid json. data2 := `{"type": "version", "version": 1` - if err, line := BulkImport(strings.NewReader(data2), false, 2); err == nil || line != 1 { + if err, line := a.BulkImport(strings.NewReader(data2), false, 2); err == nil || line != 1 { t.Fatalf("Should have failed due to invalid JSON on line 1.") } @@ -2882,13 +2893,14 @@ func TestImportBulkImport(t *testing.T) { {"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}} {"type": "user", "user": {"username": "kufjgnkxkrhhfgbrip6qxkfsaa", "email": "kufjgnkxkrhhfgbrip6qxkfsaa@example.com"}} {"type": "user", "user": {"username": "bwshaim6qnc2ne7oqkd5b2s2rq", "email": "bwshaim6qnc2ne7oqkd5b2s2rq@example.com", "teams": [{"name": "` + teamName + `", "channels": [{"name": "` + channelName + `"}]}]}}` - if err, line := BulkImport(strings.NewReader(data3), false, 2); err == nil || line != 1 { + if err, line := a.BulkImport(strings.NewReader(data3), false, 2); err == nil || line != 1 { t.Fatalf("Should have failed due to missing version line on line 1.") } } func TestImportProcessImportDataFileVersionLine(t *testing.T) { - _ = Setup() + a := Global() + _ = a.Setup() data := LineImportData{ Type: "version", diff --git a/app/job.go b/app/job.go index 005324999..88757b161 100644 --- a/app/job.go +++ b/app/job.go @@ -8,32 +8,32 @@ import ( "github.com/mattermost/platform/model" ) -func GetJob(id string) (*model.Job, *model.AppError) { - if result := <-Srv.Store.Job().Get(id); result.Err != nil { +func (a *App) GetJob(id string) (*model.Job, *model.AppError) { + if result := <-a.Srv.Store.Job().Get(id); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Job), nil } } -func GetJobsPage(page int, perPage int) ([]*model.Job, *model.AppError) { - return GetJobs(page*perPage, perPage) +func (a *App) GetJobsPage(page int, perPage int) ([]*model.Job, *model.AppError) { + return a.GetJobs(page*perPage, perPage) } -func GetJobs(offset int, limit int) ([]*model.Job, *model.AppError) { - if result := <-Srv.Store.Job().GetAllPage(offset, limit); result.Err != nil { +func (a *App) GetJobs(offset int, limit int) ([]*model.Job, *model.AppError) { + if result := <-a.Srv.Store.Job().GetAllPage(offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Job), nil } } -func GetJobsByTypePage(jobType string, page int, perPage int) ([]*model.Job, *model.AppError) { - return GetJobsByType(jobType, page*perPage, perPage) +func (a *App) GetJobsByTypePage(jobType string, page int, perPage int) ([]*model.Job, *model.AppError) { + return a.GetJobsByType(jobType, page*perPage, perPage) } -func GetJobsByType(jobType string, offset int, limit int) ([]*model.Job, *model.AppError) { - if result := <-Srv.Store.Job().GetAllByTypePage(jobType, offset, limit); result.Err != nil { +func (a *App) GetJobsByType(jobType string, offset int, limit int) ([]*model.Job, *model.AppError) { + if result := <-a.Srv.Store.Job().GetAllByTypePage(jobType, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Job), nil diff --git a/app/job_test.go b/app/job_test.go index 8f068901a..09208ec21 100644 --- a/app/job_test.go +++ b/app/job_test.go @@ -11,19 +11,20 @@ import ( ) func TestGetJob(t *testing.T) { - Setup() + a := Global() + a.Setup() status := &model.Job{ Id: model.NewId(), Status: model.NewId(), } - if result := <-Srv.Store.Job().Save(status); result.Err != nil { + if result := <-a.Srv.Store.Job().Save(status); result.Err != nil { t.Fatal(result.Err) } - defer Srv.Store.Job().Delete(status.Id) + defer a.Srv.Store.Job().Delete(status.Id) - if received, err := GetJob(status.Id); err != nil { + if received, err := a.GetJob(status.Id); err != nil { t.Fatal(err) } else if received.Id != status.Id || received.Status != status.Status { t.Fatal("inccorrect job status received") @@ -31,34 +32,35 @@ func TestGetJob(t *testing.T) { } func TestGetJobByType(t *testing.T) { - Setup() + a := Global() + a.Setup() jobType := model.NewId() statuses := []*model.Job{ { - Id: model.NewId(), - Type: jobType, + Id: model.NewId(), + Type: jobType, CreateAt: 1000, }, { - Id: model.NewId(), - Type: jobType, + Id: model.NewId(), + Type: jobType, CreateAt: 999, }, { - Id: model.NewId(), - Type: jobType, + Id: model.NewId(), + Type: jobType, CreateAt: 1001, }, } for _, status := range statuses { - store.Must(Srv.Store.Job().Save(status)) - defer Srv.Store.Job().Delete(status.Id) + store.Must(a.Srv.Store.Job().Save(status)) + defer a.Srv.Store.Job().Delete(status.Id) } - if received, err := GetJobsByType(jobType, 0, 2); err != nil { + if received, err := a.GetJobsByType(jobType, 0, 2); err != nil { t.Fatal(err) } else if len(received) != 2 { t.Fatal("received wrong number of statuses") @@ -68,7 +70,7 @@ func TestGetJobByType(t *testing.T) { t.Fatal("should've received second newest job second") } - if received, err := GetJobsByType(jobType, 2, 2); err != nil { + if received, err := a.GetJobsByType(jobType, 2, 2); err != nil { t.Fatal(err) } else if len(received) != 1 { t.Fatal("received wrong number of statuses") diff --git a/app/ldap.go b/app/ldap.go index e3c90b263..8f852114c 100644 --- a/app/ldap.go +++ b/app/ldap.go @@ -38,17 +38,17 @@ func TestLdap() *model.AppError { return nil } -func SwitchEmailToLdap(email, password, code, ldapId, ldapPassword string) (string, *model.AppError) { - user, err := GetUserByEmail(email) +func (a *App) SwitchEmailToLdap(email, password, code, ldapId, ldapPassword string) (string, *model.AppError) { + user, err := a.GetUserByEmail(email) if err != nil { return "", err } - if err := CheckPasswordAndAllCriteria(user, password, code); err != nil { + if err := a.CheckPasswordAndAllCriteria(user, password, code); err != nil { return "", err } - if err := RevokeAllSessions(user.Id); err != nil { + if err := a.RevokeAllSessions(user.Id); err != nil { return "", err } @@ -70,8 +70,8 @@ func SwitchEmailToLdap(email, password, code, ldapId, ldapPassword string) (stri return "/login?extra=signin_change", nil } -func SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) { - user, err := GetUserByEmail(email) +func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) { + user, err := a.GetUserByEmail(email) if err != nil { return "", err } @@ -93,11 +93,11 @@ func SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, * return "", err } - if err := UpdatePassword(user, newPassword); err != nil { + if err := a.UpdatePassword(user, newPassword); err != nil { return "", err } - if err := RevokeAllSessions(user.Id); err != nil { + if err := a.RevokeAllSessions(user.Id); err != nil { return "", err } diff --git a/app/license.go b/app/license.go index 8cb76fd6e..da3f6d8d6 100644 --- a/app/license.go +++ b/app/license.go @@ -12,11 +12,11 @@ import ( "github.com/mattermost/platform/utils" ) -func LoadLicense() { +func (a *App) LoadLicense() { utils.RemoveLicense() licenseId := "" - if result := <-Srv.Store.System().Get(); result.Err == nil { + if result := <-a.Srv.Store.System().Get(); result.Err == nil { props := result.Data.(model.StringMap) licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID] } @@ -26,7 +26,7 @@ func LoadLicense() { license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk() if license != nil { - if _, err := SaveLicense(licenseBytes); err != nil { + if _, err := a.SaveLicense(licenseBytes); err != nil { l4g.Info("Failed to save license key loaded from disk err=%v", err.Error()) } else { licenseId = license.Id @@ -34,7 +34,7 @@ func LoadLicense() { } } - if result := <-Srv.Store.License().Get(licenseId); result.Err == nil { + if result := <-a.Srv.Store.License().Get(licenseId); result.Err == nil { record := result.Data.(*model.LicenseRecord) utils.LoadLicense([]byte(record.Bytes)) l4g.Info("License key valid unlocking enterprise features.") @@ -43,13 +43,13 @@ func LoadLicense() { } } -func SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { +func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { var license *model.License if success, licenseStr := utils.ValidateLicense(licenseBytes); success { license = model.LicenseFromJson(strings.NewReader(licenseStr)) - if result := <-Srv.Store.User().AnalyticsUniqueUserCount(""); result.Err != nil { + if result := <-a.Srv.Store.User().AnalyticsUniqueUserCount(""); result.Err != nil { return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, result.Err.Error(), http.StatusBadRequest) } else { uniqueUserCount := result.Data.(int64) @@ -66,20 +66,20 @@ func SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { record := &model.LicenseRecord{} record.Id = license.Id record.Bytes = string(licenseBytes) - rchan := Srv.Store.License().Save(record) + rchan := a.Srv.Store.License().Save(record) if result := <-rchan; result.Err != nil { - RemoveLicense() + a.RemoveLicense() return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "err="+result.Err.Error(), http.StatusInternalServerError) } sysVar := &model.System{} sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Value = license.Id - schan := Srv.Store.System().SaveOrUpdate(sysVar) + schan := a.Srv.Store.System().SaveOrUpdate(sysVar) if result := <-schan; result.Err != nil { - RemoveLicense() + a.RemoveLicense() return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError) } } else { @@ -87,26 +87,26 @@ func SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { } ReloadConfig() - InvalidateAllCaches() + a.InvalidateAllCaches() return license, nil } -func RemoveLicense() *model.AppError { +func (a *App) RemoveLicense() *model.AppError { utils.RemoveLicense() sysVar := &model.System{} sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Value = "" - if result := <-Srv.Store.System().SaveOrUpdate(sysVar); result.Err != nil { + if result := <-a.Srv.Store.System().SaveOrUpdate(sysVar); result.Err != nil { utils.RemoveLicense() return result.Err } ReloadConfig() - InvalidateAllCaches() + a.InvalidateAllCaches() return nil } diff --git a/app/license_test.go b/app/license_test.go index 07805992a..178954bc9 100644 --- a/app/license_test.go +++ b/app/license_test.go @@ -5,33 +5,37 @@ package app import ( //"github.com/mattermost/platform/model" - "github.com/mattermost/platform/utils" "testing" + + "github.com/mattermost/platform/utils" ) func TestLoadLicense(t *testing.T) { - Setup() + a := Global() + a.Setup() - LoadLicense() + a.LoadLicense() if utils.IsLicensed() { t.Fatal("shouldn't have a valid license") } } func TestSaveLicense(t *testing.T) { - Setup() + a := Global() + a.Setup() b1 := []byte("junk") - if _, err := SaveLicense(b1); err == nil { + if _, err := a.SaveLicense(b1); err == nil { t.Fatal("shouldn't have saved license") } } func TestRemoveLicense(t *testing.T) { - Setup() + a := Global() + a.Setup() - if err := RemoveLicense(); err != nil { + if err := a.RemoveLicense(); err != nil { t.Fatal("should have removed license") } } diff --git a/app/login.go b/app/login.go index 63f713cc8..b86df41bd 100644 --- a/app/login.go +++ b/app/login.go @@ -15,7 +15,7 @@ import ( "github.com/mssola/user_agent" ) -func AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId string, ldapOnly bool) (*model.User, *model.AppError) { +func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId string, ldapOnly bool) (*model.User, *model.AppError) { if len(password) == 0 { err := model.NewAppError("AuthenticateUserForLogin", "api.user.login.blank_pwd.app_error", nil, "", http.StatusBadRequest) return nil, err @@ -25,7 +25,7 @@ func AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId string, var err *model.AppError if len(id) != 0 { - if user, err = GetUser(id); err != nil { + if user, err = a.GetUser(id); err != nil { err.StatusCode = http.StatusBadRequest if einterfaces.GetMetricsInterface() != nil { einterfaces.GetMetricsInterface().IncrementLoginFail() @@ -33,7 +33,7 @@ func AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId string, return nil, err } } else { - if user, err = GetUserForLogin(loginId, ldapOnly); err != nil { + if user, err = a.GetUserForLogin(loginId, ldapOnly); err != nil { if einterfaces.GetMetricsInterface() != nil { einterfaces.GetMetricsInterface().IncrementLoginFail() } @@ -42,7 +42,7 @@ func AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId string, } // and then authenticate them - if user, err = authenticateUser(user, password, mfaToken); err != nil { + if user, err = a.authenticateUser(user, password, mfaToken); err != nil { if einterfaces.GetMetricsInterface() != nil { einterfaces.GetMetricsInterface().IncrementLoginFail() } @@ -56,7 +56,7 @@ func AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId string, return user, nil } -func DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) (*model.Session, *model.AppError) { +func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) (*model.Session, *model.AppError) { session := &model.Session{UserId: user.Id, Roles: user.GetRawRoles(), DeviceId: deviceId, IsOAuth: false} maxAge := *utils.Cfg.ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24 @@ -65,7 +65,7 @@ func DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthMobileInDays) // A special case where we logout of all other sessions with the same Id - if err := RevokeSessionsForDeviceId(user.Id, deviceId, ""); err != nil { + if err := a.RevokeSessionsForDeviceId(user.Id, deviceId, ""); err != nil { err.StatusCode = http.StatusInternalServerError return nil, err } @@ -103,7 +103,7 @@ func DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion)) var err *model.AppError - if session, err = CreateSession(session); err != nil { + if session, err = a.CreateSession(session); err != nil { err.StatusCode = http.StatusInternalServerError return nil, err } diff --git a/app/notification.go b/app/notification.go index f488870f9..9529bfe91 100644 --- a/app/notification.go +++ b/app/notification.go @@ -25,13 +25,13 @@ import ( "github.com/nicksnyder/go-i18n/i18n" ) -func SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList) ([]string, *model.AppError) { - pchan := Srv.Store.User().GetAllProfilesInChannel(channel.Id, true) - cmnchan := Srv.Store.Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true) +func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *model.Channel, sender *model.User, parentPostList *model.PostList) ([]string, *model.AppError) { + pchan := a.Srv.Store.User().GetAllProfilesInChannel(channel.Id, true) + cmnchan := a.Srv.Store.Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true) var fchan store.StoreChannel if len(post.FileIds) != 0 { - fchan = Srv.Store.FileInfo().GetForPost(post.Id, true, true) + fchan = a.Srv.Store.FileInfo().GetForPost(post.Id, true, true) } var profileMap map[string]*model.User @@ -92,7 +92,7 @@ func SendNotifications(post *model.Post, team *model.Team, channel *model.Channe } if len(potentialOtherMentions) > 0 { - if result := <-Srv.Store.User().GetProfilesByUsernames(potentialOtherMentions, team.Id); result.Err == nil { + if result := <-a.Srv.Store.User().GetProfilesByUsernames(potentialOtherMentions, team.Id); result.Err == nil { outOfChannelMentions := result.Data.([]*model.User) if channel.Type != model.CHANNEL_GROUP { go sendOutOfChannelMentions(sender, post, team.Id, outOfChannelMentions) @@ -114,7 +114,7 @@ func SendNotifications(post *model.Post, team *model.Team, channel *model.Channe mentionedUsersList := make([]string, 0, len(mentionedUserIds)) for id := range mentionedUserIds { mentionedUsersList = append(mentionedUsersList, id) - updateMentionChans = append(updateMentionChans, Srv.Store.Channel().IncrementMentionCount(post.ChannelId, id)) + updateMentionChans = append(updateMentionChans, a.Srv.Store.Channel().IncrementMentionCount(post.ChannelId, id)) } senderName := "" @@ -166,7 +166,7 @@ func SendNotifications(post *model.Post, team *model.Team, channel *model.Channe var status *model.Status var err *model.AppError - if status, err = GetStatus(id); err != nil { + if status, err = a.GetStatus(id); err != nil { status = &model.Status{ UserId: id, Status: model.STATUS_OFFLINE, @@ -177,7 +177,7 @@ func SendNotifications(post *model.Post, team *model.Team, channel *model.Channe } if userAllowsEmails && status.Status != model.STATUS_ONLINE && profileMap[id].DeleteAt == 0 { - sendNotificationEmail(post, profileMap[id], channel, team, senderName, sender) + a.sendNotificationEmail(post, profileMap[id], channel, team, senderName, sender) } } } @@ -245,12 +245,12 @@ func SendNotifications(post *model.Post, team *model.Team, channel *model.Channe for _, id := range mentionedUsersList { var status *model.Status var err *model.AppError - if status, err = GetStatus(id); err != nil { + if status, err = a.GetStatus(id); err != nil { status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} } if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], true, status, post) { - sendPushNotification(post, profileMap[id], channel, senderName, channelName, true) + a.sendPushNotification(post, profileMap[id], channel, senderName, channelName, true) } } @@ -258,12 +258,12 @@ func SendNotifications(post *model.Post, team *model.Team, channel *model.Channe if _, ok := mentionedUserIds[id]; !ok { var status *model.Status var err *model.AppError - if status, err = GetStatus(id); err != nil { + if status, err = a.GetStatus(id); err != nil { status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""} } if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], false, status, post) { - sendPushNotification(post, profileMap[id], channel, senderName, channelName, false) + a.sendPushNotification(post, profileMap[id], channel, senderName, channelName, false) } } } @@ -303,9 +303,9 @@ func SendNotifications(post *model.Post, team *model.Team, channel *model.Channe return mentionedUsersList, nil } -func sendNotificationEmail(post *model.Post, user *model.User, channel *model.Channel, team *model.Team, senderName string, sender *model.User) *model.AppError { +func (a *App) sendNotificationEmail(post *model.Post, user *model.User, channel *model.Channel, team *model.Team, senderName string, sender *model.User) *model.AppError { if channel.IsGroupOrDirect() { - if result := <-Srv.Store.Team().GetTeamsByUserId(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Team().GetTeamsByUserId(user.Id); result.Err != nil { return result.Err } else { // if the recipient isn't in the current user's team, just pick one @@ -329,7 +329,7 @@ func sendNotificationEmail(post *model.Post, user *model.User, channel *model.Ch } if *utils.Cfg.EmailSettings.EnableEmailBatching { var sendBatched bool - if result := <-Srv.Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); result.Err != nil { + if result := <-a.Srv.Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); result.Err != nil { // if the call fails, assume that the interval has not been explicitly set and batch the notifications sendBatched = true } else { @@ -361,7 +361,7 @@ func sendNotificationEmail(post *model.Post, user *model.User, channel *model.Ch } teamURL := utils.GetSiteURL() + "/" + team.Name - var bodyText = getNotificationEmailBody(user, post, channel, senderName, team.Name, teamURL, emailNotificationContentsType, translateFunc) + var bodyText = a.getNotificationEmailBody(user, post, channel, senderName, team.Name, teamURL, emailNotificationContentsType, translateFunc) go func() { if err := utils.SendMail(user.Email, html.UnescapeString(subjectText), bodyText); err != nil { @@ -409,12 +409,12 @@ func getNotificationEmailSubject(post *model.Post, translateFunc i18n.TranslateF /** * Computes the email body for notification messages */ -func getNotificationEmailBody(recipient *model.User, post *model.Post, channel *model.Channel, senderName string, teamName string, teamURL string, emailNotificationContentsType string, translateFunc i18n.TranslateFunc) string { +func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post, channel *model.Channel, senderName string, teamName string, teamURL string, emailNotificationContentsType string, translateFunc i18n.TranslateFunc) string { // only include message contents in notification email if email notification contents type is set to full var bodyPage *utils.HTMLTemplate if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { bodyPage = utils.NewHTMLTemplate("post_body_full", recipient.Locale) - bodyPage.Props["PostMessage"] = GetMessageForNotification(post, translateFunc) + bodyPage.Props["PostMessage"] = a.GetMessageForNotification(post, translateFunc) } else { bodyPage = utils.NewHTMLTemplate("post_body_generic", recipient.Locale) } @@ -519,14 +519,14 @@ func getFormattedPostTime(post *model.Post, translateFunc i18n.TranslateFunc) fo } } -func GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string { +func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string { if len(strings.TrimSpace(post.Message)) != 0 || len(post.FileIds) == 0 { return post.Message } // extract the filenames from their paths and determine what type of files are attached var infos []*model.FileInfo - if result := <-Srv.Store.FileInfo().GetForPost(post.Id, true, true); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().GetForPost(post.Id, true, true); result.Err != nil { l4g.Warn(utils.T("api.post.get_message_for_notification.get_files.error"), post.Id, result.Err) } else { infos = result.Data.([]*model.FileInfo) @@ -554,8 +554,8 @@ func GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFun } } -func sendPushNotification(post *model.Post, user *model.User, channel *model.Channel, senderName, channelName string, wasMentioned bool) *model.AppError { - sessions, err := getMobileAppSessions(user.Id) +func (a *App) sendPushNotification(post *model.Post, user *model.User, channel *model.Channel, senderName, channelName string, wasMentioned bool) *model.AppError { + sessions, err := a.getMobileAppSessions(user.Id) if err != nil { return err } @@ -567,7 +567,7 @@ func sendPushNotification(post *model.Post, user *model.User, channel *model.Cha userLocale := utils.GetUserTranslations(user.Locale) msg := model.PushNotification{} - if badge := <-Srv.Store.User().GetUnreadCount(user.Id); badge.Err != nil { + if badge := <-a.Srv.Store.User().GetUnreadCount(user.Id); badge.Err != nil { msg.Badge = 1 l4g.Error(utils.T("store.sql_user.get_unread_count.app_error"), user.Id, badge.Err) } else { @@ -639,7 +639,7 @@ func sendPushNotification(post *model.Post, user *model.User, channel *model.Cha l4g.Debug("Sending push notification to device %v for user %v with msg of '%v'", tmpMessage.DeviceId, user.Id, msg.Message) - go sendToPushProxy(tmpMessage, session) + go a.sendToPushProxy(tmpMessage, session) if einterfaces.GetMetricsInterface() != nil { einterfaces.GetMetricsInterface().IncrementPostSentPush() @@ -649,8 +649,8 @@ func sendPushNotification(post *model.Post, user *model.User, channel *model.Cha return nil } -func ClearPushNotification(userId string, channelId string) *model.AppError { - sessions, err := getMobileAppSessions(userId) +func (a *App) ClearPushNotification(userId string, channelId string) *model.AppError { + sessions, err := a.getMobileAppSessions(userId) if err != nil { return err } @@ -659,7 +659,7 @@ func ClearPushNotification(userId string, channelId string) *model.AppError { msg.Type = model.PUSH_TYPE_CLEAR msg.ChannelId = channelId msg.ContentAvailable = 0 - if badge := <-Srv.Store.User().GetUnreadCount(userId); badge.Err != nil { + if badge := <-a.Srv.Store.User().GetUnreadCount(userId); badge.Err != nil { msg.Badge = 0 l4g.Error(utils.T("store.sql_user.get_unread_count.app_error"), userId, badge.Err) } else { @@ -671,13 +671,13 @@ func ClearPushNotification(userId string, channelId string) *model.AppError { for _, session := range sessions { tmpMessage := *model.PushNotificationFromJson(strings.NewReader(msg.ToJson())) tmpMessage.SetDeviceIdAndPlatform(session.DeviceId) - go sendToPushProxy(tmpMessage, session) + go a.sendToPushProxy(tmpMessage, session) } return nil } -func sendToPushProxy(msg model.PushNotification, session *model.Session) { +func (a *App) sendToPushProxy(msg model.PushNotification, session *model.Session) { msg.ServerId = utils.CfgDiagnosticId request, _ := http.NewRequest("POST", *utils.Cfg.EmailSettings.PushNotificationServer+model.API_URL_SUFFIX_V1+"/send_push", strings.NewReader(msg.ToJson())) @@ -693,7 +693,7 @@ func sendToPushProxy(msg model.PushNotification, session *model.Session) { if pushResponse[model.PUSH_STATUS] == model.PUSH_STATUS_REMOVE { l4g.Info("Device was reported as removed for UserId=%v SessionId=%v removing push for this session", session.UserId, session.Id) - AttachDeviceId(session.Id, "", session.ExpiresAt) + a.AttachDeviceId(session.Id, "", session.ExpiresAt) ClearSessionCacheForUser(session.UserId) } @@ -703,8 +703,8 @@ func sendToPushProxy(msg model.PushNotification, session *model.Session) { } } -func getMobileAppSessions(userId string) ([]*model.Session, *model.AppError) { - if result := <-Srv.Store.Session().GetSessionsWithActiveDeviceIds(userId); result.Err != nil { +func (a *App) getMobileAppSessions(userId string) ([]*model.Session, *model.AppError) { + if result := <-a.Srv.Store.Session().GetSessionsWithActiveDeviceIds(userId); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Session), nil diff --git a/app/notification_test.go b/app/notification_test.go index e0c1a54e6..f4b8bad61 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -12,11 +12,12 @@ import ( ) func TestSendNotifications(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() - AddUserToChannel(th.BasicUser2, th.BasicChannel) + a.AddUserToChannel(th.BasicUser2, th.BasicChannel) - post1, err := CreatePostMissingChannel(&model.Post{ + post1, err := a.CreatePostMissingChannel(&model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@" + th.BasicUser2.Username, @@ -26,7 +27,7 @@ func TestSendNotifications(t *testing.T) { t.Fatal(err) } - mentions, err := SendNotifications(post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil) + mentions, err := a.SendNotifications(post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil) if err != nil { t.Fatal(err) } else if mentions == nil { @@ -37,12 +38,12 @@ func TestSendNotifications(t *testing.T) { t.Fatal("user should have been mentioned") } - dm, err := CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + dm, err := a.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) if err != nil { t.Fatal(err) } - post2, err := CreatePostMissingChannel(&model.Post{ + post2, err := a.CreatePostMissingChannel(&model.Post{ UserId: th.BasicUser.Id, ChannelId: dm.Id, Message: "dm message", @@ -52,15 +53,15 @@ func TestSendNotifications(t *testing.T) { t.Fatal(err) } - _, err = SendNotifications(post2, th.BasicTeam, dm, th.BasicUser, nil) + _, err = a.SendNotifications(post2, th.BasicTeam, dm, th.BasicUser, nil) if err != nil { t.Fatal(err) } - UpdateActive(th.BasicUser2, false) - InvalidateAllCaches() + a.UpdateActive(th.BasicUser2, false) + a.InvalidateAllCaches() - post3, err := CreatePostMissingChannel(&model.Post{ + post3, err := a.CreatePostMissingChannel(&model.Post{ UserId: th.BasicUser.Id, ChannelId: dm.Id, Message: "dm message", @@ -70,7 +71,7 @@ func TestSendNotifications(t *testing.T) { t.Fatal(err) } - _, err = SendNotifications(post3, th.BasicTeam, dm, th.BasicUser, nil) + _, err = a.SendNotifications(post3, th.BasicTeam, dm, th.BasicUser, nil) if err != nil { t.Fatal(err) } @@ -408,7 +409,8 @@ func TestRemoveCodeFromMessage(t *testing.T) { } func TestGetMentionKeywords(t *testing.T) { - Setup() + a := Global() + a.Setup() // user with username or custom mentions enabled user1 := &model.User{ Id: model.NewId(), @@ -833,7 +835,8 @@ func TestDoesStatusAllowPushNotification(t *testing.T) { } func TestGetDirectMessageNotificationEmailSubject(t *testing.T) { - Setup() + a := Global() + a.Setup() expectedPrefix := "[http://localhost:8065] New Direct Message from sender on" post := &model.Post{ CreateAt: 1501804801000, @@ -846,7 +849,8 @@ func TestGetDirectMessageNotificationEmailSubject(t *testing.T) { } func TestGetNotificationEmailSubject(t *testing.T) { - Setup() + a := Global() + a.Setup() expectedPrefix := "[http://localhost:8065] Notification in team on" post := &model.Post{ CreateAt: 1501804801000, @@ -859,7 +863,8 @@ func TestGetNotificationEmailSubject(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -874,7 +879,7 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification.") { t.Fatal("Expected email text 'You have a new notification. Got " + body) } @@ -893,7 +898,8 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -908,7 +914,7 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification.") { t.Fatal("Expected email text 'You have a new notification. Got " + body) } @@ -927,7 +933,8 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -942,7 +949,7 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification.") { t.Fatal("Expected email text 'You have a new notification. Got " + body) } @@ -961,7 +968,8 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -976,7 +984,7 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new direct message.") { t.Fatal("Expected email text 'You have a new direct message. Got " + body) } @@ -993,7 +1001,8 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { // from here func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1008,7 +1017,7 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification from "+senderName) { t.Fatal("Expected email text 'You have a new notification from " + senderName + "'. Got " + body) } @@ -1024,7 +1033,8 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) } func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1039,7 +1049,7 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification from "+senderName) { t.Fatal("Expected email text 'You have a new notification from " + senderName + "'. Got " + body) } @@ -1055,7 +1065,8 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { } func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1070,7 +1081,7 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification from "+senderName) { t.Fatal("Expected email text 'You have a new notification from " + senderName + "'. Got " + body) } @@ -1086,7 +1097,8 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) } func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T) { - Setup() + a := Global() + a.Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1101,7 +1113,7 @@ func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T) emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new direct message from "+senderName) { t.Fatal("Expected email text 'You have a new direct message from " + senderName + "'. Got " + body) } diff --git a/app/oauth.go b/app/oauth.go index b2bedb63b..7f1a41915 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -26,7 +26,7 @@ const ( COOKIE_OAUTH = "MMOAUTH" ) -func CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { +func (a *App) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("CreateOAuthApp", "api.oauth.register_oauth_app.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -34,64 +34,64 @@ func CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { secret := model.NewId() app.ClientSecret = secret - if result := <-Srv.Store.OAuth().SaveApp(app); result.Err != nil { + if result := <-a.Srv.Store.OAuth().SaveApp(app); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.OAuthApp), nil } } -func GetOAuthApp(appId string) (*model.OAuthApp, *model.AppError) { +func (a *App) GetOAuthApp(appId string) (*model.OAuthApp, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.OAuth().GetApp(appId); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetApp(appId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.OAuthApp), nil } } -func DeleteOAuthApp(appId string) *model.AppError { +func (a *App) DeleteOAuthApp(appId string) *model.AppError { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return model.NewAppError("DeleteOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if err := (<-Srv.Store.OAuth().DeleteApp(appId)).Err; err != nil { + if err := (<-a.Srv.Store.OAuth().DeleteApp(appId)).Err; err != nil { return err } - InvalidateAllCaches() + a.InvalidateAllCaches() return nil } -func GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppError) { +func (a *App) GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthApps", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.OAuth().GetApps(page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetApps(page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.OAuthApp), nil } } -func GetOAuthAppsByCreator(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { +func (a *App) GetOAuthAppsByCreator(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthAppsByUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.OAuth().GetAppByUser(userId, page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetAppByUser(userId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.OAuthApp), nil } } -func AllowOAuthAppAccessToUser(userId string, authRequest *model.AuthorizeRequest) (string, *model.AppError) { +func (a *App) AllowOAuthAppAccessToUser(userId string, authRequest *model.AuthorizeRequest) (string, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return "", model.NewAppError("AllowOAuthAppAccessToUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } @@ -101,7 +101,7 @@ func AllowOAuthAppAccessToUser(userId string, authRequest *model.AuthorizeReques } var oauthApp *model.OAuthApp - if result := <-Srv.Store.OAuth().GetApp(authRequest.ClientId); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetApp(authRequest.ClientId); result.Err != nil { return "", result.Err } else { oauthApp = result.Data.(*model.OAuthApp) @@ -126,24 +126,24 @@ func AllowOAuthAppAccessToUser(userId string, authRequest *model.AuthorizeReques Value: authRequest.Scope, } - if result := <-Srv.Store.Preference().Save(&model.Preferences{authorizedApp}); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&model.Preferences{authorizedApp}); result.Err != nil { return authRequest.RedirectUri + "?error=server_error&state=" + authRequest.State, nil } - if result := <-Srv.Store.OAuth().SaveAuthData(authData); result.Err != nil { + if result := <-a.Srv.Store.OAuth().SaveAuthData(authData); result.Err != nil { return authRequest.RedirectUri + "?error=server_error&state=" + authRequest.State, nil } return authRequest.RedirectUri + "?code=" + url.QueryEscape(authData.Code) + "&state=" + url.QueryEscape(authData.State), nil } -func GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) { +func (a *App) GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refreshToken string) (*model.AccessResponse, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.disabled.app_error", nil, "", http.StatusNotImplemented) } var oauthApp *model.OAuthApp - if result := <-Srv.Store.OAuth().GetApp(clientId); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetApp(clientId); result.Err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.credentials.app_error", nil, "", http.StatusNotFound) } else { oauthApp = result.Data.(*model.OAuthApp) @@ -159,14 +159,14 @@ func GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refresh if grantType == model.ACCESS_TOKEN_GRANT_TYPE { var authData *model.AuthData - if result := <-Srv.Store.OAuth().GetAuthData(code); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetAuthData(code); result.Err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusInternalServerError) } else { authData = result.Data.(*model.AuthData) } if authData.IsExpired() { - <-Srv.Store.OAuth().RemoveAuthData(authData.Code) + <-a.Srv.Store.OAuth().RemoveAuthData(authData.Code) return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusForbidden) } @@ -178,18 +178,18 @@ func GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refresh return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusBadRequest) } - if result := <-Srv.Store.User().Get(authData.UserId); result.Err != nil { + if result := <-a.Srv.Store.User().Get(authData.UserId); result.Err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_user.app_error", nil, "", http.StatusNotFound) } else { user = result.Data.(*model.User) } - if result := <-Srv.Store.OAuth().GetPreviousAccessData(user.Id, clientId); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetPreviousAccessData(user.Id, clientId); result.Err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal.app_error", nil, "", http.StatusInternalServerError) } else if result.Data != nil { accessData := result.Data.(*model.AccessData) if accessData.IsExpired() { - if access, err := newSessionUpdateToken(oauthApp.Name, accessData, user); err != nil { + if access, err := a.newSessionUpdateToken(oauthApp.Name, accessData, user); err != nil { return nil, err } else { accessRsp = access @@ -206,7 +206,7 @@ func GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refresh } else { // create a new session and return new access token var session *model.Session - if result, err := newSession(oauthApp.Name, user); err != nil { + if result, err := a.newSession(oauthApp.Name, user); err != nil { return nil, err } else { session = result @@ -214,7 +214,7 @@ func GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refresh accessData = &model.AccessData{ClientId: clientId, UserId: user.Id, Token: session.Token, RefreshToken: model.NewId(), RedirectUri: redirectUri, ExpiresAt: session.ExpiresAt, Scope: authData.Scope} - if result := <-Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { + if result := <-a.Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { l4g.Error(result.Err) return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } @@ -227,22 +227,22 @@ func GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refresh } } - <-Srv.Store.OAuth().RemoveAuthData(authData.Code) + <-a.Srv.Store.OAuth().RemoveAuthData(authData.Code) } else { // when grantType is refresh_token - if result := <-Srv.Store.OAuth().GetAccessDataByRefreshToken(refreshToken); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetAccessDataByRefreshToken(refreshToken); result.Err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.refresh_token.app_error", nil, "", http.StatusNotFound) } else { accessData = result.Data.(*model.AccessData) } - if result := <-Srv.Store.User().Get(accessData.UserId); result.Err != nil { + if result := <-a.Srv.Store.User().Get(accessData.UserId); result.Err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_user.app_error", nil, "", http.StatusNotFound) } else { user = result.Data.(*model.User) } - if access, err := newSessionUpdateToken(oauthApp.Name, accessData, user); err != nil { + if access, err := a.newSessionUpdateToken(oauthApp.Name, accessData, user); err != nil { return nil, err } else { accessRsp = access @@ -252,7 +252,7 @@ func GetOAuthAccessToken(clientId, grantType, redirectUri, code, secret, refresh return accessRsp, nil } -func newSession(appName string, user *model.User) (*model.Session, *model.AppError) { +func (a *App) newSession(appName string, user *model.User) (*model.Session, *model.AppError) { // set new token an session session := &model.Session{UserId: user.Id, Roles: user.Roles, IsOAuth: true} session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthSSOInDays) @@ -260,7 +260,7 @@ func newSession(appName string, user *model.User) (*model.Session, *model.AppErr session.AddProp(model.SESSION_PROP_OS, "OAuth2") session.AddProp(model.SESSION_PROP_BROWSER, "OAuth2") - if result := <-Srv.Store.Session().Save(session); result.Err != nil { + if result := <-a.Srv.Store.Session().Save(session); result.Err != nil { return nil, model.NewAppError("newSession", "api.oauth.get_access_token.internal_session.app_error", nil, "", http.StatusInternalServerError) } else { session = result.Data.(*model.Session) @@ -270,11 +270,11 @@ func newSession(appName string, user *model.User) (*model.Session, *model.AppErr return session, nil } -func newSessionUpdateToken(appName string, accessData *model.AccessData, user *model.User) (*model.AccessResponse, *model.AppError) { +func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData, user *model.User) (*model.AccessResponse, *model.AppError) { var session *model.Session - <-Srv.Store.Session().Remove(accessData.Token) //remove the previous session + <-a.Srv.Store.Session().Remove(accessData.Token) //remove the previous session - if result, err := newSession(appName, user); err != nil { + if result, err := a.newSession(appName, user); err != nil { return nil, err } else { session = result @@ -283,7 +283,7 @@ func newSessionUpdateToken(appName string, accessData *model.AccessData, user *m accessData.Token = session.Token accessData.RefreshToken = model.NewId() accessData.ExpiresAt = session.ExpiresAt - if result := <-Srv.Store.OAuth().UpdateAccessData(accessData); result.Err != nil { + if result := <-a.Srv.Store.OAuth().UpdateAccessData(accessData); result.Err != nil { l4g.Error(result.Err) return nil, model.NewAppError("newSessionUpdateToken", "web.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } @@ -297,7 +297,7 @@ func newSessionUpdateToken(appName string, accessData *model.AccessData, user *m return accessRsp, nil } -func GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, teamId, action, redirectTo, loginHint string) (string, *model.AppError) { +func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, teamId, action, redirectTo, loginHint string) (string, *model.AppError) { stateProps := map[string]string{} stateProps["action"] = action if len(teamId) != 0 { @@ -308,33 +308,33 @@ func GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, service, team stateProps["redirect_to"] = redirectTo } - if authUrl, err := GetAuthorizationCode(w, r, service, stateProps, loginHint); err != nil { + if authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, loginHint); err != nil { return "", err } else { return authUrl, nil } } -func GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamId string) (string, *model.AppError) { +func (a *App) GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamId string) (string, *model.AppError) { stateProps := map[string]string{} stateProps["action"] = model.OAUTH_ACTION_SIGNUP if len(teamId) != 0 { stateProps["team_id"] = teamId } - if authUrl, err := GetAuthorizationCode(w, r, service, stateProps, ""); err != nil { + if authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, ""); err != nil { return "", err } else { return authUrl, nil } } -func GetAuthorizedAppsForUser(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { +func (a *App) GetAuthorizedAppsForUser(userId string, page, perPage int) ([]*model.OAuthApp, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("GetAuthorizedAppsForUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.OAuth().GetAuthorizedApps(userId, page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetAuthorizedApps(userId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { apps := result.Data.([]*model.OAuthApp) @@ -347,58 +347,58 @@ func GetAuthorizedAppsForUser(userId string, page, perPage int) ([]*model.OAuthA } } -func DeauthorizeOAuthAppForUser(userId, appId string) *model.AppError { +func (a *App) DeauthorizeOAuthAppForUser(userId, appId string) *model.AppError { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return model.NewAppError("DeauthorizeOAuthAppForUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } // revoke app sessions - if result := <-Srv.Store.OAuth().GetAccessDataByUserForApp(userId, appId); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetAccessDataByUserForApp(userId, appId); result.Err != nil { return result.Err } else { accessData := result.Data.([]*model.AccessData) - for _, a := range accessData { - if err := RevokeAccessToken(a.Token); err != nil { + for _, ad := range accessData { + if err := a.RevokeAccessToken(ad.Token); err != nil { return err } - if rad := <-Srv.Store.OAuth().RemoveAccessData(a.Token); rad.Err != nil { + if rad := <-a.Srv.Store.OAuth().RemoveAccessData(ad.Token); rad.Err != nil { return rad.Err } } } // Deauthorize the app - if err := (<-Srv.Store.Preference().Delete(userId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, appId)).Err; err != nil { + if err := (<-a.Srv.Store.Preference().Delete(userId, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, appId)).Err; err != nil { return err } return nil } -func RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { +func (a *App) RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOAuthServiceProvider { return nil, model.NewAppError("RegenerateOAuthAppSecret", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } app.ClientSecret = model.NewId() - if update := <-Srv.Store.OAuth().UpdateApp(app); update.Err != nil { + if update := <-a.Srv.Store.OAuth().UpdateApp(app); update.Err != nil { return nil, update.Err } return app, nil } -func RevokeAccessToken(token string) *model.AppError { - session, _ := GetSession(token) - schan := Srv.Store.Session().Remove(token) +func (a *App) RevokeAccessToken(token string) *model.AppError { + session, _ := a.GetSession(token) + schan := a.Srv.Store.Session().Remove(token) - if result := <-Srv.Store.OAuth().GetAccessData(token); result.Err != nil { + if result := <-a.Srv.Store.OAuth().GetAccessData(token); result.Err != nil { return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.get.app_error", nil, "", http.StatusBadRequest) } - tchan := Srv.Store.OAuth().RemoveAccessData(token) + tchan := a.Srv.Store.OAuth().RemoveAccessData(token) if result := <-tchan; result.Err != nil { return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.del_token.app_error", nil, "", http.StatusInternalServerError) @@ -415,7 +415,7 @@ func RevokeAccessToken(token string) *model.AppError { return nil } -func CompleteOAuth(service string, body io.ReadCloser, teamId string, props map[string]string) (*model.User, *model.AppError) { +func (a *App) CompleteOAuth(service string, body io.ReadCloser, teamId string, props map[string]string) (*model.User, *model.AppError) { defer func() { ioutil.ReadAll(body) body.Close() @@ -425,19 +425,19 @@ func CompleteOAuth(service string, body io.ReadCloser, teamId string, props map[ switch action { case model.OAUTH_ACTION_SIGNUP: - return CreateOAuthUser(service, body, teamId) + return a.CreateOAuthUser(service, body, teamId) case model.OAUTH_ACTION_LOGIN: - return LoginByOAuth(service, body, teamId) + return a.LoginByOAuth(service, body, teamId) case model.OAUTH_ACTION_EMAIL_TO_SSO: - return CompleteSwitchWithOAuth(service, body, props["email"]) + return a.CompleteSwitchWithOAuth(service, body, props["email"]) case model.OAUTH_ACTION_SSO_TO_EMAIL: - return LoginByOAuth(service, body, teamId) + return a.LoginByOAuth(service, body, teamId) default: - return LoginByOAuth(service, body, teamId) + return a.LoginByOAuth(service, body, teamId) } } -func LoginByOAuth(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) { +func (a *App) LoginByOAuth(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) { buf := bytes.Buffer{} buf.ReadFrom(userData) @@ -455,20 +455,20 @@ func LoginByOAuth(service string, userData io.Reader, teamId string) (*model.Use map[string]interface{}{"Service": service}, "", http.StatusBadRequest) } - user, err := GetUserByAuth(&authData, service) + user, err := a.GetUserByAuth(&authData, service) if err != nil { if err.Id == store.MISSING_AUTH_ACCOUNT_ERROR { - return CreateOAuthUser(service, bytes.NewReader(buf.Bytes()), teamId) + return a.CreateOAuthUser(service, bytes.NewReader(buf.Bytes()), teamId) } return nil, err } - if err = UpdateOAuthUserAttrs(bytes.NewReader(buf.Bytes()), user, provider, service); err != nil { + if err = a.UpdateOAuthUserAttrs(bytes.NewReader(buf.Bytes()), user, provider, service); err != nil { return nil, err } if len(teamId) > 0 { - err = AddUserToTeamByTeamId(teamId, user) + err = a.AddUserToTeamByTeamId(teamId, user) } if err != nil { @@ -478,7 +478,7 @@ func LoginByOAuth(service string, userData io.Reader, teamId string) (*model.Use return user, nil } -func CompleteSwitchWithOAuth(service string, userData io.ReadCloser, email string) (*model.User, *model.AppError) { +func (a *App) CompleteSwitchWithOAuth(service string, userData io.ReadCloser, email string) (*model.User, *model.AppError) { authData := "" ssoEmail := "" provider := einterfaces.GetOauthProvider(service) @@ -504,17 +504,17 @@ func CompleteSwitchWithOAuth(service string, userData io.ReadCloser, email strin } var user *model.User - if result := <-Srv.Store.User().GetByEmail(email); result.Err != nil { + if result := <-a.Srv.Store.User().GetByEmail(email); result.Err != nil { return nil, result.Err } else { user = result.Data.(*model.User) } - if err := RevokeAllSessions(user.Id); err != nil { + if err := a.RevokeAllSessions(user.Id); err != nil { return nil, err } - if result := <-Srv.Store.User().UpdateAuthData(user.Id, service, &authData, ssoEmail, true); result.Err != nil { + if result := <-a.Srv.Store.User().UpdateAuthData(user.Id, service, &authData, ssoEmail, true); result.Err != nil { return nil, result.Err } @@ -527,18 +527,18 @@ func CompleteSwitchWithOAuth(service string, userData io.ReadCloser, email strin return user, nil } -func CreateOAuthStateToken(extra string) (*model.Token, *model.AppError) { +func (a *App) CreateOAuthStateToken(extra string) (*model.Token, *model.AppError) { token := model.NewToken(model.TOKEN_TYPE_OAUTH, extra) - if result := <-Srv.Store.Token().Save(token); result.Err != nil { + if result := <-a.Srv.Store.Token().Save(token); result.Err != nil { return nil, result.Err } return token, nil } -func GetOAuthStateToken(token string) (*model.Token, *model.AppError) { - if result := <-Srv.Store.Token().GetByToken(token); result.Err != nil { +func (a *App) GetOAuthStateToken(token string) (*model.Token, *model.AppError) { + if result := <-a.Srv.Store.Token().GetByToken(token); result.Err != nil { return nil, model.NewAppError("GetOAuthStateToken", "api.oauth.invalid_state_token.app_error", nil, result.Err.Error(), http.StatusBadRequest) } else { token := result.Data.(*model.Token) @@ -554,7 +554,7 @@ func generateOAuthStateTokenExtra(email, action, cookie string) string { return email + ":" + action + ":" + cookie } -func GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) { +func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string, props map[string]string, loginHint string) (string, *model.AppError) { sso := utils.Cfg.GetSSOService(service) if sso != nil && !sso.Enable { return "", model.NewAppError("GetAuthorizationCode", "api.user.get_authorization_code.unsupported.app_error", nil, "service="+service, http.StatusNotImplemented) @@ -584,7 +584,7 @@ func GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string scope := sso.Scope tokenExtra := generateOAuthStateTokenExtra(props["email"], props["action"], cookieValue) - stateToken, err := CreateOAuthStateToken(tokenExtra) + stateToken, err := a.CreateOAuthStateToken(tokenExtra) if err != nil { return "", err } @@ -607,7 +607,7 @@ func GetAuthorizationCode(w http.ResponseWriter, r *http.Request, service string return authUrl, nil } -func AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.AppError) { +func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.AppError) { sso := utils.Cfg.GetSSOService(service) if sso == nil || !sso.Enable { return nil, "", nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.unsupported.app_error", nil, "service="+service, http.StatusNotImplemented) @@ -622,7 +622,7 @@ func AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, s stateProps := model.MapFromJson(strings.NewReader(stateStr)) - expectedToken, err := GetOAuthStateToken(stateProps["token"]) + expectedToken, err := a.GetOAuthStateToken(stateProps["token"]) if err != nil { return nil, "", stateProps, err } @@ -645,7 +645,7 @@ func AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, s return nil, "", stateProps, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest) } - DeleteToken(expectedToken) + a.DeleteToken(expectedToken) cookie := &http.Cookie{ Name: COOKIE_OAUTH, @@ -710,14 +710,14 @@ func AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, s } -func 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) { var user *model.User var err *model.AppError - if user, err = GetUserByEmail(email); err != nil { + if user, err = a.GetUserByEmail(email); err != nil { return "", err } - if err := CheckPasswordAndAllCriteria(user, password, code); err != nil { + if err := a.CheckPasswordAndAllCriteria(user, password, code); err != nil { return "", err } @@ -728,7 +728,7 @@ func SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, if service == model.USER_AUTH_SERVICE_SAML { return utils.GetSiteURL() + "/login/sso/saml?action=" + model.OAUTH_ACTION_EMAIL_TO_SSO + "&email=" + email, nil } else { - if authUrl, err := GetAuthorizationCode(w, r, service, stateProps, ""); err != nil { + if authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, ""); err != nil { return "", err } else { return authUrl, nil @@ -736,10 +736,10 @@ func SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, } } -func SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) { +func (a *App) SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) { var user *model.User var err *model.AppError - if user, err = GetUserByEmail(email); err != nil { + if user, err = a.GetUserByEmail(email); err != nil { return "", err } @@ -747,7 +747,7 @@ func SwitchOAuthToEmail(email, password, requesterId string) (string, *model.App return "", model.NewAppError("SwitchOAuthToEmail", "api.user.oauth_to_email.context.app_error", nil, "", http.StatusForbidden) } - if err := UpdatePassword(user, password); err != nil { + if err := a.UpdatePassword(user, password); err != nil { return "", err } @@ -759,7 +759,7 @@ func SwitchOAuthToEmail(email, password, requesterId string) (string, *model.App } }() - if err := RevokeAllSessions(requesterId); err != nil { + if err := a.RevokeAllSessions(requesterId); err != nil { return "", err } diff --git a/app/oauth_test.go b/app/oauth_test.go index 185f5d73f..349cc4a9c 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -11,8 +11,9 @@ import ( ) func TestOAuthRevokeAccessToken(t *testing.T) { - Setup() - if err := RevokeAccessToken(model.NewRandomString(16)); err == nil { + a := Global() + a.Setup() + if err := a.RevokeAccessToken(model.NewRandomString(16)); err == nil { t.Fatal("Should have failed bad token") } @@ -23,8 +24,8 @@ func TestOAuthRevokeAccessToken(t *testing.T) { session.Roles = model.ROLE_SYSTEM_USER.Id session.SetExpireInDays(1) - session, _ = CreateSession(session) - if err := RevokeAccessToken(session.Token); err == nil { + session, _ = a.CreateSession(session) + if err := a.RevokeAccessToken(session.Token); err == nil { t.Fatal("Should have failed does not have an access token") } @@ -35,17 +36,18 @@ func TestOAuthRevokeAccessToken(t *testing.T) { accessData.ClientId = model.NewId() accessData.ExpiresAt = session.ExpiresAt - if result := <-Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { + if result := <-a.Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { t.Fatal(result.Err) } - if err := RevokeAccessToken(accessData.Token); err != nil { + if err := a.RevokeAccessToken(accessData.Token); err != nil { t.Fatal(err) } } func TestOAuthDeleteApp(t *testing.T) { - Setup() + a := Global() + a.Setup() oldSetting := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider defer func() { @@ -60,7 +62,7 @@ func TestOAuthDeleteApp(t *testing.T) { a1.Homepage = "https://nowhere.com" var err *model.AppError - a1, err = CreateOAuthApp(a1) + a1, err = a.CreateOAuthApp(a1) if err != nil { t.Fatal(err) } @@ -73,7 +75,7 @@ func TestOAuthDeleteApp(t *testing.T) { session.IsOAuth = true session.SetExpireInDays(1) - session, _ = CreateSession(session) + session, _ = a.CreateSession(session) accessData := &model.AccessData{} accessData.Token = session.Token @@ -82,15 +84,15 @@ func TestOAuthDeleteApp(t *testing.T) { accessData.ClientId = a1.Id accessData.ExpiresAt = session.ExpiresAt - if result := <-Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { + if result := <-a.Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { t.Fatal(result.Err) } - if err := DeleteOAuthApp(a1.Id); err != nil { + if err := a.DeleteOAuthApp(a1.Id); err != nil { t.Fatal(err) } - if _, err := GetSession(session.Token); err == nil { + if _, err := a.GetSession(session.Token); err == nil { t.Fatal("should not get session from cache or db") } } diff --git a/app/plugins.go b/app/plugins.go index 1101f2b65..5dbb0a817 100644 --- a/app/plugins.go +++ b/app/plugins.go @@ -42,23 +42,23 @@ func (api *PluginAPI) PluginRouter() *mux.Router { } func (api *PluginAPI) GetTeamByName(name string) (*model.Team, *model.AppError) { - return GetTeamByName(name) + return Global().GetTeamByName(name) } func (api *PluginAPI) GetUserByName(name string) (*model.User, *model.AppError) { - return GetUserByUsername(name) + return Global().GetUserByUsername(name) } func (api *PluginAPI) GetChannelByName(teamId, name string) (*model.Channel, *model.AppError) { - return GetChannelByName(name, teamId) + return Global().GetChannelByName(name, teamId) } func (api *PluginAPI) GetDirectChannel(userId1, userId2 string) (*model.Channel, *model.AppError) { - return GetDirectChannel(userId1, userId2) + return Global().GetDirectChannel(userId1, userId2) } func (api *PluginAPI) CreatePost(post *model.Post) (*model.Post, *model.AppError) { - return CreatePostMissingChannel(post, true) + return Global().CreatePostMissingChannel(post, true) } func (api *PluginAPI) GetLdapUserAttributes(userId string, attributes []string) (map[string]string, *model.AppError) { @@ -67,7 +67,7 @@ func (api *PluginAPI) GetLdapUserAttributes(userId string, attributes []string) return nil, model.NewAppError("GetLdapUserAttributes", "ent.ldap.disabled.app_error", nil, "", http.StatusNotImplemented) } - user, err := GetUser(userId) + user, err := Global().GetUser(userId) if err != nil { return nil, err } @@ -111,7 +111,7 @@ func (api *PluginAPI) GetSessionFromRequest(r *http.Request) (*model.Session, *m return nil, model.NewAppError("ServeHTTP", "api.context.session_expired.app_error", nil, "token="+token, http.StatusUnauthorized) } - session, err := GetSession(token) + session, err := Global().GetSession(token) if err != nil { return nil, model.NewAppError("ServeHTTP", "api.context.session_expired.app_error", nil, "token="+token, http.StatusUnauthorized) @@ -131,7 +131,7 @@ func (api *PluginAPI) I18n(id string, r *http.Request) string { return f(id) } -func InitPlugins() { +func (a *App) InitPlugins() { plugins := map[string]plugin.Plugin{ "jira": &jira.Plugin{}, "ldapextras": &ldapextras.Plugin{}, @@ -140,7 +140,7 @@ func InitPlugins() { l4g.Info("Initializing plugin: " + id) api := &PluginAPI{ id: id, - router: Srv.Router.PathPrefix("/plugins/" + id).Subrouter(), + router: a.Srv.Router.PathPrefix("/plugins/" + id).Subrouter(), } p.Initialize(api) } @@ -154,20 +154,20 @@ func InitPlugins() { } } -func ActivatePlugins() { - if Srv.PluginEnv == nil { +func (a *App) ActivatePlugins() { + if a.Srv.PluginEnv == nil { l4g.Error("plugin env not initialized") return } - plugins, err := Srv.PluginEnv.Plugins() + plugins, err := a.Srv.PluginEnv.Plugins() if err != nil { l4g.Error("failed to start up plugins: " + err.Error()) return } for _, plugin := range plugins { - err := Srv.PluginEnv.ActivatePlugin(plugin.Manifest.Id) + err := a.Srv.PluginEnv.ActivatePlugin(plugin.Manifest.Id) if err != nil { l4g.Error(err.Error()) } @@ -175,8 +175,8 @@ func ActivatePlugins() { } } -func UnpackAndActivatePlugin(pluginFile io.Reader) (*model.Manifest, *model.AppError) { - if Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { +func (a *App) UnpackAndActivatePlugin(pluginFile io.Reader) (*model.Manifest, *model.AppError) { + if a.Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { return nil, model.NewAppError("UnpackAndActivatePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -210,14 +210,14 @@ func UnpackAndActivatePlugin(pluginFile io.Reader) (*model.Manifest, *model.AppE return nil, model.NewAppError("UnpackAndActivatePlugin", "app.plugin.manifest.app_error", nil, err.Error(), http.StatusBadRequest) } - os.Rename(manifestDir, filepath.Join(Srv.PluginEnv.SearchPath(), manifest.Id)) + os.Rename(manifestDir, filepath.Join(a.Srv.PluginEnv.SearchPath(), manifest.Id)) if err != nil { return nil, model.NewAppError("UnpackAndActivatePlugin", "app.plugin.mvdir.app_error", nil, err.Error(), http.StatusInternalServerError) } // Should add manifest validation and error handling here - err = Srv.PluginEnv.ActivatePlugin(manifest.Id) + err = a.Srv.PluginEnv.ActivatePlugin(manifest.Id) if err != nil { return nil, model.NewAppError("UnpackAndActivatePlugin", "app.plugin.activate.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -225,12 +225,12 @@ func UnpackAndActivatePlugin(pluginFile io.Reader) (*model.Manifest, *model.AppE return manifest, nil } -func GetActivePluginManifests() ([]*model.Manifest, *model.AppError) { - if Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { +func (a *App) GetActivePluginManifests() ([]*model.Manifest, *model.AppError) { + if a.Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { return nil, model.NewAppError("GetActivePluginManifests", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } - plugins, err := Srv.PluginEnv.ActivePlugins() + plugins, err := a.Srv.PluginEnv.ActivePlugins() if err != nil { return nil, model.NewAppError("GetActivePluginManifests", "app.plugin.get_plugins.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -243,17 +243,17 @@ func GetActivePluginManifests() ([]*model.Manifest, *model.AppError) { return manifests, nil } -func RemovePlugin(id string) *model.AppError { - if Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { +func (a *App) RemovePlugin(id string) *model.AppError { + if a.Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { return model.NewAppError("RemovePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } - err := Srv.PluginEnv.DeactivatePlugin(id) + err := a.Srv.PluginEnv.DeactivatePlugin(id) if err != nil { return model.NewAppError("RemovePlugin", "app.plugin.deactivate.app_error", nil, err.Error(), http.StatusBadRequest) } - err = os.RemoveAll(filepath.Join(Srv.PluginEnv.SearchPath(), id)) + err = os.RemoveAll(filepath.Join(a.Srv.PluginEnv.SearchPath(), id)) if err != nil { return model.NewAppError("RemovePlugin", "app.plugin.remove.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -267,12 +267,12 @@ type ClientConfigPlugin struct { BundlePath string `json:"bundle_path"` } -func GetPluginsForClientConfig() string { - if Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { +func (a *App) GetPluginsForClientConfig() string { + if a.Srv.PluginEnv == nil || !*utils.Cfg.PluginSettings.Enable { return "" } - plugins, err := Srv.PluginEnv.ActivePlugins() + plugins, err := a.Srv.PluginEnv.ActivePlugins() if err != nil { return "" } diff --git a/app/post.go b/app/post.go index 6e97ca680..bb2a1b5d7 100644 --- a/app/post.go +++ b/app/post.go @@ -20,10 +20,10 @@ import ( var linkWithTextRegex = regexp.MustCompile(`<([^<\|]+)\|([^>]+)>`) -func CreatePostAsUser(post *model.Post) (*model.Post, *model.AppError) { +func (a *App) CreatePostAsUser(post *model.Post) (*model.Post, *model.AppError) { // Check that channel has not been deleted var channel *model.Channel - if result := <-Srv.Store.Channel().Get(post.ChannelId, true); result.Err != nil { + if result := <-a.Srv.Store.Channel().Get(post.ChannelId, true); result.Err != nil { err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.channel_id"}, result.Err.Error(), http.StatusBadRequest) return nil, err } else { @@ -35,7 +35,7 @@ func CreatePostAsUser(post *model.Post) (*model.Post, *model.AppError) { return nil, err } - if rp, err := CreatePost(post, channel, true); err != nil { + if rp, err := a.CreatePost(post, channel, true); err != nil { if err.Id == "api.post.create_post.root_id.app_error" || err.Id == "api.post.create_post.channel_root_id.app_error" || err.Id == "api.post.create_post.parent_id.app_error" { @@ -43,7 +43,7 @@ func CreatePostAsUser(post *model.Post) (*model.Post, *model.AppError) { } if err.Id == "api.post.create_post.town_square_read_only" { - uchan := Srv.Store.User().Get(post.UserId) + uchan := a.Srv.Store.User().Get(post.UserId) var user *model.User if result := <-uchan; result.Err != nil { return nil, result.Err @@ -69,7 +69,7 @@ func CreatePostAsUser(post *model.Post) (*model.Post, *model.AppError) { } else { // Update the LastViewAt only if the post does not have from_webhook prop set (eg. Zapier app) if _, ok := post.Props["from_webhook"]; !ok { - if result := <-Srv.Store.Channel().UpdateLastViewedAt([]string{post.ChannelId}, post.UserId); result.Err != nil { + if result := <-a.Srv.Store.Channel().UpdateLastViewedAt([]string{post.ChannelId}, post.UserId); result.Err != nil { l4g.Error(utils.T("api.post.create_post.last_viewed.error"), post.ChannelId, post.UserId, result.Err) } @@ -85,25 +85,25 @@ func CreatePostAsUser(post *model.Post) (*model.Post, *model.AppError) { } -func CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { +func (a *App) CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { var channel *model.Channel - cchan := Srv.Store.Channel().Get(post.ChannelId, true) + cchan := a.Srv.Store.Channel().Get(post.ChannelId, true) if result := <-cchan; result.Err != nil { return nil, result.Err } else { channel = result.Data.(*model.Channel) } - return CreatePost(post, channel, triggerWebhooks) + return a.CreatePost(post, channel, triggerWebhooks) } -func CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool) (*model.Post, *model.AppError) { +func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool) (*model.Post, *model.AppError) { var pchan store.StoreChannel if len(post.RootId) > 0 { - pchan = Srv.Store.Post().Get(post.RootId) + pchan = a.Srv.Store.Post().Get(post.RootId) } - uchan := Srv.Store.User().Get(post.UserId) + uchan := a.Srv.Store.User().Get(post.UserId) var user *model.User if result := <-uchan; result.Err != nil { return nil, result.Err @@ -145,7 +145,7 @@ func CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool) post.Hashtags, _ = model.ParseHashtags(post.Message) var rpost *model.Post - if result := <-Srv.Store.Post().Save(post); result.Err != nil { + if result := <-a.Srv.Store.Post().Save(post); result.Err != nil { return nil, result.Err } else { rpost = result.Data.(*model.Post) @@ -165,7 +165,7 @@ func CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool) post.FileIds = utils.RemoveDuplicatesFromStringArray(post.FileIds) for _, fileId := range post.FileIds { - if result := <-Srv.Store.FileInfo().AttachToPost(fileId, post.Id); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().AttachToPost(fileId, post.Id); result.Err != nil { l4g.Error(utils.T("api.post.create_post.attach_files.error"), post.Id, post.FileIds, post.UserId, result.Err) } } @@ -175,17 +175,17 @@ func CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks bool) } } - if err := handlePostEvents(rpost, user, channel, triggerWebhooks, parentPostList); err != nil { + if err := a.handlePostEvents(rpost, user, channel, triggerWebhooks, parentPostList); err != nil { return nil, err } return rpost, nil } -func handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList) *model.AppError { +func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList) *model.AppError { var tchan store.StoreChannel if len(channel.TeamId) > 0 { - tchan = Srv.Store.Team().Get(channel.TeamId) + tchan = a.Srv.Store.Team().Get(channel.TeamId) } var team *model.Team @@ -200,16 +200,16 @@ func handlePostEvents(post *model.Post, user *model.User, channel *model.Channel team = &model.Team{} } - InvalidateCacheForChannel(channel) - InvalidateCacheForChannelPosts(channel.Id) + a.InvalidateCacheForChannel(channel) + a.InvalidateCacheForChannelPosts(channel.Id) - if _, err := SendNotifications(post, team, channel, user, parentPostList); err != nil { + if _, err := a.SendNotifications(post, team, channel, user, parentPostList); err != nil { return err } if triggerWebhooks { go func() { - if err := handleWebhookEvents(post, team, channel, user); err != nil { + if err := a.handleWebhookEvents(post, team, channel, user); err != nil { l4g.Error(err.Error()) } }() @@ -262,9 +262,9 @@ func SendEphemeralPost(userId string, post *model.Post) *model.Post { return post } -func UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { +func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { var oldPost *model.Post - if result := <-Srv.Store.Post().Get(post.Id); result.Err != nil { + if result := <-a.Srv.Store.Post().Get(post.Id); result.Err != nil { return nil, result.Err } else { oldPost = result.Data.(*model.PostList).Posts[post.Id] @@ -315,7 +315,7 @@ func UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError newPost.Props = post.Props } - if result := <-Srv.Store.Post().Update(newPost, oldPost); result.Err != nil { + if result := <-a.Srv.Store.Post().Update(newPost, oldPost); result.Err != nil { return nil, result.Err } else { rpost := result.Data.(*model.Post) @@ -323,7 +323,7 @@ func UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError esInterface := einterfaces.GetElasticsearchInterface() if esInterface != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { go func() { - if rchannel := <-Srv.Store.Channel().GetForPost(rpost.Id); rchannel.Err != nil { + if rchannel := <-a.Srv.Store.Channel().GetForPost(rpost.Id); rchannel.Err != nil { l4g.Error("Couldn't get channel %v for post %v for Elasticsearch indexing.", rpost.ChannelId, rpost.Id) } else { esInterface.IndexPost(rpost, rchannel.Data.(*model.Channel).TeamId) @@ -333,27 +333,27 @@ func UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError sendUpdatedPostEvent(rpost) - InvalidateCacheForChannelPosts(rpost.ChannelId) + a.InvalidateCacheForChannelPosts(rpost.ChannelId) return rpost, nil } } -func PatchPost(postId string, patch *model.PostPatch) (*model.Post, *model.AppError) { - post, err := GetSinglePost(postId) +func (a *App) PatchPost(postId string, patch *model.PostPatch) (*model.Post, *model.AppError) { + post, err := a.GetSinglePost(postId) if err != nil { return nil, err } post.Patch(patch) - updatedPost, err := UpdatePost(post, false) + updatedPost, err := a.UpdatePost(post, false) if err != nil { return nil, err } sendUpdatedPostEvent(updatedPost) - InvalidateCacheForChannelPosts(updatedPost.ChannelId) + a.InvalidateCacheForChannelPosts(updatedPost.ChannelId) return updatedPost, nil } @@ -365,76 +365,76 @@ func sendUpdatedPostEvent(post *model.Post) { go Publish(message) } -func GetPostsPage(channelId string, page int, perPage int) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetPosts(channelId, page*perPage, perPage, true); result.Err != nil { +func (a *App) GetPostsPage(channelId string, page int, perPage int) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetPosts(channelId, page*perPage, perPage, true); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetPosts(channelId string, offset int, limit int) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetPosts(channelId, offset, limit, true); result.Err != nil { +func (a *App) GetPosts(channelId string, offset int, limit int) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetPosts(channelId, offset, limit, true); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetPostsEtag(channelId string) string { - return (<-Srv.Store.Post().GetEtag(channelId, true)).Data.(string) +func (a *App) GetPostsEtag(channelId string) string { + return (<-a.Srv.Store.Post().GetEtag(channelId, true)).Data.(string) } -func GetPostsSince(channelId string, time int64) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetPostsSince(channelId, time, true); result.Err != nil { +func (a *App) GetPostsSince(channelId string, time int64) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetPostsSince(channelId, time, true); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetSinglePost(postId string) (*model.Post, *model.AppError) { - if result := <-Srv.Store.Post().GetSingle(postId); result.Err != nil { +func (a *App) GetSinglePost(postId string) (*model.Post, *model.AppError) { + if result := <-a.Srv.Store.Post().GetSingle(postId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Post), nil } } -func GetPostThread(postId string) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().Get(postId); result.Err != nil { +func (a *App) GetPostThread(postId string) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().Get(postId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetFlaggedPosts(userId string, offset int, limit int) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetFlaggedPosts(userId, offset, limit); result.Err != nil { +func (a *App) GetFlaggedPosts(userId string, offset int, limit int) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetFlaggedPosts(userId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetFlaggedPostsForTeam(userId, teamId string, offset int, limit int) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetFlaggedPostsForTeam(userId, teamId, offset, limit); result.Err != nil { +func (a *App) GetFlaggedPostsForTeam(userId, teamId string, offset int, limit int) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetFlaggedPostsForTeam(userId, teamId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetFlaggedPostsForChannel(userId, channelId string, offset int, limit int) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetFlaggedPostsForChannel(userId, channelId, offset, limit); result.Err != nil { +func (a *App) GetFlaggedPostsForChannel(userId, channelId string, offset int, limit int) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetFlaggedPostsForChannel(userId, channelId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetPermalinkPost(postId string, userId string) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().Get(postId); result.Err != nil { +func (a *App) GetPermalinkPost(postId string, userId string) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().Get(postId); result.Err != nil { return nil, result.Err } else { list := result.Data.(*model.PostList) @@ -446,11 +446,11 @@ func GetPermalinkPost(postId string, userId string) (*model.PostList, *model.App var channel *model.Channel var err *model.AppError - if channel, err = GetChannel(post.ChannelId); err != nil { + if channel, err = a.GetChannel(post.ChannelId); err != nil { return nil, err } - if err = JoinChannel(channel, userId); err != nil { + if err = a.JoinChannel(channel, userId); err != nil { return nil, err } @@ -458,28 +458,28 @@ func GetPermalinkPost(postId string, userId string) (*model.PostList, *model.App } } -func GetPostsBeforePost(channelId, postId string, page, perPage int) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetPostsBefore(channelId, postId, perPage, page*perPage); result.Err != nil { +func (a *App) GetPostsBeforePost(channelId, postId string, page, perPage int) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetPostsBefore(channelId, postId, perPage, page*perPage); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetPostsAfterPost(channelId, postId string, page, perPage int) (*model.PostList, *model.AppError) { - if result := <-Srv.Store.Post().GetPostsAfter(channelId, postId, perPage, page*perPage); result.Err != nil { +func (a *App) GetPostsAfterPost(channelId, postId string, page, perPage int) (*model.PostList, *model.AppError) { + if result := <-a.Srv.Store.Post().GetPostsAfter(channelId, postId, perPage, page*perPage); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.PostList), nil } } -func GetPostsAroundPost(postId, channelId string, offset, limit int, before bool) (*model.PostList, *model.AppError) { +func (a *App) GetPostsAroundPost(postId, channelId string, offset, limit int, before bool) (*model.PostList, *model.AppError) { var pchan store.StoreChannel if before { - pchan = Srv.Store.Post().GetPostsBefore(channelId, postId, limit, offset) + pchan = a.Srv.Store.Post().GetPostsBefore(channelId, postId, limit, offset) } else { - pchan = Srv.Store.Post().GetPostsAfter(channelId, postId, limit, offset) + pchan = a.Srv.Store.Post().GetPostsAfter(channelId, postId, limit, offset) } if result := <-pchan; result.Err != nil { @@ -489,14 +489,14 @@ func GetPostsAroundPost(postId, channelId string, offset, limit int, before bool } } -func DeletePost(postId string) (*model.Post, *model.AppError) { - if result := <-Srv.Store.Post().GetSingle(postId); result.Err != nil { +func (a *App) DeletePost(postId string) (*model.Post, *model.AppError) { + if result := <-a.Srv.Store.Post().GetSingle(postId); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return nil, result.Err } else { post := result.Data.(*model.Post) - if result := <-Srv.Store.Post().Delete(postId, model.GetMillis()); result.Err != nil { + if result := <-a.Srv.Store.Post().Delete(postId, model.GetMillis()); result.Err != nil { return nil, result.Err } @@ -504,38 +504,38 @@ func DeletePost(postId string) (*model.Post, *model.AppError) { message.Add("post", post.ToJson()) go Publish(message) - go DeletePostFiles(post) - go DeleteFlaggedPosts(post.Id) + go a.DeletePostFiles(post) + go a.DeleteFlaggedPosts(post.Id) esInterface := einterfaces.GetElasticsearchInterface() if esInterface != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { go esInterface.DeletePost(post) } - InvalidateCacheForChannelPosts(post.ChannelId) + a.InvalidateCacheForChannelPosts(post.ChannelId) return post, nil } } -func DeleteFlaggedPosts(postId string) { - if result := <-Srv.Store.Preference().DeleteCategoryAndName(model.PREFERENCE_CATEGORY_FLAGGED_POST, postId); result.Err != nil { +func (a *App) DeleteFlaggedPosts(postId string) { + if result := <-a.Srv.Store.Preference().DeleteCategoryAndName(model.PREFERENCE_CATEGORY_FLAGGED_POST, postId); result.Err != nil { l4g.Warn(utils.T("api.post.delete_flagged_post.app_error.warn"), result.Err) return } } -func DeletePostFiles(post *model.Post) { +func (a *App) DeletePostFiles(post *model.Post) { if len(post.FileIds) != 0 { return } - if result := <-Srv.Store.FileInfo().DeleteForPost(post.Id); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().DeleteForPost(post.Id); result.Err != nil { l4g.Warn(utils.T("api.post.delete_post_files.app_error.warn"), post.Id, result.Err) } } -func SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bool) (*model.PostList, *model.AppError) { +func (a *App) SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bool) (*model.PostList, *model.AppError) { paramsList := model.ParseSearchParams(terms) esInterface := einterfaces.GetElasticsearchInterface() @@ -548,7 +548,7 @@ func SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bo if params.Terms != "*" { // Convert channel names to channel IDs for idx, channelName := range params.InChannels { - if channel, err := GetChannelByName(channelName, teamId); err != nil { + if channel, err := a.GetChannelByName(channelName, teamId); err != nil { l4g.Error(err) } else { params.InChannels[idx] = channel.Id @@ -557,7 +557,7 @@ func SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bo // Convert usernames to user IDs for idx, username := range params.FromUsers { - if user, err := GetUserByUsername(username); err != nil { + if user, err := a.GetUserByUsername(username); err != nil { l4g.Error(err) } else { params.FromUsers[idx] = user.Id @@ -574,7 +574,7 @@ func SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bo } // We only allow the user to search in channels they are a member of. - userChannels, err := GetChannelsForUser(teamId, userId) + userChannels, err := a.GetChannelsForUser(teamId, userId) if err != nil { l4g.Error(err) return nil, err @@ -587,7 +587,7 @@ func SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bo // Get the posts postList := model.NewPostList() - if presult := <-Srv.Store.Post().GetPostsByIds(postIds); presult.Err != nil { + if presult := <-a.Srv.Store.Post().GetPostsByIds(postIds); presult.Err != nil { return nil, presult.Err } else { for _, p := range presult.Data.([]*model.Post) { @@ -604,7 +604,7 @@ func SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bo params.OrTerms = isOrSearch // don't allow users to search for everything if params.Terms != "*" { - channels = append(channels, Srv.Store.Post().Search(teamId, userId, params)) + channels = append(channels, a.Srv.Store.Post().Search(teamId, userId, params)) } } @@ -622,9 +622,9 @@ func SearchPostsInTeam(terms string, userId string, teamId string, isOrSearch bo } } -func GetFileInfosForPost(postId string, readFromMaster bool) ([]*model.FileInfo, *model.AppError) { - pchan := Srv.Store.Post().GetSingle(postId) - fchan := Srv.Store.FileInfo().GetForPost(postId, readFromMaster, true) +func (a *App) GetFileInfosForPost(postId string, readFromMaster bool) ([]*model.FileInfo, *model.AppError) { + pchan := a.Srv.Store.Post().GetSingle(postId) + fchan := a.Srv.Store.FileInfo().GetForPost(postId, readFromMaster, true) var infos []*model.FileInfo if result := <-fchan; result.Err != nil { @@ -643,9 +643,9 @@ func GetFileInfosForPost(postId string, readFromMaster bool) ([]*model.FileInfo, } if len(post.Filenames) > 0 { - Srv.Store.FileInfo().InvalidateFileInfosForPostCache(postId) + a.Srv.Store.FileInfo().InvalidateFileInfosForPostCache(postId) // The post has Filenames that need to be replaced with FileInfos - infos = MigrateFilenamesToFileInfos(post) + infos = a.MigrateFilenamesToFileInfos(post) } } @@ -669,8 +669,8 @@ func GetOpenGraphMetadata(url string) *opengraph.OpenGraph { return og } -func DoPostAction(postId string, actionId string, userId string) *model.AppError { - pchan := Srv.Store.Post().GetSingle(postId) +func (a *App) DoPostAction(postId string, actionId string, userId string) *model.AppError { + pchan := a.Srv.Store.Post().GetSingle(postId) var post *model.Post if result := <-pchan; result.Err != nil { @@ -710,7 +710,7 @@ func DoPostAction(postId string, actionId string, userId string) *model.AppError if response.Update != nil { response.Update.Id = postId response.Update.AddProp("from_webhook", "true") - if _, err := UpdatePost(response.Update, false); err != nil { + if _, err := a.UpdatePost(response.Update, false); err != nil { return err } } diff --git a/app/post_test.go b/app/post_test.go index ab8e27021..e7084325e 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -19,13 +19,14 @@ import ( ) func TestUpdatePostEditAt(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() post := &model.Post{} *post = *th.BasicPost post.IsPinned = true - if saved, err := UpdatePost(post, true); err != nil { + if saved, err := a.UpdatePost(post, true); err != nil { t.Fatal(err) } else if saved.EditAt != post.EditAt { t.Fatal("shouldn't have updated post.EditAt when pinning post") @@ -36,7 +37,7 @@ func TestUpdatePostEditAt(t *testing.T) { time.Sleep(time.Millisecond * 100) post.Message = model.NewId() - if saved, err := UpdatePost(post, true); err != nil { + if saved, err := a.UpdatePost(post, true); err != nil { t.Fatal(err) } else if saved.EditAt == post.EditAt { t.Fatal("should have updated post.EditAt when updating post message") @@ -44,20 +45,21 @@ func TestUpdatePostEditAt(t *testing.T) { } func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) { + a := Global() // This test ensures that when replying to a root post made by a user who has since left the channel, the reply // post completes successfully. This is a regression test for PLT-6523. - th := Setup().InitBasic() + th := a.Setup().InitBasic() channel := th.BasicChannel userInChannel := th.BasicUser2 userNotInChannel := th.BasicUser rootPost := th.BasicPost - if _, err := AddUserToChannel(userInChannel, channel); err != nil { + if _, err := a.AddUserToChannel(userInChannel, channel); err != nil { t.Fatal(err) } - if err := RemoveUserFromChannel(userNotInChannel.Id, "", channel); err != nil { + if err := a.RemoveUserFromChannel(userNotInChannel.Id, "", channel); err != nil { t.Fatal(err) } @@ -71,13 +73,14 @@ func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) { CreateAt: 0, } - if _, err := CreatePostAsUser(&replyPost); err != nil { + if _, err := a.CreatePostAsUser(&replyPost); err != nil { t.Fatal(err) } } func TestPostAction(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections defer func() { @@ -122,7 +125,7 @@ func TestPostAction(t *testing.T) { }, } - post, err := CreatePostAsUser(&interactivePost) + post, err := a.CreatePostAsUser(&interactivePost) require.Nil(t, err) attachments, ok := post.Props["attachments"].([]*model.SlackAttachment) @@ -131,10 +134,10 @@ func TestPostAction(t *testing.T) { require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - err = DoPostAction(post.Id, "notavalidid", th.BasicUser.Id) + err = a.DoPostAction(post.Id, "notavalidid", th.BasicUser.Id) require.NotNil(t, err) assert.Equal(t, http.StatusNotFound, err.StatusCode) - err = DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id) + err = a.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id) require.Nil(t, err) } diff --git a/app/preference.go b/app/preference.go index 425b88d29..61420ac8f 100644 --- a/app/preference.go +++ b/app/preference.go @@ -4,12 +4,13 @@ package app import ( - "github.com/mattermost/platform/model" "net/http" + + "github.com/mattermost/platform/model" ) -func GetPreferencesForUser(userId string) (model.Preferences, *model.AppError) { - if result := <-Srv.Store.Preference().GetAll(userId); result.Err != nil { +func (a *App) GetPreferencesForUser(userId string) (model.Preferences, *model.AppError) { + if result := <-a.Srv.Store.Preference().GetAll(userId); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return nil, result.Err } else { @@ -17,8 +18,8 @@ func GetPreferencesForUser(userId string) (model.Preferences, *model.AppError) { } } -func GetPreferenceByCategoryForUser(userId string, category string) (model.Preferences, *model.AppError) { - if result := <-Srv.Store.Preference().GetCategory(userId, category); result.Err != nil { +func (a *App) GetPreferenceByCategoryForUser(userId string, category string) (model.Preferences, *model.AppError) { + if result := <-a.Srv.Store.Preference().GetCategory(userId, category); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return nil, result.Err } else if len(result.Data.(model.Preferences)) == 0 { @@ -29,8 +30,8 @@ func GetPreferenceByCategoryForUser(userId string, category string) (model.Prefe } } -func GetPreferenceByCategoryAndNameForUser(userId string, category string, preferenceName string) (*model.Preference, *model.AppError) { - if result := <-Srv.Store.Preference().Get(userId, category, preferenceName); result.Err != nil { +func (a *App) GetPreferenceByCategoryAndNameForUser(userId string, category string, preferenceName string) (*model.Preference, *model.AppError) { + if result := <-a.Srv.Store.Preference().Get(userId, category, preferenceName); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return nil, result.Err } else { @@ -39,7 +40,7 @@ func GetPreferenceByCategoryAndNameForUser(userId string, category string, prefe } } -func UpdatePreferences(userId string, preferences model.Preferences) *model.AppError { +func (a *App) UpdatePreferences(userId string, preferences model.Preferences) *model.AppError { for _, preference := range preferences { if userId != preference.UserId { return model.NewAppError("savePreferences", "api.preference.update_preferences.set.app_error", nil, @@ -47,7 +48,7 @@ func UpdatePreferences(userId string, preferences model.Preferences) *model.AppE } } - if result := <-Srv.Store.Preference().Save(&preferences); result.Err != nil { + if result := <-a.Srv.Store.Preference().Save(&preferences); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return result.Err } @@ -59,7 +60,7 @@ func UpdatePreferences(userId string, preferences model.Preferences) *model.AppE return nil } -func DeletePreferences(userId string, preferences model.Preferences) *model.AppError { +func (a *App) DeletePreferences(userId string, preferences model.Preferences) *model.AppError { for _, preference := range preferences { if userId != preference.UserId { err := model.NewAppError("deletePreferences", "api.preference.delete_preferences.delete.app_error", nil, @@ -69,7 +70,7 @@ func DeletePreferences(userId string, preferences model.Preferences) *model.AppE } for _, preference := range preferences { - if result := <-Srv.Store.Preference().Delete(userId, preference.Category, preference.Name); result.Err != nil { + if result := <-a.Srv.Store.Preference().Delete(userId, preference.Category, preference.Name); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return result.Err } diff --git a/app/reaction.go b/app/reaction.go index adb92476f..b6395745e 100644 --- a/app/reaction.go +++ b/app/reaction.go @@ -7,54 +7,54 @@ import ( "github.com/mattermost/platform/model" ) -func SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) { - post, err := GetSinglePost(reaction.PostId) +func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) { + post, err := a.GetSinglePost(reaction.PostId) if err != nil { return nil, err } - if result := <-Srv.Store.Reaction().Save(reaction); result.Err != nil { + if result := <-a.Srv.Store.Reaction().Save(reaction); result.Err != nil { return nil, result.Err } else { reaction = result.Data.(*model.Reaction) - go sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_ADDED, reaction, post) + go a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_ADDED, reaction, post) return reaction, nil } } -func GetReactionsForPost(postId string) ([]*model.Reaction, *model.AppError) { - if result := <-Srv.Store.Reaction().GetForPost(postId, true); result.Err != nil { +func (a *App) GetReactionsForPost(postId string) ([]*model.Reaction, *model.AppError) { + if result := <-a.Srv.Store.Reaction().GetForPost(postId, true); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Reaction), nil } } -func DeleteReactionForPost(reaction *model.Reaction) *model.AppError { - post, err := GetSinglePost(reaction.PostId) +func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError { + post, err := a.GetSinglePost(reaction.PostId) if err != nil { return err } - if result := <-Srv.Store.Reaction().Delete(reaction); result.Err != nil { + if result := <-a.Srv.Store.Reaction().Delete(reaction); result.Err != nil { return result.Err } else { - go sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_REMOVED, reaction, post) + go a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_REMOVED, reaction, post) } return nil } -func sendReactionEvent(event string, reaction *model.Reaction, post *model.Post) { +func (a *App) sendReactionEvent(event string, reaction *model.Reaction, post *model.Post) { // send out that a reaction has been added/removed message := model.NewWebSocketEvent(event, "", post.ChannelId, "", nil) message.Add("reaction", reaction.ToJson()) Publish(message) // The post is always modified since the UpdateAt always changes - InvalidateCacheForChannelPosts(post.ChannelId) + a.InvalidateCacheForChannelPosts(post.ChannelId) post.HasReactions = true post.UpdateAt = model.GetMillis() umessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_EDITED, "", post.ChannelId, "", nil) diff --git a/app/saml.go b/app/saml.go index 6b0966ebf..616765542 100644 --- a/app/saml.go +++ b/app/saml.go @@ -9,10 +9,11 @@ import ( "net/http" "os" + "path/filepath" + "github.com/mattermost/platform/einterfaces" "github.com/mattermost/platform/model" "github.com/mattermost/platform/utils" - "path/filepath" ) func GetSamlMetadata() (string, *model.AppError) { diff --git a/app/security_update_check.go b/app/security_update_check.go index 607dd1b8a..f735784b8 100644 --- a/app/security_update_check.go +++ b/app/security_update_check.go @@ -30,9 +30,9 @@ const ( PROP_SECURITY_UNIT_TESTS = "ut" ) -func DoSecurityUpdateCheck() { +func (a *App) DoSecurityUpdateCheck() { if *utils.Cfg.ServiceSettings.EnableSecurityFixAlert { - if result := <-Srv.Store.System().Get(); result.Err == nil { + if result := <-a.Srv.Store.System().Get(); result.Err == nil { props := result.Data.(model.StringMap) lastSecurityTime, _ := strconv.ParseInt(props[model.SYSTEM_LAST_SECURITY_TIME], 10, 0) currentTime := model.GetMillis() @@ -56,20 +56,20 @@ func DoSecurityUpdateCheck() { systemSecurityLastTime := &model.System{Name: model.SYSTEM_LAST_SECURITY_TIME, Value: strconv.FormatInt(currentTime, 10)} if lastSecurityTime == 0 { - <-Srv.Store.System().Save(systemSecurityLastTime) + <-a.Srv.Store.System().Save(systemSecurityLastTime) } else { - <-Srv.Store.System().Update(systemSecurityLastTime) + <-a.Srv.Store.System().Update(systemSecurityLastTime) } - if ucr := <-Srv.Store.User().GetTotalUsersCount(); ucr.Err == nil { + if ucr := <-a.Srv.Store.User().GetTotalUsersCount(); ucr.Err == nil { v.Set(PROP_SECURITY_USER_COUNT, strconv.FormatInt(ucr.Data.(int64), 10)) } - if ucr := <-Srv.Store.Status().GetTotalActiveUsersCount(); ucr.Err == nil { + if ucr := <-a.Srv.Store.Status().GetTotalActiveUsersCount(); ucr.Err == nil { v.Set(PROP_SECURITY_ACTIVE_USER_COUNT, strconv.FormatInt(ucr.Data.(int64), 10)) } - if tcr := <-Srv.Store.Team().AnalyticsTeamCount(); tcr.Err == nil { + if tcr := <-a.Srv.Store.Team().AnalyticsTeamCount(); tcr.Err == nil { v.Set(PROP_SECURITY_TEAM_COUNT, strconv.FormatInt(tcr.Data.(int64), 10)) } @@ -86,7 +86,7 @@ func DoSecurityUpdateCheck() { for _, bulletin := range bulletins { if bulletin.AppliesToVersion == model.CurrentVersion { if props["SecurityBulletin_"+bulletin.Id] == "" { - if results := <-Srv.Store.User().GetSystemAdminProfiles(); results.Err != nil { + if results := <-a.Srv.Store.User().GetSystemAdminProfiles(); results.Err != nil { l4g.Error(utils.T("mattermost.system_admins.error")) return } else { @@ -112,7 +112,7 @@ func DoSecurityUpdateCheck() { } bulletinSeen := &model.System{Name: "SecurityBulletin_" + bulletin.Id, Value: bulletin.Id} - <-Srv.Store.System().Save(bulletinSeen) + <-a.Srv.Store.System().Save(bulletinSeen) } } } diff --git a/app/server.go b/app/server.go index ebea049f3..387cdf5e9 100644 --- a/app/server.go +++ b/app/server.go @@ -80,16 +80,14 @@ func (cw *CorsWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) { const TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN = time.Second -var Srv *Server - -func NewServer() { +func (a *App) NewServer() { l4g.Info(utils.T("api.server.new_server.init.info")) - Srv = &Server{} + a.Srv = &Server{} } -func InitStores() { - Srv.Store = store.NewLayeredStore() +func (a *App) InitStores() { + a.Srv.Store = store.NewLayeredStore() } type VaryBy struct{} @@ -128,10 +126,10 @@ func redirectHTTPToHTTPS(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, url.String(), http.StatusFound) } -func StartServer() { +func (a *App) StartServer() { l4g.Info(utils.T("api.server.start_server.starting.info")) - var handler http.Handler = &CorsWrapper{Srv.Router} + var handler http.Handler = &CorsWrapper{a.Srv.Router} if *utils.Cfg.RateLimitSettings.Enable { l4g.Info(utils.T("api.server.start_server.rate.info")) @@ -165,7 +163,7 @@ func StartServer() { handler = httpRateLimiter.RateLimit(handler) } - Srv.GracefulServer = &graceful.Server{ + a.Srv.GracefulServer = &graceful.Server{ Timeout: TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN, Server: &http.Server{ Addr: *utils.Cfg.ServiceSettings.ListenAddress, @@ -190,7 +188,7 @@ func StartServer() { } if utils.IsLicensed() && *utils.License().Features.FutureFeatures && *utils.Cfg.PluginSettings.Enable { - StartupPlugins("plugins", "webapp/dist") + a.StartupPlugins("plugins", "webapp/dist") } go func() { @@ -206,12 +204,12 @@ func StartServer() { tlsConfig.NextProtos = append(tlsConfig.NextProtos, "h2") - err = Srv.GracefulServer.ListenAndServeTLSConfig(tlsConfig) + err = a.Srv.GracefulServer.ListenAndServeTLSConfig(tlsConfig) } else { - err = Srv.GracefulServer.ListenAndServeTLS(*utils.Cfg.ServiceSettings.TLSCertFile, *utils.Cfg.ServiceSettings.TLSKeyFile) + err = a.Srv.GracefulServer.ListenAndServeTLS(*utils.Cfg.ServiceSettings.TLSCertFile, *utils.Cfg.ServiceSettings.TLSKeyFile) } } else { - err = Srv.GracefulServer.ListenAndServe() + err = a.Srv.GracefulServer.ListenAndServe() } if err != nil { l4g.Critical(utils.T("api.server.start_server.starting.critical"), err) @@ -220,18 +218,18 @@ func StartServer() { }() } -func StopServer() { +func (a *App) StopServer() { l4g.Info(utils.T("api.server.stop_server.stopping.info")) - Srv.GracefulServer.Stop(TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN) - Srv.Store.Close() + a.Srv.GracefulServer.Stop(TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN) + a.Srv.Store.Close() HubStop() l4g.Info(utils.T("api.server.stop_server.stopped.info")) } -func StartupPlugins(pluginPath, webappPath string) { +func (a *App) StartupPlugins(pluginPath, webappPath string) { l4g.Info("Starting up plugins") err := os.Mkdir(pluginPath, 0744) @@ -244,7 +242,7 @@ func StartupPlugins(pluginPath, webappPath string) { } } - Srv.PluginEnv, err = pluginenv.New( + a.Srv.PluginEnv, err = pluginenv.New( pluginenv.SearchPath(pluginPath), pluginenv.WebappPath(webappPath), ) @@ -253,5 +251,5 @@ func StartupPlugins(pluginPath, webappPath string) { l4g.Error("failed to start up plugins: " + err.Error()) } - ActivatePlugins() + a.ActivatePlugins() } diff --git a/app/session.go b/app/session.go index 1a555b9cf..674a854a7 100644 --- a/app/session.go +++ b/app/session.go @@ -15,10 +15,10 @@ import ( var sessionCache *utils.Cache = utils.NewLru(model.SESSION_CACHE_SIZE) -func CreateSession(session *model.Session) (*model.Session, *model.AppError) { +func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppError) { session.Token = "" - if result := <-Srv.Store.Session().Save(session); result.Err != nil { + if result := <-a.Srv.Store.Session().Save(session); result.Err != nil { return nil, result.Err } else { session := result.Data.(*model.Session) @@ -29,7 +29,7 @@ func CreateSession(session *model.Session) (*model.Session, *model.AppError) { } } -func GetSession(token string) (*model.Session, *model.AppError) { +func (a *App) GetSession(token string) (*model.Session, *model.AppError) { metrics := einterfaces.GetMetricsInterface() var session *model.Session @@ -45,7 +45,7 @@ func GetSession(token string) (*model.Session, *model.AppError) { } if session == nil { - if sessionResult := <-Srv.Store.Session().Get(token); sessionResult.Err == nil { + if sessionResult := <-a.Srv.Store.Session().Get(token); sessionResult.Err == nil { session = sessionResult.Data.(*model.Session) if session != nil { @@ -62,7 +62,7 @@ func GetSession(token string) (*model.Session, *model.AppError) { if session == nil { var err *model.AppError - session, err = createSessionForUserAccessToken(token) + session, err = a.createSessionForUserAccessToken(token) if err != nil { return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token}, err.Error(), http.StatusUnauthorized) } @@ -75,25 +75,25 @@ func GetSession(token string) (*model.Session, *model.AppError) { return session, nil } -func GetSessions(userId string) ([]*model.Session, *model.AppError) { - if result := <-Srv.Store.Session().GetSessions(userId); result.Err != nil { +func (a *App) GetSessions(userId string) ([]*model.Session, *model.AppError) { + if result := <-a.Srv.Store.Session().GetSessions(userId); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Session), nil } } -func RevokeAllSessions(userId string) *model.AppError { - if result := <-Srv.Store.Session().GetSessions(userId); result.Err != nil { +func (a *App) RevokeAllSessions(userId string) *model.AppError { + if result := <-a.Srv.Store.Session().GetSessions(userId); result.Err != nil { return result.Err } else { sessions := result.Data.([]*model.Session) for _, session := range sessions { if session.IsOAuth { - RevokeAccessToken(session.Token) + a.RevokeAccessToken(session.Token) } else { - if result := <-Srv.Store.Session().Remove(session.Id); result.Err != nil { + if result := <-a.Srv.Store.Session().Remove(session.Id); result.Err != nil { return result.Err } } @@ -145,15 +145,15 @@ func SessionCacheLength() int { return sessionCache.Len() } -func RevokeSessionsForDeviceId(userId string, deviceId string, currentSessionId string) *model.AppError { - if result := <-Srv.Store.Session().GetSessions(userId); result.Err != nil { +func (a *App) RevokeSessionsForDeviceId(userId string, deviceId string, currentSessionId string) *model.AppError { + if result := <-a.Srv.Store.Session().GetSessions(userId); result.Err != nil { return result.Err } else { sessions := result.Data.([]*model.Session) for _, session := range sessions { if session.DeviceId == deviceId && session.Id != currentSessionId { l4g.Debug(utils.T("api.user.login.revoking.app_error"), session.Id, userId) - if err := RevokeSession(session); err != nil { + if err := a.RevokeSession(session); err != nil { // Soft error so we still remove the other sessions l4g.Error(err.Error()) } @@ -164,22 +164,22 @@ func RevokeSessionsForDeviceId(userId string, deviceId string, currentSessionId return nil } -func RevokeSessionById(sessionId string) *model.AppError { - if result := <-Srv.Store.Session().Get(sessionId); result.Err != nil { +func (a *App) RevokeSessionById(sessionId string) *model.AppError { + if result := <-a.Srv.Store.Session().Get(sessionId); result.Err != nil { result.Err.StatusCode = http.StatusBadRequest return result.Err } else { - return RevokeSession(result.Data.(*model.Session)) + return a.RevokeSession(result.Data.(*model.Session)) } } -func RevokeSession(session *model.Session) *model.AppError { +func (a *App) RevokeSession(session *model.Session) *model.AppError { if session.IsOAuth { - if err := RevokeAccessToken(session.Token); err != nil { + if err := a.RevokeAccessToken(session.Token); err != nil { return err } } else { - if result := <-Srv.Store.Session().Remove(session.Id); result.Err != nil { + if result := <-a.Srv.Store.Session().Remove(session.Id); result.Err != nil { return result.Err } } @@ -190,21 +190,21 @@ func RevokeSession(session *model.Session) *model.AppError { return nil } -func AttachDeviceId(sessionId string, deviceId string, expiresAt int64) *model.AppError { - if result := <-Srv.Store.Session().UpdateDeviceId(sessionId, deviceId, expiresAt); result.Err != nil { +func (a *App) AttachDeviceId(sessionId string, deviceId string, expiresAt int64) *model.AppError { + if result := <-a.Srv.Store.Session().UpdateDeviceId(sessionId, deviceId, expiresAt); result.Err != nil { return result.Err } return nil } -func UpdateLastActivityAtIfNeeded(session model.Session) { +func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) { now := model.GetMillis() if now-session.LastActivityAt < model.SESSION_ACTIVITY_TIMEOUT { return } - if result := <-Srv.Store.Session().UpdateLastActivityAt(session.Id, now); result.Err != nil { + if result := <-a.Srv.Store.Session().UpdateLastActivityAt(session.Id, now); result.Err != nil { l4g.Error(utils.T("api.status.last_activity.error"), session.UserId, session.Id) } @@ -212,16 +212,16 @@ func UpdateLastActivityAtIfNeeded(session model.Session) { AddSessionToCache(&session) } -func CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) { +func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableUserAccessTokens { return nil, model.NewAppError("CreateUserAccessToken", "app.user_access_token.disabled", nil, "", http.StatusNotImplemented) } token.Token = model.NewId() - uchan := Srv.Store.User().Get(token.UserId) + uchan := a.Srv.Store.User().Get(token.UserId) - if result := <-Srv.Store.UserAccessToken().Save(token); result.Err != nil { + if result := <-a.Srv.Store.UserAccessToken().Save(token); result.Err != nil { return nil, result.Err } else { token = result.Data.(*model.UserAccessToken) @@ -240,20 +240,20 @@ func CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken } -func createSessionForUserAccessToken(tokenString string) (*model.Session, *model.AppError) { +func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Session, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableUserAccessTokens { return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "EnableUserAccessTokens=false", http.StatusUnauthorized) } var token *model.UserAccessToken - if result := <-Srv.Store.UserAccessToken().GetByToken(tokenString); result.Err != nil { + if result := <-a.Srv.Store.UserAccessToken().GetByToken(tokenString); result.Err != nil { return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, result.Err.Error(), http.StatusUnauthorized) } else { token = result.Data.(*model.UserAccessToken) } var user *model.User - if result := <-Srv.Store.User().Get(token.UserId); result.Err != nil { + if result := <-a.Srv.Store.User().Get(token.UserId); result.Err != nil { return nil, result.Err } else { user = result.Data.(*model.User) @@ -274,7 +274,7 @@ func createSessionForUserAccessToken(tokenString string) (*model.Session, *model session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_USER_ACCESS_TOKEN) session.SetExpireInDays(model.SESSION_USER_ACCESS_TOKEN_EXPIRY) - if result := <-Srv.Store.Session().Save(session); result.Err != nil { + if result := <-a.Srv.Store.Session().Save(session); result.Err != nil { return nil, result.Err } else { session := result.Data.(*model.Session) @@ -285,13 +285,13 @@ func createSessionForUserAccessToken(tokenString string) (*model.Session, *model } } -func RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError { +func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError { var session *model.Session - if result := <-Srv.Store.Session().Get(token.Token); result.Err == nil { + if result := <-a.Srv.Store.Session().Get(token.Token); result.Err == nil { session = result.Data.(*model.Session) } - if result := <-Srv.Store.UserAccessToken().Delete(token.Id); result.Err != nil { + if result := <-a.Srv.Store.UserAccessToken().Delete(token.Id); result.Err != nil { return result.Err } @@ -299,11 +299,11 @@ func RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError { return nil } - return RevokeSession(session) + return a.RevokeSession(session) } -func GetUserAccessTokensForUser(userId string, page, perPage int) ([]*model.UserAccessToken, *model.AppError) { - if result := <-Srv.Store.UserAccessToken().GetByUser(userId, page*perPage, perPage); result.Err != nil { +func (a *App) GetUserAccessTokensForUser(userId string, page, perPage int) ([]*model.UserAccessToken, *model.AppError) { + if result := <-a.Srv.Store.UserAccessToken().GetByUser(userId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { tokens := result.Data.([]*model.UserAccessToken) @@ -315,8 +315,8 @@ func GetUserAccessTokensForUser(userId string, page, perPage int) ([]*model.User } } -func GetUserAccessToken(tokenId string, sanitize bool) (*model.UserAccessToken, *model.AppError) { - if result := <-Srv.Store.UserAccessToken().Get(tokenId); result.Err != nil { +func (a *App) GetUserAccessToken(tokenId string, sanitize bool) (*model.UserAccessToken, *model.AppError) { + if result := <-a.Srv.Store.UserAccessToken().Get(tokenId); result.Err != nil { return nil, result.Err } else { token := result.Data.(*model.UserAccessToken) diff --git a/app/session_test.go b/app/session_test.go index b3cd9fd57..edb4f987a 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -4,8 +4,9 @@ package app import ( - "github.com/mattermost/platform/model" "testing" + + "github.com/mattermost/platform/model" ) func TestCache(t *testing.T) { diff --git a/app/slackimport.go b/app/slackimport.go index 23dd37695..0ddf3b3e7 100644 --- a/app/slackimport.go +++ b/app/slackimport.go @@ -15,10 +15,11 @@ import ( "strings" "unicode/utf8" + "net/http" + l4g "github.com/alecthomas/log4go" "github.com/mattermost/platform/model" "github.com/mattermost/platform/utils" - "net/http" ) type SlackChannel struct { @@ -128,7 +129,7 @@ func SlackParsePosts(data io.Reader) ([]SlackPost, error) { return posts, nil } -func SlackAddUsers(teamId string, slackusers []SlackUser, log *bytes.Buffer) map[string]*model.User { +func (a *App) SlackAddUsers(teamId string, slackusers []SlackUser, log *bytes.Buffer) map[string]*model.User { // Log header log.WriteString(utils.T("api.slackimport.slack_add_users.created")) log.WriteString("===============\r\n\r\n") @@ -137,7 +138,7 @@ func SlackAddUsers(teamId string, slackusers []SlackUser, log *bytes.Buffer) map // Need the team var team *model.Team - if result := <-Srv.Store.Team().Get(teamId); result.Err != nil { + if result := <-a.Srv.Store.Team().Get(teamId); result.Err != nil { log.WriteString(utils.T("api.slackimport.slack_import.team_fail")) return addedUsers } else { @@ -164,10 +165,10 @@ func SlackAddUsers(teamId string, slackusers []SlackUser, log *bytes.Buffer) map password := model.NewId() // Check for email conflict and use existing user if found - if result := <-Srv.Store.User().GetByEmail(email); result.Err == nil { + if result := <-a.Srv.Store.User().GetByEmail(email); result.Err == nil { existingUser := result.Data.(*model.User) addedUsers[sUser.Id] = existingUser - if err := JoinUserToTeam(team, addedUsers[sUser.Id], ""); err != nil { + if err := a.JoinUserToTeam(team, addedUsers[sUser.Id], ""); err != nil { log.WriteString(utils.T("api.slackimport.slack_add_users.merge_existing_failed", map[string]interface{}{"Email": existingUser.Email, "Username": existingUser.Username})) } else { log.WriteString(utils.T("api.slackimport.slack_add_users.merge_existing", map[string]interface{}{"Email": existingUser.Email, "Username": existingUser.Username})) @@ -183,7 +184,7 @@ func SlackAddUsers(teamId string, slackusers []SlackUser, log *bytes.Buffer) map Password: password, } - if mUser := OldImportUser(team, &newUser); mUser != nil { + if mUser := a.OldImportUser(team, &newUser); mUser != nil { addedUsers[sUser.Id] = mUser log.WriteString(utils.T("api.slackimport.slack_add_users.email_pwd", map[string]interface{}{"Email": newUser.Email, "Password": password})) } else { @@ -194,9 +195,9 @@ func SlackAddUsers(teamId string, slackusers []SlackUser, log *bytes.Buffer) map return addedUsers } -func SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User { +func (a *App) SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User { var team *model.Team - if result := <-Srv.Store.Team().Get(teamId); result.Err != nil { + if result := <-a.Srv.Store.Team().Get(teamId); result.Err != nil { log.WriteString(utils.T("api.slackimport.slack_import.team_fail")) return nil } else { @@ -215,7 +216,7 @@ func SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User { Password: password, } - if mUser := OldImportUser(team, &botUser); mUser != nil { + if mUser := a.OldImportUser(team, &botUser); mUser != nil { log.WriteString(utils.T("api.slackimport.slack_add_bot_user.email_pwd", map[string]interface{}{"Email": botUser.Email, "Password": password})) return mUser } else { @@ -224,7 +225,7 @@ func SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User { } } -func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User) { +func (a *App) SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User) { for _, sPost := range posts { switch { case sPost.Type == "message" && (sPost.SubType == "" || sPost.SubType == "file_share"): @@ -242,14 +243,14 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use CreateAt: SlackConvertTimeStamp(sPost.TimeStamp), } if sPost.Upload { - if fileInfo, ok := SlackUploadFile(sPost, uploads, teamId, newPost.ChannelId, newPost.UserId); ok == true { + if fileInfo, ok := a.SlackUploadFile(sPost, uploads, teamId, newPost.ChannelId, newPost.UserId); ok == true { newPost.FileIds = append(newPost.FileIds, fileInfo.Id) newPost.Message = sPost.File.Title } } - OldImportPost(&newPost) + a.OldImportPost(&newPost) for _, fileId := range newPost.FileIds { - if result := <-Srv.Store.FileInfo().AttachToPost(fileId, newPost.Id); result.Err != nil { + if result := <-a.Srv.Store.FileInfo().AttachToPost(fileId, newPost.Id); result.Err != nil { l4g.Error(utils.T("api.slackimport.slack_add_posts.attach_files.error"), newPost.Id, newPost.FileIds, result.Err) } } @@ -271,7 +272,7 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use Message: sPost.Comment.Comment, CreateAt: SlackConvertTimeStamp(sPost.TimeStamp), } - OldImportPost(&newPost) + a.OldImportPost(&newPost) case sPost.Type == "message" && sPost.SubType == "bot_message": if botUser == nil { l4g.Warn(utils.T("api.slackimport.slack_add_posts.bot_user_no_exists.warn")) @@ -295,7 +296,7 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use Type: model.POST_SLACK_ATTACHMENT, } - OldImportIncomingWebhookPost(post, props) + a.OldImportIncomingWebhookPost(post, props) case sPost.Type == "message" && (sPost.SubType == "channel_join" || sPost.SubType == "channel_leave"): if sPost.User == "" { l4g.Debug(utils.T("api.slackimport.slack_add_posts.msg_no_usr.debug")) @@ -322,7 +323,7 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use "username": users[sPost.User].Username, }, } - OldImportPost(&newPost) + a.OldImportPost(&newPost) case sPost.Type == "message" && sPost.SubType == "me_message": if sPost.User == "" { l4g.Debug(utils.T("api.slackimport.slack_add_posts.without_user.debug")) @@ -337,7 +338,7 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use Message: "*" + sPost.Text + "*", CreateAt: SlackConvertTimeStamp(sPost.TimeStamp), } - OldImportPost(&newPost) + a.OldImportPost(&newPost) case sPost.Type == "message" && sPost.SubType == "channel_topic": if sPost.User == "" { l4g.Debug(utils.T("api.slackimport.slack_add_posts.msg_no_usr.debug")) @@ -353,7 +354,7 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use CreateAt: SlackConvertTimeStamp(sPost.TimeStamp), Type: model.POST_HEADER_CHANGE, } - OldImportPost(&newPost) + a.OldImportPost(&newPost) case sPost.Type == "message" && sPost.SubType == "channel_purpose": if sPost.User == "" { l4g.Debug(utils.T("api.slackimport.slack_add_posts.msg_no_usr.debug")) @@ -369,7 +370,7 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use CreateAt: SlackConvertTimeStamp(sPost.TimeStamp), Type: model.POST_PURPOSE_CHANGE, } - OldImportPost(&newPost) + a.OldImportPost(&newPost) case sPost.Type == "message" && sPost.SubType == "channel_name": if sPost.User == "" { l4g.Debug(utils.T("api.slackimport.slack_add_posts.msg_no_usr.debug")) @@ -385,14 +386,14 @@ func SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, use CreateAt: SlackConvertTimeStamp(sPost.TimeStamp), Type: model.POST_DISPLAYNAME_CHANGE, } - OldImportPost(&newPost) + a.OldImportPost(&newPost) default: l4g.Warn(utils.T("api.slackimport.slack_add_posts.unsupported.warn"), sPost.Type, sPost.SubType) } } } -func SlackUploadFile(sPost SlackPost, uploads map[string]*zip.File, teamId string, channelId string, userId string) (*model.FileInfo, bool) { +func (a *App) SlackUploadFile(sPost SlackPost, uploads map[string]*zip.File, teamId string, channelId string, userId string) (*model.FileInfo, bool) { if sPost.File != nil { if file, ok := uploads[sPost.File.Id]; ok == true { openFile, err := file.Open() @@ -403,7 +404,7 @@ func SlackUploadFile(sPost SlackPost, uploads map[string]*zip.File, teamId strin defer openFile.Close() timestamp := utils.TimeFromMillis(SlackConvertTimeStamp(sPost.TimeStamp)) - uploadedFile, err := OldImportFile(timestamp, openFile, teamId, channelId, userId, filepath.Base(file.Name)) + uploadedFile, err := a.OldImportFile(timestamp, openFile, teamId, channelId, userId, filepath.Base(file.Name)) if err != nil { l4g.Warn(utils.T("api.slackimport.slack_add_posts.upload_file_upload_failed.warn", map[string]interface{}{"FileId": sPost.File.Id, "Error": err.Error()})) return nil, false @@ -420,19 +421,19 @@ func SlackUploadFile(sPost SlackPost, uploads map[string]*zip.File, teamId strin } } -func deactivateSlackBotUser(user *model.User) { - _, err := UpdateActive(user, false) +func (a *App) deactivateSlackBotUser(user *model.User) { + _, err := a.UpdateActive(user, false) if err != nil { l4g.Warn(utils.T("api.slackimport.slack_deactivate_bot_user.failed_to_deactivate", err)) } } -func addSlackUsersToChannel(members []string, users map[string]*model.User, channel *model.Channel, log *bytes.Buffer) { +func (a *App) addSlackUsersToChannel(members []string, users map[string]*model.User, channel *model.Channel, log *bytes.Buffer) { for _, member := range members { if user, ok := users[member]; !ok { log.WriteString(utils.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]interface{}{"Username": "?"})) } else { - if _, err := AddUserToChannel(user, channel); err != nil { + if _, err := a.AddUserToChannel(user, channel); err != nil { log.WriteString(utils.T("api.slackimport.slack_add_channels.failed_to_add_user", map[string]interface{}{"Username": user.Username})) } } @@ -463,7 +464,7 @@ func SlackSanitiseChannelProperties(channel model.Channel) model.Channel { return channel } -func SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[string][]SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, log *bytes.Buffer) map[string]*model.Channel { +func (a *App) SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[string][]SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, log *bytes.Buffer) map[string]*model.Channel { // Write Header log.WriteString(utils.T("api.slackimport.slack_add_channels.added")) log.WriteString("=================\r\n\r\n") @@ -481,11 +482,11 @@ func SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[str newChannel = SlackSanitiseChannelProperties(newChannel) var mChannel *model.Channel - if result := <-Srv.Store.Channel().GetByName(teamId, sChannel.Name, true); result.Err == nil { + if result := <-a.Srv.Store.Channel().GetByName(teamId, sChannel.Name, true); result.Err == nil { // The channel already exists as an active channel. Merge with the existing one. mChannel = result.Data.(*model.Channel) log.WriteString(utils.T("api.slackimport.slack_add_channels.merge", map[string]interface{}{"DisplayName": newChannel.DisplayName})) - } else if result := <-Srv.Store.Channel().GetDeletedByName(teamId, sChannel.Name); result.Err == nil { + } else if result := <-a.Srv.Store.Channel().GetDeletedByName(teamId, sChannel.Name); result.Err == nil { // The channel already exists but has been deleted. Generate a random string for the handle instead. newChannel.Name = model.NewId() newChannel = SlackSanitiseChannelProperties(newChannel) @@ -493,7 +494,7 @@ func SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[str if mChannel == nil { // Haven't found an existing channel to merge with. Try importing it as a new one. - mChannel = OldImportChannel(&newChannel) + mChannel = a.OldImportChannel(&newChannel) if mChannel == nil { l4g.Warn(utils.T("api.slackimport.slack_add_channels.import_failed.warn"), newChannel.DisplayName) log.WriteString(utils.T("api.slackimport.slack_add_channels.import_failed", map[string]interface{}{"DisplayName": newChannel.DisplayName})) @@ -501,10 +502,10 @@ func SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[str } } - addSlackUsersToChannel(sChannel.Members, users, mChannel, log) + a.addSlackUsersToChannel(sChannel.Members, users, mChannel, log) log.WriteString(newChannel.DisplayName + "\r\n") addedChannels[sChannel.Id] = mChannel - SlackAddPosts(teamId, mChannel, posts[sChannel.Name], users, uploads, botUser) + a.SlackAddPosts(teamId, mChannel, posts[sChannel.Name], users, uploads, botUser) } return addedChannels @@ -625,7 +626,7 @@ func SlackConvertPostsMarkup(posts map[string][]SlackPost) map[string][]SlackPos return posts } -func SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { +func (a *App) SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) { // Create log file log := bytes.NewBufferString(utils.T("api.slackimport.slack_import.log")) @@ -669,16 +670,16 @@ func SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model posts = SlackConvertChannelMentions(channels, posts) posts = SlackConvertPostsMarkup(posts) - addedUsers := SlackAddUsers(teamID, users, log) - botUser := SlackAddBotUser(teamID, log) + addedUsers := a.SlackAddUsers(teamID, users, log) + botUser := a.SlackAddBotUser(teamID, log) - SlackAddChannels(teamID, channels, posts, addedUsers, uploads, botUser, log) + a.SlackAddChannels(teamID, channels, posts, addedUsers, uploads, botUser, log) if botUser != nil { - deactivateSlackBotUser(botUser) + a.deactivateSlackBotUser(botUser) } - InvalidateAllCaches() + a.InvalidateAllCaches() log.WriteString(utils.T("api.slackimport.slack_import.notes")) log.WriteString("=======\r\n\r\n") diff --git a/app/status.go b/app/status.go index 9f6ad2e05..8e721a907 100644 --- a/app/status.go +++ b/app/status.go @@ -57,7 +57,7 @@ func GetAllStatuses() map[string]*model.Status { return statusMap } -func GetStatusesByIds(userIds []string) (map[string]interface{}, *model.AppError) { +func (a *App) GetStatusesByIds(userIds []string) (map[string]interface{}, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableUserStatuses { return map[string]interface{}{}, nil } @@ -81,7 +81,7 @@ func GetStatusesByIds(userIds []string) (map[string]interface{}, *model.AppError } if len(missingUserIds) > 0 { - if result := <-Srv.Store.Status().GetByIds(missingUserIds); result.Err != nil { + if result := <-a.Srv.Store.Status().GetByIds(missingUserIds); result.Err != nil { return nil, result.Err } else { statuses := result.Data.([]*model.Status) @@ -104,7 +104,7 @@ func GetStatusesByIds(userIds []string) (map[string]interface{}, *model.AppError } //GetUserStatusesByIds used by apiV4 -func GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.AppError) { +func (a *App) GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableUserStatuses { return []*model.Status{}, nil } @@ -128,7 +128,7 @@ func GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.AppError) { } if len(missingUserIds) > 0 { - if result := <-Srv.Store.Status().GetByIds(missingUserIds); result.Err != nil { + if result := <-a.Srv.Store.Status().GetByIds(missingUserIds); result.Err != nil { return nil, result.Err } else { statuses := result.Data.([]*model.Status) @@ -161,7 +161,7 @@ func GetUserStatusesByIds(userIds []string) ([]*model.Status, *model.AppError) { return statusMap, nil } -func SetStatusOnline(userId string, sessionId string, manual bool) { +func (a *App) SetStatusOnline(userId string, sessionId string, manual bool) { if !*utils.Cfg.ServiceSettings.EnableUserStatuses { return } @@ -174,7 +174,7 @@ func SetStatusOnline(userId string, sessionId string, manual bool) { var status *model.Status var err *model.AppError - if status, err = GetStatus(userId); err != nil { + if status, err = a.GetStatus(userId); err != nil { status = &model.Status{UserId: userId, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} broadcast = true } else { @@ -203,9 +203,9 @@ func SetStatusOnline(userId string, sessionId string, manual bool) { var schan store.StoreChannel if broadcast { - schan = Srv.Store.Status().SaveOrUpdate(status) + schan = a.Srv.Store.Status().SaveOrUpdate(status) } else { - schan = Srv.Store.Status().UpdateLastActivityAt(status.UserId, status.LastActivityAt) + schan = a.Srv.Store.Status().UpdateLastActivityAt(status.UserId, status.LastActivityAt) } if result := <-schan; result.Err != nil { @@ -225,12 +225,12 @@ func BroadcastStatus(status *model.Status) { go Publish(event) } -func SetStatusOffline(userId string, manual bool) { +func (a *App) SetStatusOffline(userId string, manual bool) { if !*utils.Cfg.ServiceSettings.EnableUserStatuses { return } - status, err := GetStatus(userId) + status, err := a.GetStatus(userId) if err == nil && status.Manual && !manual { return // manually set status always overrides non-manual one } @@ -239,7 +239,7 @@ func SetStatusOffline(userId string, manual bool) { AddStatusCache(status) - if result := <-Srv.Store.Status().SaveOrUpdate(status); result.Err != nil { + if result := <-a.Srv.Store.Status().SaveOrUpdate(status); result.Err != nil { l4g.Error(utils.T("api.status.save_status.error"), userId, result.Err) } @@ -249,12 +249,12 @@ func SetStatusOffline(userId string, manual bool) { go Publish(event) } -func SetStatusAwayIfNeeded(userId string, manual bool) { +func (a *App) SetStatusAwayIfNeeded(userId string, manual bool) { if !*utils.Cfg.ServiceSettings.EnableUserStatuses { return } - status, err := GetStatus(userId) + status, err := a.GetStatus(userId) if err != nil { status = &model.Status{UserId: userId, Status: model.STATUS_OFFLINE, Manual: manual, LastActivityAt: 0, ActiveChannel: ""} @@ -280,7 +280,7 @@ func SetStatusAwayIfNeeded(userId string, manual bool) { AddStatusCache(status) - if result := <-Srv.Store.Status().SaveOrUpdate(status); result.Err != nil { + if result := <-a.Srv.Store.Status().SaveOrUpdate(status); result.Err != nil { l4g.Error(utils.T("api.status.save_status.error"), userId, result.Err) } @@ -301,7 +301,7 @@ func GetStatusFromCache(userId string) *model.Status { return nil } -func GetStatus(userId string) (*model.Status, *model.AppError) { +func (a *App) GetStatus(userId string) (*model.Status, *model.AppError) { if !*utils.Cfg.ServiceSettings.EnableUserStatuses { return &model.Status{}, nil } @@ -311,7 +311,7 @@ func GetStatus(userId string) (*model.Status, *model.AppError) { return status, nil } - if result := <-Srv.Store.Status().Get(userId); result.Err != nil { + if result := <-a.Srv.Store.Status().Get(userId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Status), nil diff --git a/app/team.go b/app/team.go index f06f8bafa..85e55131d 100644 --- a/app/team.go +++ b/app/team.go @@ -16,13 +16,13 @@ import ( "github.com/mattermost/platform/utils" ) -func CreateTeam(team *model.Team) (*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().Save(team); result.Err != nil { +func (a *App) CreateTeam(team *model.Team) (*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().Save(team); result.Err != nil { return nil, result.Err } else { rteam := result.Data.(*model.Team) - if _, err := CreateDefaultChannels(rteam.Id); err != nil { + if _, err := a.CreateDefaultChannels(rteam.Id); err != nil { return nil, err } @@ -30,10 +30,10 @@ func CreateTeam(team *model.Team) (*model.Team, *model.AppError) { } } -func CreateTeamWithUser(team *model.Team, userId string) (*model.Team, *model.AppError) { +func (a *App) CreateTeamWithUser(team *model.Team, userId string) (*model.Team, *model.AppError) { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return nil, err } else { team.Email = user.Email @@ -44,11 +44,11 @@ func CreateTeamWithUser(team *model.Team, userId string) (*model.Team, *model.Ap } var rteam *model.Team - if rteam, err = CreateTeam(team); err != nil { + if rteam, err = a.CreateTeam(team); err != nil { return nil, err } - if err = JoinUserToTeam(rteam, user, ""); err != nil { + if err = a.JoinUserToTeam(rteam, user, ""); err != nil { return nil, err } @@ -86,10 +86,10 @@ func isTeamEmailAllowed(user *model.User) bool { return isTeamEmailAddressAllowed(email) } -func UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { +func (a *App) UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { var oldTeam *model.Team var err *model.AppError - if oldTeam, err = GetTeam(team.Id); err != nil { + if oldTeam, err = a.GetTeam(team.Id); err != nil { return nil, err } @@ -100,7 +100,7 @@ func UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { oldTeam.CompanyName = team.CompanyName oldTeam.AllowedDomains = team.AllowedDomains - if result := <-Srv.Store.Team().Update(oldTeam); result.Err != nil { + if result := <-a.Srv.Store.Team().Update(oldTeam); result.Err != nil { return nil, result.Err } @@ -111,15 +111,15 @@ func UpdateTeam(team *model.Team) (*model.Team, *model.AppError) { return oldTeam, nil } -func PatchTeam(teamId string, patch *model.TeamPatch) (*model.Team, *model.AppError) { - team, err := GetTeam(teamId) +func (a *App) PatchTeam(teamId string, patch *model.TeamPatch) (*model.Team, *model.AppError) { + team, err := a.GetTeam(teamId) if err != nil { return nil, err } team.Patch(patch) - updatedTeam, err := UpdateTeam(team) + updatedTeam, err := a.UpdateTeam(team) if err != nil { return nil, err } @@ -137,9 +137,9 @@ func sendUpdatedTeamEvent(team *model.Team) { go Publish(message) } -func UpdateTeamMemberRoles(teamId string, userId string, newRoles string) (*model.TeamMember, *model.AppError) { +func (a *App) UpdateTeamMemberRoles(teamId string, userId string, newRoles string) (*model.TeamMember, *model.AppError) { var member *model.TeamMember - if result := <-Srv.Store.Team().GetTeamsForUser(userId); result.Err != nil { + if result := <-a.Srv.Store.Team().GetTeamsForUser(userId); result.Err != nil { return nil, result.Err } else { members := result.Data.([]*model.TeamMember) @@ -157,7 +157,7 @@ func UpdateTeamMemberRoles(teamId string, userId string, newRoles string) (*mode member.Roles = newRoles - if result := <-Srv.Store.Team().UpdateMember(member); result.Err != nil { + if result := <-a.Srv.Store.Team().UpdateMember(member); result.Err != nil { return nil, result.Err } @@ -175,9 +175,9 @@ func sendUpdatedMemberRoleEvent(userId string, member *model.TeamMember) { go Publish(message) } -func AddUserToTeam(teamId string, userId string, userRequestorId string) (*model.Team, *model.AppError) { - tchan := Srv.Store.Team().Get(teamId) - uchan := Srv.Store.User().Get(userId) +func (a *App) AddUserToTeam(teamId string, userId string, userRequestorId string) (*model.Team, *model.AppError) { + tchan := a.Srv.Store.Team().Get(teamId) + uchan := a.Srv.Store.User().Get(userId) var team *model.Team if result := <-tchan; result.Err != nil { @@ -193,22 +193,22 @@ func AddUserToTeam(teamId string, userId string, userRequestorId string) (*model user = result.Data.(*model.User) } - if err := JoinUserToTeam(team, user, userRequestorId); err != nil { + if err := a.JoinUserToTeam(team, user, userRequestorId); err != nil { return nil, err } return team, nil } -func AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppError { - if result := <-Srv.Store.Team().Get(teamId); result.Err != nil { +func (a *App) AddUserToTeamByTeamId(teamId string, user *model.User) *model.AppError { + if result := <-a.Srv.Store.Team().Get(teamId); result.Err != nil { return result.Err } else { - return JoinUserToTeam(result.Data.(*model.Team), user, "") + return a.JoinUserToTeam(result.Data.(*model.Team), user, "") } } -func AddUserToTeamByHash(userId string, hash string, data string) (*model.Team, *model.AppError) { +func (a *App) AddUserToTeamByHash(userId string, hash string, data string) (*model.Team, *model.AppError) { props := model.MapFromJson(strings.NewReader(data)) if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, utils.Cfg.EmailSettings.InviteSalt)) { @@ -220,8 +220,8 @@ func AddUserToTeamByHash(userId string, hash string, data string) (*model.Team, return nil, model.NewAppError("JoinUserToTeamByHash", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusBadRequest) } - tchan := Srv.Store.Team().Get(props["id"]) - uchan := Srv.Store.User().Get(userId) + tchan := a.Srv.Store.Team().Get(props["id"]) + uchan := a.Srv.Store.User().Get(userId) var team *model.Team if result := <-tchan; result.Err != nil { @@ -237,16 +237,16 @@ func AddUserToTeamByHash(userId string, hash string, data string) (*model.Team, user = result.Data.(*model.User) } - if err := JoinUserToTeam(team, user, ""); err != nil { + if err := a.JoinUserToTeam(team, user, ""); err != nil { return nil, err } return team, nil } -func AddUserToTeamByInviteId(inviteId string, userId string) (*model.Team, *model.AppError) { - tchan := Srv.Store.Team().GetByInviteId(inviteId) - uchan := Srv.Store.User().Get(userId) +func (a *App) AddUserToTeamByInviteId(inviteId string, userId string) (*model.Team, *model.AppError) { + tchan := a.Srv.Store.Team().GetByInviteId(inviteId) + uchan := a.Srv.Store.User().Get(userId) var team *model.Team if result := <-tchan; result.Err != nil { @@ -262,14 +262,14 @@ func AddUserToTeamByInviteId(inviteId string, userId string) (*model.Team, *mode user = result.Data.(*model.User) } - if err := JoinUserToTeam(team, user, ""); err != nil { + if err := a.JoinUserToTeam(team, user, ""); err != nil { return nil, err } return team, nil } -func joinUserToTeam(team *model.Team, user *model.User) (bool, *model.AppError) { +func (a *App) joinUserToTeam(team *model.Team, user *model.User) (bool, *model.AppError) { tm := &model.TeamMember{ TeamId: team.Id, UserId: user.Id, @@ -280,7 +280,7 @@ func joinUserToTeam(team *model.Team, user *model.User) (bool, *model.AppError) tm.Roles = model.ROLE_TEAM_USER.Id + " " + model.ROLE_TEAM_ADMIN.Id } - if etmr := <-Srv.Store.Team().GetMember(team.Id, user.Id); etmr.Err == nil { + if etmr := <-a.Srv.Store.Team().GetMember(team.Id, user.Id); etmr.Err == nil { // Membership alredy exists. Check if deleted and and update, otherwise do nothing rtm := etmr.Data.(*model.TeamMember) @@ -289,12 +289,12 @@ func joinUserToTeam(team *model.Team, user *model.User) (bool, *model.AppError) return true, nil } - if tmr := <-Srv.Store.Team().UpdateMember(tm); tmr.Err != nil { + if tmr := <-a.Srv.Store.Team().UpdateMember(tm); tmr.Err != nil { return false, tmr.Err } } else { // Membership appears to be missing. Lets try to add. - if tmr := <-Srv.Store.Team().SaveMember(tm); tmr.Err != nil { + if tmr := <-a.Srv.Store.Team().SaveMember(tm); tmr.Err != nil { return false, tmr.Err } } @@ -302,14 +302,14 @@ func joinUserToTeam(team *model.Team, user *model.User) (bool, *model.AppError) return false, nil } -func JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) *model.AppError { - if alreadyAdded, err := joinUserToTeam(team, user); err != nil { +func (a *App) JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) *model.AppError { + if alreadyAdded, err := a.joinUserToTeam(team, user); err != nil { return err } else if alreadyAdded { return nil } - if uua := <-Srv.Store.User().UpdateUpdateAt(user.Id); uua.Err != nil { + if uua := <-a.Srv.Store.User().UpdateUpdateAt(user.Id); uua.Err != nil { return uua.Err } @@ -320,12 +320,12 @@ func JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) } // Soft error if there is an issue joining the default channels - if err := JoinDefaultChannels(team.Id, user, channelRole, userRequestorId); err != nil { + if err := a.JoinDefaultChannels(team.Id, user, channelRole, userRequestorId); err != nil { l4g.Error(utils.T("api.user.create_user.joining.error"), user.Id, team.Id, err) } ClearSessionCacheForUser(user.Id) - InvalidateCacheForUser(user.Id) + a.InvalidateCacheForUser(user.Id) message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ADDED_TO_TEAM, "", "", user.Id, nil) message.Add("team_id", team.Id) @@ -335,16 +335,16 @@ func JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) return nil } -func GetTeam(teamId string) (*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().Get(teamId); result.Err != nil { +func (a *App) GetTeam(teamId string) (*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().Get(teamId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Team), nil } } -func GetTeamByName(name string) (*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().GetByName(name); result.Err != nil { +func (a *App) GetTeamByName(name string) (*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().GetByName(name); result.Err != nil { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else { @@ -352,110 +352,110 @@ func GetTeamByName(name string) (*model.Team, *model.AppError) { } } -func GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().GetByInviteId(inviteId); result.Err != nil { +func (a *App) GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().GetByInviteId(inviteId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.Team), nil } } -func GetAllTeams() ([]*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().GetAll(); result.Err != nil { +func (a *App) GetAllTeams() ([]*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().GetAll(); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Team), nil } } -func GetAllTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().GetAllPage(offset, limit); result.Err != nil { +func (a *App) GetAllTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().GetAllPage(offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Team), nil } } -func GetAllOpenTeams() ([]*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().GetAllTeamListing(); result.Err != nil { +func (a *App) GetAllOpenTeams() ([]*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().GetAllTeamListing(); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Team), nil } } -func SearchAllTeams(term string) ([]*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().SearchAll(term); result.Err != nil { +func (a *App) SearchAllTeams(term string) ([]*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().SearchAll(term); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Team), nil } } -func SearchOpenTeams(term string) ([]*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().SearchOpen(term); result.Err != nil { +func (a *App) SearchOpenTeams(term string) ([]*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().SearchOpen(term); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Team), nil } } -func GetAllOpenTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().GetAllTeamPageListing(offset, limit); result.Err != nil { +func (a *App) GetAllOpenTeamsPage(offset int, limit int) ([]*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().GetAllTeamPageListing(offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Team), nil } } -func GetTeamsForUser(userId string) ([]*model.Team, *model.AppError) { - if result := <-Srv.Store.Team().GetTeamsByUserId(userId); result.Err != nil { +func (a *App) GetTeamsForUser(userId string) ([]*model.Team, *model.AppError) { + if result := <-a.Srv.Store.Team().GetTeamsByUserId(userId); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.Team), nil } } -func GetTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) { - if result := <-Srv.Store.Team().GetMember(teamId, userId); result.Err != nil { +func (a *App) GetTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) { + if result := <-a.Srv.Store.Team().GetMember(teamId, userId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.TeamMember), nil } } -func GetTeamMembersForUser(userId string) ([]*model.TeamMember, *model.AppError) { - if result := <-Srv.Store.Team().GetTeamsForUser(userId); result.Err != nil { +func (a *App) GetTeamMembersForUser(userId string) ([]*model.TeamMember, *model.AppError) { + if result := <-a.Srv.Store.Team().GetTeamsForUser(userId); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.TeamMember), nil } } -func GetTeamMembers(teamId string, offset int, limit int) ([]*model.TeamMember, *model.AppError) { - if result := <-Srv.Store.Team().GetMembers(teamId, offset, limit); result.Err != nil { +func (a *App) GetTeamMembers(teamId string, offset int, limit int) ([]*model.TeamMember, *model.AppError) { + if result := <-a.Srv.Store.Team().GetMembers(teamId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.TeamMember), nil } } -func GetTeamMembersByIds(teamId string, userIds []string) ([]*model.TeamMember, *model.AppError) { - if result := <-Srv.Store.Team().GetMembersByIds(teamId, userIds); result.Err != nil { +func (a *App) GetTeamMembersByIds(teamId string, userIds []string) ([]*model.TeamMember, *model.AppError) { + if result := <-a.Srv.Store.Team().GetMembersByIds(teamId, userIds); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.TeamMember), nil } } -func AddTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) { - if _, err := AddUserToTeam(teamId, userId, ""); err != nil { +func (a *App) AddTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) { + if _, err := a.AddUserToTeam(teamId, userId, ""); err != nil { return nil, err } var teamMember *model.TeamMember var err *model.AppError - if teamMember, err = GetTeamMember(teamId, userId); err != nil { + if teamMember, err = a.GetTeamMember(teamId, userId); err != nil { return nil, err } @@ -467,15 +467,15 @@ func AddTeamMember(teamId, userId string) (*model.TeamMember, *model.AppError) { return teamMember, nil } -func AddTeamMembers(teamId string, userIds []string, userRequestorId string) ([]*model.TeamMember, *model.AppError) { +func (a *App) AddTeamMembers(teamId string, userIds []string, userRequestorId string) ([]*model.TeamMember, *model.AppError) { var members []*model.TeamMember for _, userId := range userIds { - if _, err := AddUserToTeam(teamId, userId, userRequestorId); err != nil { + if _, err := a.AddUserToTeam(teamId, userId, userRequestorId); err != nil { return nil, err } - if teamMember, err := GetTeamMember(teamId, userId); err != nil { + if teamMember, err := a.GetTeamMember(teamId, userId); err != nil { return nil, err } else { members = append(members, teamMember) @@ -490,38 +490,38 @@ func AddTeamMembers(teamId string, userIds []string, userRequestorId string) ([] return members, nil } -func AddTeamMemberByHash(userId, hash, data string) (*model.TeamMember, *model.AppError) { +func (a *App) AddTeamMemberByHash(userId, hash, data string) (*model.TeamMember, *model.AppError) { var team *model.Team var err *model.AppError - if team, err = AddUserToTeamByHash(userId, hash, data); err != nil { + if team, err = a.AddUserToTeamByHash(userId, hash, data); err != nil { return nil, err } - if teamMember, err := GetTeamMember(team.Id, userId); err != nil { + if teamMember, err := a.GetTeamMember(team.Id, userId); err != nil { return nil, err } else { return teamMember, nil } } -func AddTeamMemberByInviteId(inviteId, userId string) (*model.TeamMember, *model.AppError) { +func (a *App) AddTeamMemberByInviteId(inviteId, userId string) (*model.TeamMember, *model.AppError) { var team *model.Team var err *model.AppError - if team, err = AddUserToTeamByInviteId(inviteId, userId); err != nil { + if team, err = a.AddUserToTeamByInviteId(inviteId, userId); err != nil { return nil, err } - if teamMember, err := GetTeamMember(team.Id, userId); err != nil { + if teamMember, err := a.GetTeamMember(team.Id, userId); err != nil { return nil, err } else { return teamMember, nil } } -func GetTeamUnread(teamId, userId string) (*model.TeamUnread, *model.AppError) { - result := <-Srv.Store.Team().GetChannelUnreadsForTeam(teamId, userId) +func (a *App) GetTeamUnread(teamId, userId string) (*model.TeamUnread, *model.AppError) { + result := <-a.Srv.Store.Team().GetChannelUnreadsForTeam(teamId, userId) if result.Err != nil { return nil, result.Err } @@ -544,9 +544,9 @@ func GetTeamUnread(teamId, userId string) (*model.TeamUnread, *model.AppError) { return teamUnread, nil } -func RemoveUserFromTeam(teamId string, userId string) *model.AppError { - tchan := Srv.Store.Team().Get(teamId) - uchan := Srv.Store.User().Get(userId) +func (a *App) RemoveUserFromTeam(teamId string, userId string) *model.AppError { + tchan := a.Srv.Store.Team().Get(teamId) + uchan := a.Srv.Store.User().Get(userId) var team *model.Team if result := <-tchan; result.Err != nil { @@ -562,24 +562,24 @@ func RemoveUserFromTeam(teamId string, userId string) *model.AppError { user = result.Data.(*model.User) } - if err := LeaveTeam(team, user); err != nil { + if err := a.LeaveTeam(team, user); err != nil { return err } return nil } -func LeaveTeam(team *model.Team, user *model.User) *model.AppError { +func (a *App) LeaveTeam(team *model.Team, user *model.User) *model.AppError { var teamMember *model.TeamMember var err *model.AppError - if teamMember, err = GetTeamMember(team.Id, user.Id); err != nil { + if teamMember, err = a.GetTeamMember(team.Id, user.Id); err != nil { return model.NewAppError("LeaveTeam", "api.team.remove_user_from_team.missing.app_error", nil, err.Error(), http.StatusBadRequest) } var channelList *model.ChannelList - if result := <-Srv.Store.Channel().GetChannels(team.Id, user.Id); result.Err != nil { + if result := <-a.Srv.Store.Channel().GetChannels(team.Id, user.Id); result.Err != nil { if result.Err.Id == "store.sql_channel.get_channels.not_found.app_error" { channelList = &model.ChannelList{} } else { @@ -592,8 +592,8 @@ func LeaveTeam(team *model.Team, user *model.User) *model.AppError { for _, channel := range *channelList { if !channel.IsGroupOrDirect() { - InvalidateCacheForChannelMembers(channel.Id) - if result := <-Srv.Store.Channel().RemoveMember(channel.Id, user.Id); result.Err != nil { + a.InvalidateCacheForChannelMembers(channel.Id) + if result := <-a.Srv.Store.Channel().RemoveMember(channel.Id, user.Id); result.Err != nil { return result.Err } } @@ -608,26 +608,26 @@ func LeaveTeam(team *model.Team, user *model.User) *model.AppError { teamMember.Roles = "" teamMember.DeleteAt = model.GetMillis() - if result := <-Srv.Store.Team().UpdateMember(teamMember); result.Err != nil { + if result := <-a.Srv.Store.Team().UpdateMember(teamMember); result.Err != nil { return result.Err } - if uua := <-Srv.Store.User().UpdateUpdateAt(user.Id); uua.Err != nil { + if uua := <-a.Srv.Store.User().UpdateUpdateAt(user.Id); uua.Err != nil { return uua.Err } // delete the preferences that set the last channel used in the team and other team specific preferences - if result := <-Srv.Store.Preference().DeleteCategory(user.Id, team.Id); result.Err != nil { + if result := <-a.Srv.Store.Preference().DeleteCategory(user.Id, team.Id); result.Err != nil { return result.Err } ClearSessionCacheForUser(user.Id) - InvalidateCacheForUser(user.Id) + a.InvalidateCacheForUser(user.Id) return nil } -func InviteNewUsersToTeam(emailList []string, teamId, senderId string) *model.AppError { +func (a *App) InviteNewUsersToTeam(emailList []string, teamId, senderId string) *model.AppError { if len(emailList) == 0 { err := model.NewAppError("InviteNewUsersToTeam", "api.team.invite_members.no_one.app_error", nil, "", http.StatusBadRequest) return err @@ -647,8 +647,8 @@ func InviteNewUsersToTeam(emailList []string, teamId, senderId string) *model.Ap return err } - tchan := Srv.Store.Team().Get(teamId) - uchan := Srv.Store.User().Get(senderId) + tchan := a.Srv.Store.Team().Get(teamId) + uchan := a.Srv.Store.User().Get(senderId) var team *model.Team if result := <-tchan; result.Err != nil { @@ -670,16 +670,16 @@ func InviteNewUsersToTeam(emailList []string, teamId, senderId string) *model.Ap return nil } -func FindTeamByName(name string) bool { - if result := <-Srv.Store.Team().GetByName(name); result.Err != nil { +func (a *App) FindTeamByName(name string) bool { + if result := <-a.Srv.Store.Team().GetByName(name); result.Err != nil { return false } else { return true } } -func GetTeamsUnreadForUser(excludeTeamId string, userId string) ([]*model.TeamUnread, *model.AppError) { - if result := <-Srv.Store.Team().GetChannelUnreadsForAllTeams(excludeTeamId, userId); result.Err != nil { +func (a *App) GetTeamsUnreadForUser(excludeTeamId string, userId string) ([]*model.TeamUnread, *model.AppError) { + if result := <-a.Srv.Store.Team().GetChannelUnreadsForAllTeams(excludeTeamId, userId); result.Err != nil { return nil, result.Err } else { data := result.Data.([]*model.ChannelUnread) @@ -717,64 +717,64 @@ func GetTeamsUnreadForUser(excludeTeamId string, userId string) ([]*model.TeamUn } } -func PermanentDeleteTeamId(teamId string) *model.AppError { - team, err := GetTeam(teamId) +func (a *App) PermanentDeleteTeamId(teamId string) *model.AppError { + team, err := a.GetTeam(teamId) if err != nil { return err } - return PermanentDeleteTeam(team) + return a.PermanentDeleteTeam(team) } -func PermanentDeleteTeam(team *model.Team) *model.AppError { +func (a *App) PermanentDeleteTeam(team *model.Team) *model.AppError { team.DeleteAt = model.GetMillis() - if result := <-Srv.Store.Team().Update(team); result.Err != nil { + if result := <-a.Srv.Store.Team().Update(team); result.Err != nil { return result.Err } - if result := <-Srv.Store.Channel().GetTeamChannels(team.Id); result.Err != nil { + if result := <-a.Srv.Store.Channel().GetTeamChannels(team.Id); result.Err != nil { if result.Err.Id != "store.sql_channel.get_channels.not_found.app_error" { return result.Err } } else { channels := result.Data.(*model.ChannelList) for _, c := range *channels { - PermanentDeleteChannel(c) + a.PermanentDeleteChannel(c) } } - if result := <-Srv.Store.Team().RemoveAllMembersByTeam(team.Id); result.Err != nil { + if result := <-a.Srv.Store.Team().RemoveAllMembersByTeam(team.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Command().PermanentDeleteByTeam(team.Id); result.Err != nil { + if result := <-a.Srv.Store.Command().PermanentDeleteByTeam(team.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Team().PermanentDelete(team.Id); result.Err != nil { + if result := <-a.Srv.Store.Team().PermanentDelete(team.Id); result.Err != nil { return result.Err } return nil } -func SoftDeleteTeam(teamId string) *model.AppError { - team, err := GetTeam(teamId) +func (a *App) SoftDeleteTeam(teamId string) *model.AppError { + team, err := a.GetTeam(teamId) if err != nil { return err } team.DeleteAt = model.GetMillis() - if result := <-Srv.Store.Team().Update(team); result.Err != nil { + if result := <-a.Srv.Store.Team().Update(team); result.Err != nil { return result.Err } return nil } -func GetTeamStats(teamId string) (*model.TeamStats, *model.AppError) { - tchan := Srv.Store.Team().GetTotalMemberCount(teamId) - achan := Srv.Store.Team().GetActiveMemberCount(teamId) +func (a *App) GetTeamStats(teamId string) (*model.TeamStats, *model.AppError) { + tchan := a.Srv.Store.Team().GetTotalMemberCount(teamId) + achan := a.Srv.Store.Team().GetActiveMemberCount(teamId) stats := &model.TeamStats{} stats.TeamId = teamId @@ -794,7 +794,7 @@ func GetTeamStats(teamId string) (*model.TeamStats, *model.AppError) { return stats, nil } -func GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { +func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { hash := query.Get("h") inviteId := query.Get("id") @@ -813,7 +813,7 @@ func GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { return props["id"], nil } else if len(inviteId) > 0 { - if result := <-Srv.Store.Team().GetByInviteId(inviteId); result.Err != nil { + if result := <-a.Srv.Store.Team().GetByInviteId(inviteId); result.Err != nil { // soft fail, so we still create user but don't auto-join team l4g.Error("%v", result.Err) } else { diff --git a/app/team_test.go b/app/team_test.go index 4e0ea82f5..ecbcdfb03 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -11,7 +11,8 @@ import ( ) func TestCreateTeam(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() id := model.NewId() team := &model.Team{ @@ -21,18 +22,19 @@ func TestCreateTeam(t *testing.T) { Type: model.TEAM_OPEN, } - if _, err := CreateTeam(team); err != nil { + if _, err := a.CreateTeam(team); err != nil { t.Log(err) t.Fatal("Should create a new team") } - if _, err := CreateTeam(th.BasicTeam); err == nil { + if _, err := a.CreateTeam(th.BasicTeam); err == nil { t.Fatal("Should not create a new team - team already exist") } } func TestCreateTeamWithUser(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() id := model.NewId() team := &model.Team{ @@ -42,17 +44,17 @@ func TestCreateTeamWithUser(t *testing.T) { Type: model.TEAM_OPEN, } - if _, err := CreateTeamWithUser(team, th.BasicUser.Id); err != nil { + if _, err := a.CreateTeamWithUser(team, th.BasicUser.Id); err != nil { t.Log(err) t.Fatal("Should create a new team with existing user") } - if _, err := CreateTeamWithUser(team, model.NewId()); err == nil { + if _, err := a.CreateTeamWithUser(team, model.NewId()); err == nil { t.Fatal("Should not create a new team - user does not exist") } user := model.User{Email: strings.ToLower(model.NewId()) + "success+test", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := CreateUser(&user) + ruser, _ := a.CreateUser(&user) id = model.NewId() team2 := &model.Team{ @@ -63,7 +65,7 @@ func TestCreateTeamWithUser(t *testing.T) { } //Fail to create a team with user when user has set email without domain - if _, err := CreateTeamWithUser(team2, ruser.Id); err == nil { + if _, err := a.CreateTeamWithUser(team2, ruser.Id); err == nil { t.Log(err.Message) t.Fatal("Should not create a team with user when user has set email without domain") } else { @@ -75,11 +77,12 @@ func TestCreateTeamWithUser(t *testing.T) { } func TestUpdateTeam(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() th.BasicTeam.DisplayName = "Testing 123" - if updatedTeam, err := UpdateTeam(th.BasicTeam); err != nil { + if updatedTeam, err := a.UpdateTeam(th.BasicTeam); err != nil { t.Log(err) t.Fatal("Should update the team") } else { @@ -90,33 +93,36 @@ func TestUpdateTeam(t *testing.T) { } func TestAddUserToTeam(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := CreateUser(&user) + ruser, _ := a.CreateUser(&user) - if _, err := AddUserToTeam(th.BasicTeam.Id, ruser.Id, ""); err != nil { + if _, err := a.AddUserToTeam(th.BasicTeam.Id, ruser.Id, ""); err != nil { t.Log(err) t.Fatal("Should add user to the team") } } func TestAddUserToTeamByTeamId(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := CreateUser(&user) + ruser, _ := a.CreateUser(&user) - if err := AddUserToTeamByTeamId(th.BasicTeam.Id, ruser); err != nil { + if err := a.AddUserToTeamByTeamId(th.BasicTeam.Id, ruser); err != nil { t.Log(err) t.Fatal("Should add user to the team") } } func TestPermanentDeleteTeam(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() - team, err := CreateTeam(&model.Team{ + team, err := a.CreateTeam(&model.Team{ DisplayName: "deletion-test", Name: "deletion-test", Email: "foo@foo.com", @@ -126,10 +132,10 @@ func TestPermanentDeleteTeam(t *testing.T) { t.Fatal(err.Error()) } defer func() { - PermanentDeleteTeam(team) + a.PermanentDeleteTeam(team) }() - command, err := CreateCommand(&model.Command{ + command, err := a.CreateCommand(&model.Command{ CreatorId: th.BasicUser.Id, TeamId: team.Id, Trigger: "foo", @@ -139,37 +145,37 @@ func TestPermanentDeleteTeam(t *testing.T) { if err != nil { t.Fatal(err.Error()) } - defer DeleteCommand(command.Id) + defer a.DeleteCommand(command.Id) - if command, err = GetCommand(command.Id); command == nil || err != nil { + if command, err = a.GetCommand(command.Id); command == nil || err != nil { t.Fatal("unable to get new command") } - if err := PermanentDeleteTeam(team); err != nil { + if err := a.PermanentDeleteTeam(team); err != nil { t.Fatal(err.Error()) } - if command, err = GetCommand(command.Id); command != nil || err == nil { + if command, err = a.GetCommand(command.Id); command != nil || err == nil { t.Fatal("command wasn't deleted") } // Test deleting a team with no channels. team = th.CreateTeam() defer func() { - PermanentDeleteTeam(team) + a.PermanentDeleteTeam(team) }() - if channels, err := GetPublicChannelsForTeam(team.Id, 0, 1000); err != nil { + if channels, err := a.GetPublicChannelsForTeam(team.Id, 0, 1000); err != nil { t.Fatal(err) } else { for _, channel := range *channels { - if err2 := PermanentDeleteChannel(channel); err2 != nil { + if err2 := a.PermanentDeleteChannel(channel); err2 != nil { t.Fatal(err) } } } - if err := PermanentDeleteTeam(team); err != nil { + if err := a.PermanentDeleteTeam(team); err != nil { t.Fatal(err) } } diff --git a/app/user.go b/app/user.go index 8228c8518..1c728cf56 100644 --- a/app/user.go +++ b/app/user.go @@ -38,7 +38,7 @@ const ( IMAGE_PROFILE_PIXEL_DIMENSION = 128 ) -func CreateUserWithHash(user *model.User, hash string, data string) (*model.User, *model.AppError) { +func (a *App) CreateUserWithHash(user *model.User, hash string, data string) (*model.User, *model.AppError) { if err := IsUserSignUpAllowed(); err != nil { return nil, err } @@ -56,7 +56,7 @@ func CreateUserWithHash(user *model.User, hash string, data string) (*model.User teamId := props["id"] var team *model.Team - if result := <-Srv.Store.Team().Get(teamId); result.Err != nil { + if result := <-a.Srv.Store.Team().Get(teamId); result.Err != nil { return nil, result.Err } else { team = result.Data.(*model.Team) @@ -67,26 +67,26 @@ func CreateUserWithHash(user *model.User, hash string, data string) (*model.User var ruser *model.User var err *model.AppError - if ruser, err = CreateUser(user); err != nil { + if ruser, err = a.CreateUser(user); err != nil { return nil, err } - if err := JoinUserToTeam(team, ruser, ""); err != nil { + if err := a.JoinUserToTeam(team, ruser, ""); err != nil { return nil, err } - AddDirectChannels(team.Id, ruser) + a.AddDirectChannels(team.Id, ruser) return ruser, nil } -func CreateUserWithInviteId(user *model.User, inviteId string) (*model.User, *model.AppError) { +func (a *App) CreateUserWithInviteId(user *model.User, inviteId string) (*model.User, *model.AppError) { if err := IsUserSignUpAllowed(); err != nil { return nil, err } var team *model.Team - if result := <-Srv.Store.Team().GetByInviteId(inviteId); result.Err != nil { + if result := <-a.Srv.Store.Team().GetByInviteId(inviteId); result.Err != nil { return nil, result.Err } else { team = result.Data.(*model.Team) @@ -96,54 +96,54 @@ func CreateUserWithInviteId(user *model.User, inviteId string) (*model.User, *mo var ruser *model.User var err *model.AppError - if ruser, err = CreateUser(user); err != nil { + if ruser, err = a.CreateUser(user); err != nil { return nil, err } - if err := JoinUserToTeam(team, ruser, ""); err != nil { + if err := a.JoinUserToTeam(team, ruser, ""); err != nil { return nil, err } - AddDirectChannels(team.Id, ruser) + a.AddDirectChannels(team.Id, ruser) - if err := SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, utils.GetSiteURL()); err != nil { + if err := a.SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, utils.GetSiteURL()); err != nil { l4g.Error(err.Error()) } return ruser, nil } -func CreateUserAsAdmin(user *model.User) (*model.User, *model.AppError) { - ruser, err := CreateUser(user) +func (a *App) CreateUserAsAdmin(user *model.User) (*model.User, *model.AppError) { + ruser, err := a.CreateUser(user) if err != nil { return nil, err } - if err := SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, utils.GetSiteURL()); err != nil { + if err := a.SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, utils.GetSiteURL()); err != nil { l4g.Error(err.Error()) } return ruser, nil } -func CreateUserFromSignup(user *model.User) (*model.User, *model.AppError) { +func (a *App) CreateUserFromSignup(user *model.User) (*model.User, *model.AppError) { if err := IsUserSignUpAllowed(); err != nil { return nil, err } - if !IsFirstUserAccount() && !*utils.Cfg.TeamSettings.EnableOpenServer { + if !a.IsFirstUserAccount() && !*utils.Cfg.TeamSettings.EnableOpenServer { err := model.NewAppError("CreateUserFromSignup", "api.user.create_user.no_open_server", nil, "email="+user.Email, http.StatusForbidden) return nil, err } user.EmailVerified = false - ruser, err := CreateUser(user) + ruser, err := a.CreateUser(user) if err != nil { return nil, err } - if err := SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, utils.GetSiteURL()); err != nil { + if err := a.SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, utils.GetSiteURL()); err != nil { l4g.Error(err.Error()) } @@ -158,9 +158,9 @@ func IsUserSignUpAllowed() *model.AppError { return nil } -func IsFirstUserAccount() bool { +func (a *App) IsFirstUserAccount() bool { if SessionCacheLength() == 0 { - if cr := <-Srv.Store.User().GetTotalUsersCount(); cr.Err != nil { + if cr := <-a.Srv.Store.User().GetTotalUsersCount(); cr.Err != nil { l4g.Error(cr.Err) return false } else { @@ -174,7 +174,7 @@ func IsFirstUserAccount() bool { return false } -func CreateUser(user *model.User) (*model.User, *model.AppError) { +func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) { if !user.IsLDAPUser() && !user.IsSAMLUser() && !CheckUserDomain(user, utils.Cfg.TeamSettings.RestrictCreationToDomains) { return nil, model.NewAppError("CreateUser", "api.user.create_user.accepted_domain.app_error", nil, "", http.StatusBadRequest) } @@ -183,7 +183,7 @@ func CreateUser(user *model.User) (*model.User, *model.AppError) { // Below is a special case where the first user in the entire // system is granted the system_admin role - if result := <-Srv.Store.User().GetTotalUsersCount(); result.Err != nil { + if result := <-a.Srv.Store.User().GetTotalUsersCount(); result.Err != nil { return nil, result.Err } else { count := result.Data.(int64) @@ -196,7 +196,7 @@ func CreateUser(user *model.User) (*model.User, *model.AppError) { user.Locale = *utils.Cfg.LocalizationSettings.DefaultClientLocale } - if ruser, err := createUser(user); err != nil { + if ruser, err := a.createUser(user); err != nil { return nil, err } else { // This message goes to everyone, so the teamId, channelId and userId are irrelevant @@ -208,27 +208,27 @@ func CreateUser(user *model.User) (*model.User, *model.AppError) { } } -func createUser(user *model.User) (*model.User, *model.AppError) { +func (a *App) createUser(user *model.User) (*model.User, *model.AppError) { user.MakeNonNil() if err := utils.IsPasswordValid(user.Password); user.AuthService == "" && err != nil { return nil, err } - if result := <-Srv.Store.User().Save(user); result.Err != nil { + if result := <-a.Srv.Store.User().Save(user); result.Err != nil { l4g.Error(utils.T("api.user.create_user.save.error"), result.Err) return nil, result.Err } else { ruser := result.Data.(*model.User) if user.EmailVerified { - if err := VerifyUserEmail(ruser.Id); err != nil { + if err := a.VerifyUserEmail(ruser.Id); err != nil { l4g.Error(utils.T("api.user.create_user.verified.error"), err) } } pref := model.Preference{UserId: ruser.Id, Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, Name: ruser.Id, Value: "0"} - if presult := <-Srv.Store.Preference().Save(&model.Preferences{pref}); presult.Err != nil { + if presult := <-a.Srv.Store.Preference().Save(&model.Preferences{pref}); presult.Err != nil { l4g.Error(utils.T("api.user.create_user.tutorial.error"), presult.Err.Message) } @@ -238,7 +238,7 @@ func createUser(user *model.User) (*model.User, *model.AppError) { } } -func CreateOAuthUser(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) { +func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) { if !utils.Cfg.TeamSettings.EnableUserCreation { return nil, model.NewAppError("CreateOAuthUser", "api.user.create_user.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -255,13 +255,13 @@ func CreateOAuthUser(service string, userData io.Reader, teamId string) (*model. return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.create.app_error", map[string]interface{}{"Service": service}, "", http.StatusInternalServerError) } - suchan := Srv.Store.User().GetByAuth(user.AuthData, service) - euchan := Srv.Store.User().GetByEmail(user.Email) + suchan := a.Srv.Store.User().GetByAuth(user.AuthData, service) + euchan := a.Srv.Store.User().GetByEmail(user.Email) found := true count := 0 for found { - if found = IsUsernameTaken(user.Username); found { + if found = a.IsUsernameTaken(user.Username); found { user.Username = user.Username + strconv.Itoa(count) count += 1 } @@ -282,18 +282,18 @@ func CreateOAuthUser(service string, userData io.Reader, teamId string) (*model. user.EmailVerified = true - ruser, err := CreateUser(user) + ruser, err := a.CreateUser(user) if err != nil { return nil, err } if len(teamId) > 0 { - err = AddUserToTeamByTeamId(teamId, user) + err = a.AddUserToTeamByTeamId(teamId, user) if err != nil { return nil, err } - err = AddDirectChannels(teamId, user) + err = a.AddDirectChannels(teamId, user) if err != nil { l4g.Error(err.Error()) } @@ -320,29 +320,29 @@ func CheckUserDomain(user *model.User, domains string) bool { } // Check if the username is already used by another user. Return false if the username is invalid. -func IsUsernameTaken(name string) bool { +func (a *App) IsUsernameTaken(name string) bool { if !model.IsValidUsername(name) { return false } - if result := <-Srv.Store.User().GetByUsername(name); result.Err != nil { + if result := <-a.Srv.Store.User().GetByUsername(name); result.Err != nil { return false } return true } -func GetUser(userId string) (*model.User, *model.AppError) { - if result := <-Srv.Store.User().Get(userId); result.Err != nil { +func (a *App) GetUser(userId string) (*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().Get(userId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.User), nil } } -func GetUserByUsername(username string) (*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetByUsername(username); result.Err != nil && result.Err.Id == "store.sql_user.get_by_username.app_error" { +func (a *App) GetUserByUsername(username string) (*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetByUsername(username); result.Err != nil && result.Err.Id == "store.sql_user.get_by_username.app_error" { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else { @@ -350,9 +350,9 @@ func GetUserByUsername(username string) (*model.User, *model.AppError) { } } -func GetUserByEmail(email string) (*model.User, *model.AppError) { +func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetByEmail(email); result.Err != nil && result.Err.Id == "store.sql_user.missing_account.const" { + if result := <-a.Srv.Store.User().GetByEmail(email); result.Err != nil && result.Err.Id == "store.sql_user.missing_account.const" { result.Err.StatusCode = http.StatusNotFound return nil, result.Err } else if result.Err != nil { @@ -363,18 +363,18 @@ func GetUserByEmail(email string) (*model.User, *model.AppError) { } } -func GetUserByAuth(authData *string, authService string) (*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetByAuth(authData, authService); result.Err != nil { +func (a *App) GetUserByAuth(authData *string, authService string) (*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetByAuth(authData, authService); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.User), nil } } -func GetUserForLogin(loginId string, onlyLdap bool) (*model.User, *model.AppError) { +func (a *App) GetUserForLogin(loginId string, onlyLdap bool) (*model.User, *model.AppError) { ldapAvailable := *utils.Cfg.LdapSettings.Enable && einterfaces.GetLdapInterface() != nil && utils.IsLicensed() && *utils.License().Features.LDAP - if result := <-Srv.Store.User().GetForLogin( + if result := <-a.Srv.Store.User().GetForLogin( loginId, *utils.Cfg.EmailSettings.EnableSignInWithUsername && !onlyLdap, *utils.Cfg.EmailSettings.EnableSignInWithEmail && !onlyLdap, @@ -402,16 +402,16 @@ func GetUserForLogin(loginId string, onlyLdap bool) (*model.User, *model.AppErro } } -func GetUsers(offset int, limit int) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetAllProfiles(offset, limit); result.Err != nil { +func (a *App) GetUsers(offset int, limit int) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetAllProfiles(offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.User), nil } } -func GetUsersMap(offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { - users, err := GetUsers(offset, limit) +func (a *App) GetUsersMap(offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { + users, err := a.GetUsers(offset, limit) if err != nil { return nil, err } @@ -426,8 +426,8 @@ func GetUsersMap(offset int, limit int, asAdmin bool) (map[string]*model.User, * return userMap, nil } -func GetUsersPage(page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { - users, err := GetUsers(page*perPage, perPage) +func (a *App) GetUsersPage(page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { + users, err := a.GetUsers(page*perPage, perPage) if err != nil { return nil, err } @@ -435,28 +435,28 @@ func GetUsersPage(page int, perPage int, asAdmin bool) ([]*model.User, *model.Ap return sanitizeProfiles(users, asAdmin), nil } -func GetUsersEtag() string { - return (<-Srv.Store.User().GetEtagForAllProfiles()).Data.(string) +func (a *App) GetUsersEtag() string { + return (<-a.Srv.Store.User().GetEtagForAllProfiles()).Data.(string) } -func GetUsersInTeam(teamId string, offset int, limit int) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetProfiles(teamId, offset, limit); result.Err != nil { +func (a *App) GetUsersInTeam(teamId string, offset int, limit int) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetProfiles(teamId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.User), nil } } -func GetUsersNotInTeam(teamId string, offset int, limit int) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetProfilesNotInTeam(teamId, offset, limit); result.Err != nil { +func (a *App) GetUsersNotInTeam(teamId string, offset int, limit int) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetProfilesNotInTeam(teamId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.User), nil } } -func GetUsersInTeamMap(teamId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { - users, err := GetUsersInTeam(teamId, offset, limit) +func (a *App) GetUsersInTeamMap(teamId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { + users, err := a.GetUsersInTeam(teamId, offset, limit) if err != nil { return nil, err } @@ -471,8 +471,8 @@ func GetUsersInTeamMap(teamId string, offset int, limit int, asAdmin bool) (map[ return userMap, nil } -func GetUsersInTeamPage(teamId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { - users, err := GetUsersInTeam(teamId, page*perPage, perPage) +func (a *App) GetUsersInTeamPage(teamId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { + users, err := a.GetUsersInTeam(teamId, page*perPage, perPage) if err != nil { return nil, err } @@ -480,8 +480,8 @@ func GetUsersInTeamPage(teamId string, page int, perPage int, asAdmin bool) ([]* return sanitizeProfiles(users, asAdmin), nil } -func GetUsersNotInTeamPage(teamId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { - users, err := GetUsersNotInTeam(teamId, page*perPage, perPage) +func (a *App) GetUsersNotInTeamPage(teamId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { + users, err := a.GetUsersNotInTeam(teamId, page*perPage, perPage) if err != nil { return nil, err } @@ -489,24 +489,24 @@ func GetUsersNotInTeamPage(teamId string, page int, perPage int, asAdmin bool) ( return sanitizeProfiles(users, asAdmin), nil } -func GetUsersInTeamEtag(teamId string) string { - return (<-Srv.Store.User().GetEtagForProfiles(teamId)).Data.(string) +func (a *App) GetUsersInTeamEtag(teamId string) string { + return (<-a.Srv.Store.User().GetEtagForProfiles(teamId)).Data.(string) } -func GetUsersNotInTeamEtag(teamId string) string { - return (<-Srv.Store.User().GetEtagForProfilesNotInTeam(teamId)).Data.(string) +func (a *App) GetUsersNotInTeamEtag(teamId string) string { + return (<-a.Srv.Store.User().GetEtagForProfilesNotInTeam(teamId)).Data.(string) } -func GetUsersInChannel(channelId string, offset int, limit int) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetProfilesInChannel(channelId, offset, limit); result.Err != nil { +func (a *App) GetUsersInChannel(channelId string, offset int, limit int) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetProfilesInChannel(channelId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.User), nil } } -func GetUsersInChannelMap(channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { - users, err := GetUsersInChannel(channelId, offset, limit) +func (a *App) GetUsersInChannelMap(channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { + users, err := a.GetUsersInChannel(channelId, offset, limit) if err != nil { return nil, err } @@ -521,8 +521,8 @@ func GetUsersInChannelMap(channelId string, offset int, limit int, asAdmin bool) return userMap, nil } -func GetUsersInChannelPage(channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { - users, err := GetUsersInChannel(channelId, page*perPage, perPage) +func (a *App) GetUsersInChannelPage(channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { + users, err := a.GetUsersInChannel(channelId, page*perPage, perPage) if err != nil { return nil, err } @@ -530,16 +530,16 @@ func GetUsersInChannelPage(channelId string, page int, perPage int, asAdmin bool return sanitizeProfiles(users, asAdmin), nil } -func GetUsersNotInChannel(teamId string, channelId string, offset int, limit int) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetProfilesNotInChannel(teamId, channelId, offset, limit); result.Err != nil { +func (a *App) GetUsersNotInChannel(teamId string, channelId string, offset int, limit int) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetProfilesNotInChannel(teamId, channelId, offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.User), nil } } -func GetUsersNotInChannelMap(teamId string, channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { - users, err := GetUsersNotInChannel(teamId, channelId, offset, limit) +func (a *App) GetUsersNotInChannelMap(teamId string, channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) { + users, err := a.GetUsersNotInChannel(teamId, channelId, offset, limit) if err != nil { return nil, err } @@ -554,8 +554,8 @@ func GetUsersNotInChannelMap(teamId string, channelId string, offset int, limit return userMap, nil } -func GetUsersNotInChannelPage(teamId string, channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { - users, err := GetUsersNotInChannel(teamId, channelId, page*perPage, perPage) +func (a *App) GetUsersNotInChannelPage(teamId string, channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { + users, err := a.GetUsersNotInChannel(teamId, channelId, page*perPage, perPage) if err != nil { return nil, err } @@ -563,8 +563,8 @@ func GetUsersNotInChannelPage(teamId string, channelId string, page int, perPage return sanitizeProfiles(users, asAdmin), nil } -func GetUsersWithoutTeamPage(page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { - users, err := GetUsersWithoutTeam(page*perPage, perPage) +func (a *App) GetUsersWithoutTeamPage(page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) { + users, err := a.GetUsersWithoutTeam(page*perPage, perPage) if err != nil { return nil, err } @@ -572,16 +572,16 @@ func GetUsersWithoutTeamPage(page int, perPage int, asAdmin bool) ([]*model.User return sanitizeProfiles(users, asAdmin), nil } -func GetUsersWithoutTeam(offset int, limit int) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetProfilesWithoutTeam(offset, limit); result.Err != nil { +func (a *App) GetUsersWithoutTeam(offset int, limit int) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetProfilesWithoutTeam(offset, limit); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.User), nil } } -func GetUsersByIds(userIds []string, asAdmin bool) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetProfileByIds(userIds, true); result.Err != nil { +func (a *App) GetUsersByIds(userIds []string, asAdmin bool) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetProfileByIds(userIds, true); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -589,8 +589,8 @@ func GetUsersByIds(userIds []string, asAdmin bool) ([]*model.User, *model.AppErr } } -func GetUsersByUsernames(usernames []string, asAdmin bool) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().GetProfilesByUsernames(usernames, ""); result.Err != nil { +func (a *App) GetUsersByUsernames(usernames []string, asAdmin bool) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().GetProfilesByUsernames(usernames, ""); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -606,7 +606,7 @@ func sanitizeProfiles(users []*model.User, asAdmin bool) []*model.User { return users } -func GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppError) { +func (a *App) GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppError) { mfaInterface := einterfaces.GetMfaInterface() if mfaInterface == nil { return nil, model.NewAppError("generateMfaSecret", "api.user.generate_mfa_qr.not_available.app_error", nil, "", http.StatusNotImplemented) @@ -614,7 +614,7 @@ func GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppError) { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return nil, err } @@ -627,7 +627,7 @@ func GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppError) { return mfaSecret, nil } -func ActivateMfa(userId, token string) *model.AppError { +func (a *App) ActivateMfa(userId, token string) *model.AppError { mfaInterface := einterfaces.GetMfaInterface() if mfaInterface == nil { err := model.NewAppError("ActivateMfa", "api.user.update_mfa.not_available.app_error", nil, "", http.StatusNotImplemented) @@ -635,7 +635,7 @@ func ActivateMfa(userId, token string) *model.AppError { } var user *model.User - if result := <-Srv.Store.User().Get(userId); result.Err != nil { + if result := <-a.Srv.Store.User().Get(userId); result.Err != nil { return result.Err } else { user = result.Data.(*model.User) @@ -773,7 +773,7 @@ func GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) { return img, readFailed, nil } -func SetProfileImage(userId string, imageData *multipart.FileHeader) *model.AppError { +func (a *App) SetProfileImage(userId string, imageData *multipart.FileHeader) *model.AppError { file, err := imageData.Open() defer file.Close() if err != nil { @@ -817,11 +817,11 @@ func SetProfileImage(userId string, imageData *multipart.FileHeader) *model.AppE return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.upload_profile.app_error", nil, "", http.StatusInternalServerError) } - <-Srv.Store.User().UpdateLastPictureUpdate(userId) + <-a.Srv.Store.User().UpdateLastPictureUpdate(userId) - InvalidateCacheForUser(userId) + a.InvalidateCacheForUser(userId) - if user, err := GetUser(userId); err != nil { + if user, err := a.GetUser(userId); err != nil { l4g.Error(utils.T("api.user.get_me.getting.error"), userId) } else { options := utils.Cfg.GetSanitizeOptions() @@ -838,11 +838,11 @@ func SetProfileImage(userId string, imageData *multipart.FileHeader) *model.AppE return nil } -func UpdatePasswordAsUser(userId, currentPassword, newPassword string) *model.AppError { +func (a *App) UpdatePasswordAsUser(userId, currentPassword, newPassword string) *model.AppError { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return err } @@ -856,7 +856,7 @@ func UpdatePasswordAsUser(userId, currentPassword, newPassword string) *model.Ap return err } - if err := doubleCheckPassword(user, currentPassword); err != nil { + if err := a.doubleCheckPassword(user, currentPassword); err != nil { if err.Id == "api.user.check_user_password.invalid.app_error" { err = model.NewAppError("updatePassword", "api.user.update_password.incorrect.app_error", nil, "", http.StatusBadRequest) } @@ -865,17 +865,17 @@ func UpdatePasswordAsUser(userId, currentPassword, newPassword string) *model.Ap T := utils.GetUserTranslations(user.Locale) - if err := UpdatePasswordSendEmail(user, newPassword, T("api.user.update_password.menu")); err != nil { + if err := a.UpdatePasswordSendEmail(user, newPassword, T("api.user.update_password.menu")); err != nil { return err } return nil } -func UpdateActiveNoLdap(userId string, active bool) (*model.User, *model.AppError) { +func (a *App) UpdateActiveNoLdap(userId string, active bool) (*model.User, *model.AppError) { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return nil, err } @@ -885,26 +885,26 @@ func UpdateActiveNoLdap(userId string, active bool) (*model.User, *model.AppErro return nil, err } - return UpdateActive(user, active) + return a.UpdateActive(user, active) } -func UpdateActive(user *model.User, active bool) (*model.User, *model.AppError) { +func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.AppError) { if active { user.DeleteAt = 0 } else { user.DeleteAt = model.GetMillis() } - if result := <-Srv.Store.User().Update(user, true); result.Err != nil { + if result := <-a.Srv.Store.User().Update(user, true); result.Err != nil { return nil, result.Err } else { if user.DeleteAt > 0 { - if err := RevokeAllSessions(user.Id); err != nil { + if err := a.RevokeAllSessions(user.Id); err != nil { return nil, err } } - if extra := <-Srv.Store.Channel().ExtraUpdateByUser(user.Id, model.GetMillis()); extra.Err != nil { + if extra := <-a.Srv.Store.Channel().ExtraUpdateByUser(user.Id, model.GetMillis()); extra.Err != nil { return nil, extra.Err } @@ -914,7 +914,7 @@ func UpdateActive(user *model.User, active bool) (*model.User, *model.AppError) ruser.Sanitize(options) if !active { - SetStatusOffline(ruser.Id, false) + a.SetStatusOffline(ruser.Id, false) } return ruser, nil @@ -931,8 +931,8 @@ func SanitizeProfile(user *model.User, asAdmin bool) { user.SanitizeProfile(options) } -func UpdateUserAsUser(user *model.User, asAdmin bool) (*model.User, *model.AppError) { - updatedUser, err := UpdateUser(user, true) +func (a *App) UpdateUserAsUser(user *model.User, asAdmin bool) (*model.User, *model.AppError) { + updatedUser, err := a.UpdateUser(user, true) if err != nil { return nil, err } @@ -942,15 +942,15 @@ func UpdateUserAsUser(user *model.User, asAdmin bool) (*model.User, *model.AppEr return updatedUser, nil } -func PatchUser(userId string, patch *model.UserPatch, asAdmin bool) (*model.User, *model.AppError) { - user, err := GetUser(userId) +func (a *App) PatchUser(userId string, patch *model.UserPatch, asAdmin bool) (*model.User, *model.AppError) { + user, err := a.GetUser(userId) if err != nil { return nil, err } user.Patch(patch) - updatedUser, err := UpdateUser(user, true) + updatedUser, err := a.UpdateUser(user, true) if err != nil { return nil, err } @@ -970,8 +970,8 @@ func sendUpdatedUserEvent(user model.User, asAdmin bool) { go Publish(message) } -func UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) { - if result := <-Srv.Store.User().Update(user, false); result.Err != nil { +func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().Update(user, false); result.Err != nil { return nil, result.Err } else { rusers := result.Data.([2]*model.User) @@ -985,7 +985,7 @@ func UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.A }() if utils.Cfg.EmailSettings.RequireEmailVerification { - if err := SendEmailVerification(rusers[0]); err != nil { + if err := a.SendEmailVerification(rusers[0]); err != nil { l4g.Error(err.Error()) } } @@ -1000,32 +1000,32 @@ func UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.A } } - InvalidateCacheForUser(user.Id) + a.InvalidateCacheForUser(user.Id) return rusers[0], nil } } -func UpdateUserNotifyProps(userId string, props map[string]string) (*model.User, *model.AppError) { +func (a *App) UpdateUserNotifyProps(userId string, props map[string]string) (*model.User, *model.AppError) { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return nil, err } user.NotifyProps = props var ruser *model.User - if ruser, err = UpdateUser(user, true); err != nil { + if ruser, err = a.UpdateUser(user, true); err != nil { return nil, err } return ruser, nil } -func UpdateMfa(activate bool, userId, token string) *model.AppError { +func (a *App) UpdateMfa(activate bool, userId, token string) *model.AppError { if activate { - if err := ActivateMfa(userId, token); err != nil { + if err := a.ActivateMfa(userId, token); err != nil { return err } } else { @@ -1038,7 +1038,7 @@ func UpdateMfa(activate bool, userId, token string) *model.AppError { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { l4g.Error(err.Error()) return } @@ -1051,32 +1051,32 @@ func UpdateMfa(activate bool, userId, token string) *model.AppError { return nil } -func UpdatePasswordByUserIdSendEmail(userId, newPassword, method string) *model.AppError { +func (a *App) UpdatePasswordByUserIdSendEmail(userId, newPassword, method string) *model.AppError { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { return err } - return UpdatePasswordSendEmail(user, newPassword, method) + return a.UpdatePasswordSendEmail(user, newPassword, method) } -func UpdatePassword(user *model.User, newPassword string) *model.AppError { +func (a *App) UpdatePassword(user *model.User, newPassword string) *model.AppError { if err := utils.IsPasswordValid(newPassword); err != nil { return err } hashedPassword := model.HashPassword(newPassword) - if result := <-Srv.Store.User().UpdatePassword(user.Id, hashedPassword); result.Err != nil { + if result := <-a.Srv.Store.User().UpdatePassword(user.Id, hashedPassword); result.Err != nil { return model.NewAppError("UpdatePassword", "api.user.update_password.failed.app_error", nil, result.Err.Error(), http.StatusInternalServerError) } return nil } -func UpdatePasswordSendEmail(user *model.User, newPassword, method string) *model.AppError { - if err := UpdatePassword(user, newPassword); err != nil { +func (a *App) UpdatePasswordSendEmail(user *model.User, newPassword, method string) *model.AppError { + if err := a.UpdatePassword(user, newPassword); err != nil { return err } @@ -1089,10 +1089,10 @@ func UpdatePasswordSendEmail(user *model.User, newPassword, method string) *mode return nil } -func ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model.AppError { +func (a *App) ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model.AppError { var token *model.Token var err *model.AppError - if token, err = GetPasswordRecoveryToken(userSuppliedTokenString); err != nil { + if token, err = a.GetPasswordRecoveryToken(userSuppliedTokenString); err != nil { return err } else { if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME { @@ -1101,7 +1101,7 @@ func ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model. } var user *model.User - if user, err = GetUser(token.Extra); err != nil { + if user, err = a.GetUser(token.Extra); err != nil { return err } @@ -1111,21 +1111,21 @@ func ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model. T := utils.GetUserTranslations(user.Locale) - if err := UpdatePasswordSendEmail(user, newPassword, T("api.user.reset_password.method")); err != nil { + if err := a.UpdatePasswordSendEmail(user, newPassword, T("api.user.reset_password.method")); err != nil { return err } - if err := DeleteToken(token); err != nil { + if err := a.DeleteToken(token); err != nil { l4g.Error(err.Error()) } return nil } -func SendPasswordReset(email string, siteURL string) (bool, *model.AppError) { +func (a *App) SendPasswordReset(email string, siteURL string) (bool, *model.AppError) { var user *model.User var err *model.AppError - if user, err = GetUserByEmail(email); err != nil { + if user, err = a.GetUserByEmail(email); err != nil { return false, nil } @@ -1134,7 +1134,7 @@ func SendPasswordReset(email string, siteURL string) (bool, *model.AppError) { } var token *model.Token - if token, err = CreatePasswordRecoveryToken(user.Id); err != nil { + if token, err = a.CreatePasswordRecoveryToken(user.Id); err != nil { return false, err } @@ -1145,18 +1145,18 @@ func SendPasswordReset(email string, siteURL string) (bool, *model.AppError) { return true, nil } -func CreatePasswordRecoveryToken(userId string) (*model.Token, *model.AppError) { +func (a *App) CreatePasswordRecoveryToken(userId string) (*model.Token, *model.AppError) { token := model.NewToken(TOKEN_TYPE_PASSWORD_RECOVERY, userId) - if result := <-Srv.Store.Token().Save(token); result.Err != nil { + if result := <-a.Srv.Store.Token().Save(token); result.Err != nil { return nil, result.Err } return token, nil } -func GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) { - if result := <-Srv.Store.Token().GetByToken(token); result.Err != nil { +func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) { + if result := <-a.Srv.Store.Token().GetByToken(token); result.Err != nil { return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.invalid_link.app_error", nil, result.Err.Error(), http.StatusBadRequest) } else { token := result.Data.(*model.Token) @@ -1167,25 +1167,25 @@ func GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) { } } -func DeleteToken(token *model.Token) *model.AppError { - if result := <-Srv.Store.Token().Delete(token.Token); result.Err != nil { +func (a *App) DeleteToken(token *model.Token) *model.AppError { + if result := <-a.Srv.Store.Token().Delete(token.Token); result.Err != nil { return result.Err } return nil } -func UpdateUserRoles(userId string, newRoles string) (*model.User, *model.AppError) { +func (a *App) UpdateUserRoles(userId string, newRoles string) (*model.User, *model.AppError) { var user *model.User var err *model.AppError - if user, err = GetUser(userId); err != nil { + if user, err = a.GetUser(userId); err != nil { err.StatusCode = http.StatusBadRequest return nil, err } user.Roles = newRoles - uchan := Srv.Store.User().Update(user, true) - schan := Srv.Store.Session().UpdateRoles(user.Id, newRoles) + uchan := a.Srv.Store.User().Update(user, true) + schan := a.Srv.Store.Session().UpdateRoles(user.Id, newRoles) var ruser *model.User if result := <-uchan; result.Err != nil { @@ -1204,61 +1204,61 @@ func UpdateUserRoles(userId string, newRoles string) (*model.User, *model.AppErr return ruser, nil } -func PermanentDeleteUser(user *model.User) *model.AppError { +func (a *App) PermanentDeleteUser(user *model.User) *model.AppError { l4g.Warn(utils.T("api.user.permanent_delete_user.attempting.warn"), user.Email, user.Id) if user.IsInRole(model.ROLE_SYSTEM_ADMIN.Id) { l4g.Warn(utils.T("api.user.permanent_delete_user.system_admin.warn"), user.Email) } - if _, err := UpdateActive(user, false); err != nil { + if _, err := a.UpdateActive(user, false); err != nil { return err } - if result := <-Srv.Store.Session().PermanentDeleteSessionsByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Session().PermanentDeleteSessionsByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.UserAccessToken().DeleteAllForUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.UserAccessToken().DeleteAllForUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.OAuth().PermanentDeleteAuthDataByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.OAuth().PermanentDeleteAuthDataByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Webhook().PermanentDeleteIncomingByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Webhook().PermanentDeleteIncomingByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Webhook().PermanentDeleteOutgoingByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Webhook().PermanentDeleteOutgoingByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Command().PermanentDeleteByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Command().PermanentDeleteByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Preference().PermanentDeleteByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Preference().PermanentDeleteByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Channel().PermanentDeleteMembersByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Channel().PermanentDeleteMembersByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Post().PermanentDeleteByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Post().PermanentDeleteByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.User().PermanentDelete(user.Id); result.Err != nil { + if result := <-a.Srv.Store.User().PermanentDelete(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Audit().PermanentDeleteByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Audit().PermanentDeleteByUser(user.Id); result.Err != nil { return result.Err } - if result := <-Srv.Store.Team().RemoveAllMembersByUser(user.Id); result.Err != nil { + if result := <-a.Srv.Store.Team().RemoveAllMembersByUser(user.Id); result.Err != nil { return result.Err } @@ -1267,45 +1267,45 @@ func PermanentDeleteUser(user *model.User) *model.AppError { return nil } -func PermanentDeleteAllUsers() *model.AppError { - if result := <-Srv.Store.User().GetAll(); result.Err != nil { +func (a *App) PermanentDeleteAllUsers() *model.AppError { + if result := <-a.Srv.Store.User().GetAll(); result.Err != nil { return result.Err } else { users := result.Data.([]*model.User) for _, user := range users { - PermanentDeleteUser(user) + a.PermanentDeleteUser(user) } } return nil } -func SendEmailVerification(user *model.User) *model.AppError { - token, err := CreateVerifyEmailToken(user.Id) +func (a *App) SendEmailVerification(user *model.User) *model.AppError { + token, err := a.CreateVerifyEmailToken(user.Id) if err != nil { return err } - if _, err := GetStatus(user.Id); err != nil { + if _, err := a.GetStatus(user.Id); err != nil { return SendVerifyEmail(user.Email, user.Locale, utils.GetSiteURL(), token.Token) } else { return SendEmailChangeVerifyEmail(user.Email, user.Locale, utils.GetSiteURL(), token.Token) } } -func VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError { +func (a *App) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError { var token *model.Token var err *model.AppError - if token, err = GetVerifyEmailToken(userSuppliedTokenString); err != nil { + if token, err = a.GetVerifyEmailToken(userSuppliedTokenString); err != nil { return err } else { if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME { return model.NewAppError("resetPassword", "api.user.reset_password.link_expired.app_error", nil, "", http.StatusBadRequest) } - if err := VerifyUserEmail(token.Extra); err != nil { + if err := a.VerifyUserEmail(token.Extra); err != nil { return err } - if err := DeleteToken(token); err != nil { + if err := a.DeleteToken(token); err != nil { l4g.Error(err.Error()) } } @@ -1313,18 +1313,18 @@ func VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError { return nil } -func CreateVerifyEmailToken(userId string) (*model.Token, *model.AppError) { +func (a *App) CreateVerifyEmailToken(userId string) (*model.Token, *model.AppError) { token := model.NewToken(TOKEN_TYPE_VERIFY_EMAIL, userId) - if result := <-Srv.Store.Token().Save(token); result.Err != nil { + if result := <-a.Srv.Store.Token().Save(token); result.Err != nil { return nil, result.Err } return token, nil } -func GetVerifyEmailToken(token string) (*model.Token, *model.AppError) { - if result := <-Srv.Store.Token().GetByToken(token); result.Err != nil { +func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) { + if result := <-a.Srv.Store.Token().GetByToken(token); result.Err != nil { return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.bad_link.app_error", nil, result.Err.Error(), http.StatusBadRequest) } else { token := result.Data.(*model.Token) @@ -1335,30 +1335,30 @@ func GetVerifyEmailToken(token string) (*model.Token, *model.AppError) { } } -func VerifyUserEmail(userId string) *model.AppError { - if err := (<-Srv.Store.User().VerifyEmail(userId)).Err; err != nil { +func (a *App) VerifyUserEmail(userId string) *model.AppError { + if err := (<-a.Srv.Store.User().VerifyEmail(userId)).Err; err != nil { return err } return nil } -func SearchUsers(props *model.UserSearch, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { +func (a *App) SearchUsers(props *model.UserSearch, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { if props.WithoutTeam { - return SearchUsersWithoutTeam(props.Term, searchOptions, asAdmin) + return a.SearchUsersWithoutTeam(props.Term, searchOptions, asAdmin) } else if props.InChannelId != "" { - return SearchUsersInChannel(props.InChannelId, props.Term, searchOptions, asAdmin) + return a.SearchUsersInChannel(props.InChannelId, props.Term, searchOptions, asAdmin) } else if props.NotInChannelId != "" { - return SearchUsersNotInChannel(props.TeamId, props.NotInChannelId, props.Term, searchOptions, asAdmin) + return a.SearchUsersNotInChannel(props.TeamId, props.NotInChannelId, props.Term, searchOptions, asAdmin) } else if props.NotInTeamId != "" { - return SearchUsersNotInTeam(props.NotInTeamId, props.Term, searchOptions, asAdmin) + return a.SearchUsersNotInTeam(props.NotInTeamId, props.Term, searchOptions, asAdmin) } else { - return SearchUsersInTeam(props.TeamId, props.Term, searchOptions, asAdmin) + return a.SearchUsersInTeam(props.TeamId, props.Term, searchOptions, asAdmin) } } -func SearchUsersInChannel(channelId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().SearchInChannel(channelId, term, searchOptions); result.Err != nil { +func (a *App) SearchUsersInChannel(channelId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().SearchInChannel(channelId, term, searchOptions); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -1371,8 +1371,8 @@ func SearchUsersInChannel(channelId string, term string, searchOptions map[strin } } -func SearchUsersNotInChannel(teamId string, channelId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().SearchNotInChannel(teamId, channelId, term, searchOptions); result.Err != nil { +func (a *App) SearchUsersNotInChannel(teamId string, channelId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().SearchNotInChannel(teamId, channelId, term, searchOptions); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -1385,8 +1385,8 @@ func SearchUsersNotInChannel(teamId string, channelId string, term string, searc } } -func SearchUsersInTeam(teamId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().Search(teamId, term, searchOptions); result.Err != nil { +func (a *App) SearchUsersInTeam(teamId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().Search(teamId, term, searchOptions); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -1399,8 +1399,8 @@ func SearchUsersInTeam(teamId string, term string, searchOptions map[string]bool } } -func SearchUsersNotInTeam(notInTeamId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().SearchNotInTeam(notInTeamId, term, searchOptions); result.Err != nil { +func (a *App) SearchUsersNotInTeam(notInTeamId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().SearchNotInTeam(notInTeamId, term, searchOptions); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -1413,8 +1413,8 @@ func SearchUsersNotInTeam(notInTeamId string, term string, searchOptions map[str } } -func SearchUsersWithoutTeam(term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { - if result := <-Srv.Store.User().SearchWithoutTeam(term, searchOptions); result.Err != nil { +func (a *App) SearchUsersWithoutTeam(term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) { + if result := <-a.Srv.Store.User().SearchWithoutTeam(term, searchOptions); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -1427,9 +1427,9 @@ func SearchUsersWithoutTeam(term string, searchOptions map[string]bool, asAdmin } } -func AutocompleteUsersInChannel(teamId string, channelId string, term string, searchOptions map[string]bool, asAdmin bool) (*model.UserAutocompleteInChannel, *model.AppError) { - uchan := Srv.Store.User().SearchInChannel(channelId, term, searchOptions) - nuchan := Srv.Store.User().SearchNotInChannel(teamId, channelId, term, searchOptions) +func (a *App) AutocompleteUsersInChannel(teamId string, channelId string, term string, searchOptions map[string]bool, asAdmin bool) (*model.UserAutocompleteInChannel, *model.AppError) { + uchan := a.Srv.Store.User().SearchInChannel(channelId, term, searchOptions) + nuchan := a.Srv.Store.User().SearchNotInChannel(teamId, channelId, term, searchOptions) autocomplete := &model.UserAutocompleteInChannel{} @@ -1460,10 +1460,10 @@ func AutocompleteUsersInChannel(teamId string, channelId string, term string, se return autocomplete, nil } -func AutocompleteUsersInTeam(teamId string, term string, searchOptions map[string]bool, asAdmin bool) (*model.UserAutocompleteInTeam, *model.AppError) { +func (a *App) AutocompleteUsersInTeam(teamId string, term string, searchOptions map[string]bool, asAdmin bool) (*model.UserAutocompleteInTeam, *model.AppError) { autocomplete := &model.UserAutocompleteInTeam{} - if result := <-Srv.Store.User().Search(teamId, term, searchOptions); result.Err != nil { + if result := <-a.Srv.Store.User().Search(teamId, term, searchOptions); result.Err != nil { return nil, result.Err } else { users := result.Data.([]*model.User) @@ -1478,7 +1478,7 @@ func AutocompleteUsersInTeam(teamId string, term string, searchOptions map[strin return autocomplete, nil } -func UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string) *model.AppError { +func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string) *model.AppError { oauthUser := provider.GetUserFromJson(userData) if oauthUser == nil { @@ -1488,7 +1488,7 @@ func UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterf userAttrsChanged := false if oauthUser.Username != user.Username { - if existingUser, _ := GetUserByUsername(oauthUser.Username); existingUser == nil { + if existingUser, _ := a.GetUserByUsername(oauthUser.Username); existingUser == nil { user.Username = oauthUser.Username userAttrsChanged = true } @@ -1501,7 +1501,7 @@ func UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterf } if oauthUser.Email != user.Email { - if existingUser, _ := GetUserByEmail(oauthUser.Email); existingUser == nil { + if existingUser, _ := a.GetUserByEmail(oauthUser.Email); existingUser == nil { user.Email = oauthUser.Email userAttrsChanged = true } @@ -1509,12 +1509,12 @@ func UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterf if userAttrsChanged { var result store.StoreResult - if result = <-Srv.Store.User().Update(user, true); result.Err != nil { + if result = <-a.Srv.Store.User().Update(user, true); result.Err != nil { return result.Err } user = result.Data.([2]*model.User)[0] - InvalidateCacheForUser(user.Id) + a.InvalidateCacheForUser(user.Id) } return nil diff --git a/app/user_test.go b/app/user_test.go index 34ac46615..25d6ec92c 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -20,9 +20,10 @@ import ( ) func TestIsUsernameTaken(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() user := th.BasicUser - taken := IsUsernameTaken(user.Username) + taken := a.IsUsernameTaken(user.Username) if !taken { t.Logf("the username '%v' should be taken", user.Username) @@ -30,7 +31,7 @@ func TestIsUsernameTaken(t *testing.T) { } newUsername := "randomUsername" - taken = IsUsernameTaken(newUsername) + taken = a.IsUsernameTaken(newUsername) if taken { t.Logf("the username '%v' should not be taken", newUsername) @@ -39,7 +40,8 @@ func TestIsUsernameTaken(t *testing.T) { } func TestCheckUserDomain(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() user := th.BasicUser cases := []struct { @@ -65,12 +67,13 @@ func TestCheckUserDomain(t *testing.T) { } func TestCreateOAuthUser(t *testing.T) { - th := Setup().InitBasic() + a := Global() + th := a.Setup().InitBasic() r := rand.New(rand.NewSource(time.Now().UnixNano())) glUser := oauthgitlab.GitLabUser{Id: int64(r.Intn(1000)) + 1, Username: "o" + model.NewId(), Email: model.NewId() + "@simulator.amazonses.com", Name: "Joram Wilander"} json := glUser.ToJson() - user, err := CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) + user, err := a.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) if err != nil { t.Fatal(err) } @@ -79,7 +82,7 @@ func TestCreateOAuthUser(t *testing.T) { t.Fatal("usernames didn't match") } - PermanentDeleteUser(user) + a.PermanentDeleteUser(user) userCreation := utils.Cfg.TeamSettings.EnableUserCreation defer func() { @@ -87,7 +90,7 @@ func TestCreateOAuthUser(t *testing.T) { }() utils.Cfg.TeamSettings.EnableUserCreation = false - _, err = CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) + _, err = a.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) if err == nil { t.Fatal("should have failed - user creation disabled") } @@ -115,7 +118,8 @@ func TestCreateProfileImage(t *testing.T) { } func TestUpdateOAuthUserAttrs(t *testing.T) { - Setup() + a := Global() + a.Setup() id := model.NewId() id2 := model.NewId() gitlabProvider := einterfaces.GetOauthProvider("gitlab") @@ -138,7 +142,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Username != gitlabUserObj.Username { @@ -153,7 +157,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Username == gitlabUserObj.Username { @@ -169,7 +173,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Email != gitlabUserObj.Email { @@ -188,7 +192,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Email == gitlabUserObj.Email { @@ -203,7 +207,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.FirstName != "Updated" { @@ -217,7 +221,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.LastName != "Lastname" { @@ -227,7 +231,8 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { } func getUserFromDB(id string, t *testing.T) *model.User { - if user, err := GetUser(id); err != nil { + a := Global() + if user, err := a.GetUser(id); err != nil { t.Fatal("user is not found") return nil } else { @@ -246,6 +251,7 @@ func getGitlabUserPayload(gitlabUser oauthgitlab.GitLabUser, t *testing.T) []byt } func createGitlabUser(t *testing.T, email string, username string) (*model.User, oauthgitlab.GitLabUser) { + a := Global() r := rand.New(rand.NewSource(time.Now().UnixNano())) gitlabUserObj := oauthgitlab.GitLabUser{Id: int64(r.Intn(1000)) + 1, Username: username, Login: "user1", Email: email, Name: "Test User"} gitlabUser := getGitlabUserPayload(gitlabUserObj, t) @@ -253,7 +259,7 @@ func createGitlabUser(t *testing.T, email string, username string) (*model.User, var user *model.User var err *model.AppError - if user, err = CreateOAuthUser("gitlab", bytes.NewReader(gitlabUser), ""); err != nil { + if user, err = a.CreateOAuthUser("gitlab", bytes.NewReader(gitlabUser), ""); err != nil { t.Fatal("unable to create the user") } diff --git a/app/web_conn.go b/app/web_conn.go index f57d99cde..2f49ac1bd 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -42,11 +42,11 @@ type WebConn struct { Sequence int64 } -func NewWebConn(ws *websocket.Conn, session model.Session, t goi18n.TranslateFunc, locale string) *WebConn { +func (a *App) NewWebConn(ws *websocket.Conn, session model.Session, t goi18n.TranslateFunc, locale string) *WebConn { if len(session.UserId) > 0 { go func() { - SetStatusOnline(session.UserId, session.Id, false) - UpdateLastActivityAtIfNeeded(session) + a.SetStatusOnline(session.UserId, session.Id, false) + a.UpdateLastActivityAtIfNeeded(session) }() } @@ -103,7 +103,7 @@ func (c *WebConn) ReadPump() { c.WebSocket.SetPongHandler(func(string) error { c.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) if c.IsAuthenticated() { - go SetStatusAwayIfNeeded(c.UserId, false) + go Global().SetStatusAwayIfNeeded(c.UserId, false) } return nil }) @@ -120,7 +120,7 @@ func (c *WebConn) ReadPump() { return } else { - Srv.WebSocketRouter.ServeWebSocket(c, &req) + Global().Srv.WebSocketRouter.ServeWebSocket(c, &req) } } } @@ -231,7 +231,7 @@ func (webCon *WebConn) IsAuthenticated() bool { return false } - session, err := GetSession(webCon.GetSessionToken()) + session, err := Global().GetSession(webCon.GetSessionToken()) if err != nil { l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error()) webCon.SetSessionToken("") @@ -283,7 +283,7 @@ func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { } if webCon.AllChannelMembers == nil { - if result := <-Srv.Store.Channel().GetAllChannelMembersForUser(webCon.UserId, true); result.Err != nil { + if result := <-Global().Srv.Store.Channel().GetAllChannelMembersForUser(webCon.UserId, true); result.Err != nil { l4g.Error("webhub.shouldSendEvent: " + result.Err.Error()) return false } else { @@ -313,7 +313,7 @@ func (webCon *WebConn) IsMemberOfTeam(teamId string) bool { currentSession := webCon.GetSession() if currentSession == nil || len(currentSession.Token) == 0 { - session, err := GetSession(webCon.GetSessionToken()) + session, err := Global().GetSession(webCon.GetSessionToken()) if err != nil { l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error()) return false diff --git a/app/web_hub.go b/app/web_hub.go index 0faa5fc5b..fbb62c74c 100644 --- a/app/web_hub.go +++ b/app/web_hub.go @@ -176,9 +176,9 @@ func PublishSkipClusterSend(message *model.WebSocketEvent) { } } -func InvalidateCacheForChannel(channel *model.Channel) { - InvalidateCacheForChannelSkipClusterSend(channel.Id) - InvalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name) +func (a *App) InvalidateCacheForChannel(channel *model.Channel) { + a.InvalidateCacheForChannelSkipClusterSend(channel.Id) + a.InvalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name) if cluster := einterfaces.GetClusterInterface(); cluster != nil { msg := &model.ClusterMessage{ @@ -206,12 +206,12 @@ func InvalidateCacheForChannel(channel *model.Channel) { } } -func InvalidateCacheForChannelSkipClusterSend(channelId string) { - Srv.Store.Channel().InvalidateChannel(channelId) +func (a *App) InvalidateCacheForChannelSkipClusterSend(channelId string) { + a.Srv.Store.Channel().InvalidateChannel(channelId) } -func InvalidateCacheForChannelMembers(channelId string) { - InvalidateCacheForChannelMembersSkipClusterSend(channelId) +func (a *App) InvalidateCacheForChannelMembers(channelId string) { + a.InvalidateCacheForChannelMembersSkipClusterSend(channelId) if einterfaces.GetClusterInterface() != nil { msg := &model.ClusterMessage{ @@ -223,13 +223,13 @@ func InvalidateCacheForChannelMembers(channelId string) { } } -func InvalidateCacheForChannelMembersSkipClusterSend(channelId string) { - Srv.Store.User().InvalidateProfilesInChannelCache(channelId) - Srv.Store.Channel().InvalidateMemberCount(channelId) +func (a *App) InvalidateCacheForChannelMembersSkipClusterSend(channelId string) { + a.Srv.Store.User().InvalidateProfilesInChannelCache(channelId) + a.Srv.Store.Channel().InvalidateMemberCount(channelId) } -func InvalidateCacheForChannelMembersNotifyProps(channelId string) { - InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelId) +func (a *App) InvalidateCacheForChannelMembersNotifyProps(channelId string) { + a.InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelId) if einterfaces.GetClusterInterface() != nil { msg := &model.ClusterMessage{ @@ -241,20 +241,20 @@ func InvalidateCacheForChannelMembersNotifyProps(channelId string) { } } -func InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelId string) { - Srv.Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channelId) +func (a *App) InvalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelId string) { + a.Srv.Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channelId) } -func InvalidateCacheForChannelByNameSkipClusterSend(teamId, name string) { +func (a *App) InvalidateCacheForChannelByNameSkipClusterSend(teamId, name string) { if teamId == "" { teamId = "dm" } - Srv.Store.Channel().InvalidateChannelByName(teamId, name) + a.Srv.Store.Channel().InvalidateChannelByName(teamId, name) } -func InvalidateCacheForChannelPosts(channelId string) { - InvalidateCacheForChannelPostsSkipClusterSend(channelId) +func (a *App) InvalidateCacheForChannelPosts(channelId string) { + a.InvalidateCacheForChannelPostsSkipClusterSend(channelId) if einterfaces.GetClusterInterface() != nil { msg := &model.ClusterMessage{ @@ -266,12 +266,12 @@ func InvalidateCacheForChannelPosts(channelId string) { } } -func InvalidateCacheForChannelPostsSkipClusterSend(channelId string) { - Srv.Store.Post().InvalidateLastPostTimeCache(channelId) +func (a *App) InvalidateCacheForChannelPostsSkipClusterSend(channelId string) { + a.Srv.Store.Post().InvalidateLastPostTimeCache(channelId) } -func InvalidateCacheForUser(userId string) { - InvalidateCacheForUserSkipClusterSend(userId) +func (a *App) InvalidateCacheForUser(userId string) { + a.InvalidateCacheForUserSkipClusterSend(userId) if einterfaces.GetClusterInterface() != nil { msg := &model.ClusterMessage{ @@ -283,18 +283,18 @@ func InvalidateCacheForUser(userId string) { } } -func InvalidateCacheForUserSkipClusterSend(userId string) { - Srv.Store.Channel().InvalidateAllChannelMembersForUser(userId) - Srv.Store.User().InvalidateProfilesInChannelCacheByUser(userId) - Srv.Store.User().InvalidatProfileCacheForUser(userId) +func (a *App) InvalidateCacheForUserSkipClusterSend(userId string) { + a.Srv.Store.Channel().InvalidateAllChannelMembersForUser(userId) + a.Srv.Store.User().InvalidateProfilesInChannelCacheByUser(userId) + a.Srv.Store.User().InvalidatProfileCacheForUser(userId) if len(hubs) != 0 { GetHubForUserId(userId).InvalidateUser(userId) } } -func InvalidateCacheForWebhook(webhookId string) { - InvalidateCacheForWebhookSkipClusterSend(webhookId) +func (a *App) InvalidateCacheForWebhook(webhookId string) { + a.InvalidateCacheForWebhookSkipClusterSend(webhookId) if einterfaces.GetClusterInterface() != nil { msg := &model.ClusterMessage{ @@ -306,8 +306,8 @@ func InvalidateCacheForWebhook(webhookId string) { } } -func InvalidateCacheForWebhookSkipClusterSend(webhookId string) { - Srv.Store.Webhook().InvalidateWebhookCache(webhookId) +func (a *App) InvalidateCacheForWebhookSkipClusterSend(webhookId string) { + a.Srv.Store.Webhook().InvalidateWebhookCache(webhookId) } func InvalidateWebConnSessionCacheForUser(userId string) { @@ -398,7 +398,7 @@ func (h *Hub) Start() { } if !found { - go SetStatusOffline(userId, false) + go Global().SetStatusOffline(userId, false) } case userId := <-h.invalidateUser: diff --git a/app/webhook.go b/app/webhook.go index a22cc74c4..87797edb8 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -22,7 +22,7 @@ const ( TRIGGERWORDS_STARTS_WITH = 1 ) -func handleWebhookEvents(post *model.Post, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { +func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *model.Channel, user *model.User) *model.AppError { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil } @@ -31,7 +31,7 @@ func handleWebhookEvents(post *model.Post, team *model.Team, channel *model.Chan return nil } - hchan := Srv.Store.Webhook().GetOutgoingByTeam(team.Id, -1, -1) + hchan := a.Srv.Store.Webhook().GetOutgoingByTeam(team.Id, -1, -1) result := <-hchan if result.Err != nil { return result.Err @@ -80,13 +80,13 @@ func handleWebhookEvents(post *model.Post, team *model.Team, channel *model.Chan TriggerWord: triggerWord, FileIds: strings.Join(post.FileIds, ","), } - go TriggerWebhook(payload, hook, post, channel) + go a.TriggerWebhook(payload, hook, post, channel) } return nil } -func TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { +func (a *App) TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel) { var body io.Reader var contentType string if hook.ContentType == "application/json" { @@ -109,7 +109,7 @@ func TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingW respProps := model.MapFromJson(resp.Body) if text, ok := respProps["text"]; ok { - if _, err := CreateWebhookPost(hook.CreatorId, channel, text, respProps["username"], respProps["icon_url"], post.Props, post.Type); err != nil { + if _, err := a.CreateWebhookPost(hook.CreatorId, channel, text, respProps["username"], respProps["icon_url"], post.Props, post.Type); err != nil { l4g.Error(utils.T("api.post.handle_webhook_events_and_forget.create_post.error"), err) } } @@ -118,7 +118,7 @@ func TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingW } } -func CreateWebhookPost(userId string, channel *model.Channel, text, overrideUsername, overrideIconUrl string, props model.StringInterface, postType string) (*model.Post, *model.AppError) { +func (a *App) CreateWebhookPost(userId string, channel *model.Channel, text, overrideUsername, overrideIconUrl string, props model.StringInterface, postType string) (*model.Post, *model.AppError) { // parse links into Markdown format linkWithTextRegex := regexp.MustCompile(`<([^<\|]+)\|([^>]+)>`) text = linkWithTextRegex.ReplaceAllString(text, "[${2}](${1})") @@ -173,7 +173,7 @@ func CreateWebhookPost(userId string, channel *model.Channel, text, overrideUser post.UpdateAt = 0 post.CreateAt = 0 post.Message = txt - if _, err := CreatePostMissingChannel(post, false); err != nil { + if _, err := a.CreatePostMissingChannel(post, false); err != nil { return nil, model.NewAppError("CreateWebhookPost", "api.post.create_webhook_post.creating.app_error", nil, "err="+err.Message, http.StatusInternalServerError) } @@ -189,7 +189,7 @@ func CreateWebhookPost(userId string, channel *model.Channel, text, overrideUser return firstPost, nil } -func CreateIncomingWebhookForChannel(creatorId string, channel *model.Channel, hook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) { +func (a *App) CreateIncomingWebhookForChannel(creatorId string, channel *model.Channel, hook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("CreateIncomingWebhookForChannel", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -197,14 +197,14 @@ func CreateIncomingWebhookForChannel(creatorId string, channel *model.Channel, h hook.UserId = creatorId hook.TeamId = channel.TeamId - if result := <-Srv.Store.Webhook().SaveIncoming(hook); result.Err != nil { + if result := <-a.Srv.Store.Webhook().SaveIncoming(hook); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.IncomingWebhook), nil } } -func UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) { +func (a *App) UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) (*model.IncomingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("UpdateIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -216,70 +216,70 @@ func UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) (*model. updatedHook.TeamId = oldHook.TeamId updatedHook.DeleteAt = oldHook.DeleteAt - if result := <-Srv.Store.Webhook().UpdateIncoming(updatedHook); result.Err != nil { + if result := <-a.Srv.Store.Webhook().UpdateIncoming(updatedHook); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.IncomingWebhook), nil } } -func DeleteIncomingWebhook(hookId string) *model.AppError { +func (a *App) DeleteIncomingWebhook(hookId string) *model.AppError { if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { return model.NewAppError("DeleteIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().DeleteIncoming(hookId, model.GetMillis()); result.Err != nil { + if result := <-a.Srv.Store.Webhook().DeleteIncoming(hookId, model.GetMillis()); result.Err != nil { return result.Err } - InvalidateCacheForWebhook(hookId) + a.InvalidateCacheForWebhook(hookId) return nil } -func GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model.AppError) { +func (a *App) GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("GetIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().GetIncoming(hookId, true); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetIncoming(hookId, true); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.IncomingWebhook), nil } } -func GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { +func (a *App) GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("GetIncomingWebhooksForTeamPage", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().GetIncomingByTeam(teamId, page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetIncomingByTeam(teamId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.IncomingWebhook), nil } } -func GetIncomingWebhooksPage(page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { +func (a *App) GetIncomingWebhooksPage(page, perPage int) ([]*model.IncomingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { return nil, model.NewAppError("GetIncomingWebhooksPage", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().GetIncomingList(page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetIncomingList(page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.IncomingWebhook), nil } } -func CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { +func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("CreateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } if len(hook.ChannelId) != 0 { - cchan := Srv.Store.Channel().Get(hook.ChannelId, true) + cchan := a.Srv.Store.Channel().Get(hook.ChannelId, true) var channel *model.Channel if result := <-cchan; result.Err != nil { @@ -299,7 +299,7 @@ func CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, return nil, model.NewAppError("CreateOutgoingWebhook", "api.webhook.create_outgoing.triggers.app_error", nil, "", http.StatusBadRequest) } - if result := <-Srv.Store.Webhook().GetOutgoingByTeam(hook.TeamId, -1, -1); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetOutgoingByTeam(hook.TeamId, -1, -1); result.Err != nil { return nil, result.Err } else { allHooks := result.Data.([]*model.OutgoingWebhook) @@ -314,20 +314,20 @@ func CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, } } - if result := <-Srv.Store.Webhook().SaveOutgoing(hook); result.Err != nil { + if result := <-a.Srv.Store.Webhook().SaveOutgoing(hook); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.OutgoingWebhook), nil } } -func UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { +func (a *App) UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("UpdateOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } if len(updatedHook.ChannelId) > 0 { - channel, err := GetChannel(updatedHook.ChannelId) + channel, err := a.GetChannel(updatedHook.ChannelId) if err != nil { return nil, err } @@ -344,7 +344,7 @@ func UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model. } var result store.StoreResult - if result = <-Srv.Store.Webhook().GetOutgoingByTeam(oldHook.TeamId, -1, -1); result.Err != nil { + if result = <-a.Srv.Store.Webhook().GetOutgoingByTeam(oldHook.TeamId, -1, -1); result.Err != nil { return nil, result.Err } @@ -365,93 +365,93 @@ func UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model. updatedHook.TeamId = oldHook.TeamId updatedHook.UpdateAt = model.GetMillis() - if result = <-Srv.Store.Webhook().UpdateOutgoing(updatedHook); result.Err != nil { + if result = <-a.Srv.Store.Webhook().UpdateOutgoing(updatedHook); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.OutgoingWebhook), nil } } -func GetOutgoingWebhook(hookId string) (*model.OutgoingWebhook, *model.AppError) { +func (a *App) GetOutgoingWebhook(hookId string) (*model.OutgoingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().GetOutgoing(hookId); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetOutgoing(hookId); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.OutgoingWebhook), nil } } -func GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { +func (a *App) GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhooksPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().GetOutgoingList(page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetOutgoingList(page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.OutgoingWebhook), nil } } -func GetOutgoingWebhooksForChannelPage(channelId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { +func (a *App) GetOutgoingWebhooksForChannelPage(channelId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhooksForChannelPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().GetOutgoingByChannel(channelId, page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetOutgoingByChannel(channelId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.OutgoingWebhook), nil } } -func GetOutgoingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { +func (a *App) GetOutgoingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("GetOutgoingWebhooksForTeamPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().GetOutgoingByTeam(teamId, page*perPage, perPage); result.Err != nil { + if result := <-a.Srv.Store.Webhook().GetOutgoingByTeam(teamId, page*perPage, perPage); result.Err != nil { return nil, result.Err } else { return result.Data.([]*model.OutgoingWebhook), nil } } -func DeleteOutgoingWebhook(hookId string) *model.AppError { +func (a *App) DeleteOutgoingWebhook(hookId string) *model.AppError { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return model.NewAppError("DeleteOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if result := <-Srv.Store.Webhook().DeleteOutgoing(hookId, model.GetMillis()); result.Err != nil { + if result := <-a.Srv.Store.Webhook().DeleteOutgoing(hookId, model.GetMillis()); result.Err != nil { return result.Err } return nil } -func RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { +func (a *App) RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) { if !utils.Cfg.ServiceSettings.EnableOutgoingWebhooks { return nil, model.NewAppError("RegenOutgoingWebhookToken", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } hook.Token = model.NewId() - if result := <-Srv.Store.Webhook().UpdateOutgoing(hook); result.Err != nil { + if result := <-a.Srv.Store.Webhook().UpdateOutgoing(hook); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.OutgoingWebhook), nil } } -func HandleIncomingWebhook(hookId string, req *model.IncomingWebhookRequest) *model.AppError { +func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookRequest) *model.AppError { if !utils.Cfg.ServiceSettings.EnableIncomingWebhooks { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - hchan := Srv.Store.Webhook().GetIncoming(hookId, true) + hchan := a.Srv.Store.Webhook().GetIncoming(hookId, true) if req == nil { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.parse.app_error", nil, "", http.StatusBadRequest) @@ -493,22 +493,22 @@ func HandleIncomingWebhook(hookId string, req *model.IncomingWebhookRequest) *mo if len(channelName) != 0 { if channelName[0] == '@' { - if result := <-Srv.Store.User().GetByUsername(channelName[1:]); result.Err != nil { + if result := <-a.Srv.Store.User().GetByUsername(channelName[1:]); result.Err != nil { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.user.app_error", nil, "err="+result.Err.Message, http.StatusBadRequest) } else { - if ch, err := GetDirectChannel(hook.UserId, result.Data.(*model.User).Id); err != nil { + if ch, err := a.GetDirectChannel(hook.UserId, result.Data.(*model.User).Id); err != nil { return err } else { channel = ch } } } else if channelName[0] == '#' { - cchan = Srv.Store.Channel().GetByName(hook.TeamId, channelName[1:], true) + cchan = a.Srv.Store.Channel().GetByName(hook.TeamId, channelName[1:], true) } else { - cchan = Srv.Store.Channel().GetByName(hook.TeamId, channelName, true) + cchan = a.Srv.Store.Channel().GetByName(hook.TeamId, channelName, true) } } else { - cchan = Srv.Store.Channel().Get(hook.ChannelId, true) + cchan = a.Srv.Store.Channel().Get(hook.ChannelId, true) } if channel == nil { @@ -525,21 +525,21 @@ func HandleIncomingWebhook(hookId string, req *model.IncomingWebhookRequest) *mo return model.NewLocAppError("HandleIncomingWebhook", "api.post.create_post.town_square_read_only", nil, "") } - if channel.Type != model.CHANNEL_OPEN && !HasPermissionToChannel(hook.UserId, channel.Id, model.PERMISSION_READ_CHANNEL) { + if channel.Type != model.CHANNEL_OPEN && !a.HasPermissionToChannel(hook.UserId, channel.Id, model.PERMISSION_READ_CHANNEL) { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.permissions.app_error", nil, "", http.StatusForbidden) } overrideUsername := req.Username overrideIconUrl := req.IconURL - if _, err := CreateWebhookPost(hook.UserId, channel, text, overrideUsername, overrideIconUrl, req.Props, webhookType); err != nil { + if _, err := a.CreateWebhookPost(hook.UserId, channel, text, overrideUsername, overrideIconUrl, req.Props, webhookType); err != nil { return err } return nil } -func CreateCommandWebhook(commandId string, args *model.CommandArgs) (*model.CommandWebhook, *model.AppError) { +func (a *App) CreateCommandWebhook(commandId string, args *model.CommandArgs) (*model.CommandWebhook, *model.AppError) { hook := &model.CommandWebhook{ CommandId: commandId, UserId: args.UserId, @@ -548,27 +548,27 @@ func CreateCommandWebhook(commandId string, args *model.CommandArgs) (*model.Com ParentId: args.ParentId, } - if result := <-Srv.Store.CommandWebhook().Save(hook); result.Err != nil { + if result := <-a.Srv.Store.CommandWebhook().Save(hook); result.Err != nil { return nil, result.Err } else { return result.Data.(*model.CommandWebhook), nil } } -func HandleCommandWebhook(hookId string, response *model.CommandResponse) *model.AppError { +func (a *App) HandleCommandWebhook(hookId string, response *model.CommandResponse) *model.AppError { if response == nil { return model.NewAppError("HandleCommandWebhook", "web.command_webhook.parse.app_error", nil, "", http.StatusBadRequest) } var hook *model.CommandWebhook - if result := <-Srv.Store.CommandWebhook().Get(hookId); result.Err != nil { + if result := <-a.Srv.Store.CommandWebhook().Get(hookId); result.Err != nil { return model.NewAppError("HandleCommandWebhook", "web.command_webhook.invalid.app_error", nil, "err="+result.Err.Message, result.Err.StatusCode) } else { hook = result.Data.(*model.CommandWebhook) } var cmd *model.Command - if result := <-Srv.Store.Command().Get(hook.CommandId); result.Err != nil { + if result := <-a.Srv.Store.Command().Get(hook.CommandId); result.Err != nil { return model.NewAppError("HandleCommandWebhook", "web.command_webhook.command.app_error", nil, "err="+result.Err.Message, http.StatusBadRequest) } else { cmd = result.Data.(*model.Command) @@ -582,10 +582,10 @@ func HandleCommandWebhook(hookId string, response *model.CommandResponse) *model ParentId: hook.ParentId, } - if result := <-Srv.Store.CommandWebhook().TryUse(hook.Id, 5); result.Err != nil { + if result := <-a.Srv.Store.CommandWebhook().TryUse(hook.Id, 5); result.Err != nil { return model.NewAppError("HandleCommandWebhook", "web.command_webhook.invalid.app_error", nil, "err="+result.Err.Message, result.Err.StatusCode) } - _, err := HandleCommandResponse(cmd, args, response, false) + _, err := a.HandleCommandResponse(cmd, args, response, false) return err } diff --git a/app/webhook_test.go b/app/webhook_test.go index 8333de0ee..49ffdf649 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -11,8 +11,9 @@ import ( ) func TestCreateWebhookPost(t *testing.T) { - th := Setup().InitBasic() - defer TearDown() + a := Global() + th := a.Setup().InitBasic() + defer a.TearDown() enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks defer func() { @@ -22,13 +23,13 @@ func TestCreateWebhookPost(t *testing.T) { utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true utils.SetDefaultRolesBasedOnConfig() - hook, err := CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id}) + hook, err := a.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id}) if err != nil { t.Fatal(err.Error()) } - defer DeleteIncomingWebhook(hook.Id) + defer a.DeleteIncomingWebhook(hook.Id) - post, err := CreateWebhookPost(hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", model.StringInterface{ + post, err := a.CreateWebhookPost(hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", model.StringInterface{ "attachments": []*model.SlackAttachment{ &model.SlackAttachment{ Text: "text", diff --git a/app/websocket_router.go b/app/websocket_router.go index a3c56454f..d308a14f7 100644 --- a/app/websocket_router.go +++ b/app/websocket_router.go @@ -6,9 +6,10 @@ package app import ( l4g "github.com/alecthomas/log4go" + "net/http" + "github.com/mattermost/platform/model" "github.com/mattermost/platform/utils" - "net/http" ) type webSocketHandler interface { @@ -53,14 +54,14 @@ func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketReque return } - session, err := GetSession(token) + session, err := Global().GetSession(token) if err != nil { conn.WebSocket.Close() } else { go func() { - SetStatusOnline(session.UserId, session.Id, false) - UpdateLastActivityAtIfNeeded(*session) + Global().SetStatusOnline(session.UserId, session.Id, false) + Global().UpdateLastActivityAtIfNeeded(*session) }() conn.SetSession(session) -- cgit v1.2.3-1-g7c22