Этот коммит содержится в:
Ben Schumacher
2021-07-12 20:05:36 +02:00
коммит произвёл Claudio Costa
родитель 953eebdef4
Коммит 97ccf0bdf6
472 изменённых файлов: 9126 добавлений и 9132 удалений

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

@@ -155,8 +155,8 @@ func (s *Server) InvalidateAllCaches() *model.AppError {
if s.Cluster != nil {
msg := &model.ClusterMessage{
Event: model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES,
SendType: model.CLUSTER_SEND_RELIABLE,
Event: model.ClusterEventInvalidateAllCaches,
SendType: model.ClusterSendReliable,
WaitForAllToSend: true,
}
@@ -211,7 +211,7 @@ func (a *App) TestEmail(userID string, cfg *model.Config) *model.AppError {
// if the user hasn't changed their email settings, fill in the actual SMTP password so that
// the user can verify an existing SMTP connection
if *cfg.EmailSettings.SMTPPassword == model.FAKE_SETTING {
if *cfg.EmailSettings.SMTPPassword == model.FakeSetting {
if *cfg.EmailSettings.SMTPServer == *a.Config().EmailSettings.SMTPServer &&
*cfg.EmailSettings.SMTPPort == *a.Config().EmailSettings.SMTPPort &&
*cfg.EmailSettings.SMTPUsername == *a.Config().EmailSettings.SMTPUsername {

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

@@ -48,7 +48,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo
var openChannelsCount int64
g.Go(func() error {
var err error
if openChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.CHANNEL_OPEN); err != nil {
if openChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.ChannelTypeOpen); err != nil {
return model.NewAppError("GetAnalytics", "app.channel.analytics_type_count.app_error", nil, err.Error(), http.StatusInternalServerError)
}
return nil
@@ -57,7 +57,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo
var privateChannelsCount int64
g.Go(func() error {
var err error
if privateChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.CHANNEL_PRIVATE); err != nil {
if privateChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.ChannelTypePrivate); err != nil {
return model.NewAppError("GetAnalytics", "app.channel.analytics_type_count.app_error", nil, err.Error(), http.StatusInternalServerError)
}
return nil

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

@@ -64,7 +64,7 @@ func (a *App) Handle404(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) getSystemInstallDate() (int64, *model.AppError) {
systemData, err := s.Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY)
systemData, err := s.Store.System().GetByName(model.SystemInstallationDateKey)
if err != nil {
return 0, model.NewAppError("getSystemInstallDate", "app.system.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -76,7 +76,7 @@ func (s *Server) getSystemInstallDate() (int64, *model.AppError) {
}
func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) {
systemData, err := s.Store.System().GetByName(model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY)
systemData, err := s.Store.System().GetByName(model.SystemFirstServerRunTimestampKey)
if err != nil {
return 0, model.NewAppError("getFirstServerRunTimestamp", "app.system.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -89,7 +89,7 @@ func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) {
//nolint:golint,unused,deadcode
func (s *Server) getLastWarnMetricTimestamp() (int64, *model.AppError) {
systemData, err := s.Store.System().GetByName(model.SYSTEM_WARN_METRIC_LAST_RUN_TIMESTAMP_KEY)
systemData, err := s.Store.System().GetByName(model.SystemWarnMetricLastRunTimestampKey)
if err != nil {
return 0, model.NewAppError("getLastWarnMetricTimestamp", "app.system.get_by_name.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -110,9 +110,9 @@ func (a *App) GetWarnMetricsStatus() (map[string]*model.WarnMetricStatus, *model
result := map[string]*model.WarnMetricStatus{}
for key, value := range systemDataList {
if strings.HasPrefix(key, model.WARN_METRIC_STATUS_STORE_PREFIX) {
if strings.HasPrefix(key, model.WarnMetricStatusStorePrefix) {
if warnMetric, ok := model.WarnMetricsTable[key]; ok {
if !warnMetric.IsBotOnly && (value == model.WARN_METRIC_STATUS_RUNONCE || value == model.WARN_METRIC_STATUS_LIMIT_REACHED) {
if !warnMetric.IsBotOnly && (value == model.WarnMetricStatusRunonce || value == model.WarnMetricStatusLimitReached) {
result[key], _ = a.getWarnMetricStatusAndDisplayTextsForId(key, nil, isE0Edition)
}
}
@@ -141,7 +141,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.BotSuccessMessage = T("api.server.warn_metric.bot_response.notification_success.message")
switch warnMetricId {
case model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5:
case model.SystemWarnMetricNumberOfTeams5:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_teams_5.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_teams_5.start_trial.notification_body")
@@ -150,7 +150,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_teams_5.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_teams_5.notification_body")
}
case model.SYSTEM_WARN_METRIC_MFA:
case model.SystemWarnMetricMfa:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.mfa.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.mfa.start_trial.notification_body")
@@ -159,7 +159,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.mfa.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.mfa.notification_body")
}
case model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN:
case model.SystemWarnMetricEmailDomain:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.email_domain.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.email_domain.start_trial.notification_body")
@@ -168,7 +168,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.email_domain.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.email_domain.notification_body")
}
case model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50:
case model.SystemWarnMetricNumberOfChannels50:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_channels_50.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_channels_50.start_trial.notification_body")
@@ -177,7 +177,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_channels_50.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_channels_50.notification_body")
}
case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100:
case model.SystemWarnMetricNumberOfActiveUsers100:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_100.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_100.start_trial.notification_body")
@@ -186,7 +186,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_100.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_100.notification_body")
}
case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200:
case model.SystemWarnMetricNumberOfActiveUsers200:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_200.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_200.start_trial.notification_body")
@@ -195,7 +195,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_200.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_200.notification_body")
}
case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300:
case model.SystemWarnMetricNumberOfActiveUsers300:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_300.start_trial.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_300.start_trial.notification_body")
@@ -204,7 +204,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_300.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_300.notification_body")
}
case model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500:
case model.SystemWarnMetricNumberOfActiveUsers500:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_active_users_500.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_500.start_trial.notification_body")
@@ -213,7 +213,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_active_users_500.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_active_users_500.notification_body")
}
case model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M:
case model.SystemWarnMetricNumberOfPosts2m:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.number_of_posts_2M.notification_title")
if isE0Edition {
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_posts_2M.start_trial.notification_body")
@@ -222,7 +222,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
warnMetricDisplayTexts.EmailBody = T("api.server.warn_metric.number_of_posts_2M.contact_us.email_body")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.number_of_posts_2M.notification_body")
}
case model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED:
case model.SystemMetricSupportEmailNotConfigured:
warnMetricDisplayTexts.BotTitle = T("api.server.warn_metric.support_email_not_configured.notification_title")
warnMetricDisplayTexts.BotMessageBody = T("api.server.warn_metric.support_email_not_configured.start_trial.notification_body")
default:
@@ -252,7 +252,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st
userOptions := &model.UserGetOptions{
Page: 0,
PerPage: perPage,
Role: model.SYSTEM_ADMIN_ROLE_ID,
Role: model.SystemAdminRoleId,
Inactive: false,
}
@@ -293,7 +293,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st
botPost := &model.Post{
UserId: warnMetricsBot.UserId,
ChannelId: channel.Id,
Type: model.POST_SYSTEM_WARN_METRIC_STATUS,
Type: model.PostTypeSystemWarnMetricStatus,
Message: "",
}
@@ -314,7 +314,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st
&model.PostAction{
Id: actionId,
Name: actionName,
Type: model.POST_ACTION_TYPE_BUTTON,
Type: model.PostActionTypeButton,
Options: []*model.PostActionOptions{
{
Text: "TrackEventId",
@@ -359,7 +359,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId st
func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, forceAck bool, isBot bool) *model.AppError {
if warnMetric, ok := model.WarnMetricsTable[warnMetricId]; ok {
data, nErr := a.Srv().Store.System().GetByName(warnMetric.Id)
if nErr == nil && data != nil && data.Value == model.WARN_METRIC_STATUS_ACK {
if nErr == nil && data != nil && data.Value == model.WarnMetricStatusAck {
mlog.Debug("This metric warning has already been acknowledged", mlog.String("id", warnMetric.Id))
return nil
}
@@ -404,7 +404,7 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User,
return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError)
}
if err := mail.SendMailUsingConfig(model.MM_SUPPORT_ADVISOR_ADDRESS, subject, body, mailConfig, false, sender.Email); err != nil {
if err := mail.SendMailUsingConfig(model.MmSupportAdvisorAddress, subject, body, mailConfig, false, sender.Email); err != nil {
return model.NewAppError("NotifyAndSetWarnMetricAck", "api.email.send_warn_metric_ack.failure.app_error", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError)
}
}
@@ -418,12 +418,12 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User,
func (a *App) setWarnMetricsStatusAndNotify(warnMetricId string) *model.AppError {
// Ack all metric warnings on the server
if err := a.setWarnMetricsStatus(model.WARN_METRIC_STATUS_ACK); err != nil {
if err := a.setWarnMetricsStatus(model.WarnMetricStatusAck); err != nil {
return err
}
// Inform client that this metric warning has been acked
message := model.NewWebSocketEvent(model.WEBSOCKET_WARN_METRIC_STATUS_REMOVED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketWarnMetricStatusRemoved, "", "", "", nil)
message.Add("warnMetricId", warnMetricId)
a.Publish(message)
@@ -468,7 +468,7 @@ func (a *App) RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId st
trialLicenseRequest := &model.TrialLicenseRequest{
ServerID: a.TelemetryId(),
Name: currentUser.GetDisplayName(model.SHOW_FULLNAME),
Name: currentUser.GetDisplayName(model.ShowFullName),
Email: currentUser.Email,
SiteName: *a.Config().TeamSettings.SiteName,
SiteURL: *a.Config().ServiceSettings.SiteURL,

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

@@ -1058,8 +1058,8 @@ type AppIface interface {
UpdateLastActivityAtIfNeeded(session model.Session)
UpdateMfa(activate bool, userID, token string) *model.AppError
UpdateMobileAppBadge(userID string)
UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string, tokenUser *model.User) *model.AppError
UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError)
UpdateOAuthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError)
UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError
UpdateOutgoingWebhook(oldHook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError)
UpdatePassword(user *model.User, newPassword string) *model.AppError
UpdatePasswordAsUser(userID, currentPassword, newPassword string) *model.AppError

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

@@ -98,87 +98,87 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) {
expected1 := map[string][]string{
"channel_user": {
model.PERMISSION_READ_CHANNEL.Id,
model.PERMISSION_ADD_REACTION.Id,
model.PERMISSION_REMOVE_REACTION.Id,
model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id,
model.PERMISSION_UPLOAD_FILE.Id,
model.PERMISSION_GET_PUBLIC_LINK.Id,
model.PERMISSION_CREATE_POST.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PERMISSION_USE_SLASH_COMMANDS.Id,
model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id,
model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id,
model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id,
model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id,
model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id,
model.PERMISSION_DELETE_POST.Id,
model.PERMISSION_EDIT_POST.Id,
model.PermissionReadChannel.Id,
model.PermissionAddReaction.Id,
model.PermissionRemoveReaction.Id,
model.PermissionManagePublicChannelMembers.Id,
model.PermissionUploadFile.Id,
model.PermissionGetPublicLink.Id,
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
model.PermissionUseSlashCommands.Id,
model.PermissionManagePublicChannelProperties.Id,
model.PermissionDeletePublicChannel.Id,
model.PermissionManagePrivateChannelProperties.Id,
model.PermissionDeletePrivateChannel.Id,
model.PermissionManagePrivateChannelMembers.Id,
model.PermissionDeletePost.Id,
model.PermissionEditPost.Id,
},
"channel_admin": {
model.PERMISSION_MANAGE_CHANNEL_ROLES.Id,
model.PERMISSION_USE_GROUP_MENTIONS.Id,
model.PermissionManageChannelRoles.Id,
model.PermissionUseGroupMentions.Id,
},
"team_user": {
model.PERMISSION_LIST_TEAM_CHANNELS.Id,
model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id,
model.PERMISSION_READ_PUBLIC_CHANNEL.Id,
model.PERMISSION_VIEW_TEAM.Id,
model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id,
model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id,
model.PERMISSION_INVITE_USER.Id,
model.PERMISSION_ADD_USER_TO_TEAM.Id,
model.PermissionListTeamChannels.Id,
model.PermissionJoinPublicChannels.Id,
model.PermissionReadPublicChannel.Id,
model.PermissionViewTeam.Id,
model.PermissionCreatePublicChannel.Id,
model.PermissionCreatePrivateChannel.Id,
model.PermissionInviteUser.Id,
model.PermissionAddUserToTeam.Id,
},
"team_post_all": {
model.PERMISSION_CREATE_POST.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
},
"team_post_all_public": {
model.PERMISSION_CREATE_POST_PUBLIC.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePostPublic.Id,
model.PermissionUseChannelMentions.Id,
},
"team_admin": {
model.PERMISSION_REMOVE_USER_FROM_TEAM.Id,
model.PERMISSION_MANAGE_TEAM.Id,
model.PERMISSION_IMPORT_TEAM.Id,
model.PERMISSION_MANAGE_TEAM_ROLES.Id,
model.PERMISSION_MANAGE_CHANNEL_ROLES.Id,
model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_SLASH_COMMANDS.Id,
model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS.Id,
model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id,
model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id,
model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id,
model.PERMISSION_DELETE_POST.Id,
model.PERMISSION_DELETE_OTHERS_POSTS.Id,
model.PermissionRemoveUserFromTeam.Id,
model.PermissionManageTeam.Id,
model.PermissionImportTeam.Id,
model.PermissionManageTeamRoles.Id,
model.PermissionManageChannelRoles.Id,
model.PermissionManageOthersIncomingWebhooks.Id,
model.PermissionManageOthersOutgoingWebhooks.Id,
model.PermissionManageSlashCommands.Id,
model.PermissionManageOthersSlashCommands.Id,
model.PermissionManageIncomingWebhooks.Id,
model.PermissionManageOutgoingWebhooks.Id,
model.PermissionConvertPublicChannelToPrivate.Id,
model.PermissionConvertPrivateChannelToPublic.Id,
model.PermissionDeletePost.Id,
model.PermissionDeleteOthersPosts.Id,
},
"system_user": {
model.PERMISSION_LIST_PUBLIC_TEAMS.Id,
model.PERMISSION_JOIN_PUBLIC_TEAMS.Id,
model.PERMISSION_CREATE_DIRECT_CHANNEL.Id,
model.PERMISSION_CREATE_GROUP_CHANNEL.Id,
model.PERMISSION_VIEW_MEMBERS.Id,
model.PERMISSION_CREATE_TEAM.Id,
model.PermissionListPublicTeams.Id,
model.PermissionJoinPublicTeams.Id,
model.PermissionCreateDirectChannel.Id,
model.PermissionCreateGroupChannel.Id,
model.PermissionViewMembers.Id,
model.PermissionCreateTeam.Id,
},
"system_post_all": {
model.PERMISSION_CREATE_POST.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
},
"system_post_all_public": {
model.PERMISSION_CREATE_POST_PUBLIC.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePostPublic.Id,
model.PermissionUseChannelMentions.Id,
},
"system_user_access_token": {
model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_READ_USER_ACCESS_TOKEN.Id,
model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id,
model.PermissionCreateUserAccessToken.Id,
model.PermissionReadUserAccessToken.Id,
model.PermissionRevokeUserAccessToken.Id,
},
"system_admin": allPermissionIDs,
}
assert.Contains(t, allPermissionIDs, model.PERMISSION_MANAGE_SHARED_CHANNELS.Id, "manage_shared_channels permission not found")
assert.Contains(t, allPermissionIDs, model.PERMISSION_MANAGE_SECURE_CONNECTIONS.Id, "manage_secure_connections permission not found")
assert.Contains(t, allPermissionIDs, model.PermissionManageSharedChannels.Id, "manage_shared_channels permission not found")
assert.Contains(t, allPermissionIDs, model.PermissionManageSecureConnections.Id, "manage_secure_connections permission not found")
// Check the migration matches what's expected.
for name, permissions := range expected1 {
@@ -200,10 +200,10 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) {
}()
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement = model.PERMISSIONS_TEAM_ADMIN
*cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPublicChannelManagement = model.PermissionsTeamAdmin
})
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN
*cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = model.PermissionsTeamAdmin
})
th.App.Srv().SetLicense(model.NewTestLicense())
@@ -229,82 +229,82 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) {
// Check the role permissions.
expected2 := map[string][]string{
"channel_user": {
model.PERMISSION_READ_CHANNEL.Id,
model.PERMISSION_ADD_REACTION.Id,
model.PERMISSION_REMOVE_REACTION.Id,
model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id,
model.PERMISSION_UPLOAD_FILE.Id,
model.PERMISSION_GET_PUBLIC_LINK.Id,
model.PERMISSION_CREATE_POST.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PERMISSION_USE_SLASH_COMMANDS.Id,
model.PERMISSION_DELETE_PUBLIC_CHANNEL.Id,
model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id,
model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id,
model.PERMISSION_DELETE_POST.Id,
model.PERMISSION_EDIT_POST.Id,
model.PermissionReadChannel.Id,
model.PermissionAddReaction.Id,
model.PermissionRemoveReaction.Id,
model.PermissionManagePublicChannelMembers.Id,
model.PermissionUploadFile.Id,
model.PermissionGetPublicLink.Id,
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
model.PermissionUseSlashCommands.Id,
model.PermissionDeletePublicChannel.Id,
model.PermissionDeletePrivateChannel.Id,
model.PermissionManagePrivateChannelMembers.Id,
model.PermissionDeletePost.Id,
model.PermissionEditPost.Id,
},
"channel_admin": {
model.PERMISSION_MANAGE_CHANNEL_ROLES.Id,
model.PERMISSION_USE_GROUP_MENTIONS.Id,
model.PermissionManageChannelRoles.Id,
model.PermissionUseGroupMentions.Id,
},
"team_user": {
model.PERMISSION_LIST_TEAM_CHANNELS.Id,
model.PERMISSION_JOIN_PUBLIC_CHANNELS.Id,
model.PERMISSION_READ_PUBLIC_CHANNEL.Id,
model.PERMISSION_VIEW_TEAM.Id,
model.PERMISSION_CREATE_PUBLIC_CHANNEL.Id,
model.PERMISSION_CREATE_PRIVATE_CHANNEL.Id,
model.PERMISSION_INVITE_USER.Id,
model.PERMISSION_ADD_USER_TO_TEAM.Id,
model.PermissionListTeamChannels.Id,
model.PermissionJoinPublicChannels.Id,
model.PermissionReadPublicChannel.Id,
model.PermissionViewTeam.Id,
model.PermissionCreatePublicChannel.Id,
model.PermissionCreatePrivateChannel.Id,
model.PermissionInviteUser.Id,
model.PermissionAddUserToTeam.Id,
},
"team_post_all": {
model.PERMISSION_CREATE_POST.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
},
"team_post_all_public": {
model.PERMISSION_CREATE_POST_PUBLIC.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePostPublic.Id,
model.PermissionUseChannelMentions.Id,
},
"team_admin": {
model.PERMISSION_REMOVE_USER_FROM_TEAM.Id,
model.PERMISSION_MANAGE_TEAM.Id,
model.PERMISSION_IMPORT_TEAM.Id,
model.PERMISSION_MANAGE_TEAM_ROLES.Id,
model.PERMISSION_MANAGE_CHANNEL_ROLES.Id,
model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_SLASH_COMMANDS.Id,
model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS.Id,
model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id,
model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id,
model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id,
model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id,
model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id,
model.PERMISSION_DELETE_POST.Id,
model.PERMISSION_DELETE_OTHERS_POSTS.Id,
model.PermissionRemoveUserFromTeam.Id,
model.PermissionManageTeam.Id,
model.PermissionImportTeam.Id,
model.PermissionManageTeamRoles.Id,
model.PermissionManageChannelRoles.Id,
model.PermissionManageOthersIncomingWebhooks.Id,
model.PermissionManageOthersOutgoingWebhooks.Id,
model.PermissionManageSlashCommands.Id,
model.PermissionManageOthersSlashCommands.Id,
model.PermissionManageIncomingWebhooks.Id,
model.PermissionManageOutgoingWebhooks.Id,
model.PermissionConvertPublicChannelToPrivate.Id,
model.PermissionConvertPrivateChannelToPublic.Id,
model.PermissionManagePublicChannelProperties.Id,
model.PermissionManagePrivateChannelProperties.Id,
model.PermissionDeletePost.Id,
model.PermissionDeleteOthersPosts.Id,
},
"system_user": {
model.PERMISSION_LIST_PUBLIC_TEAMS.Id,
model.PERMISSION_JOIN_PUBLIC_TEAMS.Id,
model.PERMISSION_CREATE_DIRECT_CHANNEL.Id,
model.PERMISSION_CREATE_GROUP_CHANNEL.Id,
model.PERMISSION_VIEW_MEMBERS.Id,
model.PERMISSION_CREATE_TEAM.Id,
model.PermissionListPublicTeams.Id,
model.PermissionJoinPublicTeams.Id,
model.PermissionCreateDirectChannel.Id,
model.PermissionCreateGroupChannel.Id,
model.PermissionViewMembers.Id,
model.PermissionCreateTeam.Id,
},
"system_post_all": {
model.PERMISSION_CREATE_POST.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
},
"system_post_all_public": {
model.PERMISSION_CREATE_POST_PUBLIC.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PermissionCreatePostPublic.Id,
model.PermissionUseChannelMentions.Id,
},
"system_user_access_token": {
model.PERMISSION_CREATE_USER_ACCESS_TOKEN.Id,
model.PERMISSION_READ_USER_ACCESS_TOKEN.Id,
model.PERMISSION_REVOKE_USER_ACCESS_TOKEN.Id,
model.PermissionCreateUserAccessToken.Id,
model.PermissionReadUserAccessToken.Id,
model.PermissionRevokeUserAccessToken.Id,
},
"system_admin": allPermissionIDs,
}
@@ -384,7 +384,7 @@ func TestDoEmojisPermissionsMigration(t *testing.T) {
}()
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_SYSTEM_ADMIN
*cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RestrictEmojiCreationSystemAdmin
})
th.ResetEmojisMigration()
@@ -393,84 +393,84 @@ func TestDoEmojisPermissionsMigration(t *testing.T) {
expectedSystemAdmin := allPermissionIDs
sort.Strings(expectedSystemAdmin)
role1, err1 := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
role1, err1 := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId)
assert.Nil(t, err1)
sort.Strings(role1.Permissions)
assert.Equal(t, expectedSystemAdmin, role1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_ADMIN_ROLE_ID))
assert.Equal(t, expectedSystemAdmin, role1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemAdminRoleId))
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_ADMIN
*cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RestrictEmojiCreationAdmin
})
th.ResetEmojisMigration()
th.App.DoEmojisPermissionsMigration()
role2, err2 := th.App.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID)
role2, err2 := th.App.GetRoleByName(context.Background(), model.TeamAdminRoleId)
assert.Nil(t, err2)
expected2 := []string{
model.PERMISSION_REMOVE_USER_FROM_TEAM.Id,
model.PERMISSION_MANAGE_TEAM.Id,
model.PERMISSION_IMPORT_TEAM.Id,
model.PERMISSION_MANAGE_TEAM_ROLES.Id,
model.PERMISSION_READ_PUBLIC_CHANNEL_GROUPS.Id,
model.PERMISSION_READ_PRIVATE_CHANNEL_GROUPS.Id,
model.PERMISSION_MANAGE_CHANNEL_ROLES.Id,
model.PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_SLASH_COMMANDS.Id,
model.PERMISSION_MANAGE_OTHERS_SLASH_COMMANDS.Id,
model.PERMISSION_MANAGE_INCOMING_WEBHOOKS.Id,
model.PERMISSION_MANAGE_OUTGOING_WEBHOOKS.Id,
model.PERMISSION_DELETE_POST.Id,
model.PERMISSION_DELETE_OTHERS_POSTS.Id,
model.PERMISSION_CREATE_EMOJIS.Id,
model.PERMISSION_DELETE_EMOJIS.Id,
model.PERMISSION_ADD_REACTION.Id,
model.PERMISSION_CREATE_POST.Id,
model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id,
model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS.Id,
model.PERMISSION_REMOVE_REACTION.Id,
model.PERMISSION_USE_CHANNEL_MENTIONS.Id,
model.PERMISSION_USE_GROUP_MENTIONS.Id,
model.PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE.Id,
model.PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC.Id,
model.PermissionRemoveUserFromTeam.Id,
model.PermissionManageTeam.Id,
model.PermissionImportTeam.Id,
model.PermissionManageTeamRoles.Id,
model.PermissionReadPublicChannelGroups.Id,
model.PermissionReadPrivateChannelGroups.Id,
model.PermissionManageChannelRoles.Id,
model.PermissionManageOthersIncomingWebhooks.Id,
model.PermissionManageOthersOutgoingWebhooks.Id,
model.PermissionManageSlashCommands.Id,
model.PermissionManageOthersSlashCommands.Id,
model.PermissionManageIncomingWebhooks.Id,
model.PermissionManageOutgoingWebhooks.Id,
model.PermissionDeletePost.Id,
model.PermissionDeleteOthersPosts.Id,
model.PermissionCreateEmojis.Id,
model.PermissionDeleteEmojis.Id,
model.PermissionAddReaction.Id,
model.PermissionCreatePost.Id,
model.PermissionManagePublicChannelMembers.Id,
model.PermissionManagePrivateChannelMembers.Id,
model.PermissionRemoveReaction.Id,
model.PermissionUseChannelMentions.Id,
model.PermissionUseGroupMentions.Id,
model.PermissionConvertPublicChannelToPrivate.Id,
model.PermissionConvertPrivateChannelToPublic.Id,
}
sort.Strings(expected2)
sort.Strings(role2.Permissions)
assert.Equal(t, expected2, role2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.TEAM_ADMIN_ROLE_ID))
assert.Equal(t, expected2, role2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.TeamAdminRoleId))
systemAdmin1, systemAdminErr1 := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
systemAdmin1, systemAdminErr1 := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId)
assert.Nil(t, systemAdminErr1)
sort.Strings(systemAdmin1.Permissions)
assert.Equal(t, expectedSystemAdmin, systemAdmin1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_ADMIN_ROLE_ID))
assert.Equal(t, expectedSystemAdmin, systemAdmin1.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemAdminRoleId))
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RESTRICT_EMOJI_CREATION_ALL
*cfg.ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation = model.RestrictEmojiCreationAll
})
th.ResetEmojisMigration()
th.App.DoEmojisPermissionsMigration()
role3, err3 := th.App.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID)
role3, err3 := th.App.GetRoleByName(context.Background(), model.SystemUserRoleId)
assert.Nil(t, err3)
expected3 := []string{
model.PERMISSION_LIST_PUBLIC_TEAMS.Id,
model.PERMISSION_JOIN_PUBLIC_TEAMS.Id,
model.PERMISSION_CREATE_DIRECT_CHANNEL.Id,
model.PERMISSION_CREATE_GROUP_CHANNEL.Id,
model.PERMISSION_CREATE_TEAM.Id,
model.PERMISSION_CREATE_EMOJIS.Id,
model.PERMISSION_DELETE_EMOJIS.Id,
model.PERMISSION_VIEW_MEMBERS.Id,
model.PermissionListPublicTeams.Id,
model.PermissionJoinPublicTeams.Id,
model.PermissionCreateDirectChannel.Id,
model.PermissionCreateGroupChannel.Id,
model.PermissionCreateTeam.Id,
model.PermissionCreateEmojis.Id,
model.PermissionDeleteEmojis.Id,
model.PermissionViewMembers.Id,
}
sort.Strings(expected3)
sort.Strings(role3.Permissions)
assert.Equal(t, expected3, role3.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_USER_ROLE_ID))
assert.Equal(t, expected3, role3.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemUserRoleId))
systemAdmin2, systemAdminErr2 := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
systemAdmin2, systemAdminErr2 := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId)
assert.Nil(t, systemAdminErr2)
sort.Strings(systemAdmin2.Permissions)
assert.Equal(t, expectedSystemAdmin, systemAdmin2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SYSTEM_ADMIN_ROLE_ID))
assert.Equal(t, expectedSystemAdmin, systemAdmin2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemAdminRoleId))
}
func TestDBHealthCheckWriteAndDelete(t *testing.T) {

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

@@ -249,7 +249,7 @@ func (a *App) authenticateUser(c *request.Context, user *model.User, password, m
license := a.Srv().License()
ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP
if user.AuthService == model.USER_AUTH_SERVICE_LDAP {
if user.AuthService == model.UserAuthServiceLdap {
if !ldapAvailable {
err := model.NewAppError("login", "api.user.login_ldap.not_available.app_error", nil, "", http.StatusNotImplemented)
return user, err
@@ -267,7 +267,7 @@ func (a *App) authenticateUser(c *request.Context, user *model.User, password, m
if user.AuthService != "" {
authService := user.AuthService
if authService == model.USER_AUTH_SERVICE_SAML {
if authService == model.UserAuthServiceSaml {
authService = strings.ToUpper(authService)
}
err := model.NewAppError("login", "api.user.login.use_auth_service.app_error", map[string]interface{}{"AuthService": authService}, "", http.StatusBadRequest)
@@ -283,20 +283,20 @@ func (a *App) authenticateUser(c *request.Context, user *model.User, password, m
}
func ParseAuthTokenFromRequest(r *http.Request) (string, TokenLocation) {
authHeader := r.Header.Get(model.HEADER_AUTH)
authHeader := r.Header.Get(model.HeaderAuth)
// Attempt to parse the token from the cookie
if cookie, err := r.Cookie(model.SESSION_COOKIE_TOKEN); err == nil {
if cookie, err := r.Cookie(model.SessionCookieToken); err == nil {
return cookie.Value, TokenLocationCookie
}
// Parse the token from the header
if len(authHeader) > 6 && strings.ToUpper(authHeader[0:6]) == model.HEADER_BEARER {
if len(authHeader) > 6 && strings.ToUpper(authHeader[0:6]) == model.HeaderBearer {
// Default session token
return authHeader[7:], TokenLocationHeader
}
if len(authHeader) > 5 && strings.ToLower(authHeader[0:5]) == model.HEADER_TOKEN {
if len(authHeader) > 5 && strings.ToLower(authHeader[0:5]) == model.HeaderToken {
// OAuth token
return authHeader[6:], TokenLocationHeader
}
@@ -306,11 +306,11 @@ func ParseAuthTokenFromRequest(r *http.Request) (string, TokenLocation) {
return token, TokenLocationQueryString
}
if token := r.Header.Get(model.HEADER_CLOUD_TOKEN); token != "" {
if token := r.Header.Get(model.HeaderCloudToken); token != "" {
return token, TokenLocationCloudHeader
}
if token := r.Header.Get(model.HEADER_REMOTECLUSTER_TOKEN); token != "" {
if token := r.Header.Get(model.HeaderRemoteclusterToken); token != "" {
return token, TokenLocationRemoteClusterHeader
}

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

@@ -38,12 +38,12 @@ func TestParseAuthTokenFromRequest(t *testing.T) {
req := httptest.NewRequest("GET", pathname, nil)
switch tc.expectedLocation {
case TokenLocationHeader:
req.Header.Add(model.HEADER_AUTH, tc.header)
req.Header.Add(model.HeaderAuth, tc.header)
case TokenLocationCloudHeader:
req.Header.Add(model.HEADER_CLOUD_TOKEN, tc.header)
req.Header.Add(model.HeaderCloudToken, tc.header)
case TokenLocationCookie:
req.AddCookie(&http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Name: model.SessionCookieToken,
Value: tc.cookie,
})
}

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

@@ -106,7 +106,7 @@ func (a *App) SessionHasPermissionToChannelByPost(session model.Session, postID
}
func (a *App) SessionHasPermissionToCategory(session model.Session, userID, teamID, categoryId string) bool {
if a.SessionHasPermissionTo(session, model.PERMISSION_EDIT_OTHER_USERS) {
if a.SessionHasPermissionTo(session, model.PermissionEditOtherUsers) {
return true
}
category, err := a.GetSidebarCategory(categoryId)
@@ -125,7 +125,7 @@ func (a *App) SessionHasPermissionToUser(session model.Session, userID string) b
return true
}
if a.SessionHasPermissionTo(session, model.PERMISSION_EDIT_OTHER_USERS) {
if a.SessionHasPermissionTo(session, model.PermissionEditOtherUsers) {
return true
}
@@ -212,7 +212,7 @@ func (a *App) HasPermissionToUser(askingUserId string, userID string) bool {
return true
}
if a.HasPermissionTo(askingUserId, model.PERMISSION_EDIT_OTHER_USERS) {
if a.HasPermissionTo(askingUserId, model.PermissionEditOtherUsers) {
return true
}
@@ -257,22 +257,22 @@ func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId s
}
if existingBot.OwnerId == session.UserId {
if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_BOTS) {
if !a.SessionHasPermissionTo(session, model.PERMISSION_READ_BOTS) {
if !a.SessionHasPermissionTo(session, model.PermissionManageBots) {
if !a.SessionHasPermissionTo(session, model.PermissionReadBots) {
// If the user doesn't have permission to read bots, pretend as if
// the bot doesn't exist at all.
return model.MakeBotNotFoundError(botUserId)
}
return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_BOTS})
return a.MakePermissionError(&session, []*model.Permission{model.PermissionManageBots})
}
} else {
if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_OTHERS_BOTS) {
if !a.SessionHasPermissionTo(session, model.PERMISSION_READ_OTHERS_BOTS) {
if !a.SessionHasPermissionTo(session, model.PermissionManageOthersBots) {
if !a.SessionHasPermissionTo(session, model.PermissionReadOthersBots) {
// If the user doesn't have permission to read others' bots,
// pretend as if the bot doesn't exist at all.
return model.MakeBotNotFoundError(botUserId)
}
return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_OTHERS_BOTS})
return a.MakePermissionError(&session, []*model.Permission{model.PermissionManageOthersBots})
}
}

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

@@ -24,14 +24,14 @@ func TestCheckIfRolesGrantPermission(t *testing.T) {
permissionId string
shouldGrant bool
}{
{[]string{model.SYSTEM_ADMIN_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, true},
{[]string{model.SYSTEM_ADMIN_ROLE_ID}, "non-existent-permission", false},
{[]string{model.CHANNEL_USER_ROLE_ID}, model.PERMISSION_READ_CHANNEL.Id, true},
{[]string{model.CHANNEL_USER_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, false},
{[]string{model.SYSTEM_ADMIN_ROLE_ID, model.CHANNEL_USER_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, true},
{[]string{model.CHANNEL_USER_ROLE_ID, model.SYSTEM_ADMIN_ROLE_ID}, model.PERMISSION_MANAGE_SYSTEM.Id, true},
{[]string{model.TEAM_USER_ROLE_ID, model.TEAM_ADMIN_ROLE_ID}, model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, true},
{[]string{model.TEAM_ADMIN_ROLE_ID, model.TEAM_USER_ROLE_ID}, model.PERMISSION_MANAGE_SLASH_COMMANDS.Id, true},
{[]string{model.SystemAdminRoleId}, model.PermissionManageSystem.Id, true},
{[]string{model.SystemAdminRoleId}, "non-existent-permission", false},
{[]string{model.ChannelUserRoleId}, model.PermissionReadChannel.Id, true},
{[]string{model.ChannelUserRoleId}, model.PermissionManageSystem.Id, false},
{[]string{model.SystemAdminRoleId, model.ChannelUserRoleId}, model.PermissionManageSystem.Id, true},
{[]string{model.ChannelUserRoleId, model.SystemAdminRoleId}, model.PermissionManageSystem.Id, true},
{[]string{model.TeamUserRoleId, model.TeamAdminRoleId}, model.PermissionManageSlashCommands.Id, true},
{[]string{model.TeamAdminRoleId, model.TeamUserRoleId}, model.PermissionManageSlashCommands.Id, true},
}
for _, testcase := range cases {
@@ -50,17 +50,17 @@ func TestHasPermissionToTeam(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
assert.True(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS))
assert.True(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.RemoveUserFromTeam(th.BasicUser, th.BasicTeam)
assert.False(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS))
assert.False(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS))
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam)
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS))
th.RemovePermissionFromRole(model.PERMISSION_LIST_TEAM_CHANNELS.Id, model.TEAM_USER_ROLE_ID)
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS))
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.RemovePermissionFromRole(model.PermissionListTeamChannels.Id, model.TeamUserRoleId)
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.RemoveUserFromTeam(th.SystemAdminUser, th.BasicTeam)
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PERMISSION_LIST_TEAM_CHANNELS))
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
}
func TestSessionHasPermissionToChannel(t *testing.T) {
@@ -72,7 +72,7 @@ func TestSessionHasPermissionToChannel(t *testing.T) {
}
t.Run("basic user can access basic channel", func(t *testing.T) {
assert.True(t, th.App.SessionHasPermissionToChannel(session, th.BasicChannel.Id, model.PERMISSION_ADD_REACTION))
assert.True(t, th.App.SessionHasPermissionToChannel(session, th.BasicChannel.Id, model.PermissionAddReaction))
})
t.Run("does not panic if fetching channel causes an error", func(t *testing.T) {
@@ -97,7 +97,7 @@ func TestSessionHasPermissionToChannel(t *testing.T) {
// If there's an error returned from the GetChannel call the code should continue to cascade and since there
// are no session level permissions in this test case, the permission should be denied.
assert.False(t, th.App.SessionHasPermissionToChannel(session, th.BasicUser.Id, model.PERMISSION_ADD_REACTION))
assert.False(t, th.App.SessionHasPermissionToChannel(session, th.BasicUser.Id, model.PermissionAddReaction))
})
}

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

@@ -22,7 +22,7 @@ func (a *App) checkIfRespondedToday(createdAt int64, channelId, userId string) (
}
func (a *App) SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) {
if channel.Type != model.CHANNEL_DIRECT {
if channel.Type != model.ChannelTypeDirect {
return false, nil
}
@@ -57,8 +57,8 @@ func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, recei
return false, nil
}
active := receiver.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true"
message := receiver.NotifyProps[model.AUTO_RESPONDER_MESSAGE_NOTIFY_PROP]
active := receiver.NotifyProps[model.AutoResponderActiveNotifyProp] == "true"
message := receiver.NotifyProps[model.AutoResponderMessageNotifyProp]
if !active || message == "" {
return false, nil
@@ -73,7 +73,7 @@ func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, recei
ChannelId: channel.Id,
Message: message,
RootId: rootID,
Type: model.POST_AUTO_RESPONDER,
Type: model.PostTypeAutoResponder,
UserId: receiver.Id,
}
@@ -85,8 +85,8 @@ func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, recei
}
func (a *App) SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap) {
active := user.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true"
oldActive := oldNotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true"
active := user.NotifyProps[model.AutoResponderActiveNotifyProp] == "true"
oldActive := oldNotifyProps[model.AutoResponderActiveNotifyProp] == "true"
autoResponderEnabled := !oldActive && active
autoResponderDisabled := oldActive && !active
@@ -104,12 +104,12 @@ func (a *App) DisableAutoResponder(userID string, asAdmin bool) *model.AppError
return err
}
active := user.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] == "true"
active := user.NotifyProps[model.AutoResponderActiveNotifyProp] == "true"
if active {
patch := &model.UserPatch{}
patch.NotifyProps = user.NotifyProps
patch.NotifyProps[model.AUTO_RESPONDER_ACTIVE_NOTIFY_PROP] = "false"
patch.NotifyProps[model.AutoResponderActiveNotifyProp] = "false"
_, err := a.PatchUser(userID, patch, asAdmin)
if err != nil {

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

@@ -33,7 +33,7 @@ func TestSetAutoResponderStatus(t *testing.T) {
status, err := th.App.GetStatus(userUpdated1.Id)
require.Nil(t, err)
assert.Equal(t, model.STATUS_OUT_OF_OFFICE, status.Status)
assert.Equal(t, model.StatusOutOfOffice, status.Status)
patch2 := &model.UserPatch{}
patch2.NotifyProps = make(map[string]string)
@@ -47,7 +47,7 @@ func TestSetAutoResponderStatus(t *testing.T) {
status, err = th.App.GetStatus(userUpdated2.Id)
require.Nil(t, err)
assert.Equal(t, model.STATUS_ONLINE, status.Status)
assert.Equal(t, model.StatusOnline, status.Status)
}
@@ -268,7 +268,7 @@ func TestSendAutoResponseSuccess(t *testing.T) {
autoResponderPostFound := false
for _, post := range list.Posts {
if post.Type == model.POST_AUTO_RESPONDER {
if post.Type == model.PostTypeAutoResponder {
autoResponderPostFound = true
assert.Equal(t, savedPost.Id, post.RootId)
assert.Equal(t, savedPost.Id, post.ParentId)
@@ -318,7 +318,7 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) {
autoResponderPostFound := false
for _, post := range list.Posts {
if post.Type == model.POST_AUTO_RESPONDER {
if post.Type == model.PostTypeAutoResponder {
autoResponderPostFound = true
assert.Equal(t, savedPost.RootId, post.RootId)
assert.Equal(t, savedPost.ParentId, post.ParentId)
@@ -359,7 +359,7 @@ func TestSendAutoResponseFailure(t *testing.T) {
} else {
autoResponderPostFound := false
for _, post := range list.Posts {
if post.Type == model.POST_AUTO_RESPONDER {
if post.Type == model.PostTypeAutoResponder {
autoResponderPostFound = true
}
}

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

@@ -76,7 +76,7 @@ func (a *App) CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model.
T := i18n.GetUserTranslations(ownerUser.Locale)
botAddPost := &model.Post{
Type: model.POST_ADD_BOT_TEAMS_CHANNELS,
Type: model.PostTypeAddBotTeamsChannels,
UserId: savedBot.UserId,
ChannelId: channel.Id,
Message: T("api.bot.teams_channels.add_message_mobile"),
@@ -96,7 +96,7 @@ func (a *App) GetWarnMetricsBot() (*model.Bot, *model.AppError) {
userOptions := &model.UserGetOptions{
Page: 0,
PerPage: perPage,
Role: model.SYSTEM_ADMIN_ROLE_ID,
Role: model.SystemAdminRoleId,
Inactive: false,
}
@@ -111,7 +111,7 @@ func (a *App) GetWarnMetricsBot() (*model.Bot, *model.AppError) {
T := i18n.GetUserTranslations(sysAdminList[0].Locale)
warnMetricsBot := &model.Bot{
Username: model.BOT_WARN_METRIC_BOT_USERNAME,
Username: model.BotWarnMetricBotUsername,
DisplayName: T("app.system.warn_metric.bot_displayname"),
Description: "",
OwnerId: sysAdminList[0].Id,
@@ -125,7 +125,7 @@ func (a *App) GetSystemBot() (*model.Bot, *model.AppError) {
userOptions := &model.UserGetOptions{
Page: 0,
PerPage: perPage,
Role: model.SYSTEM_ADMIN_ROLE_ID,
Role: model.SystemAdminRoleId,
Inactive: false,
}
@@ -140,7 +140,7 @@ func (a *App) GetSystemBot() (*model.Bot, *model.AppError) {
T := i18n.GetUserTranslations(sysAdminList[0].Locale)
systemBot := &model.Bot{
Username: model.BOT_SYSTEM_BOT_USERNAME,
Username: model.BotSystemBotUsername,
DisplayName: T("app.system.system_bot.bot_displayname"),
Description: "",
OwnerId: sysAdminList[0].Id,
@@ -478,7 +478,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(c *request.Context, userID stri
userOptions := &model.UserGetOptions{
Page: 0,
PerPage: perPage,
Role: model.SYSTEM_ADMIN_ROLE_ID,
Role: model.SystemAdminRoleId,
Inactive: false,
}
// get sysadmins
@@ -515,7 +515,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(c *request.Context, userID stri
UserId: sysAdmin.Id,
ChannelId: channel.Id,
Message: a.getDisableBotSysadminMessage(user, userBots),
Type: model.POST_SYSTEM_GENERIC,
Type: model.PostTypeSystemGeneric,
}
_, appErr = a.CreatePost(c, post, channel, false, true)

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

@@ -87,7 +87,7 @@ func TestCreateBot(t *testing.T) {
postArray := posts.ToSlice()
assert.Len(t, postArray, 1)
assert.Equal(t, postArray[0].Type, model.POST_ADD_BOT_TEAMS_CHANNELS)
assert.Equal(t, postArray[0].Type, model.PostTypeAddBotTeamsChannels)
})
t.Run("create bot, username already used by a non-bot user", func(t *testing.T) {
@@ -595,20 +595,20 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
Nickname: "nn_sysadmin1",
Password: "hello1",
Username: "un_sysadmin1",
Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId}
_, err := th.App.CreateUser(th.Context, &sysadmin1)
require.Nil(t, err, "failed to create user")
th.App.UpdateUserRoles(sysadmin1.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
th.App.UpdateUserRoles(sysadmin1.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false)
sysadmin2 := model.User{
Email: "sys2@example.com",
Nickname: "nn_sysadmin2",
Password: "hello1",
Username: "un_sysadmin2",
Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId}
_, err = th.App.CreateUser(th.Context, &sysadmin2)
require.Nil(t, err, "failed to create user")
th.App.UpdateUserRoles(sysadmin2.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
th.App.UpdateUserRoles(sysadmin2.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false)
// create user to be disabled
user1, err := th.App.CreateUser(th.Context, &model.User{
@@ -932,23 +932,23 @@ func TestGetSystemBot(t *testing.T) {
t.Run("The bot should be created the first time it's retrieved", func(t *testing.T) {
// assert no bot with username exists
_, err := th.App.GetUserByUsername(model.BOT_SYSTEM_BOT_USERNAME)
_, err := th.App.GetUserByUsername(model.BotSystemBotUsername)
require.NotNil(t, err)
bot, err := th.App.GetSystemBot()
require.Nil(t, err)
require.Equal(t, bot.Username, model.BOT_SYSTEM_BOT_USERNAME)
require.Equal(t, bot.Username, model.BotSystemBotUsername)
})
t.Run("The bot should be correctly retrieved if it exists already", func(t *testing.T) {
// assert that the bot is now present
botUser, err := th.App.GetUserByUsername(model.BOT_SYSTEM_BOT_USERNAME)
botUser, err := th.App.GetUserByUsername(model.BotSystemBotUsername)
require.Nil(t, err)
require.True(t, botUser.IsBot)
bot, err := th.App.GetSystemBot()
require.Nil(t, err)
require.Equal(t, bot.Username, model.BOT_SYSTEM_BOT_USERNAME)
require.Equal(t, bot.Username, model.BotSystemBotUsername)
require.Equal(t, bot.UserId, botUser.Id)
})
}

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

@@ -55,7 +55,7 @@ func (b *Busy) Set(dur time.Duration) {
b.setWithoutNotify(dur)
if b.cluster != nil {
sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), Expires_ts: b.expires.UTC().Format(TimestampFormat)}
sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), ExpiresTS: b.expires.UTC().Format(TimestampFormat)}
b.notifyServerBusyChange(sbs)
}
}
@@ -80,7 +80,7 @@ func (b *Busy) Clear() {
b.clearWithoutNotify()
if b.cluster != nil {
sbs := &model.ServerBusyState{Busy: false, Expires: time.Time{}.Unix(), Expires_ts: ""}
sbs := &model.ServerBusyState{Busy: false, Expires: time.Time{}.Unix(), ExpiresTS: ""}
b.notifyServerBusyChange(sbs)
}
}
@@ -110,8 +110,8 @@ func (b *Busy) notifyServerBusyChange(sbs *model.ServerBusyState) {
return
}
msg := &model.ClusterMessage{
Event: model.CLUSTER_EVENT_BUSY_STATE_CHANGED,
SendType: model.CLUSTER_SEND_RELIABLE,
Event: model.ClusterEventBusyStateChanged,
SendType: model.ClusterSendReliable,
WaitForAllToSend: true,
Data: sbs.ToJson(),
}
@@ -139,9 +139,9 @@ func (b *Busy) ToJson() string {
defer b.mux.RUnlock()
sbs := &model.ServerBusyState{
Busy: atomic.LoadInt32(&b.busy) != 0,
Expires: b.expires.Unix(),
Expires_ts: b.expires.UTC().Format(TimestampFormat),
Busy: atomic.LoadInt32(&b.busy) != 0,
Expires: b.expires.Unix(),
ExpiresTS: b.expires.UTC().Format(TimestampFormat),
}
return sbs.ToJson()
}

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

@@ -31,7 +31,7 @@ func (a *App) CreateDefaultChannels(c *request.Context, teamID string) ([]*model
defaultChannelNames := a.DefaultChannelNames()
for _, name := range defaultChannelNames {
displayName := i18n.TDefault(displayNames[name], name)
channel := &model.Channel{DisplayName: displayName, Name: name, Type: model.CHANNEL_OPEN, TeamId: teamID}
channel := &model.Channel{DisplayName: displayName, Name: name, Type: model.ChannelTypeOpen, TeamId: teamID}
if _, err := a.CreateChannel(c, channel, false); err != nil {
return nil, err
}
@@ -96,7 +96,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model
continue
}
if channel.Type != model.CHANNEL_OPEN {
if channel.Type != model.ChannelTypeOpen {
continue
}
@@ -122,7 +122,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model
a.invalidateCacheForChannelMembers(channel.Id)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_ADDED, "", channel.Id, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventUserAdded, "", channel.Id, "", nil)
message.Add("user_id", user.Id)
message.Add("team_id", channel.TeamId)
a.Publish(message)
@@ -147,7 +147,7 @@ func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model
}
func (a *App) postJoinMessageForDefaultChannel(c *request.Context, user *model.User, requestor *model.User, channel *model.Channel) *model.AppError {
if channel.Name == model.DEFAULT_CHANNEL {
if channel.Name == model.DefaultChannelName {
if requestor == nil {
if err := a.postJoinTeamMessage(c, user, channel); err != nil {
return err
@@ -205,7 +205,7 @@ func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel,
a.postJoinChannelMessage(c, user, channel)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CREATED, "", "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelCreated, "", "", userID, nil)
message.Add("channel_id", channel.Id)
message.Add("team_id", channel.TeamId)
a.Publish(message)
@@ -215,11 +215,11 @@ func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel,
// RenameChannel is used to rename the channel Name and the DisplayName fields
func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) {
if channel.Type == model.CHANNEL_DIRECT {
if channel.Type == model.ChannelTypeDirect {
return nil, model.NewAppError("RenameChannel", "api.channel.rename_channel.cant_rename_direct_messages.app_error", nil, "", http.StatusBadRequest)
}
if channel.Type == model.CHANNEL_GROUP {
if channel.Type == model.ChannelTypeGroup {
return nil, model.NewAppError("RenameChannel", "api.channel.rename_channel.cant_rename_group_messages.app_error", nil, "", http.StatusBadRequest)
}
@@ -332,8 +332,8 @@ func (a *App) GetOrCreateDirectChannel(c *request.Context, userID, otherUserID s
return channel, nil
}
if *a.Config().TeamSettings.RestrictDirectMessage == model.DIRECT_MESSAGE_TEAM &&
!a.SessionHasPermissionTo(*c.Session(), model.PERMISSION_MANAGE_SYSTEM) {
if *a.Config().TeamSettings.RestrictDirectMessage == model.DirectMessageTeam &&
!a.SessionHasPermissionTo(*c.Session(), model.PermissionManageSystem) {
commonTeamIDs, err := a.GetCommonTeamIDsForTwoUsers(userID, otherUserID)
if err != nil {
return nil, err
@@ -391,7 +391,7 @@ func (a *App) handleCreationEvent(c *request.Context, userID, otherUserID string
})
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_DIRECT_ADDED, "", channel.Id, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventDirectAdded, "", channel.Id, "", nil)
message.Add("creator_id", userID)
message.Add("teammate_id", otherUserID)
a.Publish(message)
@@ -509,7 +509,7 @@ func (a *App) CreateGroupChannel(userIDs []string, creatorId string) (*model.Cha
a.InvalidateCacheForUser(userID)
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_GROUP_ADDED, "", channel.Id, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventGroupAdded, "", channel.Id, "", nil)
message.Add("teammate_ids", model.ArrayToJson(userIDs))
a.Publish(message)
@@ -517,7 +517,7 @@ func (a *App) CreateGroupChannel(userIDs []string, creatorId string) (*model.Cha
}
func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppError) {
if len(userIDs) > model.CHANNEL_GROUP_MAX_USERS || len(userIDs) < model.CHANNEL_GROUP_MIN_USERS {
if len(userIDs) > model.ChannelGroupMaxUsers || len(userIDs) < model.ChannelGroupMinUsers {
return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest)
}
@@ -533,7 +533,7 @@ func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppEr
group := &model.Channel{
Name: model.GetGroupNameFromUserIds(userIDs),
DisplayName: model.GetGroupDisplayNameFromUsers(users, true),
Type: model.CHANNEL_GROUP,
Type: model.ChannelTypeGroup,
}
channel, nErr := a.Srv().Store.Channel().Save(group, *a.Config().TeamSettings.MaxChannelsPerTeam)
@@ -596,7 +596,7 @@ func (a *App) createGroupChannel(userIDs []string) (*model.Channel, *model.AppEr
}
func (a *App) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) {
if len(userIDs) > model.CHANNEL_GROUP_MAX_USERS || len(userIDs) < model.CHANNEL_GROUP_MIN_USERS {
if len(userIDs) > model.ChannelGroupMaxUsers || len(userIDs) < model.ChannelGroupMinUsers {
return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest)
}
@@ -635,7 +635,7 @@ func (a *App) UpdateChannel(channel *model.Channel) (*model.Channel, *model.AppE
a.invalidateCacheForChannel(channel)
messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_UPDATED, "", channel.Id, "", nil)
messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelUpdated, "", channel.Id, "", nil)
messageWs.Add("channel", channel.ToJson())
a.Publish(messageWs)
@@ -647,7 +647,7 @@ func (a *App) CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model
scheme, err := a.CreateScheme(&model.Scheme{
Name: model.NewId(),
DisplayName: model.NewId(),
Scope: model.SCHEME_SCOPE_CHANNEL,
Scope: model.SchemeScopeChannel,
})
if err != nil {
return nil, err
@@ -690,10 +690,10 @@ func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel
}
if err := a.postChannelPrivacyMessage(c, user, channel); err != nil {
if channel.Type == model.CHANNEL_OPEN {
channel.Type = model.CHANNEL_PRIVATE
if channel.Type == model.ChannelTypeOpen {
channel.Type = model.ChannelTypePrivate
} else {
channel.Type = model.CHANNEL_OPEN
channel.Type = model.ChannelTypeOpen
}
// revert to previous channel privacy
a.UpdateChannel(channel)
@@ -702,7 +702,7 @@ func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel
a.invalidateCacheForChannel(channel)
messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CONVERTED, channel.TeamId, "", "", nil)
messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelConverted, channel.TeamId, "", "", nil)
messageWs.Add("channel_id", channel.Id)
a.Publish(messageWs)
@@ -726,13 +726,13 @@ func (a *App) postChannelPrivacyMessage(c *request.Context, user *model.User, ch
}
message := (map[string]string{
model.CHANNEL_OPEN: i18n.T("api.channel.change_channel_privacy.private_to_public"),
model.CHANNEL_PRIVATE: i18n.T("api.channel.change_channel_privacy.public_to_private"),
model.ChannelTypeOpen: i18n.T("api.channel.change_channel_privacy.private_to_public"),
model.ChannelTypePrivate: i18n.T("api.channel.change_channel_privacy.public_to_private"),
})[channel.Type]
post := &model.Post{
ChannelId: channel.Id,
Message: message,
Type: model.POST_CHANGE_CHANNEL_PRIVACY,
Type: model.PostTypeChangeChannelPrivacy,
UserId: authorId,
Props: model.StringInterface{
"username": authorUsername,
@@ -757,7 +757,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID
channel.DeleteAt = 0
a.invalidateCacheForChannel(channel)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_RESTORED, channel.TeamId, "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelRestored, channel.TeamId, "", "", nil)
message.Add("channel_id", channel.Id)
a.Publish(message)
@@ -782,7 +782,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID
post := &model.Post{
ChannelId: channel.Id,
Message: T("api.channel.restore_channel.unarchived", map[string]interface{}{"Username": user.Username}),
Type: model.POST_CHANNEL_RESTORED,
Type: model.PostTypeChannelRestored,
UserId: userID,
Props: model.StringInterface{
"username": user.Username,
@@ -803,7 +803,7 @@ func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID
post := &model.Post{
ChannelId: channel.Id,
Message: i18n.T("api.channel.restore_channel.unarchived", map[string]interface{}{"Username": systemBot.Username}),
Type: model.POST_CHANNEL_RESTORED,
Type: model.PostTypeChannelRestored,
UserId: systemBot.UserId,
Props: model.StringInterface{
"username": systemBot.Username,
@@ -893,9 +893,9 @@ func (a *App) GetTeamSchemeChannelRoles(teamID string) (guestRoleName, userRoleN
userRoleName = scheme.DefaultChannelUserRole
adminRoleName = scheme.DefaultChannelAdminRole
} else {
guestRoleName = model.CHANNEL_GUEST_ROLE_ID
userRoleName = model.CHANNEL_USER_ROLE_ID
adminRoleName = model.CHANNEL_ADMIN_ROLE_ID
guestRoleName = model.ChannelGuestRoleId
userRoleName = model.ChannelUserRoleId
adminRoleName = model.ChannelAdminRoleId
}
return
@@ -994,7 +994,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM
}
a.sendUpdatedRoleEvent(adminRole)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_SCHEME_UPDATED, "", channel.Id, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelSchemeUpdated, "", channel.Id, "", nil)
a.Publish(message)
mlog.Info("Permission scheme created.", mlog.String("channel_id", channel.Id), mlog.String("channel_name", channel.Name))
} else {
@@ -1052,7 +1052,7 @@ func (a *App) PatchChannelModerationsForChannel(channel *model.Channel, channelM
return nil, err
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_SCHEME_UPDATED, "", channel.Id, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelSchemeUpdated, "", channel.Id, "", nil)
a.Publish(message)
memberRole = higherScopedMemberRole
@@ -1199,7 +1199,7 @@ func (a *App) UpdateChannelMemberSchemeRoles(channelID string, userID string, is
// If the migration is not completed, we also need to check the default channel_admin/channel_user roles are not present in the roles field.
if err = a.IsPhase2MigrationCompleted(); err != nil {
member.ExplicitRoles = RemoveRoles([]string{model.CHANNEL_GUEST_ROLE_ID, model.CHANNEL_USER_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID}, member.ExplicitRoles)
member.ExplicitRoles = RemoveRoles([]string{model.ChannelGuestRoleId, model.ChannelUserRoleId, model.ChannelAdminRoleId}, member.ExplicitRoles)
}
return a.updateChannelMember(member)
@@ -1213,24 +1213,24 @@ func (a *App) UpdateChannelMemberNotifyProps(data map[string]string, channelID s
}
// update whichever notify properties have been provided, but don't change the others
if markUnread, exists := data[model.MARK_UNREAD_NOTIFY_PROP]; exists {
member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] = markUnread
if markUnread, exists := data[model.MarkUnreadNotifyProp]; exists {
member.NotifyProps[model.MarkUnreadNotifyProp] = markUnread
}
if desktop, exists := data[model.DESKTOP_NOTIFY_PROP]; exists {
member.NotifyProps[model.DESKTOP_NOTIFY_PROP] = desktop
if desktop, exists := data[model.DesktopNotifyProp]; exists {
member.NotifyProps[model.DesktopNotifyProp] = desktop
}
if email, exists := data[model.EMAIL_NOTIFY_PROP]; exists {
member.NotifyProps[model.EMAIL_NOTIFY_PROP] = email
if email, exists := data[model.EmailNotifyProp]; exists {
member.NotifyProps[model.EmailNotifyProp] = email
}
if push, exists := data[model.PUSH_NOTIFY_PROP]; exists {
member.NotifyProps[model.PUSH_NOTIFY_PROP] = push
if push, exists := data[model.PushNotifyProp]; exists {
member.NotifyProps[model.PushNotifyProp] = push
}
if ignoreChannelMentions, exists := data[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP]; exists {
member.NotifyProps[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP] = ignoreChannelMentions
if ignoreChannelMentions, exists := data[model.IgnoreChannelMentionsNotifyProp]; exists {
member.NotifyProps[model.IgnoreChannelMentionsNotifyProp] = ignoreChannelMentions
}
member, err = a.updateChannelMember(member)
@@ -1261,7 +1261,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe
a.InvalidateCacheForUser(member.UserId)
// Notify the clients that the member notify props changed
evt := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", member.UserId, nil)
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil)
evt.Add("channelMember", member.ToJson())
a.Publish(evt)
@@ -1317,8 +1317,8 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s
return err
}
if channel.Name == model.DEFAULT_CHANNEL {
err := model.NewAppError("deleteChannel", "api.channel.delete_channel.cannot.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest)
if channel.Name == model.DefaultChannelName {
err := model.NewAppError("deleteChannel", "api.channel.delete_channel.cannot.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest)
return err
}
@@ -1328,7 +1328,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s
post := &model.Post{
ChannelId: channel.Id,
Message: fmt.Sprintf(T("api.channel.delete_channel.archived"), user.Username),
Type: model.POST_CHANNEL_DELETED,
Type: model.PostTypeChannelDeleted,
UserId: userID,
Props: model.StringInterface{
"username": user.Username,
@@ -1349,7 +1349,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s
post := &model.Post{
ChannelId: channel.Id,
Message: fmt.Sprintf(i18n.T("api.channel.delete_channel.archived"), systemBot.Username),
Type: model.POST_CHANNEL_DELETED,
Type: model.PostTypeChannelDeleted,
UserId: systemBot.UserId,
Props: model.StringInterface{
"username": systemBot.Username,
@@ -1383,7 +1383,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s
}
a.invalidateCacheForChannel(channel)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_DELETED, channel.TeamId, "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelDeleted, channel.TeamId, "", "", nil)
message.Add("channel_id", channel.Id)
message.Add("delete_at", deleteAt)
a.Publish(message)
@@ -1392,7 +1392,7 @@ func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID s
}
func (a *App) addUserToChannel(user *model.User, channel *model.Channel) (*model.ChannelMember, *model.AppError) {
if channel.Type != model.CHANNEL_OPEN && channel.Type != model.CHANNEL_PRIVATE {
if channel.Type != model.ChannelTypeOpen && channel.Type != model.ChannelTypePrivate {
return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest)
}
@@ -1472,7 +1472,7 @@ func (a *App) AddUserToChannel(user *model.User, channel *model.Channel, skipTea
return nil, err
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_ADDED, "", channel.Id, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventUserAdded, "", channel.Id, "", nil)
message.Add("user_id", user.Id)
message.Add("team_id", channel.TeamId)
a.Publish(message)
@@ -1560,7 +1560,7 @@ func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError
preference := model.Preference{
UserId: user.Id,
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Category: model.PreferenceCategoryDirectChannelShow,
Name: profile.Id,
Value: "true",
}
@@ -1597,7 +1597,7 @@ func (a *App) PostUpdateChannelHeaderMessage(c *request.Context, userID string,
post := &model.Post{
ChannelId: channel.Id,
Message: message,
Type: model.POST_HEADER_CHANGE,
Type: model.PostTypeHeaderChange,
UserId: userID,
Props: model.StringInterface{
"username": user.Username,
@@ -1631,7 +1631,7 @@ func (a *App) PostUpdateChannelPurposeMessage(c *request.Context, userID string,
post := &model.Post{
ChannelId: channel.Id,
Message: message,
Type: model.POST_PURPOSE_CHANGE,
Type: model.PostTypePurposeChange,
UserId: userID,
Props: model.StringInterface{
"username": user.Username,
@@ -1657,7 +1657,7 @@ func (a *App) PostUpdateChannelDisplayNameMessage(c *request.Context, userID str
post := &model.Post{
ChannelId: channel.Id,
Message: message,
Type: model.POST_DISPLAYNAME_CHANGE,
Type: model.PostTypeDisplaynameChange,
UserId: userID,
Props: model.StringInterface{
"username": user.Username,
@@ -1984,7 +1984,7 @@ func (a *App) GetChannelUnread(channelID, userID string) (*model.ChannelUnread,
}
}
if channelUnread.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_MARK_UNREAD_MENTION {
if channelUnread.NotifyProps[model.MarkUnreadNotifyProp] == model.ChannelMarkUnreadMention {
channelUnread.MsgCount = 0
channelUnread.MsgCountRoot = 0
}
@@ -2024,7 +2024,7 @@ func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID str
user := uresult.Data.(*model.User)
if channel.Type != model.CHANNEL_OPEN {
if channel.Type != model.ChannelTypeOpen {
return model.NewAppError("JoinChannel", "api.channel.join_channel.permissions.app_error", nil, "", http.StatusBadRequest)
}
@@ -2052,11 +2052,11 @@ func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID str
func (a *App) postJoinChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError {
message := fmt.Sprintf(i18n.T("api.channel.join_channel.post_and_forget"), user.Username)
postType := model.POST_JOIN_CHANNEL
postType := model.PostTypeJoinChannel
if user.IsGuest() {
message = fmt.Sprintf(i18n.T("api.channel.guest_join_channel.post_and_forget"), user.Username)
postType = model.POST_GUEST_JOIN_CHANNEL
postType = model.PostTypeGuestJoinChannel
}
post := &model.Post{
@@ -2080,7 +2080,7 @@ func (a *App) postJoinTeamMessage(c *request.Context, user *model.User, channel
post := &model.Post{
ChannelId: channel.Id,
Message: fmt.Sprintf(i18n.T("api.team.join_team.post_and_forget"), user.Username),
Type: model.POST_JOIN_TEAM,
Type: model.PostTypeJoinTeam,
UserId: user.Id,
Props: model.StringInterface{
"username": user.Username,
@@ -2150,7 +2150,7 @@ func (a *App) LeaveChannel(c *request.Context, channelID string, userID string)
return err
}
if channel.Type == model.CHANNEL_PRIVATE && membersCount == 1 {
if channel.Type == model.ChannelTypePrivate && membersCount == 1 {
err := model.NewAppError("LeaveChannel", "api.channel.leave.last_member.app_error", nil, "userId="+user.Id, http.StatusBadRequest)
return err
}
@@ -2159,7 +2159,7 @@ func (a *App) LeaveChannel(c *request.Context, channelID string, userID string)
return err
}
if channel.Name == model.DEFAULT_CHANNEL && !*a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages {
if channel.Name == model.DefaultChannelName && !*a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages {
return nil
}
@@ -2177,7 +2177,7 @@ func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, chan
// treat this as a username mention even though the user has now left the channel.
// The client renders its own system message, ignoring this value altogether.
Message: fmt.Sprintf(i18n.T("api.channel.leave.left"), fmt.Sprintf("@%s", user.Username)),
Type: model.POST_LEAVE_CHANNEL,
Type: model.PostTypeLeaveChannel,
UserId: user.Id,
Props: model.StringInterface{
"username": user.Username,
@@ -2193,11 +2193,11 @@ func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, chan
func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError {
message := fmt.Sprintf(i18n.T("api.channel.add_member.added"), addedUser.Username, user.Username)
postType := model.POST_ADD_TO_CHANNEL
postType := model.PostTypeAddToChannel
if addedUser.IsGuest() {
message = fmt.Sprintf(i18n.T("api.channel.add_guest.added"), addedUser.Username, user.Username)
postType = model.POST_ADD_GUEST_TO_CHANNEL
postType = model.PostTypeAddGuestToChannel
}
post := &model.Post{
@@ -2207,10 +2207,10 @@ func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, adde
UserId: user.Id,
RootId: postRootId,
Props: model.StringInterface{
"userId": user.Id,
"username": user.Username,
model.POST_PROPS_ADDED_USER_ID: addedUser.Id,
"addedUsername": addedUser.Username,
"userId": user.Id,
"username": user.Username,
model.PostPropsAddedUserId: addedUser.Id,
"addedUsername": addedUser.Username,
},
}
@@ -2225,14 +2225,14 @@ func (a *App) postAddToTeamMessage(c *request.Context, user *model.User, addedUs
post := &model.Post{
ChannelId: channel.Id,
Message: fmt.Sprintf(i18n.T("api.team.add_user_to_team.added"), addedUser.Username, user.Username),
Type: model.POST_ADD_TO_TEAM,
Type: model.PostTypeAddToTeam,
UserId: user.Id,
RootId: postRootId,
Props: model.StringInterface{
"userId": user.Id,
"username": user.Username,
model.POST_PROPS_ADDED_USER_ID: addedUser.Id,
"addedUsername": addedUser.Username,
"userId": user.Id,
"username": user.Username,
model.PostPropsAddedUserId: addedUser.Id,
"addedUsername": addedUser.Username,
},
}
@@ -2260,7 +2260,7 @@ func (a *App) postRemoveFromChannelMessage(c *request.Context, removerUserId str
// treat this as a username mention even though the user has now left the channel.
// The client renders its own system message, ignoring this value altogether.
Message: fmt.Sprintf(i18n.T("api.channel.remove_member.removed"), fmt.Sprintf("@%s", removedUser.Username)),
Type: model.POST_REMOVE_FROM_CHANNEL,
Type: model.PostTypeRemoveFromChannel,
UserId: messageUserId,
Props: model.StringInterface{
"removedUserId": removedUser.Id,
@@ -2288,9 +2288,9 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r
}
isGuest := user.IsGuest()
if channel.Name == model.DEFAULT_CHANNEL {
if channel.Name == model.DefaultChannelName {
if !isGuest {
return model.NewAppError("RemoveUserFromChannel", "api.channel.remove.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}, "", http.StatusBadRequest)
return model.NewAppError("RemoveUserFromChannel", "api.channel.remove.default.app_error", map[string]interface{}{"Channel": model.DefaultChannelName}, "", http.StatusBadRequest)
}
}
@@ -2351,13 +2351,13 @@ func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, r
})
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_REMOVED, "", channel.Id, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventUserRemoved, "", channel.Id, "", nil)
message.Add("user_id", userIDToRemove)
message.Add("remover_id", removerUserId)
a.Publish(message)
// because the removed user no longer belongs to the channel we need to send a separate websocket event
userMsg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_REMOVED, "", "", userIDToRemove, nil)
userMsg := model.NewWebSocketEvent(model.WebsocketEventUserRemoved, "", "", userIDToRemove, nil)
userMsg.Add("channel_id", channel.Id)
userMsg.Add("remover_id", removerUserId)
a.Publish(userMsg)
@@ -2410,15 +2410,15 @@ func (a *App) GetNumberOfChannelsOnTeam(teamID string) (int, *model.AppError) {
func (a *App) SetActiveChannel(userID string, channelID string) *model.AppError {
status, err := a.GetStatus(userID)
oldStatus := model.STATUS_OFFLINE
oldStatus := model.StatusOffline
if err != nil {
status = &model.Status{UserId: userID, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: channelID}
status = &model.Status{UserId: userID, Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: channelID}
} else {
oldStatus = status.Status
status.ActiveChannel = channelID
if !status.Manual && channelID != "" {
status.Status = model.STATUS_ONLINE
status.Status = model.StatusOnline
}
status.LastActivityAt = model.GetMillis()
}
@@ -2445,7 +2445,7 @@ func (a *App) UpdateChannelLastViewedAt(channelIDs []string, userID string) *mod
if *a.Config().ServiceSettings.EnableChannelViewedMessages {
for _, channelID := range channelIDs {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_VIEWED, "", "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelViewed, "", "", userID, nil)
message.Add("channel_id", channelID)
a.Publish(message)
}
@@ -2455,12 +2455,12 @@ func (a *App) UpdateChannelLastViewedAt(channelIDs []string, userID string) *mod
}
func (a *App) isCRTEnabledForUser(userID string) bool {
if *a.Config().ServiceSettings.CollapsedThreads == model.COLLAPSED_THREADS_DISABLED {
if *a.Config().ServiceSettings.CollapsedThreads == model.CollapsedThreadsDisabled {
return false
}
threadsEnabled := *a.Config().ServiceSettings.CollapsedThreads == model.COLLAPSED_THREADS_DEFAULT_ON
threadsEnabled := *a.Config().ServiceSettings.CollapsedThreads == model.CollapsedThreadsDefaultOn
// check if a participant has overridden collapsed threads settings
if preference, err := a.Srv().Store.Preference().Get(userID, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED); err == nil {
if preference, err := a.Srv().Store.Preference().Get(userID, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled); err == nil {
threadsEnabled = preference.Value == "on"
}
return threadsEnabled
@@ -2537,7 +2537,7 @@ func (a *App) MarkChannelAsUnreadFromPost(postID string, userID string, collapse
thread.Post.SanitizeProps()
payload := thread.ToJson()
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_UPDATED, channel.TeamId, "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, channel.TeamId, "", userID, nil)
message.Add("thread", payload)
a.Publish(message)
}
@@ -2653,7 +2653,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st
payload := thread.ToJson()
if a.isCRTEnabledForUser(userID) {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_UPDATED, channel.TeamId, "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, channel.TeamId, "", userID, nil)
message.Add("thread", payload)
a.Publish(message)
}
@@ -2665,7 +2665,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(postID string, userID st
}
func (a *App) sendWebSocketPostUnreadEvent(channelUnread *model.ChannelUnreadAt, postID string, withMsgCountRoot bool) {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_UNREAD, channelUnread.TeamId, channelUnread.ChannelId, channelUnread.UserId, nil)
message := model.NewWebSocketEvent(model.WebsocketEventPostUnread, channelUnread.TeamId, channelUnread.ChannelId, channelUnread.UserId, nil)
message.Add("msg_count", channelUnread.MsgCount)
if withMsgCountRoot {
message.Add("msg_count_root", channelUnread.MsgCountRoot)
@@ -2810,22 +2810,22 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe
continue
}
notify := member.NotifyProps[model.PUSH_NOTIFY_PROP]
if notify == model.CHANNEL_NOTIFY_DEFAULT {
notify := member.NotifyProps[model.PushNotifyProp]
if notify == model.ChannelNotifyDefault {
user, err := a.GetUser(userID)
if err != nil {
mlog.Warn("Failed to get user", mlog.String("user_id", userID), mlog.Err(err))
continue
}
notify = user.NotifyProps[model.PUSH_NOTIFY_PROP]
notify = user.NotifyProps[model.PushNotifyProp]
}
if notify == model.USER_NOTIFY_ALL {
if notify == model.UserNotifyAll {
if count, err := a.Srv().Store.User().GetAnyUnreadPostCountForChannel(userID, channelID); err == nil {
if count > 0 {
channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelID)
}
}
} else if notify == model.USER_NOTIFY_MENTION || channel.Type == model.CHANNEL_DIRECT {
} else if notify == model.UserNotifyMention || channel.Type == model.ChannelTypeDirect {
if count, err := a.Srv().Store.User().GetUnreadCountForChannel(userID, channelID); err == nil {
if count > 0 {
channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelID)
@@ -2847,7 +2847,7 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe
if *a.Config().ServiceSettings.EnableChannelViewedMessages {
for _, channelID := range channelIDs {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_VIEWED, "", "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelViewed, "", "", userID, nil)
message.Add("channel_id", channelID)
a.Publish(message)
}
@@ -2864,7 +2864,7 @@ func (a *App) MarkChannelsAsViewed(channelIDs []string, userID string, currentSe
if a.isCRTEnabledForUser(userID) {
timestamp := model.GetMillis()
for _, channelID := range channelIDs {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_READ_CHANGED, "", channelID, userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventThreadReadChanged, "", channelID, userID, nil)
message.Add("timestamp", timestamp)
a.Publish(message)
}
@@ -2920,7 +2920,7 @@ func (a *App) PermanentDeleteChannel(channel *model.Channel) *model.AppError {
}
a.invalidateCacheForChannel(channel)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_DELETED, channel.TeamId, "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelDeleted, channel.TeamId, "", "", nil)
message.Add("channel_id", channel.Id)
message.Add("delete_at", deleteAt)
a.Publish(message)
@@ -3045,7 +3045,7 @@ func (a *App) postChannelMoveMessage(c *request.Context, user *model.User, chann
post := &model.Post{
ChannelId: channel.Id,
Message: fmt.Sprintf(i18n.T("api.team.move_channel.success"), previousTeam.Name),
Type: model.POST_MOVE_CHANNEL,
Type: model.PostTypeMoveChannel,
UserId: user.Id,
Props: model.StringInterface{
"username": user.Username,
@@ -3179,7 +3179,7 @@ func (a *App) setChannelsMuted(channelIDs []string, userID string, muted bool) (
for _, member := range updated {
a.invalidateCacheForChannelMembersNotifyProps(member.ChannelId)
evt := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", member.UserId, nil)
evt := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", member.UserId, nil)
evt.Add("channelMember", member.ToJson())
a.Publish(evt)
}
@@ -3231,7 +3231,7 @@ func (a *App) FillInChannelsProps(channelList *model.ChannelList) *model.AppErro
channelMentionsProp := make(map[string]interface{}, len(channelMentions[channel]))
for _, channelMention := range channelMentions[channel] {
if mentioned, ok := mentionedChannelsByName[channelMention]; ok {
if mentioned.Type == model.CHANNEL_OPEN {
if mentioned.Type == model.ChannelTypeOpen {
channelMentionsProp[mentioned.Name] = map[string]interface{}{
"display_name": mentioned.DisplayName,
}
@@ -3281,7 +3281,7 @@ func (a *App) forEachChannelMember(channelID string, f func(model.ChannelMember)
func (a *App) ClearChannelMembersCache(channelID string) {
clearSessionCache := func(channelMember model.ChannelMember) error {
a.ClearSessionCacheForUser(channelMember.UserId)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", channelMember.UserId, nil)
message := model.NewWebSocketEvent(model.WebsocketEventChannelMemberUpdated, "", "", channelMember.UserId, nil)
message.Add("channelMember", channelMember.ToJson())
a.Publish(message)
return nil

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

@@ -86,7 +86,7 @@ func (a *App) CreateSidebarCategory(userID, teamID string, newCategory *model.Si
return nil, model.NewAppError("CreateSidebarCategory", "app.channel.sidebar_categories.app_error", nil, err.Error(), http.StatusInternalServerError)
}
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_CREATED, teamID, "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryCreated, teamID, "", userID, nil)
message.Add("category_id", category.Id)
a.Publish(message)
return category, nil
@@ -106,7 +106,7 @@ func (a *App) UpdateSidebarCategoryOrder(userID, teamID string, categoryOrder []
return model.NewAppError("UpdateSidebarCategoryOrder", "app.channel.sidebar_categories.app_error", nil, err.Error(), http.StatusInternalServerError)
}
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_ORDER_UPDATED, teamID, "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryOrderUpdated, teamID, "", userID, nil)
message.Add("order", categoryOrder)
a.Publish(message)
return nil
@@ -118,7 +118,7 @@ func (a *App) UpdateSidebarCategories(userID, teamID string, categories []*model
return nil, model.NewAppError("UpdateSidebarCategories", "app.channel.sidebar_categories.app_error", nil, err.Error(), http.StatusInternalServerError)
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_UPDATED, teamID, "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryUpdated, teamID, "", userID, nil)
a.Publish(message)
a.muteChannelsForUpdatedCategories(userID, updatedCategories, originalCategories)
@@ -243,7 +243,7 @@ func (a *App) DeleteSidebarCategory(userID, teamID, categoryId string) *model.Ap
}
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_DELETED, teamID, "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryDeleted, teamID, "", userID, nil)
message.Add("category_id", categoryId)
a.Publish(message)

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

@@ -31,7 +31,7 @@ func TestPermanentDeleteChannel(t *testing.T) {
*cfg.ServiceSettings.EnableOutgoingWebhooks = true
})
channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false)
require.NotNil(t, channel, "Channel shouldn't be nil")
require.Nil(t, err)
defer func() {
@@ -169,7 +169,7 @@ func TestMoveChannel(t *testing.T) {
channel3 := &model.Channel{
DisplayName: "dn_" + model.NewId(),
Name: "name_" + model.NewId(),
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
TeamId: sourceTeam.Id,
CreatorId: th.BasicUser.Id,
}
@@ -352,7 +352,7 @@ func TestCreateChannelPublicCreatesChannelMemberHistoryRecord(t *testing.T) {
defer th.TearDown()
// creates a public channel and adds basic user to it
publicChannel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN)
publicChannel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen)
// there should be a ChannelMemberHistory record for the user
histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id)
@@ -367,7 +367,7 @@ func TestCreateChannelPrivateCreatesChannelMemberHistoryRecord(t *testing.T) {
defer th.TearDown()
// creates a private channel and adds basic user to it
privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE)
privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate)
// there should be a ChannelMemberHistory record for the user
histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id)
@@ -380,7 +380,7 @@ func TestCreateChannelDisplayNameTrimsWhitespace(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false)
defer th.App.PermanentDeleteChannel(channel)
require.Nil(t, err)
require.Equal(t, channel.DisplayName, "Public 1")
@@ -390,13 +390,13 @@ func TestUpdateChannelPrivacy(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE)
privateChannel.Type = model.CHANNEL_OPEN
privateChannel := th.createChannel(th.BasicTeam, model.ChannelTypePrivate)
privateChannel.Type = model.ChannelTypeOpen
publicChannel, err := th.App.UpdateChannelPrivacy(th.Context, privateChannel, th.BasicUser)
require.Nil(t, err, "Failed to update channel privacy.")
assert.Equal(t, publicChannel.Id, privateChannel.Id)
assert.Equal(t, publicChannel.Type, model.CHANNEL_OPEN)
assert.Equal(t, publicChannel.Type, model.ChannelTypeOpen)
}
func TestCreateGroupChannelCreatesChannelMemberHistoryRecord(t *testing.T) {
@@ -496,7 +496,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) {
groupUserIds = append(groupUserIds, th.BasicUser.Id)
groupUserIds = append(groupUserIds, user.Id)
channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN)
channel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen)
_, err = th.App.AddUserToChannel(user, channel, false)
require.Nil(t, err, "Failed to add user to channel.")
@@ -583,7 +583,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) {
groupUserIds = append(groupUserIds, th.BasicUser.Id)
groupUserIds = append(groupUserIds, user.Id)
channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN)
channel := th.createChannel(th.BasicTeam, model.ChannelTypeOpen)
_, err = th.App.AddChannelMember(th.Context, user.Id, channel, ChannelMemberOpts{})
require.Nil(t, err, "Failed to add user to channel.")
@@ -605,7 +605,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) {
if assert.Len(t, postList.Order, 1) {
post := postList.Posts[postList.Order[0]]
assert.Equal(t, model.POST_JOIN_CHANNEL, post.Type)
assert.Equal(t, model.PostTypeJoinChannel, post.Type)
assert.Equal(t, user.Id, post.UserId)
assert.Equal(t, user.Username, post.GetProp("username"))
}
@@ -682,15 +682,15 @@ func TestFillInChannelProps(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
channelPublic1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
channelPublic1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false)
require.Nil(t, err)
defer th.App.PermanentDeleteChannel(channelPublic1)
channelPublic2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
channelPublic2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false)
require.Nil(t, err)
defer th.App.PermanentDeleteChannel(channelPublic2)
channelPrivate, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Private", Name: "private", Type: model.CHANNEL_PRIVATE, TeamId: th.BasicTeam.Id}, false)
channelPrivate, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Private", Name: "private", Type: model.ChannelTypePrivate, TeamId: th.BasicTeam.Id}, false)
require.Nil(t, err)
defer th.App.PermanentDeleteChannel(channelPrivate)
@@ -699,13 +699,13 @@ func TestFillInChannelProps(t *testing.T) {
DisplayName: "dn_" + otherTeamId,
Name: "name" + otherTeamId,
Email: "success+" + otherTeamId + "@simulator.amazonses.com",
Type: model.TEAM_OPEN,
Type: model.TeamOpen,
}
otherTeam, err = th.App.CreateTeam(th.Context, otherTeam)
require.Nil(t, err)
defer th.App.PermanentDeleteTeam(otherTeam)
channelOtherTeam, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.CHANNEL_OPEN, TeamId: otherTeam.Id}, false)
channelOtherTeam, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.ChannelTypeOpen, TeamId: otherTeam.Id}, false)
require.Nil(t, err)
defer th.App.PermanentDeleteChannel(channelOtherTeam)
@@ -897,7 +897,7 @@ func TestRenameChannel(t *testing.T) {
}{
{
"Rename open channel",
th.createChannel(th.BasicTeam, model.CHANNEL_OPEN),
th.createChannel(th.BasicTeam, model.ChannelTypeOpen),
false,
"newchannelname",
"newchannelname",
@@ -905,7 +905,7 @@ func TestRenameChannel(t *testing.T) {
},
{
"Fail on rename open channel with bad name",
th.createChannel(th.BasicTeam, model.CHANNEL_OPEN),
th.createChannel(th.BasicTeam, model.ChannelTypeOpen),
true,
"6zii9a9g6pruzj451x3esok54h__wr4j4g8zqtnhmkw771pfpynqwo",
"",
@@ -913,7 +913,7 @@ func TestRenameChannel(t *testing.T) {
},
{
"Success on rename open channel with consecutive underscores in name",
th.createChannel(th.BasicTeam, model.CHANNEL_OPEN),
th.createChannel(th.BasicTeam, model.ChannelTypeOpen),
false,
"foo__bar",
"foo__bar",
@@ -988,7 +988,7 @@ func TestGetChannelsForUser(t *testing.T) {
channel := &model.Channel{
DisplayName: "Public",
Name: "public",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
CreatorId: th.BasicUser.Id,
TeamId: th.BasicTeam.Id,
}
@@ -1034,7 +1034,7 @@ func TestGetPublicChannelsForTeam(t *testing.T) {
channel := model.Channel{
DisplayName: fmt.Sprintf("Public %v", i),
Name: fmt.Sprintf("public_%v", i),
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
TeamId: team.Id,
}
var rchannel *model.Channel
@@ -1067,7 +1067,7 @@ func TestGetPrivateChannelsForTeam(t *testing.T) {
channel := model.Channel{
DisplayName: fmt.Sprintf("Private %v", i),
Name: fmt.Sprintf("private_%v", i),
Type: model.CHANNEL_PRIVATE,
Type: model.ChannelTypePrivate,
TeamId: team.Id,
}
var rchannel *model.Channel
@@ -1189,13 +1189,13 @@ func TestSearchChannelsForUser(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
c1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
c1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false)
require.Nil(t, err)
c2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
c2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false)
require.Nil(t, err)
c3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
c3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.ChannelTypeOpen, TeamId: th.BasicTeam.Id}, false)
require.Nil(t, err)
defer func() {
@@ -1539,7 +1539,7 @@ func TestPatchChannelModerationsForChannel(t *testing.T) {
manageMembers := model.ChannelModeratedPermissions[2]
channelMentions := model.ChannelModeratedPermissions[3]
nonChannelModeratedPermission := model.PERMISSION_CREATE_BOT.Id
nonChannelModeratedPermission := model.PermissionCreateBot.Id
testCases := []struct {
Name string
@@ -1942,11 +1942,11 @@ func TestPatchChannelModerationsForChannel(t *testing.T) {
_, err := th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), addCreatePosts)
require.Nil(t, err)
require.True(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PERMISSION_CREATE_POST))
require.True(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PermissionCreatePost))
_, err = th.App.PatchChannelModerationsForChannel(channel.DeepCopy(), removeCreatePosts)
require.Nil(t, err)
require.False(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PERMISSION_CREATE_POST))
require.False(t, th.App.SessionHasPermissionToChannel(mockSession, channel.Id, model.PermissionCreatePost))
})
}
@@ -1963,7 +1963,7 @@ func TestMarkChannelsAsViewedPanic(t *testing.T) {
mockChannelStore.On("Get", "channelID", true).Return(&model.Channel{}, nil)
mockChannelStore.On("GetMember", context.Background(), "channelID", "userID").Return(&model.ChannelMember{
NotifyProps: model.StringMap{
model.PUSH_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT,
model.PushNotifyProp: model.ChannelNotifyDefault,
}}, nil)
times := map[string]int64{
"userID": 1,
@@ -2049,14 +2049,14 @@ func TestViewChannelCollapsedThreadsTurnedOff(t *testing.T) {
defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS")
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
// Turn off CRT for user
preference := model.Preference{
UserId: u1.Id,
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameCollapsedThreadsEnabled,
Value: "off",
}
var preferences model.Preferences
@@ -2123,7 +2123,7 @@ func TestMarkChannelAsUnreadFromPostCollapsedThreadsTurnedOff(t *testing.T) {
defer th.TearDown()
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
th.AddUserToChannel(th.BasicUser2, th.BasicChannel)
@@ -2131,8 +2131,8 @@ func TestMarkChannelAsUnreadFromPostCollapsedThreadsTurnedOff(t *testing.T) {
// Turn off CRT for user
preference := model.Preference{
UserId: th.BasicUser.Id,
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameCollapsedThreadsEnabled,
Value: "off",
}
var preferences model.Preferences
@@ -2210,7 +2210,7 @@ func TestMarkUnreadWithThreads(t *testing.T) {
defer th.TearDown()
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
t.Run("Follow threads only if specified", func(t *testing.T) {

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

@@ -17,7 +17,7 @@ func (a *App) getSysAdminsEmailRecipients() ([]*model.User, *model.AppError) {
userOptions := &model.UserGetOptions{
Page: 0,
PerPage: 100,
Role: model.SYSTEM_ADMIN_ROLE_ID,
Role: model.SystemAdminRoleId,
Inactive: false,
}
return a.GetUsers(userOptions)

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

@@ -15,7 +15,7 @@ func TestClusterDiscoveryService(t *testing.T) {
defer th.TearDown()
ds := th.App.NewClusterDiscoveryService()
ds.Type = model.CDS_TYPE_APP
ds.Type = model.CDSTypeApp
ds.ClusterName = "ClusterA"
ds.AutoFillHostname()

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

@@ -53,19 +53,19 @@ func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) {
// The cluster event handlers are spread across this function and NewLocalCacheLayer.
// Be careful to not have duplicated handlers here and there.
func (s *Server) registerClusterHandlers() {
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PUBLISH, s.clusterPublishHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_UPDATE_STATUS, s.clusterUpdateStatusHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, s.clusterInvalidateAllCachesHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBERS_NOTIFY_PROPS, s.clusterInvalidateCacheForChannelMembersNotifyPropHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_BY_NAME, s.clusterInvalidateCacheForChannelByNameHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, s.clusterInvalidateCacheForUserHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, s.clusterInvalidateCacheForUserTeamsHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_BUSY_STATE_CHANGED, s.clusterBusyStateChgHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, s.clusterClearSessionCacheForUserHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, s.clusterClearSessionCacheForAllUsersHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INSTALL_PLUGIN, s.clusterInstallPluginHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_REMOVE_PLUGIN, s.clusterRemovePluginHandler)
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PLUGIN_EVENT, s.clusterPluginEventHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventPublish, s.clusterPublishHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventUpdateStatus, s.clusterUpdateStatusHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateAllCaches, s.clusterInvalidateAllCachesHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelMembersNotifyProps, s.clusterInvalidateCacheForChannelMembersNotifyPropHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelByName, s.clusterInvalidateCacheForChannelByNameHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUser, s.clusterInvalidateCacheForUserHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUserTeams, s.clusterInvalidateCacheForUserTeamsHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventBusyStateChanged, s.clusterBusyStateChgHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForUser, s.clusterClearSessionCacheForUserHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForAllUsers, s.clusterClearSessionCacheForAllUsersHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInstallPlugin, s.clusterInstallPluginHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventRemovePlugin, s.clusterRemovePluginHandler)
s.Cluster.RegisterClusterMessageHandler(model.ClusterEventPluginEvent, s.clusterPluginEventHandler)
}
func (s *Server) clusterPublishHandler(msg *model.ClusterMessage) {

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

@@ -56,7 +56,7 @@ func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID str
post.CreateAt = model.GetMillis()
if strings.HasPrefix(post.Type, model.POST_SYSTEM_MESSAGE_PREFIX) {
if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) {
err := model.NewAppError("CreateCommandPost", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest)
return nil, err
}
@@ -65,11 +65,11 @@ func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID str
model.ParseSlackAttachment(post, response.Attachments)
}
if response.ResponseType == model.COMMAND_RESPONSE_TYPE_IN_CHANNEL {
if response.ResponseType == model.CommandResponseTypeInChannel {
return a.CreatePostMissingChannel(c, post, true)
}
if (response.ResponseType == "" || response.ResponseType == model.COMMAND_RESPONSE_TYPE_EPHEMERAL) && (response.Text != "" || response.Attachments != nil) {
if (response.ResponseType == "" || response.ResponseType == model.CommandResponseTypeEphemeral) && (response.Text != "" || response.Attachments != nil) {
post.ParentId = ""
a.SendEphemeralPost(post.UserId, post)
}
@@ -477,7 +477,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command
// Prepare the request
var req *http.Request
var err error
if cmd.Method == model.COMMAND_METHOD_GET {
if cmd.Method == model.CommandMethodGet {
req, err = http.NewRequest(http.MethodGet, cmd.URL, nil)
} else {
req, err = http.NewRequest(http.MethodPost, cmd.URL, strings.NewReader(p.Encode()))
@@ -487,7 +487,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command
return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed.app_error", map[string]interface{}{"Trigger": cmd.Trigger}, err.Error(), http.StatusInternalServerError)
}
if cmd.Method == model.COMMAND_METHOD_GET {
if cmd.Method == model.CommandMethodGet {
if req.URL.RawQuery != "" {
req.URL.RawQuery += "&"
}
@@ -496,7 +496,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Token "+cmd.Token)
if cmd.Method == model.COMMAND_METHOD_POST {
if cmd.Method == model.CommandMethodPost {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}

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

@@ -54,7 +54,7 @@ func (a *App) getSuggestions(c *request.Context, commandArgs *model.CommandArgs,
if index == -1 { // no space in input
for _, command := range commands {
if strings.HasPrefix(command.Trigger, strings.ToLower(inputToBeParsed)) && (command.RoleID == roleID || roleID == model.SYSTEM_ADMIN_ROLE_ID || roleID == "") {
if strings.HasPrefix(command.Trigger, strings.ToLower(inputToBeParsed)) && (command.RoleID == roleID || roleID == model.SystemAdminRoleId || roleID == "") {
s := model.AutocompleteSuggestion{
Complete: inputParsed + command.Trigger,
Suggestion: command.Trigger,
@@ -71,7 +71,7 @@ func (a *App) getSuggestions(c *request.Context, commandArgs *model.CommandArgs,
if command.Trigger != strings.ToLower(inputToBeParsed[:index]) {
continue
}
if roleID != "" && roleID != model.SYSTEM_ADMIN_ROLE_ID && roleID != command.RoleID {
if roleID != "" && roleID != model.SystemAdminRoleId && roleID != command.RoleID {
continue
}
toBeParsed := inputToBeParsed[index+1:]

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

@@ -208,21 +208,21 @@ func TestSuggestions(t *testing.T) {
jira := createJiraAutocompleteData()
emptyCmdArgs := &model.CommandArgs{}
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SYSTEM_ADMIN_ROLE_ID)
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, jira.Trigger, suggestions[0].Complete)
assert.Equal(t, jira.Trigger, suggestions[0].Suggestion)
assert.Equal(t, "[command]", suggestions[0].Hint)
assert.Equal(t, jira.HelpText, suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira create", suggestions[0].Complete)
assert.Equal(t, "create", suggestions[0].Suggestion)
assert.Equal(t, "[issue text]", suggestions[0].Hint)
assert.Equal(t, "Create a new Issue", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SystemAdminRoleId)
assert.Len(t, suggestions, 2)
assert.Equal(t, "jira create", suggestions[1].Complete)
assert.Equal(t, "create", suggestions[1].Suggestion)
@@ -233,27 +233,27 @@ func TestSuggestions(t *testing.T) {
assert.Equal(t, "[url]", suggestions[0].Hint)
assert.Equal(t, "Connect your Mattermost account to your Jira account", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira create ", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "[text]", suggestions[0].Hint)
assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira create some", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "[text]", suggestions[0].Hint)
assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 0)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SystemAdminRoleId)
assert.Len(t, suggestions, 0)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SystemAdminRoleId)
assert.Len(t, suggestions, 2)
assert.Equal(t, "jira settings notifications On", suggestions[0].Complete)
assert.Equal(t, "On", suggestions[0].Suggestion)
@@ -264,48 +264,48 @@ func TestSuggestions(t *testing.T) {
assert.Equal(t, "Turn notifications off", suggestions[1].Hint)
assert.Equal(t, "", suggestions[1].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 11)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_USER_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SystemUserRoleId)
assert.Len(t, suggestions, 9)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira create \"some issue text", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "[text]", suggestions[0].Hint)
assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete)
assert.Equal(t, "--zone", suggestions[0].Suggestion)
assert.Equal(t, "", suggestions[0].Hint)
assert.Equal(t, "Set timezone", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete)
assert.Equal(t, "--zone", suggestions[0].Suggestion)
assert.Equal(t, "", suggestions[0].Hint)
assert.Equal(t, "Set timezone", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint)
assert.Equal(t, "Set timezone", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "jira timezone --zone bla", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint)
assert.Equal(t, "Set timezone", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SystemAdminRoleId)
assert.Len(t, suggestions, 0)
commandA := &model.Command{
@@ -320,7 +320,7 @@ func TestSuggestions(t *testing.T) {
Trigger: "charles",
AutocompleteData: model.NewAutocompleteData("charles", "", ""),
}
suggestions = th.App.GetSuggestions(th.Context, emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.GetSuggestions(th.Context, emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SystemAdminRoleId)
assert.Len(t, suggestions, 3)
assert.Equal(t, "alice", suggestions[0].Complete)
assert.Equal(t, "bob", suggestions[1].Complete)
@@ -334,14 +334,14 @@ func TestCommandWithOptionalArgs(t *testing.T) {
command := createCommandWithOptionalArgs()
emptyCmdArgs := &model.CommandArgs{}
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SYSTEM_ADMIN_ROLE_ID)
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, command.Trigger, suggestions[0].Complete)
assert.Equal(t, command.Trigger, suggestions[0].Suggestion)
assert.Equal(t, "", suggestions[0].Hint)
assert.Equal(t, command.HelpText, suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 4)
assert.Equal(t, "command subcommand1", suggestions[0].Complete)
assert.Equal(t, "subcommand1", suggestions[0].Suggestion)
@@ -356,7 +356,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[2].Hint)
assert.Equal(t, "", suggestions[2].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 2)
assert.Equal(t, "command subcommand1 item1", suggestions[0].Complete)
assert.Equal(t, "item1", suggestions[0].Suggestion)
@@ -367,21 +367,21 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[1].Hint)
assert.Equal(t, "", suggestions[1].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "command subcommand1 item1 --name2 ", suggestions[0].Complete)
assert.Equal(t, "--name2", suggestions[0].Suggestion)
assert.Equal(t, "", suggestions[0].Hint)
assert.Equal(t, "arg2", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "command subcommand1 item1 --name2 bla", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "", suggestions[0].Hint)
assert.Equal(t, "arg2", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 2)
assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete)
assert.Equal(t, "--name1", suggestions[0].Suggestion)
@@ -392,7 +392,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[1].Hint)
assert.Equal(t, "arg2", suggestions[1].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SystemAdminRoleId)
assert.Len(t, suggestions, 2)
assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete)
assert.Equal(t, "--name1", suggestions[0].Suggestion)
@@ -403,7 +403,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[1].Hint)
assert.Equal(t, "arg2", suggestions[1].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 3)
assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete)
assert.Equal(t, "item1", suggestions[0].Suggestion)
@@ -418,7 +418,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[2].Hint)
assert.Equal(t, "arg3", suggestions[2].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SystemAdminRoleId)
assert.Len(t, suggestions, 3)
assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete)
assert.Equal(t, "item1", suggestions[0].Suggestion)
@@ -433,24 +433,24 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[2].Hint)
assert.Equal(t, "arg3", suggestions[2].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "command subcommand2 --name1 item1 ", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "", suggestions[0].Hint)
assert.Equal(t, "arg2", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "command subcommand2 --name1 item1 bla ", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
assert.Equal(t, "", suggestions[0].Hint)
assert.Equal(t, "arg3", suggestions[0].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 0)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 3)
assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete)
assert.Equal(t, "--name1", suggestions[0].Suggestion)
@@ -465,7 +465,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[2].Hint)
assert.Equal(t, "arg3", suggestions[2].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SystemAdminRoleId)
assert.Len(t, suggestions, 3)
assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete)
assert.Equal(t, "--name1", suggestions[0].Suggestion)
@@ -480,7 +480,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[2].Hint)
assert.Equal(t, "arg3", suggestions[2].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 2)
assert.Equal(t, "command subcommand3 --name1 item1", suggestions[0].Complete)
assert.Equal(t, "item1", suggestions[0].Suggestion)
@@ -491,7 +491,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "", suggestions[1].Hint)
assert.Equal(t, "", suggestions[1].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 2)
assert.Equal(t, "command subcommand4 item1", suggestions[0].Complete)
assert.Equal(t, "item1", suggestions[0].Suggestion)
@@ -502,7 +502,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
assert.Equal(t, "message", suggestions[1].Hint)
assert.Equal(t, "help4", suggestions[1].Description)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 1)
assert.Equal(t, "command subcommand4 item1 ", suggestions[0].Complete)
assert.Equal(t, "", suggestions[0].Suggestion)
@@ -591,7 +591,7 @@ func createJiraAutocompleteData() *model.AutocompleteData {
jira.AddCommand(timezone)
install := model.NewAutocompleteData("install", "", "Connect Mattermost to a Jira instance")
install.RoleID = model.SYSTEM_ADMIN_ROLE_ID
install.RoleID = model.SystemAdminRoleId
cloud := model.NewAutocompleteData("cloud", "", "Connect to a Jira Cloud instance")
urlPattern := "https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)"
cloud.AddTextArgument("input URL of the Jira Cloud instance", "[URL]", urlPattern)
@@ -602,7 +602,7 @@ func createJiraAutocompleteData() *model.AutocompleteData {
jira.AddCommand(install)
uninstall := model.NewAutocompleteData("uninstall", "", "Disconnect Mattermost from a Jira instance")
uninstall.RoleID = model.SYSTEM_ADMIN_ROLE_ID
uninstall.RoleID = model.SystemAdminRoleId
cloud = model.NewAutocompleteData("cloud", "", "Disconnect from a Jira Cloud instance")
cloud.AddTextArgument("input URL of the Jira Cloud instance", "[URL]", urlPattern)
uninstall.AddCommand(cloud)
@@ -625,7 +625,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) {
emptyCmdArgs := &model.CommandArgs{}
t.Run("GetAutoCompleteListItems", func(t *testing.T) {
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SystemAdminRoleId)
assert.Len(t, suggestions, 3)
assert.Equal(t, "this is hint 1", suggestions[0].Hint)
assert.Equal(t, "this is hint 2", suggestions[1].Hint)
@@ -633,7 +633,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) {
})
t.Run("GetAutoCompleteListItems bad arg", func(t *testing.T) {
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SYSTEM_ADMIN_ROLE_ID)
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SystemAdminRoleId)
assert.Empty(t, suggestions)
})
}
@@ -662,7 +662,7 @@ func (p *testCommandProvider) GetCommand(a *App, T i18n.TranslateFunc) *model.Co
func (p *testCommandProvider) DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
return &model.CommandResponse{
Text: "I do nothing!",
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}

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

@@ -30,7 +30,7 @@ func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *m
return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented)
}
job.Type = model.COMPLIANCE_TYPE_ADHOC
job.Type = model.ComplianceTypeAdhoc
job, err := a.Srv().Store.Compliance().Save(job)
if err != nil {

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

@@ -116,7 +116,7 @@ func (s *Server) ensurePostActionCookieSecret() error {
var secret *model.SystemPostActionCookieSecret
value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET)
value, err := s.Store.System().GetByName(model.SystemPostActionCookieSecretKey)
if err == nil {
if err := json.Unmarshal([]byte(value.Value), &secret); err != nil {
return err
@@ -134,7 +134,7 @@ func (s *Server) ensurePostActionCookieSecret() error {
}
system := &model.System{
Name: model.SYSTEM_POST_ACTION_COOKIE_SECRET,
Name: model.SystemPostActionCookieSecretKey,
}
v, err := json.Marshal(newSecret)
if err != nil {
@@ -152,7 +152,7 @@ func (s *Server) ensurePostActionCookieSecret() error {
// If we weren't able to save a new key above, another server must have beat us to it. Get the
// key from the database, and if that fails, error out.
if secret == nil {
value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET)
value, err := s.Store.System().GetByName(model.SystemPostActionCookieSecretKey)
if err != nil {
return err
}
@@ -175,7 +175,7 @@ func (s *Server) ensureAsymmetricSigningKey() error {
var key *model.SystemAsymmetricSigningKey
value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY)
value, err := s.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey)
if err == nil {
if err := json.Unmarshal([]byte(value.Value), &key); err != nil {
return err
@@ -197,7 +197,7 @@ func (s *Server) ensureAsymmetricSigningKey() error {
},
}
system := &model.System{
Name: model.SYSTEM_ASYMMETRIC_SIGNING_KEY,
Name: model.SystemAsymmetricSigningKeyKey,
}
v, err := json.Marshal(newKey)
if err != nil {
@@ -215,7 +215,7 @@ func (s *Server) ensureAsymmetricSigningKey() error {
// If we weren't able to save a new key above, another server must have beat us to it. Get the
// key from the database, and if that fails, error out.
if key == nil {
value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY)
value, err := s.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey)
if err != nil {
return err
}
@@ -259,7 +259,7 @@ func (s *Server) ensureInstallationDate() error {
}
if err := s.Store.System().SaveOrUpdate(&model.System{
Name: model.SYSTEM_INSTALLATION_DATE_KEY,
Name: model.SystemInstallationDateKey,
Value: strconv.FormatInt(installationDate, 10),
}); err != nil {
return err
@@ -274,7 +274,7 @@ func (s *Server) ensureFirstServerRunTimestamp() error {
}
if err := s.Store.System().SaveOrUpdate(&model.System{
Name: model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY,
Name: model.SystemFirstServerRunTimestampKey,
Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10),
}); err != nil {
return err

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

@@ -135,10 +135,10 @@ func TestEnsureInstallationDate(t *testing.T) {
}
if tc.PrevInstallationDate == nil {
th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_INSTALLATION_DATE_KEY)
th.App.Srv().Store.System().PermanentDeleteByName(model.SystemInstallationDateKey)
} else {
th.App.Srv().Store.System().SaveOrUpdate(&model.System{
Name: model.SYSTEM_INSTALLATION_DATE_KEY,
Name: model.SystemInstallationDateKey,
Value: strconv.FormatInt(*tc.PrevInstallationDate, 10),
})
}
@@ -150,7 +150,7 @@ func TestEnsureInstallationDate(t *testing.T) {
} else {
assert.NoError(t, err)
data, err := th.App.Srv().Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY)
data, err := th.App.Srv().Store.System().GetByName(model.SystemInstallationDateKey)
assert.NoError(t, err)
value, _ := strconv.ParseInt(data.Value, 10, 64)
assert.True(t, *tc.ExpectedInstallationDate <= value && *tc.ExpectedInstallationDate+1000 >= value)

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

@@ -181,14 +181,14 @@ 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
preference, err := job.service.store.Preference().Get(userID, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL)
preference, err := job.service.store.Preference().Get(userID, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval)
if 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)
interval, _ = strconv.ParseInt(model.PreferenceEmailIntervalBatchingSeconds, 10, 64)
} else {
if value, err := strconv.ParseInt(preference.Value, 10, 64); err != nil {
// // use the default batching interval if an error ocurrs while deserializing user preferences
interval, _ = strconv.ParseInt(model.PREFERENCE_EMAIL_INTERVAL_BATCHING_SECONDS, 10, 64)
interval, _ = strconv.ParseInt(model.PreferenceEmailIntervalBatchingSeconds, 10, 64)
} else {
interval = value
}
@@ -220,12 +220,12 @@ func (es *Service) sendBatchedEmailNotification(userID string, notifications []*
postsData := make([]*postData, 0 /* len */, len(notifications) /* cap */)
embeddedFiles := make(map[string]io.Reader)
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
if license := es.license(); license != nil && *license.Features.EmailNotificationContents {
emailNotificationContentsType = *es.config().EmailSettings.EmailNotificationContentsType
}
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
if emailNotificationContentsType == model.EmailNotificationContentsFull {
for i, notification := range notifications {
sender, errSender := es.userService.GetUser(notification.post.UserId)
if errSender != nil {

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

@@ -98,8 +98,8 @@ func TestCheckPendingNotifications(t *testing.T) {
nErr := th.store.Preference().Save(&model.Preferences{{
UserId: th.BasicUser.Id,
Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS,
Name: model.PREFERENCE_NAME_EMAIL_INTERVAL,
Category: model.PreferenceCategoryNotifications,
Name: model.PreferenceNameEmailInterval,
Value: "60",
}})
require.NoError(t, nErr)
@@ -120,8 +120,8 @@ func TestCheckPendingNotifications(t *testing.T) {
// We reset the interval to something shorter
nErr = th.store.Preference().Save(&model.Preferences{{
UserId: th.BasicUser.Id,
Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS,
Name: model.PREFERENCE_NAME_EMAIL_INTERVAL,
Category: model.PreferenceCategoryNotifications,
Name: model.PreferenceNameEmailInterval,
Value: "10",
}})
require.NoError(t, nErr)
@@ -256,8 +256,8 @@ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) {
// preference value is not an integer, so we'll fall back to the default 15min value
nErr := th.store.Preference().Save(&model.Preferences{{
UserId: th.BasicUser.Id,
Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS,
Name: model.PREFERENCE_NAME_EMAIL_INTERVAL,
Category: model.PreferenceCategoryNotifications,
Name: model.PreferenceNameEmailInterval,
Value: "notAnIntegerValue",
}})
require.NoError(t, nErr)

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

@@ -54,7 +54,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper {
th := setupTestHelper(mockStore, tb)
statusMock := mocks.StatusStore{}
statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil)
statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil)
statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil)
emptyMockStore := mocks.Store{}
@@ -155,7 +155,7 @@ func (th *TestHelper) InitBasic() *TestHelper {
th.BasicUser2, _ = th.service.userService.GetUser(th.BasicUser2.Id)
th.addUserToTeam(th.BasicTeam, th.BasicUser2)
th.BasicChannel = th.createChannel(th.BasicTeam, model.CHANNEL_OPEN)
th.BasicChannel = th.createChannel(th.BasicTeam, model.ChannelTypeOpen)
th.addUserToChannel(th.BasicChannel, th.SystemAdminUser)
th.addUserToChannel(th.BasicChannel, th.BasicUser)
th.addUserToChannel(th.BasicChannel, th.BasicUser2)
@@ -169,7 +169,7 @@ func (th *TestHelper) CreateTeam() *model.Team {
DisplayName: "dn_" + id,
Name: "name" + id,
Email: "success+" + id + "@simulator.amazonses.com",
Type: model.TEAM_OPEN,
Type: model.TeamOpen,
}
utils.DisableDebugLogForTest()

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

@@ -77,7 +77,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma
return nil, model.NewAppError("CreateEmoji", "app.emoji.create.internal_error", nil, err.Error(), http.StatusInternalServerError)
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EMOJI_ADDED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventEmojiAdded, "", "", "", nil)
message.Add("emoji", emoji.ToJson())
a.Publish(message)
return emoji, nil

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

@@ -32,8 +32,8 @@ func (a *App) NotifySessionsExpired() *model.AppError {
}
msg := &model.PushNotification{
Version: model.PUSH_MESSAGE_V2,
Type: model.PUSH_TYPE_SESSION,
Version: model.PushMessageV2,
Type: model.PushTypeSession,
}
for _, session := range sessions {
@@ -59,7 +59,7 @@ func (a *App) NotifySessionsExpired() *model.AppError {
mlog.String("type", tmpMessage.Type),
mlog.String("userId", session.UserId),
mlog.String("deviceId", tmpMessage.DeviceId),
mlog.String("status", model.PUSH_SEND_SUCCESS),
mlog.String("status", model.PushSendSuccess),
)
if a.Metrics() != nil {
@@ -75,7 +75,7 @@ func (a *App) NotifySessionsExpired() *model.AppError {
}
func (a *App) getSessionExpiredPushMessage(session *model.Session) string {
locale := model.DEFAULT_LOCALE
locale := model.DefaultLocale
user, err := a.GetUser(session.UserId)
if err == nil {
locale = user.Locale

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

@@ -70,11 +70,11 @@ func TestNotifySessionsExpired(t *testing.T) {
require.Equal(t, 2, handler.numReqs())
expected := []string{"22222", "33333"}
require.Equal(t, model.PUSH_TYPE_SESSION, handler.notifications()[0].Type)
require.Equal(t, model.PushTypeSession, handler.notifications()[0].Type)
require.Contains(t, expected, handler.notifications()[0].DeviceId)
require.Contains(t, handler.notifications()[0].Message, "Session Expired")
require.Equal(t, model.PUSH_TYPE_SESSION, handler.notifications()[1].Type)
require.Equal(t, model.PushTypeSession, handler.notifications()[1].Type)
require.Contains(t, expected, handler.notifications()[1].DeviceId)
require.Contains(t, handler.notifications()[1].Message, "Session Expired")
})

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

@@ -32,35 +32,35 @@ const ExportDataDir = "data"
// We use this map to identify the exportable preferences.
// Here we link the preference category and name, to the name of the relevant field in the import struct.
var exportablePreferences = map[ComparablePreference]string{{
Category: model.PREFERENCE_CATEGORY_THEME,
Category: model.PreferenceCategoryTheme,
Name: "",
}: "Theme", {
Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS,
Category: model.PreferenceCategoryAdvancedSettings,
Name: "feature_enabled_markdown_preview",
}: "UseMarkdownPreview", {
Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS,
Category: model.PreferenceCategoryAdvancedSettings,
Name: "formatting",
}: "UseFormatting", {
Category: model.PREFERENCE_CATEGORY_SIDEBAR_SETTINGS,
Category: model.PreferenceCategorySidebarSettings,
Name: "show_unread_section",
}: "ShowUnreadSection", {
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_USE_MILITARY_TIME,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameUseMilitaryTime,
}: "UseMilitaryTime", {
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_COLLAPSE_SETTING,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameCollapseSetting,
}: "CollapsePreviews", {
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_MESSAGE_DISPLAY,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameMessageDisplay,
}: "MessageDisplay", {
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Category: model.PreferenceCategoryDisplaySettings,
Name: "channel_display_mode",
}: "ChannelDisplayMode", {
Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS,
Category: model.PreferenceCategoryTutorialSteps,
Name: "",
}: "TutorialStep", {
Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS,
Name: model.PREFERENCE_NAME_EMAIL_INTERVAL,
Category: model.PreferenceCategoryNotifications,
Name: model.PreferenceNameEmailInterval,
}: "EmailInterval",
}
@@ -251,17 +251,17 @@ func (a *App) exportAllUsers(writer io.Writer) *model.AppError {
for _, pref := range allPrefs {
// We need to manage the special cases
// Here we manage Tutorial steps
if pref.Category == model.PREFERENCE_CATEGORY_TUTORIAL_STEPS {
if pref.Category == model.PreferenceCategoryTutorialSteps {
pref.Name = ""
// Then the email interval
} else if pref.Category == model.PREFERENCE_CATEGORY_NOTIFICATIONS && pref.Name == model.PREFERENCE_NAME_EMAIL_INTERVAL {
} else if pref.Category == model.PreferenceCategoryNotifications && pref.Name == model.PreferenceNameEmailInterval {
switch pref.Value {
case model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS:
pref.Value = model.PREFERENCE_EMAIL_INTERVAL_IMMEDIATELY
case model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN_AS_SECONDS:
pref.Value = model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN
case model.PREFERENCE_EMAIL_INTERVAL_HOUR_AS_SECONDS:
pref.Value = model.PREFERENCE_EMAIL_INTERVAL_HOUR
case model.PreferenceEmailIntervalNoBatchingSeconds:
pref.Value = model.PreferenceEmailIntervalImmediately
case model.PreferenceEmailIntervalFifteenAsSeconds:
pref.Value = model.PreferenceEmailIntervalFifteen
case model.PreferenceEmailIntervalHourAsSeconds:
pref.Value = model.PreferenceEmailIntervalHour
case "0":
pref.Value = ""
}
@@ -325,7 +325,7 @@ func (a *App) buildUserTeamAndChannelMemberships(userID string) (*[]UserTeamImpo
}
// Get the user theme
themePreference, nErr := a.Srv().Store.Preference().Get(member.UserId, model.PREFERENCE_CATEGORY_THEME, member.TeamId)
themePreference, nErr := a.Srv().Store.Preference().Get(member.UserId, model.PreferenceCategoryTheme, member.TeamId)
if nErr == nil {
memberData.Theme = &themePreference.Value
}
@@ -346,7 +346,7 @@ func (a *App) buildUserChannelMemberships(userID string, teamID string) (*[]User
return nil, model.NewAppError("buildUserChannelMemberships", "app.channel.get_members.app_error", nil, nErr.Error(), http.StatusInternalServerError)
}
category := model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL
category := model.PreferenceCategoryFavoriteChannel
preferences, err := a.GetPreferenceByCategoryForUser(userID, category)
if err != nil && err.StatusCode != http.StatusNotFound {
return nil, err
@@ -368,14 +368,14 @@ func (a *App) buildUserNotifyProps(notifyProps model.StringMap) *UserNotifyProps
}
return &UserNotifyPropsImportData{
Desktop: getProp(model.DESKTOP_NOTIFY_PROP),
DesktopSound: getProp(model.DESKTOP_SOUND_NOTIFY_PROP),
Email: getProp(model.EMAIL_NOTIFY_PROP),
Mobile: getProp(model.PUSH_NOTIFY_PROP),
MobilePushStatus: getProp(model.PUSH_STATUS_NOTIFY_PROP),
ChannelTrigger: getProp(model.CHANNEL_MENTIONS_NOTIFY_PROP),
CommentsTrigger: getProp(model.COMMENTS_NOTIFY_PROP),
MentionKeys: getProp(model.MENTION_KEYS_NOTIFY_PROP),
Desktop: getProp(model.DesktopNotifyProp),
DesktopSound: getProp(model.DesktopSoundNotifyProp),
Email: getProp(model.EmailNotifyProp),
Mobile: getProp(model.PushNotifyProp),
MobilePushStatus: getProp(model.PushStatusNotifyProp),
ChannelTrigger: getProp(model.ChannelMentionsNotifyProp),
CommentsTrigger: getProp(model.CommentsNotifyProp),
MentionKeys: getProp(model.MentionKeysNotifyProp),
}
}
@@ -518,7 +518,7 @@ func (a *App) exportCustomEmoji(writer io.Writer, outPath, exportDir string, exp
var emojiPaths []string
pageNumber := 0
for {
customEmojiList, err := a.GetEmojiList(pageNumber, 100, model.EMOJI_SORT_BY_NAME)
customEmojiList, err := a.GetEmojiList(pageNumber, 100, model.EmojiSortByName)
if err != nil {
return nil, err

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

@@ -90,13 +90,13 @@ func ImportLineFromUser(user *model.User, exportedPrefs map[string]*string) *Lin
func ImportUserTeamDataFromTeamMember(member *model.TeamMemberForExport) *UserTeamImportData {
rolesList := strings.Fields(member.Roles)
if member.SchemeAdmin {
rolesList = append(rolesList, model.TEAM_ADMIN_ROLE_ID)
rolesList = append(rolesList, model.TeamAdminRoleId)
}
if member.SchemeUser {
rolesList = append(rolesList, model.TEAM_USER_ROLE_ID)
rolesList = append(rolesList, model.TeamUserRoleId)
}
if member.SchemeGuest {
rolesList = append(rolesList, model.TEAM_GUEST_ROLE_ID)
rolesList = append(rolesList, model.TeamGuestRoleId)
}
roles := strings.Join(rolesList, " ")
return &UserTeamImportData{
@@ -108,26 +108,26 @@ func ImportUserTeamDataFromTeamMember(member *model.TeamMemberForExport) *UserTe
func ImportUserChannelDataFromChannelMemberAndPreferences(member *model.ChannelMemberForExport, preferences *model.Preferences) *UserChannelImportData {
rolesList := strings.Fields(member.Roles)
if member.SchemeAdmin {
rolesList = append(rolesList, model.CHANNEL_ADMIN_ROLE_ID)
rolesList = append(rolesList, model.ChannelAdminRoleId)
}
if member.SchemeUser {
rolesList = append(rolesList, model.CHANNEL_USER_ROLE_ID)
rolesList = append(rolesList, model.ChannelUserRoleId)
}
if member.SchemeGuest {
rolesList = append(rolesList, model.CHANNEL_GUEST_ROLE_ID)
rolesList = append(rolesList, model.ChannelGuestRoleId)
}
props := member.NotifyProps
notifyProps := UserChannelNotifyPropsImportData{}
desktop, exist := props[model.DESKTOP_NOTIFY_PROP]
desktop, exist := props[model.DesktopNotifyProp]
if exist {
notifyProps.Desktop = &desktop
}
mobile, exist := props[model.PUSH_NOTIFY_PROP]
mobile, exist := props[model.PushNotifyProp]
if exist {
notifyProps.Mobile = &mobile
}
markUnread, exist := props[model.MARK_UNREAD_NOTIFY_PROP]
markUnread, exist := props[model.MarkUnreadNotifyProp]
if exist {
notifyProps.MarkUnread = &markUnread
}

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

@@ -52,26 +52,26 @@ func TestExportUserNotifyProps(t *testing.T) {
defer th.TearDown()
userNotifyProps := model.StringMap{
model.DESKTOP_NOTIFY_PROP: model.USER_NOTIFY_ALL,
model.DESKTOP_SOUND_NOTIFY_PROP: "true",
model.EMAIL_NOTIFY_PROP: "true",
model.PUSH_NOTIFY_PROP: model.USER_NOTIFY_ALL,
model.PUSH_STATUS_NOTIFY_PROP: model.STATUS_ONLINE,
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.COMMENTS_NOTIFY_PROP: model.COMMENTS_NOTIFY_ROOT,
model.MENTION_KEYS_NOTIFY_PROP: "valid,misc",
model.DesktopNotifyProp: model.UserNotifyAll,
model.DesktopSoundNotifyProp: "true",
model.EmailNotifyProp: "true",
model.PushNotifyProp: model.UserNotifyAll,
model.PushStatusNotifyProp: model.StatusOnline,
model.ChannelMentionsNotifyProp: "true",
model.CommentsNotifyProp: model.CommentsNotifyRoot,
model.MentionKeysNotifyProp: "valid,misc",
}
exportNotifyProps := th.App.buildUserNotifyProps(userNotifyProps)
require.Equal(t, userNotifyProps[model.DESKTOP_NOTIFY_PROP], *exportNotifyProps.Desktop)
require.Equal(t, userNotifyProps[model.DESKTOP_SOUND_NOTIFY_PROP], *exportNotifyProps.DesktopSound)
require.Equal(t, userNotifyProps[model.EMAIL_NOTIFY_PROP], *exportNotifyProps.Email)
require.Equal(t, userNotifyProps[model.PUSH_NOTIFY_PROP], *exportNotifyProps.Mobile)
require.Equal(t, userNotifyProps[model.PUSH_STATUS_NOTIFY_PROP], *exportNotifyProps.MobilePushStatus)
require.Equal(t, userNotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP], *exportNotifyProps.ChannelTrigger)
require.Equal(t, userNotifyProps[model.COMMENTS_NOTIFY_PROP], *exportNotifyProps.CommentsTrigger)
require.Equal(t, userNotifyProps[model.MENTION_KEYS_NOTIFY_PROP], *exportNotifyProps.MentionKeys)
require.Equal(t, userNotifyProps[model.DesktopNotifyProp], *exportNotifyProps.Desktop)
require.Equal(t, userNotifyProps[model.DesktopSoundNotifyProp], *exportNotifyProps.DesktopSound)
require.Equal(t, userNotifyProps[model.EmailNotifyProp], *exportNotifyProps.Email)
require.Equal(t, userNotifyProps[model.PushNotifyProp], *exportNotifyProps.Mobile)
require.Equal(t, userNotifyProps[model.PushStatusNotifyProp], *exportNotifyProps.MobilePushStatus)
require.Equal(t, userNotifyProps[model.ChannelMentionsNotifyProp], *exportNotifyProps.ChannelTrigger)
require.Equal(t, userNotifyProps[model.CommentsNotifyProp], *exportNotifyProps.CommentsTrigger)
require.Equal(t, userNotifyProps[model.MentionKeysNotifyProp], *exportNotifyProps.MentionKeys)
}
func TestExportUserChannels(t *testing.T) {
@@ -82,12 +82,12 @@ func TestExportUserChannels(t *testing.T) {
team := th.BasicTeam
channelName := channel.Name
notifyProps := model.StringMap{
model.DESKTOP_NOTIFY_PROP: model.USER_NOTIFY_ALL,
model.PUSH_NOTIFY_PROP: model.USER_NOTIFY_NONE,
model.DesktopNotifyProp: model.UserNotifyAll,
model.PushNotifyProp: model.UserNotifyNone,
}
preference := model.Preference{
UserId: user.Id,
Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL,
Category: model.PreferenceCategoryFavoriteChannel,
Name: channel.Id,
Value: "true",
}

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

@@ -234,7 +234,7 @@ func TestFindTeamIdForFilename(t *testing.T) {
teamID := th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png")
assert.Equal(t, th.BasicTeam.Id, teamID)
_, err := th.App.CreateTeamWithUser(th.Context, &model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TEAM_OPEN}, th.BasicUser.Id)
_, err := th.App.CreateTeamWithUser(th.Context, &model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TeamOpen}, th.BasicUser.Id)
require.Nil(t, err)
teamID = th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png")

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

@@ -96,7 +96,7 @@ func (a *App) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) {
updatedGroup, err := a.Srv().Store.Group().Update(group)
if err == nil {
messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP, "", "", "", nil)
messageWs := model.NewWebSocketEvent(model.WebsocketEventReceivedGroup, "", "", "", nil)
messageWs.Add("group", updatedGroup.ToJson())
a.Publish(messageWs)
}
@@ -121,7 +121,7 @@ func (a *App) DeleteGroup(groupID string) (*model.Group, *model.AppError) {
deletedGroup, err := a.Srv().Store.Group().Delete(groupID)
if err == nil {
messageWs := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP, "", "", "", nil)
messageWs := model.NewWebSocketEvent(model.WebsocketEventReceivedGroup, "", "", "", nil)
messageWs.Add("group", deletedGroup.ToJson())
a.Publish(messageWs)
}
@@ -287,9 +287,9 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr
var messageWs *model.WebSocketEvent
if gs.Type == model.GroupSyncableTypeTeam {
messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_ASSOCIATED_TO_TEAM, gs.SyncableId, "", "", nil)
messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupAssociatedToTeam, gs.SyncableId, "", "", nil)
} else {
messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_ASSOCIATED_TO_CHANNEL, "", gs.SyncableId, "", nil)
messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupAssociatedToChannel, "", gs.SyncableId, "", nil)
}
messageWs.Add("group_id", gs.GroupId)
a.Publish(messageWs)
@@ -388,9 +388,9 @@ func (a *App) DeleteGroupSyncable(groupID string, syncableID string, syncableTyp
var messageWs *model.WebSocketEvent
if gs.Type == model.GroupSyncableTypeTeam {
messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_NOT_ASSOCIATED_TO_TEAM, gs.SyncableId, "", "", nil)
messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupNotAssociatedToTeam, gs.SyncableId, "", "", nil)
} else {
messageWs = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_RECEIVED_GROUP_NOT_ASSOCIATED_TO_CHANNEL, "", gs.SyncableId, "", nil)
messageWs = model.NewWebSocketEvent(model.WebsocketEventReceivedGroupNotAssociatedToChannel, "", gs.SyncableId, "", nil)
}
messageWs.Add("group_id", gs.GroupId)

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

@@ -164,7 +164,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper {
th := setupTestHelper(mockStore, false, false, tb)
statusMock := mocks.StatusStore{}
statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil)
statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil)
statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil)
emptyMockStore := mocks.Store{}
@@ -179,7 +179,7 @@ func SetupEnterpriseWithStoreMock(tb testing.TB) *TestHelper {
th := setupTestHelper(mockStore, true, false, tb)
statusMock := mocks.StatusStore{}
statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil)
statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil)
statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil)
statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil)
emptyMockStore := mocks.Store{}
@@ -200,7 +200,7 @@ func (th *TestHelper) InitBasic() *TestHelper {
// create users once and cache them because password hashing is slow
initBasicOnce.Do(func() {
th.SystemAdminUser = th.CreateUser()
th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false)
th.SystemAdminUser, _ = th.App.GetUser(th.SystemAdminUser.Id)
userCache.SystemAdminUser = th.SystemAdminUser.DeepCopy()
@@ -237,7 +237,7 @@ func (th *TestHelper) CreateTeam() *model.Team {
DisplayName: "dn_" + id,
Name: "name" + id,
Email: "success+" + id + "@simulator.amazonses.com",
Type: model.TEAM_OPEN,
Type: model.TeamOpen,
}
utils.DisableDebugLogForTest()
@@ -309,11 +309,11 @@ func WithShared(v bool) ChannelOption {
}
func (th *TestHelper) CreateChannel(team *model.Team, options ...ChannelOption) *model.Channel {
return th.createChannel(team, model.CHANNEL_OPEN, options...)
return th.createChannel(team, model.ChannelTypeOpen, options...)
}
func (th *TestHelper) CreatePrivateChannel(team *model.Team) *model.Channel {
return th.createChannel(team, model.CHANNEL_PRIVATE)
return th.createChannel(team, model.ChannelTypePrivate)
}
func (th *TestHelper) createChannel(team *model.Team, channelType string, options ...ChannelOption) *model.Channel {
@@ -462,7 +462,7 @@ func (th *TestHelper) CreateScheme() (*model.Scheme, []*model.Role) {
DisplayName: "Test Scheme Display Name",
Name: model.NewId(),
Description: "Test scheme description",
Scope: model.SCHEME_SCOPE_TEAM,
Scope: model.SchemeScopeTeam,
})
if err != nil {
panic(err)
@@ -597,7 +597,7 @@ func (*TestHelper) ResetRoleMigration() {
mainHelper.GetClusterInterface().SendClearRoleCacheMessage()
if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": model.ADVANCED_PERMISSIONS_MIGRATION_KEY}); err != nil {
if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": model.AdvancedPermissionsMigrationKey}); err != nil {
panic(err)
}
}
@@ -630,7 +630,7 @@ func (th *TestHelper) CheckTeamCount(t *testing.T, expected int64) {
}
func (th *TestHelper) CheckChannelsCount(t *testing.T, expected int64) {
count, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN)
count, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen)
require.NoError(t, err, "Failed to get channel count.")
require.Equalf(t, count, expected, "Unexpected number of channels. Expected: %v, found: %v", expected, count)
}
@@ -639,7 +639,7 @@ func (th *TestHelper) SetupTeamScheme() *model.Scheme {
scheme, err := th.App.CreateScheme(&model.Scheme{
Name: model.NewId(),
DisplayName: model.NewId(),
Scope: model.SCHEME_SCOPE_TEAM,
Scope: model.SchemeScopeTeam,
})
if err != nil {
panic(err)
@@ -651,7 +651,7 @@ func (th *TestHelper) SetupChannelScheme() *model.Scheme {
scheme, err := th.App.CreateScheme(&model.Scheme{
Name: model.NewId(),
DisplayName: model.NewId(),
Scope: model.SCHEME_SCOPE_CHANNEL,
Scope: model.SchemeScopeChannel,
})
if err != nil {
panic(err)

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

@@ -65,7 +65,7 @@ func (a *App) importScheme(data *SchemeImportData, dryRun bool) *model.AppError
return err
}
if scheme.Scope == model.SCHEME_SCOPE_TEAM {
if scheme.Scope == model.SchemeScopeTeam {
data.DefaultTeamAdminRole.Name = &scheme.DefaultTeamAdminRole
if err := a.importRole(data.DefaultTeamAdminRole, dryRun, true); err != nil {
return err
@@ -87,7 +87,7 @@ func (a *App) importScheme(data *SchemeImportData, dryRun bool) *model.AppError
}
}
if scheme.Scope == model.SCHEME_SCOPE_TEAM || scheme.Scope == model.SCHEME_SCOPE_CHANNEL {
if scheme.Scope == model.SchemeScopeTeam || scheme.Scope == model.SchemeScopeChannel {
data.DefaultChannelAdminRole.Name = &scheme.DefaultChannelAdminRole
if err := a.importRole(data.DefaultChannelAdminRole, dryRun, true); err != nil {
return err
@@ -197,7 +197,7 @@ func (a *App) importTeam(c *request.Context, data *TeamImportData, dryRun bool)
return model.NewAppError("BulkImport", "app.import.import_team.scheme_deleted.error", nil, "", http.StatusBadRequest)
}
if scheme.Scope != model.SCHEME_SCOPE_TEAM {
if scheme.Scope != model.SchemeScopeTeam {
return model.NewAppError("BulkImport", "app.import.import_team.scheme_wrong_scope.error", nil, "", http.StatusBadRequest)
}
@@ -262,7 +262,7 @@ func (a *App) importChannel(c *request.Context, data *ChannelImportData, dryRun
return model.NewAppError("BulkImport", "app.import.import_channel.scheme_deleted.error", nil, "", http.StatusBadRequest)
}
if scheme.Scope != model.SCHEME_SCOPE_CHANNEL {
if scheme.Scope != model.SchemeScopeChannel {
return model.NewAppError("BulkImport", "app.import.import_channel.scheme_wrong_scope.error", nil, "", http.StatusBadRequest)
}
@@ -415,8 +415,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
}
} else if user.Roles == "" {
// Set SYSTEM_USER roles on newly created users by default.
if user.Roles != model.SYSTEM_USER_ROLE_ID {
roles = model.SYSTEM_USER_ROLE_ID
if user.Roles != model.SystemUserRoleId {
roles = model.SystemUserRoleId
hasUserRolesChanged = true
}
}
@@ -424,57 +424,57 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.NotifyProps != nil {
if data.NotifyProps.Desktop != nil {
if value, ok := user.NotifyProps[model.DESKTOP_NOTIFY_PROP]; !ok || value != *data.NotifyProps.Desktop {
user.AddNotifyProp(model.DESKTOP_NOTIFY_PROP, *data.NotifyProps.Desktop)
if value, ok := user.NotifyProps[model.DesktopNotifyProp]; !ok || value != *data.NotifyProps.Desktop {
user.AddNotifyProp(model.DesktopNotifyProp, *data.NotifyProps.Desktop)
hasNotifyPropsChanged = true
}
}
if data.NotifyProps.DesktopSound != nil {
if value, ok := user.NotifyProps[model.DESKTOP_SOUND_NOTIFY_PROP]; !ok || value != *data.NotifyProps.DesktopSound {
user.AddNotifyProp(model.DESKTOP_SOUND_NOTIFY_PROP, *data.NotifyProps.DesktopSound)
if value, ok := user.NotifyProps[model.DesktopSoundNotifyProp]; !ok || value != *data.NotifyProps.DesktopSound {
user.AddNotifyProp(model.DesktopSoundNotifyProp, *data.NotifyProps.DesktopSound)
hasNotifyPropsChanged = true
}
}
if data.NotifyProps.Email != nil {
if value, ok := user.NotifyProps[model.EMAIL_NOTIFY_PROP]; !ok || value != *data.NotifyProps.Email {
user.AddNotifyProp(model.EMAIL_NOTIFY_PROP, *data.NotifyProps.Email)
if value, ok := user.NotifyProps[model.EmailNotifyProp]; !ok || value != *data.NotifyProps.Email {
user.AddNotifyProp(model.EmailNotifyProp, *data.NotifyProps.Email)
hasNotifyPropsChanged = true
}
}
if data.NotifyProps.Mobile != nil {
if value, ok := user.NotifyProps[model.PUSH_NOTIFY_PROP]; !ok || value != *data.NotifyProps.Mobile {
user.AddNotifyProp(model.PUSH_NOTIFY_PROP, *data.NotifyProps.Mobile)
if value, ok := user.NotifyProps[model.PushNotifyProp]; !ok || value != *data.NotifyProps.Mobile {
user.AddNotifyProp(model.PushNotifyProp, *data.NotifyProps.Mobile)
hasNotifyPropsChanged = true
}
}
if data.NotifyProps.MobilePushStatus != nil {
if value, ok := user.NotifyProps[model.PUSH_STATUS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.MobilePushStatus {
user.AddNotifyProp(model.PUSH_STATUS_NOTIFY_PROP, *data.NotifyProps.MobilePushStatus)
if value, ok := user.NotifyProps[model.PushStatusNotifyProp]; !ok || value != *data.NotifyProps.MobilePushStatus {
user.AddNotifyProp(model.PushStatusNotifyProp, *data.NotifyProps.MobilePushStatus)
hasNotifyPropsChanged = true
}
}
if data.NotifyProps.ChannelTrigger != nil {
if value, ok := user.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.ChannelTrigger {
user.AddNotifyProp(model.CHANNEL_MENTIONS_NOTIFY_PROP, *data.NotifyProps.ChannelTrigger)
if value, ok := user.NotifyProps[model.ChannelMentionsNotifyProp]; !ok || value != *data.NotifyProps.ChannelTrigger {
user.AddNotifyProp(model.ChannelMentionsNotifyProp, *data.NotifyProps.ChannelTrigger)
hasNotifyPropsChanged = true
}
}
if data.NotifyProps.CommentsTrigger != nil {
if value, ok := user.NotifyProps[model.COMMENTS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.CommentsTrigger {
user.AddNotifyProp(model.COMMENTS_NOTIFY_PROP, *data.NotifyProps.CommentsTrigger)
if value, ok := user.NotifyProps[model.CommentsNotifyProp]; !ok || value != *data.NotifyProps.CommentsTrigger {
user.AddNotifyProp(model.CommentsNotifyProp, *data.NotifyProps.CommentsTrigger)
hasNotifyPropsChanged = true
}
}
if data.NotifyProps.MentionKeys != nil {
if value, ok := user.NotifyProps[model.MENTION_KEYS_NOTIFY_PROP]; !ok || value != *data.NotifyProps.MentionKeys {
user.AddNotifyProp(model.MENTION_KEYS_NOTIFY_PROP, *data.NotifyProps.MentionKeys)
if value, ok := user.NotifyProps[model.MentionKeysNotifyProp]; !ok || value != *data.NotifyProps.MentionKeys {
user.AddNotifyProp(model.MentionKeysNotifyProp, *data.NotifyProps.MentionKeys)
hasNotifyPropsChanged = true
}
} else {
@@ -509,7 +509,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
}
}
pref := model.Preference{UserId: savedUser.Id, Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, Name: savedUser.Id, Value: "0"}
pref := model.Preference{UserId: savedUser.Id, Category: model.PreferenceCategoryTutorialSteps, Name: savedUser.Id, Value: "0"}
if err := a.Srv().Store.Preference().Save(&model.Preferences{pref}); err != nil {
mlog.Warn("Encountered error saving tutorial preference", mlog.Err(err))
}
@@ -580,7 +580,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.Theme != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_THEME,
Category: model.PreferenceCategoryTheme,
Name: "",
Value: *data.Theme,
})
@@ -589,8 +589,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.UseMilitaryTime != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_USE_MILITARY_TIME,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameUseMilitaryTime,
Value: *data.UseMilitaryTime,
})
}
@@ -598,8 +598,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.CollapsePreviews != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_COLLAPSE_SETTING,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameCollapseSetting,
Value: *data.CollapsePreviews,
})
}
@@ -607,8 +607,8 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.MessageDisplay != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Name: model.PREFERENCE_NAME_MESSAGE_DISPLAY,
Category: model.PreferenceCategoryDisplaySettings,
Name: model.PreferenceNameMessageDisplay,
Value: *data.MessageDisplay,
})
}
@@ -616,7 +616,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.ChannelDisplayMode != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
Category: model.PreferenceCategoryDisplaySettings,
Name: "channel_display_mode",
Value: *data.ChannelDisplayMode,
})
@@ -625,7 +625,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.TutorialStep != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS,
Category: model.PreferenceCategoryTutorialSteps,
Name: savedUser.Id,
Value: *data.TutorialStep,
})
@@ -634,7 +634,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.UseMarkdownPreview != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS,
Category: model.PreferenceCategoryAdvancedSettings,
Name: "feature_enabled_markdown_preview",
Value: *data.UseMarkdownPreview,
})
@@ -643,7 +643,7 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.UseFormatting != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS,
Category: model.PreferenceCategoryAdvancedSettings,
Name: "formatting",
Value: *data.UseFormatting,
})
@@ -652,31 +652,31 @@ func (a *App) importUser(data *UserImportData, dryRun bool) *model.AppError {
if data.ShowUnreadSection != nil {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_SIDEBAR_SETTINGS,
Category: model.PreferenceCategorySidebarSettings,
Name: "show_unread_section",
Value: *data.ShowUnreadSection,
})
}
if data.EmailInterval != nil || savedUser.NotifyProps[model.EMAIL_NOTIFY_PROP] == "false" {
if data.EmailInterval != nil || savedUser.NotifyProps[model.EmailNotifyProp] == "false" {
var intervalSeconds string
if value := savedUser.NotifyProps[model.EMAIL_NOTIFY_PROP]; value == "false" {
if value := savedUser.NotifyProps[model.EmailNotifyProp]; value == "false" {
intervalSeconds = "0"
} else {
switch *data.EmailInterval {
case model.PREFERENCE_EMAIL_INTERVAL_IMMEDIATELY:
intervalSeconds = model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS
case model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN:
intervalSeconds = model.PREFERENCE_EMAIL_INTERVAL_FIFTEEN_AS_SECONDS
case model.PREFERENCE_EMAIL_INTERVAL_HOUR:
intervalSeconds = model.PREFERENCE_EMAIL_INTERVAL_HOUR_AS_SECONDS
case model.PreferenceEmailIntervalImmediately:
intervalSeconds = model.PreferenceEmailIntervalNoBatchingSeconds
case model.PreferenceEmailIntervalFifteen:
intervalSeconds = model.PreferenceEmailIntervalFifteenAsSeconds
case model.PreferenceEmailIntervalHour:
intervalSeconds = model.PreferenceEmailIntervalHourAsSeconds
}
}
if intervalSeconds != "" {
preferences = append(preferences, model.Preference{
UserId: savedUser.Id,
Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS,
Name: model.PREFERENCE_NAME_EMAIL_INTERVAL,
Category: model.PreferenceCategoryNotifications,
Name: model.PreferenceNameEmailInterval,
Value: intervalSeconds,
})
}
@@ -730,7 +730,7 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod
if tdata.Theme != nil {
teamThemePreferencesByID[team.Id] = append(teamThemePreferencesByID[team.Id], model.Preference{
UserId: user.Id,
Category: model.PREFERENCE_CATEGORY_THEME,
Category: model.PreferenceCategoryTheme,
Name: team.Id,
Value: *tdata.Theme,
})
@@ -746,12 +746,12 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod
rawRoles := *tdata.Roles
explicitRoles := []string{}
for _, role := range strings.Fields(rawRoles) {
if role == model.TEAM_GUEST_ROLE_ID {
if role == model.TeamGuestRoleId {
isGuestByTeamId[team.Id] = true
isUserByTeamId[team.Id] = false
} else if role == model.TEAM_USER_ROLE_ID {
} else if role == model.TeamUserRoleId {
isUserByTeamId[team.Id] = true
} else if role == model.TEAM_ADMIN_ROLE_ID {
} else if role == model.TeamAdminRoleId {
isAdminByTeamId[team.Id] = true
} else {
explicitRoles = append(explicitRoles, role)
@@ -780,7 +780,7 @@ func (a *App) importUserTeams(user *model.User, data *[]UserTeamImportData) *mod
channels[team.Id] = append(channels[team.Id], *tdata.Channels...)
}
if !user.IsGuest() {
channels[team.Id] = append(channels[team.Id], UserChannelImportData{Name: model.NewString(model.DEFAULT_CHANNEL)})
channels[team.Id] = append(channels[team.Id], UserChannelImportData{Name: model.NewString(model.DefaultChannelName)})
}
teamsByID[team.Id] = team
@@ -886,7 +886,7 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use
if !ok {
return model.NewAppError("BulkImport", "app.import.import_user_channels.channel_not_found.error", nil, "", http.StatusInternalServerError)
}
if _, ok = channelsByID[channel.Id]; ok && *cdata.Name == model.DEFAULT_CHANNEL {
if _, ok = channelsByID[channel.Id]; ok && *cdata.Name == model.DefaultChannelName {
// town-square membership was in the import and added by the importer (skip the added by the importer)
continue
}
@@ -901,12 +901,12 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use
rawRoles := *cdata.Roles
explicitRoles := []string{}
for _, role := range strings.Fields(rawRoles) {
if role == model.CHANNEL_GUEST_ROLE_ID {
if role == model.ChannelGuestRoleId {
isGuestByChannelId[channel.Id] = true
isUserByChannelId[channel.Id] = false
} else if role == model.CHANNEL_USER_ROLE_ID {
} else if role == model.ChannelUserRoleId {
isUserByChannelId[channel.Id] = true
} else if role == model.CHANNEL_ADMIN_ROLE_ID {
} else if role == model.ChannelAdminRoleId {
isAdminByChannelId[channel.Id] = true
} else {
explicitRoles = append(explicitRoles, role)
@@ -918,7 +918,7 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use
if cdata.Favorite != nil && *cdata.Favorite {
channelPreferencesByID[channel.Id] = append(channelPreferencesByID[channel.Id], model.Preference{
UserId: user.Id,
Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL,
Category: model.PreferenceCategoryFavoriteChannel,
Name: channel.Id,
Value: "true",
})
@@ -943,15 +943,15 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, data *[]Use
if cdata.NotifyProps != nil {
if cdata.NotifyProps.Desktop != nil {
member.NotifyProps[model.DESKTOP_NOTIFY_PROP] = *cdata.NotifyProps.Desktop
member.NotifyProps[model.DesktopNotifyProp] = *cdata.NotifyProps.Desktop
}
if cdata.NotifyProps.Mobile != nil {
member.NotifyProps[model.PUSH_NOTIFY_PROP] = *cdata.NotifyProps.Mobile
member.NotifyProps[model.PushNotifyProp] = *cdata.NotifyProps.Mobile
}
if cdata.NotifyProps.MarkUnread != nil {
member.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] = *cdata.NotifyProps.MarkUnread
member.NotifyProps[model.MarkUnreadNotifyProp] = *cdata.NotifyProps.MarkUnread
}
}
@@ -1446,7 +1446,7 @@ func (a *App) importMultiplePostLines(c *request.Context, lines []LineImportWork
preferences = append(preferences, model.Preference{
UserId: user.Id,
Category: model.PREFERENCE_CATEGORY_FLAGGED_POST,
Category: model.PreferenceCategoryFlaggedPost,
Name: postWithData.post.Id,
Value: "true",
})
@@ -1544,7 +1544,7 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m
for _, userID := range userIDs {
preferences = append(preferences, model.Preference{
UserId: userID,
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Category: model.PreferenceCategoryDirectChannelShow,
Name: channel.Id,
Value: "true",
})
@@ -1554,7 +1554,7 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m
for _, favoriter := range *data.FavoritedBy {
preferences = append(preferences, model.Preference{
UserId: userMap[favoriter].Id,
Category: model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL,
Category: model.PreferenceCategoryFavoriteChannel,
Name: channel.Id,
Value: "true",
})
@@ -1740,7 +1740,7 @@ func (a *App) importMultipleDirectPostLines(c *request.Context, lines []LineImpo
preferences = append(preferences, model.Preference{
UserId: user.Id,
Category: model.PREFERENCE_CATEGORY_FLAGGED_POST,
Category: model.PreferenceCategoryFlaggedPost,
Name: postWithData.post.Id,
Value: "true",
})

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

@@ -25,10 +25,10 @@ func TestImportImportScheme(t *testing.T) {
defer th.TearDown()
// Mark the phase 2 permissions migration as completed.
th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"})
defer func() {
th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2)
}()
// Try importing an invalid scheme in dryRun mode.
@@ -220,10 +220,10 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) {
defer th.TearDown()
// Mark the phase 2 permissions migration as completed.
th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"})
defer func() {
th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2)
}()
// Try importing an invalid scheme in dryRun mode.
@@ -496,10 +496,10 @@ func TestImportImportTeam(t *testing.T) {
defer th.TearDown()
// Mark the phase 2 permissions migration as completed.
th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"})
defer func() {
th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2)
}()
scheme1 := th.SetupTeamScheme()
@@ -586,10 +586,10 @@ func TestImportImportChannel(t *testing.T) {
defer th.TearDown()
// Mark the phase 2 permissions migration as completed.
th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"})
defer func() {
th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2)
}()
scheme1 := th.SetupChannelScheme()
@@ -606,7 +606,7 @@ func TestImportImportChannel(t *testing.T) {
require.Nil(t, err, "Failed to get team from database.")
// Check how many channels are in the database.
channelCount, nErr := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN)
channelCount, nErr := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen)
require.NoError(t, nErr, "Failed to get team count.")
// Do an invalid channel in dry-run mode.
@@ -679,7 +679,7 @@ func TestImportImportChannel(t *testing.T) {
// Alter all the fields of that channel.
data.DisplayName = ptrStr("Chaned Disp Name")
data.Type = ptrStr(model.CHANNEL_PRIVATE)
data.Type = ptrStr(model.ChannelTypePrivate)
data.Header = ptrStr("New Header")
data.Purpose = ptrStr("New Purpose")
data.Scheme = &scheme2.Name
@@ -1088,9 +1088,9 @@ func TestImportImportUser(t *testing.T) {
channelMember, appErr := th.App.GetChannelMember(context.Background(), channel.Id, user.Id)
require.Nil(t, appErr, "Failed to get channel member from database.")
assert.Equal(t, "channel_user", channelMember.Roles)
assert.Equal(t, "default", channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP])
assert.Equal(t, "default", channelMember.NotifyProps[model.PUSH_NOTIFY_PROP])
assert.Equal(t, "all", channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
assert.Equal(t, "default", channelMember.NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, "default", channelMember.NotifyProps[model.PushNotifyProp])
assert.Equal(t, "all", channelMember.NotifyProps[model.MarkUnreadNotifyProp])
// Test with the properties of the team and channel membership changed.
data.Teams = &[]UserTeamImportData{
@@ -1103,9 +1103,9 @@ func TestImportImportUser(t *testing.T) {
Name: &channelName,
Roles: ptrStr("channel_user channel_admin"),
NotifyProps: &UserChannelNotifyPropsImportData{
Desktop: ptrStr(model.USER_NOTIFY_MENTION),
Mobile: ptrStr(model.USER_NOTIFY_MENTION),
MarkUnread: ptrStr(model.USER_NOTIFY_MENTION),
Desktop: ptrStr(model.UserNotifyMention),
Mobile: ptrStr(model.UserNotifyMention),
MarkUnread: ptrStr(model.UserNotifyMention),
},
Favorite: ptrBool(true),
},
@@ -1123,12 +1123,12 @@ func TestImportImportUser(t *testing.T) {
channelMember, appErr = th.App.GetChannelMember(context.Background(), channel.Id, user.Id)
require.Nil(t, appErr, "Failed to get channel member Desktop from database.")
assert.Equal(t, "channel_user channel_admin", channelMember.Roles)
assert.Equal(t, model.USER_NOTIFY_MENTION, channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP])
assert.Equal(t, model.USER_NOTIFY_MENTION, channelMember.NotifyProps[model.PUSH_NOTIFY_PROP])
assert.Equal(t, model.USER_NOTIFY_MENTION, channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
assert.Equal(t, model.UserNotifyMention, channelMember.NotifyProps[model.DesktopNotifyProp])
assert.Equal(t, model.UserNotifyMention, channelMember.NotifyProps[model.PushNotifyProp])
assert.Equal(t, model.UserNotifyMention, channelMember.NotifyProps[model.MarkUnreadNotifyProp])
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, team.Id, *(*data.Teams)[0].Theme)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryFavoriteChannel, channel.Id, "true")
checkPreference(t, th.App, user.Id, model.PreferenceCategoryTheme, team.Id, *(*data.Teams)[0].Theme)
// No more new member objects.
tmc, appErr = th.App.GetTeamMembers(team.Id, 0, 1000, nil)
@@ -1162,16 +1162,16 @@ func TestImportImportUser(t *testing.T) {
user, appErr = th.App.GetUserByUsername(username)
require.Nil(t, appErr, "Failed to get user from database.")
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME, *data.UseMilitaryTime)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSE_SETTING, *data.CollapsePreviews)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_MESSAGE_DISPLAY, *data.MessageDisplay)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_CHANNEL_DISPLAY_MODE, *data.ChannelDisplayMode)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "feature_enabled_markdown_preview", *data.UseMarkdownPreview)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "formatting", *data.UseFormatting)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_SIDEBAR_SETTINGS, "show_unread_section", *data.ShowUnreadSection)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL, "30")
checkPreference(t, th.App, user.Id, model.PreferenceCategoryTheme, "", *data.Theme)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime, *data.UseMilitaryTime)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapseSetting, *data.CollapsePreviews)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameMessageDisplay, *data.MessageDisplay)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameChannelDisplayMode, *data.ChannelDisplayMode)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryTutorialSteps, user.Id, *data.TutorialStep)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryAdvancedSettings, "feature_enabled_markdown_preview", *data.UseMarkdownPreview)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryAdvancedSettings, "formatting", *data.UseFormatting)
checkPreference(t, th.App, user.Id, model.PreferenceCategorySidebarSettings, "show_unread_section", *data.ShowUnreadSection)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval, "30")
// Change those preferences.
data = UserImportData{
@@ -1189,23 +1189,23 @@ func TestImportImportUser(t *testing.T) {
assert.Nil(t, appErr)
// Check their values again.
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME, *data.UseMilitaryTime)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSE_SETTING, *data.CollapsePreviews)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_MESSAGE_DISPLAY, *data.MessageDisplay)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_CHANNEL_DISPLAY_MODE, *data.ChannelDisplayMode)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep)
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL, "3600")
checkPreference(t, th.App, user.Id, model.PreferenceCategoryTheme, "", *data.Theme)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime, *data.UseMilitaryTime)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapseSetting, *data.CollapsePreviews)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameMessageDisplay, *data.MessageDisplay)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameChannelDisplayMode, *data.ChannelDisplayMode)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryTutorialSteps, user.Id, *data.TutorialStep)
checkPreference(t, th.App, user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval, "3600")
// Set Notify Without mention keys
data.NotifyProps = &UserNotifyPropsImportData{
Desktop: ptrStr(model.USER_NOTIFY_ALL),
Desktop: ptrStr(model.UserNotifyAll),
DesktopSound: ptrStr("true"),
Email: ptrStr("true"),
Mobile: ptrStr(model.USER_NOTIFY_ALL),
MobilePushStatus: ptrStr(model.STATUS_ONLINE),
Mobile: ptrStr(model.UserNotifyAll),
MobilePushStatus: ptrStr(model.StatusOnline),
ChannelTrigger: ptrStr("true"),
CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ROOT),
CommentsTrigger: ptrStr(model.CommentsNotifyRoot),
}
appErr = th.App.importUser(&data, false)
assert.Nil(t, appErr)
@@ -1213,24 +1213,24 @@ func TestImportImportUser(t *testing.T) {
user, appErr = th.App.GetUserByUsername(username)
require.Nil(t, appErr, "Failed to get user from database.")
checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_ALL)
checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "true")
checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "true")
checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_ALL)
checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_ONLINE)
checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "true")
checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ROOT)
checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "")
checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyAll)
checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "true")
checkNotifyProp(t, user, model.EmailNotifyProp, "true")
checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyAll)
checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusOnline)
checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "true")
checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyRoot)
checkNotifyProp(t, user, model.MentionKeysNotifyProp, "")
// Set Notify Props with Mention keys
data.NotifyProps = &UserNotifyPropsImportData{
Desktop: ptrStr(model.USER_NOTIFY_ALL),
Desktop: ptrStr(model.UserNotifyAll),
DesktopSound: ptrStr("true"),
Email: ptrStr("true"),
Mobile: ptrStr(model.USER_NOTIFY_ALL),
MobilePushStatus: ptrStr(model.STATUS_ONLINE),
Mobile: ptrStr(model.UserNotifyAll),
MobilePushStatus: ptrStr(model.StatusOnline),
ChannelTrigger: ptrStr("true"),
CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ROOT),
CommentsTrigger: ptrStr(model.CommentsNotifyRoot),
MentionKeys: ptrStr("valid,misc"),
}
appErr = th.App.importUser(&data, false)
@@ -1239,24 +1239,24 @@ func TestImportImportUser(t *testing.T) {
user, appErr = th.App.GetUserByUsername(username)
require.Nil(t, appErr, "Failed to get user from database.")
checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_ALL)
checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "true")
checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "true")
checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_ALL)
checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_ONLINE)
checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "true")
checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ROOT)
checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "valid,misc")
checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyAll)
checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "true")
checkNotifyProp(t, user, model.EmailNotifyProp, "true")
checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyAll)
checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusOnline)
checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "true")
checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyRoot)
checkNotifyProp(t, user, model.MentionKeysNotifyProp, "valid,misc")
// Change Notify Props with mention keys
data.NotifyProps = &UserNotifyPropsImportData{
Desktop: ptrStr(model.USER_NOTIFY_MENTION),
Desktop: ptrStr(model.UserNotifyMention),
DesktopSound: ptrStr("false"),
Email: ptrStr("false"),
Mobile: ptrStr(model.USER_NOTIFY_NONE),
MobilePushStatus: ptrStr(model.STATUS_AWAY),
Mobile: ptrStr(model.UserNotifyNone),
MobilePushStatus: ptrStr(model.StatusAway),
ChannelTrigger: ptrStr("false"),
CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY),
CommentsTrigger: ptrStr(model.CommentsNotifyAny),
MentionKeys: ptrStr("misc"),
}
appErr = th.App.importUser(&data, false)
@@ -1265,24 +1265,24 @@ func TestImportImportUser(t *testing.T) {
user, appErr = th.App.GetUserByUsername(username)
require.Nil(t, appErr, "Failed to get user from database.")
checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION)
checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE)
checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY)
checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY)
checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc")
checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyMention)
checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "false")
checkNotifyProp(t, user, model.EmailNotifyProp, "false")
checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyNone)
checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusAway)
checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "false")
checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyAny)
checkNotifyProp(t, user, model.MentionKeysNotifyProp, "misc")
// Change Notify Props without mention keys
data.NotifyProps = &UserNotifyPropsImportData{
Desktop: ptrStr(model.USER_NOTIFY_MENTION),
Desktop: ptrStr(model.UserNotifyMention),
DesktopSound: ptrStr("false"),
Email: ptrStr("false"),
Mobile: ptrStr(model.USER_NOTIFY_NONE),
MobilePushStatus: ptrStr(model.STATUS_AWAY),
Mobile: ptrStr(model.UserNotifyNone),
MobilePushStatus: ptrStr(model.StatusAway),
ChannelTrigger: ptrStr("false"),
CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY),
CommentsTrigger: ptrStr(model.CommentsNotifyAny),
}
appErr = th.App.importUser(&data, false)
assert.Nil(t, appErr)
@@ -1290,14 +1290,14 @@ func TestImportImportUser(t *testing.T) {
user, appErr = th.App.GetUserByUsername(username)
require.Nil(t, appErr, "Failed to get user from database.")
checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION)
checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE)
checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY)
checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY)
checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc")
checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyMention)
checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "false")
checkNotifyProp(t, user, model.EmailNotifyProp, "false")
checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyNone)
checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusAway)
checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "false")
checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyAny)
checkNotifyProp(t, user, model.MentionKeysNotifyProp, "misc")
// Check Notify Props get set on *create* user.
username = model.NewId()
@@ -1306,13 +1306,13 @@ func TestImportImportUser(t *testing.T) {
Email: ptrStr(model.NewId() + "@example.com"),
}
data.NotifyProps = &UserNotifyPropsImportData{
Desktop: ptrStr(model.USER_NOTIFY_MENTION),
Desktop: ptrStr(model.UserNotifyMention),
DesktopSound: ptrStr("false"),
Email: ptrStr("false"),
Mobile: ptrStr(model.USER_NOTIFY_NONE),
MobilePushStatus: ptrStr(model.STATUS_AWAY),
Mobile: ptrStr(model.UserNotifyNone),
MobilePushStatus: ptrStr(model.StatusAway),
ChannelTrigger: ptrStr("false"),
CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY),
CommentsTrigger: ptrStr(model.CommentsNotifyAny),
MentionKeys: ptrStr("misc"),
}
@@ -1322,24 +1322,24 @@ func TestImportImportUser(t *testing.T) {
user, appErr = th.App.GetUserByUsername(username)
require.Nil(t, appErr, "Failed to get user from database.")
checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION)
checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE)
checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY)
checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false")
checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY)
checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc")
checkNotifyProp(t, user, model.DesktopNotifyProp, model.UserNotifyMention)
checkNotifyProp(t, user, model.DesktopSoundNotifyProp, "false")
checkNotifyProp(t, user, model.EmailNotifyProp, "false")
checkNotifyProp(t, user, model.PushNotifyProp, model.UserNotifyNone)
checkNotifyProp(t, user, model.PushStatusNotifyProp, model.StatusAway)
checkNotifyProp(t, user, model.ChannelMentionsNotifyProp, "false")
checkNotifyProp(t, user, model.CommentsNotifyProp, model.CommentsNotifyAny)
checkNotifyProp(t, user, model.MentionKeysNotifyProp, "misc")
// Test importing a user with roles set to a team and a channel which are affected by an override scheme.
// The import subsystem should translate `channel_admin/channel_user/team_admin/team_user`
// to the appropriate scheme-managed-role booleans.
// Mark the phase 2 permissions migration as completed.
th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"})
defer func() {
th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2)
}()
teamSchemeData := &SchemeImportData{
@@ -1596,7 +1596,7 @@ func TestImportUserTeams(t *testing.T) {
data: &[]UserTeamImportData{
{
Name: &th.BasicTeam.Name,
Roles: model.NewString(model.TEAM_ADMIN_ROLE_ID),
Roles: model.NewString(model.TeamAdminRoleId),
},
},
expectedError: false,
@@ -1640,7 +1640,7 @@ func TestImportUserTeams(t *testing.T) {
Name: &th.BasicTeam.Name,
Channels: &[]UserChannelImportData{
{
Name: ptrStr(model.DEFAULT_CHANNEL),
Name: ptrStr(model.DefaultChannelName),
},
},
},
@@ -1720,7 +1720,7 @@ func TestImportUserTeams(t *testing.T) {
require.Equal(t, tc.expectedExplicitRoles, teamMembers[0].ExplicitRoles, "Not matching expected explicit roles")
require.Equal(t, tc.expectedRoles, teamMembers[0].Roles, "not matching expected roles")
if tc.expectedTheme != "" {
pref, prefErr := th.App.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_THEME, teamMembers[0].TeamId)
pref, prefErr := th.App.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryTheme, teamMembers[0].TeamId)
require.NoError(t, prefErr)
require.Equal(t, tc.expectedTheme, pref.Value)
}
@@ -1816,7 +1816,7 @@ func TestImportUserChannels(t *testing.T) {
data: &[]UserChannelImportData{
{
Name: &th.BasicChannel.Name,
Roles: model.NewString(model.CHANNEL_ADMIN_ROLE_ID),
Roles: model.NewString(model.ChannelAdminRoleId),
},
},
expectedError: false,
@@ -1874,9 +1874,9 @@ func TestImportUserChannels(t *testing.T) {
require.Equal(t, tc.expectedExplicitRoles, channelMember.ExplicitRoles, "Not matching expected explicit roles")
require.Equal(t, tc.expectedRoles, channelMember.Roles, "not matching expected roles")
if tc.expectedNotifyProps != nil {
require.Equal(t, *tc.expectedNotifyProps.Desktop, channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP])
require.Equal(t, *tc.expectedNotifyProps.Mobile, channelMember.NotifyProps[model.PUSH_NOTIFY_PROP])
require.Equal(t, *tc.expectedNotifyProps.MarkUnread, channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
require.Equal(t, *tc.expectedNotifyProps.Desktop, channelMember.NotifyProps[model.DesktopNotifyProp])
require.Equal(t, *tc.expectedNotifyProps.Mobile, channelMember.NotifyProps[model.PushNotifyProp])
require.Equal(t, *tc.expectedNotifyProps.MarkUnread, channelMember.NotifyProps[model.MarkUnreadNotifyProp])
}
}
}
@@ -1904,7 +1904,7 @@ func TestImportUserDefaultNotifyProps(t *testing.T) {
require.Nil(t, err)
// Check the value of the notify prop we specified explicitly in the import data.
val, ok := user.NotifyProps[model.EMAIL_NOTIFY_PROP]
val, ok := user.NotifyProps[model.EmailNotifyProp]
assert.True(t, ok)
assert.Equal(t, "false", val)
@@ -1913,7 +1913,7 @@ func TestImportUserDefaultNotifyProps(t *testing.T) {
comparisonUser.SetDefaultNotifications()
for key, expectedValue := range comparisonUser.NotifyProps {
if key == model.EMAIL_NOTIFY_PROP {
if key == model.EmailNotifyProp {
continue
}
@@ -2239,8 +2239,8 @@ func TestImportimportMultiplePostLines(t *testing.T) {
postBool = post.Message != *data.Post.Message || post.CreateAt != *data.Post.CreateAt || post.UserId != user.Id
require.False(t, postBool, "Post properties not as expected")
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, user2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, user.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
checkPreference(t, th.App, user2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
// Post with reaction.
reactionPostTime := hashtagTime + 2
@@ -2785,8 +2785,8 @@ func TestImportImportPost(t *testing.T) {
postBool := post.Message != *data.Post.Message || post.CreateAt != *data.Post.CreateAt || post.UserId != user.Id
require.False(t, postBool, "Post properties not as expected")
checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, user2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, user.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
checkPreference(t, th.App, user2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
})
t.Run("Post with reaction", func(t *testing.T) {
@@ -2959,10 +2959,10 @@ func TestImportImportDirectChannel(t *testing.T) {
defer th.TearDown()
// Check how many channels are in the database.
directChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT)
directChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeDirect)
require.NoError(t, err, "Failed to get direct channel count.")
groupChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP)
groupChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeGroup)
require.NoError(t, err, "Failed to get group channel count.")
// Do an invalid channel in dry-run mode.
@@ -2976,8 +2976,8 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Error(t, err)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Do a valid DIRECT channel with a nonexistent member in dry-run mode.
data.Members = &[]string{
@@ -2988,8 +2988,8 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Nil(t, appErr)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Do a valid GROUP channel with a nonexistent member in dry-run mode.
data.Members = &[]string{
@@ -3001,8 +3001,8 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Nil(t, appErr)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Do an invalid channel in apply mode.
data.Members = &[]string{
@@ -3012,8 +3012,8 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Error(t, err)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Do a valid DIRECT channel.
data.Members = &[]string{
@@ -3024,16 +3024,16 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Nil(t, appErr)
// Check that one more DIRECT channel is in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Do the same DIRECT channel again.
appErr = th.App.importDirectChannel(&data, false)
require.Nil(t, appErr)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Update the channel's HEADER
data.Header = ptrStr("New Channel Header 2")
@@ -3041,8 +3041,8 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Nil(t, appErr)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Get the channel to check that the header was updated.
channel, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
@@ -3061,8 +3061,8 @@ func TestImportImportDirectChannel(t *testing.T) {
require.NotNil(t, appErr)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount)
// Do a valid GROUP channel.
data.Members = &[]string{
@@ -3074,16 +3074,16 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Nil(t, appErr)
// Check that one more GROUP channel is in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount+1)
// Do the same DIRECT channel again.
appErr = th.App.importDirectChannel(&data, false)
require.Nil(t, appErr)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount+1)
// Update the channel's HEADER
data.Header = ptrStr("New Channel Header 3")
@@ -3091,8 +3091,8 @@ func TestImportImportDirectChannel(t *testing.T) {
require.Nil(t, appErr)
// Check that no more channels are in the DB.
AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeDirect, directChannelCount+1)
AssertChannelCount(t, th.App, model.ChannelTypeGroup, groupChannelCount+1)
// Get the channel to check that the header was updated.
userIDs := []string{
@@ -3118,8 +3118,8 @@ func TestImportImportDirectChannel(t *testing.T) {
channel, appErr = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
require.Nil(t, appErr)
checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
checkPreference(t, th.App, th.BasicUser.Id, model.PreferenceCategoryFavoriteChannel, channel.Id, "true")
checkPreference(t, th.App, th.BasicUser2.Id, model.PreferenceCategoryFavoriteChannel, channel.Id, "true")
}
func TestImportImportDirectPost(t *testing.T) {
@@ -3376,8 +3376,8 @@ func TestImportImportDirectPost(t *testing.T) {
require.Len(t, posts, 1)
post := posts[0]
checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, th.BasicUser.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
checkPreference(t, th.App, th.BasicUser2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
})
// ------------------ Group Channel -------------------------
@@ -3649,8 +3649,8 @@ func TestImportImportDirectPost(t *testing.T) {
require.Len(t, posts, 1)
post := posts[0]
checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
checkPreference(t, th.App, th.BasicUser.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
checkPreference(t, th.App, th.BasicUser2.Id, model.PreferenceCategoryFlaggedPost, post.Id, "true")
})
t.Run("Post with reaction", func(t *testing.T) {

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

@@ -20,11 +20,11 @@ func validateSchemeImportData(data *SchemeImportData) *model.AppError {
}
switch *data.Scope {
case model.SCHEME_SCOPE_TEAM:
case model.SchemeScopeTeam:
if data.DefaultTeamAdminRole == nil || data.DefaultTeamUserRole == nil || data.DefaultChannelAdminRole == nil || data.DefaultChannelUserRole == nil {
return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.wrong_roles_for_scope.error", nil, "", http.StatusBadRequest)
}
case model.SCHEME_SCOPE_CHANNEL:
case model.SchemeScopeChannel:
if data.DefaultTeamAdminRole != nil || data.DefaultTeamUserRole != nil || data.DefaultChannelAdminRole == nil || data.DefaultChannelUserRole == nil {
return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.wrong_roles_for_scope.error", nil, "", http.StatusBadRequest)
}
@@ -36,11 +36,11 @@ func validateSchemeImportData(data *SchemeImportData) *model.AppError {
return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.name_invalid.error", nil, "", http.StatusBadRequest)
}
if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.SCHEME_DISPLAY_NAME_MAX_LENGTH {
if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.SchemeDisplayNameMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest)
}
if data.Description != nil && len(*data.Description) > model.SCHEME_DESCRIPTION_MAX_LENGTH {
if data.Description != nil && len(*data.Description) > model.SchemeDescriptionMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_scheme_import_data.description_invalid.error", nil, "", http.StatusBadRequest)
}
@@ -89,11 +89,11 @@ func validateRoleImportData(data *RoleImportData) *model.AppError {
return model.NewAppError("BulkImport", "app.import.validate_role_import_data.name_invalid.error", nil, "", http.StatusBadRequest)
}
if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.ROLE_DISPLAY_NAME_MAX_LENGTH {
if data.DisplayName == nil || *data.DisplayName == "" || len(*data.DisplayName) > model.RoleDisplayNameMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_role_import_data.display_name_invalid.error", nil, "", http.StatusBadRequest)
}
if data.Description != nil && len(*data.Description) > model.ROLE_DESCRIPTION_MAX_LENGTH {
if data.Description != nil && len(*data.Description) > model.RoleDescriptionMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_role_import_data.description_invalid.error", nil, "", http.StatusBadRequest)
}
@@ -120,7 +120,7 @@ func validateTeamImportData(data *TeamImportData) *model.AppError {
if data.Name == nil {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.name_missing.error", nil, "", http.StatusBadRequest)
} else if len(*data.Name) > model.TEAM_NAME_MAX_LENGTH {
} else if len(*data.Name) > model.TeamNameMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.name_length.error", nil, "", http.StatusBadRequest)
} else if model.IsReservedTeamName(*data.Name) {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.name_reserved.error", nil, "", http.StatusBadRequest)
@@ -130,17 +130,17 @@ func validateTeamImportData(data *TeamImportData) *model.AppError {
if data.DisplayName == nil {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.display_name_missing.error", nil, "", http.StatusBadRequest)
} else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.TEAM_DISPLAY_NAME_MAX_RUNES {
} else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.TeamDisplayNameMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.display_name_length.error", nil, "", http.StatusBadRequest)
}
if data.Type == nil {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.type_missing.error", nil, "", http.StatusBadRequest)
} else if *data.Type != model.TEAM_OPEN && *data.Type != model.TEAM_INVITE {
} else if *data.Type != model.TeamOpen && *data.Type != model.TeamInvite {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.type_invalid.error", nil, "", http.StatusBadRequest)
}
if data.Description != nil && len(*data.Description) > model.TEAM_DESCRIPTION_MAX_LENGTH {
if data.Description != nil && len(*data.Description) > model.TeamDescriptionMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_team_import_data.description_length.error", nil, "", http.StatusBadRequest)
}
@@ -159,7 +159,7 @@ func validateChannelImportData(data *ChannelImportData) *model.AppError {
if data.Name == nil {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.name_missing.error", nil, "", http.StatusBadRequest)
} else if len(*data.Name) > model.CHANNEL_NAME_MAX_LENGTH {
} else if len(*data.Name) > model.ChannelNameMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.name_length.error", nil, "", http.StatusBadRequest)
} else if !model.IsValidChannelIdentifier(*data.Name) {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.name_characters.error", nil, "", http.StatusBadRequest)
@@ -167,21 +167,21 @@ func validateChannelImportData(data *ChannelImportData) *model.AppError {
if data.DisplayName == nil {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.display_name_missing.error", nil, "", http.StatusBadRequest)
} else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.CHANNEL_DISPLAY_NAME_MAX_RUNES {
} else if utf8.RuneCountInString(*data.DisplayName) == 0 || utf8.RuneCountInString(*data.DisplayName) > model.ChannelDisplayNameMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.display_name_length.error", nil, "", http.StatusBadRequest)
}
if data.Type == nil {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.type_missing.error", nil, "", http.StatusBadRequest)
} else if *data.Type != model.CHANNEL_OPEN && *data.Type != model.CHANNEL_PRIVATE {
} else if *data.Type != model.ChannelTypeOpen && *data.Type != model.ChannelTypePrivate {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.type_invalid.error", nil, "", http.StatusBadRequest)
}
if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.CHANNEL_HEADER_MAX_RUNES {
if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.ChannelHeaderMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.header_length.error", nil, "", http.StatusBadRequest)
}
if data.Purpose != nil && utf8.RuneCountInString(*data.Purpose) > model.CHANNEL_PURPOSE_MAX_RUNES {
if data.Purpose != nil && utf8.RuneCountInString(*data.Purpose) > model.ChannelPurposeMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_channel_import_data.purpose_length.error", nil, "", http.StatusBadRequest)
}
@@ -207,7 +207,7 @@ func validateUserImportData(data *UserImportData) *model.AppError {
if data.Email == nil {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_missing.error", nil, "", http.StatusBadRequest)
} else if *data.Email == "" || len(*data.Email) > model.USER_EMAIL_MAX_LENGTH {
} else if *data.Email == "" || len(*data.Email) > model.UserEmailMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.email_length.error", nil, "", http.StatusBadRequest)
}
@@ -215,7 +215,7 @@ func validateUserImportData(data *UserImportData) *model.AppError {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.auth_data_and_password.error", nil, "", http.StatusBadRequest)
}
if data.AuthData != nil && len(*data.AuthData) > model.USER_AUTH_DATA_MAX_LENGTH {
if data.AuthData != nil && len(*data.AuthData) > model.UserAuthDataMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.auth_data_length.error", nil, "", http.StatusBadRequest)
}
@@ -234,23 +234,23 @@ func validateUserImportData(data *UserImportData) *model.AppError {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.password_length.error", nil, "", http.StatusBadRequest)
}
if data.Password != nil && len(*data.Password) > model.USER_PASSWORD_MAX_LENGTH {
if data.Password != nil && len(*data.Password) > model.UserPasswordMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.password_length.error", nil, "", http.StatusBadRequest)
}
if data.Nickname != nil && utf8.RuneCountInString(*data.Nickname) > model.USER_NICKNAME_MAX_RUNES {
if data.Nickname != nil && utf8.RuneCountInString(*data.Nickname) > model.UserNicknameMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.nickname_length.error", nil, "", http.StatusBadRequest)
}
if data.FirstName != nil && utf8.RuneCountInString(*data.FirstName) > model.USER_FIRST_NAME_MAX_RUNES {
if data.FirstName != nil && utf8.RuneCountInString(*data.FirstName) > model.UserFirstNameMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.first_name_length.error", nil, "", http.StatusBadRequest)
}
if data.LastName != nil && utf8.RuneCountInString(*data.LastName) > model.USER_LAST_NAME_MAX_RUNES {
if data.LastName != nil && utf8.RuneCountInString(*data.LastName) > model.UserLastNameMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.last_name_length.error", nil, "", http.StatusBadRequest)
}
if data.Position != nil && utf8.RuneCountInString(*data.Position) > model.USER_POSITION_MAX_RUNES {
if data.Position != nil && utf8.RuneCountInString(*data.Position) > model.UserPositionMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_user_import_data.position_length.error", nil, "", http.StatusBadRequest)
}
@@ -381,7 +381,7 @@ func validateReactionImportData(data *ReactionImportData, parentCreateAt int64)
if data.EmojiName == nil {
return model.NewAppError("BulkImport", "app.import.validate_reaction_import_data.emoji_name_missing.error", nil, "", http.StatusBadRequest)
} else if utf8.RuneCountInString(*data.EmojiName) > model.EMOJI_NAME_MAX_LENGTH {
} else if utf8.RuneCountInString(*data.EmojiName) > model.EmojiNameMaxLength {
return model.NewAppError("BulkImport", "app.import.validate_reaction_import_data.emoji_name_length.error", nil, "", http.StatusBadRequest)
}
@@ -457,7 +457,7 @@ func validatePostImportData(data *PostImportData, maxPostSize int) *model.AppErr
}
}
if data.Props != nil && utf8.RuneCountInString(model.StringInterfaceToJson(*data.Props)) > model.POST_PROPS_MAX_RUNES {
if data.Props != nil && utf8.RuneCountInString(model.StringInterfaceToJson(*data.Props)) > model.PostPropsMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_post_import_data.props_too_large.error", nil, "", http.StatusBadRequest)
}
@@ -470,14 +470,14 @@ func validateDirectChannelImportData(data *DirectChannelImportData) *model.AppEr
}
if len(*data.Members) != 2 {
if len(*data.Members) < model.CHANNEL_GROUP_MIN_USERS {
if len(*data.Members) < model.ChannelGroupMinUsers {
return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.members_too_few.error", nil, "", http.StatusBadRequest)
} else if len(*data.Members) > model.CHANNEL_GROUP_MAX_USERS {
} else if len(*data.Members) > model.ChannelGroupMaxUsers {
return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.members_too_many.error", nil, "", http.StatusBadRequest)
}
}
if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.CHANNEL_HEADER_MAX_RUNES {
if data.Header != nil && utf8.RuneCountInString(*data.Header) > model.ChannelHeaderMaxRunes {
return model.NewAppError("BulkImport", "app.import.validate_direct_channel_import_data.header_length.error", nil, "", http.StatusBadRequest)
}
@@ -505,9 +505,9 @@ func validateDirectPostImportData(data *DirectPostImportData, maxPostSize int) *
}
if len(*data.ChannelMembers) != 2 {
if len(*data.ChannelMembers) < model.CHANNEL_GROUP_MIN_USERS {
if len(*data.ChannelMembers) < model.ChannelGroupMinUsers {
return model.NewAppError("BulkImport", "app.import.validate_direct_post_import_data.channel_members_too_few.error", nil, "", http.StatusBadRequest)
} else if len(*data.ChannelMembers) > model.CHANNEL_GROUP_MAX_USERS {
} else if len(*data.ChannelMembers) > model.ChannelGroupMaxUsers {
return model.NewAppError("BulkImport", "app.import.validate_direct_post_import_data.channel_members_too_many.error", nil, "", http.StatusBadRequest)
}
}

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

@@ -586,7 +586,7 @@ func TestImportValidateUserImportData(t *testing.T) {
data.NotifyProps.Desktop = ptrStr("invalid")
checkError(t, validateUserImportData(&data))
data.NotifyProps.Desktop = ptrStr(model.USER_NOTIFY_ALL)
data.NotifyProps.Desktop = ptrStr(model.UserNotifyAll)
data.NotifyProps.DesktopSound = ptrStr("invalid")
checkError(t, validateUserImportData(&data))
@@ -598,11 +598,11 @@ func TestImportValidateUserImportData(t *testing.T) {
data.NotifyProps.Mobile = ptrStr("invalid")
checkError(t, validateUserImportData(&data))
data.NotifyProps.Mobile = ptrStr(model.USER_NOTIFY_ALL)
data.NotifyProps.Mobile = ptrStr(model.UserNotifyAll)
data.NotifyProps.MobilePushStatus = ptrStr("invalid")
checkError(t, validateUserImportData(&data))
data.NotifyProps.MobilePushStatus = ptrStr(model.STATUS_ONLINE)
data.NotifyProps.MobilePushStatus = ptrStr(model.StatusOnline)
data.NotifyProps.ChannelTrigger = ptrStr("invalid")
checkError(t, validateUserImportData(&data))
@@ -610,7 +610,7 @@ func TestImportValidateUserImportData(t *testing.T) {
data.NotifyProps.CommentsTrigger = ptrStr("invalid")
checkError(t, validateUserImportData(&data))
data.NotifyProps.CommentsTrigger = ptrStr(model.COMMENTS_NOTIFY_ROOT)
data.NotifyProps.CommentsTrigger = ptrStr(model.CommentsNotifyRoot)
data.NotifyProps.MentionKeys = ptrStr("valid")
checkNoError(t, validateUserImportData(&data))
@@ -1013,7 +1013,7 @@ func TestImportValidatePostImportData(t *testing.T) {
t.Run("Test with props too large", func(t *testing.T) {
props := model.StringInterface{
"attachment": strings.Repeat("a", model.POST_PROPS_MAX_RUNES),
"attachment": strings.Repeat("a", model.PostPropsMaxRunes),
}
data := PostImportData{

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

@@ -219,7 +219,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI
upstreamRequest.TeamName = team.Name
}
if upstreamRequest.Type == model.POST_ACTION_TYPE_SELECT {
if upstreamRequest.Type == model.PostActionTypeSelect {
if selectedOption != "" {
if upstreamRequest.Context == nil {
upstreamRequest.Context = map[string]interface{}{}
@@ -329,7 +329,7 @@ func (a *App) DoActionRequest(c *request.Context, rawURL string, body []byte) (*
subpath, _ := utils.GetSubpathFromConfig(a.Config())
siteURL, _ := url.Parse(*a.Config().ServiceSettings.SiteURL)
if (inURL.Hostname() == "localhost" || inURL.Hostname() == "127.0.0.1" || inURL.Hostname() == siteURL.Hostname()) && strings.HasPrefix(inURL.Path, path.Join(subpath, "plugins")) {
req.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token)
req.Header.Set(model.HeaderAuth, "Bearer "+c.Session().Token)
httpClient = a.HTTPService().MakeClient(true)
} else {
httpClient = a.HTTPService().MakeClient(false)
@@ -414,7 +414,7 @@ func (a *App) doPluginRequest(c *request.Context, method, rawURL string, values
return nil, model.NewAppError("doPluginRequest", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest)
}
r.Header.Set("Mattermost-User-Id", c.Session().UserId)
r.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token)
r.Header.Set(model.HeaderAuth, "Bearer "+c.Session().Token)
params := make(map[string]string)
params["plugin_id"] = pluginID
r = mux.SetURLVars(r, params)
@@ -485,7 +485,7 @@ func (a *App) doLocalWarnMetricsRequest(c *request.Context, rawURL string, upstr
&model.PostAction{
Id: "emailUs",
Name: i18n.T("api.server.warn_metric.email_us"),
Type: model.POST_ACTION_TYPE_BUTTON,
Type: model.PostActionTypeButton,
Options: []*model.PostActionOptions{
{
Text: "WarnMetricMailtoUrl",
@@ -501,7 +501,7 @@ func (a *App) doLocalWarnMetricsRequest(c *request.Context, rawURL string, upstr
"bot_user_id": botPost.UserId,
"force_ack": true,
},
URL: fmt.Sprintf("/warn_metrics/ack/%s", model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500),
URL: fmt.Sprintf("/warn_metrics/ack/%s", model.SystemWarnMetricNumberOfActiveUsers500),
},
},
)
@@ -563,7 +563,7 @@ func (a *App) buildWarnMetricMailtoLink(warnMetricId string, user *model.User) s
mailToLinkContent := &MailToLinkContent{
MetricId: warnMetricId,
MailRecipient: model.MM_SUPPORT_ADVISOR_ADDRESS,
MailRecipient: model.MmSupportAdvisorAddress,
MailCC: user.Email,
MailSubject: T("api.server.warn_metric.bot_response.mailto_subject"),
MailBody: mailBody,
@@ -586,7 +586,7 @@ func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppE
jsonRequest, _ := json.Marshal(request)
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_OPEN_DIALOG, "", "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventOpenDialog, "", "", userID, nil)
message.Add("dialog", string(jsonRequest))
a.Publish(message)

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

@@ -162,7 +162,7 @@ func TestPostAction(t *testing.T) {
assert.Equal(t, request.UserName, th.BasicUser.Username)
assert.Equal(t, request.ChannelId, channel.Id)
assert.Equal(t, request.ChannelName, channel.Name)
if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP {
if channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup {
assert.Empty(t, request.TeamId)
assert.Empty(t, request.TeamName)
} else {
@@ -170,7 +170,7 @@ func TestPostAction(t *testing.T) {
assert.Equal(t, request.TeamName, th.BasicTeam.Name)
}
assert.True(t, request.TriggerId != "")
if request.Type == model.POST_ACTION_TYPE_SELECT {
if request.Type == model.PostActionTypeSelect {
assert.Equal(t, request.DataSource, "some_source")
assert.Equal(t, request.Context["selected_option"], "selected")
} else {
@@ -238,7 +238,7 @@ func TestPostAction(t *testing.T) {
URL: ts.URL,
},
Name: "action",
Type: model.POST_ACTION_TYPE_SELECT,
Type: model.PostActionTypeSelect,
DataSource: "some_source",
},
},

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

@@ -74,30 +74,30 @@ func (a *App) CancelJob(jobId string) *model.AppError {
func (a *App) SessionHasPermissionToCreateJob(session model.Session, job *model.Job) (bool, *model.Permission) {
switch job.Type {
case model.JOB_TYPE_BLEVE_POST_INDEXING:
return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB), model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB
case model.JOB_TYPE_DATA_RETENTION:
return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_DATA_RETENTION_JOB), model.PERMISSION_CREATE_DATA_RETENTION_JOB
case model.JOB_TYPE_MESSAGE_EXPORT:
return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB), model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB
case model.JOB_TYPE_ELASTICSEARCH_POST_INDEXING:
return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB), model.PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB
case model.JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION:
return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB), model.PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB
case model.JOB_TYPE_LDAP_SYNC:
return a.SessionHasPermissionTo(session, model.PERMISSION_CREATE_LDAP_SYNC_JOB), model.PERMISSION_CREATE_LDAP_SYNC_JOB
case model.JobTypeBlevePostIndexing:
return a.SessionHasPermissionTo(session, model.PermissionCreatePostBleveIndexesJob), model.PermissionCreatePostBleveIndexesJob
case model.JobTypeDataRetention:
return a.SessionHasPermissionTo(session, model.PermissionCreateDataRetentionJob), model.PermissionCreateDataRetentionJob
case model.JobTypeMessageExport:
return a.SessionHasPermissionTo(session, model.PermissionCreateComplianceExportJob), model.PermissionCreateComplianceExportJob
case model.JobTypeElasticsearchPostIndexing:
return a.SessionHasPermissionTo(session, model.PermissionCreateElasticsearchPostIndexingJob), model.PermissionCreateElasticsearchPostIndexingJob
case model.JobTypeElasticsearchPostAggregation:
return a.SessionHasPermissionTo(session, model.PermissionCreateElasticsearchPostAggregationJob), model.PermissionCreateElasticsearchPostAggregationJob
case model.JobTypeLdapSync:
return a.SessionHasPermissionTo(session, model.PermissionCreateLdapSyncJob), model.PermissionCreateLdapSyncJob
case
model.JOB_TYPE_MIGRATIONS,
model.JOB_TYPE_PLUGINS,
model.JOB_TYPE_PRODUCT_NOTICES,
model.JOB_TYPE_EXPIRY_NOTIFY,
model.JOB_TYPE_ACTIVE_USERS,
model.JOB_TYPE_IMPORT_PROCESS,
model.JOB_TYPE_IMPORT_DELETE,
model.JOB_TYPE_EXPORT_PROCESS,
model.JOB_TYPE_EXPORT_DELETE,
model.JOB_TYPE_CLOUD:
return a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_JOBS), model.PERMISSION_MANAGE_JOBS
model.JobTypeMigrations,
model.JobTypePlugins,
model.JobTypeProductNotices,
model.JobTypeExpiryNotify,
model.JobTypeActiveUsers,
model.JobTypeImportProcess,
model.JobTypeImportDelete,
model.JobTypeExportProcess,
model.JobTypeExportDelete,
model.JobTypeCloud:
return a.SessionHasPermissionTo(session, model.PermissionManageJobs), model.PermissionManageJobs
}
return false, nil
@@ -105,29 +105,29 @@ func (a *App) SessionHasPermissionToCreateJob(session model.Session, job *model.
func (a *App) SessionHasPermissionToReadJob(session model.Session, jobType string) (bool, *model.Permission) {
switch jobType {
case model.JOB_TYPE_DATA_RETENTION:
return a.SessionHasPermissionTo(session, model.PERMISSION_READ_DATA_RETENTION_JOB), model.PERMISSION_READ_DATA_RETENTION_JOB
case model.JOB_TYPE_MESSAGE_EXPORT:
return a.SessionHasPermissionTo(session, model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB), model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB
case model.JOB_TYPE_ELASTICSEARCH_POST_INDEXING:
return a.SessionHasPermissionTo(session, model.PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB), model.PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB
case model.JOB_TYPE_ELASTICSEARCH_POST_AGGREGATION:
return a.SessionHasPermissionTo(session, model.PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB), model.PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB
case model.JOB_TYPE_LDAP_SYNC:
return a.SessionHasPermissionTo(session, model.PERMISSION_READ_LDAP_SYNC_JOB), model.PERMISSION_READ_LDAP_SYNC_JOB
case model.JobTypeDataRetention:
return a.SessionHasPermissionTo(session, model.PermissionReadDataRetentionJob), model.PermissionReadDataRetentionJob
case model.JobTypeMessageExport:
return a.SessionHasPermissionTo(session, model.PermissionReadComplianceExportJob), model.PermissionReadComplianceExportJob
case model.JobTypeElasticsearchPostIndexing:
return a.SessionHasPermissionTo(session, model.PermissionReadElasticsearchPostIndexingJob), model.PermissionReadElasticsearchPostIndexingJob
case model.JobTypeElasticsearchPostAggregation:
return a.SessionHasPermissionTo(session, model.PermissionReadElasticsearchPostAggregationJob), model.PermissionReadElasticsearchPostAggregationJob
case model.JobTypeLdapSync:
return a.SessionHasPermissionTo(session, model.PermissionReadLdapSyncJob), model.PermissionReadLdapSyncJob
case
model.JOB_TYPE_BLEVE_POST_INDEXING,
model.JOB_TYPE_MIGRATIONS,
model.JOB_TYPE_PLUGINS,
model.JOB_TYPE_PRODUCT_NOTICES,
model.JOB_TYPE_EXPIRY_NOTIFY,
model.JOB_TYPE_ACTIVE_USERS,
model.JOB_TYPE_IMPORT_PROCESS,
model.JOB_TYPE_IMPORT_DELETE,
model.JOB_TYPE_EXPORT_PROCESS,
model.JOB_TYPE_EXPORT_DELETE,
model.JOB_TYPE_CLOUD:
return a.SessionHasPermissionTo(session, model.PERMISSION_READ_JOBS), model.PERMISSION_READ_JOBS
model.JobTypeBlevePostIndexing,
model.JobTypeMigrations,
model.JobTypePlugins,
model.JobTypeProductNotices,
model.JobTypeExpiryNotify,
model.JobTypeActiveUsers,
model.JobTypeImportProcess,
model.JobTypeImportDelete,
model.JobTypeExportProcess,
model.JobTypeExportDelete,
model.JobTypeCloud:
return a.SessionHasPermissionTo(session, model.PermissionReadJobs), model.PermissionReadJobs
}
return false, nil

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

@@ -39,17 +39,17 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) {
jobs := []model.Job{
{
Id: model.NewId(),
Type: model.JOB_TYPE_BLEVE_POST_INDEXING,
Type: model.JobTypeBlevePostIndexing,
CreateAt: 1000,
},
{
Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION,
Type: model.JobTypeDataRetention,
CreateAt: 999,
},
{
Id: model.NewId(),
Type: model.JOB_TYPE_MESSAGE_EXPORT,
Type: model.JobTypeMessageExport,
CreateAt: 1001,
},
}
@@ -60,20 +60,20 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) {
}{
{
Job: jobs[0],
PermissionRequired: model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB,
PermissionRequired: model.PermissionCreatePostBleveIndexesJob,
},
{
Job: jobs[1],
PermissionRequired: model.PERMISSION_CREATE_DATA_RETENTION_JOB,
PermissionRequired: model.PermissionCreateDataRetentionJob,
},
{
Job: jobs[2],
PermissionRequired: model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB,
PermissionRequired: model.PermissionCreateComplianceExportJob,
},
}
session := model.Session{
Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID,
Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId,
}
// Check to see if admin has permission to all the jobs
@@ -85,7 +85,7 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) {
}
session = model.Session{
Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID,
Roles: model.SystemUserRoleId + " " + model.SystemReadOnlyAdminRoleId,
}
// Initially the system read only admin should not have access to create these jobs
@@ -97,9 +97,9 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) {
}
ctx := sqlstore.WithMaster(context.Background())
role, _ := th.App.GetRoleByName(ctx, model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID)
role, _ := th.App.GetRoleByName(ctx, model.SystemReadOnlyAdminRoleId)
role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB.Id)
role.Permissions = append(role.Permissions, model.PermissionCreatePostBleveIndexesJob.Id)
_, err := th.App.UpdateRole(role)
require.Nil(t, err)
@@ -107,14 +107,14 @@ func TestSessionHasPermissionToCreateJob(t *testing.T) {
// Now system read only admin should have ability to create a Belve Post Index job but not the others
for _, testCase := range testCases {
hasPermission, permissionRequired := th.App.SessionHasPermissionToCreateJob(session, &testCase.Job)
expectedHasPermission := testCase.Job.Type == model.JOB_TYPE_BLEVE_POST_INDEXING
expectedHasPermission := testCase.Job.Type == model.JobTypeBlevePostIndexing
assert.Equal(t, expectedHasPermission, hasPermission)
require.NotNil(t, permissionRequired)
assert.Equal(t, testCase.PermissionRequired.Id, permissionRequired.Id)
}
role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_DATA_RETENTION_JOB.Id)
role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB.Id)
role.Permissions = append(role.Permissions, model.PermissionCreateDataRetentionJob.Id)
role.Permissions = append(role.Permissions, model.PermissionCreateComplianceExportJob.Id)
_, err = th.App.UpdateRole(role)
require.Nil(t, err)
@@ -135,12 +135,12 @@ func TestSessionHasPermissionToReadJob(t *testing.T) {
jobs := []model.Job{
{
Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION,
Type: model.JobTypeDataRetention,
CreateAt: 999,
},
{
Id: model.NewId(),
Type: model.JOB_TYPE_MESSAGE_EXPORT,
Type: model.JobTypeMessageExport,
CreateAt: 1001,
},
}
@@ -150,16 +150,16 @@ func TestSessionHasPermissionToReadJob(t *testing.T) {
}{
{
Job: jobs[0],
PermissionRequired: model.PERMISSION_READ_DATA_RETENTION_JOB,
PermissionRequired: model.PermissionReadDataRetentionJob,
},
{
Job: jobs[1],
PermissionRequired: model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB,
PermissionRequired: model.PermissionReadComplianceExportJob,
},
}
session := model.Session{
Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_ADMIN_ROLE_ID,
Roles: model.SystemUserRoleId + " " + model.SystemAdminRoleId,
}
// Check to see if admin has permission to all the jobs
@@ -171,7 +171,7 @@ func TestSessionHasPermissionToReadJob(t *testing.T) {
}
session = model.Session{
Roles: model.SYSTEM_USER_ROLE_ID + " " + model.SYSTEM_MANAGER_ROLE_ID,
Roles: model.SystemUserRoleId + " " + model.SystemManagerRoleId,
}
// Initially the system manager should not have access to read these jobs
@@ -183,9 +183,9 @@ func TestSessionHasPermissionToReadJob(t *testing.T) {
}
ctx := sqlstore.WithMaster(context.Background())
role, _ := th.App.GetRoleByName(ctx, model.SYSTEM_MANAGER_ROLE_ID)
role, _ := th.App.GetRoleByName(ctx, model.SystemManagerRoleId)
role.Permissions = append(role.Permissions, model.PERMISSION_READ_DATA_RETENTION_JOB.Id)
role.Permissions = append(role.Permissions, model.PermissionReadDataRetentionJob.Id)
_, err := th.App.UpdateRole(role)
require.Nil(t, err)
@@ -193,13 +193,13 @@ func TestSessionHasPermissionToReadJob(t *testing.T) {
// Now system manager should have ability to read data retention jobs
for _, testCase := range testCases {
hasPermission, permissionRequired := th.App.SessionHasPermissionToReadJob(session, testCase.Job.Type)
expectedHasPermission := testCase.Job.Type == model.JOB_TYPE_DATA_RETENTION
expectedHasPermission := testCase.Job.Type == model.JobTypeDataRetention
assert.Equal(t, expectedHasPermission, hasPermission)
require.NotNil(t, permissionRequired)
assert.Equal(t, testCase.PermissionRequired.Id, permissionRequired.Id)
}
role.Permissions = append(role.Permissions, model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB.Id)
role.Permissions = append(role.Permissions, model.PermissionReadComplianceExportJob.Id)
_, err = th.App.UpdateRole(role)
require.Nil(t, err)

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

@@ -128,7 +128,7 @@ func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (
return "", err
}
if user.AuthService != model.USER_AUTH_SERVICE_LDAP {
if user.AuthService != model.UserAuthServiceLdap {
return "", model.NewAppError("SwitchLdapToEmail", "api.user.ldap_to_email.not_ldap_account.app_error", nil, "", http.StatusBadRequest)
}
@@ -200,12 +200,12 @@ func (a *App) writeLdapFile(filename string, fileData *multipart.FileHeader) *mo
}
func (a *App) AddLdapPublicCertificate(fileData *multipart.FileHeader) *model.AppError {
if err := a.writeLdapFile(model.LDAP_PUBLIC_CERTIFICATE_NAME, fileData); err != nil {
if err := a.writeLdapFile(model.LdapPublicCertificateName, fileData); err != nil {
return err
}
cfg := a.Config().Clone()
*cfg.LdapSettings.PublicCertificateFile = model.LDAP_PUBLIC_CERTIFICATE_NAME
*cfg.LdapSettings.PublicCertificateFile = model.LdapPublicCertificateName
if err := cfg.IsValid(); err != nil {
return err
@@ -217,12 +217,12 @@ func (a *App) AddLdapPublicCertificate(fileData *multipart.FileHeader) *model.Ap
}
func (a *App) AddLdapPrivateCertificate(fileData *multipart.FileHeader) *model.AppError {
if err := a.writeLdapFile(model.LDAP_PRIVATE_KEY_NAME, fileData); err != nil {
if err := a.writeLdapFile(model.LdapPrivateKeyName, fileData); err != nil {
return err
}
cfg := a.Config().Clone()
*cfg.LdapSettings.PrivateKeyFile = model.LDAP_PRIVATE_KEY_NAME
*cfg.LdapSettings.PrivateKeyFile = model.LdapPrivateKeyName
if err := cfg.IsValid(); err != nil {
return err

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

@@ -67,7 +67,7 @@ func (s *Server) LoadLicense() {
licenseId := ""
props, nErr := s.Store.System().Get()
if nErr == nil {
licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID]
licenseId = props[model.SystemActiveLicenseId]
}
if !model.IsValidId(licenseId) {
@@ -97,7 +97,7 @@ func (s *Server) LoadLicense() {
func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) {
success, licenseStr := utils.LicenseValidator.ValidateLicense(licenseBytes)
if !success {
return nil, model.NewAppError("addLicense", model.INVALID_LICENSE_ERROR, nil, "", http.StatusBadRequest)
return nil, model.NewAppError("addLicense", model.InvalidLicenseError, nil, "", http.StatusBadRequest)
}
license := model.LicenseFromJson(strings.NewReader(licenseStr))
@@ -111,11 +111,11 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr
}
if license != nil && license.IsExpired() {
return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest)
return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest)
}
if ok := s.SetLicense(license); !ok {
return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest)
return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest)
}
record := &model.LicenseRecord{}
@@ -135,7 +135,7 @@ func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppErr
}
sysVar := &model.System{}
sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID
sysVar.Name = model.SystemActiveLicenseId
sysVar.Value = license.Id
if err := s.Store.System().SaveOrUpdate(sysVar); err != nil {
s.RemoveLicense()
@@ -220,10 +220,10 @@ func (s *Server) RemoveLicense() *model.AppError {
return nil
}
mlog.Info("Remove license.", mlog.String("id", model.SYSTEM_ACTIVE_LICENSE_ID))
mlog.Info("Remove license.", mlog.String("id", model.SystemActiveLicenseId))
sysVar := &model.System{}
sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID
sysVar.Name = model.SystemActiveLicenseId
sysVar.Value = ""
if err := s.Store.System().SaveOrUpdate(sysVar); err != nil {
@@ -280,7 +280,7 @@ func (s *Server) GenerateRenewalToken(expiration time.Duration) (string, *model.
license := s.License()
if license == nil {
// Clean renewal token if there is no license present
if _, err := s.Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN); err != nil {
if _, err := s.Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken); err != nil {
mlog.Warn("error removing the renewal token", mlog.Err(err))
}
return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.no_license", nil, "", http.StatusBadRequest)
@@ -290,7 +290,7 @@ func (s *Server) GenerateRenewalToken(expiration time.Duration) (string, *model.
return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.bad_license", nil, "", http.StatusBadRequest)
}
currentToken, _ := s.Store.System().GetByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN)
currentToken, _ := s.Store.System().GetByName(model.SystemLicenseRenewalToken)
if currentToken != nil {
tokenIsValid, err := s.renewalTokenValid(currentToken.Value, license.Customer.Email)
if err != nil {
@@ -322,7 +322,7 @@ func (s *Server) GenerateRenewalToken(expiration time.Duration) (string, *model.
return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.app_error", nil, err.Error(), http.StatusInternalServerError)
}
err = s.Store.System().SaveOrUpdate(&model.System{
Name: model.SYSTEM_LICENSE_RENEWAL_TOKEN,
Name: model.SystemLicenseRenewalToken,
Value: tokenString,
})
if err != nil {

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

@@ -85,7 +85,7 @@ func TestGenerateRenewalToken(t *testing.T) {
token, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration)
require.Nil(t, appErr)
require.NotEmpty(t, token)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken)
customerEmail := th.App.Srv().License().Customer.Email
validToken, err := th.App.Srv().renewalTokenValid(token, customerEmail)
@@ -98,7 +98,7 @@ func TestGenerateRenewalToken(t *testing.T) {
token, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration)
require.Nil(t, appErr)
require.NotEmpty(t, token)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken)
newToken, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration)
require.Nil(t, appErr)
@@ -116,7 +116,7 @@ func TestGenerateRenewalToken(t *testing.T) {
token, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration)
require.Nil(t, appErr)
require.NotEmpty(t, token)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken)
setLicense(th, &model.Customer{
Name: "another customer",
Email: "another@example.com",
@@ -131,7 +131,7 @@ func TestGenerateRenewalToken(t *testing.T) {
token, appErr := th.App.Srv().GenerateRenewalToken(1 * time.Second)
require.Nil(t, appErr)
require.NotEmpty(t, token)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SYSTEM_LICENSE_RENEWAL_TOKEN)
defer th.App.Srv().Store.System().PermanentDeleteByName(model.SystemLicenseRenewalToken)
// The small time unit for expiration we're using is seconds
time.Sleep(1 * time.Second)
newToken, appErr := th.App.Srv().GenerateRenewalToken(JWTDefaultTokenExpiration)

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

@@ -102,7 +102,7 @@ func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password
// If client side cert is enable and it's checking as a primary source
// then trust the proxy and cert that the correct user is supplied and allow
// them access
if *a.Config().ExperimentalSettings.ClientSideCertEnable && *a.Config().ExperimentalSettings.ClientSideCertCheck == model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH {
if *a.Config().ExperimentalSettings.ClientSideCertEnable && *a.Config().ExperimentalSettings.ClientSideCertCheck == model.ClientSideCertCheckPrimaryAuth {
// Unless the user is a bot.
if err = checkUserNotBot(user); err != nil {
return nil, err
@@ -145,7 +145,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError)
// Try to get the user with LDAP if enabled
if *a.Config().LdapSettings.Enable && a.Ldap() != nil {
if ldapUser, err := a.Ldap().GetUser(loginId); err == nil {
if user, err := a.GetUserByAuth(ldapUser.AuthData, model.USER_AUTH_SERVICE_LDAP); err == nil {
if user, err := a.GetUserByAuth(ldapUser.AuthData, model.UserAuthServiceLdap); err == nil {
return user, nil
}
return ldapUser, nil
@@ -170,9 +170,9 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request
}
session := &model.Session{UserId: user.Id, Roles: user.GetRawRoles(), DeviceId: deviceID, IsOAuth: false, Props: map[string]string{
model.USER_AUTH_SERVICE_IS_MOBILE: strconv.FormatBool(isMobile),
model.USER_AUTH_SERVICE_IS_SAML: strconv.FormatBool(isSaml),
model.USER_AUTH_SERVICE_IS_OAUTH: strconv.FormatBool(isOAuthUser),
model.UserAuthServiceIsMobile: strconv.FormatBool(isMobile),
model.UserAuthServiceIsSaml: strconv.FormatBool(isSaml),
model.UserAuthServiceIsOAuth: strconv.FormatBool(isOAuthUser),
}}
session.GenerateCSRF()
@@ -199,13 +199,13 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request
bname := getBrowserName(ua, r.UserAgent())
bversion := getBrowserVersion(ua, r.UserAgent())
session.AddProp(model.SESSION_PROP_PLATFORM, plat)
session.AddProp(model.SESSION_PROP_OS, os)
session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion))
session.AddProp(model.SessionPropPlatform, plat)
session.AddProp(model.SessionPropOs, os)
session.AddProp(model.SessionPropBrowser, fmt.Sprintf("%v/%v", bname, bversion))
if user.IsGuest() {
session.AddProp(model.SESSION_PROP_IS_GUEST, "true")
session.AddProp(model.SessionPropIsGuest, "true")
} else {
session.AddProp(model.SESSION_PROP_IS_GUEST, "false")
session.AddProp(model.SessionPropIsGuest, "false")
}
var err *model.AppError
@@ -214,7 +214,7 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request
return err
}
w.Header().Set(model.HEADER_TOKEN, session.Token)
w.Header().Set(model.HeaderToken, session.Token)
c.SetSession(session)
if a.Srv().License() != nil && *a.Srv().License().Features.LDAP && a.Ldap() != nil {
@@ -250,7 +250,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r
expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0)
sessionCookie := &http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Name: model.SessionCookieToken,
Value: c.Session().Token,
Path: subpath,
MaxAge: maxAge,
@@ -261,7 +261,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r
}
userCookie := &http.Cookie{
Name: model.SESSION_COOKIE_USER,
Name: model.SessionCookieUser,
Value: c.Session().UserId,
Path: subpath,
MaxAge: maxAge,
@@ -271,7 +271,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r
}
csrfCookie := &http.Cookie{
Name: model.SESSION_COOKIE_CSRF,
Name: model.SessionCookieCsrf,
Value: c.Session().GetCSRF(),
Path: subpath,
MaxAge: maxAge,
@@ -286,7 +286,7 @@ func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r
}
func GetProtocol(r *http.Request) string {
if r.Header.Get(model.HEADER_FORWARDED_PROTO) == "https" || r.TLS != nil {
if r.Header.Get(model.HeaderForwardedProto) == "https" || r.TLS != nil {
return "https"
}
return "http"

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

@@ -25,7 +25,7 @@ func (a *App) DoAdvancedPermissionsMigration() {
func (s *Server) doAdvancedPermissionsMigration() {
// If the migration is already marked as completed, don't do it again.
if _, err := s.Store.System().GetByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil {
if _, err := s.Store.System().GetByName(model.AdvancedPermissionsMigrationKey); err == nil {
return
}
@@ -68,7 +68,7 @@ func (s *Server) doAdvancedPermissionsMigration() {
}
config := s.Config()
if *config.ServiceSettings.DEPRECATED_DO_NOT_USE_AllowEditPost == model.ALLOW_EDIT_POST_ALWAYS {
if *config.ServiceSettings.DEPRECATED_DO_NOT_USE_AllowEditPost == model.AllowEditPostAlways {
*config.ServiceSettings.PostEditTimeLimit = -1
if _, _, err := s.SaveConfig(config, true); err != nil {
mlog.Error("Failed to update config in Advanced Permissions Phase 1 Migration.", mlog.Err(err))
@@ -76,7 +76,7 @@ func (s *Server) doAdvancedPermissionsMigration() {
}
system := model.System{
Name: model.ADVANCED_PERMISSIONS_MIGRATION_KEY,
Name: model.AdvancedPermissionsMigrationKey,
Value: "true",
}
@@ -87,7 +87,7 @@ func (s *Server) doAdvancedPermissionsMigration() {
func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error {
if !isComplete {
if _, err := a.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil {
if _, err := a.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil {
return err
}
}
@@ -111,19 +111,19 @@ func (s *Server) doEmojisPermissionsMigration() {
mlog.Info("Migrating emojis config to database.")
switch *s.Config().ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation {
case model.RESTRICT_EMOJI_CREATION_ALL:
role, err = s.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID)
case model.RestrictEmojiCreationAll:
role, err = s.GetRoleByName(context.Background(), model.SystemUserRoleId)
if err != nil {
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
return
}
case model.RESTRICT_EMOJI_CREATION_ADMIN:
role, err = s.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID)
case model.RestrictEmojiCreationAdmin:
role, err = s.GetRoleByName(context.Background(), model.TeamAdminRoleId)
if err != nil {
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
return
}
case model.RESTRICT_EMOJI_CREATION_SYSTEM_ADMIN:
case model.RestrictEmojiCreationSystemAdmin:
role = nil
default:
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config. Invalid restrict emoji creation setting")
@@ -131,23 +131,23 @@ func (s *Server) doEmojisPermissionsMigration() {
}
if role != nil {
role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id, model.PERMISSION_DELETE_EMOJIS.Id)
role.Permissions = append(role.Permissions, model.PermissionCreateEmojis.Id, model.PermissionDeleteEmojis.Id)
if _, nErr := s.Store.Role().Save(role); nErr != nil {
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(nErr))
return
}
}
systemAdminRole, err = s.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
systemAdminRole, err = s.GetRoleByName(context.Background(), model.SystemAdminRoleId)
if err != nil {
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
return
}
systemAdminRole.Permissions = append(systemAdminRole.Permissions,
model.PERMISSION_CREATE_EMOJIS.Id,
model.PERMISSION_DELETE_EMOJIS.Id,
model.PERMISSION_DELETE_OTHERS_EMOJIS.Id,
model.PermissionCreateEmojis.Id,
model.PermissionDeleteEmojis.Id,
model.PermissionDeleteOthersEmojis.Id,
)
if _, err := s.Store.Role().Save(systemAdminRole); err != nil {
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
@@ -177,20 +177,20 @@ func (s *Server) doGuestRolesCreationMigration() {
roles := model.MakeDefaultRoles()
allSucceeded := true
if _, err := s.Store.Role().GetByName(context.Background(), model.CHANNEL_GUEST_ROLE_ID); err != nil {
if _, err := s.Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil {
if _, err := s.Store.Role().GetByName(context.Background(), model.ChannelGuestRoleId); err != nil {
if _, err := s.Store.Role().Save(roles[model.ChannelGuestRoleId]); err != nil {
mlog.Critical("Failed to create new guest role to database.", mlog.Err(err))
allSucceeded = false
}
}
if _, err := s.Store.Role().GetByName(context.Background(), model.TEAM_GUEST_ROLE_ID); err != nil {
if _, err := s.Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil {
if _, err := s.Store.Role().GetByName(context.Background(), model.TeamGuestRoleId); err != nil {
if _, err := s.Store.Role().Save(roles[model.TeamGuestRoleId]); err != nil {
mlog.Critical("Failed to create new guest role to database.", mlog.Err(err))
allSucceeded = false
}
}
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_GUEST_ROLE_ID); err != nil {
if _, err := s.Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil {
if _, err := s.Store.Role().GetByName(context.Background(), model.SystemGuestRoleId); err != nil {
if _, err := s.Store.Role().Save(roles[model.SystemGuestRoleId]); err != nil {
mlog.Critical("Failed to create new guest role to database.", mlog.Err(err))
allSucceeded = false
}
@@ -203,12 +203,12 @@ func (s *Server) doGuestRolesCreationMigration() {
}
for _, scheme := range schemes {
if scheme.DefaultTeamGuestRole == "" || scheme.DefaultChannelGuestRole == "" {
if scheme.Scope == model.SCHEME_SCOPE_TEAM {
if scheme.Scope == model.SchemeScopeTeam {
// Team Guest Role
teamGuestRole := &model.Role{
Name: model.NewId(),
DisplayName: fmt.Sprintf("Team Guest Role for Scheme %s", scheme.Name),
Permissions: roles[model.TEAM_GUEST_ROLE_ID].Permissions,
Permissions: roles[model.TeamGuestRoleId].Permissions,
SchemeManaged: true,
}
@@ -224,7 +224,7 @@ func (s *Server) doGuestRolesCreationMigration() {
channelGuestRole := &model.Role{
Name: model.NewId(),
DisplayName: fmt.Sprintf("Channel Guest Role for Scheme %s", scheme.Name),
Permissions: roles[model.CHANNEL_GUEST_ROLE_ID].Permissions,
Permissions: roles[model.ChannelGuestRoleId].Permissions,
SchemeManaged: true,
}
@@ -270,21 +270,21 @@ func (s *Server) doSystemConsoleRolesCreationMigration() {
roles := model.MakeDefaultRoles()
allSucceeded := true
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_MANAGER_ROLE_ID); err != nil {
if _, err := s.Store.Role().Save(roles[model.SYSTEM_MANAGER_ROLE_ID]); err != nil {
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_MANAGER_ROLE_ID))
if _, err := s.Store.Role().GetByName(context.Background(), model.SystemManagerRoleId); err != nil {
if _, err := s.Store.Role().Save(roles[model.SystemManagerRoleId]); err != nil {
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemManagerRoleId))
allSucceeded = false
}
}
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID); err != nil {
if _, err := s.Store.Role().Save(roles[model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID]); err != nil {
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID))
if _, err := s.Store.Role().GetByName(context.Background(), model.SystemReadOnlyAdminRoleId); err != nil {
if _, err := s.Store.Role().Save(roles[model.SystemReadOnlyAdminRoleId]); err != nil {
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemReadOnlyAdminRoleId))
allSucceeded = false
}
}
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_USER_MANAGER_ROLE_ID); err != nil {
if _, err := s.Store.Role().Save(roles[model.SYSTEM_USER_MANAGER_ROLE_ID]); err != nil {
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_USER_MANAGER_ROLE_ID))
if _, err := s.Store.Role().GetByName(context.Background(), model.SystemUserManagerRoleId); err != nil {
if _, err := s.Store.Role().Save(roles[model.SystemUserManagerRoleId]); err != nil {
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemUserManagerRoleId))
allSucceeded = false
}
}

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

@@ -85,7 +85,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
allActivityPushUserIds := []string{}
var allowChannelMentions bool
var keywords map[string][]string
if channel.Type == model.CHANNEL_DIRECT {
if channel.Type == model.ChannelTypeDirect {
otherUserId := channel.GetOtherUserIdForDM(post.UserId)
_, ok := profileMap[otherUserId]
@@ -103,8 +103,8 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
mentions = getExplicitMentions(post, keywords, groups)
// Add an implicit mention when a user is added to a channel
// even if the user has set 'username mentions' to false in account settings.
if post.Type == model.POST_ADD_TO_CHANNEL {
addedUserId, ok := post.GetProp(model.POST_PROPS_ADDED_USER_ID).(string)
if post.Type == model.PostTypeAddToChannel {
addedUserId, ok := post.GetProp(model.PostPropsAddedUserId).(string)
if ok {
mentions.addMention(addedUserId, KeywordMention)
}
@@ -133,7 +133,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
if threadPost.Id == parentPostList.Order[0] && threadPost.IsFromOAuthBot() {
continue
}
if profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ANY || (profile.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ROOT && threadPost.Id == parentPostList.Order[0]) {
if profile.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyAny || (profile.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyRoot && threadPost.Id == parentPostList.Order[0]) {
mentionType := ThreadMention
if threadPost.Id == parentPostList.Order[0] {
mentionType = CommentMention
@@ -158,8 +158,8 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
// find which users in the channel are set up to always receive mobile notifications
for _, profile := range profileMap {
if (profile.NotifyProps[model.PUSH_NOTIFY_PROP] == model.USER_NOTIFY_ALL ||
channelMemberNotifyPropsMap[profile.Id][model.PUSH_NOTIFY_PROP] == model.CHANNEL_NOTIFY_ALL) &&
if (profile.NotifyProps[model.PushNotifyProp] == model.UserNotifyAll ||
channelMemberNotifyPropsMap[profile.Id][model.PushNotifyProp] == model.ChannelNotifyAll) &&
(post.UserId != profile.Id || post.GetProp("from_webhook") == "true") &&
!post.IsSystemMessage() {
allActivityPushUserIds = append(allActivityPushUserIds, profile.Id)
@@ -175,7 +175,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
var rootMentions *ExplicitMentions
if parentPostList != nil {
threadParticipants[parentPostList.Posts[parentPostList.Order[0]].UserId] = true
if channel.Type != model.CHANNEL_DIRECT {
if channel.Type != model.ChannelTypeDirect {
rootPost := parentPostList.Posts[parentPostList.Order[0]]
rootMentions = getExplicitMentions(rootPost, keywords, groups)
for id := range rootMentions.Mentions {
@@ -358,7 +358,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
var status *model.Status
var err *model.AppError
if status, err = a.GetStatus(id); err != nil {
status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
status = &model.Status{UserId: id, Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
}
if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], true, status, post) {
@@ -366,9 +366,9 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
replyToThreadType := ""
if mentionType == ThreadMention {
replyToThreadType = model.COMMENTS_NOTIFY_ANY
replyToThreadType = model.CommentsNotifyAny
} else if mentionType == CommentMention {
replyToThreadType = model.COMMENTS_NOTIFY_ROOT
replyToThreadType = model.CommentsNotifyRoot
}
a.sendPushNotification(
@@ -382,10 +382,10 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
// register that a notification was not sent
a.NotificationsLog().Debug("Notification not sent",
mlog.String("ackId", ""),
mlog.String("type", model.PUSH_TYPE_MESSAGE),
mlog.String("type", model.PushTypeMessage),
mlog.String("userId", id),
mlog.String("postId", post.Id),
mlog.String("status", model.PUSH_NOT_SENT),
mlog.String("status", model.PushNotSent),
)
}
}
@@ -399,7 +399,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
var status *model.Status
var err *model.AppError
if status, err = a.GetStatus(id); err != nil {
status = &model.Status{UserId: id, Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
status = &model.Status{UserId: id, Status: model.StatusOffline, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
}
if ShouldSendPushNotification(profileMap[id], channelMemberNotifyPropsMap[id], false, status, post) {
@@ -414,25 +414,25 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
// register that a notification was not sent
a.NotificationsLog().Debug("Notification not sent",
mlog.String("ackId", ""),
mlog.String("type", model.PUSH_TYPE_MESSAGE),
mlog.String("type", model.PushTypeMessage),
mlog.String("userId", id),
mlog.String("postId", post.Id),
mlog.String("status", model.PUSH_NOT_SENT),
mlog.String("status", model.PushNotSent),
)
}
}
}
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, "", post.ChannelId, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventPosted, "", post.ChannelId, "", nil)
// Note that PreparePostForClient should've already been called by this point
message.Add("post", post.ToJson())
message.Add("channel_type", channel.Type)
message.Add("channel_display_name", notification.GetChannelName(model.SHOW_USERNAME, ""))
message.Add("channel_display_name", notification.GetChannelName(model.ShowUsername, ""))
message.Add("channel_name", channel.Name)
message.Add("sender_name", notification.GetSenderName(model.SHOW_USERNAME, *a.Config().ServiceSettings.EnablePostUsernameOverride))
message.Add("sender_name", notification.GetSenderName(model.ShowUsername, *a.Config().ServiceSettings.EnablePostUsernameOverride))
message.Add("team_id", team.Id)
message.Add("set_online", setOnline)
@@ -461,19 +461,19 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
a.Publish(message)
// If this is a reply in a thread, notify participants
if a.Config().FeatureFlags.CollapsedThreads && *a.Config().ServiceSettings.CollapsedThreads != model.COLLAPSED_THREADS_DISABLED && post.RootId != "" {
if a.Config().FeatureFlags.CollapsedThreads && *a.Config().ServiceSettings.CollapsedThreads != model.CollapsedThreadsDisabled && post.RootId != "" {
followers, err := a.Srv().Store.Thread().GetThreadFollowers(post.RootId)
if err != nil {
return nil, errors.Wrapf(err, "cannot get thread %q followers", post.RootId)
}
for _, uid := range followers {
sendEvent := *a.Config().ServiceSettings.CollapsedThreads == model.COLLAPSED_THREADS_DEFAULT_ON
sendEvent := *a.Config().ServiceSettings.CollapsedThreads == model.CollapsedThreadsDefaultOn
// check if a participant has overridden collapsed threads settings
if preference, err := a.Srv().Store.Preference().Get(uid, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSED_THREADS_ENABLED); err == nil {
if preference, err := a.Srv().Store.Preference().Get(uid, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled); err == nil {
sendEvent = preference.Value == "on"
}
if sendEvent {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_THREAD_UPDATED, team.Id, "", uid, nil)
message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, team.Id, "", uid, nil)
threadMembership, err := a.Srv().Store.Thread().GetMembershipForUser(uid, post.RootId)
if err != nil {
return nil, errors.Wrapf(err, "cannot get thread membership %q for user %q", post.RootId, uid)
@@ -496,16 +496,16 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod
}
func (a *App) userAllowsEmail(user *model.User, channelMemberNotificationProps model.StringMap, post *model.Post) bool {
userAllowsEmails := user.NotifyProps[model.EMAIL_NOTIFY_PROP] != "false"
if channelEmail, ok := channelMemberNotificationProps[model.EMAIL_NOTIFY_PROP]; ok {
if channelEmail != model.CHANNEL_NOTIFY_DEFAULT {
userAllowsEmails := user.NotifyProps[model.EmailNotifyProp] != "false"
if channelEmail, ok := channelMemberNotificationProps[model.EmailNotifyProp]; ok {
if channelEmail != model.ChannelNotifyDefault {
userAllowsEmails = channelEmail != "false"
}
}
// Remove the user as recipient when the user has muted the channel.
if channelMuted, ok := channelMemberNotificationProps[model.MARK_UNREAD_NOTIFY_PROP]; ok {
if channelMuted == model.CHANNEL_MARK_UNREAD_MENTION {
if channelMuted, ok := channelMemberNotificationProps[model.MarkUnreadNotifyProp]; ok {
if channelMuted == model.ChannelMarkUnreadMention {
mlog.Debug("Channel muted for user", mlog.String("user_id", user.Id), mlog.String("channel_mute", channelMuted))
userAllowsEmails = false
}
@@ -516,15 +516,15 @@ func (a *App) userAllowsEmail(user *model.User, channelMemberNotificationProps m
if status, err = a.GetStatus(user.Id); err != nil {
status = &model.Status{
UserId: user.Id,
Status: model.STATUS_OFFLINE,
Status: model.StatusOffline,
Manual: false,
LastActivityAt: 0,
ActiveChannel: "",
}
}
autoResponderRelated := status.Status == model.STATUS_OUT_OF_OFFICE || post.Type == model.POST_AUTO_RESPONDER
emailNotificationsAllowedForStatus := status.Status != model.STATUS_ONLINE && status.Status != model.STATUS_DND
autoResponderRelated := status.Status == model.StatusOutOfOffice || post.Type == model.PostTypeAutoResponder
emailNotificationsAllowedForStatus := status.Status != model.StatusOnline && status.Status != model.StatusDnd
return userAllowsEmails && emailNotificationsAllowedForStatus && user.DeleteAt == 0 && !autoResponderRelated
}
@@ -577,7 +577,7 @@ func (a *App) filterOutOfChannelMentions(sender *model.User, post *model.Post, c
return nil, nil, nil
}
if channel.TeamId == "" || channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP {
if channel.TeamId == "" || channel.Type == model.ChannelTypeDirect || channel.Type == model.ChannelTypeGroup {
return nil, nil, nil
}
@@ -669,7 +669,7 @@ func makeOutOfChannelMentionPost(sender *model.User, post *model.Post, outOfChan
}
props := model.StringInterface{
model.PROPS_ADD_CHANNEL_MEMBER: model.StringInterface{
model.PropsAddChannelMember: model.StringInterface{
"post_id": ephemeralPostId,
"usernames": allUsers.Usernames(), // Kept for backwards compatibility of mobile app.
@@ -844,11 +844,11 @@ func getMentionsEnabledFields(post *model.Post) model.StringArray {
// allowChannelMentions returns whether or not the channel mentions are allowed for the given post.
func (a *App) allowChannelMentions(post *model.Post, numProfiles int) bool {
if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_CHANNEL_MENTIONS) {
if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseChannelMentions) {
return false
}
if post.Type == model.POST_HEADER_CHANGE || post.Type == model.POST_PURPOSE_CHANGE {
if post.Type == model.PostTypeHeaderChange || post.Type == model.PostTypePurposeChange {
return false
}
@@ -865,11 +865,11 @@ func (a *App) allowGroupMentions(post *model.Post) bool {
return false
}
if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) {
if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseGroupMentions) {
return false
}
if post.Type == model.POST_HEADER_CHANGE || post.Type == model.POST_PURPOSE_CHANGE {
if post.Type == model.PostTypeHeaderChange || post.Type == model.PostTypePurposeChange {
return false
}
@@ -990,20 +990,20 @@ func addMentionKeywordsForUser(keywords map[string][]string, profile *model.User
}
// If turned on, add the user's case sensitive first name
if profile.NotifyProps[model.FIRST_NAME_NOTIFY_PROP] == "true" && profile.FirstName != "" {
if profile.NotifyProps[model.FirstNameNotifyProp] == "true" && profile.FirstName != "" {
keywords[profile.FirstName] = append(keywords[profile.FirstName], profile.Id)
}
// Add @channel and @all to keywords if user has them turned on and the server allows them
if allowChannelMentions {
// Ignore channel mentions if channel is muted and channel mention setting is default
ignoreChannelMentions := channelNotifyProps[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP] == model.IGNORE_CHANNEL_MENTIONS_ON || (channelNotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.USER_NOTIFY_MENTION && channelNotifyProps[model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP] == model.IGNORE_CHANNEL_MENTIONS_DEFAULT)
ignoreChannelMentions := channelNotifyProps[model.IgnoreChannelMentionsNotifyProp] == model.IgnoreChannelMentionsOn || (channelNotifyProps[model.MarkUnreadNotifyProp] == model.UserNotifyMention && channelNotifyProps[model.IgnoreChannelMentionsNotifyProp] == model.IgnoreChannelMentionsDefault)
if profile.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] == "true" && !ignoreChannelMentions {
if profile.NotifyProps[model.ChannelMentionsNotifyProp] == "true" && !ignoreChannelMentions {
keywords["@channel"] = append(keywords["@channel"], profile.Id)
keywords["@all"] = append(keywords["@all"], profile.Id)
if status != nil && status.Status == model.STATUS_ONLINE {
if status != nil && status.Status == model.StatusOnline {
keywords["@here"] = append(keywords["@here"], profile.Id)
}
}
@@ -1025,9 +1025,9 @@ type PostNotification struct {
// channel, with an option to exclude the recipient of the message from that list.
func (n *PostNotification) GetChannelName(userNameFormat, excludeId string) string {
switch n.Channel.Type {
case model.CHANNEL_DIRECT:
case model.ChannelTypeDirect:
return n.Sender.GetDisplayNameWithPrefix(userNameFormat, "@")
case model.CHANNEL_GROUP:
case model.ChannelTypeGroup:
names := []string{}
for _, user := range n.ProfileMap {
if user.Id != excludeId {
@@ -1050,7 +1050,7 @@ func (n *PostNotification) GetSenderName(userNameFormat string, overridesAllowed
return i18n.T("system.message.name")
}
if overridesAllowed && n.Channel.Type != model.CHANNEL_DIRECT {
if overridesAllowed && n.Channel.Type != model.ChannelTypeDirect {
if value, ok := n.Post.GetProps()["override_username"]; ok && n.Post.GetProp("from_webhook") == "true" {
return value.(string)
}
@@ -1182,10 +1182,10 @@ func (m *ExplicitMentions) processText(text string, keywords map[string][]string
func (a *App) GetNotificationNameFormat(user *model.User) string {
if !*a.Config().PrivacySettings.ShowFullName {
return model.SHOW_USERNAME
return model.ShowUsername
}
data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_NAME_FORMAT)
data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameNameFormat)
if err != nil {
return *a.Config().TeamSettings.TeammateNameDisplay
}

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

@@ -48,12 +48,12 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model.
if *a.Config().EmailSettings.EnableEmailBatching {
var sendBatched bool
if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_NOTIFICATIONS, model.PREFERENCE_NAME_EMAIL_INTERVAL); err != nil {
if data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval); err != nil {
// if the call fails, assume that the interval has not been explicitly set and batch the notifications
sendBatched = true
} else {
// if the user has chosen to receive notifications immediately, don't batch them
sendBatched = data.Value != model.PREFERENCE_EMAIL_INTERVAL_NO_BATCHING_SECONDS
sendBatched = data.Value != model.PreferenceEmailIntervalNoBatchingSeconds
}
if sendBatched {
@@ -68,7 +68,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model.
translateFunc := i18n.GetUserTranslations(user.Locale)
var useMilitaryTime bool
if data, err := a.Srv().Store.Preference().Get(user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME); err != nil {
if data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime); err != nil {
useMilitaryTime = true
} else {
useMilitaryTime = data.Value == "true"
@@ -79,15 +79,15 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model.
channelName := notification.GetChannelName(nameFormat, "")
senderName := notification.GetSenderName(nameFormat, *a.Config().ServiceSettings.EnablePostUsernameOverride)
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
if license := a.Srv().License(); license != nil && *license.Features.EmailNotificationContents {
emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType
}
var subjectText string
if channel.Type == model.CHANNEL_DIRECT {
if channel.Type == model.ChannelTypeDirect {
subjectText = getDirectMessageNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, senderName, useMilitaryTime)
} else if channel.Type == model.CHANNEL_GROUP {
} else if channel.Type == model.ChannelTypeGroup {
subjectText = getGroupMessageNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, channelName, emailNotificationContentsType, useMilitaryTime)
} else if *a.Config().EmailSettings.UseChannelInEmailNotifications {
subjectText = getNotificationEmailSubject(user, post, translateFunc, *a.Config().TeamSettings.SiteName, team.DisplayName+" ("+channelName+")", useMilitaryTime)
@@ -97,7 +97,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model.
senderPhoto := ""
embeddedFiles := make(map[string]io.Reader)
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL && senderProfileImage != nil {
if emailNotificationContentsType == model.EmailNotificationContentsFull && senderProfileImage != nil {
senderPhoto = "user-avatar.png"
embeddedFiles = map[string]io.Reader{
senderPhoto: bytes.NewReader(senderProfileImage),
@@ -165,7 +165,7 @@ func getGroupMessageNotificationEmailSubject(user *model.User, post *model.Post,
"Day": t.Day,
"Year": t.Year,
}
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
if emailNotificationContentsType == model.EmailNotificationContentsFull {
subjectParameters["ChannelName"] = channelName
return translateFunc("app.notification.subject.group_message.full", subjectParameters)
}
@@ -198,7 +198,7 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post,
"TimeZone": t.TimeZone,
}
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
if emailNotificationContentsType == model.EmailNotificationContentsFull {
postMessage := a.GetMessageForNotification(post, translateFunc)
postMessage = html.EscapeString(postMessage)
normalizedPostMessage, err := a.generateHyperlinkForChannels(postMessage, teamName, landingURL)
@@ -224,11 +224,11 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post,
data.Props["NotificationFooterInfoLogin"] = translateFunc("app.notification.footer.infoLogin")
data.Props["NotificationFooterInfo"] = translateFunc("app.notification.footer.info")
if channel.Type == model.CHANNEL_DIRECT {
if channel.Type == model.ChannelTypeDirect {
// Direct Messages
data.Props["Title"] = translateFunc("app.notification.body.dm.title", map[string]interface{}{"SenderName": senderName})
data.Props["SubTitle"] = translateFunc("app.notification.body.dm.subTitle", map[string]interface{}{"SenderName": senderName})
} else if channel.Type == model.CHANNEL_GROUP {
} else if channel.Type == model.ChannelTypeGroup {
// Group Messages
data.Props["Title"] = translateFunc("app.notification.body.group.title", map[string]interface{}{"SenderName": senderName})
data.Props["SubTitle"] = translateFunc("app.notification.body.group.subTitle", map[string]interface{}{"SenderName": senderName})
@@ -240,7 +240,7 @@ func (a *App) getNotificationEmailBody(recipient *model.User, post *model.Post,
}
// only include posts in notification email if email notification contents type is set to full
if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL {
if emailNotificationContentsType == model.EmailNotificationContentsFull {
data.Props["Posts"] = []postData{pData}
} else {
data.Props["Posts"] = []postData{}
@@ -309,7 +309,7 @@ func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string
visited := make(map[string]bool)
for _, ch := range channels {
if !visited[ch.Id] && ch.Type == model.CHANNEL_OPEN {
if !visited[ch.Id] && ch.Type == model.ChannelTypeOpen {
channelURL := teamURL + "/channels/" + ch.Name
channelHyperLink := fmt.Sprintf("<a href='%s'>%s</a>", channelURL, "~"+ch.Name)
postMessage = strings.Replace(postMessage, "~"+ch.Name, channelHyperLink, -1)

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

@@ -38,7 +38,7 @@ func TestGetGroupMessageNotificationEmailSubjectFull(t *testing.T) {
CreateAt: 1501804801000,
}
translateFunc := i18n.GetUserTranslations("en")
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
subject := getGroupMessageNotificationEmailSubject(user, post, translateFunc, "http://localhost:8065", "sender", emailNotificationContentsType, true)
require.Regexp(t, regexp.MustCompile("^"+regexp.QuoteMeta(expectedPrefix)), subject, fmt.Sprintf("Expected subject line prefix '%s', got %s", expectedPrefix, subject))
}
@@ -50,7 +50,7 @@ func TestGetGroupMessageNotificationEmailSubjectGeneric(t *testing.T) {
CreateAt: 1501804801000,
}
translateFunc := i18n.GetUserTranslations("en")
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC
emailNotificationContentsType := model.EmailNotificationContentsGeneric
subject := getGroupMessageNotificationEmailSubject(user, post, translateFunc, "http://localhost:8065", "sender", emailNotificationContentsType, true)
require.Regexp(t, regexp.MustCompile("^"+regexp.QuoteMeta(expectedPrefix)), subject, fmt.Sprintf("Expected subject line prefix '%s', got %s", expectedPrefix, subject))
}
@@ -76,13 +76,13 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) {
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -107,13 +107,13 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) {
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_GROUP,
Type: model.ChannelTypeGroup,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -138,13 +138,13 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) {
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_PRIVATE,
Type: model.ChannelTypePrivate,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -169,13 +169,13 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) {
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_DIRECT,
Type: model.ChannelTypeDirect,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -204,13 +204,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeWithTimezone(t *testi
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_DIRECT,
Type: model.ChannelTypeDirect,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -238,13 +238,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeNoTimezone(t *testing
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_DIRECT,
Type: model.ChannelTypeDirect,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -287,13 +287,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime12Hour(t *testing.T)
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_DIRECT,
Type: model.ChannelTypeDirect,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -320,13 +320,13 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime24Hour(t *testing.T)
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_DIRECT,
Type: model.ChannelTypeDirect,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -350,13 +350,13 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T)
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC
emailNotificationContentsType := model.EmailNotificationContentsGeneric
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -380,13 +380,13 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) {
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_GROUP,
Type: model.ChannelTypeGroup,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC
emailNotificationContentsType := model.EmailNotificationContentsGeneric
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -410,13 +410,13 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T)
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_PRIVATE,
Type: model.ChannelTypePrivate,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC
emailNotificationContentsType := model.EmailNotificationContentsGeneric
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -440,13 +440,13 @@ func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T)
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_DIRECT,
Type: model.ChannelTypeDirect,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC
emailNotificationContentsType := model.EmailNotificationContentsGeneric
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -466,7 +466,7 @@ func TestGetNotificationEmailEscapingChars(t *testing.T) {
ch := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
channelName := "ChannelName"
recipient := &model.User{}
@@ -478,7 +478,7 @@ func TestGetNotificationEmailEscapingChars(t *testing.T) {
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -501,7 +501,7 @@ func TestGetNotificationEmailBodyPublicChannelMention(t *testing.T) {
ch := &model.Channel{
Name: "channelname",
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
id := model.NewId()
recipient := &model.User{
@@ -518,7 +518,7 @@ func TestGetNotificationEmailBodyPublicChannelMention(t *testing.T) {
senderName := "user1"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -547,7 +547,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) {
Id: model.NewId(),
Name: "channelnameone",
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
mention := "~" + ch.Name
@@ -555,7 +555,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) {
Id: model.NewId(),
Name: "channelnametwo",
DisplayName: "ChannelName2",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
mention2 := "~" + ch2.Name
@@ -563,7 +563,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) {
Id: model.NewId(),
Name: "channelnamethree",
DisplayName: "ChannelName3",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
mention3 := "~" + ch3.Name
@@ -584,7 +584,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) {
senderName := "user1"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -616,7 +616,7 @@ func TestGetNotificationEmailBodyPrivateChannelMention(t *testing.T) {
ch := &model.Channel{
Name: "channelname",
DisplayName: "ChannelName",
Type: model.CHANNEL_PRIVATE,
Type: model.ChannelTypePrivate,
}
id := model.NewId()
recipient := &model.User{
@@ -633,7 +633,7 @@ func TestGetNotificationEmailBodyPrivateChannelMention(t *testing.T) {
senderName := "user1"
teamName := "testteam"
teamURL := "http://localhost:8065/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -661,7 +661,7 @@ func TestGenerateHyperlinkForChannelsPublic(t *testing.T) {
ch := &model.Channel{
Name: "channelname",
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
message := "This is the message "
mention := "~" + ch.Name
@@ -693,7 +693,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) {
Id: model.NewId(),
Name: "channelnameone",
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
mention := "~" + ch.Name
@@ -701,7 +701,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) {
Id: model.NewId(),
Name: "channelnametwo",
DisplayName: "ChannelName2",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
mention2 := "~" + ch2.Name
@@ -709,7 +709,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) {
Id: model.NewId(),
Name: "channelnamethree",
DisplayName: "ChannelName3",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
mention3 := "~" + ch3.Name
@@ -746,7 +746,7 @@ func TestGenerateHyperlinkForChannelsPrivate(t *testing.T) {
ch := &model.Channel{
Name: "channelname",
DisplayName: "ChannelName",
Type: model.CHANNEL_PRIVATE,
Type: model.ChannelTypePrivate,
}
message := "This is the message ~" + ch.Name
@@ -777,13 +777,13 @@ func TestLandingLink(t *testing.T) {
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/landing#/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)
@@ -807,13 +807,13 @@ func TestLandingLinkPermalink(t *testing.T) {
}
channel := &model.Channel{
DisplayName: "ChannelName",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
}
channelName := "ChannelName"
senderName := "sender"
teamName := "testteam"
teamURL := "http://localhost:8065/landing#/testteam"
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
emailNotificationContentsType := model.EmailNotificationContentsFull
translateFunc := i18n.GetUserTranslations("en")
storeMock := th.App.Srv().Store.(*mocks.Store)

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

@@ -122,7 +122,7 @@ func (a *App) sendPushNotificationToAllSessions(msg *model.PushNotification, use
mlog.String("postId", tmpMessage.PostId),
mlog.String("channelId", tmpMessage.ChannelId),
mlog.String("deviceId", tmpMessage.DeviceId),
mlog.String("status", model.PUSH_SEND_SUCCESS),
mlog.String("status", model.PushSendSuccess),
)
if a.Metrics() != nil {
@@ -165,20 +165,20 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp
// If the post only has images then push an appropriate message
if postMessage == "" && hasFiles {
if channelType == model.CHANNEL_DIRECT {
if channelType == model.ChannelTypeDirect {
return strings.Trim(userLocale("api.post.send_notifications_and_forget.push_image_only"), " ")
}
return senderName + userLocale("api.post.send_notifications_and_forget.push_image_only")
}
if contentsConfig == model.FULL_NOTIFICATION {
if channelType == model.CHANNEL_DIRECT {
if contentsConfig == model.FullNotification {
if channelType == model.ChannelTypeDirect {
return model.ClearMentionTags(postMessage)
}
return senderName + ": " + model.ClearMentionTags(postMessage)
}
if channelType == model.CHANNEL_DIRECT {
if channelType == model.ChannelTypeDirect {
return userLocale("api.post.send_notifications_and_forget.push_message")
}
@@ -190,11 +190,11 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp
return senderName + userLocale("api.post.send_notifications_and_forget.push_explicit_mention")
}
if replyToThreadType == model.COMMENTS_NOTIFY_ROOT {
if replyToThreadType == model.CommentsNotifyRoot {
return senderName + userLocale("api.post.send_notification_and_forget.push_comment_on_post")
}
if replyToThreadType == model.COMMENTS_NOTIFY_ANY {
if replyToThreadType == model.CommentsNotifyAny {
return senderName + userLocale("api.post.send_notification_and_forget.push_comment_on_thread")
}
@@ -203,8 +203,8 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp
func (a *App) clearPushNotificationSync(currentSessionId, userID, channelID string) *model.AppError {
msg := &model.PushNotification{
Type: model.PUSH_TYPE_CLEAR,
Version: model.PUSH_MESSAGE_V2,
Type: model.PushTypeClear,
Version: model.PushMessageV2,
ChannelId: channelID,
ContentAvailable: 1,
}
@@ -234,8 +234,8 @@ func (a *App) clearPushNotification(currentSessionId, userID, channelID string)
func (a *App) updateMobileAppBadgeSync(userID string) *model.AppError {
msg := &model.PushNotification{
Type: model.PUSH_TYPE_UPDATE_BADGE,
Version: model.PUSH_MESSAGE_V2,
Type: model.PushTypeUpdateBadge,
Version: model.PushMessageV2,
Sound: "none",
ContentAvailable: 1,
}
@@ -360,10 +360,10 @@ func (a *App) sendToPushProxy(msg *model.PushNotification, session *model.Sessio
mlog.String("type", msg.Type),
mlog.String("userId", session.UserId),
mlog.String("postId", msg.PostId),
mlog.String("status", model.PUSH_SEND_PREPARE),
mlog.String("status", model.PushSendPrepare),
)
url := strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/") + model.API_URL_SUFFIX_V1 + "/send_push"
url := strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/") + model.ApiUrlSuffixV1 + "/send_push"
request, err := http.NewRequest("POST", url, strings.NewReader(msg.ToJson()))
if err != nil {
return err
@@ -377,13 +377,13 @@ func (a *App) sendToPushProxy(msg *model.PushNotification, session *model.Sessio
pushResponse := model.PushResponseFromJson(resp.Body)
switch pushResponse[model.PUSH_STATUS] {
case model.PUSH_STATUS_REMOVE:
switch pushResponse[model.PushStatus] {
case model.PushStatusRemove:
a.AttachDeviceId(session.Id, "", session.ExpiresAt)
a.ClearSessionCacheForUser(session.UserId)
return errors.New("Device was reported as removed")
case model.PUSH_STATUS_FAIL:
return errors.New(pushResponse[model.PUSH_STATUS_ERROR_MSG])
case model.PushStatusFail:
return errors.New(pushResponse[model.PushStatusErrorMsg])
}
return nil
}
@@ -398,12 +398,12 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error {
mlog.String("type", ack.NotificationType),
mlog.String("deviceType", ack.ClientPlatform),
mlog.Int64("receivedAt", ack.ClientReceivedAt),
mlog.String("status", model.PUSH_RECEIVED),
mlog.String("status", model.PushReceived),
)
request, err := http.NewRequest(
"POST",
strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/")+model.API_URL_SUFFIX_V1+"/ack",
strings.TrimRight(*a.Config().EmailSettings.PushNotificationServer, "/")+model.ApiUrlSuffixV1+"/ack",
strings.NewReader(ack.ToJson()),
)
@@ -441,14 +441,14 @@ func ShouldSendPushNotification(user *model.User, channelNotifyProps model.Strin
func DoesNotifyPropsAllowPushNotification(user *model.User, channelNotifyProps model.StringMap, post *model.Post, wasMentioned bool) bool {
userNotifyProps := user.NotifyProps
userNotify := userNotifyProps[model.PUSH_NOTIFY_PROP]
channelNotify, ok := channelNotifyProps[model.PUSH_NOTIFY_PROP]
userNotify := userNotifyProps[model.PushNotifyProp]
channelNotify, ok := channelNotifyProps[model.PushNotifyProp]
if !ok || channelNotify == "" {
channelNotify = model.CHANNEL_NOTIFY_DEFAULT
channelNotify = model.ChannelNotifyDefault
}
// If the channel is muted do not send push notifications
if channelNotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_MARK_UNREAD_MENTION {
if channelNotifyProps[model.MarkUnreadNotifyProp] == model.ChannelMarkUnreadMention {
return false
}
@@ -456,25 +456,25 @@ func DoesNotifyPropsAllowPushNotification(user *model.User, channelNotifyProps m
return false
}
if channelNotify == model.USER_NOTIFY_NONE {
if channelNotify == model.UserNotifyNone {
return false
}
if channelNotify == model.CHANNEL_NOTIFY_MENTION && !wasMentioned {
if channelNotify == model.ChannelNotifyMention && !wasMentioned {
return false
}
if userNotify == model.USER_NOTIFY_MENTION && channelNotify == model.CHANNEL_NOTIFY_DEFAULT && !wasMentioned {
if userNotify == model.UserNotifyMention && channelNotify == model.ChannelNotifyDefault && !wasMentioned {
return false
}
if (userNotify == model.USER_NOTIFY_ALL || channelNotify == model.CHANNEL_NOTIFY_ALL) &&
if (userNotify == model.UserNotifyAll || channelNotify == model.ChannelNotifyAll) &&
(post.UserId != user.Id || post.GetProp("from_webhook") == "true") {
return true
}
if userNotify == model.USER_NOTIFY_NONE &&
channelNotify == model.CHANNEL_NOTIFY_DEFAULT {
if userNotify == model.UserNotifyNone &&
channelNotify == model.ChannelNotifyDefault {
return false
}
@@ -483,20 +483,20 @@ func DoesNotifyPropsAllowPushNotification(user *model.User, channelNotifyProps m
func DoesStatusAllowPushNotification(userNotifyProps model.StringMap, status *model.Status, channelID string) bool {
// If User status is DND or OOO return false right away
if status.Status == model.STATUS_DND || status.Status == model.STATUS_OUT_OF_OFFICE {
if status.Status == model.StatusDnd || status.Status == model.StatusOutOfOffice {
return false
}
pushStatus, ok := userNotifyProps[model.PUSH_STATUS_NOTIFY_PROP]
if (pushStatus == model.STATUS_ONLINE || !ok) && (status.ActiveChannel != channelID || model.GetMillis()-status.LastActivityAt > model.STATUS_CHANNEL_TIMEOUT) {
pushStatus, ok := userNotifyProps[model.PushStatusNotifyProp]
if (pushStatus == model.StatusOnline || !ok) && (status.ActiveChannel != channelID || model.GetMillis()-status.LastActivityAt > model.StatusChannelTimeout) {
return true
}
if pushStatus == model.STATUS_AWAY && (status.Status == model.STATUS_AWAY || status.Status == model.STATUS_OFFLINE) {
if pushStatus == model.StatusAway && (status.Status == model.StatusAway || status.Status == model.StatusOffline) {
return true
}
if pushStatus == model.STATUS_OFFLINE && status.Status == model.STATUS_OFFLINE {
if pushStatus == model.StatusOffline && status.Status == model.StatusOffline {
return true
}
@@ -509,11 +509,11 @@ func (a *App) BuildPushNotificationMessage(contentsConfig string, post *model.Po
var msg *model.PushNotification
notificationInterface := a.Srv().Notification
if (notificationInterface == nil || notificationInterface.CheckLicense() != nil) && contentsConfig == model.ID_LOADED_NOTIFICATION {
contentsConfig = model.GENERIC_NOTIFICATION
if (notificationInterface == nil || notificationInterface.CheckLicense() != nil) && contentsConfig == model.IdLoadedNotification {
contentsConfig = model.GenericNotification
}
if contentsConfig == model.ID_LOADED_NOTIFICATION {
if contentsConfig == model.IdLoadedNotification {
msg = a.buildIdLoadedPushNotificationMessage(post, user)
} else {
msg = a.buildFullPushNotificationMessage(contentsConfig, post, user, channel, channelName, senderName, explicitMention, channelWideMention, replyToThreadType)
@@ -533,9 +533,9 @@ func (a *App) buildIdLoadedPushNotificationMessage(post *model.Post, user *model
msg := &model.PushNotification{
PostId: post.Id,
ChannelId: post.ChannelId,
Category: model.CATEGORY_CAN_REPLY,
Version: model.PUSH_MESSAGE_V2,
Type: model.PUSH_TYPE_MESSAGE,
Category: model.CategoryCanReply,
Version: model.PushMessageV2,
Type: model.PushTypeMessage,
IsIdLoaded: true,
SenderId: user.Id,
Message: userLocale("api.push_notification.id_loaded.default_message"),
@@ -548,9 +548,9 @@ func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *mode
explicitMention bool, channelWideMention bool, replyToThreadType string) *model.PushNotification {
msg := &model.PushNotification{
Category: model.CATEGORY_CAN_REPLY,
Version: model.PUSH_MESSAGE_V2,
Type: model.PUSH_TYPE_MESSAGE,
Category: model.CategoryCanReply,
Version: model.PushMessageV2,
Type: model.PushTypeMessage,
TeamId: channel.TeamId,
ChannelId: channel.Id,
PostId: post.Id,
@@ -560,7 +560,7 @@ func (a *App) buildFullPushNotificationMessage(contentsConfig string, post *mode
}
cfg := a.Config()
if contentsConfig != model.GENERIC_NO_CHANNEL_NOTIFICATION || channel.Type == model.CHANNEL_DIRECT {
if contentsConfig != model.GenericNoChannelNotification || channel.Type == model.ChannelTypeDirect {
msg.ChannelName = channelName
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

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

@@ -26,8 +26,8 @@ func TestSendNotifications(t *testing.T) {
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "@" + th.BasicUser2.Username,
Type: model.POST_ADD_TO_CHANNEL,
Props: map[string]interface{}{model.POST_PROPS_ADDED_USER_ID: "junk"},
Type: model.PostTypeAddToChannel,
Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"},
}, true)
require.Nil(t, appErr)
@@ -103,14 +103,14 @@ func TestSendNotifications(t *testing.T) {
require.False(t, utils.StringInSlice(user.Id, mentions))
}
th.BasicUser.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY
th.BasicUser.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny
th.BasicUser, appErr = th.App.UpdateUser(th.BasicUser, false)
require.Nil(t, appErr)
t.Run("user wants notifications on all comments", func(t *testing.T) {
testUserNotNotified(t, th.BasicUser)
})
th.BasicUser.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ROOT
th.BasicUser.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyRoot
th.BasicUser, appErr = th.App.UpdateUser(th.BasicUser, false)
require.Nil(t, appErr)
t.Run("user wants notifications on root comment", func(t *testing.T) {
@@ -135,8 +135,8 @@ func TestSendNotificationsWithManyUsers(t *testing.T) {
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "@channel",
Type: model.POST_ADD_TO_CHANNEL,
Props: map[string]interface{}{model.POST_PROPS_ADDED_USER_ID: "junk"},
Type: model.PostTypeAddToChannel,
Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"},
}, true)
require.Nil(t, appErr1)
@@ -155,8 +155,8 @@ func TestSendNotificationsWithManyUsers(t *testing.T) {
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "@channel",
Type: model.POST_ADD_TO_CHANNEL,
Props: map[string]interface{}{model.POST_PROPS_ADDED_USER_ID: "junk"},
Type: model.PostTypeAddToChannel,
Props: map[string]interface{}{model.PostPropsAddedUserId: "junk"},
}, true)
require.Nil(t, appErr1)
@@ -249,7 +249,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) {
t.Run("should not return results for a system message", func(t *testing.T) {
post := &model.Post{
Type: model.POST_ADD_REMOVE,
Type: model.PostTypeAddRemove,
}
potentialMentions := []string{user2.Username, user3.Username}
@@ -263,7 +263,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) {
t.Run("should not return results for a direct message", func(t *testing.T) {
post := &model.Post{}
directChannel := &model.Channel{
Type: model.CHANNEL_DIRECT,
Type: model.ChannelTypeDirect,
}
potentialMentions := []string{user2.Username, user3.Username}
@@ -277,7 +277,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) {
t.Run("should not return results for a group message", func(t *testing.T) {
post := &model.Post{}
groupChannel := &model.Channel{
Type: model.CHANNEL_GROUP,
Type: model.ChannelTypeGroup,
}
potentialMentions := []string{user2.Username, user3.Username}
@@ -1016,13 +1016,13 @@ func TestAllowChannelMentions(t *testing.T) {
})
t.Run("should return false for a channel header post", func(t *testing.T) {
headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_HEADER_CHANGE}
headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypeHeaderChange}
allowChannelMentions := th.App.allowChannelMentions(headerChangePost, 5)
assert.False(t, allowChannelMentions)
})
t.Run("should return false for a channel purpose post", func(t *testing.T) {
purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_PURPOSE_CHANGE}
purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypePurposeChange}
allowChannelMentions := th.App.allowChannelMentions(purposeChangePost, 5)
assert.False(t, allowChannelMentions)
})
@@ -1033,10 +1033,10 @@ func TestAllowChannelMentions(t *testing.T) {
})
t.Run("should return false for a post where the post user does not have USE_CHANNEL_MENTIONS permission", func(t *testing.T) {
defer th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
defer th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
defer th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId)
defer th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId)
th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId)
th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId)
allowChannelMentions := th.App.allowChannelMentions(post, 5)
assert.False(t, allowChannelMentions)
})
@@ -1061,24 +1061,24 @@ func TestAllowGroupMentions(t *testing.T) {
})
t.Run("should return false for a channel header post", func(t *testing.T) {
headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_HEADER_CHANGE}
headerChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypeHeaderChange}
allowGroupMentions := th.App.allowGroupMentions(headerChangePost)
assert.False(t, allowGroupMentions)
})
t.Run("should return false for a channel purpose post", func(t *testing.T) {
purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.POST_PURPOSE_CHANGE}
purposeChangePost := &model.Post{ChannelId: th.BasicChannel.Id, UserId: th.BasicUser.Id, Type: model.PostTypePurposeChange}
allowGroupMentions := th.App.allowGroupMentions(purposeChangePost)
assert.False(t, allowGroupMentions)
})
t.Run("should return false for a post where the post user does not have USE_GROUP_MENTIONS permission", func(t *testing.T) {
defer func() {
th.AddPermissionToRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
th.AddPermissionToRole(model.PermissionUseGroupMentions.Id, model.ChannelUserRoleId)
th.AddPermissionToRole(model.PermissionUseGroupMentions.Id, model.ChannelAdminRoleId)
}()
th.RemovePermissionFromRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
th.RemovePermissionFromRole(model.PERMISSION_USE_GROUP_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
th.RemovePermissionFromRole(model.PermissionUseGroupMentions.Id, model.ChannelUserRoleId)
th.RemovePermissionFromRole(model.PermissionUseGroupMentions.Id, model.ChannelAdminRoleId)
allowGroupMentions := th.App.allowGroupMentions(post)
assert.False(t, allowGroupMentions)
})
@@ -1100,7 +1100,7 @@ func TestGetMentionKeywords(t *testing.T) {
channelMemberNotifyPropsMap1Off := map[string]model.StringMap{
user1.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
}
@@ -1130,7 +1130,7 @@ func TestGetMentionKeywords(t *testing.T) {
channelMemberNotifyPropsMap2Off := map[string]model.StringMap{
user2.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
}
@@ -1155,7 +1155,7 @@ func TestGetMentionKeywords(t *testing.T) {
// Channel-wide mentions are not ignored on channel level
channelMemberNotifyPropsMap3Off := map[string]model.StringMap{
user3.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
}
profiles = map[string]*model.User{user3.Id: user3}
@@ -1171,7 +1171,7 @@ func TestGetMentionKeywords(t *testing.T) {
// Channel member notify props is set to default
channelMemberNotifyPropsMapDefault := map[string]model.StringMap{
user3.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_DEFAULT,
"ignore_channel_mentions": model.IgnoreChannelMentionsDefault,
},
}
profiles = map[string]*model.User{user3.Id: user3}
@@ -1199,7 +1199,7 @@ func TestGetMentionKeywords(t *testing.T) {
// Channel-wide mentions are ignored channel level
channelMemberNotifyPropsMap3On := map[string]model.StringMap{
user3.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_ON,
"ignore_channel_mentions": model.IgnoreChannelMentionsOn,
},
}
mentions = th.App.getMentionKeywordsInChannel(profiles, true, channelMemberNotifyPropsMap3On)
@@ -1220,7 +1220,7 @@ func TestGetMentionKeywords(t *testing.T) {
// Channel-wide mentions are not ignored on channel level
channelMemberNotifyPropsMap4Off := map[string]model.StringMap{
user4.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
}
@@ -1249,7 +1249,7 @@ func TestGetMentionKeywords(t *testing.T) {
// Channel-wide mentions are ignored on channel level
channelMemberNotifyPropsMap4On := map[string]model.StringMap{
user4.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_ON,
"ignore_channel_mentions": model.IgnoreChannelMentionsOn,
},
}
mentions = th.App.getMentionKeywordsInChannel(profiles, true, channelMemberNotifyPropsMap4On)
@@ -1295,16 +1295,16 @@ func TestGetMentionKeywords(t *testing.T) {
// Channel-wide mentions are not ignored on channel level for all users
channelMemberNotifyPropsMap5Off := map[string]model.StringMap{
user1.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
user2.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
user3.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
user4.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
}
mentions = th.App.getMentionKeywordsInChannel(profiles, true, channelMemberNotifyPropsMap5Off)
@@ -1393,7 +1393,7 @@ func TestGetMentionKeywords(t *testing.T) {
channelMemberNotifyPropsMapEmptyOff := map[string]model.StringMap{
userNoMentionKeys.Id: {
"ignore_channel_mentions": model.IGNORE_CHANNEL_MENTIONS_OFF,
"ignore_channel_mentions": model.IgnoreChannelMentionsOff,
},
}
@@ -1424,7 +1424,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.MENTION_KEYS_NOTIFY_PROP: "apple,BANANA,OrAnGe",
model.MentionKeysNotifyProp: "apple,BANANA,OrAnGe",
},
}
channelNotifyProps := map[string]string{}
@@ -1442,7 +1442,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.MENTION_KEYS_NOTIFY_PROP: ",,",
model.MentionKeysNotifyProp: ",,",
},
}
channelNotifyProps := map[string]string{}
@@ -1460,7 +1460,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
FirstName: "William",
LastName: "Robert",
NotifyProps: map[string]string{
model.FIRST_NAME_NOTIFY_PROP: "true",
model.FirstNameNotifyProp: "true",
},
}
channelNotifyProps := map[string]string{}
@@ -1480,7 +1480,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
FirstName: "",
LastName: "Robert",
NotifyProps: map[string]string{
model.FIRST_NAME_NOTIFY_PROP: "true",
model.FirstNameNotifyProp: "true",
},
}
channelNotifyProps := map[string]string{}
@@ -1498,7 +1498,7 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
FirstName: "William",
LastName: "Robert",
NotifyProps: map[string]string{
model.FIRST_NAME_NOTIFY_PROP: "false",
model.FirstNameNotifyProp: "false",
},
}
channelNotifyProps := map[string]string{}
@@ -1516,12 +1516,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.ChannelMentionsNotifyProp: "true",
},
}
channelNotifyProps := map[string]string{}
status := &model.Status{
Status: model.STATUS_ONLINE,
Status: model.StatusOnline,
}
keywords := map[string][]string{}
@@ -1537,12 +1537,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.ChannelMentionsNotifyProp: "true",
},
}
channelNotifyProps := map[string]string{}
status := &model.Status{
Status: model.STATUS_ONLINE,
Status: model.StatusOnline,
}
keywords := map[string][]string{}
@@ -1558,12 +1558,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "false",
model.ChannelMentionsNotifyProp: "false",
},
}
channelNotifyProps := map[string]string{}
status := &model.Status{
Status: model.STATUS_ONLINE,
Status: model.StatusOnline,
}
keywords := map[string][]string{}
@@ -1579,14 +1579,14 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.ChannelMentionsNotifyProp: "true",
},
}
channelNotifyProps := map[string]string{
model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP: model.IGNORE_CHANNEL_MENTIONS_ON,
model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsOn,
}
status := &model.Status{
Status: model.STATUS_ONLINE,
Status: model.StatusOnline,
}
keywords := map[string][]string{}
@@ -1602,15 +1602,15 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.ChannelMentionsNotifyProp: "true",
},
}
channelNotifyProps := map[string]string{
model.MARK_UNREAD_NOTIFY_PROP: model.USER_NOTIFY_MENTION,
model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP: model.IGNORE_CHANNEL_MENTIONS_DEFAULT,
model.MarkUnreadNotifyProp: model.UserNotifyMention,
model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsDefault,
}
status := &model.Status{
Status: model.STATUS_ONLINE,
Status: model.StatusOnline,
}
keywords := map[string][]string{}
@@ -1626,12 +1626,12 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.ChannelMentionsNotifyProp: "true",
},
}
channelNotifyProps := map[string]string{}
status := &model.Status{
Status: model.STATUS_AWAY,
Status: model.StatusAway,
}
keywords := map[string][]string{}
@@ -1647,14 +1647,14 @@ func TestAddMentionKeywordsForUser(t *testing.T) {
Id: model.NewId(),
Username: "user1",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.ChannelMentionsNotifyProp: "true",
},
}
user2 := &model.User{
Id: model.NewId(),
Username: "user2",
NotifyProps: map[string]string{
model.CHANNEL_MENTIONS_NOTIFY_PROP: "true",
model.ChannelMentionsNotifyProp: "true",
},
}
@@ -1719,50 +1719,50 @@ func TestPostNotificationGetChannelName(t *testing.T) {
expected string
}{
"regular channel": {
channel: &model.Channel{Type: model.CHANNEL_OPEN, Name: "channel", DisplayName: "My Channel"},
channel: &model.Channel{Type: model.ChannelTypeOpen, Name: "channel", DisplayName: "My Channel"},
expected: "My Channel",
},
"direct channel, unspecified": {
channel: &model.Channel{Type: model.CHANNEL_DIRECT},
channel: &model.Channel{Type: model.ChannelTypeDirect},
expected: "@sender",
},
"direct channel, username": {
channel: &model.Channel{Type: model.CHANNEL_DIRECT},
nameFormat: model.SHOW_USERNAME,
channel: &model.Channel{Type: model.ChannelTypeDirect},
nameFormat: model.ShowUsername,
expected: "@sender",
},
"direct channel, full name": {
channel: &model.Channel{Type: model.CHANNEL_DIRECT},
nameFormat: model.SHOW_FULLNAME,
channel: &model.Channel{Type: model.ChannelTypeDirect},
nameFormat: model.ShowFullName,
expected: "Sender Sender",
},
"direct channel, nickname": {
channel: &model.Channel{Type: model.CHANNEL_DIRECT},
nameFormat: model.SHOW_NICKNAME_FULLNAME,
channel: &model.Channel{Type: model.ChannelTypeDirect},
nameFormat: model.ShowNicknameFullName,
expected: "Sender",
},
"group channel, unspecified": {
channel: &model.Channel{Type: model.CHANNEL_GROUP},
channel: &model.Channel{Type: model.ChannelTypeGroup},
expected: "other, sender",
},
"group channel, username": {
channel: &model.Channel{Type: model.CHANNEL_GROUP},
nameFormat: model.SHOW_USERNAME,
channel: &model.Channel{Type: model.ChannelTypeGroup},
nameFormat: model.ShowUsername,
expected: "other, sender",
},
"group channel, full name": {
channel: &model.Channel{Type: model.CHANNEL_GROUP},
nameFormat: model.SHOW_FULLNAME,
channel: &model.Channel{Type: model.ChannelTypeGroup},
nameFormat: model.ShowFullName,
expected: "Other Other, Sender Sender",
},
"group channel, nickname": {
channel: &model.Channel{Type: model.CHANNEL_GROUP},
nameFormat: model.SHOW_NICKNAME_FULLNAME,
channel: &model.Channel{Type: model.ChannelTypeGroup},
nameFormat: model.ShowNicknameFullName,
expected: "Other, Sender",
},
"group channel, not excluding current user": {
channel: &model.Channel{Type: model.CHANNEL_GROUP},
nameFormat: model.SHOW_NICKNAME_FULLNAME,
channel: &model.Channel{Type: model.ChannelTypeGroup},
nameFormat: model.ShowNicknameFullName,
expected: "Other, Sender",
recipientId: "",
},
@@ -1788,7 +1788,7 @@ func TestPostNotificationGetSenderName(t *testing.T) {
th := Setup(t)
defer th.TearDown()
defaultChannel := &model.Channel{Type: model.CHANNEL_OPEN}
defaultChannel := &model.Channel{Type: model.ChannelTypeOpen}
defaultPost := &model.Post{Props: model.StringInterface{}}
sender := &model.User{Id: model.NewId(), Username: "sender", FirstName: "Sender", LastName: "Sender", Nickname: "Sender"}
@@ -1810,19 +1810,19 @@ func TestPostNotificationGetSenderName(t *testing.T) {
expected: "@" + sender.Username,
},
"name format username": {
nameFormat: model.SHOW_USERNAME,
nameFormat: model.ShowUsername,
expected: "@" + sender.Username,
},
"name format full name": {
nameFormat: model.SHOW_FULLNAME,
nameFormat: model.ShowFullName,
expected: sender.FirstName + " " + sender.LastName,
},
"name format nickname": {
nameFormat: model.SHOW_NICKNAME_FULLNAME,
nameFormat: model.ShowNicknameFullName,
expected: sender.Nickname,
},
"system message": {
post: &model.Post{Type: model.POST_SYSTEM_MESSAGE_PREFIX + "custom"},
post: &model.Post{Type: model.PostSystemMessagePrefix + "custom"},
expected: i18n.T("system.message.name"),
},
"overridden username": {
@@ -1831,7 +1831,7 @@ func TestPostNotificationGetSenderName(t *testing.T) {
expected: overriddenPost.GetProp("override_username").(string),
},
"overridden username, direct channel": {
channel: &model.Channel{Type: model.CHANNEL_DIRECT},
channel: &model.Channel{Type: model.ChannelTypeDirect},
post: overriddenPost,
allowOverrides: true,
expected: "@" + sender.Username,
@@ -2294,19 +2294,19 @@ func TestGetNotificationNameFormat(t *testing.T) {
t.Run("show full name on", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.PrivacySettings.ShowFullName = true
*cfg.TeamSettings.TeammateNameDisplay = model.SHOW_FULLNAME
*cfg.TeamSettings.TeammateNameDisplay = model.ShowFullName
})
assert.Equal(t, model.SHOW_FULLNAME, th.App.GetNotificationNameFormat(th.BasicUser))
assert.Equal(t, model.ShowFullName, th.App.GetNotificationNameFormat(th.BasicUser))
})
t.Run("show full name off", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.PrivacySettings.ShowFullName = false
*cfg.TeamSettings.TeammateNameDisplay = model.SHOW_FULLNAME
*cfg.TeamSettings.TeammateNameDisplay = model.ShowFullName
})
assert.Equal(t, model.SHOW_USERNAME, th.App.GetNotificationNameFormat(th.BasicUser))
assert.Equal(t, model.ShowUsername, th.App.GetNotificationNameFormat(th.BasicUser))
})
}
@@ -2320,8 +2320,8 @@ func TestUserAllowsEmail(t *testing.T) {
th.App.SetStatusOffline(user.Id, true)
channelMemberNotificationProps := model.StringMap{
model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT,
model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL,
model.EmailNotifyProp: model.ChannelNotifyDefault,
model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll,
}
assert.True(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"}))
@@ -2333,8 +2333,8 @@ func TestUserAllowsEmail(t *testing.T) {
th.App.SetStatusOnline(user.Id, true)
channelMemberNotificationProps := model.StringMap{
model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT,
model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL,
model.EmailNotifyProp: model.ChannelNotifyDefault,
model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll,
}
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"}))
@@ -2346,8 +2346,8 @@ func TestUserAllowsEmail(t *testing.T) {
th.App.SetStatusOffline(user.Id, true)
channelMemberNotificationProps := model.StringMap{
model.EMAIL_NOTIFY_PROP: "false",
model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL,
model.EmailNotifyProp: "false",
model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll,
}
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"}))
@@ -2359,8 +2359,8 @@ func TestUserAllowsEmail(t *testing.T) {
th.App.SetStatusOffline(user.Id, true)
channelMemberNotificationProps := model.StringMap{
model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT,
model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_MENTION,
model.EmailNotifyProp: model.ChannelNotifyDefault,
model.MarkUnreadNotifyProp: model.ChannelMarkUnreadMention,
}
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: "some-post-type"}))
@@ -2372,11 +2372,11 @@ func TestUserAllowsEmail(t *testing.T) {
th.App.SetStatusOffline(user.Id, true)
channelMemberNotificationProps := model.StringMap{
model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT,
model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL,
model.EmailNotifyProp: model.ChannelNotifyDefault,
model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll,
}
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.POST_AUTO_RESPONDER}))
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder}))
})
t.Run("should return false in case the status is STATUS_OUT_OF_OFFICE", func(t *testing.T) {
@@ -2385,11 +2385,11 @@ func TestUserAllowsEmail(t *testing.T) {
th.App.SetStatusOutOfOffice(user.Id)
channelMemberNotificationProps := model.StringMap{
model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT,
model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL,
model.EmailNotifyProp: model.ChannelNotifyDefault,
model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll,
}
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.POST_AUTO_RESPONDER}))
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder}))
})
t.Run("should return false in case the status is STATUS_ONLINE", func(t *testing.T) {
@@ -2398,11 +2398,11 @@ func TestUserAllowsEmail(t *testing.T) {
th.App.SetStatusDoNotDisturb(user.Id)
channelMemberNotificationProps := model.StringMap{
model.EMAIL_NOTIFY_PROP: model.CHANNEL_NOTIFY_DEFAULT,
model.MARK_UNREAD_NOTIFY_PROP: model.CHANNEL_MARK_UNREAD_ALL,
model.EmailNotifyProp: model.ChannelNotifyDefault,
model.MarkUnreadNotifyProp: model.ChannelMarkUnreadAll,
}
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.POST_AUTO_RESPONDER}))
assert.False(t, th.App.userAllowsEmail(user, channelMemberNotificationProps, &model.Post{Type: model.PostTypeAutoResponder}))
})
}
@@ -2483,13 +2483,13 @@ func TestInsertGroupMentions(t *testing.T) {
mentions := &ExplicitMentions{}
emptyProfileMap := make(map[string]*model.User)
groupChannel := &model.Channel{Type: model.CHANNEL_GROUP}
groupChannel := &model.Channel{Type: model.ChannelTypeGroup}
usersMentioned, _ := th.App.insertGroupMentions(group, groupChannel, emptyProfileMap, mentions)
// Ensure group channel with no group members mentioned always returns true
require.Equal(t, usersMentioned, true)
require.Equal(t, len(mentions.Mentions), 0)
directChannel := &model.Channel{Type: model.CHANNEL_DIRECT}
directChannel := &model.Channel{Type: model.ChannelTypeDirect}
usersMentioned, _ = th.App.insertGroupMentions(group, directChannel, emptyProfileMap, mentions)
// Ensure direct channel with no group members mentioned always returns true
require.Equal(t, usersMentioned, true)
@@ -2624,15 +2624,15 @@ func TestReplyPostNotificationsWithCRT(t *testing.T) {
// Enable "Trigger notifications on messages in
// reply threads that I start or participate in"
// for the second user
oldValue := th.BasicUser2.NotifyProps[model.COMMENTS_NOTIFY_PROP]
oldValue := th.BasicUser2.NotifyProps[model.CommentsNotifyProp]
newNotifyProps := th.BasicUser2.NotifyProps
newNotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY
newNotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny
u2, appErr := th.App.PatchUser(th.BasicUser2.Id, &model.UserPatch{NotifyProps: newNotifyProps}, false)
require.Nil(t, appErr)
require.Equal(t, model.COMMENTS_NOTIFY_ANY, u2.NotifyProps[model.COMMENTS_NOTIFY_PROP])
require.Equal(t, model.CommentsNotifyAny, u2.NotifyProps[model.CommentsNotifyProp])
defer func() {
newNotifyProps := th.BasicUser2.NotifyProps
newNotifyProps[model.COMMENTS_NOTIFY_PROP] = oldValue
newNotifyProps[model.CommentsNotifyProp] = oldValue
_, nAppErr := th.App.PatchUser(th.BasicUser2.Id, &model.UserPatch{NotifyProps: newNotifyProps}, false)
require.Nil(t, nAppErr)
}()
@@ -2642,7 +2642,7 @@ func TestReplyPostNotificationsWithCRT(t *testing.T) {
defer os.Unsetenv("MM_FEATUREFLAGS_COLLAPSEDTHREADS")
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
rootPost := &model.Post{

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

@@ -28,8 +28,8 @@ import (
)
const (
OauthCookieMaxAgeSeconds = 30 * 60 // 30 minutes
CookieOauth = "MMOAUTH"
OAuthCookieMaxAgeSeconds = 30 * 60 // 30 minutes
CookieOAuth = "MMOAUTH"
OpenIDScope = "openid"
)
@@ -76,9 +76,9 @@ func (a *App) GetOAuthApp(appID string) (*model.OAuthApp, *model.AppError) {
return oauthApp, nil
}
func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) {
func (a *App) UpdateOAuthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) {
if !*a.Config().ServiceSettings.EnableOAuthServiceProvider {
return nil, model.NewAppError("UpdateOauthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented)
return nil, model.NewAppError("UpdateOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented)
}
updatedApp.Id = oldApp.Id
@@ -94,9 +94,9 @@ func (a *App) UpdateOauthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthAp
case errors.As(err, &appErr):
return nil, appErr
case errors.As(err, &invErr):
return nil, model.NewAppError("UpdateOauthApp", "app.oauth.update_app.find.app_error", nil, invErr.Error(), http.StatusBadRequest)
return nil, model.NewAppError("UpdateOAuthApp", "app.oauth.update_app.find.app_error", nil, invErr.Error(), http.StatusBadRequest)
default:
return nil, model.NewAppError("UpdateOauthApp", "app.oauth.update_app.updating.app_error", nil, err.Error(), http.StatusInternalServerError)
return nil, model.NewAppError("UpdateOAuthApp", "app.oauth.update_app.updating.app_error", nil, err.Error(), http.StatusInternalServerError)
}
}
@@ -178,7 +178,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author
}
if authRequest.Scope == "" {
authRequest.Scope = model.DEFAULT_SCOPE
authRequest.Scope = model.DefaultScope
}
oauthApp, nErr := a.Srv().Store.OAuth().GetApp(authRequest.ClientId)
@@ -199,9 +199,9 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author
var redirectURI string
var err *model.AppError
switch authRequest.ResponseType {
case model.AUTHCODE_RESPONSE_TYPE:
case model.AuthCodeResponseType:
redirectURI, err = a.GetOAuthCodeRedirect(userID, authRequest)
case model.IMPLICIT_RESPONSE_TYPE:
case model.ImplicitResponseType:
redirectURI, err = a.GetOAuthImplicitRedirect(userID, authRequest)
default:
return authRequest.RedirectUri + "?error=unsupported_response_type&state=" + authRequest.State, nil
@@ -215,7 +215,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author
// This saves the OAuth2 app as authorized
authorizedApp := model.Preference{
UserId: userID,
Category: model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP,
Category: model.PreferenceCategoryAuthorizedOAuthApp,
Name: authRequest.ClientId,
Value: authRequest.Scope,
}
@@ -274,7 +274,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c
var accessData *model.AccessData
var accessRsp *model.AccessResponse
var user *model.User
if grantType == model.ACCESS_TOKEN_GRANT_TYPE {
if grantType == model.AccessTokenGrantType {
var authData *model.AuthData
authData, nErr = a.Srv().Store.OAuth().GetAuthData(code)
if nErr != nil {
@@ -314,7 +314,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c
// Return the same token and no need to create a new session
accessRsp = &model.AccessResponse{
AccessToken: accessData.Token,
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
RefreshToken: accessData.RefreshToken,
ExpiresIn: int32((accessData.ExpiresAt - model.GetMillis()) / 1000),
}
@@ -335,7 +335,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectUri, c
accessRsp = &model.AccessResponse{
AccessToken: session.Token,
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
RefreshToken: accessData.RefreshToken,
ExpiresIn: int32(*a.Config().ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24),
}
@@ -371,9 +371,9 @@ func (a *App) newSession(appName string, user *model.User) (*model.Session, *mod
session := &model.Session{UserId: user.Id, Roles: user.Roles, IsOAuth: true}
session.GenerateCSRF()
a.srv.userService.SetSessionExpireInDays(session, *a.Config().ServiceSettings.SessionLengthSSOInDays)
session.AddProp(model.SESSION_PROP_PLATFORM, appName)
session.AddProp(model.SESSION_PROP_OS, "OAuth2")
session.AddProp(model.SESSION_PROP_BROWSER, "OAuth2")
session.AddProp(model.SessionPropPlatform, appName)
session.AddProp(model.SessionPropOs, "OAuth2")
session.AddProp(model.SessionPropBrowser, "OAuth2")
session, err := a.Srv().Store.Session().Save(session)
if err != nil {
@@ -406,7 +406,7 @@ func (a *App) newSessionUpdateToken(appName string, accessData *model.AccessData
accessRsp := &model.AccessResponse{
AccessToken: session.Token,
RefreshToken: accessData.RefreshToken,
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
ExpiresIn: int32(*a.Config().ServiceSettings.SessionLengthSSOInDays * 60 * 60 * 24),
}
@@ -424,7 +424,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv
stateProps["redirect_to"] = redirectTo
}
stateProps[model.USER_AUTH_SERVICE_IS_MOBILE] = strconv.FormatBool(isMobile)
stateProps[model.UserAuthServiceIsMobile] = strconv.FormatBool(isMobile)
authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, loginHint)
if err != nil {
@@ -436,7 +436,7 @@ func (a *App) GetOAuthLoginEndpoint(w http.ResponseWriter, r *http.Request, serv
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
stateProps["action"] = model.OAuthActionSignup
if teamID != "" {
stateProps["team_id"] = teamID
}
@@ -489,7 +489,7 @@ func (a *App) DeauthorizeOAuthAppForUser(userID, appID string) *model.AppError {
}
// Deauthorize the app
if err := a.Srv().Store.Preference().Delete(userID, model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, appID); err != nil {
if err := a.Srv().Store.Preference().Delete(userID, model.PreferenceCategoryAuthorizedOAuthApp, appID); err != nil {
return model.NewAppError("DeauthorizeOAuthAppForUser", "app.preference.delete.app_error", nil, err.Error(), http.StatusInternalServerError)
}
@@ -539,29 +539,29 @@ func (a *App) CompleteOAuth(c *request.Context, service string, body io.ReadClos
action := props["action"]
switch action {
case model.OAUTH_ACTION_SIGNUP:
case model.OAuthActionSignup:
return a.CreateOAuthUser(c, service, body, teamID, tokenUser)
case model.OAUTH_ACTION_LOGIN:
case model.OAuthActionLogin:
return a.LoginByOAuth(c, service, body, teamID, tokenUser)
case model.OAUTH_ACTION_EMAIL_TO_SSO:
case model.OAuthActionEmailToSSO:
return a.CompleteSwitchWithOAuth(service, body, props["email"], tokenUser)
case model.OAUTH_ACTION_SSO_TO_EMAIL:
case model.OAuthActionSSOToEmail:
return a.LoginByOAuth(c, service, body, teamID, tokenUser)
default:
return a.LoginByOAuth(c, service, body, teamID, tokenUser)
}
}
func (a *App) getSSOProvider(service string) (einterfaces.OauthProvider, *model.AppError) {
func (a *App) getSSOProvider(service string) (einterfaces.OAuthProvider, *model.AppError) {
sso := a.Config().GetSSOService(service)
if sso == nil || !*sso.Enable {
return nil, model.NewAppError("getSSOProvider", "api.user.authorize_oauth_user.unsupported.app_error", nil, "service="+service, http.StatusNotImplemented)
}
providerType := service
if strings.Contains(*sso.Scope, OpenIDScope) {
providerType = model.SERVICE_OPENID
providerType = model.ServiceOpenid
}
provider := einterfaces.GetOauthProvider(providerType)
provider := einterfaces.GetOAuthProvider(providerType)
if provider == nil {
return nil, model.NewAppError("getSSOProvider", "api.user.login_by_oauth.not_available.app_error",
map[string]interface{}{"Service": strings.Title(service)}, "", http.StatusNotImplemented)
@@ -672,7 +672,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email
}
func (a *App) CreateOAuthStateToken(extra string) (*model.Token, *model.AppError) {
token := model.NewToken(model.TOKEN_TYPE_OAUTH, extra)
token := model.NewToken(model.TokenTypeOAuth, extra)
if err := a.Srv().Store.Token().Save(token); err != nil {
var appErr *model.AppError
@@ -693,7 +693,7 @@ func (a *App) GetOAuthStateToken(token string) (*model.Token, *model.AppError) {
return nil, model.NewAppError("GetOAuthStateToken", "api.oauth.invalid_state_token.app_error", nil, err.Error(), http.StatusBadRequest)
}
if mToken.Type != model.TOKEN_TYPE_OAUTH {
if mToken.Type != model.TokenTypeOAuth {
return nil, model.NewAppError("GetOAuthStateToken", "api.oauth.invalid_state_token.app_error", nil, "", http.StatusBadRequest)
}
@@ -719,12 +719,12 @@ func (a *App) GetAuthorizationCode(w http.ResponseWriter, r *http.Request, servi
cookieValue := model.NewId()
subpath, _ := utils.GetSubpathFromConfig(a.Config())
expiresAt := time.Unix(model.GetMillis()/1000+int64(OauthCookieMaxAgeSeconds), 0)
expiresAt := time.Unix(model.GetMillis()/1000+int64(OAuthCookieMaxAgeSeconds), 0)
oauthCookie := &http.Cookie{
Name: CookieOauth,
Name: CookieOAuth,
Value: cookieValue,
Path: subpath,
MaxAge: OauthCookieMaxAgeSeconds,
MaxAge: OAuthCookieMaxAgeSeconds,
Expires: expiresAt,
HttpOnly: true,
Secure: secure,
@@ -791,11 +791,11 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
stateEmail := stateProps["email"]
stateAction := stateProps["action"]
if stateAction == model.OAUTH_ACTION_EMAIL_TO_SSO && stateEmail == "" {
if stateAction == model.OAuthActionEmailToSSO && stateEmail == "" {
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest)
}
cookie, cookieErr := r.Cookie(CookieOauth)
cookie, cookieErr := r.Cookie(CookieOAuth)
if cookieErr != nil {
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest)
}
@@ -813,7 +813,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
subpath, _ := utils.GetSubpathFromConfig(a.Config())
httpCookie := &http.Cookie{
Name: CookieOauth,
Name: CookieOAuth,
Value: "",
Path: subpath,
MaxAge: -1,
@@ -828,7 +828,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
p.Set("client_id", *sso.Id)
p.Set("client_secret", *sso.Secret)
p.Set("code", code)
p.Set("grant_type", model.ACCESS_TOKEN_GRANT_TYPE)
p.Set("grant_type", model.AccessTokenGrantType)
p.Set("redirect_uri", redirectUri)
req, requestErr := http.NewRequest("POST", *sso.TokenEndpoint, strings.NewReader(p.Encode()))
@@ -852,7 +852,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.bad_response.app_error", nil, fmt.Sprintf("response_body=%s, status_code=%d", buf.String(), resp.StatusCode), http.StatusInternalServerError)
}
if strings.ToLower(ar.TokenType) != model.ACCESS_TOKEN_TYPE {
if strings.ToLower(ar.TokenType) != model.AccessTokenType {
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.bad_token.app_error", nil, "token_type="+ar.TokenType+", response_body="+buf.String(), http.StatusInternalServerError)
}
@@ -892,7 +892,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
mlog.Error("Error getting OAuth user", mlog.Int("response", resp.StatusCode), mlog.String("body_string", bodyString))
if service == model.SERVICE_GITLAB && resp.StatusCode == http.StatusForbidden && strings.Contains(bodyString, "Terms of Service") {
if service == model.ServiceGitlab && resp.StatusCode == http.StatusForbidden && strings.Contains(bodyString, "Terms of Service") {
// Return a nicer error when the user hasn't accepted GitLab's terms of service
return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "oauth.gitlab.tos.error", nil, "", http.StatusBadRequest)
}
@@ -919,11 +919,11 @@ func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email,
}
stateProps := map[string]string{}
stateProps["action"] = model.OAUTH_ACTION_EMAIL_TO_SSO
stateProps["action"] = model.OAuthActionEmailToSSO
stateProps["email"] = email
if service == model.USER_AUTH_SERVICE_SAML {
return a.GetSiteURL() + "/login/sso/saml?action=" + model.OAUTH_ACTION_EMAIL_TO_SSO + "&email=" + utils.URLEncode(email), nil
if service == model.UserAuthServiceSaml {
return a.GetSiteURL() + "/login/sso/saml?action=" + model.OAuthActionEmailToSSO + "&email=" + utils.URLEncode(email), nil
}
authUrl, err := a.GetAuthorizationCode(w, r, service, stateProps, "")

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

@@ -35,7 +35,7 @@ func TestGetOAuthAccessTokenForImplicitFlow(t *testing.T) {
require.Nil(t, err)
authRequest := &model.AuthorizeRequest{
ResponseType: model.IMPLICIT_RESPONSE_TYPE,
ResponseType: model.ImplicitResponseType,
ClientId: oapp.Id,
RedirectUri: oapp.CallbackUrls[0],
Scope: "",
@@ -74,7 +74,7 @@ func TestOAuthRevokeAccessToken(t *testing.T) {
session.CreateAt = model.GetMillis()
session.UserId = model.NewId()
session.Token = model.NewId()
session.Roles = model.SYSTEM_USER_ROLE_ID
session.Roles = model.SystemUserRoleId
th.App.SetSessionExpireInDays(session, 1)
var err *model.AppError
@@ -105,7 +105,7 @@ func TestOAuthDeleteApp(t *testing.T) {
session.CreateAt = model.GetMillis()
session.UserId = model.NewId()
session.Token = model.NewId()
session.Roles = model.SYSTEM_USER_ROLE_ID
session.Roles = model.SystemUserRoleId
session.IsOAuth = true
th.App.srv.userService.SetSessionExpireInDays(session, 1)
@@ -167,7 +167,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
if cookie != "" {
request.AddCookie(&http.Cookie{
Name: CookieOauth,
Name: CookieOAuth,
Value: cookie,
})
}
@@ -179,7 +179,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
th := setup(t, false, true, true, "")
defer th.TearDown()
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", "", "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", "", "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.unsupported.app_error", err.Id)
})
@@ -190,7 +190,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
state := "!"
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id)
})
@@ -203,7 +203,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
"token": model.NewId(),
})))
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.oauth.invalid_state_token.app_error", err.Id)
assert.NotEqual(t, "", err.DetailedError)
@@ -218,7 +218,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
state := makeState(token)
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.oauth.invalid_state_token.app_error", err.Id)
assert.Equal(t, "", err.DetailedError)
@@ -229,7 +229,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
defer th.TearDown()
email := ""
action := model.OAUTH_ACTION_EMAIL_TO_SSO
action := model.OAuthActionEmailToSSO
cookie := model.NewId()
token, err := th.App.CreateOAuthStateToken(generateOAuthStateTokenExtra(email, action, cookie))
@@ -241,7 +241,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
"token": token.Token,
})))
_, _, _, _, err = th.App.AuthorizeOAuthUser(nil, nil, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err = th.App.AuthorizeOAuthUser(nil, nil, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id)
})
@@ -254,7 +254,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest("")
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(nil, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id)
})
@@ -271,7 +271,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(token)
_, _, _, _, err = th.App.AuthorizeOAuthUser(nil, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err = th.App.AuthorizeOAuthUser(nil, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.invalid_state.app_error", err.Id)
})
@@ -284,7 +284,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.token_failed.app_error", err.Id)
})
@@ -302,7 +302,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.bad_response.app_error", err.Id)
assert.Contains(t, err.DetailedError, "status_code=418")
@@ -321,7 +321,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.bad_response.app_error", err.Id)
assert.Contains(t, err.DetailedError, "response_body=invalid")
@@ -343,7 +343,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.bad_token.app_error", err.Id)
})
@@ -352,7 +352,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(&model.AccessResponse{
AccessToken: "",
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
})
}))
defer server.Close()
@@ -364,7 +364,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.missing.app_error", err.Id)
})
@@ -373,7 +373,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(&model.AccessResponse{
AccessToken: model.NewId(),
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
})
}))
defer server.Close()
@@ -385,7 +385,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.service.app_error", err.Id)
})
@@ -397,7 +397,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
t.Log("hit token")
json.NewEncoder(w).Encode(&model.AccessResponse{
AccessToken: model.NewId(),
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
})
case "/user":
t.Log("hit user")
@@ -413,7 +413,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.response.app_error", err.Id)
})
@@ -425,7 +425,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
t.Log("hit token")
json.NewEncoder(w).Encode(&model.AccessResponse{
AccessToken: model.NewId(),
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
})
case "/user":
t.Log("hit user")
@@ -442,7 +442,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
request := makeRequest(cookie)
state := makeState(makeToken(th, cookie))
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.SERVICE_GITLAB, "", state, "")
_, _, _, _, err := th.App.AuthorizeOAuthUser(&httptest.ResponseRecorder{}, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, err)
assert.Equal(t, "oauth.gitlab.tos.error", err.Id)
})
@@ -466,7 +466,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
case "/token":
json.NewEncoder(w).Encode(&model.AccessResponse{
AccessToken: model.NewId(),
TokenType: model.ACCESS_TOKEN_TYPE,
TokenType: model.AccessTokenType,
})
case "/user":
w.WriteHeader(http.StatusOK)
@@ -492,7 +492,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
recorder := httptest.ResponseRecorder{}
body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.SERVICE_GITLAB, "", state, "")
body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, body)
bodyBytes, bodyErr := ioutil.ReadAll(body)
@@ -519,7 +519,7 @@ func TestGetAuthorizationCode(t *testing.T) {
*cfg.GitLabSettings.Enable = false
})
_, err := th.App.GetAuthorizationCode(nil, nil, model.SERVICE_GITLAB, map[string]string{}, "")
_, err := th.App.GetAuthorizationCode(nil, nil, model.ServiceGitlab, map[string]string{}, "")
require.NotNil(t, err)
assert.Equal(t, "api.user.authorize_oauth_user.unsupported.app_error", err.Id)
@@ -556,7 +556,7 @@ func TestGetAuthorizationCode(t *testing.T) {
}
recorder := httptest.ResponseRecorder{}
url, err := th.App.GetAuthorizationCode(&recorder, request, model.SERVICE_GITLAB, stateProps, "")
url, err := th.App.GetAuthorizationCode(&recorder, request, model.ServiceGitlab, stateProps, "")
require.Nil(t, err)
assert.NotEmpty(t, url)

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

@@ -16161,7 +16161,29 @@ func (a *OpenTracingAppLayer) UpdateMobileAppBadge(userID string) {
a.app.UpdateMobileAppBadge(userID)
}
func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string, tokenUser *model.User) *model.AppError {
func (a *OpenTracingAppLayer) UpdateOAuthApp(oldApp *model.OAuthApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOAuthApp")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.UpdateOAuthApp(oldApp, updatedApp)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
ext.Error.Set(span, true)
}
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OAuthProvider, service string, tokenUser *model.User) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOAuthUserAttrs")
@@ -16183,28 +16205,6 @@ func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *mod
return resultVar0
}
func (a *OpenTracingAppLayer) UpdateOauthApp(oldApp *model.OAuthApp, updatedApp *model.OAuthApp) (*model.OAuthApp, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOauthApp")
a.ctx = newCtx
a.app.Srv().Store.SetContext(newCtx)
defer func() {
a.app.Srv().Store.SetContext(origCtx)
a.ctx = origCtx
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.UpdateOauthApp(oldApp, updatedApp)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
ext.Error.Set(span, true)
}
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) UpdateOutgoingWebhook(oldHook *model.OutgoingWebhook, updatedHook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOutgoingWebhook")

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

@@ -56,7 +56,7 @@ func (a *App) ResetPermissionsSystem() *model.AppError {
}
// Remove the "System" table entry that marks the advanced permissions migration as done.
if _, err := a.Srv().Store.System().PermanentDeleteByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err != nil {
if _, err := a.Srv().Store.System().PermanentDeleteByName(model.AdvancedPermissionsMigrationKey); err != nil {
return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, err.Error(), http.StatusInternalServerError)
}

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

@@ -222,12 +222,12 @@ func (a *App) getWebhooksPermissionsSplitMigration() (permissionsMap, error) {
func (a *App) getListJoinPublicPrivateTeamsPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: []string{PermissionListPrivateTeams, PermissionJoinPrivateTeams},
Remove: []string{},
},
permissionTransformation{
On: isRole(model.SYSTEM_USER_ROLE_ID),
On: isRole(model.SystemUserRoleId),
Add: []string{PermissionListPublicTeams, PermissionJoinPublicTeams},
Remove: []string{},
},
@@ -246,7 +246,7 @@ func (a *App) removePermanentDeleteUserMigration() (permissionsMap, error) {
func (a *App) getAddBotPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: []string{PermissionCreateBot, PermissionReadBots, PermissionReadOthersBots, PermissionManageBots, PermissionManageOthersBots},
Remove: []string{},
},
@@ -256,19 +256,19 @@ func (a *App) getAddBotPermissionsMigration() (permissionsMap, error) {
func (a *App) applyChannelManageDeleteToChannelUser() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePrivateChannelProperties))),
On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionManagePrivateChannelProperties))),
Add: []string{PermissionManagePrivateChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePrivateChannel))),
On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionDeletePrivateChannel))),
Add: []string{PermissionDeletePrivateChannel},
},
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePublicChannelProperties))),
On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionManagePublicChannelProperties))),
Add: []string{PermissionManagePublicChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePublicChannel))),
On: permissionAnd(isRole(model.ChannelUserRoleId), onOtherRole(model.TeamUserRoleId, permissionExists(PermissionDeletePublicChannel))),
Add: []string{PermissionDeletePublicChannel},
},
}, nil
@@ -277,19 +277,19 @@ func (a *App) applyChannelManageDeleteToChannelUser() (permissionsMap, error) {
func (a *App) removeChannelManageDeleteFromTeamUser() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePrivateChannelProperties)),
On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionManagePrivateChannelProperties)),
Remove: []string{PermissionManagePrivateChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePrivateChannel)),
Remove: []string{model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id},
On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionDeletePrivateChannel)),
Remove: []string{model.PermissionDeletePrivateChannel.Id},
},
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePublicChannelProperties)),
On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionManagePublicChannelProperties)),
Remove: []string{PermissionManagePublicChannelProperties},
},
permissionTransformation{
On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePublicChannel)),
On: permissionAnd(isRole(model.TeamUserRoleId), permissionExists(PermissionDeletePublicChannel)),
Remove: []string{PermissionDeletePublicChannel},
},
}, nil
@@ -298,11 +298,11 @@ func (a *App) removeChannelManageDeleteFromTeamUser() (permissionsMap, error) {
func (a *App) getViewMembersPermissionMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_USER_ROLE_ID),
On: isRole(model.SystemUserRoleId),
Add: []string{PermissionViewMembers},
},
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: []string{PermissionViewMembers},
},
}, nil
@@ -311,7 +311,7 @@ func (a *App) getViewMembersPermissionMigration() (permissionsMap, error) {
func (a *App) getAddManageGuestsPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: []string{PermissionPromoteGuest, PermissionDemoteToGuest, PermissionInviteGuest},
},
}, nil
@@ -321,7 +321,7 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) {
transformations := permissionsMap{}
var allTeamSchemes []*model.Scheme
next := a.SchemesIterator(model.SCHEME_SCOPE_TEAM, 100)
next := a.SchemesIterator(model.SchemeScopeTeam, 100)
var schemeBatch []*model.Scheme
for schemeBatch = next(); len(schemeBatch) > 0; schemeBatch = next() {
allTeamSchemes = append(allTeamSchemes, schemeBatch...)
@@ -396,27 +396,27 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) {
// ensure team admins have create_post
transformations = append(transformations, permissionTransformation{
On: isRole(model.TEAM_ADMIN_ROLE_ID),
On: isRole(model.TeamAdminRoleId),
Add: []string{PermissionCreatePost},
})
// ensure channel admins have create_post
transformations = append(transformations, permissionTransformation{
On: isRole(model.CHANNEL_ADMIN_ROLE_ID),
On: isRole(model.ChannelAdminRoleId),
Add: []string{PermissionCreatePost},
})
// conditionally add all other moderated permissions to team and channel admins
transformations = append(transformations, teamAndChannelAdminConditionalTransformations(
model.TEAM_ADMIN_ROLE_ID,
model.CHANNEL_ADMIN_ROLE_ID,
model.CHANNEL_USER_ROLE_ID,
model.CHANNEL_GUEST_ROLE_ID,
model.TeamAdminRoleId,
model.ChannelAdminRoleId,
model.ChannelUserRoleId,
model.ChannelGuestRoleId,
)...)
// ensure system admin has all of the moderated permissions
transformations = append(transformations, permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: append(moderatedPermissionsMinusCreatePost, PermissionCreatePost),
})
@@ -433,7 +433,7 @@ func (a *App) getAddUseGroupMentionsPermissionMigration() (permissionsMap, error
return permissionsMap{
permissionTransformation{
On: permissionAnd(
isNotRole(model.CHANNEL_GUEST_ROLE_ID),
isNotRole(model.ChannelGuestRoleId),
isNotSchemeRole("Channel Guest Role for Scheme"),
permissionOr(permissionExists(PermissionCreatePost), permissionExists(PermissionCreatePost_PUBLIC)),
),
@@ -453,7 +453,7 @@ func (a *App) getAddSystemConsolePermissionsMigration() (permissionsMap, error)
// add the new permissions to system admin
transformations = append(transformations,
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: permissionsToAdd,
})
@@ -502,8 +502,8 @@ func (a *App) getAddConvertChannelPermissionsMigration() (permissionsMap, error)
func (a *App) getSystemRolesPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_SYSTEM_ROLES.Id, model.PERMISSION_SYSCONSOLE_WRITE_USERMANAGEMENT_SYSTEM_ROLES.Id},
On: isRole(model.SystemAdminRoleId),
Add: []string{model.PermissionSysconsoleReadUserManagementSystemRoles.Id, model.PermissionSysconsoleWriteUserManagementSystemRoles.Id},
},
}, nil
}
@@ -511,7 +511,7 @@ func (a *App) getSystemRolesPermissionsMigration() (permissionsMap, error) {
func (a *App) getAddManageSharedChannelsPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: []string{PermissionManageSharedChannels},
},
}, nil
@@ -520,8 +520,8 @@ func (a *App) getAddManageSharedChannelsPermissionsMigration() (permissionsMap,
func (a *App) getBillingPermissionsMigration() (permissionsMap, error) {
return permissionsMap{
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{model.PERMISSION_SYSCONSOLE_READ_BILLING.Id, model.PERMISSION_SYSCONSOLE_WRITE_BILLING.Id},
On: isRole(model.SystemAdminRoleId),
Add: []string{model.PermissionSysconsoleReadBilling.Id, model.PermissionSysconsoleWriteBilling.Id},
},
}, nil
}
@@ -532,14 +532,14 @@ func (a *App) getAddManageSecureConnectionsPermissionsMigration() (permissionsMa
// add the new permission to system admin
transformations = append(transformations,
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Add: []string{PermissionManageSecureConnections},
})
// remote the decprecated permission from system admin
transformations = append(transformations,
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
On: isRole(model.SystemAdminRoleId),
Remove: []string{PermissionManageRemoteClusters},
})
@@ -549,25 +549,25 @@ func (a *App) getAddManageSecureConnectionsPermissionsMigration() (permissionsMa
func (a *App) getAddDownloadComplianceExportResult() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsToAddComplianceRead := []string{model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id, model.PERMISSION_READ_DATA_RETENTION_JOB.Id}
permissionsToAddComplianceWrite := []string{model.PERMISSION_MANAGE_JOBS.Id}
permissionsToAddComplianceRead := []string{model.PermissionDownloadComplianceExportResult.Id, model.PermissionReadDataRetentionJob.Id}
permissionsToAddComplianceWrite := []string{model.PermissionManageJobs.Id}
// add the new permissions to system admin
transformations = append(transformations,
permissionTransformation{
On: isRole(model.SYSTEM_ADMIN_ROLE_ID),
Add: []string{model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id},
On: isRole(model.SystemAdminRoleId),
Add: []string{model.PermissionDownloadComplianceExportResult.Id},
})
// add Download Compliance Export Result and Read Jobs to all roles with sysconsole_read_compliance
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE.Id),
On: permissionExists(model.PermissionSysconsoleReadCompliance.Id),
Add: permissionsToAddComplianceRead,
})
// add manage_jobs to all roles with sysconsole_write_compliance
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE.Id),
On: permissionExists(model.PermissionSysconsoleWriteCompliance.Id),
Add: permissionsToAddComplianceWrite,
})
@@ -577,25 +577,25 @@ func (a *App) getAddDownloadComplianceExportResult() (permissionsMap, error) {
func (a *App) getAddExperimentalSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsExperimentalRead := []string{model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_BLEVE.Id, model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURES.Id, model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL_FEATURE_FLAGS.Id}
permissionsExperimentalWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE.Id, model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURES.Id, model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_FEATURE_FLAGS.Id}
permissionsExperimentalRead := []string{model.PermissionSysconsoleReadExperimentalBleve.Id, model.PermissionSysconsoleReadExperimentalFeatures.Id, model.PermissionSysconsoleReadExperimentalFeatureFlags.Id}
permissionsExperimentalWrite := []string{model.PermissionSysconsoleWriteExperimentalBleve.Id, model.PermissionSysconsoleWriteExperimentalFeatures.Id, model.PermissionSysconsoleWriteExperimentalFeatureFlags.Id}
// Give the new subsection READ permissions to any user with READ_EXPERIMENTAL
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_EXPERIMENTAL.Id),
On: permissionExists(model.PermissionSysconsoleReadExperimental.Id),
Add: permissionsExperimentalRead,
})
// Give the new subsection WRITE permissions to any user with WRITE_EXPERIMENTAL
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL.Id),
On: permissionExists(model.PermissionSysconsoleWriteExperimental.Id),
Add: permissionsExperimentalWrite,
})
// Give the ancillary permissions MANAGE_JOBS and PURGE_BLEVE_INDEXES to anyone with WRITE_EXPERIMENTAL_BLEVE
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_EXPERIMENTAL_BLEVE.Id),
Add: []string{model.PERMISSION_CREATE_POST_BLEVE_INDEXES_JOB.Id, model.PERMISSION_PURGE_BLEVE_INDEXES.Id},
On: permissionExists(model.PermissionSysconsoleWriteExperimentalBleve.Id),
Add: []string{model.PermissionCreatePostBleveIndexesJob.Id, model.PermissionPurgeBleveIndexes.Id},
})
return transformations, nil
@@ -604,18 +604,18 @@ func (a *App) getAddExperimentalSubsectionPermissions() (permissionsMap, error)
func (a *App) getAddIntegrationsSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsIntegrationsRead := []string{model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_BOT_ACCOUNTS.Id, model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_GIF.Id, model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS_CORS.Id}
permissionsIntegrationsWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_INTEGRATION_MANAGEMENT.Id, model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_BOT_ACCOUNTS.Id, model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_GIF.Id, model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS_CORS.Id}
permissionsIntegrationsRead := []string{model.PermissionSysconsoleReadIntegrationsIntegrationManagement.Id, model.PermissionSysconsoleReadIntegrationsBotAccounts.Id, model.PermissionSysconsoleReadIntegrationsGif.Id, model.PermissionSysconsoleReadIntegrationsCors.Id}
permissionsIntegrationsWrite := []string{model.PermissionSysconsoleWriteIntegrationsIntegrationManagement.Id, model.PermissionSysconsoleWriteIntegrationsBotAccounts.Id, model.PermissionSysconsoleWriteIntegrationsGif.Id, model.PermissionSysconsoleWriteIntegrationsCors.Id}
// Give the new subsection READ permissions to any user with READ_INTEGRATIONS
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_INTEGRATIONS.Id),
On: permissionExists(model.PermissionSysconsoleReadIntegrations.Id),
Add: permissionsIntegrationsRead,
})
// Give the new subsection WRITE permissions to any user with WRITE_EXPERIMENTAL
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_INTEGRATIONS.Id),
On: permissionExists(model.PermissionSysconsoleWriteIntegrations.Id),
Add: permissionsIntegrationsWrite,
})
@@ -625,25 +625,25 @@ func (a *App) getAddIntegrationsSubsectionPermissions() (permissionsMap, error)
func (a *App) getAddSiteSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsSiteRead := []string{model.PERMISSION_SYSCONSOLE_READ_SITE_CUSTOMIZATION.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_LOCALIZATION.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_USERS_AND_TEAMS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_NOTIFICATIONS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_ANNOUNCEMENT_BANNER.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_EMOJI.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_POSTS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_FILE_SHARING_AND_DOWNLOADS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_PUBLIC_LINKS.Id, model.PERMISSION_SYSCONSOLE_READ_SITE_NOTICES.Id}
permissionsSiteWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_LOCALIZATION.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_USERS_AND_TEAMS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_NOTIFICATIONS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_ANNOUNCEMENT_BANNER.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_EMOJI.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_POSTS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_FILE_SHARING_AND_DOWNLOADS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_PUBLIC_LINKS.Id, model.PERMISSION_SYSCONSOLE_WRITE_SITE_NOTICES.Id}
permissionsSiteRead := []string{model.PermissionSysconsoleReadSiteCustomization.Id, model.PermissionSysconsoleReadSiteLocalization.Id, model.PermissionSysconsoleReadSiteUsersAndTeams.Id, model.PermissionSysconsoleReadSiteNotifications.Id, model.PermissionSysconsoleReadSiteAnnouncementBanner.Id, model.PermissionSysconsoleReadSiteEmoji.Id, model.PermissionSysconsoleReadSitePosts.Id, model.PermissionSysconsoleReadSiteFileSharingAndDownloads.Id, model.PermissionSysconsoleReadSitePublicLinks.Id, model.PermissionSysconsoleReadSiteNotices.Id}
permissionsSiteWrite := []string{model.PermissionSysconsoleWriteSiteCustomization.Id, model.PermissionSysconsoleWriteSiteLocalization.Id, model.PermissionSysconsoleWriteSiteUsersAndTeams.Id, model.PermissionSysconsoleWriteSiteNotifications.Id, model.PermissionSysconsoleWriteSiteAnnouncementBanner.Id, model.PermissionSysconsoleWriteSiteEmoji.Id, model.PermissionSysconsoleWriteSitePosts.Id, model.PermissionSysconsoleWriteSiteFileSharingAndDownloads.Id, model.PermissionSysconsoleWriteSitePublicLinks.Id, model.PermissionSysconsoleWriteSiteNotices.Id}
// Give the new subsection READ permissions to any user with READ_SITE
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_SITE.Id),
On: permissionExists(model.PermissionSysconsoleReadSite.Id),
Add: permissionsSiteRead,
})
// Give the new subsection WRITE permissions to any user with WRITE_SITE
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_SITE.Id),
On: permissionExists(model.PermissionSysconsoleWriteSite.Id),
Add: permissionsSiteWrite,
})
// Give the ancillary permissions EDIT_BRAND to anyone with WRITE_SITE_CUSTOMIZATION
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_SITE_CUSTOMIZATION.Id),
Add: []string{model.PERMISSION_EDIT_BRAND.Id},
On: permissionExists(model.PermissionSysconsoleWriteSiteCustomization.Id),
Add: []string{model.PermissionEditBrand.Id},
})
return transformations, nil
@@ -652,45 +652,45 @@ func (a *App) getAddSiteSubsectionPermissions() (permissionsMap, error) {
func (a *App) getAddComplianceSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsComplianceRead := []string{model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY.Id, model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT.Id, model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_MONITORING.Id, model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id}
permissionsComplianceWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY.Id, model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT.Id, model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_MONITORING.Id, model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id}
permissionsComplianceRead := []string{model.PermissionSysconsoleReadComplianceDataRetentionPolicy.Id, model.PermissionSysconsoleReadComplianceComplianceExport.Id, model.PermissionSysconsoleReadComplianceComplianceMonitoring.Id, model.PermissionSysconsoleReadComplianceCustomTermsOfService.Id}
permissionsComplianceWrite := []string{model.PermissionSysconsoleWriteComplianceDataRetentionPolicy.Id, model.PermissionSysconsoleWriteComplianceComplianceExport.Id, model.PermissionSysconsoleWriteComplianceComplianceMonitoring.Id, model.PermissionSysconsoleWriteComplianceCustomTermsOfService.Id}
// Give the new subsection READ permissions to any user with READ_COMPLIANCE
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE.Id),
On: permissionExists(model.PermissionSysconsoleReadCompliance.Id),
Add: permissionsComplianceRead,
})
// Give the new subsection WRITE permissions to any user with WRITE_COMPLIANCE
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE.Id),
On: permissionExists(model.PermissionSysconsoleWriteCompliance.Id),
Add: permissionsComplianceWrite,
})
// Ancilary permissions
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_DATA_RETENTION_POLICY.Id),
Add: []string{model.PERMISSION_CREATE_DATA_RETENTION_JOB.Id},
On: permissionExists(model.PermissionSysconsoleWriteComplianceDataRetentionPolicy.Id),
Add: []string{model.PermissionCreateDataRetentionJob.Id},
})
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_DATA_RETENTION_POLICY.Id),
Add: []string{model.PERMISSION_READ_DATA_RETENTION_JOB.Id},
On: permissionExists(model.PermissionSysconsoleReadComplianceDataRetentionPolicy.Id),
Add: []string{model.PermissionReadDataRetentionJob.Id},
})
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_COMPLIANCE_COMPLIANCE_EXPORT.Id),
Add: []string{model.PERMISSION_CREATE_COMPLIANCE_EXPORT_JOB.Id, model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id},
On: permissionExists(model.PermissionSysconsoleWriteComplianceComplianceExport.Id),
Add: []string{model.PermissionCreateComplianceExportJob.Id, model.PermissionDownloadComplianceExportResult.Id},
})
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_COMPLIANCE_EXPORT.Id),
Add: []string{model.PERMISSION_READ_COMPLIANCE_EXPORT_JOB.Id, model.PERMISSION_DOWNLOAD_COMPLIANCE_EXPORT_RESULT.Id},
On: permissionExists(model.PermissionSysconsoleReadComplianceComplianceExport.Id),
Add: []string{model.PermissionReadComplianceExportJob.Id, model.PermissionDownloadComplianceExportResult.Id},
})
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_COMPLIANCE_CUSTOM_TERMS_OF_SERVICE.Id),
Add: []string{model.PERMISSION_READ_AUDITS.Id},
On: permissionExists(model.PermissionSysconsoleReadComplianceCustomTermsOfService.Id),
Add: []string{model.PermissionReadAudits.Id},
})
return transformations, nil
@@ -700,88 +700,88 @@ func (a *App) getAddEnvironmentSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsEnvironmentRead := []string{
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_WEB_SERVER.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DATABASE.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_FILE_STORAGE.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_IMAGE_PROXY.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SMTP.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PUSH_NOTIFICATION_SERVER.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_HIGH_AVAILABILITY.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_RATE_LIMITING.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_LOGGING.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_SESSION_LENGTHS.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_PERFORMANCE_MONITORING.Id,
model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_DEVELOPER.Id,
model.PermissionSysconsoleReadEnvironmentWebServer.Id,
model.PermissionSysconsoleReadEnvironmentDatabase.Id,
model.PermissionSysconsoleReadEnvironmentElasticsearch.Id,
model.PermissionSysconsoleReadEnvironmentFileStorage.Id,
model.PermissionSysconsoleReadEnvironmentImageProxy.Id,
model.PermissionSysconsoleReadEnvironmentSmtp.Id,
model.PermissionSysconsoleReadEnvironmentPushNotificationServer.Id,
model.PermissionSysconsoleReadEnvironmentHighAvailability.Id,
model.PermissionSysconsoleReadEnvironmentRateLimiting.Id,
model.PermissionSysconsoleReadEnvironmentLogging.Id,
model.PermissionSysconsoleReadEnvironmentSessionLengths.Id,
model.PermissionSysconsoleReadEnvironmentPerformanceMonitoring.Id,
model.PermissionSysconsoleReadEnvironmentDeveloper.Id,
}
permissionsEnvironmentWrite := []string{
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_IMAGE_PROXY.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PUSH_NOTIFICATION_SERVER.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_HIGH_AVAILABILITY.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_RATE_LIMITING.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_LOGGING.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SESSION_LENGTHS.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_PERFORMANCE_MONITORING.Id,
model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DEVELOPER.Id,
model.PermissionSysconsoleWriteEnvironmentWebServer.Id,
model.PermissionSysconsoleWriteEnvironmentDatabase.Id,
model.PermissionSysconsoleWriteEnvironmentElasticsearch.Id,
model.PermissionSysconsoleWriteEnvironmentFileStorage.Id,
model.PermissionSysconsoleWriteEnvironmentImageProxy.Id,
model.PermissionSysconsoleWriteEnvironmentSmtp.Id,
model.PermissionSysconsoleWriteEnvironmentPushNotificationServer.Id,
model.PermissionSysconsoleWriteEnvironmentHighAvailability.Id,
model.PermissionSysconsoleWriteEnvironmentRateLimiting.Id,
model.PermissionSysconsoleWriteEnvironmentLogging.Id,
model.PermissionSysconsoleWriteEnvironmentSessionLengths.Id,
model.PermissionSysconsoleWriteEnvironmentPerformanceMonitoring.Id,
model.PermissionSysconsoleWriteEnvironmentDeveloper.Id,
}
// Give the new subsection READ permissions to any user with READ_ENVIRONMENT
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT.Id),
On: permissionExists(model.PermissionSysconsoleReadEnvironment.Id),
Add: permissionsEnvironmentRead,
})
// Give the new subsection WRITE permissions to any user with WRITE_ENVIRONMENT
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT.Id),
On: permissionExists(model.PermissionSysconsoleWriteEnvironment.Id),
Add: permissionsEnvironmentWrite,
})
// Give these ancillary permissions to anyone with READ_ENVIRONMENT_ELASTICSEARCH
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ENVIRONMENT_ELASTICSEARCH.Id),
On: permissionExists(model.PermissionSysconsoleReadEnvironmentElasticsearch.Id),
Add: []string{
model.PERMISSION_READ_ELASTICSEARCH_POST_INDEXING_JOB.Id,
model.PERMISSION_READ_ELASTICSEARCH_POST_AGGREGATION_JOB.Id,
model.PermissionReadElasticsearchPostIndexingJob.Id,
model.PermissionReadElasticsearchPostAggregationJob.Id,
},
})
// Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_WEB_SERVER
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_WEB_SERVER.Id),
On: permissionExists(model.PermissionSysconsoleWriteEnvironmentWebServer.Id),
Add: []string{
model.PERMISSION_TEST_SITE_URL.Id,
model.PERMISSION_RELOAD_CONFIG.Id,
model.PERMISSION_INVALIDATE_CACHES.Id,
model.PermissionTestSiteUrl.Id,
model.PermissionReloadConfig.Id,
model.PermissionInvalidateCaches.Id,
},
})
// Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_DATABASE
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_DATABASE.Id),
Add: []string{model.PERMISSION_RECYCLE_DATABASE_CONNECTIONS.Id},
On: permissionExists(model.PermissionSysconsoleWriteEnvironmentDatabase.Id),
Add: []string{model.PermissionRecycleDatabaseConnections.Id},
})
// Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_ELASTICSEARCH
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_ELASTICSEARCH.Id),
On: permissionExists(model.PermissionSysconsoleWriteEnvironmentElasticsearch.Id),
Add: []string{
model.PERMISSION_TEST_ELASTICSEARCH.Id,
model.PERMISSION_CREATE_ELASTICSEARCH_POST_INDEXING_JOB.Id,
model.PERMISSION_CREATE_ELASTICSEARCH_POST_AGGREGATION_JOB.Id,
model.PERMISSION_PURGE_ELASTICSEARCH_INDEXES.Id,
model.PermissionTestElasticsearch.Id,
model.PermissionCreateElasticsearchPostIndexingJob.Id,
model.PermissionCreateElasticsearchPostAggregationJob.Id,
model.PermissionPurgeElasticsearchIndexes.Id,
},
})
// Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_FILE_STORAGE
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_FILE_STORAGE.Id),
Add: []string{model.PERMISSION_TEST_S3.Id},
On: permissionExists(model.PermissionSysconsoleWriteEnvironmentFileStorage.Id),
Add: []string{model.PermissionTestS3.Id},
})
return transformations, nil
@@ -790,27 +790,27 @@ func (a *App) getAddEnvironmentSubsectionPermissions() (permissionsMap, error) {
func (a *App) getAddAboutSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsAboutRead := []string{model.PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE.Id}
permissionsAboutWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE.Id}
permissionsAboutRead := []string{model.PermissionSysconsoleReadAboutEditionAndLicense.Id}
permissionsAboutWrite := []string{model.PermissionSysconsoleWriteAboutEditionAndLicense.Id}
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ABOUT.Id),
On: permissionExists(model.PermissionSysconsoleReadAbout.Id),
Add: permissionsAboutRead,
})
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ABOUT.Id),
On: permissionExists(model.PermissionSysconsoleWriteAbout.Id),
Add: permissionsAboutWrite,
})
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_ABOUT_EDITION_AND_LICENSE.Id),
Add: []string{model.PERMISSION_READ_LICENSE_INFORMATION.Id},
On: permissionExists(model.PermissionSysconsoleReadAboutEditionAndLicense.Id),
Add: []string{model.PermissionReadLicenseInformation.Id},
})
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ABOUT_EDITION_AND_LICENSE.Id),
Add: []string{model.PERMISSION_MANAGE_LICENSE_INFORMATION.Id},
On: permissionExists(model.PermissionSysconsoleWriteAboutEditionAndLicense.Id),
Add: []string{model.PermissionManageLicenseInformation.Id},
})
return transformations, nil
@@ -820,38 +820,38 @@ func (a *App) getAddReportingSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsReportingRead := []string{
model.PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id,
model.PERMISSION_SYSCONSOLE_READ_REPORTING_TEAM_STATISTICS.Id,
model.PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS.Id,
model.PermissionSysconsoleReadReportingSiteStatistics.Id,
model.PermissionSysconsoleReadReportingTeamStatistics.Id,
model.PermissionSysconsoleReadReportingServerLogs.Id,
}
permissionsReportingWrite := []string{
model.PERMISSION_SYSCONSOLE_WRITE_REPORTING_SITE_STATISTICS.Id,
model.PERMISSION_SYSCONSOLE_WRITE_REPORTING_TEAM_STATISTICS.Id,
model.PERMISSION_SYSCONSOLE_WRITE_REPORTING_SERVER_LOGS.Id,
model.PermissionSysconsoleWriteReportingSiteStatistics.Id,
model.PermissionSysconsoleWriteReportingTeamStatistics.Id,
model.PermissionSysconsoleWriteReportingServerLogs.Id,
}
// Give the new subsection READ permissions to any user with READ_REPORTING
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_REPORTING.Id),
On: permissionExists(model.PermissionSysconsoleReadReporting.Id),
Add: permissionsReportingRead,
})
// Give the new subsection WRITE permissions to any user with WRITE_REPORTING
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_REPORTING.Id),
On: permissionExists(model.PermissionSysconsoleWriteReporting.Id),
Add: permissionsReportingWrite,
})
// Give the ancillary permissions PERMISSION_GET_ANALYTICS to anyone with PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS or PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS
transformations = append(transformations, permissionTransformation{
On: permissionOr(permissionExists(model.PERMISSION_SYSCONSOLE_READ_USERMANAGEMENT_USERS.Id), permissionExists(model.PERMISSION_SYSCONSOLE_READ_REPORTING_SITE_STATISTICS.Id)),
Add: []string{model.PERMISSION_GET_ANALYTICS.Id},
On: permissionOr(permissionExists(model.PermissionSysconsoleReadUserManagementUsers.Id), permissionExists(model.PermissionSysconsoleReadReportingSiteStatistics.Id)),
Add: []string{model.PermissionGetAnalytics.Id},
})
// Give the ancillary permissions PERMISSION_GET_LOGS to anyone with PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_REPORTING_SERVER_LOGS.Id),
Add: []string{model.PERMISSION_GET_LOGS.Id},
On: permissionExists(model.PermissionSysconsoleReadReportingServerLogs.Id),
Add: []string{model.PermissionGetLogs.Id},
})
return transformations, nil
@@ -860,43 +860,43 @@ func (a *App) getAddReportingSubsectionPermissions() (permissionsMap, error) {
func (a *App) getAddAuthenticationSubsectionPermissions() (permissionsMap, error) {
transformations := []permissionTransformation{}
permissionsAuthenticationRead := []string{model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SIGNUP.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_EMAIL.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_PASSWORD.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_MFA.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_SAML.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_OPENID.Id, model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_GUEST_ACCESS.Id}
permissionsAuthenticationWrite := []string{model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SIGNUP.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_PASSWORD.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_MFA.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_OPENID.Id, model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_GUEST_ACCESS.Id}
permissionsAuthenticationRead := []string{model.PermissionSysconsoleReadAuthenticationSignup.Id, model.PermissionSysconsoleReadAuthenticationEmail.Id, model.PermissionSysconsoleReadAuthenticationPassword.Id, model.PermissionSysconsoleReadAuthenticationMfa.Id, model.PermissionSysconsoleReadAuthenticationLdap.Id, model.PermissionSysconsoleReadAuthenticationSaml.Id, model.PermissionSysconsoleReadAuthenticationOpenid.Id, model.PermissionSysconsoleReadAuthenticationGuestAccess.Id}
permissionsAuthenticationWrite := []string{model.PermissionSysconsoleWriteAuthenticationSignup.Id, model.PermissionSysconsoleWriteAuthenticationEmail.Id, model.PermissionSysconsoleWriteAuthenticationPassword.Id, model.PermissionSysconsoleWriteAuthenticationMfa.Id, model.PermissionSysconsoleWriteAuthenticationLdap.Id, model.PermissionSysconsoleWriteAuthenticationSaml.Id, model.PermissionSysconsoleWriteAuthenticationOpenid.Id, model.PermissionSysconsoleWriteAuthenticationGuestAccess.Id}
// Give the new subsection READ permissions to any user with READ_AUTHENTICATION
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION.Id),
On: permissionExists(model.PermissionSysconsoleReadAuthentication.Id),
Add: permissionsAuthenticationRead,
})
// Give the new subsection WRITE permissions to any user with WRITE_AUTHENTICATION
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION.Id),
On: permissionExists(model.PermissionSysconsoleWriteAuthentication.Id),
Add: permissionsAuthenticationWrite,
})
// Give the ancillary permissions for LDAP to anyone with WRITE_AUTHENTICATION_LDAP
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_LDAP.Id),
Add: []string{model.PERMISSION_CREATE_LDAP_SYNC_JOB.Id, model.PERMISSION_TEST_LDAP.Id, model.PERMISSION_ADD_LDAP_PUBLIC_CERT.Id, model.PERMISSION_ADD_LDAP_PRIVATE_CERT.Id, model.PERMISSION_REMOVE_LDAP_PUBLIC_CERT.Id, model.PERMISSION_REMOVE_LDAP_PRIVATE_CERT.Id},
On: permissionExists(model.PermissionSysconsoleWriteAuthenticationLdap.Id),
Add: []string{model.PermissionCreateLdapSyncJob.Id, model.PermissionTestLdap.Id, model.PermissionAddLdapPublicCert.Id, model.PermissionAddLdapPrivateCert.Id, model.PermissionRemoveLdapPublicCert.Id, model.PermissionRemoveLdapPrivateCert.Id},
})
// Give the ancillary permissions PERMISSION_TEST_LDAP to anyone with READ_AUTHENTICATION_LDAP
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_READ_AUTHENTICATION_LDAP.Id),
Add: []string{model.PERMISSION_READ_LDAP_SYNC_JOB.Id},
On: permissionExists(model.PermissionSysconsoleReadAuthenticationLdap.Id),
Add: []string{model.PermissionReadLdapSyncJob.Id},
})
// Give the ancillary permissions PERMISSION_INVALIDATE_EMAIL_INVITE to anyone with WRITE_AUTHENTICATION_EMAIL
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_EMAIL.Id),
Add: []string{model.PERMISSION_INVALIDATE_EMAIL_INVITE.Id},
On: permissionExists(model.PermissionSysconsoleWriteAuthenticationEmail.Id),
Add: []string{model.PermissionInvalidateEmailInvite.Id},
})
// Give the ancillary permissions for SAML to anyone with WRITE_AUTHENTICATION_SAML
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_AUTHENTICATION_SAML.Id),
Add: []string{model.PERMISSION_GET_SAML_METADATA_FROM_IDP.Id, model.PERMISSION_ADD_SAML_PUBLIC_CERT.Id, model.PERMISSION_ADD_SAML_PRIVATE_CERT.Id, model.PERMISSION_ADD_SAML_IDP_CERT.Id, model.PERMISSION_REMOVE_SAML_PUBLIC_CERT.Id, model.PERMISSION_REMOVE_SAML_PRIVATE_CERT.Id, model.PERMISSION_REMOVE_SAML_IDP_CERT.Id, model.PERMISSION_GET_SAML_CERT_STATUS.Id},
On: permissionExists(model.PermissionSysconsoleWriteAuthenticationSaml.Id),
Add: []string{model.PermissionGetSamlMetadataFromIdp.Id, model.PermissionAddSamlPublicCert.Id, model.PermissionAddSamlPrivateCert.Id, model.PermissionAddSamlIdpCert.Id, model.PermissionRemoveSamlPublicCert.Id, model.PermissionRemoveSamlPrivateCert.Id, model.PermissionRemoveSamlIdpCert.Id, model.PermissionGetSamlCertStatus.Id},
})
return transformations, nil
@@ -908,8 +908,8 @@ func (a *App) getAddTestEmailAncillaryPermission() (permissionsMap, error) {
// Give these ancillary permissions to anyone with WRITE_ENVIRONMENT_SMTP
transformations = append(transformations, permissionTransformation{
On: permissionExists(model.PERMISSION_SYSCONSOLE_WRITE_ENVIRONMENT_SMTP.Id),
Add: []string{model.PERMISSION_TEST_EMAIL.Id},
On: permissionExists(model.PermissionSysconsoleWriteEnvironmentSmtp.Id),
Add: []string{model.PermissionTestEmail.Id},
})
return transformations, nil
@@ -926,33 +926,33 @@ func (s *Server) doPermissionsMigrations() error {
Key string
Migration func() (permissionsMap, error)
}{
{Key: model.MIGRATION_KEY_EMOJI_PERMISSIONS_SPLIT, Migration: a.getEmojisPermissionsSplitMigration},
{Key: model.MIGRATION_KEY_WEBHOOK_PERMISSIONS_SPLIT, Migration: a.getWebhooksPermissionsSplitMigration},
{Key: model.MIGRATION_KEY_LIST_JOIN_PUBLIC_PRIVATE_TEAMS, Migration: a.getListJoinPublicPrivateTeamsPermissionsMigration},
{Key: model.MIGRATION_KEY_REMOVE_PERMANENT_DELETE_USER, Migration: a.removePermanentDeleteUserMigration},
{Key: model.MIGRATION_KEY_ADD_BOT_PERMISSIONS, Migration: a.getAddBotPermissionsMigration},
{Key: model.MIGRATION_KEY_APPLY_CHANNEL_MANAGE_DELETE_TO_CHANNEL_USER, Migration: a.applyChannelManageDeleteToChannelUser},
{Key: model.MIGRATION_KEY_REMOVE_CHANNEL_MANAGE_DELETE_FROM_TEAM_USER, Migration: a.removeChannelManageDeleteFromTeamUser},
{Key: model.MIGRATION_KEY_VIEW_MEMBERS_NEW_PERMISSION, Migration: a.getViewMembersPermissionMigration},
{Key: model.MIGRATION_KEY_ADD_MANAGE_GUESTS_PERMISSIONS, Migration: a.getAddManageGuestsPermissionsMigration},
{Key: model.MIGRATION_KEY_CHANNEL_MODERATIONS_PERMISSIONS, Migration: a.channelModerationPermissionsMigration},
{Key: model.MIGRATION_KEY_ADD_USE_GROUP_MENTIONS_PERMISSION, Migration: a.getAddUseGroupMentionsPermissionMigration},
{Key: model.MIGRATION_KEY_ADD_SYSTEM_CONSOLE_PERMISSIONS, Migration: a.getAddSystemConsolePermissionsMigration},
{Key: model.MIGRATION_KEY_ADD_CONVERT_CHANNEL_PERMISSIONS, Migration: a.getAddConvertChannelPermissionsMigration},
{Key: model.MIGRATION_KEY_ADD_MANAGE_SHARED_CHANNEL_PERMISSIONS, Migration: a.getAddManageSharedChannelsPermissionsMigration},
{Key: model.MIGRATION_KEY_ADD_MANAGE_SECURE_CONNECTIONS_PERMISSIONS, Migration: a.getAddManageSecureConnectionsPermissionsMigration},
{Key: model.MIGRATION_KEY_ADD_SYSTEM_ROLES_PERMISSIONS, Migration: a.getSystemRolesPermissionsMigration},
{Key: model.MIGRATION_KEY_ADD_BILLING_PERMISSIONS, Migration: a.getBillingPermissionsMigration},
{Key: model.MIGRATION_KEY_ADD_DOWNLOAD_COMPLIANCE_EXPORT_RESULTS, Migration: a.getAddDownloadComplianceExportResult},
{Key: model.MIGRATION_KEY_ADD_EXPERIMENTAL_SUBSECTION_PERMISSIONS, Migration: a.getAddExperimentalSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_AUTHENTICATION_SUBSECTION_PERMISSIONS, Migration: a.getAddAuthenticationSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_INTEGRATIONS_SUBSECTION_PERMISSIONS, Migration: a.getAddIntegrationsSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_SITE_SUBSECTION_PERMISSIONS, Migration: a.getAddSiteSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_COMPLIANCE_SUBSECTION_PERMISSIONS, Migration: a.getAddComplianceSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_ENVIRONMENT_SUBSECTION_PERMISSIONS, Migration: a.getAddEnvironmentSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_ABOUT_SUBSECTION_PERMISSIONS, Migration: a.getAddAboutSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_REPORTING_SUBSECTION_PERMISSIONS, Migration: a.getAddReportingSubsectionPermissions},
{Key: model.MIGRATION_KEY_ADD_TEST_EMAIL_ANCILLARY_PERMISSION, Migration: a.getAddTestEmailAncillaryPermission},
{Key: model.MigrationKeyEmojiPermissionsSplit, Migration: a.getEmojisPermissionsSplitMigration},
{Key: model.MigrationKeyWebhookPermissionsSplit, Migration: a.getWebhooksPermissionsSplitMigration},
{Key: model.MigrationKeyListJoinPublicPrivateTeams, Migration: a.getListJoinPublicPrivateTeamsPermissionsMigration},
{Key: model.MigrationKeyRemovePermanentDeleteUser, Migration: a.removePermanentDeleteUserMigration},
{Key: model.MigrationKeyAddBotPermissions, Migration: a.getAddBotPermissionsMigration},
{Key: model.MigrationKeyApplyChannelManageDeleteToChannelUser, Migration: a.applyChannelManageDeleteToChannelUser},
{Key: model.MigrationKeyRemoveChannelManageDeleteFromTeamUser, Migration: a.removeChannelManageDeleteFromTeamUser},
{Key: model.MigrationKeyViewMembersNewPermission, Migration: a.getViewMembersPermissionMigration},
{Key: model.MigrationKeyAddManageGuestsPermissions, Migration: a.getAddManageGuestsPermissionsMigration},
{Key: model.MigrationKeyChannelModerationsPermissions, Migration: a.channelModerationPermissionsMigration},
{Key: model.MigrationKeyAddUseGroupMentionsPermission, Migration: a.getAddUseGroupMentionsPermissionMigration},
{Key: model.MigrationKeyAddSystemConsolePermissions, Migration: a.getAddSystemConsolePermissionsMigration},
{Key: model.MigrationKeyAddConvertChannelPermissions, Migration: a.getAddConvertChannelPermissionsMigration},
{Key: model.MigrationKeyAddManageSharedChannelPermissions, Migration: a.getAddManageSharedChannelsPermissionsMigration},
{Key: model.MigrationKeyAddManageSecureConnectionsPermissions, Migration: a.getAddManageSecureConnectionsPermissionsMigration},
{Key: model.MigrationKeyAddSystemRolesPermissions, Migration: a.getSystemRolesPermissionsMigration},
{Key: model.MigrationKeyAddBillingPermissions, Migration: a.getBillingPermissionsMigration},
{Key: model.MigrationKeyAddDownloadComplianceExportResults, Migration: a.getAddDownloadComplianceExportResult},
{Key: model.MigrationKeyAddExperimentalSubsectionPermissions, Migration: a.getAddExperimentalSubsectionPermissions},
{Key: model.MigrationKeyAddAuthenticationSubsectionPermissions, Migration: a.getAddAuthenticationSubsectionPermissions},
{Key: model.MigrationKeyAddIntegrationsSubsectionPermissions, Migration: a.getAddIntegrationsSubsectionPermissions},
{Key: model.MigrationKeyAddSiteSubsectionPermissions, Migration: a.getAddSiteSubsectionPermissions},
{Key: model.MigrationKeyAddComplianceSubsectionPermissions, Migration: a.getAddComplianceSubsectionPermissions},
{Key: model.MigrationKeyAddEnvironmentSubsectionPermissions, Migration: a.getAddEnvironmentSubsectionPermissions},
{Key: model.MigrationKeyAddAboutSubsectionPermissions, Migration: a.getAddAboutSubsectionPermissions},
{Key: model.MigrationKeyAddReportingSubsectionPermissions, Migration: a.getAddReportingSubsectionPermissions},
{Key: model.MigrationKeyAddTestEmailAncillaryPermission, Migration: a.getAddTestEmailAncillaryPermission},
}
roles, err := s.Store.Role().GetAll()

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

@@ -99,7 +99,7 @@ func TestImportPermissions(t *testing.T) {
name := model.NewId()
displayName := model.NewId()
description := "my test description"
scope := model.SCHEME_SCOPE_CHANNEL
scope := model.SchemeScopeChannel
roleName1 := model.NewId()
roleName2 := model.NewId()
@@ -179,7 +179,7 @@ func TestImportPermissions_idempotentScheme(t *testing.T) {
name := model.NewId()
displayName := model.NewId()
description := "my test description"
scope := model.SCHEME_SCOPE_CHANNEL
scope := model.SchemeScopeChannel
roleName1 := model.NewId()
roleName2 := model.NewId()
@@ -191,7 +191,7 @@ func TestImportPermissions_idempotentScheme(t *testing.T) {
var expected int
withMigrationMarkedComplete(th, func() {
var appErr *model.AppError
results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100)
results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100)
if appErr != nil {
panic(appErr)
}
@@ -202,7 +202,7 @@ func TestImportPermissions_idempotentScheme(t *testing.T) {
t.Error(err)
}
results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100)
results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100)
if appErr != nil {
panic(appErr)
}
@@ -233,7 +233,7 @@ func TestImportPermissions_schemeDeletedOnRoleFailure(t *testing.T) {
var expected int
withMigrationMarkedComplete(th, func() {
var appErr *model.AppError
results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100)
results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100)
if appErr != nil {
panic(appErr)
}
@@ -244,7 +244,7 @@ func TestImportPermissions_schemeDeletedOnRoleFailure(t *testing.T) {
t.Error(err)
}
results, appErr = th.App.GetSchemes(model.SCHEME_SCOPE_CHANNEL, 0, 100)
results, appErr = th.App.GetSchemes(model.SchemeScopeChannel, 0, 100)
if appErr != nil {
panic(appErr)
}
@@ -261,30 +261,30 @@ func TestMigration(t *testing.T) {
th := Setup(t)
defer th.TearDown()
role, err := th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
role, err := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId)
require.Nil(t, err)
assert.Contains(t, role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id)
assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_EMOJIS.Id)
assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_OTHERS_EMOJIS.Id)
assert.Contains(t, role.Permissions, model.PERMISSION_USE_GROUP_MENTIONS.Id)
assert.Contains(t, role.Permissions, model.PermissionCreateEmojis.Id)
assert.Contains(t, role.Permissions, model.PermissionDeleteEmojis.Id)
assert.Contains(t, role.Permissions, model.PermissionDeleteOthersEmojis.Id)
assert.Contains(t, role.Permissions, model.PermissionUseGroupMentions.Id)
th.App.ResetPermissionsSystem()
role, err = th.App.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
role, err = th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId)
require.Nil(t, err)
assert.Contains(t, role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id)
assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_EMOJIS.Id)
assert.Contains(t, role.Permissions, model.PERMISSION_DELETE_OTHERS_EMOJIS.Id)
assert.Contains(t, role.Permissions, model.PERMISSION_USE_GROUP_MENTIONS.Id)
assert.Contains(t, role.Permissions, model.PermissionCreateEmojis.Id)
assert.Contains(t, role.Permissions, model.PermissionDeleteEmojis.Id)
assert.Contains(t, role.Permissions, model.PermissionDeleteOthersEmojis.Id)
assert.Contains(t, role.Permissions, model.PermissionUseGroupMentions.Id)
}
func withMigrationMarkedComplete(th *TestHelper, f func()) {
// Mark the migration as done.
th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
th.App.Srv().Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2)
th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"})
// Un-mark the migration at the end of the test.
defer func() {
th.App.Srv().Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2)
}()
f()
}

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

@@ -127,7 +127,7 @@ func (s *Server) syncPluginsActiveState() {
deactivated := pluginsEnvironment.Deactivate(plugin.Manifest.Id)
if deactivated && plugin.Manifest.HasClient() {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_DISABLED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventPluginDisabled, "", "", "", nil)
message.Add("manifest", plugin.Manifest.ClientManifest())
s.Publish(message)
}
@@ -803,7 +803,7 @@ func (s *Server) notifyPluginEnabled(manifest *model.Manifest) error {
}
// Notify all cluster peer clients.
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_ENABLED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventPluginEnabled, "", "", "", nil)
message.Add("manifest", manifest.ClientManifest())
s.Publish(message)
@@ -823,7 +823,7 @@ func (s *Server) getPluginsFromFilePaths(fileStorePaths []string) map[string]*pl
pluginSignaturePathMap := make(map[string]*pluginSignaturePath)
fsPrefix := ""
if *s.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
if *s.Config().FileSettings.DriverName == model.ImageDriverS3 {
ptr := s.Config().FileSettings.AmazonS3PathPrefix
if ptr != nil && *ptr != "" {
fsPrefix = *ptr + "/"

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

@@ -315,13 +315,13 @@ func (api *PluginAPI) GetUserStatusesByIds(userIDs []string) ([]*model.Status, *
func (api *PluginAPI) UpdateUserStatus(userID, status string) (*model.Status, *model.AppError) {
switch status {
case model.STATUS_ONLINE:
case model.StatusOnline:
api.app.SetStatusOnline(userID, true)
case model.STATUS_OFFLINE:
case model.StatusOffline:
api.app.SetStatusOffline(userID, true)
case model.STATUS_AWAY:
case model.StatusAway:
api.app.SetStatusAwayIfNeeded(userID, true)
case model.STATUS_DND:
case model.StatusDnd:
api.app.SetStatusDoNotDisturb(userID)
default:
return nil, model.NewAppError("UpdateUserStatus", "plugin.api.update_user_status.bad_status", nil, "unrecognized status", http.StatusBadRequest)
@@ -340,13 +340,13 @@ func (api *PluginAPI) SetUserStatusTimedDND(userID string, endTime int64) (*mode
func (api *PluginAPI) GetUsersInChannel(channelID, sortBy string, page, perPage int) ([]*model.User, *model.AppError) {
switch sortBy {
case model.CHANNEL_SORT_BY_USERNAME:
case model.ChannelSortByUsername:
return api.app.GetUsersInChannel(&model.UserGetOptions{
InChannelId: channelID,
Page: page,
PerPage: perPage,
})
case model.CHANNEL_SORT_BY_STATUS:
case model.ChannelSortByStatus:
return api.app.GetUsersInChannelByStatus(&model.UserGetOptions{
InChannelId: channelID,
Page: page,
@@ -372,8 +372,8 @@ func (api *PluginAPI) GetLDAPUserAttributes(userID string, attributes []string)
}
// Only bother running the query if the user's auth service is LDAP or it's SAML and sync is enabled.
if user.AuthService == model.USER_AUTH_SERVICE_LDAP ||
(user.AuthService == model.USER_AUTH_SERVICE_SAML && *api.app.Config().SamlSettings.EnableSyncWithLdap) {
if user.AuthService == model.UserAuthServiceLdap ||
(user.AuthService == model.UserAuthServiceSaml && *api.app.Config().SamlSettings.EnableSyncWithLdap) {
return api.app.Ldap().GetUserAttributes(*user.AuthData, attributes)
}
@@ -1116,7 +1116,7 @@ func (api *PluginAPI) UpdateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *mod
return nil, err
}
return api.app.UpdateOauthApp(oldApp, app)
return api.app.UpdateOAuthApp(oldApp, app)
}
func (api *PluginAPI) DeleteOAuthApp(appID string) *model.AppError {
@@ -1132,7 +1132,7 @@ func (api *PluginAPI) PublishPluginClusterEvent(ev model.PluginClusterEvent,
}
msg := &model.ClusterMessage{
Event: model.CLUSTER_EVENT_PLUGIN_EVENT,
Event: model.ClusterEventPluginEvent,
SendType: opts.SendType,
WaitForAllToSend: false,
Props: map[string]string{
@@ -1175,7 +1175,7 @@ func (api *PluginAPI) RequestTrialLicense(requesterID string, users int, termsAc
trialLicenseRequest := &model.TrialLicenseRequest{
ServerID: api.app.TelemetryId(),
Name: requester.GetDisplayName(model.SHOW_FULLNAME),
Name: requester.GetDisplayName(model.ShowFullName),
Email: requester.Email,
SiteName: *api.app.Config().TeamSettings.SiteName,
SiteURL: *api.app.Config().ServiceSettings.SiteURL,

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

@@ -180,7 +180,7 @@ func TestPluginAPIGetUserPreferences(t *testing.T) {
assert.Equal(t, 1, len(preferences))
assert.Equal(t, user1.Id, preferences[0].UserId)
assert.Equal(t, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, preferences[0].Category)
assert.Equal(t, model.PreferenceCategoryTutorialSteps, preferences[0].Category)
assert.Equal(t, user1.Id, preferences[0].Name)
assert.Equal(t, "0", preferences[0].Value)
}
@@ -219,7 +219,7 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) {
preference := model.Preference{
Name: user2.Id,
UserId: user2.Id,
Category: model.PREFERENCE_CATEGORY_THEME,
Category: model.PreferenceCategoryTheme,
Value: `{"color": "#ff0000", "color2": "#faf"}`,
}
err = api.UpdatePreferencesForUser(user2.Id, []model.Preference{preference})
@@ -234,7 +234,7 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) {
preferences, err = api.GetPreferencesForUser(user2.Id)
require.Nil(t, err)
assert.Equal(t, 1, len(preferences))
assert.Equal(t, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, preferences[0].Category)
assert.Equal(t, model.PreferenceCategoryTutorialSteps, preferences[0].Category)
}
func TestPluginAPIUpdateUserPreferences(t *testing.T) {
@@ -254,14 +254,14 @@ func TestPluginAPIUpdateUserPreferences(t *testing.T) {
require.Nil(t, err)
assert.Equal(t, 1, len(preferences))
assert.Equal(t, user1.Id, preferences[0].UserId)
assert.Equal(t, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, preferences[0].Category)
assert.Equal(t, model.PreferenceCategoryTutorialSteps, preferences[0].Category)
assert.Equal(t, user1.Id, preferences[0].Name)
assert.Equal(t, "0", preferences[0].Value)
preference := model.Preference{
Name: user1.Id,
UserId: user1.Id,
Category: model.PREFERENCE_CATEGORY_THEME,
Category: model.PreferenceCategoryTheme,
Value: `{"color": "#ff0000", "color2": "#faf"}`,
}
@@ -272,12 +272,12 @@ func TestPluginAPIUpdateUserPreferences(t *testing.T) {
require.Nil(t, err)
assert.Equal(t, 2, len(preferences))
expectedCategories := []string{model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, model.PREFERENCE_CATEGORY_THEME}
expectedCategories := []string{model.PreferenceCategoryTutorialSteps, model.PreferenceCategoryTheme}
for _, pref := range preferences {
assert.Contains(t, expectedCategories, pref.Category)
assert.Equal(t, user1.Id, pref.UserId)
assert.Equal(t, user1.Id, pref.Name)
if pref.Category == model.PREFERENCE_CATEGORY_TUTORIAL_STEPS {
if pref.Category == model.PreferenceCategoryTutorialSteps {
assert.Equal(t, "0", pref.Value)
} else {
newTheme, _ := json.Marshal(map[string]string{"color": "#ff0000", "color2": "#faf"})
@@ -586,7 +586,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) {
t.Run("get file infos filtered by channel ordered by created at descending", func(t *testing.T) {
fileInfos, err := api.GetFileInfos(0, 5, &model.GetFileInfosOptions{
ChannelIds: []string{th.BasicChannel.Id},
SortBy: model.FILEINFO_SORT_BY_CREATED,
SortBy: model.FileinfoSortByCreated,
SortDescending: true,
})
require.Nil(t, err)
@@ -1316,33 +1316,33 @@ func TestPluginAPIGetConfig(t *testing.T) {
config := api.GetConfig()
if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" {
assert.Equal(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING)
assert.Equal(t, *config.LdapSettings.BindPassword, model.FakeSetting)
}
assert.Equal(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING)
assert.Equal(t, *config.FileSettings.PublicLinkSalt, model.FakeSetting)
if *config.FileSettings.AmazonS3SecretAccessKey != "" {
assert.Equal(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING)
assert.Equal(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FakeSetting)
}
if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" {
assert.Equal(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING)
assert.Equal(t, *config.EmailSettings.SMTPPassword, model.FakeSetting)
}
if *config.GitLabSettings.Secret != "" {
assert.Equal(t, *config.GitLabSettings.Secret, model.FAKE_SETTING)
assert.Equal(t, *config.GitLabSettings.Secret, model.FakeSetting)
}
assert.Equal(t, *config.SqlSettings.DataSource, model.FAKE_SETTING)
assert.Equal(t, *config.SqlSettings.AtRestEncryptKey, model.FAKE_SETTING)
assert.Equal(t, *config.ElasticsearchSettings.Password, model.FAKE_SETTING)
assert.Equal(t, *config.SqlSettings.DataSource, model.FakeSetting)
assert.Equal(t, *config.SqlSettings.AtRestEncryptKey, model.FakeSetting)
assert.Equal(t, *config.ElasticsearchSettings.Password, model.FakeSetting)
for i := range config.SqlSettings.DataSourceReplicas {
assert.Equal(t, config.SqlSettings.DataSourceReplicas[i], model.FAKE_SETTING)
assert.Equal(t, config.SqlSettings.DataSourceReplicas[i], model.FakeSetting)
}
for i := range config.SqlSettings.DataSourceSearchReplicas {
assert.Equal(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FAKE_SETTING)
assert.Equal(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FakeSetting)
}
}
@@ -1353,33 +1353,33 @@ func TestPluginAPIGetUnsanitizedConfig(t *testing.T) {
config := api.GetUnsanitizedConfig()
if config.LdapSettings.BindPassword != nil && *config.LdapSettings.BindPassword != "" {
assert.NotEqual(t, *config.LdapSettings.BindPassword, model.FAKE_SETTING)
assert.NotEqual(t, *config.LdapSettings.BindPassword, model.FakeSetting)
}
assert.NotEqual(t, *config.FileSettings.PublicLinkSalt, model.FAKE_SETTING)
assert.NotEqual(t, *config.FileSettings.PublicLinkSalt, model.FakeSetting)
if *config.FileSettings.AmazonS3SecretAccessKey != "" {
assert.NotEqual(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FAKE_SETTING)
assert.NotEqual(t, *config.FileSettings.AmazonS3SecretAccessKey, model.FakeSetting)
}
if config.EmailSettings.SMTPPassword != nil && *config.EmailSettings.SMTPPassword != "" {
assert.NotEqual(t, *config.EmailSettings.SMTPPassword, model.FAKE_SETTING)
assert.NotEqual(t, *config.EmailSettings.SMTPPassword, model.FakeSetting)
}
if *config.GitLabSettings.Secret != "" {
assert.NotEqual(t, *config.GitLabSettings.Secret, model.FAKE_SETTING)
assert.NotEqual(t, *config.GitLabSettings.Secret, model.FakeSetting)
}
assert.NotEqual(t, *config.SqlSettings.DataSource, model.FAKE_SETTING)
assert.NotEqual(t, *config.SqlSettings.AtRestEncryptKey, model.FAKE_SETTING)
assert.NotEqual(t, *config.ElasticsearchSettings.Password, model.FAKE_SETTING)
assert.NotEqual(t, *config.SqlSettings.DataSource, model.FakeSetting)
assert.NotEqual(t, *config.SqlSettings.AtRestEncryptKey, model.FakeSetting)
assert.NotEqual(t, *config.ElasticsearchSettings.Password, model.FakeSetting)
for i := range config.SqlSettings.DataSourceReplicas {
assert.NotEqual(t, config.SqlSettings.DataSourceReplicas[i], model.FAKE_SETTING)
assert.NotEqual(t, config.SqlSettings.DataSourceReplicas[i], model.FakeSetting)
}
for i := range config.SqlSettings.DataSourceSearchReplicas {
assert.NotEqual(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FAKE_SETTING)
assert.NotEqual(t, config.SqlSettings.DataSourceSearchReplicas[i], model.FakeSetting)
}
}
@@ -1712,7 +1712,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) {
defer wsc.Close()
resp := <-wsc.ResponseChannel
require.Equal(t, resp.Status, model.STATUS_OK)
require.Equal(t, resp.Status, model.StatusOk)
for i := 0; i < 10; i++ {
wsc.SendMessage("custom_action", map[string]interface{}{"value": i})
@@ -1722,7 +1722,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) {
case <-time.After(1 * time.Second):
}
require.NotNil(t, resp)
require.Equal(t, resp.Status, model.STATUS_OK)
require.Equal(t, resp.Status, model.StatusOk)
require.Equal(t, "custom_action", resp.Data["action"])
require.Equal(t, float64(i), resp.Data["value"])
}
@@ -1750,7 +1750,7 @@ func (mscp *MockSlashCommandProvider) DoCommand(a *App, c *request.Context, args
mscp.Message = message
return &model.CommandResponse{
Text: "mock",
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}

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

@@ -26,7 +26,7 @@ func (p *MyPlugin) OnConfigurationChange() error {
func (p *MyPlugin) MessageWillBePosted(_ *plugin.Context, _ *model.Post) (*model.Post, string) {
uid := p.configuration.BasicUserID
statuses := []string{model.STATUS_ONLINE, model.STATUS_AWAY, model.STATUS_DND, model.STATUS_OFFLINE}
statuses := []string{model.StatusOnline, model.StatusAway, model.StatusDnd, model.StatusOffline}
for _, s := range statuses {
status, err := p.API.UpdateUserStatus(uid, s)

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

@@ -78,7 +78,7 @@ func TestPluginCommand(t *testing.T) {
func (p *MyPlugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
Text: "text",
}, nil
}
@@ -93,7 +93,7 @@ func TestPluginCommand(t *testing.T) {
resp, err := th.App.ExecuteCommand(th.Context, args)
require.Nil(t, err)
require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType)
require.Equal(t, model.CommandResponseTypeEphemeral, resp.ResponseType)
require.Equal(t, "text", resp.Text)
err2 := th.App.DisablePlugin(pluginIDs[0])
@@ -172,7 +172,7 @@ func TestPluginCommand(t *testing.T) {
p.API.LogInfo("ExecuteCommand, saved plugin config")
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
Text: "text",
}, nil
}
@@ -196,7 +196,7 @@ func TestPluginCommand(t *testing.T) {
// Ignore if we kill below.
if !killed {
require.Nil(t, err)
require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType)
require.Equal(t, model.CommandResponseTypeEphemeral, resp.ResponseType)
require.Equal(t, "text", resp.Text)
}
}()
@@ -266,7 +266,7 @@ func TestPluginCommand(t *testing.T) {
func (p *MyPlugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
Text: "text",
}, nil
}
@@ -282,7 +282,7 @@ func TestPluginCommand(t *testing.T) {
args.Command = "/code"
resp, err := th.App.ExecuteCommand(th.Context, args)
require.Nil(t, err)
require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType)
require.Equal(t, model.CommandResponseTypeEphemeral, resp.ResponseType)
require.Equal(t, "text", resp.Text)
th.App.RemovePlugin(pluginIDs[0])

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

@@ -11,7 +11,7 @@ func (s *Server) notifyClusterPluginEvent(event string, data model.PluginEventDa
if s.Cluster != nil {
s.Cluster.SendClusterMessage(&model.ClusterMessage{
Event: event,
SendType: model.CLUSTER_SEND_RELIABLE,
SendType: model.ClusterSendReliable,
WaitForAllToSend: true,
Data: data.ToJson(),
})

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

@@ -170,7 +170,7 @@ func (s *Server) installPlugin(pluginFile, signature io.ReadSeeker, installation
}
s.notifyClusterPluginEvent(
model.CLUSTER_EVENT_INSTALL_PLUGIN,
model.ClusterEventInstallPlugin,
model.PluginEventData{
Id: manifest.Id,
},
@@ -444,7 +444,7 @@ func (s *Server) removePlugin(id string) *model.AppError {
}
s.notifyClusterPluginEvent(
model.CLUSTER_EVENT_REMOVE_PLUGIN,
model.ClusterEventRemovePlugin,
model.PluginEventData{
Id: id,
},

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

@@ -125,12 +125,12 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand
}
cookieAuth := false
authHeader := r.Header.Get(model.HEADER_AUTH)
if strings.HasPrefix(strings.ToUpper(authHeader), model.HEADER_BEARER+" ") {
token = authHeader[len(model.HEADER_BEARER)+1:]
} else if strings.HasPrefix(strings.ToLower(authHeader), model.HEADER_TOKEN+" ") {
token = authHeader[len(model.HEADER_TOKEN)+1:]
} else if cookie, _ := r.Cookie(model.SESSION_COOKIE_TOKEN); cookie != nil {
authHeader := r.Header.Get(model.HeaderAuth)
if strings.HasPrefix(strings.ToUpper(authHeader), model.HeaderBearer+" ") {
token = authHeader[len(model.HeaderBearer)+1:]
} else if strings.HasPrefix(strings.ToLower(authHeader), model.HeaderToken+" ") {
token = authHeader[len(model.HeaderToken)+1:]
} else if cookie, _ := r.Cookie(model.SessionCookieToken); cookie != nil {
token = cookie.Value
cookieAuth = true
} else {
@@ -150,14 +150,14 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand
if session != nil && err == nil && cookieAuth && r.Method != "GET" {
sentToken := ""
if r.Header.Get(model.HEADER_CSRF_TOKEN) == "" {
if r.Header.Get(model.HeaderCsrfToken) == "" {
bodyBytes, _ := ioutil.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
r.ParseForm()
sentToken = r.FormValue("csrf")
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
} else {
sentToken = r.Header.Get(model.HEADER_CSRF_TOKEN)
sentToken = r.Header.Get(model.HeaderCsrfToken)
}
expectedToken := session.GetCSRF()
@@ -167,7 +167,7 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand
}
// ToDo(DSchalla) 2019/01/04: Remove after deprecation period and only allow CSRF Header (MM-13657)
if r.Header.Get(model.HEADER_REQUESTED_WITH) == model.HEADER_REQUESTED_WITH_XML && !csrfCheckPassed {
if r.Header.Get(model.HeaderRequestedWith) == model.HeaderRequestedWithXml && !csrfCheckPassed {
csrfErrorMessage := "CSRF Check failed for request - Please migrate your plugin to either send a CSRF Header or Form Field, XMLHttpRequest is deprecated"
sid := ""
userID := ""
@@ -204,11 +204,11 @@ func (s *Server) servePluginRequest(w http.ResponseWriter, r *http.Request, hand
cookies := r.Cookies()
r.Header.Del("Cookie")
for _, c := range cookies {
if c.Name != model.SESSION_COOKIE_TOKEN {
if c.Name != model.SessionCookieToken {
r.AddCookie(c)
}
}
r.Header.Del(model.HEADER_AUTH)
r.Header.Del(model.HeaderAuth)
r.Header.Del("Referer")
params := mux.Vars(r)

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

@@ -99,7 +99,7 @@ func (s *Server) notifyPluginStatusesChanged() error {
}
// Notify any system admins.
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_STATUSES_CHANGED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventPluginStatusesChanged, "", "", "", nil)
message.Add("plugin_statuses", pluginStatuses)
message.GetBroadcast().ContainsSensitiveData = true
s.Publish(message)

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

@@ -476,7 +476,7 @@ func TestPluginSync(t *testing.T) {
{
"local",
func(cfg *model.Config) {
cfg.FileSettings.DriverName = model.NewString(model.IMAGE_DRIVER_LOCAL)
cfg.FileSettings.DriverName = model.NewString(model.ImageDriverLocal)
},
},
{
@@ -493,10 +493,10 @@ func TestPluginSync(t *testing.T) {
}
s3Endpoint := fmt.Sprintf("%s:%s", s3Host, s3Port)
cfg.FileSettings.DriverName = model.NewString(model.IMAGE_DRIVER_S3)
cfg.FileSettings.AmazonS3AccessKeyId = model.NewString(model.MINIO_ACCESS_KEY)
cfg.FileSettings.AmazonS3SecretAccessKey = model.NewString(model.MINIO_SECRET_KEY)
cfg.FileSettings.AmazonS3Bucket = model.NewString(model.MINIO_BUCKET)
cfg.FileSettings.DriverName = model.NewString(model.ImageDriverS3)
cfg.FileSettings.AmazonS3AccessKeyId = model.NewString(model.MinioAccessKey)
cfg.FileSettings.AmazonS3SecretAccessKey = model.NewString(model.MinioSecretKey)
cfg.FileSettings.AmazonS3Bucket = model.NewString(model.MinioBucket)
cfg.FileSettings.AmazonS3PathPrefix = model.NewString("")
cfg.FileSettings.AmazonS3Endpoint = model.NewString(s3Endpoint)
cfg.FileSettings.AmazonS3Region = model.NewString("")

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

@@ -37,7 +37,7 @@ func (a *App) CreatePostAsUser(c *request.Context, post *model.Post, currentSess
return nil, err
}
if strings.HasPrefix(post.Type, model.POST_SYSTEM_MESSAGE_PREFIX) {
if strings.HasPrefix(post.Type, model.PostSystemMessagePrefix) {
err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]interface{}{"Name": "post.type"}, "", http.StatusBadRequest)
return nil, err
}
@@ -211,13 +211,13 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch
if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly &&
!post.IsSystemMessage() &&
channel.Name == model.DEFAULT_CHANNEL &&
!a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) {
channel.Name == model.DefaultChannelName &&
!a.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) {
return nil, model.NewAppError("createPost", "api.post.create_post.town_square_read_only", nil, "", http.StatusForbidden)
}
var ephemeralPost *model.Post
if post.Type == "" && !a.HasPermissionToChannel(user.Id, channel.Id, model.PERMISSION_USE_CHANNEL_MENTIONS) {
if post.Type == "" && !a.HasPermissionToChannel(user.Id, channel.Id, model.PermissionUseChannelMentions) {
mention := post.DisableMentionHighlights()
if mention != "" {
T := i18n.GetUserTranslations(user.Locale)
@@ -227,7 +227,7 @@ func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Ch
ParentId: post.ParentId,
ChannelId: channel.Id,
Message: T("model.post.channel_notifications_disabled_in_channel.message", model.StringInterface{"ChannelName": channel.Name, "Mention": mention}),
Props: model.StringInterface{model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED: true},
Props: model.StringInterface{model.PostPropsMentionHighlightDisabled: true},
}
}
}
@@ -422,7 +422,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A
}
for _, mentioned := range mentionedChannels {
if mentioned.Type == model.CHANNEL_OPEN {
if mentioned.Type == model.ChannelTypeOpen {
team, err := a.Srv().Store.Team().Get(mentioned.TeamId)
if err != nil {
mlog.Warn("Failed to get team of the channel mention", mlog.String("team_id", channel.TeamId), mlog.String("channel_id", channel.Id), mlog.Err(err))
@@ -442,9 +442,9 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A
post.DelProp("channel_mentions")
}
matched := model.AT_MENTION_PATTEN.MatchString(post.Message)
if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) {
post.AddProp(model.POST_PROPS_GROUP_HIGHLIGHT_DISABLED, true)
matched := model.AtMentionPattern.MatchString(post.Message)
if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseGroupMentions) {
post.AddProp(model.PostPropsGroupHighlightDisabled, true)
}
return nil
@@ -470,7 +470,7 @@ func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model
return err
}
if post.Type != model.POST_AUTO_RESPONDER { // don't respond to an auto-responder
if post.Type != model.PostTypeAutoResponder { // don't respond to an auto-responder
a.Srv().Go(func() {
_, err := a.SendAutoResponseIfNecessary(c, channel, user, post)
if err != nil {
@@ -491,7 +491,7 @@ func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model
}
func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post {
post.Type = model.POST_EPHEMERAL
post.Type = model.PostTypeEphemeral
// fill in fields which haven't been specified which have sensible defaults
if post.Id == "" {
@@ -505,7 +505,7 @@ func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post {
}
post.GenerateActionIds()
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE, "", post.ChannelId, userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventEphemeralMessage, "", post.ChannelId, userID, nil)
post = a.PreparePostForClient(post, true, false)
post = model.AddPostActionCookies(post, a.PostActionCookieSecret())
message.Add("post", post.ToJson())
@@ -515,7 +515,7 @@ func (a *App) SendEphemeralPost(userID string, post *model.Post) *model.Post {
}
func (a *App) UpdateEphemeralPost(userID string, post *model.Post) *model.Post {
post.Type = model.POST_EPHEMERAL
post.Type = model.PostTypeEphemeral
post.UpdateAt = model.GetMillis()
if post.GetProps() == nil {
@@ -523,7 +523,7 @@ func (a *App) UpdateEphemeralPost(userID string, post *model.Post) *model.Post {
}
post.GenerateActionIds()
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_EDITED, "", post.ChannelId, userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventPostEdited, "", post.ChannelId, userID, nil)
post = a.PreparePostForClient(post, true, false)
post = model.AddPostActionCookies(post, a.PostActionCookieSecret())
message.Add("post", post.ToJson())
@@ -536,12 +536,12 @@ func (a *App) DeleteEphemeralPost(userID, postID string) {
post := &model.Post{
Id: postID,
UserId: userID,
Type: model.POST_EPHEMERAL,
Type: model.PostTypeEphemeral,
DeleteAt: model.GetMillis(),
UpdateAt: model.GetMillis(),
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_DELETED, "", "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventPostDeleted, "", "", userID, nil)
message.Add("post", post.ToJson())
a.Publish(message)
}
@@ -664,7 +664,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool)
// individually.
rpost.IsFollowing = nil
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_EDITED, "", rpost.ChannelId, "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventPostEdited, "", rpost.ChannelId, "", nil)
message.Add("post", rpost.ToJson())
a.Publish(message)
@@ -689,7 +689,7 @@ func (a *App) PatchPost(c *request.Context, postID string, patch *model.PostPatc
return nil, err
}
if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_CHANNEL_MENTIONS) {
if !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PermissionUseChannelMentions) {
patch.DisableMentionHighlights()
}
@@ -1058,12 +1058,12 @@ func (a *App) DeletePost(postID, deleteByID string) (*model.Post, *model.AppErro
postData := a.PreparePostForClient(post, false, false).ToJson()
userMessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_DELETED, "", post.ChannelId, "", nil)
userMessage := model.NewWebSocketEvent(model.WebsocketEventPostDeleted, "", post.ChannelId, "", nil)
userMessage.Add("post", postData)
userMessage.GetBroadcast().ContainsSanitizedData = true
a.Publish(userMessage)
adminMessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POST_DELETED, "", post.ChannelId, "", nil)
adminMessage := model.NewWebSocketEvent(model.WebsocketEventPostDeleted, "", post.ChannelId, "", nil)
adminMessage.Add("post", postData)
adminMessage.Add("delete_by", deleteByID)
adminMessage.GetBroadcast().ContainsSensitiveData = true
@@ -1082,7 +1082,7 @@ func (a *App) DeletePost(postID, deleteByID string) (*model.Post, *model.AppErro
}
func (a *App) DeleteFlaggedPosts(postID string) {
if err := a.Srv().Store.Preference().DeleteCategoryAndName(model.PREFERENCE_CATEGORY_FLAGGED_POST, postID); err != nil {
if err := a.Srv().Store.Preference().DeleteCategoryAndName(model.PreferenceCategoryFlaggedPost, postID); err != nil {
mlog.Warn("Unable to delete flagged post preference when deleting post.", mlog.Err(err))
return
}
@@ -1346,7 +1346,7 @@ func (a *App) ImageProxyRemover() (f func(string) string) {
func (s *Server) MaxPostSize() int {
maxPostSize := s.Store.Post().GetMaxPostSize()
if maxPostSize == 0 {
return model.POST_MESSAGE_MAX_RUNES_V1
return model.PostMessageMaxRunesV1
}
return maxPostSize
@@ -1367,7 +1367,7 @@ func (a *App) countThreadMentions(user *model.User, post *model.Post, teamID str
map[string][]string{},
user,
map[string]string{},
&model.Status{Status: model.STATUS_ONLINE}, // Assume the user is online since they would've triggered this
&model.Status{Status: model.StatusOnline}, // Assume the user is online since they would've triggered this
true, // Assume channel mentions are always allowed for simplicity
)
@@ -1378,7 +1378,7 @@ func (a *App) countThreadMentions(user *model.User, post *model.Post, teamID str
count := 0
if channel.Type == model.CHANNEL_DIRECT {
if channel.Type == model.ChannelTypeDirect {
// In a DM channel, every post made by the other user is a mention
otherId := channel.GetOtherUserIdForDM(user.Id)
for _, p := range posts {
@@ -1424,7 +1424,7 @@ func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, in
return 0, 0, err
}
if channel.Type == model.CHANNEL_DIRECT {
if channel.Type == model.ChannelTypeDirect {
// In a DM channel, every post made by the other user is a mention
count, countRoot, nErr := a.Srv().Store.Channel().CountPostsAfter(post.ChannelId, post.CreateAt-1, channel.GetOtherUserIdForDM(user.Id))
if nErr != nil {
@@ -1443,11 +1443,11 @@ func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, in
map[string][]string{},
user,
channelMember.NotifyProps,
&model.Status{Status: model.STATUS_ONLINE}, // Assume the user is online since they would've triggered this
&model.Status{Status: model.StatusOnline}, // Assume the user is online since they would've triggered this
true, // Assume channel mentions are always allowed for simplicity
)
commentMentions := user.NotifyProps[model.COMMENTS_NOTIFY_PROP]
checkForCommentMentions := commentMentions == model.COMMENTS_NOTIFY_ROOT || commentMentions == model.COMMENTS_NOTIFY_ANY
commentMentions := user.NotifyProps[model.CommentsNotifyProp]
checkForCommentMentions := commentMentions == model.CommentsNotifyRoot || commentMentions == model.CommentsNotifyAny
// A mapping of thread root IDs to whether or not a post in that thread mentions the user
mentionedByThread := make(map[string]bool)
@@ -1513,7 +1513,7 @@ func isCommentMention(user *model.User, post *model.Post, otherPosts map[string]
mentioned := otherPosts[post.RootId].UserId == user.Id
// Or because they commented on it before this post
if !mentioned && user.NotifyProps[model.COMMENTS_NOTIFY_PROP] == model.COMMENTS_NOTIFY_ANY {
if !mentioned && user.NotifyProps[model.CommentsNotifyProp] == model.CommentsNotifyAny {
for _, otherPost := range otherPosts {
if otherPost.Id == post.Id {
continue
@@ -1548,8 +1548,8 @@ func isPostMention(user *model.User, post *model.Post, keywords map[string][]str
}
// Check for mentions caused by being added to the channel
if post.Type == model.POST_ADD_TO_CHANNEL {
if addedUserId, ok := post.GetProp(model.POST_PROPS_ADDED_USER_ID).(string); ok && addedUserId == user.Id {
if post.Type == model.PostTypeAddToChannel {
if addedUserId, ok := post.GetProp(model.PostPropsAddedUserId).(string); ok && addedUserId == user.Id {
return true
}
}

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

@@ -68,7 +68,7 @@ func (a *App) PreparePostListForClient(originalList *model.PostList) *model.Post
// OverrideIconURLIfEmoji changes the post icon override URL prop, if it has an emoji icon,
// so that it points to the URL (relative) of the emoji - static if emoji is default, /api if custom.
func (a *App) OverrideIconURLIfEmoji(post *model.Post) {
prop, ok := post.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI]
prop, ok := post.GetProps()[model.PostPropsOverrideIconEmoji]
if !ok || prop == nil {
return
}
@@ -85,7 +85,7 @@ func (a *App) OverrideIconURLIfEmoji(post *model.Post) {
emojiName = strings.ReplaceAll(emojiName, ":", "")
if emojiUrl, err := a.GetEmojiStaticUrl(emojiName); err == nil {
post.AddProp(model.POST_PROPS_OVERRIDE_ICON_URL, emojiUrl)
post.AddProp(model.PostPropsOverrideIconUrl, emojiUrl)
} else {
mlog.Warn("Failed to retrieve URL for overridden profile icon (emoji)", mlog.String("emojiName", emojiName), mlog.Err(err))
}
@@ -167,7 +167,7 @@ func (a *App) getEmojisAndReactionsForPost(post *model.Post) ([]*model.Emoji, []
func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool) (*model.PostEmbed, error) {
if _, ok := post.GetProps()["attachments"]; ok {
return &model.PostEmbed{
Type: model.POST_EMBED_MESSAGE_ATTACHMENT,
Type: model.PostEmbedMessageAttachment,
}, nil
}
@@ -182,7 +182,7 @@ func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool
if og != nil {
return &model.PostEmbed{
Type: model.POST_EMBED_OPENGRAPH,
Type: model.PostEmbedOpengraph,
URL: firstLink,
Data: og,
}, nil
@@ -191,13 +191,13 @@ func (a *App) getEmbedForPost(post *model.Post, firstLink string, isNewPost bool
if image != nil {
// Note that we're not passing the image info here since it'll be part of the PostMetadata.Images field
return &model.PostEmbed{
Type: model.POST_EMBED_IMAGE,
Type: model.PostEmbedImage,
URL: firstLink,
}, nil
}
return &model.PostEmbed{
Type: model.POST_EMBED_LINK,
Type: model.PostEmbedLink,
URL: firstLink,
}, nil
}
@@ -207,14 +207,14 @@ func (a *App) getImagesForPost(post *model.Post, imageURLs []string, isNewPost b
for _, embed := range post.Metadata.Embeds {
switch embed.Type {
case model.POST_EMBED_IMAGE:
case model.PostEmbedImage:
// These dimensions will generally be cached by a previous call to getEmbedForPost
imageURLs = append(imageURLs, embed.URL)
case model.POST_EMBED_MESSAGE_ATTACHMENT:
case model.PostEmbedMessageAttachment:
imageURLs = append(imageURLs, a.getImagesInMessageAttachments(post)...)
case model.POST_EMBED_OPENGRAPH:
case model.PostEmbedOpengraph:
for _, image := range embed.Data.(*opengraph.OpenGraph).Images {
var imageURL string
if image.SecureURL != "" {
@@ -250,7 +250,7 @@ func (a *App) getImagesForPost(post *model.Post, imageURLs []string, isNewPost b
}
func getEmojiNamesForString(s string) []string {
names := model.EMOJI_PATTERN.FindAllString(s, -1)
names := model.EmojiPattern.FindAllString(s, -1)
for i, name := range names {
names[i] = strings.Trim(name, ":")
@@ -503,13 +503,13 @@ func (a *App) saveLinkMetadataToDatabase(requestURL string, timestamp int64, og
}
if og != nil {
metadata.Type = model.LINK_METADATA_TYPE_OPENGRAPH
metadata.Type = model.LinkMetadataTypeOpengraph
metadata.Data = og
} else if image != nil {
metadata.Type = model.LINK_METADATA_TYPE_IMAGE
metadata.Type = model.LinkMetadataTypeImage
metadata.Data = image
} else {
metadata.Type = model.LINK_METADATA_TYPE_NONE
metadata.Type = model.LinkMetadataTypeNone
}
_, err := a.Srv().Store.LinkMetadata().Save(metadata)

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

@@ -297,8 +297,8 @@ func TestPreparePostForClient(t *testing.T) {
require.Nil(t, err)
post.AddProp(model.POST_PROPS_OVERRIDE_ICON_URL, url)
post.AddProp(model.POST_PROPS_OVERRIDE_ICON_EMOJI, emoji)
post.AddProp(model.PostPropsOverrideIconUrl, url)
post.AddProp(model.PostPropsOverrideIconEmoji, emoji)
return th.App.PreparePostForClient(post, false, false)
}
@@ -310,10 +310,10 @@ func TestPreparePostForClient(t *testing.T) {
t.Run("does not override icon URL", func(t *testing.T) {
clientPost := prepare(false, url, emoji)
s, ok := clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_URL]
s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl]
assert.True(t, ok)
assert.EqualValues(t, url, s)
s, ok = clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI]
s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji]
assert.True(t, ok)
assert.EqualValues(t, emoji, s)
})
@@ -321,10 +321,10 @@ func TestPreparePostForClient(t *testing.T) {
t.Run("overrides icon URL", func(t *testing.T) {
clientPost := prepare(true, url, emoji)
s, ok := clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_URL]
s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl]
assert.True(t, ok)
assert.EqualValues(t, overridenUrl, s)
s, ok = clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI]
s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji]
assert.True(t, ok)
assert.EqualValues(t, emoji, s)
})
@@ -333,10 +333,10 @@ func TestPreparePostForClient(t *testing.T) {
colonEmoji := ":basketball:"
clientPost := prepare(true, url, colonEmoji)
s, ok := clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_URL]
s, ok := clientPost.GetProps()[model.PostPropsOverrideIconUrl]
assert.True(t, ok)
assert.EqualValues(t, overridenUrl, s)
s, ok = clientPost.GetProps()[model.POST_PROPS_OVERRIDE_ICON_EMOJI]
s, ok = clientPost.GetProps()[model.PostPropsOverrideIconEmoji]
assert.True(t, ok)
assert.EqualValues(t, colonEmoji, s)
})
@@ -384,7 +384,7 @@ func TestPreparePostForClient(t *testing.T) {
require.Nil(t, err)
// this value expected to be a string
post.AddProp(model.POST_PROPS_OVERRIDE_ICON_EMOJI, true)
post.AddProp(model.PostPropsOverrideIconEmoji, true)
require.NotPanics(t, func() {
_ = th.App.PreparePostForClient(post, false, false)
@@ -424,7 +424,7 @@ func TestPreparePostForClient(t *testing.T) {
t.Run("populates embeds", func(t *testing.T) {
assert.ElementsMatch(t, []*model.PostEmbed{
{
Type: model.POST_EMBED_IMAGE,
Type: model.PostEmbedImage,
URL: server.URL + "/test-image2.png",
},
}, clientPost.Metadata.Embeds)
@@ -457,7 +457,7 @@ func TestPreparePostForClient(t *testing.T) {
ogData := firstEmbed.Data.(*opengraph.OpenGraph)
t.Run("populates embeds", func(t *testing.T) {
assert.Equal(t, firstEmbed.Type, model.POST_EMBED_OPENGRAPH)
assert.Equal(t, firstEmbed.Type, model.PostEmbedOpengraph)
assert.Equal(t, firstEmbed.URL, server.URL)
assert.Equal(t, ogData.Description, "Contribute to hmhealey/test-files development by creating an account on GitHub.")
assert.Equal(t, ogData.SiteName, "GitHub")
@@ -500,7 +500,7 @@ func TestPreparePostForClient(t *testing.T) {
t.Run("populates embeds", func(t *testing.T) {
assert.ElementsMatch(t, []*model.PostEmbed{
{
Type: model.POST_EMBED_MESSAGE_ATTACHMENT,
Type: model.PostEmbedMessageAttachment,
},
}, clientPost.Metadata.Embeds)
})
@@ -644,7 +644,7 @@ func testProxyOpenGraphImage(t *testing.T, th *TestHelper, shouldProxy bool) {
require.Len(t, embeds, 1, "should have one embed")
embed := embeds[0]
assert.Equal(t, model.POST_EMBED_OPENGRAPH, embed.Type, "embed type should be OpenGraph")
assert.Equal(t, model.PostEmbedOpengraph, embed.Type, "embed type should be OpenGraph")
assert.Equal(t, server.URL, embed.URL, "embed URL should be correct")
og, ok := embed.Data.(*opengraph.OpenGraph)
@@ -718,7 +718,7 @@ func TestGetEmbedForPost(t *testing.T) {
}, "", false)
assert.Equal(t, &model.PostEmbed{
Type: model.POST_EMBED_MESSAGE_ATTACHMENT,
Type: model.PostEmbedMessageAttachment,
}, embed)
assert.NoError(t, err)
})
@@ -727,7 +727,7 @@ func TestGetEmbedForPost(t *testing.T) {
embed, err := th.App.getEmbedForPost(&model.Post{}, imageURL, false)
assert.Equal(t, &model.PostEmbed{
Type: model.POST_EMBED_IMAGE,
Type: model.PostEmbedImage,
URL: imageURL,
}, embed)
assert.NoError(t, err)
@@ -737,7 +737,7 @@ func TestGetEmbedForPost(t *testing.T) {
embed, err := th.App.getEmbedForPost(&model.Post{}, ogURL, false)
assert.Equal(t, &model.PostEmbed{
Type: model.POST_EMBED_OPENGRAPH,
Type: model.PostEmbedOpengraph,
URL: ogURL,
Data: &opengraph.OpenGraph{
Title: "Title",
@@ -750,7 +750,7 @@ func TestGetEmbedForPost(t *testing.T) {
embed, err := th.App.getEmbedForPost(&model.Post{}, otherURL, false)
assert.Equal(t, &model.PostEmbed{
Type: model.POST_EMBED_LINK,
Type: model.PostEmbedLink,
URL: otherURL,
}, embed)
assert.NoError(t, err)
@@ -778,7 +778,7 @@ func TestGetEmbedForPost(t *testing.T) {
}, "", false)
assert.Equal(t, &model.PostEmbed{
Type: model.POST_EMBED_MESSAGE_ATTACHMENT,
Type: model.PostEmbedMessageAttachment,
}, embed)
assert.NoError(t, err)
})
@@ -890,7 +890,7 @@ func TestGetImagesForPost(t *testing.T) {
Metadata: &model.PostMetadata{
Embeds: []*model.PostEmbed{
{
Type: model.POST_EMBED_OPENGRAPH,
Type: model.PostEmbedOpengraph,
URL: ogURL,
Data: &opengraph.OpenGraph{
Images: []*opengraph.Image{
@@ -944,7 +944,7 @@ func TestGetImagesForPost(t *testing.T) {
Metadata: &model.PostMetadata{
Embeds: []*model.PostEmbed{
{
Type: model.POST_EMBED_OPENGRAPH,
Type: model.PostEmbedOpengraph,
URL: ogURL,
Data: &opengraph.OpenGraph{
Images: []*opengraph.Image{
@@ -997,7 +997,7 @@ func TestGetImagesForPost(t *testing.T) {
Metadata: &model.PostMetadata{
Embeds: []*model.PostEmbed{
{
Type: model.POST_EMBED_OPENGRAPH,
Type: model.PostEmbedOpengraph,
URL: ogURL,
Data: &opengraph.OpenGraph{
Images: []*opengraph.Image{

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

@@ -414,7 +414,7 @@ func TestPostChannelMentions(t *testing.T) {
channelToMention, err := th.App.CreateChannel(th.Context, &model.Channel{
DisplayName: "Mention Test",
Name: "mention-test",
Type: model.CHANNEL_OPEN,
Type: model.ChannelTypeOpen,
TeamId: th.BasicTeam.Id,
}, false)
require.Nil(t, err)
@@ -484,7 +484,7 @@ func TestImageProxy(t *testing.T) {
ProxiedRemovedImageURL string
}{
"atmos/camo": {
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
ProxyType: model.ImageProxyTypeAtmosCamo,
ProxyURL: "https://127.0.0.1",
ProxyOptions: "foo",
ImageURL: "http://mydomain.com/myimage",
@@ -492,7 +492,7 @@ func TestImageProxy(t *testing.T) {
ProxiedImageURL: "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage",
},
"atmos/camo_SameSite": {
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
ProxyType: model.ImageProxyTypeAtmosCamo,
ProxyURL: "https://127.0.0.1",
ProxyOptions: "foo",
ImageURL: "http://mymattermost.com/myimage",
@@ -500,7 +500,7 @@ func TestImageProxy(t *testing.T) {
ProxiedImageURL: "http://mymattermost.com/myimage",
},
"atmos/camo_PathOnly": {
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
ProxyType: model.ImageProxyTypeAtmosCamo,
ProxyURL: "https://127.0.0.1",
ProxyOptions: "foo",
ImageURL: "/myimage",
@@ -508,7 +508,7 @@ func TestImageProxy(t *testing.T) {
ProxiedImageURL: "http://mymattermost.com/myimage",
},
"atmos/camo_EmptyImageURL": {
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
ProxyType: model.ImageProxyTypeAtmosCamo,
ProxyURL: "https://127.0.0.1",
ProxyOptions: "foo",
ImageURL: "",
@@ -516,25 +516,25 @@ func TestImageProxy(t *testing.T) {
ProxiedImageURL: "",
},
"local": {
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
ProxyType: model.ImageProxyTypeLocal,
ImageURL: "http://mydomain.com/myimage",
ProxiedRemovedImageURL: "http://mydomain.com/myimage",
ProxiedImageURL: "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage",
},
"local_SameSite": {
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
ProxyType: model.ImageProxyTypeLocal,
ImageURL: "http://mymattermost.com/myimage",
ProxiedRemovedImageURL: "http://mymattermost.com/myimage",
ProxiedImageURL: "http://mymattermost.com/myimage",
},
"local_PathOnly": {
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
ProxyType: model.ImageProxyTypeLocal,
ImageURL: "/myimage",
ProxiedRemovedImageURL: "http://mymattermost.com/myimage",
ProxiedImageURL: "http://mymattermost.com/myimage",
},
"local_EmptyImageURL": {
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
ProxyType: model.ImageProxyTypeLocal,
ImageURL: "",
ProxiedRemovedImageURL: "",
ProxiedImageURL: "",
@@ -585,7 +585,7 @@ func TestMaxPostSize(t *testing.T) {
{
"Max post size less than model.model.POST_MESSAGE_MAX_RUNES_V1 ",
0,
model.POST_MESSAGE_MAX_RUNES_V1,
model.PostMessageMaxRunesV1,
},
{
"4000 rune limit",
@@ -730,8 +730,8 @@ func TestCreatePost(t *testing.T) {
})
t.Run("Sets prop when post has mentions and user does not have USE_CHANNEL_MENTIONS", func(t *testing.T) {
th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId)
th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId)
postWithNoMention := &model.Post{
ChannelId: th.BasicChannel.Id,
@@ -749,10 +749,10 @@ func TestCreatePost(t *testing.T) {
}
rpost, err = th.App.CreatePost(th.Context, postWithMention, th.BasicChannel, false, true)
require.Nil(t, err)
assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true)
assert.Equal(t, rpost.GetProp(model.PostPropsMentionHighlightDisabled), true)
th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId)
th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId)
})
})
}
@@ -824,8 +824,8 @@ func TestPatchPost(t *testing.T) {
})
t.Run("Sets prop when user does not have USE_CHANNEL_MENTIONS", func(t *testing.T) {
th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId)
th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId)
patchWithNoMention := &model.PostPatch{Message: model.NewString("This patch still does not have a mention")}
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention)
@@ -836,10 +836,10 @@ func TestPatchPost(t *testing.T) {
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention)
require.Nil(t, err)
assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true)
assert.Equal(t, rpost.GetProp(model.PostPropsMentionHighlightDisabled), true)
th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_USER_ROLE_ID)
th.AddPermissionToRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelUserRoleId)
th.AddPermissionToRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId)
})
})
}
@@ -1246,7 +1246,7 @@ func TestCountMentionsFromPost(t *testing.T) {
channel := th.CreateChannel(th.BasicTeam)
th.AddUserToChannel(user2, channel)
user2.NotifyProps[model.MENTION_KEYS_NOTIFY_PROP] = "apple"
user2.NotifyProps[model.MentionKeysNotifyProp] = "apple"
post1, err := th.App.CreatePost(th.Context, &model.Post{
UserId: user1.Id,
@@ -1285,7 +1285,7 @@ func TestCountMentionsFromPost(t *testing.T) {
channel := th.CreateChannel(th.BasicTeam)
th.AddUserToChannel(user2, channel)
user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "true"
user2.NotifyProps[model.ChannelMentionsNotifyProp] = "true"
post1, err := th.App.CreatePost(th.Context, &model.Post{
UserId: user1.Id,
@@ -1324,7 +1324,7 @@ func TestCountMentionsFromPost(t *testing.T) {
channel := th.CreateChannel(th.BasicTeam)
th.AddUserToChannel(user2, channel)
user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "false"
user2.NotifyProps[model.ChannelMentionsNotifyProp] = "false"
post1, err := th.App.CreatePost(th.Context, &model.Post{
UserId: user1.Id,
@@ -1361,10 +1361,10 @@ func TestCountMentionsFromPost(t *testing.T) {
channel := th.CreateChannel(th.BasicTeam)
th.AddUserToChannel(user2, channel)
user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "true"
user2.NotifyProps[model.ChannelMentionsNotifyProp] = "true"
_, err := th.App.UpdateChannelMemberNotifyProps(map[string]string{
model.IGNORE_CHANNEL_MENTIONS_NOTIFY_PROP: model.IGNORE_CHANNEL_MENTIONS_ON,
model.IgnoreChannelMentionsNotifyProp: model.IgnoreChannelMentionsOn,
}, channel.Id, user2.Id)
require.Nil(t, err)
@@ -1403,7 +1403,7 @@ func TestCountMentionsFromPost(t *testing.T) {
channel := th.CreateChannel(th.BasicTeam)
th.AddUserToChannel(user2, channel)
user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ROOT
user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyRoot
post1, err := th.App.CreatePost(th.Context, &model.Post{
UserId: user2.Id,
@@ -1457,7 +1457,7 @@ func TestCountMentionsFromPost(t *testing.T) {
channel := th.CreateChannel(th.BasicTeam)
th.AddUserToChannel(user2, channel)
user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY
user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny
post1, err := th.App.CreatePost(th.Context, &model.Post{
UserId: user2.Id,
@@ -1515,9 +1515,9 @@ func TestCountMentionsFromPost(t *testing.T) {
UserId: user1.Id,
ChannelId: channel.Id,
Message: "test",
Type: model.POST_ADD_TO_CHANNEL,
Type: model.PostTypeAddToChannel,
Props: map[string]interface{}{
model.POST_PROPS_ADDED_USER_ID: model.NewId(),
model.PostPropsAddedUserId: model.NewId(),
},
}, channel, false, true)
require.Nil(t, err)
@@ -1525,9 +1525,9 @@ func TestCountMentionsFromPost(t *testing.T) {
UserId: user1.Id,
ChannelId: channel.Id,
Message: "test2",
Type: model.POST_ADD_TO_CHANNEL,
Type: model.PostTypeAddToChannel,
Props: map[string]interface{}{
model.POST_PROPS_ADDED_USER_ID: user2.Id,
model.PostPropsAddedUserId: user2.Id,
},
}, channel, false, true)
require.Nil(t, err)
@@ -1535,9 +1535,9 @@ func TestCountMentionsFromPost(t *testing.T) {
UserId: user1.Id,
ChannelId: channel.Id,
Message: "test3",
Type: model.POST_ADD_TO_CHANNEL,
Type: model.PostTypeAddToChannel,
Props: map[string]interface{}{
model.POST_PROPS_ADDED_USER_ID: user2.Id,
model.PostPropsAddedUserId: user2.Id,
},
}, channel, false, true)
require.Nil(t, err)
@@ -1663,7 +1663,7 @@ func TestCountMentionsFromPost(t *testing.T) {
channel := th.CreateChannel(th.BasicTeam)
th.AddUserToChannel(user2, channel)
user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY
user2.NotifyProps[model.CommentsNotifyProp] = model.CommentsNotifyAny
post1, err := th.App.CreatePost(th.Context, &model.Post{
UserId: user1.Id,
@@ -1931,7 +1931,7 @@ func TestFollowThreadSkipsParticipants(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
channel := th.BasicChannel
@@ -1989,7 +1989,7 @@ func TestAutofollowBasedOnRootPost(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
channel := th.BasicChannel
@@ -2019,7 +2019,7 @@ func TestViewChannelShouldNotUpdateThreads(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
channel := th.BasicChannel
@@ -2052,7 +2052,7 @@ func TestCollapsedThreadFetch(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
user1 := th.BasicUser
user2 := th.BasicUser2
@@ -2144,8 +2144,8 @@ func TestReplyToPostWithLag(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
if *th.App.Srv().Config().SqlSettings.DriverName != model.DATABASE_DRIVER_MYSQL {
t.Skipf("requires %q database driver", model.DATABASE_DRIVER_MYSQL)
if *th.App.Srv().Config().SqlSettings.DriverName != model.DatabaseDriverMysql {
t.Skipf("requires %q database driver", model.DatabaseDriverMysql)
}
mainHelper.SQLStore.UpdateLicense(model.NewTestLicense("somelicense"))
@@ -2268,7 +2268,7 @@ func TestAutofollowOnPostingAfterUnfollow(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.ThreadAutoFollow = true
*cfg.ServiceSettings.CollapsedThreads = model.COLLAPSED_THREADS_DEFAULT_ON
*cfg.ServiceSettings.CollapsedThreads = model.CollapsedThreadsDefaultOn
})
channel := th.BasicChannel

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

@@ -60,11 +60,11 @@ func (a *App) UpdatePreferences(userID string, preferences model.Preferences) *m
return model.NewAppError("UpdatePreferences", "api.preference.update_preferences.update_sidebar.app_error", nil, err.Error(), http.StatusInternalServerError)
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_UPDATED, "", "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryUpdated, "", "", userID, nil)
// TODO this needs to be updated to include information on which categories changed
a.Publish(message)
message = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PREFERENCES_CHANGED, "", "", userID, nil)
message = model.NewWebSocketEvent(model.WebsocketEventPreferencesChanged, "", "", userID, nil)
message.Add("preferences", preferences.ToJson())
a.Publish(message)
@@ -90,11 +90,11 @@ func (a *App) DeletePreferences(userID string, preferences model.Preferences) *m
return model.NewAppError("DeletePreferences", "api.preference.delete_preferences.update_sidebar.app_error", nil, err.Error(), http.StatusInternalServerError)
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_SIDEBAR_CATEGORY_UPDATED, "", "", userID, nil)
message := model.NewWebSocketEvent(model.WebsocketEventSidebarCategoryUpdated, "", "", userID, nil)
// TODO this needs to be updated to include information on which categories changed
a.Publish(message)
message = model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PREFERENCES_DELETED, "", "", userID, nil)
message = model.NewWebSocketEvent(model.WebsocketEventPreferencesDeleted, "", "", userID, nil)
message.Add("preferences", preferences.ToJson())
a.Publish(message)

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

@@ -68,7 +68,7 @@ func noticeMatchesConditions(config *model.Config, preferences store.PreferenceS
// check if client version is in notice range
clientVersions := cnd.DesktopVersion
if client == model.NoticeClientType_MobileAndroid || client == model.NoticeClientType_MobileIos {
if client == model.NoticeClientTypeMobileAndroid || client == model.NoticeClientTypeMobileIos {
clientVersions = cnd.MobileVersion
}
@@ -155,7 +155,7 @@ func noticeMatchesConditions(config *model.Config, preferences store.PreferenceS
}
switch cnd.DeprecatingDependency.Name {
case model.DATABASE_DRIVER_MYSQL, model.DATABASE_DRIVER_POSTGRES:
case model.DatabaseDriverMysql, model.DatabaseDriverPostgres:
if dbName != cnd.DeprecatingDependency.Name {
return false, nil
}
@@ -164,8 +164,8 @@ func noticeMatchesConditions(config *model.Config, preferences store.PreferenceS
return false, errors.Wrapf(err, "Cannot parse DBMS version %s", dbVer)
}
return extDepVersion.GreaterThan(serverDBMSVersion), nil
case model.SEARCHENGINE_ELASTICSEARCH:
if searchEngineName != model.SEARCHENGINE_ELASTICSEARCH {
case model.SearchengineElasticsearch:
if searchEngineName != model.SearchengineElasticsearch {
return false, nil
}
semverESVersion, err := semver.NewVersion(searchEngineVer)
@@ -239,8 +239,8 @@ func validateConfigEntry(conf *model.Config, path string, expectedValue interfac
// GetProductNotices is called from the frontend to fetch the product notices that are relevant to the caller
func (a *App) GetProductNotices(c *request.Context, userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) {
isSystemAdmin := a.SessionHasPermissionTo(*c.Session(), model.PERMISSION_MANAGE_SYSTEM)
isTeamAdmin := a.SessionHasPermissionToTeam(*c.Session(), teamID, model.PERMISSION_MANAGE_TEAM)
isSystemAdmin := a.SessionHasPermissionTo(*c.Session(), model.PermissionManageSystem)
isTeamAdmin := a.SessionHasPermissionToTeam(*c.Session(), teamID, model.PermissionManageTeam)
// check if notices for regular users are disabled
if !*a.Srv().Config().AnnouncementSettings.UserNoticesEnabled && !isSystemAdmin {

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

@@ -101,7 +101,7 @@ func TestNoticeValidation(t *testing.T) {
notice: &model.ProductNotice{
Conditions: model.Conditions{
ClientType: model.NewNoticeClientType(model.NoticeClientType_Mobile),
ClientType: model.NewNoticeClientType(model.NoticeClientTypeMobile),
},
},
},
@@ -396,7 +396,7 @@ func TestNoticeValidation(t *testing.T) {
systemAdmin: true,
notice: &model.ProductNotice{
Conditions: model.Conditions{
Audience: model.NewNoticeAudience(model.NoticeAudience_Sysadmin),
Audience: model.NewNoticeAudience(model.NoticeAudienceSysadmin),
},
},
},
@@ -409,7 +409,7 @@ func TestNoticeValidation(t *testing.T) {
systemAdmin: false,
notice: &model.ProductNotice{
Conditions: model.Conditions{
Audience: model.NewNoticeAudience(model.NoticeAudience_Sysadmin),
Audience: model.NewNoticeAudience(model.NoticeAudienceSysadmin),
},
},
},
@@ -422,7 +422,7 @@ func TestNoticeValidation(t *testing.T) {
teamAdmin: true,
notice: &model.ProductNotice{
Conditions: model.Conditions{
Audience: model.NewNoticeAudience(model.NoticeAudience_TeamAdmin),
Audience: model.NewNoticeAudience(model.NoticeAudienceTeamAdmin),
},
},
},
@@ -435,7 +435,7 @@ func TestNoticeValidation(t *testing.T) {
teamAdmin: false,
notice: &model.ProductNotice{
Conditions: model.Conditions{
Audience: model.NewNoticeAudience(model.NoticeAudience_TeamAdmin),
Audience: model.NewNoticeAudience(model.NoticeAudienceTeamAdmin),
},
},
},
@@ -447,7 +447,7 @@ func TestNoticeValidation(t *testing.T) {
args: args{
notice: &model.ProductNotice{
Conditions: model.Conditions{
Audience: model.NewNoticeAudience(model.NoticeAudience_Member),
Audience: model.NewNoticeAudience(model.NoticeAudienceMember),
},
},
},
@@ -460,7 +460,7 @@ func TestNoticeValidation(t *testing.T) {
systemAdmin: true,
notice: &model.ProductNotice{
Conditions: model.Conditions{
Audience: model.NewNoticeAudience(model.NoticeAudience_Member),
Audience: model.NewNoticeAudience(model.NoticeAudienceMember),
},
},
},
@@ -473,7 +473,7 @@ func TestNoticeValidation(t *testing.T) {
sku: "e20",
notice: &model.ProductNotice{
Conditions: model.Conditions{
Sku: model.NewNoticeSKU(model.NoticeSKU_E20),
Sku: model.NewNoticeSKU(model.NoticeSKUE20),
},
},
},
@@ -486,7 +486,7 @@ func TestNoticeValidation(t *testing.T) {
sku: "e20",
notice: &model.ProductNotice{
Conditions: model.Conditions{
Sku: model.NewNoticeSKU(model.NoticeSKU_E10),
Sku: model.NewNoticeSKU(model.NoticeSKUE10),
},
},
},
@@ -499,7 +499,7 @@ func TestNoticeValidation(t *testing.T) {
sku: "",
notice: &model.ProductNotice{
Conditions: model.Conditions{
Sku: model.NewNoticeSKU(model.NoticeSKU_Team),
Sku: model.NewNoticeSKU(model.NoticeSKUTeam),
},
},
},
@@ -511,7 +511,7 @@ func TestNoticeValidation(t *testing.T) {
args: args{
notice: &model.ProductNotice{
Conditions: model.Conditions{
Sku: model.NewNoticeSKU(model.NoticeSKU_All),
Sku: model.NewNoticeSKU(model.NoticeSKUAll),
},
},
},
@@ -524,7 +524,7 @@ func TestNoticeValidation(t *testing.T) {
cloud: true,
notice: &model.ProductNotice{
Conditions: model.Conditions{
InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceType_Cloud),
InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceTypeCloud),
},
},
},
@@ -536,7 +536,7 @@ func TestNoticeValidation(t *testing.T) {
args: args{
notice: &model.ProductNotice{
Conditions: model.Conditions{
InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceType_Both),
InstanceType: model.NewNoticeInstanceType(model.NoticeInstanceTypeBoth),
},
},
},
@@ -719,7 +719,7 @@ func TestNoticeFetch(t *testing.T) {
require.Nil(t, appErr)
// get them for specified user
messages, appErr := th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
messages, appErr := th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientTypeAll, "1.2.3", "en")
require.Nil(t, appErr)
require.Len(t, messages, 1)
@@ -728,7 +728,7 @@ func TestNoticeFetch(t *testing.T) {
require.Nil(t, appErr)
// get them again, see that none are returned
messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientTypeAll, "1.2.3", "en")
require.Nil(t, appErr)
require.Len(t, messages, 0)
@@ -747,7 +747,7 @@ func TestNoticeFetch(t *testing.T) {
require.Nil(t, appErr)
// get them again, since conditions don't match we should be zero
messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientTypeAll, "1.2.3", "en")
require.Nil(t, appErr)
require.Len(t, messages, 0)

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

@@ -73,7 +73,7 @@ func TestGenerateKey(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
if tc.authTokenResult != "" {
req.AddCookie(&http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Name: model.SessionCookieToken,
Value: tc.authTokenResult,
})
}

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

@@ -27,14 +27,14 @@ func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction)
return nil, model.NewAppError("deleteReactionForPost", "api.reaction.save.archived_channel.app_error", nil, "", http.StatusForbidden)
}
if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL {
if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DefaultChannelName {
var user *model.User
user, err = a.GetUser(reaction.UserId)
if err != nil {
return nil, err
}
if !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) {
if !a.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) {
return nil, model.NewAppError("saveReactionForPost", "api.reaction.town_square_read_only", nil, "", http.StatusForbidden)
}
}
@@ -64,7 +64,7 @@ func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction)
}
a.Srv().Go(func() {
a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_ADDED, reaction, post)
a.sendReactionEvent(model.WebsocketEventReactionAdded, reaction, post)
})
return reaction, nil
@@ -121,13 +121,13 @@ func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction
return model.NewAppError("DeleteReactionForPost", "api.reaction.delete.archived_channel.app_error", nil, "", http.StatusForbidden)
}
if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL {
if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DefaultChannelName {
user, err := a.GetUser(reaction.UserId)
if err != nil {
return err
}
if !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) {
if !a.RolesGrantPermission(user.GetRoles(), model.PermissionManageSystem.Id) {
return model.NewAppError("DeleteReactionForPost", "api.reaction.town_square_read_only", nil, "", http.StatusForbidden)
}
}
@@ -150,7 +150,7 @@ func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction
}
a.Srv().Go(func() {
a.sendReactionEvent(model.WEBSOCKET_EVENT_REACTION_REMOVED, reaction, post)
a.sendReactionEvent(model.WebsocketEventReactionRemoved, reaction, post)
})
return nil

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

@@ -163,9 +163,9 @@ func (a *App) UpdateRole(role *model.Role) (*model.Role, *model.AppError) {
}
builtInChannelRoles := []string{
model.CHANNEL_GUEST_ROLE_ID,
model.CHANNEL_USER_ROLE_ID,
model.CHANNEL_ADMIN_ROLE_ID,
model.ChannelGuestRoleId,
model.ChannelUserRoleId,
model.ChannelAdminRoleId,
}
builtInRolesMinusChannelRoles := append(utils.RemoveStringsFromSlice(model.BuiltInSchemeManagedRoleIDs, builtInChannelRoles...), model.NewSystemRoleIDs...)
@@ -239,7 +239,7 @@ func (a *App) CheckRolesExist(roleNames []string) *model.AppError {
}
func (a *App) sendUpdatedRoleEvent(role *model.Role) {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ROLE_UPDATED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventRoleUpdated, "", "", "", nil)
message.Add("role", role.ToJson())
a.Srv().Go(func() {

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

@@ -70,15 +70,15 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th
th.App.SetPhase2PermissionsMigrationStatus(true)
permissionsDefault := []string{
model.PERMISSION_MANAGE_CHANNEL_ROLES.Id,
model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id,
model.PermissionManageChannelRoles.Id,
model.PermissionManagePublicChannelMembers.Id,
}
// Defer resetting the system scheme permissions
systemSchemeRoles, err := th.App.GetRolesByNames([]string{
model.CHANNEL_GUEST_ROLE_ID,
model.CHANNEL_USER_ROLE_ID,
model.CHANNEL_ADMIN_ROLE_ID,
model.ChannelGuestRoleId,
model.ChannelUserRoleId,
model.ChannelAdminRoleId,
})
require.Nil(t, err)
require.Len(t, systemSchemeRoles, 3)
@@ -94,7 +94,7 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th
channelScheme, err := th.App.CreateScheme(&model.Scheme{
Name: model.NewId(),
DisplayName: model.NewId(),
Scope: model.SCHEME_SCOPE_CHANNEL,
Scope: model.SchemeScopeChannel,
})
require.Nil(t, err)
defer th.App.DeleteScheme(channelScheme.Id)
@@ -154,9 +154,9 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th
// select the permission to test (moderated or non-moderated)
var permission *model.Permission
if permissionIsModerated {
permission = model.PERMISSION_CREATE_POST // moderated
permission = model.PermissionCreatePost // moderated
} else {
permission = model.PERMISSION_READ_CHANNEL // non-moderated
permission = model.PermissionReadChannel // non-moderated
}
// add or remove the permission from the higher-scoped scheme
@@ -208,13 +208,13 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th
}
// test 24 combinations where the higher-scoped scheme is the SYSTEM scheme
test(model.CHANNEL_GUEST_ROLE_ID, model.CHANNEL_USER_ROLE_ID, model.CHANNEL_ADMIN_ROLE_ID)
test(model.ChannelGuestRoleId, model.ChannelUserRoleId, model.ChannelAdminRoleId)
// create a team scheme
teamScheme, err := th.App.CreateScheme(&model.Scheme{
Name: model.NewId(),
DisplayName: model.NewId(),
Scope: model.SCHEME_SCOPE_TEAM,
Scope: model.SchemeScopeTeam,
})
require.Nil(t, err)
defer th.App.DeleteScheme(teamScheme.Id)

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

@@ -288,7 +288,7 @@ func (a *App) ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs
appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented)
return
}
numAffected, err := a.srv.Store.User().ResetAuthDataToEmailForUsers(model.USER_AUTH_SERVICE_SAML, userIDs, includeDeleted, dryRun)
numAffected, err := a.srv.Store.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, userIDs, includeDeleted, dryRun)
if err != nil {
appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.failure_reset_authdata_to_email.app_error", nil, err.Error(), http.StatusInternalServerError)
return

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

@@ -202,7 +202,7 @@ func (s *Server) IsPhase2MigrationCompleted() *model.AppError {
return nil
}
if _, err := s.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil {
if _, err := s.Store.System().GetByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil {
return model.NewAppError("App.IsPhase2MigrationCompleted", "app.schemes.is_phase_2_migration_completed.not_completed.app_error", nil, err.Error(), http.StatusNotImplemented)
}

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

@@ -11,7 +11,7 @@ import (
)
func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError {
if *cfg.ElasticsearchSettings.Password == model.FAKE_SETTING {
if *cfg.ElasticsearchSettings.Password == model.FakeSetting {
if *cfg.ElasticsearchSettings.ConnectionUrl == *a.Config().ElasticsearchSettings.ConnectionUrl && *cfg.ElasticsearchSettings.Username == *a.Config().ElasticsearchSettings.Username {
*cfg.ElasticsearchSettings.Password = *a.Config().ElasticsearchSettings.Password
} else {

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

@@ -41,7 +41,7 @@ func (s *Server) DoSecurityUpdateCheck() {
return
}
lastSecurityTime, _ := strconv.ParseInt(props[model.SYSTEM_LAST_SECURITY_TIME], 10, 0)
lastSecurityTime, _ := strconv.ParseInt(props[model.SystemLastSecurityTime], 10, 0)
currentTime := model.GetMillis()
if (currentTime - lastSecurityTime) > SecurityUpdatePeriod {
@@ -55,13 +55,13 @@ func (s *Server) DoSecurityUpdateCheck() {
v.Set(PropSecurityDatabase, *s.Config().SqlSettings.DriverName)
v.Set(PropSecurityOS, runtime.GOOS)
if props[model.SYSTEM_RAN_UNIT_TESTS] != "" {
if props[model.SystemRanUnitTests] != "" {
v.Set(PropSecurityUnitTests, "1")
} else {
v.Set(PropSecurityUnitTests, "0")
}
systemSecurityLastTime := &model.System{Name: model.SYSTEM_LAST_SECURITY_TIME, Value: strconv.FormatInt(currentTime, 10)}
systemSecurityLastTime := &model.System{Name: model.SystemLastSecurityTime, Value: strconv.FormatInt(currentTime, 10)}
if lastSecurityTime == 0 {
s.Store.System().Save(systemSecurityLastTime)
} else {

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

@@ -338,7 +338,7 @@ func NewServer(options ...Option) (*Server, error) {
return nil, errors.Wrap(err, "Unable to create pending post ids cache")
}
if s.statusCache, err = s.CacheProvider.NewCache(&cache.CacheOptions{
Size: model.STATUS_CACHE_SIZE,
Size: model.StatusCacheSize,
Striped: true,
StripedBuckets: maxInt(runtime.NumCPU()-1, 1),
}); err != nil {
@@ -426,7 +426,7 @@ func NewServer(options ...Option) (*Server, error) {
s.configListenerId = s.AddConfigListener(func(_, _ *model.Config) {
s.configOrLicenseListener()
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CONFIG_CHANGED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventConfigChanged, "", "", "", nil)
message.Add("config", s.ClientConfigWithComputed())
s.Go(func() {
@@ -436,7 +436,7 @@ func NewServer(options ...Option) (*Server, error) {
s.licenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) {
s.configOrLicenseListener()
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LICENSE_CHANGED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketEventLicenseChanged, "", "", "", nil)
message.Add("license", s.GetSanitizedClientLicense())
s.Go(func() {
s.Publish(message)
@@ -1109,7 +1109,7 @@ func (s *Server) Restart() error {
}
func (s *Server) isUpgradedFromTE() bool {
val, err := s.Store.System().GetByName(model.SYSTEM_UPGRADED_FROM_TE_ID)
val, err := s.Store.System().GetByName(model.SystemUpgradedFromTeId)
if err != nil {
return false
}
@@ -1124,7 +1124,7 @@ func (s *Server) UpgradeToE0() error {
if err := upgrader.UpgradeToE0(); err != nil {
return err
}
upgradedFromTE := &model.System{Name: model.SYSTEM_UPGRADED_FROM_TE_ID, Value: "true"}
upgradedFromTE := &model.System{Name: model.SystemUpgradedFromTeId, Value: "true"}
s.Store.System().Save(upgradedFromTE)
return nil
}
@@ -1247,7 +1247,7 @@ func (s *Server) Start() error {
addr := *s.Config().ServiceSettings.ListenAddress
if addr == "" {
if *s.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS {
if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTls {
addr = ":https"
} else {
addr = ":http"
@@ -1307,7 +1307,7 @@ func (s *Server) Start() error {
s.didFinishListen = make(chan struct{})
go func() {
var err error
if *s.Config().ServiceSettings.ConnectionSecurity == model.CONN_SECURITY_TLS {
if *s.Config().ServiceSettings.ConnectionSecurity == model.ConnSecurityTls {
tlsConfig := &tls.Config{
PreferServerCipherSuites: true,
@@ -1486,7 +1486,7 @@ func (s *Server) runLicenseExpirationCheckJob() {
func runReportToAWSMeterJob(s *Server) {
model.CreateRecurringTask("Collect and send usage report to AWS Metering Service", func() {
doReportUsageToAWSMeteringService(s)
}, time.Hour*model.AWS_METERING_REPORT_INTERVAL)
}, time.Hour*model.AwsMeteringReportInterval)
}
func doReportUsageToAWSMeteringService(s *Server) {
@@ -1496,8 +1496,8 @@ func doReportUsageToAWSMeteringService(s *Server) {
return
}
dimensions := []string{model.AWS_METERING_DIMENSION_USAGE_HRS}
reports := awsMeter.GetUserCategoryUsage(dimensions, time.Now().UTC(), time.Now().Add(-model.AWS_METERING_REPORT_INTERVAL*time.Hour).UTC())
dimensions := []string{model.AwsMeteringDimensionUsageHrs}
reports := awsMeter.GetUserCategoryUsage(dimensions, time.Now().UTC(), time.Now().Add(-model.AwsMeteringReportInterval*time.Hour).UTC())
awsMeter.ReportUserCategoryUsage(reports)
}
@@ -1506,14 +1506,14 @@ func runCheckWarnMetricStatusJob(a *App, c *request.Context) {
doCheckWarnMetricStatus(a, c)
model.CreateRecurringTask("Check Warn Metric Status Job", func() {
doCheckWarnMetricStatus(a, c)
}, time.Hour*model.WARN_METRIC_JOB_INTERVAL)
}, time.Hour*model.WarnMetricJobInterval)
}
func runCheckAdminSupportStatusJob(a *App, c *request.Context) {
doCheckAdminSupportStatus(a, c)
model.CreateRecurringTask("Check Admin Support Status Job", func() {
doCheckAdminSupportStatus(a, c)
}, time.Hour*model.WARN_METRIC_JOB_INTERVAL)
}, time.Hour*model.WarnMetricJobInterval)
}
func doSecurity(s *Server) {
@@ -1554,10 +1554,10 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
warnMetricStatusFromStore := make(map[string]string)
for key, value := range systemDataList {
if strings.HasPrefix(key, model.WARN_METRIC_STATUS_STORE_PREFIX) {
if strings.HasPrefix(key, model.WarnMetricStatusStorePrefix) {
if _, ok := model.WarnMetricsTable[key]; ok {
warnMetricStatusFromStore[key] = value
if value == model.WARN_METRIC_STATUS_ACK {
if value == model.WarnMetricStatusAck {
// If any warn metric has already been acked, we return
mlog.Debug("Warn metrics have been acked, skip")
return
@@ -1572,7 +1572,7 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
} else {
currentTime := utils.MillisFromTime(time.Now())
// If the admin advisory has already been shown in the last 7 days
if (currentTime-lastWarnMetricRunTimestamp)/(model.WARN_METRIC_JOB_WAIT_TIME) < 1 {
if (currentTime-lastWarnMetricRunTimestamp)/(model.WarnMetricJobWaitTime) < 1 {
mlog.Debug("No advisories should be shown during the wait interval time")
return
}
@@ -1588,7 +1588,7 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
mlog.Debug("Error attempting to get number of teams.", mlog.Err(err1))
}
openChannelCount, err2 := a.Srv().Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN)
openChannelCount, err2 := a.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen)
if err2 != nil {
mlog.Debug("Error attempting to get number of public channels.", mlog.Err(err2))
}
@@ -1604,31 +1604,31 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
warnMetrics := []model.WarnMetric{}
if numberOfActiveUsers < model.WARN_METRIC_NUMBER_OF_ACTIVE_USERS_25 {
if numberOfActiveUsers < model.WarnMetricNumberOfActiveUsers25 {
return
} else if teamCount >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5] != model.WARN_METRIC_STATUS_RUNONCE {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_TEAMS_5])
} else if *a.Config().ServiceSettings.EnableMultifactorAuthentication && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_MFA] != model.WARN_METRIC_STATUS_RUNONCE {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_MFA])
} else if isDiffEmailAccount && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN] != model.WARN_METRIC_STATUS_RUNONCE {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_EMAIL_DOMAIN])
} else if openChannelCount >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50] != model.WARN_METRIC_STATUS_RUNONCE {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_CHANNELS_50])
} else if teamCount >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfTeams5].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfTeams5] != model.WarnMetricStatusRunonce {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfTeams5])
} else if *a.Config().ServiceSettings.EnableMultifactorAuthentication && warnMetricStatusFromStore[model.SystemWarnMetricMfa] != model.WarnMetricStatusRunonce {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricMfa])
} else if isDiffEmailAccount && warnMetricStatusFromStore[model.SystemWarnMetricEmailDomain] != model.WarnMetricStatusRunonce {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricEmailDomain])
} else if openChannelCount >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfChannels50].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfChannels50] != model.WarnMetricStatusRunonce {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfChannels50])
}
// If the system did not cross any of the thresholds for the Contextual Advisories
if len(warnMetrics) == 0 {
if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100] != model.WARN_METRIC_STATUS_RUNONCE {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_100])
} else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200] != model.WARN_METRIC_STATUS_RUNONCE {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_200])
} else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300] != model.WARN_METRIC_STATUS_RUNONCE {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_300])
} else if numberOfActiveUsers >= model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500].Limit {
if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers100].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers200].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers100] != model.WarnMetricStatusRunonce {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers100])
} else if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers200].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers300].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers200] != model.WarnMetricStatusRunonce {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers200])
} else if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers300].Limit && numberOfActiveUsers < model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers500].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers300] != model.WarnMetricStatusRunonce {
warnMetrics = append(warnMetrics, model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers300])
} else if numberOfActiveUsers >= model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers500].Limit {
var tWarnMetric model.WarnMetric
if warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500] != model.WARN_METRIC_STATUS_RUNONCE {
tWarnMetric = model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_ACTIVE_USERS_500]
if warnMetricStatusFromStore[model.SystemWarnMetricNumberOfActiveUsers500] != model.WarnMetricStatusRunonce {
tWarnMetric = model.WarnMetricsTable[model.SystemWarnMetricNumberOfActiveUsers500]
}
postsCount, err4 := a.Srv().Store.Post().AnalyticsPostCount("", false, false)
@@ -1636,8 +1636,8 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
mlog.Debug("Error attempting to get number of posts.", mlog.Err(err4))
}
if postsCount > model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M].Limit && warnMetricStatusFromStore[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M] != model.WARN_METRIC_STATUS_RUNONCE {
tWarnMetric = model.WarnMetricsTable[model.SYSTEM_WARN_METRIC_NUMBER_OF_POSTS_2M]
if postsCount > model.WarnMetricsTable[model.SystemWarnMetricNumberOfPosts2m].Limit && warnMetricStatusFromStore[model.SystemWarnMetricNumberOfPosts2m] != model.WarnMetricStatusRunonce {
tWarnMetric = model.WarnMetricsTable[model.SystemWarnMetricNumberOfPosts2m]
}
if tWarnMetric != (model.WarnMetric{}) {
@@ -1650,7 +1650,7 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
for _, warnMetric := range warnMetrics {
data, nErr := a.Srv().Store.System().GetByName(warnMetric.Id)
if nErr == nil && data != nil && warnMetric.IsBotOnly && data.Value == model.WARN_METRIC_STATUS_RUNONCE {
if nErr == nil && data != nil && warnMetric.IsBotOnly && data.Value == model.WarnMetricStatusRunonce {
mlog.Debug("This metric warning is bot only and ran once")
continue
}
@@ -1658,12 +1658,12 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
warnMetricStatus, _ := a.getWarnMetricStatusAndDisplayTextsForId(warnMetric.Id, nil, isE0Edition)
if !warnMetric.IsBotOnly {
// Banner and bot metric types - send websocket event every interval
message := model.NewWebSocketEvent(model.WEBSOCKET_WARN_METRIC_STATUS_RECEIVED, "", "", "", nil)
message := model.NewWebSocketEvent(model.WebsocketWarnMetricStatusReceived, "", "", "", nil)
message.Add("warnMetricStatus", warnMetricStatus.ToJson())
a.Publish(message)
// Banner and bot metric types, send the bot message only once
if data != nil && data.Value == model.WARN_METRIC_STATUS_RUNONCE {
if data != nil && data.Value == model.WarnMetricStatusRunonce {
continue
}
}
@@ -1673,9 +1673,9 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
}
if warnMetric.IsRunOnce {
a.setWarnMetricsStatusForId(warnMetric.Id, model.WARN_METRIC_STATUS_RUNONCE)
a.setWarnMetricsStatusForId(warnMetric.Id, model.WarnMetricStatusRunonce)
} else {
a.setWarnMetricsStatusForId(warnMetric.Id, model.WARN_METRIC_STATUS_LIMIT_REACHED)
a.setWarnMetricsStatusForId(warnMetric.Id, model.WarnMetricStatusLimitReached)
}
}
}
@@ -1683,8 +1683,8 @@ func doCheckWarnMetricStatus(a *App, c *request.Context) {
func doCheckAdminSupportStatus(a *App, c *request.Context) {
isE0Edition := model.BuildEnterpriseReady == "true"
if strings.TrimSpace(*a.Config().SupportSettings.SupportEmail) == model.SUPPORT_SETTINGS_DEFAULT_SUPPORT_EMAIL {
if err := a.notifyAdminsOfWarnMetricStatus(c, model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED, isE0Edition); err != nil {
if strings.TrimSpace(*a.Config().SupportSettings.SupportEmail) == model.SupportSettingsDefaultSupportEmail {
if err := a.notifyAdminsOfWarnMetricStatus(c, model.SystemMetricSupportEmailNotConfigured, isE0Edition); err != nil {
mlog.Error("Failed to send notifications to admin users.", mlog.Err(err))
}
}
@@ -1791,7 +1791,7 @@ func (s *Server) startMetricsServer() {
}
func (s *Server) sendLicenseUpForRenewalEmail(users map[string]*model.User, license *model.License) *model.AppError {
key := model.LICENSE_UP_FOR_RENEWAL_EMAIL_SENT + license.Id
key := model.LicenseUpForRenewalEmailSent + license.Id
if _, err := s.Store.System().GetByName(key); err == nil {
// return early because the key already exists and that means we already executed the code below to send email successfully
return nil

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

@@ -66,10 +66,10 @@ func TestReadReplicaDisabledBasedOnLicense(t *testing.T) {
cfg.SetDefaults()
driverName := os.Getenv("MM_SQLSETTINGS_DRIVERNAME")
if driverName == "" {
driverName = model.DATABASE_DRIVER_POSTGRES
driverName = model.DatabaseDriverPostgres
}
dsn := ""
if driverName == model.DATABASE_DRIVER_POSTGRES {
if driverName == model.DatabaseDriverPostgres {
dsn = os.Getenv("TEST_DATABASE_POSTGRESQL_DSN")
} else {
dsn = os.Getenv("TEST_DATABASE_MYSQL_DSN")
@@ -172,9 +172,9 @@ func TestStartServerNoS3Bucket(t *testing.T) {
server.configStore = store
server.UpdateConfig(func(cfg *model.Config) {
cfg.FileSettings = model.FileSettings{
DriverName: model.NewString(model.IMAGE_DRIVER_S3),
AmazonS3AccessKeyId: model.NewString(model.MINIO_ACCESS_KEY),
AmazonS3SecretAccessKey: model.NewString(model.MINIO_SECRET_KEY),
DriverName: model.NewString(model.ImageDriverS3),
AmazonS3AccessKeyId: model.NewString(model.MinioAccessKey),
AmazonS3SecretAccessKey: model.NewString(model.MinioSecretKey),
AmazonS3Bucket: model.NewString("nosuchbucket"),
AmazonS3Endpoint: model.NewString(s3Endpoint),
AmazonS3Region: model.NewString(""),
@@ -707,7 +707,7 @@ func TestAdminAdvisor(t *testing.T) {
Username: "vader" + model.NewId(),
Password: "passwd1",
AuthService: "",
Roles: model.SYSTEM_ADMIN_ROLE_ID,
Roles: model.SystemAdminRoleId,
}
ruser, err := th.App.CreateUser(th.Context, &user)
assert.Nil(t, err, "User should be created")
@@ -716,7 +716,7 @@ func TestAdminAdvisor(t *testing.T) {
t.Run("Should notify admin of un-configured support email", func(t *testing.T) {
doCheckAdminSupportStatus(th.App, th.Context)
bot, err := th.App.GetUserByUsername(model.BOT_WARN_METRIC_BOT_USERNAME)
bot, err := th.App.GetUserByUsername(model.BotWarnMetricBotUsername)
assert.NotNil(t, bot, "Bot should have been created now")
assert.Nil(t, err, "No error should be generated")
@@ -731,7 +731,7 @@ func TestAdminAdvisor(t *testing.T) {
m.SupportSettings.SupportEmail = &email
})
bot, err := th.App.GetUserByUsername(model.BOT_WARN_METRIC_BOT_USERNAME)
bot, err := th.App.GetUserByUsername(model.BotWarnMetricBotUsername)
assert.NotNil(t, bot, "Bot should be already created")
assert.Nil(t, err, "No error should be generated")

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

@@ -41,7 +41,7 @@ func (a *App) GetCloudSession(token string) (*model.Session, *model.AppError) {
IsOAuth: false,
}
session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_CLOUD_KEY)
session.AddProp(model.SessionPropType, model.SessionTypeCloudKey)
return session, nil
}
return nil, model.NewAppError("GetCloudSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized)
@@ -56,7 +56,7 @@ func (a *App) GetRemoteClusterSession(token string, remoteId string) (*model.Ses
IsOAuth: false,
}
session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_REMOTECLUSTER_TOKEN)
session.AddProp(model.SessionPropType, model.SessionTypeRemoteclusterToken)
return session, nil
}
return nil, model.NewAppError("GetRemoteClusterSession", "api.context.invalid_token.error", map[string]interface{}{"Token": token, "Error": ""}, "The provided token is invalid", http.StatusUnauthorized)
@@ -98,7 +98,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) {
if *a.Config().ServiceSettings.SessionIdleTimeoutInMinutes > 0 &&
!session.IsOAuth && !session.IsMobileApp() &&
session.Props[model.SESSION_PROP_TYPE] != model.SESSION_TYPE_USER_ACCESS_TOKEN &&
session.Props[model.SessionPropType] != model.SessionTypeUserAccessToken &&
!*a.Config().ServiceSettings.ExtendSessionLengthWithActivity {
timeout := int64(*a.Config().ServiceSettings.SessionIdleTimeoutInMinutes) * 1000 * 60
@@ -239,7 +239,7 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) {
a.UpdateWebConnUserActivity(session, now)
if now-session.LastActivityAt < model.SESSION_ACTIVITY_TIMEOUT {
if now-session.LastActivityAt < model.SessionActivityTimeout {
return
}
@@ -407,17 +407,17 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio
IsOAuth: false,
}
session.AddProp(model.SESSION_PROP_USER_ACCESS_TOKEN_ID, token.Id)
session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_USER_ACCESS_TOKEN)
session.AddProp(model.SessionPropUserAccessTokenId, token.Id)
session.AddProp(model.SessionPropType, model.SessionTypeUserAccessToken)
if user.IsBot {
session.AddProp(model.SESSION_PROP_IS_BOT, model.SESSION_PROP_IS_BOT_VALUE)
session.AddProp(model.SessionPropIsBot, model.SessionPropIsBotValue)
}
if user.IsGuest() {
session.AddProp(model.SESSION_PROP_IS_GUEST, "true")
session.AddProp(model.SessionPropIsGuest, "true")
} else {
session.AddProp(model.SESSION_PROP_IS_GUEST, "false")
session.AddProp(model.SessionPropIsGuest, "false")
}
a.srv.userService.SetSessionExpireInDays(session, model.SESSION_USER_ACCESS_TOKEN_EXPIRY)
a.srv.userService.SetSessionExpireInDays(session, model.SessionUserAccessTokenExpiry)
session, nErr = a.Srv().Store.Session().Save(session)
if nErr != nil {

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

@@ -64,7 +64,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) {
session = &model.Session{
UserId: model.NewId(),
}
session.AddProp(model.SESSION_PROP_TYPE, model.SESSION_TYPE_USER_ACCESS_TOKEN)
session.AddProp(model.SessionPropType, model.SessionTypeUserAccessToken)
session, _ = th.App.CreateSession(session)
time = session.LastActivityAt - (1000 * 60 * 6)
@@ -103,48 +103,48 @@ func TestUpdateSessionOnPromoteDemote(t *testing.T) {
t.Run("Promote Guest to User updates the session", func(t *testing.T) {
guest := th.CreateGuest()
session, err := th.App.CreateSession(&model.Session{UserId: guest.Id, Props: model.StringMap{model.SESSION_PROP_IS_GUEST: "true"}})
session, err := th.App.CreateSession(&model.Session{UserId: guest.Id, Props: model.StringMap{model.SessionPropIsGuest: "true"}})
require.Nil(t, err)
rsession, err := th.App.GetSession(session.Token)
require.Nil(t, err)
assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST])
assert.Equal(t, "true", rsession.Props[model.SessionPropIsGuest])
err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id)
require.Nil(t, err)
rsession, err = th.App.GetSession(session.Token)
require.Nil(t, err)
assert.Equal(t, "false", rsession.Props[model.SESSION_PROP_IS_GUEST])
assert.Equal(t, "false", rsession.Props[model.SessionPropIsGuest])
th.App.ClearSessionCacheForUser(session.UserId)
rsession, err = th.App.GetSession(session.Token)
require.Nil(t, err)
assert.Equal(t, "false", rsession.Props[model.SESSION_PROP_IS_GUEST])
assert.Equal(t, "false", rsession.Props[model.SessionPropIsGuest])
})
t.Run("Demote User to Guest updates the session", func(t *testing.T) {
user := th.CreateUser()
session, err := th.App.CreateSession(&model.Session{UserId: user.Id, Props: model.StringMap{model.SESSION_PROP_IS_GUEST: "false"}})
session, err := th.App.CreateSession(&model.Session{UserId: user.Id, Props: model.StringMap{model.SessionPropIsGuest: "false"}})
require.Nil(t, err)
rsession, err := th.App.GetSession(session.Token)
require.Nil(t, err)
assert.Equal(t, "false", rsession.Props[model.SESSION_PROP_IS_GUEST])
assert.Equal(t, "false", rsession.Props[model.SessionPropIsGuest])
err = th.App.DemoteUserToGuest(user)
require.Nil(t, err)
rsession, err = th.App.GetSession(session.Token)
require.Nil(t, err)
assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST])
assert.Equal(t, "true", rsession.Props[model.SessionPropIsGuest])
th.App.ClearSessionCacheForUser(session.UserId)
rsession, err = th.App.GetSession(session.Token)
require.Nil(t, err)
assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST])
assert.Equal(t, "true", rsession.Props[model.SessionPropIsGuest])
})
}
@@ -175,7 +175,7 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) {
session := &model.Session{
UserId: model.NewId(),
Props: map[string]string{
model.USER_AUTH_SERVICE_IS_MOBILE: "true",
model.UserAuthServiceIsMobile: "true",
},
}
session, err := th.App.CreateSession(session)
@@ -189,8 +189,8 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) {
session := &model.Session{
UserId: model.NewId(),
Props: map[string]string{
model.USER_AUTH_SERVICE_IS_MOBILE: "true",
model.USER_AUTH_SERVICE_IS_SAML: "true",
model.UserAuthServiceIsMobile: "true",
model.UserAuthServiceIsSaml: "true",
},
}
session, err := th.App.CreateSession(session)
@@ -204,7 +204,7 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) {
session := &model.Session{
UserId: model.NewId(),
Props: map[string]string{
model.USER_AUTH_SERVICE_IS_OAUTH: "true",
model.UserAuthServiceIsOAuth: "true",
},
}
session, err := th.App.CreateSession(session)
@@ -218,7 +218,7 @@ func TestApp_GetSessionLengthInMillis(t *testing.T) {
session := &model.Session{
UserId: model.NewId(),
Props: map[string]string{
model.USER_AUTH_SERVICE_IS_SAML: "true",
model.UserAuthServiceIsSaml: "true",
}}
session, err := th.App.CreateSession(session)
require.Nil(t, err)

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

@@ -15,15 +15,15 @@ import (
)
var sharedChannelEventsForSync model.StringArray = []string{
model.WEBSOCKET_EVENT_POSTED,
model.WEBSOCKET_EVENT_POST_EDITED,
model.WEBSOCKET_EVENT_POST_DELETED,
model.WEBSOCKET_EVENT_REACTION_ADDED,
model.WEBSOCKET_EVENT_REACTION_REMOVED,
model.WebsocketEventPosted,
model.WebsocketEventPostEdited,
model.WebsocketEventPostDeleted,
model.WebsocketEventReactionAdded,
model.WebsocketEventReactionRemoved,
}
var sharedChannelEventsForInvitation model.StringArray = []string{
model.WEBSOCKET_EVENT_DIRECT_ADDED,
model.WebsocketEventDirectAdded,
}
// SharedChannelSyncHandler is called when a websocket event is received by a cluster node.

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

@@ -33,7 +33,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) {
th.App.srv.SetSharedChannelSyncService(mockService)
channel := th.CreateChannel(th.BasicTeam, WithShared(true))
websocketEvent := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_ADDED_TO_TEAM, model.NewId(), channel.Id, "", nil)
websocketEvent := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, model.NewId(), channel.Id, "", nil)
th.App.srv.SharedChannelSyncHandler(websocketEvent)
assert.Empty(t, mockService.channelNotifications)
@@ -47,7 +47,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) {
mockService.active = true
th.App.srv.SetSharedChannelSyncService(mockService)
websocketEvent := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, model.NewId(), model.NewId(), "", nil)
websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), model.NewId(), "", nil)
th.App.srv.SharedChannelSyncHandler(websocketEvent)
assert.Empty(t, mockService.channelNotifications)
@@ -62,7 +62,7 @@ func TestServerSyncSharedChannelHandler(t *testing.T) {
th.App.srv.SetSharedChannelSyncService(mockService)
channel := th.CreateChannel(th.BasicTeam, WithShared(true))
websocketEvent := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_POSTED, model.NewId(), channel.Id, "", nil)
websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), channel.Id, "", nil)
th.App.srv.SharedChannelSyncHandler(websocketEvent)
assert.Len(t, mockService.channelNotifications, 1)

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

@@ -10,11 +10,11 @@ import (
const (
UserPassword = "Usr@MMTest123"
ChannelType = model.CHANNEL_OPEN
ChannelType = model.ChannelTypeOpen
BTestTeamDisplayName = "TestTeam"
BTestTeamName = "z-z-testdomaina"
BTestTeamEmail = "test@nowhere.com"
BTestTeamType = model.TEAM_OPEN
BTestTeamType = model.TeamOpen
BTestUserName = "Mr. Testing Tester"
BTestUserEmail = "success+ttester@simulator.amazonses.com"
BTestUserPassword = "passwd"

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

@@ -54,7 +54,7 @@ func (cfg *AutoTeamCreator) createRandomTeam() (*model.Team, error) {
DisplayName: teamDisplayName,
Name: teamName,
Email: teamEmail,
Type: model.TEAM_OPEN,
Type: model.TeamOpen,
}
createdTeam, resp := cfg.client.CreateTeam(team)

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

@@ -99,7 +99,7 @@ func (cfg *AutoUserCreator) createRandomUser(c *request.Context) (*model.User, e
return nil, appErr
}
status := &model.Status{UserId: ruser.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""}
status := &model.Status{UserId: ruser.Id, Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""}
if err := cfg.app.Srv().Store.Status().SaveOrUpdate(status); err != nil {
return nil, err
}

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

@@ -37,5 +37,5 @@ func (*AwayProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command
func (*AwayProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
a.SetStatusAwayIfNeeded(args.UserId, true)
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")}
return &model.CommandResponse{ResponseType: model.CommandResponseTypeEphemeral, Text: args.T("api.command_away.success")}
}

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

@@ -42,49 +42,49 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com
if err != nil {
return &model.CommandResponse{
Text: args.T("api.command_channel_header.channel.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}
switch channel.Type {
case model.CHANNEL_OPEN:
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) {
case model.ChannelTypeOpen:
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePublicChannelProperties) {
return &model.CommandResponse{
Text: args.T("api.command_channel_header.permission.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}
case model.CHANNEL_PRIVATE:
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) {
case model.ChannelTypePrivate:
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PermissionManagePrivateChannelProperties) {
return &model.CommandResponse{
Text: args.T("api.command_channel_header.permission.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}
case model.CHANNEL_GROUP, model.CHANNEL_DIRECT:
case model.ChannelTypeGroup, model.ChannelTypeDirect:
// Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership.
var channelMember *model.ChannelMember
channelMember, err = a.GetChannelMember(context.Background(), args.ChannelId, args.UserId)
if err != nil || channelMember == nil {
return &model.CommandResponse{
Text: args.T("api.command_channel_header.permission.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}
default:
return &model.CommandResponse{
Text: args.T("api.command_channel_header.permission.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}
if message == "" {
return &model.CommandResponse{
Text: args.T("api.command_channel_header.message.app_error"),
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}
@@ -98,13 +98,13 @@ func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.Com
text := args.T("api.command_channel_header.update_channel.app_error")
if err.Id == "model.channel.is_valid.header.app_error" {
text = args.T("api.command_channel_header.update_channel.max_length", map[string]interface{}{
"MaxLength": model.CHANNEL_HEADER_MAX_RUNES,
"MaxLength": model.ChannelHeaderMaxRunes,
})
}
return &model.CommandResponse{
Text: text,
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
ResponseType: model.CommandResponseTypeEphemeral,
}
}

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

@@ -17,7 +17,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
hp := HeaderProvider{}
th.addPermissionToRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
th.addPermissionToRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId)
// Try a public channel *with* permission.
args := &model.CommandArgs{
@@ -34,7 +34,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
assert.Equal(t, expected, actual)
}
th.removePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
th.removePermissionFromRole(model.PermissionManagePublicChannelProperties.Id, model.ChannelUserRoleId)
// Try a public channel *without* permission.
args = &model.CommandArgs{
@@ -46,7 +46,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
actual := hp.DoCommand(th.App, th.Context, args, "hello").Text
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
th.addPermissionToRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId)
// Try a private channel *with* permission.
privateChannel := th.createPrivateChannel(th.BasicTeam)
@@ -60,7 +60,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
actual = hp.DoCommand(th.App, th.Context, args, "hello").Text
assert.Equal(t, "", actual)
th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
th.removePermissionFromRole(model.PermissionManagePrivateChannelProperties.Id, model.ChannelUserRoleId)
// Try a private channel *without* permission.
args = &model.CommandArgs{

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше