app type transition (#7167)
Этот коммит содержится в:
23
app/admin.go
23
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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
10
app/app.go
10
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)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ import (
|
||||
)
|
||||
|
||||
func TestCheckIfRolesGrantPermission(t *testing.T) {
|
||||
Setup()
|
||||
a := Global()
|
||||
a.Setup()
|
||||
|
||||
cases := []struct {
|
||||
roles []string
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
384
app/channel.go
384
app/channel.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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -12,7 +12,8 @@ import (
|
||||
)
|
||||
|
||||
func TestClusterDiscoveryService(t *testing.T) {
|
||||
Setup()
|
||||
a := Global()
|
||||
a.Setup()
|
||||
|
||||
ds := NewClusterDiscoveryService()
|
||||
ds.Type = model.CDS_TYPE_APP
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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")}
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ import (
|
||||
)
|
||||
|
||||
func TestRenameProviderDoCommand(t *testing.T) {
|
||||
th := Setup().InitBasic()
|
||||
a := Global()
|
||||
th := a.Setup().InitBasic()
|
||||
|
||||
rp := RenameProvider{}
|
||||
args := &model.CommandArgs{
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
|
||||
@@ -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")}
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -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")}
|
||||
}
|
||||
|
||||
@@ -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")}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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.")
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
28
app/emoji.go
28
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)
|
||||
}
|
||||
|
||||
30
app/file.go
30
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
|
||||
|
||||
@@ -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)
|
||||
}()
|
||||
}
|
||||
|
||||
166
app/import.go
166
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)
|
||||
}
|
||||
|
||||
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
20
app/job.go
20
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
|
||||
|
||||
@@ -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")
|
||||
|
||||
16
app/ldap.go
16
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
14
app/login.go
14
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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
170
app/oauth.go
170
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
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 ""
|
||||
}
|
||||
|
||||
164
app/post.go
164
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/mattermost/platform/model"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/platform/model"
|
||||
)
|
||||
|
||||
func TestCache(t *testing.T) {
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
240
app/team.go
240
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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
408
app/user.go
408
app/user.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")
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
112
app/webhook.go
112
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
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
Ссылка в новой задаче
Block a user