diff --git a/.golangci.yml b/.golangci.yml index 71c041aa53..29d9a4622a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -49,7 +49,11 @@ issues: - linters: - golint - text: "should have|should be|should replace|stutters|underscore|ALL_CAPS|annoying|error strings should not be capitalized" + text: "should have|should be|should replace|stutters|underscore|annoying|error strings should not be capitalized" + + - linters: + - golint + path: "model/" - linters: - misspell diff --git a/api4/channel.go b/api4/channel.go index 7b7ecef117..5bc3246f06 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -1481,7 +1481,7 @@ func addChannelMember(c *Context, w http.ResponseWriter, r *http.Request) { isNewMembership := false if _, err = c.App.GetChannelMember(member.ChannelId, member.UserId); err != nil { - if err.Id == app.MISSING_CHANNEL_MEMBER_ERROR { + if err.Id == app.MissingChannelMemberError { isNewMembership = true } else { c.Err = err diff --git a/api4/channel_test.go b/api4/channel_test.go index 1b2597ef13..d781e1fb28 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -2285,8 +2285,8 @@ func TestUpdateChannelRoles(t *testing.T) { defer th.TearDown() Client := th.Client - const CHANNEL_ADMIN = "channel_user channel_admin" - const CHANNEL_MEMBER = "channel_user" + const ChannelAdmin = "channel_user channel_admin" + const ChannelMember = "channel_user" // User 1 creates a channel, making them channel admin by default. channel := th.CreatePublicChannel() @@ -2295,44 +2295,44 @@ func TestUpdateChannelRoles(t *testing.T) { th.App.AddUserToChannel(th.BasicUser2, channel) // User 1 promotes User 2 - pass, resp := Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN) + pass, resp := Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, ChannelAdmin) CheckNoError(t, resp) require.True(t, pass, "should have passed") member, resp := Client.GetChannelMember(channel.Id, th.BasicUser2.Id, "") CheckNoError(t, resp) - require.Equal(t, CHANNEL_ADMIN, member.Roles, "roles don't match") + require.Equal(t, ChannelAdmin, member.Roles, "roles don't match") // User 1 demotes User 2 - _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_MEMBER) + _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, ChannelMember) CheckNoError(t, resp) th.LoginBasic2() // User 2 cannot demote User 1 - _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER) + _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelMember) CheckForbiddenStatus(t, resp) // User 2 cannot promote self - _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, CHANNEL_ADMIN) + _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser2.Id, ChannelAdmin) CheckForbiddenStatus(t, resp) th.LoginBasic() // User 1 demotes self - _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER) + _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelMember) CheckNoError(t, resp) // System Admin promotes User 1 - _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN) + _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelAdmin) CheckNoError(t, resp) // System Admin demotes User 1 - _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_MEMBER) + _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelMember) CheckNoError(t, resp) // System Admin promotes User 1 - _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, CHANNEL_ADMIN) + _, resp = th.SystemAdminClient.UpdateChannelRoles(channel.Id, th.BasicUser.Id, ChannelAdmin) CheckNoError(t, resp) th.LoginBasic() @@ -2340,16 +2340,16 @@ func TestUpdateChannelRoles(t *testing.T) { _, resp = Client.UpdateChannelRoles(channel.Id, th.BasicUser.Id, "junk") CheckBadRequestStatus(t, resp) - _, resp = Client.UpdateChannelRoles(channel.Id, "junk", CHANNEL_MEMBER) + _, resp = Client.UpdateChannelRoles(channel.Id, "junk", ChannelMember) CheckBadRequestStatus(t, resp) - _, resp = Client.UpdateChannelRoles("junk", th.BasicUser.Id, CHANNEL_MEMBER) + _, resp = Client.UpdateChannelRoles("junk", th.BasicUser.Id, ChannelMember) CheckBadRequestStatus(t, resp) - _, resp = Client.UpdateChannelRoles(channel.Id, model.NewId(), CHANNEL_MEMBER) + _, resp = Client.UpdateChannelRoles(channel.Id, model.NewId(), ChannelMember) CheckNotFoundStatus(t, resp) - _, resp = Client.UpdateChannelRoles(model.NewId(), th.BasicUser.Id, CHANNEL_MEMBER) + _, resp = Client.UpdateChannelRoles(model.NewId(), th.BasicUser.Id, ChannelMember) CheckForbiddenStatus(t, resp) } diff --git a/api4/emoji.go b/api4/emoji.go index 49402cc710..13b8f2c424 100644 --- a/api4/emoji.go +++ b/api4/emoji.go @@ -16,7 +16,7 @@ import ( ) const ( - EMOJI_MAX_AUTOCOMPLETE_ITEMS = 100 + EmojiMaxAutocompleteItems = 100 ) func (api *API) InitEmoji() { @@ -256,7 +256,7 @@ func searchEmojis(c *Context, w http.ResponseWriter, r *http.Request) { return } - emojis, err := c.App.SearchEmoji(emojiSearch.Term, emojiSearch.PrefixOnly, web.PER_PAGE_MAXIMUM) + emojis, err := c.App.SearchEmoji(emojiSearch.Term, emojiSearch.PrefixOnly, web.PerPageMaximum) if err != nil { c.Err = err return @@ -273,7 +273,7 @@ func autocompleteEmojis(c *Context, w http.ResponseWriter, r *http.Request) { return } - emojis, err := c.App.SearchEmoji(name, true, EMOJI_MAX_AUTOCOMPLETE_ITEMS) + emojis, err := c.App.SearchEmoji(name, true, EmojiMaxAutocompleteItems) if err != nil { c.Err = err return diff --git a/api4/file.go b/api4/file.go index 6fdd7acebb..5eb8c9e885 100644 --- a/api4/file.go +++ b/api4/file.go @@ -22,13 +22,13 @@ import ( ) const ( - FILE_TEAM_ID = "noteam" + FileTeamId = "noteam" - PREVIEW_IMAGE_TYPE = "image/jpeg" - THUMBNAIL_IMAGE_TYPE = "image/jpeg" + PreviewImageType = "image/jpeg" + ThumbnailImageType = "image/jpeg" ) -var UNSAFE_CONTENT_TYPES = [...]string{ +var UnsafeContentTypes = [...]string{ "application/javascript", "application/ecmascript", "text/javascript", @@ -37,7 +37,7 @@ var UNSAFE_CONTENT_TYPES = [...]string{ "text/html", } -var MEDIA_CONTENT_TYPES = [...]string{ +var MediaContentTypes = [...]string{ "image/jpeg", "image/png", "image/bmp", @@ -169,7 +169,7 @@ func uploadFileSimple(c *Context, r *http.Request, timestamp time.Time) *model.F auditRec.AddMeta("client_id", clientId) info, appErr := c.App.UploadFileX(c.Params.ChannelId, c.Params.Filename, r.Body, - app.UploadFileSetTeamId(FILE_TEAM_ID), + app.UploadFileSetTeamId(FileTeamId), app.UploadFileSetUserId(c.App.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(r.ContentLength), @@ -332,7 +332,7 @@ NEXT_PART: auditRec.AddMeta("client_id", clientId) info, appErr := c.App.UploadFileX(c.Params.ChannelId, filename, part, - app.UploadFileSetTeamId(FILE_TEAM_ID), + app.UploadFileSetTeamId(FileTeamId), app.UploadFileSetUserId(c.App.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(-1), @@ -435,7 +435,7 @@ func uploadFileMultipartLegacy(c *Context, mr *multipart.Reader, auditRec.AddMeta("client_id", clientId) info, appErr := c.App.UploadFileX(c.Params.ChannelId, fileHeader.Filename, f, - app.UploadFileSetTeamId(FILE_TEAM_ID), + app.UploadFileSetTeamId(FileTeamId), app.UploadFileSetUserId(c.App.Session().UserId), app.UploadFileSetTimestamp(timestamp), app.UploadFileSetContentLength(-1), @@ -532,7 +532,7 @@ func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) { } defer fileReader.Close() - err = writeFileResponse(info.Name, THUMBNAIL_IMAGE_TYPE, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r) + err = writeFileResponse(info.Name, ThumbnailImageType, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r) if err != nil { c.Err = err return @@ -611,7 +611,7 @@ func getFilePreview(c *Context, w http.ResponseWriter, r *http.Request) { } defer fileReader.Close() - err = writeFileResponse(info.Name, PREVIEW_IMAGE_TYPE, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r) + err = writeFileResponse(info.Name, PreviewImageType, 0, time.Unix(0, info.UpdateAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, forceDownload, w, r) if err != nil { c.Err = err return @@ -701,7 +701,7 @@ func writeFileResponse(filename string, contentType string, contentSize int64, l if contentType == "" { contentType = "application/octet-stream" } else { - for _, unsafeContentType := range UNSAFE_CONTENT_TYPES { + for _, unsafeContentType := range UnsafeContentTypes { if strings.HasPrefix(contentType, unsafeContentType) { contentType = "text/plain" break @@ -717,7 +717,7 @@ func writeFileResponse(filename string, contentType string, contentSize int64, l } else { isMediaType := false - for _, mediaContentType := range MEDIA_CONTENT_TYPES { + for _, mediaContentType := range MediaContentTypes { if strings.HasPrefix(contentType, mediaContentType) { isMediaType = true break diff --git a/api4/file_test.go b/api4/file_test.go index fbc1a12388..6469496512 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -635,7 +635,7 @@ func TestUploadFiles(t *testing.T) { _, fname := filepath.Split(dbInfo.Path) ext := filepath.Ext(fname) name := fname[:len(fname)-len(ext)] - expectedDir := fmt.Sprintf("%v/teams/%v/channels/%v/users/%s/%s", date, FILE_TEAM_ID, channel.Id, ri.CreatorId, ri.Id) + expectedDir := fmt.Sprintf("%v/teams/%v/channels/%v/users/%s/%s", date, FileTeamId, channel.Id, ri.CreatorId, ri.Id) expectedPath := fmt.Sprintf("%s/%s", expectedDir, fname) assert.Equal(t, dbInfo.Path, expectedPath, fmt.Sprintf("File %v saved to:%q, expected:%q", dbInfo.Name, dbInfo.Path, expectedPath)) diff --git a/api4/job.go b/api4/job.go index 45de6813a5..832390c651 100644 --- a/api4/job.go +++ b/api4/job.go @@ -44,8 +44,8 @@ func getJob(c *Context, w http.ResponseWriter, r *http.Request) { func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) { config := c.App.Config() - const FILE_PATH = "export" - const FILE_MIME = "application/zip" + const FilePath = "export" + const FileMime = "application/zip" c.RequireJobId() if c.Err != nil { @@ -75,7 +75,7 @@ func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) { } fileName := job.Id + ".zip" - filePath := filepath.Join(FILE_PATH, fileName) + filePath := filepath.Join(FilePath, fileName) fileReader, err := c.App.FileReader(filePath) if err != nil { c.Err = err @@ -86,7 +86,7 @@ func downloadJob(c *Context, w http.ResponseWriter, r *http.Request) { // We are able to pass 0 for content size due to the fact that Golang's serveContent (https://golang.org/src/net/http/fs.go) // already sets that for us - err = writeFileResponse(fileName, FILE_MIME, 0, time.Unix(0, job.LastActivityAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, true, w, r) + err = writeFileResponse(fileName, FileMime, 0, time.Unix(0, job.LastActivityAt*int64(1000*1000)), *c.App.Config().ServiceSettings.WebserverMode, fileReader, true, w, r) if err != nil { c.Err = err return diff --git a/api4/openGraph.go b/api4/openGraph.go index 72ac9135fa..eed7db7217 100644 --- a/api4/openGraph.go +++ b/api4/openGraph.go @@ -11,10 +11,10 @@ import ( "github.com/mattermost/mattermost-server/v5/services/cache" ) -const OPEN_GRAPH_METADATA_CACHE_SIZE = 10000 +const OpenGraphMetadataCacheSize = 10000 var openGraphDataCache = cache.NewLRU(cache.LRUOptions{ - Size: OPEN_GRAPH_METADATA_CACHE_SIZE, + Size: OpenGraphMetadataCacheSize, }) func (api *API) InitOpenGraph() { diff --git a/api4/plugin.go b/api4/plugin.go index 0ff1915606..71d78710a9 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -19,7 +19,7 @@ import ( ) const ( - MAXIMUM_PLUGIN_FILE_SIZE = 50 * 1024 * 1024 + MaximumPluginFileSize = 50 * 1024 * 1024 ) func (api *API) InitPlugin() { @@ -55,7 +55,7 @@ func uploadPlugin(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := r.ParseMultipartForm(MAXIMUM_PLUGIN_FILE_SIZE); err != nil { + if err := r.ParseMultipartForm(MaximumPluginFileSize); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } diff --git a/api4/post.go b/api4/post.go index aa635de26a..994fc4c7ef 100644 --- a/api4/post.go +++ b/api4/post.go @@ -253,7 +253,7 @@ func getPostsForChannelAroundLastUnread(c *Context, w http.ResponseWriter, r *ht return } - postList, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: app.PAGE_DEFAULT, PerPage: c.Params.LimitBefore, SkipFetchThreads: skipFetchThreads}) + postList, err = c.App.GetPostsPage(model.GetPostsOptions{ChannelId: channelId, Page: app.PageDefault, PerPage: c.Params.LimitBefore, SkipFetchThreads: skipFetchThreads}) if err != nil { c.Err = err return diff --git a/api4/post_test.go b/api4/post_test.go index 614d7d4f08..18547494c7 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -400,32 +400,32 @@ func testCreatePostWithOutgoingHook( } func TestCreatePostWithOutgoingHook_form_urlencoded(t *testing.T) { - testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false) - testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false) - testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false) - testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false) - testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, true) - testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, true) + testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, false) + testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsStartsWith, false) + testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TriggerwordsExactMatch, false) + testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TriggerwordsStartsWith, false) + testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, true) + testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsStartsWith, true) } func TestCreatePostWithOutgoingHook_json(t *testing.T) { - testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, false) - testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH, false) - testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false) - testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false) - testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, true) - testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, true) + testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, false) + testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TriggerwordsStartsWith, false) + testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "", []string{"file_id_1"}, app.TriggerwordsExactMatch, false) + testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TriggerwordsStartsWith, false) + testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, true) + testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TriggerwordsStartsWith, true) } // hooks created before we added the ContentType field should be considered as // application/x-www-form-urlencoded func TestCreatePostWithOutgoingHook_no_content_type(t *testing.T) { - testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false) - testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false) - testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, false) - testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH, false) - testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, true) - testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, true) + testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, false) + testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsStartsWith, false) + testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, false) + testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TriggerwordsStartsWith, false) + testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TriggerwordsExactMatch, true) + testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TriggerwordsExactMatch, true) } func TestCreatePostPublic(t *testing.T) { diff --git a/api4/system.go b/api4/system.go index 63acdbeaa5..5710c6e225 100644 --- a/api4/system.go +++ b/api4/system.go @@ -23,13 +23,13 @@ import ( ) const ( - REDIRECT_LOCATION_CACHE_SIZE = 10000 - DEFAULT_SERVER_BUSY_SECONDS = 3600 - MAX_SERVER_BUSY_SECONDS = 86400 + RedirectLocationCacheSize = 10000 + DefaultServerBusySeconds = 3600 + MaxServerBusySeconds = 86400 ) var redirectLocationDataCache = cache.NewLRU(cache.LRUOptions{ - Size: REDIRECT_LOCATION_CACHE_SIZE, + Size: RedirectLocationCacheSize, }) func (api *API) InitSystem() { @@ -512,12 +512,12 @@ func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { // number of seconds to keep server marked busy secs := r.URL.Query().Get("seconds") if secs == "" { - secs = strconv.FormatInt(DEFAULT_SERVER_BUSY_SECONDS, 10) + secs = strconv.FormatInt(DefaultServerBusySeconds, 10) } i, err := strconv.ParseInt(secs, 10, 64) - if err != nil || i <= 0 || i > MAX_SERVER_BUSY_SECONDS { - c.SetInvalidUrlParam(fmt.Sprintf("seconds must be 1 - %d", MAX_SERVER_BUSY_SECONDS)) + if err != nil || i <= 0 || i > MaxServerBusySeconds { + c.SetInvalidUrlParam(fmt.Sprintf("seconds must be 1 - %d", MaxServerBusySeconds)) return } diff --git a/api4/system_test.go b/api4/system_test.go index 08b24224a0..fcd6c747d7 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -588,7 +588,7 @@ func TestSetServerBusyInvalidParam(t *testing.T) { defer th.TearDown() th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { - params := []int{-1, 0, MAX_SERVER_BUSY_SECONDS + 1} + params := []int{-1, 0, MaxServerBusySeconds + 1} for _, p := range params { ok, resp := c.SetServerBusy(p) CheckBadRequestStatus(t, resp) diff --git a/api4/team.go b/api4/team.go index 6faa0f14f0..0fc815e4de 100644 --- a/api4/team.go +++ b/api4/team.go @@ -20,9 +20,9 @@ import ( ) const ( - MAX_ADD_MEMBERS_BATCH = 256 - MAXIMUM_BULK_IMPORT_SIZE = 10 * 1024 * 1024 - groupIDsParamPattern = "[^a-zA-Z0-9,]*" + MaxAddMembersBatch = 256 + MaximumBulkImportSize = 10 * 1024 * 1024 + groupIDsParamPattern = "[^a-zA-Z0-9,]*" ) var groupIDsQueryParamRegex *regexp.Regexp @@ -695,7 +695,7 @@ func addTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) { var err *model.AppError members := model.TeamMembersFromJson(r.Body) - if len(members) > MAX_ADD_MEMBERS_BATCH { + if len(members) > MaxAddMembersBatch { c.SetInvalidParam("too many members in batch") return } @@ -1094,7 +1094,7 @@ func importTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := r.ParseMultipartForm(MAXIMUM_BULK_IMPORT_SIZE); err != nil { + if err := r.ParseMultipartForm(MaximumBulkImportSize); err != nil { c.Err = model.NewAppError("importTeam", "api.team.import_team.parse.app_error", nil, err.Error(), http.StatusInternalServerError) return } diff --git a/api4/team_test.go b/api4/team_test.go index cff4849f16..939a10cfec 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -1855,7 +1855,7 @@ func TestAddTeamMember(t *testing.T) { Client.Login(otherUser.Email, otherUser.Password) token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": team.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -1878,7 +1878,7 @@ func TestAddTeamMember(t *testing.T) { require.Nil(t, tm, "should have not returned team member") // expired token of more than 50 hours - token = model.NewToken(app.TOKEN_TYPE_TEAM_INVITATION, "") + token = model.NewToken(app.TokenTypeTeamInvitation, "") token.CreateAt = model.GetMillis() - 1000*60*60*50 require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -1889,7 +1889,7 @@ func TestAddTeamMember(t *testing.T) { // invalid team id testId := GenerateTestId() token = model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": testId}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -1931,7 +1931,7 @@ func TestAddTeamMember(t *testing.T) { // Attempt to use a token on a group-constrained team token = model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": team.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -2359,42 +2359,42 @@ func TestUpdateTeamMemberRoles(t *testing.T) { Client := th.Client SystemAdminClient := th.SystemAdminClient - const TEAM_MEMBER = "team_user" - const TEAM_ADMIN = "team_user team_admin" + const TeamMember = "team_user" + const TeamAdmin = "team_user team_admin" // user 1 tries to promote user 2 - ok, resp := Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_ADMIN) + ok, resp := Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamAdmin) CheckForbiddenStatus(t, resp) require.False(t, ok, "should have returned false") // user 1 tries to promote himself - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TEAM_ADMIN) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TeamAdmin) CheckForbiddenStatus(t, resp) // user 1 tries to demote someone - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TEAM_MEMBER) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TeamMember) CheckForbiddenStatus(t, resp) // system admin promotes user 1 - ok, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TEAM_ADMIN) + ok, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TeamAdmin) CheckNoError(t, resp) require.True(t, ok, "should have returned true") // user 1 (team admin) promotes user 2 - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_ADMIN) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamAdmin) CheckNoError(t, resp) // user 1 (team admin) demotes user 2 (team admin) - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_MEMBER) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamMember) CheckNoError(t, resp) // user 1 (team admin) tries to demote system admin (not member of a team) - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TEAM_MEMBER) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TeamMember) CheckNotFoundStatus(t, resp) // user 1 (team admin) demotes system admin (member of a team) th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam) - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TEAM_MEMBER) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.SystemAdminUser.Id, TeamMember) CheckNoError(t, resp) // Note from API v3 // Note to anyone who thinks this (above) test is wrong: @@ -2403,19 +2403,19 @@ func TestUpdateTeamMemberRoles(t *testing.T) { // System admins should be able to manipulate permission no matter what their team level permissions are. // system admin promotes user 2 - _, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_ADMIN) + _, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamAdmin) CheckNoError(t, resp) // system admin demotes user 2 (team admin) - _, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TEAM_MEMBER) + _, resp = SystemAdminClient.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser2.Id, TeamMember) CheckNoError(t, resp) // user 1 (team admin) tries to promote himself to a random team - _, resp = Client.UpdateTeamMemberRoles(model.NewId(), th.BasicUser.Id, TEAM_ADMIN) + _, resp = Client.UpdateTeamMemberRoles(model.NewId(), th.BasicUser.Id, TeamAdmin) CheckForbiddenStatus(t, resp) // user 1 (team admin) tries to promote a random user - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, model.NewId(), TEAM_ADMIN) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, model.NewId(), TeamAdmin) CheckNotFoundStatus(t, resp) // user 1 (team admin) tries to promote invalid team permission @@ -2423,7 +2423,7 @@ func TestUpdateTeamMemberRoles(t *testing.T) { CheckBadRequestStatus(t, resp) // user 1 (team admin) demotes himself - _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TEAM_MEMBER) + _, resp = Client.UpdateTeamMemberRoles(th.BasicTeam.Id, th.BasicUser.Id, TeamMember) CheckNoError(t, resp) } diff --git a/api4/terms_of_service.go b/api4/terms_of_service.go index 2e01c6f39f..46b8c5506f 100644 --- a/api4/terms_of_service.go +++ b/api4/terms_of_service.go @@ -50,7 +50,7 @@ func createTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { } oldTermsOfService, err := c.App.GetLatestTermsOfService() - if err != nil && err.Id != app.ERROR_TERMS_OF_SERVICE_NO_ROWS_FOUND { + if err != nil && err.Id != app.ErrorTermsOfServiceNoRowsFound { c.Err = err return } diff --git a/api4/user.go b/api4/user.go index f5aa8eafdb..5978080daa 100644 --- a/api4/user.go +++ b/api4/user.go @@ -137,7 +137,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("token_type", token.Type) - if token.Type == app.TOKEN_TYPE_GUEST_INVITATION { + if token.Type == app.TokenTypeGuestInvitation { if c.App.Srv().License() == nil { c.Err = model.NewAppError("CreateUserWithToken", "api.user.create_user.guest_accounts.license.app_error", nil, "", http.StatusBadRequest) return diff --git a/api4/user_test.go b/api4/user_test.go index 1884764943..f43954cf6a 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -194,7 +194,7 @@ func TestCreateUserWithToken(t *testing.T) { t.Run("CreateWithTokenHappyPath", func(t *testing.T) { user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -219,7 +219,7 @@ func TestCreateUserWithToken(t *testing.T) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -244,7 +244,7 @@ func TestCreateUserWithToken(t *testing.T) { t.Run("NoToken", func(t *testing.T) { user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -260,7 +260,7 @@ func TestCreateUserWithToken(t *testing.T) { timeNow := time.Now() past49Hours := timeNow.Add(-49*time.Hour).UnixNano() / int64(time.Millisecond) token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) token.CreateAt = past49Hours @@ -290,7 +290,7 @@ func TestCreateUserWithToken(t *testing.T) { user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -310,7 +310,7 @@ func TestCreateUserWithToken(t *testing.T) { user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -327,7 +327,7 @@ func TestCreateUserWithToken(t *testing.T) { user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} token := model.NewToken( - app.TOKEN_TYPE_TEAM_INVITATION, + app.TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) diff --git a/app/analytics.go b/app/analytics.go index d32dd1efe8..ae73158563 100644 --- a/app/analytics.go +++ b/app/analytics.go @@ -12,8 +12,8 @@ import ( ) const ( - DAY_MILLISECONDS = 24 * 60 * 60 * 1000 - MONTH_MILLISECONDS = 31 * DAY_MILLISECONDS + DayMilliseconds = 24 * 60 * 60 * 1000 + MonthMilliseconds = 31 * DayMilliseconds ) func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *model.AppError) { @@ -93,14 +93,14 @@ func (a *App) GetAnalytics(name string, teamId string) (model.AnalyticsRows, *mo dailyActiveChan := make(chan store.StoreResult, 1) go func() { - dailyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + dailyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) dailyActiveChan <- store.StoreResult{Data: dailyActive, NErr: err2} close(dailyActiveChan) }() monthlyActiveChan := make(chan store.StoreResult, 1) go func() { - monthlyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + monthlyActive, err2 := a.Srv().Store.User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) monthlyActiveChan <- store.StoreResult{Data: monthlyActive, NErr: err2} close(monthlyActiveChan) }() diff --git a/app/bot.go b/app/bot.go index a7b6be191b..ecd4b16cc6 100644 --- a/app/bot.go +++ b/app/bot.go @@ -158,7 +158,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("PatchBot", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("PatchBot", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("PatchBot", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -235,7 +235,7 @@ func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("PatchBot", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("PatchBot", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("PatchBot", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } diff --git a/app/brand.go b/app/brand.go index 7710c0647f..4853af9cf1 100644 --- a/app/brand.go +++ b/app/brand.go @@ -17,8 +17,8 @@ import ( ) const ( - BRAND_FILE_PATH = "brand/" - BRAND_FILE_NAME = "image.png" + BrandFilePath = "brand/" + BrandFileName = "image.png" ) func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { @@ -59,9 +59,9 @@ func (a *App) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { } t := time.Now() - a.MoveFile(BRAND_FILE_PATH+BRAND_FILE_NAME, BRAND_FILE_PATH+t.Format("2006-01-02T15:04:05")+".png") + a.MoveFile(BrandFilePath+BrandFileName, BrandFilePath+t.Format("2006-01-02T15:04:05")+".png") - if _, err := a.WriteFile(buf, BRAND_FILE_PATH+BRAND_FILE_NAME); err != nil { + if _, err := a.WriteFile(buf, BrandFilePath+BrandFileName); err != nil { return model.NewAppError("SaveBrandImage", "brand.save_brand_image.save_image.app_error", nil, "", http.StatusInternalServerError) } @@ -73,7 +73,7 @@ func (a *App) GetBrandImage() ([]byte, *model.AppError) { return nil, model.NewAppError("GetBrandImage", "api.admin.get_brand_image.storage.app_error", nil, "", http.StatusNotImplemented) } - img, err := a.ReadFile(BRAND_FILE_PATH + BRAND_FILE_NAME) + img, err := a.ReadFile(BrandFilePath + BrandFileName) if err != nil { return nil, err } @@ -82,7 +82,7 @@ func (a *App) GetBrandImage() ([]byte, *model.AppError) { } func (a *App) DeleteBrandImage() *model.AppError { - filePath := BRAND_FILE_PATH + BRAND_FILE_NAME + filePath := BrandFilePath + BrandFileName fileExists, err := a.FileExists(filePath) diff --git a/app/busy.go b/app/busy.go index 3541138554..63582c8f80 100644 --- a/app/busy.go +++ b/app/busy.go @@ -13,7 +13,7 @@ import ( ) const ( - TIMESTAMP_FORMAT = "Mon Jan 2 15:04:05 -0700 MST 2006" + TimestampFormat = "Mon Jan 2 15:04:05 -0700 MST 2006" ) // Busy represents the busy state of the server. A server marked busy @@ -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(TIMESTAMP_FORMAT)} + sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), Expires_ts: b.expires.UTC().Format(TimestampFormat)} b.notifyServerBusyChange(sbs) } } @@ -141,7 +141,7 @@ func (b *Busy) ToJson() string { sbs := &model.ServerBusyState{ Busy: atomic.LoadInt32(&b.busy) != 0, Expires: b.expires.Unix(), - Expires_ts: b.expires.UTC().Format(TIMESTAMP_FORMAT), + Expires_ts: b.expires.UTC().Format(TimestampFormat), } return sbs.ToJson() } diff --git a/app/channel.go b/app/channel.go index 40533940d6..e47be7513e 100644 --- a/app/channel.go +++ b/app/channel.go @@ -72,7 +72,7 @@ func (a *App) JoinDefaultChannels(teamId string, user *model.User, shouldBeAdmin var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return model.NewAppError("JoinDefaultChannels", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("JoinDefaultChannels", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("JoinDefaultChannels", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -249,7 +249,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.existing.app_error", nil, "id="+invErr.Value.(string), http.StatusBadRequest) } case errors.As(nErr, &cErr): - return sc, model.NewAppError("CreateChannel", store.CHANNEL_EXISTS_ERROR, nil, cErr.Error(), http.StatusBadRequest) + return sc, model.NewAppError("CreateChannel", store.ChannelExistsError, nil, cErr.Error(), http.StatusBadRequest) case errors.As(nErr, <Err): return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.limit.app_error", nil, ltErr.Error(), http.StatusBadRequest) case errors.As(nErr, &appErr): // in case we haven't converted to plain error. @@ -265,7 +265,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("CreateChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("CreateChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("CreateChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -324,7 +324,7 @@ func (a *App) GetOrCreateDirectChannel(userId, otherUserId string) (*model.Chann var err *model.AppError channel, err = a.createDirectChannel(userId, otherUserId) if err != nil { - if err.Id == store.CHANNEL_EXISTS_ERROR { + if err.Id == store.ChannelExistsError { return channel, nil } return nil, err @@ -401,7 +401,7 @@ func (a *App) createDirectChannel(userId string, otherUserId string) (*model.Cha case errors.As(nErr, &cErr): switch cErr.Resource { case "Channel": - return channel, model.NewAppError("CreateChannel", store.CHANNEL_EXISTS_ERROR, nil, cErr.Error(), http.StatusBadRequest) + return channel, model.NewAppError("CreateChannel", store.ChannelExistsError, nil, cErr.Error(), http.StatusBadRequest) case "ChannelMembers": return nil, model.NewAppError("CreateChannel", "app.channel.save_member.exists.app_error", nil, cErr.Error(), http.StatusBadRequest) } @@ -457,7 +457,7 @@ func (a *App) WaitForChannelMembership(channelId string, userId string) { func (a *App) CreateGroupChannel(userIds []string, creatorId string) (*model.Channel, *model.AppError) { channel, err := a.createGroupChannel(userIds, creatorId) if err != nil { - if err.Id == store.CHANNEL_EXISTS_ERROR { + if err.Id == store.ChannelExistsError { return channel, nil } return nil, err @@ -515,7 +515,7 @@ func (a *App) createGroupChannel(userIds []string, creatorId string) (*model.Cha return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.existing.app_error", nil, "id="+invErr.Value.(string), http.StatusBadRequest) } case errors.As(nErr, &cErr): - return channel, model.NewAppError("CreateChannel", store.CHANNEL_EXISTS_ERROR, nil, cErr.Error(), http.StatusBadRequest) + return channel, model.NewAppError("CreateChannel", store.ChannelExistsError, nil, cErr.Error(), http.StatusBadRequest) case errors.As(nErr, <Err): return nil, model.NewAppError("CreateChannel", "store.sql_channel.save_channel.limit.app_error", nil, ltErr.Error(), http.StatusBadRequest) case errors.As(nErr, &appErr): // in case we haven't converted to plain error. @@ -713,7 +713,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userId string) (*model.Chan var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("RestoreChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("RestoreChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("RestoreChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -1164,7 +1164,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe case errors.As(nErr, &appErr): return nil, appErr case errors.As(nErr, &nfErr): - return nil, model.NewAppError("updateChannelMember", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("updateChannelMember", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("updateChannelMember", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -1204,7 +1204,7 @@ func (a *App) DeleteChannel(channel *model.Channel, userId string) *model.AppErr var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return model.NewAppError("DeleteChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("DeleteChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("DeleteChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -1740,7 +1740,7 @@ func (a *App) GetChannelMember(channelId string, userId string) (*model.ChannelM var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): - return nil, model.NewAppError("GetChannelMember", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("GetChannelMember", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("GetChannelMember", "app.channel.get_member.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -1883,7 +1883,7 @@ func (a *App) JoinChannel(channel *model.Channel, userId string) *model.AppError var nfErr *store.ErrNotFound switch { case errors.As(uresult.NErr, &nfErr): - return model.NewAppError("CreateChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("CreateChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("CreateChannel", "app.user.get.app_error", nil, uresult.NErr.Error(), http.StatusInternalServerError) } @@ -2004,7 +2004,7 @@ func (a *App) LeaveChannel(channelId string, userId string) *model.AppError { var nfErr *store.ErrNotFound switch { case errors.As(uresult.NErr, &nfErr): - return model.NewAppError("LeaveChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("LeaveChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("LeaveChannel", "app.user.get.app_error", nil, uresult.NErr.Error(), http.StatusInternalServerError) } @@ -2144,7 +2144,7 @@ func (a *App) removeUserFromChannel(userIdToRemove string, removerUserId string, var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return model.NewAppError("removeUserFromChannel", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("removeUserFromChannel", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("removeUserFromChannel", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -2785,7 +2785,7 @@ func (a *App) ToggleMuteChannel(channelId, userId string) (*model.ChannelMember, case errors.As(nErr, &appErr): return nil, appErr case errors.As(nErr, &nfErr): - return nil, model.NewAppError("ToggleMuteChannel", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("ToggleMuteChannel", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("ToggleMuteChannel", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -2839,7 +2839,7 @@ func (a *App) setChannelsMuted(channelIds []string, userId string, muted bool) ( case errors.As(nErr, &appErr): return nil, appErr case errors.As(nErr, &nfErr): - return nil, model.NewAppError("setChannelsMuted", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("setChannelsMuted", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("setChannelsMuted", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError) } diff --git a/app/cluster_discovery.go b/app/cluster_discovery.go index c3bf7fee47..036e8f2d20 100644 --- a/app/cluster_discovery.go +++ b/app/cluster_discovery.go @@ -11,7 +11,7 @@ import ( ) const ( - DISCOVERY_SERVICE_WRITE_PING = 60 * time.Second + DiscoveryServiceWritePing = 60 * time.Second ) type ClusterDiscoveryService struct { @@ -58,7 +58,7 @@ func (cds *ClusterDiscoveryService) Start() { go func() { mlog.Debug("ClusterDiscoveryService ping writer started", mlog.String("ClusterDiscovery", cds.ClusterDiscovery.ToJson())) - ticker := time.NewTicker(DISCOVERY_SERVICE_WRITE_PING) + ticker := time.NewTicker(DiscoveryServiceWritePing) defer func() { ticker.Stop() if _, err := cds.srv.Store.ClusterDiscovery().Delete(&cds.ClusterDiscovery); err != nil { diff --git a/app/command.go b/app/command.go index 88073ef308..daf0020465 100644 --- a/app/command.go +++ b/app/command.go @@ -394,7 +394,7 @@ func (a *App) tryExecuteCustomCommand(args *model.CommandArgs, trigger string, m var nfErr *store.ErrNotFound switch { case errors.As(ur.NErr, &nfErr): - return nil, nil, model.NewAppError("tryExecuteCustomCommand", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, nil, model.NewAppError("tryExecuteCustomCommand", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, nil, model.NewAppError("tryExecuteCustomCommand", "app.user.get.app_error", nil, ur.NErr.Error(), http.StatusInternalServerError) } diff --git a/app/config.go b/app/config.go index 7861516537..fd806ffbf8 100644 --- a/app/config.go +++ b/app/config.go @@ -26,7 +26,7 @@ import ( ) const ( - ERROR_TERMS_OF_SERVICE_NO_ROWS_FOUND = "app.terms_of_service.get.no_rows.app_error" + ErrorTermsOfServiceNoRowsFound = "app.terms_of_service.get.no_rows.app_error" ) func (s *Server) Config() *model.Config { diff --git a/app/constants.go b/app/constants.go index 65ddc1d98b..59092e6ea8 100644 --- a/app/constants.go +++ b/app/constants.go @@ -3,6 +3,6 @@ package app -const MISSING_CHANNEL_MEMBER_ERROR = "app.channel.get_member.missing.app_error" -const MISSING_ACCOUNT_ERROR = "app.user.missing_account.const" -const MISSING_AUTH_ACCOUNT_ERROR = "app.user.get_by_auth.missing_account.app_error" +const MissingChannelMemberError = "app.channel.get_member.missing.app_error" +const MissingAccountError = "app.user.missing_account.const" +const MissingAuthAccountError = "app.user.get_by_auth.missing_account.app_error" diff --git a/app/download.go b/app/download.go index 627bee9d25..9f1c180498 100644 --- a/app/download.go +++ b/app/download.go @@ -17,9 +17,9 @@ import ( ) const ( - // HTTP_REQUEST_TIMEOUT defines a high timeout for downloading large files + // HTTPRequestTimeout defines a high timeout for downloading large files // from an external URL to avoid slow connections from failing to install. - HTTP_REQUEST_TIMEOUT = 1 * time.Hour + HTTPRequestTimeout = 1 * time.Hour ) func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) { @@ -36,7 +36,7 @@ func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) { } client := a.HTTPService().MakeClient(true) - client.Timeout = HTTP_REQUEST_TIMEOUT + client.Timeout = HTTPRequestTimeout var resp *http.Response err = utils.ProgressiveRetry(func() error { diff --git a/app/email.go b/app/email.go index 273e97e281..fcab7de697 100644 --- a/app/email.go +++ b/app/email.go @@ -359,7 +359,7 @@ func (es *EmailService) SendInviteEmails(team *model.Team, senderName string, se bodyPage.Props["TeamURL"] = siteURL + "/" + team.Name token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": team.Id, "email": invite}), ) @@ -429,7 +429,7 @@ func (es *EmailService) sendGuestInviteEmails(team *model.Team, channels []*mode } token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{ "teamId": team.Id, "channels": strings.Join(channelIds, " "), @@ -576,7 +576,7 @@ func (es *EmailService) CreateVerifyEmailToken(userId string, newEmail string) ( return nil, model.NewAppError("CreateVerifyEmailToken", "api.user.create_email_token.error", nil, "", http.StatusInternalServerError) } - token := model.NewToken(TOKEN_TYPE_VERIFY_EMAIL, string(jsonData)) + token := model.NewToken(TokenTypeVerifyEmail, string(jsonData)) if err = es.srv.Store.Token().Save(token); err != nil { var appErr *model.AppError diff --git a/app/email_batching.go b/app/email_batching.go index f53f92d361..06e89150dc 100644 --- a/app/email_batching.go +++ b/app/email_batching.go @@ -20,7 +20,7 @@ import ( ) const ( - EMAIL_BATCHING_TASK_NAME = "Email Batching" + EmailBatchingTaskName = "Email Batching" ) func (es *EmailService) InitEmailBatching() { @@ -72,7 +72,7 @@ func NewEmailBatchingJob(es *EmailService, bufferSize int) *EmailBatchingJob { func (job *EmailBatchingJob) Start() { mlog.Debug("Email batching job starting. Checking for pending emails periodically.", mlog.Int("interval_in_seconds", *job.server.Config().EmailSettings.EmailBatchingInterval)) - newTask := model.CreateRecurringTask(EMAIL_BATCHING_TASK_NAME, job.CheckPendingEmails, time.Duration(*job.server.Config().EmailSettings.EmailBatchingInterval)*time.Second) + newTask := model.CreateRecurringTask(EmailBatchingTaskName, job.CheckPendingEmails, time.Duration(*job.server.Config().EmailSettings.EmailBatchingInterval)*time.Second) job.taskMutex.Lock() oldTask := job.task diff --git a/app/file.go b/app/file.go index e6b6de734a..17fdbb38c1 100644 --- a/app/file.go +++ b/app/file.go @@ -67,9 +67,9 @@ const ( maxUploadInitialBufferSize = 1024 * 1024 // 1Mb // Deprecated - IMAGE_THUMBNAIL_PIXEL_WIDTH = 120 - IMAGE_THUMBNAIL_PIXEL_HEIGHT = 100 - IMAGE_PREVIEW_PIXEL_WIDTH = 1920 + ImageThumbnailPixelWidth = 120 + ImageThumbnailPixelHeight = 100 + ImagePreviewPixelWidth = 1920 ) func (a *App) FileBackend() (filesstore.FileBackend, *model.AppError) { diff --git a/app/helper_test.go b/app/helper_test.go index cab856700f..d4643fbb63 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -570,7 +570,7 @@ func (*TestHelper) ResetEmojisMigration() { mainHelper.GetClusterInterface().SendClearRoleCacheMessage() - if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": EMOJIS_PERMISSIONS_MIGRATION_KEY}); err != nil { + if _, err := sqlStore.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": EmojisPermissionsMigrationKey}); err != nil { panic(err) } } diff --git a/app/import_functions.go b/app/import_functions.go index 04718cdf5c..bfc3dc340e 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -936,7 +936,7 @@ func (a *App) importUserChannels(user *model.User, team *model.Team, teamMember case errors.As(nErr, &appErr): return appErr case errors.As(nErr, &nfErr): - return model.NewAppError("importUserChannels", MISSING_CHANNEL_MEMBER_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("importUserChannels", MissingChannelMemberError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("importUserChannels", "app.channel.get_member.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -1466,13 +1466,13 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m if len(userIds) == 2 { ch, err := a.createDirectChannel(userIds[0], userIds[1]) - if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { + if err != nil && err.Id != store.ChannelExistsError { return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_direct_channel.error", nil, err.Error(), http.StatusBadRequest) } channel = ch } else { ch, err := a.createGroupChannel(userIds, userIds[0]) - if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { + if err != nil && err.Id != store.ChannelExistsError { return model.NewAppError("BulkImport", "app.import.import_direct_channel.create_group_channel.error", nil, err.Error(), http.StatusBadRequest) } channel = ch @@ -1571,13 +1571,13 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun var ch *model.Channel if len(userIds) == 2 { ch, err = a.GetOrCreateDirectChannel(userIds[0], userIds[1]) - if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { + if err != nil && err.Id != store.ChannelExistsError { return line.LineNumber, model.NewAppError("BulkImport", "app.import.import_direct_post.create_direct_channel.error", nil, err.Error(), http.StatusBadRequest) } channel = ch } else { ch, err = a.createGroupChannel(userIds, userIds[0]) - if err != nil && err.Id != store.CHANNEL_EXISTS_ERROR { + if err != nil && err.Id != store.ChannelExistsError { return line.LineNumber, model.NewAppError("BulkImport", "app.import.import_direct_post.create_group_channel.error", nil, err.Error(), http.StatusBadRequest) } channel = ch diff --git a/app/import_functions_test.go b/app/import_functions_test.go index 4c1d79bb1a..76fa2051ff 100644 --- a/app/import_functions_test.go +++ b/app/import_functions_test.go @@ -3102,7 +3102,7 @@ func TestImportImportDirectChannel(t *testing.T) { user3.Id, } channel, appErr := th.App.createGroupChannel(userIds, th.BasicUser.Id) - require.Equal(t, appErr.Id, store.CHANNEL_EXISTS_ERROR) + require.Equal(t, appErr.Id, store.ChannelExistsError) require.Equal(t, channel.Header, *data.Header) // Import a channel with some favorites. @@ -3403,7 +3403,7 @@ func TestImportImportDirectPost(t *testing.T) { user3.Id, } channel, appErr = th.App.createGroupChannel(userIds, th.BasicUser.Id) - require.Equal(t, appErr.Id, store.CHANNEL_EXISTS_ERROR) + require.Equal(t, appErr.Id, store.ChannelExistsError) groupChannel = channel // Get the number of posts in the system. diff --git a/app/integration_action.go b/app/integration_action.go index 035c40430c..ac194f3e72 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -192,7 +192,7 @@ func (a *App) DoPostActionWithCookie(postId, actionId, userId, selectedOption st var nfErr *store.ErrNotFound switch { case errors.As(ur.NErr, &nfErr): - return "", model.NewAppError("DoPostActionWithCookie", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return "", model.NewAppError("DoPostActionWithCookie", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return "", model.NewAppError("DoPostActionWithCookie", "app.user.get.app_error", nil, ur.NErr.Error(), http.StatusInternalServerError) } diff --git a/app/layer_generators/main.go b/app/layer_generators/main.go index a79ce8374f..17e8ffc9b1 100644 --- a/app/layer_generators/main.go +++ b/app/layer_generators/main.go @@ -31,13 +31,13 @@ var ( ) const ( - OPEN_TRACING_PARAMS_MARKER = "@openTracingParams" - APP_ERROR_TYPE = "*model.AppError" - ERROR_TYPE = "error" + OpenTracingParamsMarker = "@openTracingParams" + AppErrorType = "*model.AppError" + ErrorType = "error" ) func isError(typeName string) bool { - return strings.Contains(typeName, APP_ERROR_TYPE) || strings.Contains(typeName, ERROR_TYPE) + return strings.Contains(typeName, AppErrorType) || strings.Contains(typeName, ErrorType) } func init() { @@ -108,8 +108,8 @@ func extractMethodMetadata(method *ast.Field, src []byte) methodData { if method.Doc != nil { for _, comment := range method.Doc.List { s := comment.Text - if idx := strings.Index(s, OPEN_TRACING_PARAMS_MARKER); idx != -1 { - for _, p := range strings.Split(s[idx+len(OPEN_TRACING_PARAMS_MARKER):], ",") { + if idx := strings.Index(s, OpenTracingParamsMarker); idx != -1 { + for _, p := range strings.Split(s[idx+len(OpenTracingParamsMarker):], ",") { paramsToTrace[strings.TrimSpace(p)] = true } } @@ -148,7 +148,7 @@ func extractMethodMetadata(method *ast.Field, src []byte) methodData { } } if !found { - log.Fatalf("Unable to find a parameter called '%s' (method '%s') that is mentioned in the '%s' comment. Maybe it was renamed?", paramName, method.Names[0].Name, OPEN_TRACING_PARAMS_MARKER) + log.Fatalf("Unable to find a parameter called '%s' (method '%s') that is mentioned in the '%s' comment. Maybe it was renamed?", paramName, method.Names[0].Name, OpenTracingParamsMarker) } } return methodData{Params: params, Results: results, ParamsToTrace: paramsToTrace} diff --git a/app/login.go b/app/login.go index e32f023182..38db548b02 100644 --- a/app/login.go +++ b/app/login.go @@ -83,7 +83,7 @@ func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken token = &model.Token{ Token: cwsToken, CreateAt: model.GetMillis(), - Type: TOKEN_TYPE_CWS_ACCESS, + Type: TokenTypeCWSAccess, } err := a.Srv().Store.Token().Save(token) if err != nil { @@ -125,7 +125,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) if id != "" { user, err := a.GetUser(id) if err != nil { - if err.Id != MISSING_ACCOUNT_ERROR { + if err.Id != MissingAccountError { err.StatusCode = http.StatusInternalServerError return nil, err } diff --git a/app/login_test.go b/app/login_test.go index 68c18bc57f..76a35beae1 100644 --- a/app/login_test.go +++ b/app/login_test.go @@ -47,7 +47,7 @@ func TestCWSLogin(t *testing.T) { th.App.Srv().SetLicense(license) t.Run("Should authenticate user when CWS login is enabled and tokens are equal", func(t *testing.T) { - token := model.NewToken(TOKEN_TYPE_CWS_ACCESS, "") + token := model.NewToken(TokenTypeCWSAccess, "") defer th.App.DeleteToken(token) os.Setenv("CWS_CLOUD_TOKEN", token.Token) user, err := th.App.AuthenticateUserForLogin("", th.BasicUser.Username, "", "", token.Token, false) @@ -60,7 +60,7 @@ func TestCWSLogin(t *testing.T) { }) t.Run("Should not authenticate the user when CWS token was used", func(t *testing.T) { - token := model.NewToken(TOKEN_TYPE_CWS_ACCESS, "") + token := model.NewToken(TokenTypeCWSAccess, "") os.Setenv("CWS_CLOUD_TOKEN", token.Token) require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) diff --git a/app/migrations.go b/app/migrations.go index a0571e013b..7f10c64b77 100644 --- a/app/migrations.go +++ b/app/migrations.go @@ -12,9 +12,9 @@ import ( "github.com/mattermost/mattermost-server/v5/utils" ) -const EMOJIS_PERMISSIONS_MIGRATION_KEY = "EmojisPermissionsMigrationComplete" -const GUEST_ROLES_CREATION_MIGRATION_KEY = "GuestRolesCreationMigrationComplete" -const SYSTEM_CONSOLE_ROLES_CREATION_MIGRATION_KEY = "SystemConsoleRolesCreationMigrationComplete" +const EmojisPermissionsMigrationKey = "EmojisPermissionsMigrationComplete" +const GuestRolesCreationMigrationKey = "GuestRolesCreationMigrationComplete" +const SystemConsoleRolesCreationMigrationKey = "SystemConsoleRolesCreationMigrationComplete" // This function migrates the default built in roles from code/config to the database. func (a *App) DoAdvancedPermissionsMigration() { @@ -91,7 +91,7 @@ func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error { func (a *App) DoEmojisPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(EMOJIS_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := a.Srv().Store.System().GetByName(EmojisPermissionsMigrationKey); err == nil { return } @@ -145,7 +145,7 @@ func (a *App) DoEmojisPermissionsMigration() { } system := model.System{ - Name: EMOJIS_PERMISSIONS_MIGRATION_KEY, + Name: EmojisPermissionsMigrationKey, Value: "true", } @@ -156,7 +156,7 @@ func (a *App) DoEmojisPermissionsMigration() { func (a *App) DoGuestRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(GUEST_ROLES_CREATION_MIGRATION_KEY); err == nil { + if _, err := a.Srv().Store.System().GetByName(GuestRolesCreationMigrationKey); err == nil { return } @@ -232,7 +232,7 @@ func (a *App) DoGuestRolesCreationMigration() { } system := model.System{ - Name: GUEST_ROLES_CREATION_MIGRATION_KEY, + Name: GuestRolesCreationMigrationKey, Value: "true", } @@ -243,7 +243,7 @@ func (a *App) DoGuestRolesCreationMigration() { func (a *App) DoSystemConsoleRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := a.Srv().Store.System().GetByName(SYSTEM_CONSOLE_ROLES_CREATION_MIGRATION_KEY); err == nil { + if _, err := a.Srv().Store.System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil { return } @@ -274,7 +274,7 @@ func (a *App) DoSystemConsoleRolesCreationMigration() { } system := model.System{ - Name: SYSTEM_CONSOLE_ROLES_CREATION_MIGRATION_KEY, + Name: SystemConsoleRolesCreationMigrationKey, Value: "true", } diff --git a/app/oauth.go b/app/oauth.go index 3578cfbb7a..4a3709120c 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -24,9 +24,9 @@ import ( ) const ( - OAUTH_COOKIE_MAX_AGE_SECONDS = 30 * 60 // 30 minutes - COOKIE_OAUTH = "MMOAUTH" - OPENID_SCOPE = "openid" + OauthCookieMaxAgeSeconds = 30 * 60 // 30 minutes + CookieOauth = "MMOAUTH" + OpenIDScope = "openid" ) func (a *App) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError) { @@ -567,7 +567,7 @@ func (a *App) getSSOProvider(service string) (einterfaces.OauthProvider, *model. 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, OPENID_SCOPE) { + if strings.Contains(*sso.Scope, OpenIDScope) { providerType = model.SERVICE_OPENID } provider := einterfaces.GetOauthProvider(providerType) @@ -603,7 +603,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamId string, to user, err := a.GetUserByAuth(model.NewString(*authUser.AuthData), service) if err != nil { - if err.Id == MISSING_AUTH_ACCOUNT_ERROR { + if err.Id == MissingAuthAccountError { user, err = a.CreateOAuthUser(service, bytes.NewReader(buf.Bytes()), teamId, tokenUser) } else { return nil, err @@ -654,7 +654,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email user, nErr := a.Srv().Store.User().GetByEmail(email) if nErr != nil { - return nil, model.NewAppError("CompleteSwitchWithOAuth", MISSING_ACCOUNT_ERROR, nil, nErr.Error(), http.StatusInternalServerError) + return nil, model.NewAppError("CompleteSwitchWithOAuth", MissingAccountError, nil, nErr.Error(), http.StatusInternalServerError) } if err := a.RevokeAllSessions(user.Id); err != nil { @@ -728,12 +728,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(OAUTH_COOKIE_MAX_AGE_SECONDS), 0) + expiresAt := time.Unix(model.GetMillis()/1000+int64(OauthCookieMaxAgeSeconds), 0) oauthCookie := &http.Cookie{ - Name: COOKIE_OAUTH, + Name: CookieOauth, Value: cookieValue, Path: subpath, - MaxAge: OAUTH_COOKIE_MAX_AGE_SECONDS, + MaxAge: OauthCookieMaxAgeSeconds, Expires: expiresAt, HttpOnly: true, Secure: secure, @@ -804,7 +804,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service return nil, "", stateProps, nil, model.NewAppError("AuthorizeOAuthUser", "api.user.authorize_oauth_user.invalid_state.app_error", nil, "", http.StatusBadRequest) } - cookie, cookieErr := r.Cookie(COOKIE_OAUTH) + 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) } @@ -822,7 +822,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service subpath, _ := utils.GetSubpathFromConfig(a.Config()) httpCookie := &http.Cookie{ - Name: COOKIE_OAUTH, + Name: CookieOauth, Value: "", Path: subpath, MaxAge: -1, diff --git a/app/oauth_test.go b/app/oauth_test.go index 93a8452d04..50f544c6e8 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -179,7 +179,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { if cookie != "" { request.AddCookie(&http.Cookie{ - Name: COOKIE_OAUTH, + Name: CookieOauth, Value: cookie, }) } diff --git a/app/permissions.go b/app/permissions.go index fbcafa0b92..d501166907 100644 --- a/app/permissions.go +++ b/app/permissions.go @@ -59,12 +59,12 @@ func (a *App) ResetPermissionsSystem() *model.AppError { } // Remove the "System" table entry that marks the emoji permissions migration as done. - if _, err := a.Srv().Store.System().PermanentDeleteByName(EMOJIS_PERMISSIONS_MIGRATION_KEY); err != nil { + if _, err := a.Srv().Store.System().PermanentDeleteByName(EmojisPermissionsMigrationKey); err != nil { return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) } // Remove the "System" table entry that marks the guest roles permissions migration as done. - if _, err := a.Srv().Store.System().PermanentDeleteByName(GUEST_ROLES_CREATION_MIGRATION_KEY); err != nil { + if _, err := a.Srv().Store.System().PermanentDeleteByName(GuestRolesCreationMigrationKey); err != nil { return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/permissions_migrations.go b/app/permissions_migrations.go index 5758a5cf23..7a9d794b5e 100644 --- a/app/permissions_migrations.go +++ b/app/permissions_migrations.go @@ -20,57 +20,57 @@ type permissionTransformation struct { type permissionsMap []permissionTransformation const ( - PERMISSION_MANAGE_SYSTEM = "manage_system" - PERMISSION_MANAGE_TEAM = "manage_team" - PERMISSION_MANAGE_EMOJIS = "manage_emojis" - PERMISSION_MANAGE_OTHERS_EMOJIS = "manage_others_emojis" - PERMISSION_CREATE_EMOJIS = "create_emojis" - PERMISSION_DELETE_EMOJIS = "delete_emojis" - PERMISSION_DELETE_OTHERS_EMOJIS = "delete_others_emojis" - PERMISSION_MANAGE_WEBHOOKS = "manage_webhooks" - PERMISSION_MANAGE_OTHERS_WEBHOOKS = "manage_others_webhooks" - PERMISSION_MANAGE_INCOMING_WEBHOOKS = "manage_incoming_webhooks" - PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS = "manage_others_incoming_webhooks" - PERMISSION_MANAGE_OUTGOING_WEBHOOKS = "manage_outgoing_webhooks" - PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS = "manage_others_outgoing_webhooks" - PERMISSION_LIST_PUBLIC_TEAMS = "list_public_teams" - PERMISSION_LIST_PRIVATE_TEAMS = "list_private_teams" - PERMISSION_JOIN_PUBLIC_TEAMS = "join_public_teams" - PERMISSION_JOIN_PRIVATE_TEAMS = "join_private_teams" - PERMISSION_PERMANENT_DELETE_USER = "permanent_delete_user" - PERMISSION_CREATE_BOT = "create_bot" - PERMISSION_READ_BOTS = "read_bots" - PERMISSION_READ_OTHERS_BOTS = "read_others_bots" - PERMISSION_MANAGE_BOTS = "manage_bots" - PERMISSION_MANAGE_OTHERS_BOTS = "manage_others_bots" - PERMISSION_DELETE_PUBLIC_CHANNEL = "delete_public_channel" - PERMISSION_DELETE_PRIVATE_CHANNEL = "delete_private_channel" - PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES = "manage_public_channel_properties" - PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES = "manage_private_channel_properties" - PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE = "convert_public_channel_to_private" - PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC = "convert_private_channel_to_public" - PERMISSION_VIEW_MEMBERS = "view_members" - PERMISSION_INVITE_USER = "invite_user" - PERMISSION_INVITE_GUEST = "invite_guest" - PERMISSION_PROMOTE_GUEST = "promote_guest" - PERMISSION_DEMOTE_TO_GUEST = "demote_to_guest" - PERMISSION_USE_CHANNEL_MENTIONS = "use_channel_mentions" - PERMISSION_CREATE_POST = "create_post" - PERMISSION_CREATE_POST_PUBLIC = "create_post_public" - PERMISSION_USE_GROUP_MENTIONS = "use_group_mentions" - PERMISSION_ADD_REACTION = "add_reaction" - PERMISSION_REMOVE_REACTION = "remove_reaction" - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS = "manage_public_channel_members" - PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS = "manage_private_channel_members" - PERMISSION_READ_JOBS = "read_jobs" - PERMISSION_MANAGE_JOBS = "manage_jobs" - PERMISSION_READ_OTHER_USERS_TEAMS = "read_other_users_teams" - PERMISSION_EDIT_OTHER_USERS = "edit_other_users" - PERMISSION_READ_PUBLIC_CHANNEL_GROUPS = "read_public_channel_groups" - PERMISSION_READ_PRIVATE_CHANNEL_GROUPS = "read_private_channel_groups" - PERMISSION_EDIT_BRAND = "edit_brand" - PERMISSION_MANAGE_SHARED_CHANNELS = "manage_shared_channels" - PERMISSION_MANAGE_REMOTE_CLUSTERS = "manage_remote_clusters" + PermissionManageSystem = "manage_system" + PermissionManageTeam = "manage_team" + PermissionManageEmojis = "manage_emojis" + PermissionManageOthersEmojis = "manage_others_emojis" + PermissionCreateEmojis = "create_emojis" + PermissionDeleteEmojis = "delete_emojis" + PermissionDeleteOthersEmojis = "delete_others_emojis" + PermissionManageWebhooks = "manage_webhooks" + PermissionManageOthersWebhooks = "manage_others_webhooks" + PermissionManageIncomingWebhooks = "manage_incoming_webhooks" + PermissionManageOthersIncomingWebhooks = "manage_others_incoming_webhooks" + PermissionManageOutgoingWebhooks = "manage_outgoing_webhooks" + PermissionManageOthersOutgoingWebhooks = "manage_others_outgoing_webhooks" + PermissionListPublicTeams = "list_public_teams" + PermissionListPrivateTeams = "list_private_teams" + PermissionJoinPublicTeams = "join_public_teams" + PermissionJoinPrivateTeams = "join_private_teams" + PermissionPermanentDeleteUser = "permanent_delete_user" + PermissionCreateBot = "create_bot" + PermissionReadBots = "read_bots" + PermissionReadOthersBots = "read_others_bots" + PermissionManageBots = "manage_bots" + PermissionManageOthersBots = "manage_others_bots" + PermissionDeletePublicChannel = "delete_public_channel" + PermissionDeletePrivateChannel = "delete_private_channel" + PermissionManagePublicChannelProperties = "manage_public_channel_properties" + PermissionManagePrivateChannelProperties = "manage_private_channel_properties" + PermissionConvertPublicChannelToPrivate = "convert_public_channel_to_private" + PermissionConvertPrivateChannelToPublic = "convert_private_channel_to_public" + PermissionViewMembers = "view_members" + PermissionInviteUser = "invite_user" + PermissionInviteGuest = "invite_guest" + PermissionPromoteGuest = "promote_guest" + PermissionDemoteToGuest = "demote_to_guest" + PermissionUseChannelMentions = "use_channel_mentions" + PermissionCreatePost = "create_post" + PermissionCreatePost_PUBLIC = "create_post_public" + PermissionUseGroupMentions = "use_group_mentions" + PermissionAddReaction = "add_reaction" + PermissionRemoveReaction = "remove_reaction" + PermissionManagePublicChannelMembers = "manage_public_channel_members" + PermissionManagePrivateChannelMembers = "manage_private_channel_members" + PermissionReadJobs = "read_jobs" + PermissionManageJobs = "manage_jobs" + PermissionReadOtherUsersTeams = "read_other_users_teams" + PermissionEditOtherUsers = "edit_other_users" + PermissionReadPublicChannelGroups = "read_public_channel_groups" + PermissionReadPrivateChannelGroups = "read_private_channel_groups" + PermissionEditBrand = "edit_brand" + PermissionManageSharedChannels = "manage_shared_channels" + PermissionManageRemoteClusters = "manage_remote_clusters" ) func isRole(roleName string) func(*model.Role, map[string]map[string]bool) bool { @@ -191,14 +191,14 @@ func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, ro func (a *App) getEmojisPermissionsSplitMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_EMOJIS), - Add: []string{PERMISSION_CREATE_EMOJIS, PERMISSION_DELETE_EMOJIS}, - Remove: []string{PERMISSION_MANAGE_EMOJIS}, + On: permissionExists(PermissionManageEmojis), + Add: []string{PermissionCreateEmojis, PermissionDeleteEmojis}, + Remove: []string{PermissionManageEmojis}, }, permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_OTHERS_EMOJIS), - Add: []string{PERMISSION_DELETE_OTHERS_EMOJIS}, - Remove: []string{PERMISSION_MANAGE_OTHERS_EMOJIS}, + On: permissionExists(PermissionManageOthersEmojis), + Add: []string{PermissionDeleteOthersEmojis}, + Remove: []string{PermissionManageOthersEmojis}, }, }, nil } @@ -206,14 +206,14 @@ func (a *App) getEmojisPermissionsSplitMigration() (permissionsMap, error) { func (a *App) getWebhooksPermissionsSplitMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_WEBHOOKS), - Add: []string{PERMISSION_MANAGE_INCOMING_WEBHOOKS, PERMISSION_MANAGE_OUTGOING_WEBHOOKS}, - Remove: []string{PERMISSION_MANAGE_WEBHOOKS}, + On: permissionExists(PermissionManageWebhooks), + Add: []string{PermissionManageIncomingWebhooks, PermissionManageOutgoingWebhooks}, + Remove: []string{PermissionManageWebhooks}, }, permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_OTHERS_WEBHOOKS), - Add: []string{PERMISSION_MANAGE_OTHERS_INCOMING_WEBHOOKS, PERMISSION_MANAGE_OTHERS_OUTGOING_WEBHOOKS}, - Remove: []string{PERMISSION_MANAGE_OTHERS_WEBHOOKS}, + On: permissionExists(PermissionManageOthersWebhooks), + Add: []string{PermissionManageOthersIncomingWebhooks, PermissionManageOthersOutgoingWebhooks}, + Remove: []string{PermissionManageOthersWebhooks}, }, }, nil } @@ -222,12 +222,12 @@ func (a *App) getListJoinPublicPrivateTeamsPermissionsMigration() (permissionsMa return permissionsMap{ permissionTransformation{ On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{PERMISSION_LIST_PRIVATE_TEAMS, PERMISSION_JOIN_PRIVATE_TEAMS}, + Add: []string{PermissionListPrivateTeams, PermissionJoinPrivateTeams}, Remove: []string{}, }, permissionTransformation{ On: isRole(model.SYSTEM_USER_ROLE_ID), - Add: []string{PERMISSION_LIST_PUBLIC_TEAMS, PERMISSION_JOIN_PUBLIC_TEAMS}, + Add: []string{PermissionListPublicTeams, PermissionJoinPublicTeams}, Remove: []string{}, }, }, nil @@ -236,8 +236,8 @@ func (a *App) getListJoinPublicPrivateTeamsPermissionsMigration() (permissionsMa func (a *App) removePermanentDeleteUserMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: permissionExists(PERMISSION_PERMANENT_DELETE_USER), - Remove: []string{PERMISSION_PERMANENT_DELETE_USER}, + On: permissionExists(PermissionPermanentDeleteUser), + Remove: []string{PermissionPermanentDeleteUser}, }, }, nil } @@ -246,7 +246,7 @@ func (a *App) getAddBotPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{PERMISSION_CREATE_BOT, PERMISSION_READ_BOTS, PERMISSION_READ_OTHERS_BOTS, PERMISSION_MANAGE_BOTS, PERMISSION_MANAGE_OTHERS_BOTS}, + Add: []string{PermissionCreateBot, PermissionReadBots, PermissionReadOthersBots, PermissionManageBots, PermissionManageOthersBots}, Remove: []string{}, }, }, nil @@ -255,20 +255,20 @@ 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(PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES))), - Add: []string{PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES}, + On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePrivateChannelProperties))), + Add: []string{PermissionManagePrivateChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PERMISSION_DELETE_PRIVATE_CHANNEL))), - Add: []string{PERMISSION_DELETE_PRIVATE_CHANNEL}, + On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePrivateChannel))), + Add: []string{PermissionDeletePrivateChannel}, }, permissionTransformation{ - On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES))), - Add: []string{PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES}, + On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionManagePublicChannelProperties))), + Add: []string{PermissionManagePublicChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PERMISSION_DELETE_PUBLIC_CHANNEL))), - Add: []string{PERMISSION_DELETE_PUBLIC_CHANNEL}, + On: permissionAnd(isRole(model.CHANNEL_USER_ROLE_ID), onOtherRole(model.TEAM_USER_ROLE_ID, permissionExists(PermissionDeletePublicChannel))), + Add: []string{PermissionDeletePublicChannel}, }, }, nil } @@ -276,20 +276,20 @@ func (a *App) applyChannelManageDeleteToChannelUser() (permissionsMap, error) { func (a *App) removeChannelManageDeleteFromTeamUser() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES)), - Remove: []string{PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES}, + On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePrivateChannelProperties)), + Remove: []string{PermissionManagePrivateChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_DELETE_PRIVATE_CHANNEL)), + On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePrivateChannel)), Remove: []string{model.PERMISSION_DELETE_PRIVATE_CHANNEL.Id}, }, permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES)), - Remove: []string{PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES}, + On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionManagePublicChannelProperties)), + Remove: []string{PermissionManagePublicChannelProperties}, }, permissionTransformation{ - On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PERMISSION_DELETE_PUBLIC_CHANNEL)), - Remove: []string{PERMISSION_DELETE_PUBLIC_CHANNEL}, + On: permissionAnd(isRole(model.TEAM_USER_ROLE_ID), permissionExists(PermissionDeletePublicChannel)), + Remove: []string{PermissionDeletePublicChannel}, }, }, nil } @@ -298,11 +298,11 @@ func (a *App) getViewMembersPermissionMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ On: isRole(model.SYSTEM_USER_ROLE_ID), - Add: []string{PERMISSION_VIEW_MEMBERS}, + Add: []string{PermissionViewMembers}, }, permissionTransformation{ On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{PERMISSION_VIEW_MEMBERS}, + Add: []string{PermissionViewMembers}, }, }, nil } @@ -311,7 +311,7 @@ func (a *App) getAddManageGuestsPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{PERMISSION_PROMOTE_GUEST, PERMISSION_DEMOTE_TO_GUEST, PERMISSION_INVITE_GUEST}, + Add: []string{PermissionPromoteGuest, PermissionDemoteToGuest, PermissionInviteGuest}, }, }, nil } @@ -327,11 +327,11 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) { } moderatedPermissionsMinusCreatePost := []string{ - PERMISSION_ADD_REACTION, - PERMISSION_REMOVE_REACTION, - PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS, - PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS, - PERMISSION_USE_CHANNEL_MENTIONS, + PermissionAddReaction, + PermissionRemoveReaction, + PermissionManagePublicChannelMembers, + PermissionManagePrivateChannelMembers, + PermissionUseChannelMentions, } teamAndChannelAdminConditionalTransformations := func(teamAdminID, channelAdminID, channelUserID, channelGuestID string) []permissionTransformation { @@ -373,14 +373,14 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) { // ensure all team scheme channel admins have create_post because it's not exposed via the UI trans := permissionTransformation{ On: isRole(ts.DefaultChannelAdminRole), - Add: []string{PERMISSION_CREATE_POST}, + Add: []string{PermissionCreatePost}, } transformations = append(transformations, trans) // ensure all team scheme team admins have create_post because it's not exposed via the UI trans = permissionTransformation{ On: isRole(ts.DefaultTeamAdminRole), - Add: []string{PERMISSION_CREATE_POST}, + Add: []string{PermissionCreatePost}, } transformations = append(transformations, trans) @@ -396,13 +396,13 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) { // ensure team admins have create_post transformations = append(transformations, permissionTransformation{ On: isRole(model.TEAM_ADMIN_ROLE_ID), - Add: []string{PERMISSION_CREATE_POST}, + Add: []string{PermissionCreatePost}, }) // ensure channel admins have create_post transformations = append(transformations, permissionTransformation{ On: isRole(model.CHANNEL_ADMIN_ROLE_ID), - Add: []string{PERMISSION_CREATE_POST}, + Add: []string{PermissionCreatePost}, }) // conditionally add all other moderated permissions to team and channel admins @@ -416,13 +416,13 @@ func (a *App) channelModerationPermissionsMigration() (permissionsMap, error) { // ensure system admin has all of the moderated permissions transformations = append(transformations, permissionTransformation{ On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: append(moderatedPermissionsMinusCreatePost, PERMISSION_CREATE_POST), + Add: append(moderatedPermissionsMinusCreatePost, PermissionCreatePost), }) // add the new use_channel_mentions permission to everyone who has create_post transformations = append(transformations, permissionTransformation{ - On: permissionOr(permissionExists(PERMISSION_CREATE_POST), permissionExists(PERMISSION_CREATE_POST_PUBLIC)), - Add: []string{PERMISSION_USE_CHANNEL_MENTIONS}, + On: permissionOr(permissionExists(PermissionCreatePost), permissionExists(PermissionCreatePost_PUBLIC)), + Add: []string{PermissionUseChannelMentions}, }) return transformations, nil @@ -434,9 +434,9 @@ func (a *App) getAddUseGroupMentionsPermissionMigration() (permissionsMap, error On: permissionAnd( isNotRole(model.CHANNEL_GUEST_ROLE_ID), isNotSchemeRole("Channel Guest Role for Scheme"), - permissionOr(permissionExists(PERMISSION_CREATE_POST), permissionExists(PERMISSION_CREATE_POST_PUBLIC)), + permissionOr(permissionExists(PermissionCreatePost), permissionExists(PermissionCreatePost_PUBLIC)), ), - Add: []string{PERMISSION_USE_GROUP_MENTIONS}, + Add: []string{PermissionUseGroupMentions}, }, }, nil } @@ -458,32 +458,32 @@ func (a *App) getAddSystemConsolePermissionsMigration() (permissionsMap, error) // add read_jobs to all roles with manage_jobs transformations = append(transformations, permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_JOBS), - Add: []string{PERMISSION_READ_JOBS}, + On: permissionExists(PermissionManageJobs), + Add: []string{PermissionReadJobs}, }) // add read_other_users_teams to all roles with edit_other_users transformations = append(transformations, permissionTransformation{ - On: permissionExists(PERMISSION_EDIT_OTHER_USERS), - Add: []string{PERMISSION_READ_OTHER_USERS_TEAMS}, + On: permissionExists(PermissionEditOtherUsers), + Add: []string{PermissionReadOtherUsersTeams}, }) // add read_public_channel_groups to all roles with manage_public_channel_members transformations = append(transformations, permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS), - Add: []string{PERMISSION_READ_PUBLIC_CHANNEL_GROUPS}, + On: permissionExists(PermissionManagePublicChannelMembers), + Add: []string{PermissionReadPublicChannelGroups}, }) // add read_private_channel_groups to all roles with manage_private_channel_members transformations = append(transformations, permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS), - Add: []string{PERMISSION_READ_PRIVATE_CHANNEL_GROUPS}, + On: permissionExists(PermissionManagePrivateChannelMembers), + Add: []string{PermissionReadPrivateChannelGroups}, }) // add edit_brand to all roles with manage_system transformations = append(transformations, permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_SYSTEM), - Add: []string{PERMISSION_EDIT_BRAND}, + On: permissionExists(PermissionManageSystem), + Add: []string{PermissionEditBrand}, }) return transformations, nil @@ -492,8 +492,8 @@ func (a *App) getAddSystemConsolePermissionsMigration() (permissionsMap, error) func (a *App) getAddConvertChannelPermissionsMigration() (permissionsMap, error) { return permissionsMap{ permissionTransformation{ - On: permissionExists(PERMISSION_MANAGE_TEAM), - Add: []string{PERMISSION_CONVERT_PUBLIC_CHANNEL_TO_PRIVATE, PERMISSION_CONVERT_PRIVATE_CHANNEL_TO_PUBLIC}, + On: permissionExists(PermissionManageTeam), + Add: []string{PermissionConvertPublicChannelToPrivate, PermissionConvertPrivateChannelToPublic}, }, }, nil } @@ -511,7 +511,7 @@ func (a *App) getAddManageSharedChannelsPermissionsMigration() (permissionsMap, return permissionsMap{ permissionTransformation{ On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{PERMISSION_MANAGE_SHARED_CHANNELS}, + Add: []string{PermissionManageSharedChannels}, }, }, nil } @@ -529,7 +529,7 @@ func (a *App) getAddManageRemoteClustersPermissionsMigration() (permissionsMap, return permissionsMap{ permissionTransformation{ On: isRole(model.SYSTEM_ADMIN_ROLE_ID), - Add: []string{PERMISSION_MANAGE_REMOTE_CLUSTERS}, + Add: []string{PermissionManageRemoteClusters}, }, }, nil } diff --git a/app/post.go b/app/post.go index 4ab5c0f188..d39106504f 100644 --- a/app/post.go +++ b/app/post.go @@ -21,9 +21,9 @@ import ( ) const ( - PENDING_POST_IDS_CACHE_SIZE = 25000 - PENDING_POST_IDS_CACHE_TTL = 30 * time.Second - PAGE_DEFAULT = 0 + PendingPostIDsCacheSize = 25000 + PendingPostIDsCacheTTL = 30 * time.Second + PageDefault = 0 ) func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) { @@ -58,7 +58,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnl var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("CreatePostAsUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("CreatePostAsUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("CreatePostAsUser", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -128,7 +128,7 @@ func (a *App) deduplicateCreatePost(post *model.Post) (foundPost *model.Post, er var postId string nErr := a.Srv().seenPendingPostIdsCache.Get(post.PendingPostId, &postId) if nErr == cache.ErrKeyNotFound { - a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, unknownPostId, PENDING_POST_IDS_CACHE_TTL) + a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, unknownPostId, PendingPostIDsCacheTTL) return nil, nil } @@ -176,7 +176,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo return } - a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, savedPost.Id, PENDING_POST_IDS_CACHE_TTL) + a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, savedPost.Id, PendingPostIDsCacheTTL) }() post.SanitizeProps() @@ -196,7 +196,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("CreatePost", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("CreatePost", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("CreatePost", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -318,7 +318,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo // Update the mapping from pending post id to the actual post id, for any clients that // might be duplicating requests. - a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, rpost.Id, PENDING_POST_IDS_CACHE_TTL) + a.Srv().seenPendingPostIdsCache.SetWithExpiry(post.PendingPostId, rpost.Id, PendingPostIDsCacheTTL) // We make a copy of the post for the plugin hook to avoid a race condition. rPostCopy := rpost.Clone() @@ -999,13 +999,13 @@ func (a *App) GetPostsForChannelAroundLastUnread(channelId, userId string, limit // channel organically, those replies will be added below. postList.Order = []string{lastUnreadPostId} - if postListBefore, err := a.GetPostsBeforePost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PAGE_DEFAULT, PerPage: limitBefore, SkipFetchThreads: skipFetchThreads}); err != nil { + if postListBefore, err := a.GetPostsBeforePost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PageDefault, PerPage: limitBefore, SkipFetchThreads: skipFetchThreads}); err != nil { return nil, err } else if postListBefore != nil { postList.Extend(postListBefore) } - if postListAfter, err := a.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PAGE_DEFAULT, PerPage: limitAfter - 1, SkipFetchThreads: skipFetchThreads}); err != nil { + if postListAfter, err := a.GetPostsAfterPost(model.GetPostsOptions{ChannelId: channelId, PostId: lastUnreadPostId, Page: PageDefault, PerPage: limitAfter - 1, SkipFetchThreads: skipFetchThreads}); err != nil { return nil, err } else if postListAfter != nil { postList.Extend(postListAfter) diff --git a/app/post_metadata.go b/app/post_metadata.go index 7604ee64a1..2c97cacf21 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -27,12 +27,12 @@ type linkMetadataCache struct { PostImage *model.PostImage } -const LINK_CACHE_SIZE = 10000 -const LINK_CACHE_DURATION = 1 * time.Hour +const LinkCacheSize = 10000 +const LinkCacheDuration = 1 * time.Hour const MaxMetadataImageSize = MaxOpenGraphResponseSize var linkCache = cache.NewLRU(cache.LRUOptions{ - Size: LINK_CACHE_SIZE, + Size: LinkCacheSize, }) func (a *App) InitPostMetadata() { @@ -514,7 +514,7 @@ func cacheLinkMetadata(requestURL string, timestamp int64, og *opengraph.OpenGra PostImage: image, } - linkCache.SetWithExpiry(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), metadata, LINK_CACHE_DURATION) + linkCache.SetWithExpiry(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), metadata, LinkCacheDuration) } func (a *App) parseLinkMetadata(requestURL string, body io.Reader, contentType string) (*opengraph.OpenGraph, *model.PostImage, error) { diff --git a/app/post_test.go b/app/post_test.go index 0d51b1bdd3..abe2c2e8a4 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -177,7 +177,7 @@ func TestCreatePostDeduplicate(t *testing.T) { require.Nil(t, err) require.Equal(t, "message", post.Message) - time.Sleep(PENDING_POST_IDS_CACHE_TTL) + time.Sleep(PendingPostIDsCacheTTL) duplicatePost, err := th.App.CreatePostAsUser(&model.Post{ UserId: th.BasicUser.Id, diff --git a/app/product_notices.go b/app/product_notices.go index d84c577476..1c65bce59a 100644 --- a/app/product_notices.go +++ b/app/product_notices.go @@ -22,8 +22,8 @@ import ( date_constraints "github.com/reflog/dateconstraints" ) -const MAX_REPEAT_VIEWINGS = 3 -const MIN_SECONDS_BETWEEN_REPEAT_VIEWINGS = 60 * 60 +const MaxRepeatViewings = 3 +const MinSecondsBetweenRepeatViewings = 60 * 60 // http request cache var noticesCache = utils.RequestCache{} @@ -237,10 +237,10 @@ func (a *App) GetProductNotices(userId, teamId string, client model.NoticeClient if view != nil { repeatable := notice.Repeatable != nil && *notice.Repeatable if repeatable { - if view.Viewed > MAX_REPEAT_VIEWINGS { + if view.Viewed > MaxRepeatViewings { continue } - if (time.Now().UTC().Unix() - view.Timestamp) < MIN_SECONDS_BETWEEN_REPEAT_VIEWINGS { + if (time.Now().UTC().Unix() - view.Timestamp) < MinSecondsBetweenRepeatViewings { continue } } else if view.Viewed > 0 { diff --git a/app/security_update_check.go b/app/security_update_check.go index ac37175a71..c36a3f6b7f 100644 --- a/app/security_update_check.go +++ b/app/security_update_check.go @@ -17,18 +17,18 @@ import ( ) const ( - SECURITY_URL = "https://securityupdatecheck.mattermost.com" - SECURITY_UPDATE_PERIOD = 86400000 // 24 hours in milliseconds. + PropSecurityURL = "https://securityupdatecheck.mattermost.com" + SecurityUpdatePeriod = 86400000 // 24 hours in milliseconds. - PROP_SECURITY_ID = "id" - PROP_SECURITY_BUILD = "b" - PROP_SECURITY_ENTERPRISE_READY = "be" - PROP_SECURITY_DATABASE = "db" - PROP_SECURITY_OS = "os" - PROP_SECURITY_USER_COUNT = "uc" - PROP_SECURITY_TEAM_COUNT = "tc" - PROP_SECURITY_ACTIVE_USER_COUNT = "auc" - PROP_SECURITY_UNIT_TESTS = "ut" + PropSecurityID = "id" + PropSecurityBuild = "b" + PropSecurityEnterpriseReady = "be" + PropSecurityDatabase = "db" + PropSecurityOS = "os" + PropSecurityUserCount = "uc" + PropSecurityTeamCount = "tc" + PropSecurityActiveUserCount = "auc" + PropSecurityUnitTests = "ut" ) func (s *Server) DoSecurityUpdateCheck() { @@ -44,21 +44,21 @@ func (s *Server) DoSecurityUpdateCheck() { lastSecurityTime, _ := strconv.ParseInt(props[model.SYSTEM_LAST_SECURITY_TIME], 10, 0) currentTime := model.GetMillis() - if (currentTime - lastSecurityTime) > SECURITY_UPDATE_PERIOD { + if (currentTime - lastSecurityTime) > SecurityUpdatePeriod { mlog.Debug("Checking for security update from Mattermost") v := url.Values{} - v.Set(PROP_SECURITY_ID, s.TelemetryId()) - v.Set(PROP_SECURITY_BUILD, model.CurrentVersion+"."+model.BuildNumber) - v.Set(PROP_SECURITY_ENTERPRISE_READY, model.BuildEnterpriseReady) - v.Set(PROP_SECURITY_DATABASE, *s.Config().SqlSettings.DriverName) - v.Set(PROP_SECURITY_OS, runtime.GOOS) + v.Set(PropSecurityID, s.TelemetryId()) + v.Set(PropSecurityBuild, model.CurrentVersion+"."+model.BuildNumber) + v.Set(PropSecurityEnterpriseReady, model.BuildEnterpriseReady) + v.Set(PropSecurityDatabase, *s.Config().SqlSettings.DriverName) + v.Set(PropSecurityOS, runtime.GOOS) if len(props[model.SYSTEM_RAN_UNIT_TESTS]) > 0 { - v.Set(PROP_SECURITY_UNIT_TESTS, "1") + v.Set(PropSecurityUnitTests, "1") } else { - v.Set(PROP_SECURITY_UNIT_TESTS, "0") + v.Set(PropSecurityUnitTests, "0") } systemSecurityLastTime := &model.System{Name: model.SYSTEM_LAST_SECURITY_TIME, Value: strconv.FormatInt(currentTime, 10)} @@ -69,18 +69,18 @@ func (s *Server) DoSecurityUpdateCheck() { } if count, err := s.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { - v.Set(PROP_SECURITY_USER_COUNT, strconv.FormatInt(count, 10)) + v.Set(PropSecurityUserCount, strconv.FormatInt(count, 10)) } if ucr, err := s.Store.Status().GetTotalActiveUsersCount(); err == nil { - v.Set(PROP_SECURITY_ACTIVE_USER_COUNT, strconv.FormatInt(ucr, 10)) + v.Set(PropSecurityActiveUserCount, strconv.FormatInt(ucr, 10)) } if teamCount, err := s.Store.Team().AnalyticsTeamCount(false); err == nil { - v.Set(PROP_SECURITY_TEAM_COUNT, strconv.FormatInt(teamCount, 10)) + v.Set(PropSecurityTeamCount, strconv.FormatInt(teamCount, 10)) } - res, err := http.Get(SECURITY_URL + "/security?" + v.Encode()) + res, err := http.Get(PropSecurityURL + "/security?" + v.Encode()) if err != nil { mlog.Error("Failed to get security update information from Mattermost.") return @@ -99,7 +99,7 @@ func (s *Server) DoSecurityUpdateCheck() { return } - resBody, err := http.Get(SECURITY_URL + "/bulletins/" + bulletin.Id) + resBody, err := http.Get(PropSecurityURL + "/bulletins/" + bulletin.Id) if err != nil { mlog.Error("Failed to get security bulletin details") return diff --git a/app/server.go b/app/server.go index a98c8ac5cd..67fba7098a 100644 --- a/app/server.go +++ b/app/server.go @@ -62,7 +62,7 @@ import ( var MaxNotificationsPerChannelDefault int64 = 1000000 // declaring this as var to allow overriding in tests -var SENTRY_DSN = "placeholder_sentry_dsn" +var SentryDSN = "placeholder_sentry_dsn" type Server struct { sqlStore *sqlstore.SqlStore @@ -232,11 +232,11 @@ func NewServer(options ...Option) (*Server, error) { fakeApp.HubStart() if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry { - if strings.Contains(SENTRY_DSN, "placeholder") { + if strings.Contains(SentryDSN, "placeholder") { mlog.Warn("Sentry reporting is enabled, but SENTRY_DSN is not set. Disabling reporting.") } else { if err := sentry.Init(sentry.ClientOptions{ - Dsn: SENTRY_DSN, + Dsn: SentryDSN, Release: model.BuildHash, AttachStacktrace: true, BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event { @@ -297,7 +297,7 @@ func NewServer(options ...Option) (*Server, error) { return nil, errors.Wrap(err, "Unable to create session cache") } if s.seenPendingPostIdsCache, err = s.CacheProvider.NewCache(&cache.CacheOptions{ - Size: PENDING_POST_IDS_CACHE_SIZE, + Size: PendingPostIDsCacheSize, }); err != nil { return nil, errors.Wrap(err, "Unable to create pending post ids cache") } @@ -329,8 +329,8 @@ func NewServer(options ...Option) (*Server, error) { if err2 != nil { return nil, errors.Wrap(err2, "cannot parse DB version") } - if intVer < sqlstore.MINIMUM_REQUIRED_POSTGRES_VERSION { - return nil, fmt.Errorf("minimum required postgres version is %s; found %s", sqlstore.VersionString(sqlstore.MINIMUM_REQUIRED_POSTGRES_VERSION), sqlstore.VersionString(intVer)) + if intVer < sqlstore.MinimumRequiredPostgresVersion { + return nil, fmt.Errorf("minimum required postgres version is %s; found %s", sqlstore.VersionString(sqlstore.MinimumRequiredPostgresVersion), sqlstore.VersionString(intVer)) } } @@ -738,11 +738,11 @@ func (s *Server) enableLoggingMetrics() { } } -const TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN = time.Second +const TimeToWaitForConnectionsToCloseOnServerShutdown = time.Second func (s *Server) StopHTTPServer() { if s.Server != nil { - ctx, cancel := context.WithTimeout(context.Background(), TIME_TO_WAIT_FOR_CONNECTIONS_TO_CLOSE_ON_SERVER_SHUTDOWN) + ctx, cancel := context.WithTimeout(context.Background(), TimeToWaitForConnectionsToCloseOnServerShutdown) defer cancel() didShutdown := false for s.didFinishListen != nil && !didShutdown { @@ -952,7 +952,7 @@ func (s *Server) Start() error { var handler http.Handler = s.RootRouter - if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry && !strings.Contains(SENTRY_DSN, "placeholder") { + if *s.Config().LogSettings.EnableDiagnostics && *s.Config().LogSettings.EnableSentry && !strings.Contains(SentryDSN, "placeholder") { sentryHandler := sentryhttp.New(sentryhttp.Options{ Repanic: true, }) @@ -1277,11 +1277,11 @@ func doCommandWebhookCleanup(s *Server) { } const ( - SESSIONS_CLEANUP_BATCH_SIZE = 1000 + SessionsCleanupBatchSize = 1000 ) func doSessionCleanup(s *Server) { - s.Store.Session().Cleanup(model.GetMillis(), SESSIONS_CLEANUP_BATCH_SIZE) + s.Store.Session().Cleanup(model.GetMillis(), SessionsCleanupBatchSize) } func doCheckWarnMetricStatus(a *App) { diff --git a/app/server_test.go b/app/server_test.go index bdc6119020..794aaf73ca 100644 --- a/app/server_test.go +++ b/app/server_test.go @@ -382,7 +382,7 @@ func TestSentry(t *testing.T) { _, port, _ := net.SplitHostPort(server.Listener.Addr().String()) dsn, err := sentry.NewDsn(fmt.Sprintf("http://test:test@localhost:%s/123", port)) require.NoError(t, err) - SENTRY_DSN = dsn.String() + SentryDSN = dsn.String() s, err := NewServer(func(server *Server) error { configStore, _ := config.NewFileStore("config.json", true) @@ -433,7 +433,7 @@ func TestSentry(t *testing.T) { _, port, _ := net.SplitHostPort(server.Listener.Addr().String()) dsn, err := sentry.NewDsn(fmt.Sprintf("http://test:test@localhost:%s/123", port)) require.NoError(t, err) - SENTRY_DSN = dsn.String() + SentryDSN = dsn.String() s, err := NewServer(func(server *Server) error { configStore, _ := config.NewFileStore("config.json", true) diff --git a/app/session.go b/app/session.go index fdd55e4927..6fb9627fbe 100644 --- a/app/session.go +++ b/app/session.go @@ -420,7 +420,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("CreateUserAccessToken", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("CreateUserAccessToken", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("CreateUserAccessToken", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -469,7 +469,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("createSessionForUserAccessToken", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("createSessionForUserAccessToken", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("createSessionForUserAccessToken", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } diff --git a/app/slashcommands/auto_channels.go b/app/slashcommands/auto_channels.go index 9ec07964b0..9c972def4f 100644 --- a/app/slashcommands/auto_channels.go +++ b/app/slashcommands/auto_channels.go @@ -27,11 +27,11 @@ func NewAutoChannelCreator(a *app.App, team *model.Team, userId string) *AutoCha team: team, userId: userId, Fuzzy: false, - DisplayNameLen: CHANNEL_DISPLAY_NAME_LEN, + DisplayNameLen: ChannelDisplayNameLen, DisplayNameCharset: utils.ALPHANUMERIC, - NameLen: CHANNEL_NAME_LEN, + NameLen: ChannelNameLen, NameCharset: utils.LOWERCASE, - ChannelType: CHANNEL_TYPE, + ChannelType: ChannelType, } } diff --git a/app/slashcommands/auto_constants.go b/app/slashcommands/auto_constants.go index 269005a463..266fc38540 100644 --- a/app/slashcommands/auto_constants.go +++ b/app/slashcommands/auto_constants.go @@ -9,24 +9,24 @@ import ( ) const ( - USER_PASSWORD = "passwd" - CHANNEL_TYPE = model.CHANNEL_OPEN - BTEST_TEAM_DISPLAY_NAME = "TestTeam" - BTEST_TEAM_NAME = "z-z-testdomaina" - BTEST_TEAM_EMAIL = "test@nowhere.com" - BTEST_TEAM_TYPE = model.TEAM_OPEN - BTEST_USER_NAME = "Mr. Testing Tester" - BTEST_USER_EMAIL = "success+ttester@simulator.amazonses.com" - BTEST_USER_PASSWORD = "passwd" + UserPassword = "passwd" + ChannelType = model.CHANNEL_OPEN + BTestTeamDisplayName = "TestTeam" + BTestTeamName = "z-z-testdomaina" + BTestTeamEmail = "test@nowhere.com" + BTestTeamType = model.TEAM_OPEN + BTestUserName = "Mr. Testing Tester" + BTestUserEmail = "success+ttester@simulator.amazonses.com" + BTestUserPassword = "passwd" ) var ( - TEAM_NAME_LEN = utils.Range{Begin: 10, End: 20} - TEAM_DOMAIN_NAME_LEN = utils.Range{Begin: 10, End: 20} - TEAM_EMAIL_LEN = utils.Range{Begin: 15, End: 30} - USER_NAME_LEN = utils.Range{Begin: 5, End: 20} - USER_EMAIL_LEN = utils.Range{Begin: 15, End: 30} - CHANNEL_DISPLAY_NAME_LEN = utils.Range{Begin: 10, End: 20} - CHANNEL_NAME_LEN = utils.Range{Begin: 5, End: 20} - TEST_IMAGE_FILENAMES = []string{"test.png", "testjpg.jpg", "testgif.gif"} + TeamNameLen = utils.Range{Begin: 10, End: 20} + TeamDomainNameLen = utils.Range{Begin: 10, End: 20} + TeamEmailLen = utils.Range{Begin: 15, End: 30} + UserNameLen = utils.Range{Begin: 5, End: 20} + UserEmailLen = utils.Range{Begin: 15, End: 30} + ChannelDisplayNameLen = utils.Range{Begin: 10, End: 20} + ChannelNameLen = utils.Range{Begin: 5, End: 20} + TestImageFileNames = []string{"test.png", "testjpg.jpg", "testgif.gif"} ) diff --git a/app/slashcommands/auto_environment.go b/app/slashcommands/auto_environment.go index 6375ca8ac8..8270d328ac 100644 --- a/app/slashcommands/auto_environment.go +++ b/app/slashcommands/auto_environment.go @@ -36,7 +36,7 @@ func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeam if err != nil { return TestEnvironment{}, err } - client.LoginById(randomUser.Id, USER_PASSWORD) + client.LoginById(randomUser.Id, UserPassword) teamEnvironment, err := CreateTestEnvironmentInTeam(a, client, team, rangeChannels, rangeUsers, rangePosts, fuzzy) if err != nil { return TestEnvironment{}, err @@ -76,7 +76,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model. // Have every user join every channel for _, user := range users { for _, channel := range channels { - _, resp := client.LoginById(user.Id, USER_PASSWORD) + _, resp := client.LoginById(user.Id, UserPassword) if resp.Error != nil { return TeamEnvironment{}, resp.Error } @@ -92,7 +92,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model. numImages := utils.RandIntFromRange(rangePosts) / 4 for j := 0; j < numPosts; j++ { user := users[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(users) - 1})] - _, resp := client.LoginById(user.Id, USER_PASSWORD) + _, resp := client.LoginById(user.Id, UserPassword) if resp.Error != nil { return TeamEnvironment{}, resp.Error } diff --git a/app/slashcommands/auto_posts.go b/app/slashcommands/auto_posts.go index d0bf5acfe1..aa09c18cde 100644 --- a/app/slashcommands/auto_posts.go +++ b/app/slashcommands/auto_posts.go @@ -37,7 +37,7 @@ func NewAutoPostCreator(a *app.App, channelid, userid string) *AutoPostCreator { Fuzzy: false, TextLength: utils.Range{Begin: 100, End: 200}, HasImage: false, - ImageFilenames: TEST_IMAGE_FILENAMES, + ImageFilenames: TestImageFileNames, Users: []string{}, Mentions: utils.Range{Begin: 0, End: 5}, Tags: utils.Range{Begin: 0, End: 7}, diff --git a/app/slashcommands/auto_teams.go b/app/slashcommands/auto_teams.go index 0bfd4507e3..d84fb230d1 100644 --- a/app/slashcommands/auto_teams.go +++ b/app/slashcommands/auto_teams.go @@ -28,11 +28,11 @@ func NewAutoTeamCreator(client *model.Client4) *AutoTeamCreator { return &AutoTeamCreator{ client: client, Fuzzy: false, - NameLength: TEAM_NAME_LEN, + NameLength: TeamNameLen, NameCharset: utils.LOWERCASE, - DomainLength: TEAM_DOMAIN_NAME_LEN, + DomainLength: TeamDomainNameLen, DomainCharset: utils.LOWERCASE, - EmailLength: TEAM_EMAIL_LEN, + EmailLength: TeamEmailLen, EmailCharset: utils.LOWERCASE, } } diff --git a/app/slashcommands/auto_users.go b/app/slashcommands/auto_users.go index 9908dee7e1..cea4dbe378 100644 --- a/app/slashcommands/auto_users.go +++ b/app/slashcommands/auto_users.go @@ -29,9 +29,9 @@ func NewAutoUserCreator(a *app.App, client *model.Client4, team *model.Team) *Au app: a, client: client, team: team, - EmailLength: USER_EMAIL_LEN, + EmailLength: UserEmailLen, EmailCharset: utils.LOWERCASE, - NameLength: USER_NAME_LEN, + NameLength: UserNameLen, NameCharset: utils.LOWERCASE, Fuzzy: false, } @@ -39,17 +39,17 @@ func NewAutoUserCreator(a *app.App, client *model.Client4, team *model.Team) *Au // Basic test team and user so you always know one func CreateBasicUser(a *app.App, client *model.Client4) *model.AppError { - found, _ := client.TeamExists(BTEST_TEAM_NAME, "") + found, _ := client.TeamExists(BTestTeamName, "") if found { return nil } - newteam := &model.Team{DisplayName: BTEST_TEAM_DISPLAY_NAME, Name: BTEST_TEAM_NAME, Email: BTEST_TEAM_EMAIL, Type: BTEST_TEAM_TYPE} + newteam := &model.Team{DisplayName: BTestTeamDisplayName, Name: BTestTeamName, Email: BTestTeamEmail, Type: BTestTeamType} basicteam, resp := client.CreateTeam(newteam) if resp.Error != nil { return resp.Error } - newuser := &model.User{Email: BTEST_USER_EMAIL, Nickname: BTEST_USER_NAME, Password: BTEST_USER_PASSWORD} + newuser := &model.User{Email: BTestUserEmail, Nickname: BTestUserName, Password: BTestUserPassword} ruser, resp := client.CreateUser(newuser) if resp.Error != nil { return resp.Error @@ -91,7 +91,7 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) { user := &model.User{ Email: userEmail, Nickname: userName, - Password: USER_PASSWORD} + Password: UserPassword} ruser, resp := cfg.client.CreateUserWithInviteId(user, cfg.team.InviteId) if resp.Error != nil { diff --git a/app/slashcommands/command_away.go b/app/slashcommands/command_away.go index d42bb849ee..86664f2a11 100644 --- a/app/slashcommands/command_away.go +++ b/app/slashcommands/command_away.go @@ -13,7 +13,7 @@ type AwayProvider struct { } const ( - CMD_AWAY = "away" + CmdAway = "away" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*AwayProvider) GetTrigger() string { - return CMD_AWAY + return CmdAway } func (*AwayProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_AWAY, + Trigger: CmdAway, AutoComplete: true, AutoCompleteDesc: T("api.command_away.desc"), DisplayName: T("api.command_away.name"), diff --git a/app/slashcommands/command_channel_header.go b/app/slashcommands/command_channel_header.go index 82a6f711a7..a6c4a7f939 100644 --- a/app/slashcommands/command_channel_header.go +++ b/app/slashcommands/command_channel_header.go @@ -14,7 +14,7 @@ type HeaderProvider struct { } const ( - CMD_HEADER = "header" + CmdHeader = "header" ) func init() { @@ -22,12 +22,12 @@ func init() { } func (*HeaderProvider) GetTrigger() string { - return CMD_HEADER + return CmdHeader } func (*HeaderProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_HEADER, + Trigger: CmdHeader, AutoComplete: true, AutoCompleteDesc: T("api.command_channel_header.desc"), AutoCompleteHint: T("api.command_channel_header.hint"), diff --git a/app/slashcommands/command_channel_purpose.go b/app/slashcommands/command_channel_purpose.go index 0e24b35a81..8c98d0ebdd 100644 --- a/app/slashcommands/command_channel_purpose.go +++ b/app/slashcommands/command_channel_purpose.go @@ -14,7 +14,7 @@ type PurposeProvider struct { } const ( - CMD_PURPOSE = "purpose" + CmdPurpose = "purpose" ) func init() { @@ -22,12 +22,12 @@ func init() { } func (*PurposeProvider) GetTrigger() string { - return CMD_PURPOSE + return CmdPurpose } func (*PurposeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_PURPOSE, + Trigger: CmdPurpose, AutoComplete: true, AutoCompleteDesc: T("api.command_channel_purpose.desc"), AutoCompleteHint: T("api.command_channel_purpose.hint"), diff --git a/app/slashcommands/command_channel_rename.go b/app/slashcommands/command_channel_rename.go index bb7fd85c83..aa6a37c548 100644 --- a/app/slashcommands/command_channel_rename.go +++ b/app/slashcommands/command_channel_rename.go @@ -14,7 +14,7 @@ type RenameProvider struct { } const ( - CMD_RENAME = "rename" + CmdRename = "rename" ) func init() { @@ -22,14 +22,14 @@ func init() { } func (*RenameProvider) GetTrigger() string { - return CMD_RENAME + return CmdRename } func (*RenameProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { - renameAutocompleteData := model.NewAutocompleteData(CMD_RENAME, T("api.command_channel_rename.hint"), T("api.command_channel_rename.desc")) + renameAutocompleteData := model.NewAutocompleteData(CmdRename, T("api.command_channel_rename.hint"), T("api.command_channel_rename.desc")) renameAutocompleteData.AddTextArgument(T("api.command_channel_rename.hint"), "[text]", "") return &model.Command{ - Trigger: CMD_RENAME, + Trigger: CmdRename, AutoComplete: true, AutoCompleteDesc: T("api.command_channel_rename.desc"), AutoCompleteHint: T("api.command_channel_rename.hint"), diff --git a/app/slashcommands/command_code.go b/app/slashcommands/command_code.go index 2be8794d69..461a013f1e 100644 --- a/app/slashcommands/command_code.go +++ b/app/slashcommands/command_code.go @@ -15,7 +15,7 @@ type CodeProvider struct { } const ( - CMD_CODE = "code" + CmdCode = "code" ) func init() { @@ -23,12 +23,12 @@ func init() { } func (*CodeProvider) GetTrigger() string { - return CMD_CODE + return CmdCode } func (*CodeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_CODE, + Trigger: CmdCode, AutoComplete: true, AutoCompleteDesc: T("api.command_code.desc"), AutoCompleteHint: T("api.command_code.hint"), diff --git a/app/slashcommands/command_dnd.go b/app/slashcommands/command_dnd.go index 16ad735821..00406b19ea 100644 --- a/app/slashcommands/command_dnd.go +++ b/app/slashcommands/command_dnd.go @@ -13,7 +13,7 @@ type DndProvider struct { } const ( - CMD_DND = "dnd" + CmdDND = "dnd" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*DndProvider) GetTrigger() string { - return CMD_DND + return CmdDND } func (*DndProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_DND, + Trigger: CmdDND, AutoComplete: true, AutoCompleteDesc: T("api.command_dnd.desc"), DisplayName: T("api.command_dnd.name"), diff --git a/app/slashcommands/command_echo.go b/app/slashcommands/command_echo.go index 27428dbc23..9dc6c0e5f2 100644 --- a/app/slashcommands/command_echo.go +++ b/app/slashcommands/command_echo.go @@ -20,7 +20,7 @@ type EchoProvider struct { } const ( - CMD_ECHO = "echo" + CmdEcho = "echo" ) func init() { @@ -28,12 +28,12 @@ func init() { } func (*EchoProvider) GetTrigger() string { - return CMD_ECHO + return CmdEcho } func (*EchoProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_ECHO, + Trigger: CmdEcho, AutoComplete: true, AutoCompleteDesc: T("api.command_echo.desc"), AutoCompleteHint: T("api.command_echo.hint"), diff --git a/app/slashcommands/command_expand_collapse.go b/app/slashcommands/command_expand_collapse.go index d1748d574c..6697ade713 100644 --- a/app/slashcommands/command_expand_collapse.go +++ b/app/slashcommands/command_expand_collapse.go @@ -18,8 +18,8 @@ type CollapseProvider struct { } const ( - CMD_EXPAND = "expand" - CMD_COLLAPSE = "collapse" + CmdExpand = "expand" + CmdCollapse = "collapse" ) func init() { @@ -28,16 +28,16 @@ func init() { } func (*ExpandProvider) GetTrigger() string { - return CMD_EXPAND + return CmdExpand } func (*CollapseProvider) GetTrigger() string { - return CMD_COLLAPSE + return CmdCollapse } func (*ExpandProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_EXPAND, + Trigger: CmdExpand, AutoComplete: true, AutoCompleteDesc: T("api.command_expand.desc"), DisplayName: T("api.command_expand.name"), @@ -46,7 +46,7 @@ func (*ExpandProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Com func (*CollapseProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_COLLAPSE, + Trigger: CmdCollapse, AutoComplete: true, AutoCompleteDesc: T("api.command_collapse.desc"), DisplayName: T("api.command_collapse.name"), diff --git a/app/slashcommands/command_groupmsg.go b/app/slashcommands/command_groupmsg.go index 83877295df..9eb9d687f6 100644 --- a/app/slashcommands/command_groupmsg.go +++ b/app/slashcommands/command_groupmsg.go @@ -17,7 +17,7 @@ type groupmsgProvider struct { } const ( - CMD_GROUPMSG = "groupmsg" + CmdGroupMsg = "groupmsg" ) func init() { @@ -25,12 +25,12 @@ func init() { } func (*groupmsgProvider) GetTrigger() string { - return CMD_GROUPMSG + return CmdGroupMsg } func (*groupmsgProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_GROUPMSG, + Trigger: CmdGroupMsg, AutoComplete: true, AutoCompleteDesc: T("api.command_groupmsg.desc"), AutoCompleteHint: T("api.command_groupmsg.hint"), diff --git a/app/slashcommands/command_help.go b/app/slashcommands/command_help.go index ddbfa90a9e..2229c38036 100644 --- a/app/slashcommands/command_help.go +++ b/app/slashcommands/command_help.go @@ -13,7 +13,7 @@ type HelpProvider struct { } const ( - CMD_HELP = "help" + CmdHelp = "help" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (h *HelpProvider) GetTrigger() string { - return CMD_HELP + return CmdHelp } func (h *HelpProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_HELP, + Trigger: CmdHelp, AutoComplete: true, AutoCompleteDesc: T("api.command_help.desc"), DisplayName: T("api.command_help.name"), diff --git a/app/slashcommands/command_invite.go b/app/slashcommands/command_invite.go index a668f643ae..42e55bfcd0 100644 --- a/app/slashcommands/command_invite.go +++ b/app/slashcommands/command_invite.go @@ -17,7 +17,7 @@ type InviteProvider struct { } const ( - CMD_INVITE = "invite" + CmdInvite = "invite" ) func init() { @@ -25,12 +25,12 @@ func init() { } func (*InviteProvider) GetTrigger() string { - return CMD_INVITE + return CmdInvite } func (*InviteProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_INVITE, + Trigger: CmdInvite, AutoComplete: true, AutoCompleteDesc: T("api.command_invite.desc"), AutoCompleteHint: T("api.command_invite.hint"), diff --git a/app/slashcommands/command_invite_people.go b/app/slashcommands/command_invite_people.go index 20be428892..2f697e8e42 100644 --- a/app/slashcommands/command_invite_people.go +++ b/app/slashcommands/command_invite_people.go @@ -16,7 +16,7 @@ type InvitePeopleProvider struct { } const ( - CMD_INVITE_PEOPLE = "invite_people" + CmdInvite_PEOPLE = "invite_people" ) func init() { @@ -24,7 +24,7 @@ func init() { } func (*InvitePeopleProvider) GetTrigger() string { - return CMD_INVITE_PEOPLE + return CmdInvite_PEOPLE } func (*InvitePeopleProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { @@ -33,7 +33,7 @@ func (*InvitePeopleProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *mod autoComplete = false } return &model.Command{ - Trigger: CMD_INVITE_PEOPLE, + Trigger: CmdInvite_PEOPLE, AutoComplete: autoComplete, AutoCompleteDesc: T("api.command.invite_people.desc"), AutoCompleteHint: T("api.command.invite_people.hint"), diff --git a/app/slashcommands/command_join.go b/app/slashcommands/command_join.go index 1be256b7f7..246f0bddf1 100644 --- a/app/slashcommands/command_join.go +++ b/app/slashcommands/command_join.go @@ -15,7 +15,7 @@ type JoinProvider struct { } const ( - CMD_JOIN = "join" + CmdJoin = "join" ) func init() { @@ -23,12 +23,12 @@ func init() { } func (*JoinProvider) GetTrigger() string { - return CMD_JOIN + return CmdJoin } func (*JoinProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_JOIN, + Trigger: CmdJoin, AutoComplete: true, AutoCompleteDesc: T("api.command_join.desc"), AutoCompleteHint: T("api.command_join.hint"), diff --git a/app/slashcommands/command_leave.go b/app/slashcommands/command_leave.go index cbd0672674..e98c9ceab8 100644 --- a/app/slashcommands/command_leave.go +++ b/app/slashcommands/command_leave.go @@ -13,7 +13,7 @@ type LeaveProvider struct { } const ( - CMD_LEAVE = "leave" + CmdLeave = "leave" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*LeaveProvider) GetTrigger() string { - return CMD_LEAVE + return CmdLeave } func (*LeaveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_LEAVE, + Trigger: CmdLeave, AutoComplete: true, AutoCompleteDesc: T("api.command_leave.desc"), DisplayName: T("api.command_leave.name"), diff --git a/app/slashcommands/command_loadtest.go b/app/slashcommands/command_loadtest.go index 1f77096e53..7893ad1b49 100644 --- a/app/slashcommands/command_loadtest.go +++ b/app/slashcommands/command_loadtest.go @@ -72,7 +72,7 @@ var usage = `Mattermost testing commands to help configure the system ` const ( - CMD_TEST = "test" + CmdTest = "test" ) var ( @@ -91,7 +91,7 @@ func init() { } func (*LoadTestProvider) GetTrigger() string { - return CMD_TEST + return CmdTest } func (*LoadTestProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { @@ -99,7 +99,7 @@ func (*LoadTestProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.C return nil } return &model.Command{ - Trigger: CMD_TEST, + Trigger: CmdTest, AutoComplete: false, AutoCompleteDesc: "Debug Load Testing", AutoCompleteHint: "help", @@ -110,7 +110,7 @@ func (*LoadTestProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.C func (lt *LoadTestProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse { commandResponse, err := lt.doCommand(a, args, message) if err != nil { - mlog.Error("failed command /"+CMD_TEST, mlog.Err(err)) + mlog.Error("failed command /"+CmdTest, mlog.Err(err)) } return commandResponse @@ -213,7 +213,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa if err := CreateBasicUser(a, client); err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err } - _, resp := client.Login(BTEST_USER_EMAIL, BTEST_USER_PASSWORD) + _, resp := client.Login(BTestUserEmail, BTestUserPassword) if resp.Error != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error } @@ -232,7 +232,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa mlog.Info("Testing environment created") for i := 0; i < len(environment.Teams); i++ { mlog.Info("Team Created: " + environment.Teams[i].Name) - mlog.Info("\t User to login: " + environment.Environments[i].Users[0].Email + ", " + USER_PASSWORD) + mlog.Info("\t User to login: " + environment.Environments[i].Users[0].Email + ", " + UserPassword) } } else { team, err := a.Srv().Store.Team().Get(args.TeamId) diff --git a/app/slashcommands/command_logout.go b/app/slashcommands/command_logout.go index d7bbba201f..a539f7f48a 100644 --- a/app/slashcommands/command_logout.go +++ b/app/slashcommands/command_logout.go @@ -13,7 +13,7 @@ type LogoutProvider struct { } const ( - CMD_LOGOUT = "logout" + CmdLogout = "logout" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*LogoutProvider) GetTrigger() string { - return CMD_LOGOUT + return CmdLogout } func (*LogoutProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_LOGOUT, + Trigger: CmdLogout, AutoComplete: true, AutoCompleteDesc: T("api.command_logout.desc"), AutoCompleteHint: "", diff --git a/app/slashcommands/command_me.go b/app/slashcommands/command_me.go index 14658197b3..d296d9d2b6 100644 --- a/app/slashcommands/command_me.go +++ b/app/slashcommands/command_me.go @@ -13,7 +13,7 @@ type MeProvider struct { } const ( - CMD_ME = "me" + CmdMe = "me" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*MeProvider) GetTrigger() string { - return CMD_ME + return CmdMe } func (*MeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_ME, + Trigger: CmdMe, AutoComplete: true, AutoCompleteDesc: T("api.command_me.desc"), AutoCompleteHint: T("api.command_me.hint"), diff --git a/app/slashcommands/command_msg.go b/app/slashcommands/command_msg.go index 6221513e75..b10cddf304 100644 --- a/app/slashcommands/command_msg.go +++ b/app/slashcommands/command_msg.go @@ -18,7 +18,7 @@ type msgProvider struct { } const ( - CMD_MSG = "msg" + CmdMsg = "msg" ) func init() { @@ -26,12 +26,12 @@ func init() { } func (*msgProvider) GetTrigger() string { - return CMD_MSG + return CmdMsg } func (*msgProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_MSG, + Trigger: CmdMsg, AutoComplete: true, AutoCompleteDesc: T("api.command_msg.desc"), AutoCompleteHint: T("api.command_msg.hint"), diff --git a/app/slashcommands/command_mute.go b/app/slashcommands/command_mute.go index 92a275040c..07354a2d23 100644 --- a/app/slashcommands/command_mute.go +++ b/app/slashcommands/command_mute.go @@ -15,7 +15,7 @@ type MuteProvider struct { } const ( - CMD_MUTE = "mute" + CmdMute = "mute" ) func init() { @@ -23,12 +23,12 @@ func init() { } func (*MuteProvider) GetTrigger() string { - return CMD_MUTE + return CmdMute } func (*MuteProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_MUTE, + Trigger: CmdMute, AutoComplete: true, AutoCompleteDesc: T("api.command_mute.desc"), AutoCompleteHint: T("api.command_mute.hint"), diff --git a/app/slashcommands/command_offline.go b/app/slashcommands/command_offline.go index 95cfd75b4d..a470e8d65d 100644 --- a/app/slashcommands/command_offline.go +++ b/app/slashcommands/command_offline.go @@ -13,7 +13,7 @@ type OfflineProvider struct { } const ( - CMD_OFFLINE = "offline" + CmdOffline = "offline" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*OfflineProvider) GetTrigger() string { - return CMD_OFFLINE + return CmdOffline } func (*OfflineProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_OFFLINE, + Trigger: CmdOffline, AutoComplete: true, AutoCompleteDesc: T("api.command_offline.desc"), DisplayName: T("api.command_offline.name"), diff --git a/app/slashcommands/command_online.go b/app/slashcommands/command_online.go index 0727fd7fba..36efa96057 100644 --- a/app/slashcommands/command_online.go +++ b/app/slashcommands/command_online.go @@ -13,7 +13,7 @@ type OnlineProvider struct { } const ( - CMD_ONLINE = "online" + CmdOnline = "online" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*OnlineProvider) GetTrigger() string { - return CMD_ONLINE + return CmdOnline } func (*OnlineProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_ONLINE, + Trigger: CmdOnline, AutoComplete: true, AutoCompleteDesc: T("api.command_online.desc"), DisplayName: T("api.command_online.name"), diff --git a/app/slashcommands/command_open.go b/app/slashcommands/command_open.go index 63124a1ca6..074d72c97b 100644 --- a/app/slashcommands/command_open.go +++ b/app/slashcommands/command_open.go @@ -14,7 +14,7 @@ type OpenProvider struct { } const ( - CMD_OPEN = "open" + CmdOpen = "open" ) func init() { @@ -22,12 +22,12 @@ func init() { } func (open *OpenProvider) GetTrigger() string { - return CMD_OPEN + return CmdOpen } func (open *OpenProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { cmd := open.JoinProvider.GetCommand(a, T) - cmd.Trigger = CMD_OPEN + cmd.Trigger = CmdOpen cmd.DisplayName = T("api.command_open.name") return cmd } diff --git a/app/slashcommands/command_remove.go b/app/slashcommands/command_remove.go index e2403e068b..054b6bee24 100644 --- a/app/slashcommands/command_remove.go +++ b/app/slashcommands/command_remove.go @@ -20,8 +20,8 @@ type KickProvider struct { } const ( - CMD_REMOVE = "remove" - CMD_KICK = "kick" + CmdRemove = "remove" + CmdKick = "kick" ) func init() { @@ -30,16 +30,16 @@ func init() { } func (*RemoveProvider) GetTrigger() string { - return CMD_REMOVE + return CmdRemove } func (*KickProvider) GetTrigger() string { - return CMD_KICK + return CmdKick } func (*RemoveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_REMOVE, + Trigger: CmdRemove, AutoComplete: true, AutoCompleteDesc: T("api.command_remove.desc"), AutoCompleteHint: T("api.command_remove.hint"), @@ -49,7 +49,7 @@ func (*RemoveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Com func (*KickProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_KICK, + Trigger: CmdKick, AutoComplete: true, AutoCompleteDesc: T("api.command_remove.desc"), AutoCompleteHint: T("api.command_remove.hint"), diff --git a/app/slashcommands/command_search.go b/app/slashcommands/command_search.go index dae5493bd5..71659e3acb 100644 --- a/app/slashcommands/command_search.go +++ b/app/slashcommands/command_search.go @@ -13,7 +13,7 @@ type SearchProvider struct { } const ( - CMD_SEARCH = "search" + CmdSearch = "search" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (search *SearchProvider) GetTrigger() string { - return CMD_SEARCH + return CmdSearch } func (search *SearchProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_SEARCH, + Trigger: CmdSearch, AutoComplete: true, AutoCompleteDesc: T("api.command_search.desc"), AutoCompleteHint: T("api.command_search.hint"), diff --git a/app/slashcommands/command_settings.go b/app/slashcommands/command_settings.go index 09d71fe325..8e3b3c3813 100644 --- a/app/slashcommands/command_settings.go +++ b/app/slashcommands/command_settings.go @@ -13,7 +13,7 @@ type SettingsProvider struct { } const ( - CMD_SETTINGS = "settings" + CmdSettings = "settings" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (settings *SettingsProvider) GetTrigger() string { - return CMD_SETTINGS + return CmdSettings } func (settings *SettingsProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_SETTINGS, + Trigger: CmdSettings, AutoComplete: true, AutoCompleteDesc: T("api.command_settings.desc"), AutoCompleteHint: "", diff --git a/app/slashcommands/command_shortcuts.go b/app/slashcommands/command_shortcuts.go index 9312cd0c26..ed86da87af 100644 --- a/app/slashcommands/command_shortcuts.go +++ b/app/slashcommands/command_shortcuts.go @@ -13,7 +13,7 @@ type ShortcutsProvider struct { } const ( - CMD_SHORTCUTS = "shortcuts" + CmdShortcuts = "shortcuts" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*ShortcutsProvider) GetTrigger() string { - return CMD_SHORTCUTS + return CmdShortcuts } func (*ShortcutsProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_SHORTCUTS, + Trigger: CmdShortcuts, AutoComplete: true, AutoCompleteDesc: T("api.command_shortcuts.desc"), AutoCompleteHint: "", diff --git a/app/slashcommands/command_shrug.go b/app/slashcommands/command_shrug.go index b01e043230..a48ba3bf58 100644 --- a/app/slashcommands/command_shrug.go +++ b/app/slashcommands/command_shrug.go @@ -13,7 +13,7 @@ type ShrugProvider struct { } const ( - CMD_SHRUG = "shrug" + CmdShrug = "shrug" ) func init() { @@ -21,12 +21,12 @@ func init() { } func (*ShrugProvider) GetTrigger() string { - return CMD_SHRUG + return CmdShrug } func (*ShrugProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command { return &model.Command{ - Trigger: CMD_SHRUG, + Trigger: CmdShrug, AutoComplete: true, AutoCompleteDesc: T("api.command_shrug.desc"), AutoCompleteHint: T("api.command_shrug.hint"), diff --git a/app/team.go b/app/team.go index 3bcb24fd11..d4799529f8 100644 --- a/app/team.go +++ b/app/team.go @@ -510,7 +510,7 @@ func (a *App) AddUserToTeam(teamId string, userId string, userRequestorId string var nfErr *store.ErrNotFound switch { case errors.As(result.NErr, &nfErr): - return nil, model.NewAppError("AddUserToTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("AddUserToTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("AddUserToTeam", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError) } @@ -545,11 +545,11 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team, return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_invalid.app_error", nil, err.Error(), http.StatusBadRequest) } - if token.Type != TOKEN_TYPE_TEAM_INVITATION && token.Type != TOKEN_TYPE_GUEST_INVITATION { + if token.Type != TokenTypeTeamInvitation && token.Type != TokenTypeGuestInvitation { return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusBadRequest) } - if model.GetMillis()-token.CreateAt >= INVITATION_EXPIRY_TIME { + if model.GetMillis()-token.CreateAt >= InvitationExpiryTime { a.DeleteToken(token) return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusBadRequest) } @@ -591,17 +591,17 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team, var nfErr *store.ErrNotFound switch { case errors.As(result.NErr, &nfErr): - return nil, model.NewAppError("AddUserToTeamByToken", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("AddUserToTeamByToken", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("AddUserToTeamByToken", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError) } } user := result.Data.(*model.User) - if user.IsGuest() && token.Type == TOKEN_TYPE_TEAM_INVITATION { + if user.IsGuest() && token.Type == TokenTypeTeamInvitation { return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.invalid_invitation_type.app_error", nil, "", http.StatusBadRequest) } - if !user.IsGuest() && token.Type == TOKEN_TYPE_GUEST_INVITATION { + if !user.IsGuest() && token.Type == TokenTypeGuestInvitation { return nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.invalid_invitation_type.app_error", nil, "", http.StatusBadRequest) } @@ -609,7 +609,7 @@ func (a *App) AddUserToTeamByToken(userId string, tokenId string) (*model.Team, return nil, err } - if token.Type == TOKEN_TYPE_GUEST_INVITATION { + if token.Type == TokenTypeGuestInvitation { channels, err := a.Srv().Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " "), false) if err != nil { return nil, model.NewAppError("AddUserToTeamByToken", "app.channel.get_channels_by_ids.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -662,7 +662,7 @@ func (a *App) AddUserToTeamByInviteId(inviteId string, userId string) (*model.Te var nfErr *store.ErrNotFound switch { case errors.As(result.NErr, &nfErr): - return nil, model.NewAppError("AddUserToTeamByInviteId", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("AddUserToTeamByInviteId", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("AddUserToTeamByInviteId", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError) } @@ -1184,7 +1184,7 @@ func (a *App) RemoveUserFromTeam(teamId string, userId string, requestorId strin var nfErr *store.ErrNotFound switch { case errors.As(result.NErr, &nfErr): - return model.NewAppError("RemoveUserFromTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("RemoveUserFromTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("RemoveUserFromTeam", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError) } @@ -1210,7 +1210,7 @@ func (a *App) RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return model.NewAppError("RemoveTeamMemberFromTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("RemoveTeamMemberFromTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("RemoveTeamMemberFromTeam", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } @@ -1389,7 +1389,7 @@ func (a *App) prepareInviteNewUsersToTeam(teamId, senderId string) (*model.User, var nfErr *store.ErrNotFound switch { case errors.As(result.NErr, &nfErr): - return nil, nil, model.NewAppError("prepareInviteNewUsersToTeam", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, nil, model.NewAppError("prepareInviteNewUsersToTeam", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, nil, model.NewAppError("prepareInviteNewUsersToTeam", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError) } @@ -1514,7 +1514,7 @@ func (a *App) prepareInviteGuestsToChannels(teamId string, guestsInvite *model.G var nfErr *store.ErrNotFound switch { case errors.As(result.NErr, &nfErr): - return nil, nil, nil, model.NewAppError("prepareInviteGuestsToChannels", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, nil, nil, model.NewAppError("prepareInviteGuestsToChannels", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, nil, nil, model.NewAppError("prepareInviteGuestsToChannels", "app.user.get.app_error", nil, result.NErr.Error(), http.StatusInternalServerError) } @@ -1845,11 +1845,11 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest) } - if token.Type != TOKEN_TYPE_TEAM_INVITATION && token.Type != TOKEN_TYPE_GUEST_INVITATION { + if token.Type != TokenTypeTeamInvitation && token.Type != TokenTypeGuestInvitation { return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest) } - if model.GetMillis()-token.CreateAt >= INVITATION_EXPIRY_TIME { + if model.GetMillis()-token.CreateAt >= InvitationExpiryTime { a.DeleteToken(token) return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.expired_link.app_error", nil, "", http.StatusBadRequest) } @@ -2005,10 +2005,10 @@ func (a *App) RemoveTeamIcon(teamId string) *model.AppError { } func (a *App) InvalidateAllEmailInvites() *model.AppError { - if err := a.Srv().Store.Token().RemoveAllTokensByType(TOKEN_TYPE_TEAM_INVITATION); err != nil { + if err := a.Srv().Store.Token().RemoveAllTokensByType(TokenTypeTeamInvitation); err != nil { return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, err.Error(), http.StatusBadRequest) } - if err := a.Srv().Store.Token().RemoveAllTokensByType(TOKEN_TYPE_GUEST_INVITATION); err != nil { + if err := a.Srv().Store.Token().RemoveAllTokensByType(TokenTypeGuestInvitation); err != nil { return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, err.Error(), http.StatusBadRequest) } return nil diff --git a/app/team_test.go b/app/team_test.go index 0759f6a612..fcba6bd4fb 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -200,7 +200,7 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("invalid token type", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_VERIFY_EMAIL, + TokenTypeVerifyEmail, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) @@ -213,11 +213,11 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("expired token", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) - token.CreateAt = model.GetMillis() - INVITATION_EXPIRY_TIME - 1 + token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1 require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) @@ -227,7 +227,7 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("invalid team id", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": model.NewId()}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -239,7 +239,7 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("invalid user id", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -251,7 +251,7 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("valid request", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -268,7 +268,7 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("invalid add a guest using a regular invite", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -278,7 +278,7 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("invalid add a regular user using a guest invite", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -293,7 +293,7 @@ func TestAddUserToTeamByToken(t *testing.T) { }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.RestrictCreationToDomains = "restricted.com" }) token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -309,7 +309,7 @@ func TestAddUserToTeamByToken(t *testing.T) { }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.RestrictCreationToDomains = "restricted.com" }) token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) guestEmail := rguest.Email @@ -335,7 +335,7 @@ func TestAddUserToTeamByToken(t *testing.T) { }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictCreationToDomains = "restricted.com" }) token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) _, err = th.App.Srv().Store.User().Update(rguest, false) @@ -350,7 +350,7 @@ func TestAddUserToTeamByToken(t *testing.T) { t.Run("valid request from guest invite", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -373,7 +373,7 @@ func TestAddUserToTeamByToken(t *testing.T) { require.Nil(t, err, "Should update the team") token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -397,7 +397,7 @@ func TestAddUserToTeamByToken(t *testing.T) { defer th.App.PermanentDeleteUser(&user) token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -412,7 +412,7 @@ func TestAddUserToTeamByToken(t *testing.T) { team := th.CreateTeam() token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": team.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -1102,7 +1102,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) { t1 := model.Token{ Token: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", CreateAt: model.GetMillis(), - Type: TOKEN_TYPE_GUEST_INVITATION, + Type: TokenTypeGuestInvitation, Extra: "", } err := th.App.Srv().Store.Token().Save(&t1) @@ -1111,7 +1111,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) { t2 := model.Token{ Token: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", CreateAt: model.GetMillis(), - Type: TOKEN_TYPE_TEAM_INVITATION, + Type: TokenTypeTeamInvitation, Extra: "", } err = th.App.Srv().Store.Token().Save(&t2) diff --git a/app/user.go b/app/user.go index ec0c1ba631..cdb549ebba 100644 --- a/app/user.go +++ b/app/user.go @@ -38,14 +38,14 @@ import ( ) const ( - TOKEN_TYPE_PASSWORD_RECOVERY = "password_recovery" - TOKEN_TYPE_VERIFY_EMAIL = "verify_email" - TOKEN_TYPE_TEAM_INVITATION = "team_invitation" - TOKEN_TYPE_GUEST_INVITATION = "guest_invitation" - TOKEN_TYPE_CWS_ACCESS = "cws_access_token" - PASSWORD_RECOVER_EXPIRY_TIME = 1000 * 60 * 60 // 1 hour - INVITATION_EXPIRY_TIME = 1000 * 60 * 60 * 48 // 48 hours - IMAGE_PROFILE_PIXEL_DIMENSION = 128 + TokenTypePasswordRecovery = "password_recovery" + TokenTypeVerifyEmail = "verify_email" + TokenTypeTeamInvitation = "team_invitation" + TokenTypeGuestInvitation = "guest_invitation" + TokenTypeCWSAccess = "cws_access_token" + PasswordRecoverExpiryTime = 1000 * 60 * 60 // 1 hour + InvitationExpiryTime = 1000 * 60 * 60 * 48 // 48 hours + ImageProfilePixelDimension = 128 ) func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model.User, *model.AppError) { @@ -53,11 +53,11 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model. return nil, err } - if token.Type != TOKEN_TYPE_TEAM_INVITATION && token.Type != TOKEN_TYPE_GUEST_INVITATION { + if token.Type != TokenTypeTeamInvitation && token.Type != TokenTypeGuestInvitation { return nil, model.NewAppError("CreateUserWithToken", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusBadRequest) } - if model.GetMillis()-token.CreateAt >= INVITATION_EXPIRY_TIME { + if model.GetMillis()-token.CreateAt >= InvitationExpiryTime { a.DeleteToken(token) return nil, model.NewAppError("CreateUserWithToken", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusBadRequest) } @@ -85,7 +85,7 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model. var ruser *model.User var err *model.AppError - if token.Type == TOKEN_TYPE_TEAM_INVITATION { + if token.Type == TokenTypeTeamInvitation { ruser, err = a.CreateUser(user) } else { ruser, err = a.CreateGuest(user) @@ -100,7 +100,7 @@ func (a *App) CreateUserWithToken(user *model.User, token *model.Token) (*model. a.AddDirectChannels(team.Id, ruser) - if token.Type == TOKEN_TYPE_GUEST_INVITATION { + if token.Type == TokenTypeGuestInvitation { for _, channel := range channels { _, err := a.AddChannelMember(ruser.Id, channel, "", "") if err != nil { @@ -448,7 +448,7 @@ func (a *App) GetUser(userId string) (*model.User, *model.AppError) { var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): - return nil, model.NewAppError("GetUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("GetUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("GetUser", "app.user.get.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -477,9 +477,9 @@ func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) { var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): - return nil, model.NewAppError("GetUserByEmail", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("GetUserByEmail", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: - return nil, model.NewAppError("GetUserByEmail", MISSING_ACCOUNT_ERROR, nil, err.Error(), http.StatusInternalServerError) + return nil, model.NewAppError("GetUserByEmail", MissingAccountError, nil, err.Error(), http.StatusInternalServerError) } } return user, nil @@ -492,9 +492,9 @@ func (a *App) GetUserByAuth(authData *string, authService string) (*model.User, var nfErr *store.ErrNotFound switch { case errors.As(err, &invErr): - return nil, model.NewAppError("GetUserByAuth", MISSING_AUTH_ACCOUNT_ERROR, nil, invErr.Error(), http.StatusBadRequest) + return nil, model.NewAppError("GetUserByAuth", MissingAuthAccountError, nil, invErr.Error(), http.StatusBadRequest) case errors.As(err, &nfErr): - return nil, model.NewAppError("GetUserByAuth", MISSING_AUTH_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusInternalServerError) + return nil, model.NewAppError("GetUserByAuth", MissingAuthAccountError, nil, nfErr.Error(), http.StatusInternalServerError) default: return nil, model.NewAppError("GetUserByAuth", "app.user.get_by_auth.other.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -755,7 +755,7 @@ func (a *App) ActivateMfa(userId, token string) *model.AppError { var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): - return model.NewAppError("ActivateMfa", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return model.NewAppError("ActivateMfa", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return model.NewAppError("ActivateMfa", "app.user.get.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -830,10 +830,10 @@ func CreateProfileImage(username string, userId string, initialFont string) ([]b } color := colors[int64(seed)%int64(len(colors))] - dstImg := image.NewRGBA(image.Rect(0, 0, IMAGE_PROFILE_PIXEL_DIMENSION, IMAGE_PROFILE_PIXEL_DIMENSION)) + dstImg := image.NewRGBA(image.Rect(0, 0, ImageProfilePixelDimension, ImageProfilePixelDimension)) srcImg := image.White draw.Draw(dstImg, dstImg.Bounds(), &image.Uniform{color}, image.Point{}, draw.Src) - size := float64(IMAGE_PROFILE_PIXEL_DIMENSION / 2) + size := float64(ImageProfilePixelDimension / 2) c := freetype.NewContext() c.SetFont(font) @@ -842,7 +842,7 @@ func CreateProfileImage(username string, userId string, initialFont string) ([]b c.SetDst(dstImg) c.SetSrc(srcImg) - pt := freetype.Pt(IMAGE_PROFILE_PIXEL_DIMENSION/5, IMAGE_PROFILE_PIXEL_DIMENSION*2/3) + pt := freetype.Pt(ImageProfilePixelDimension/5, ImageProfilePixelDimension*2/3) _, err = c.DrawString(initial, pt) if err != nil { return nil, model.NewAppError("CreateProfileImage", "api.user.create_profile_image.initial.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -1247,7 +1247,7 @@ func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): - return nil, model.NewAppError("UpdateUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("UpdateUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("UpdateUser", "app.user.get.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -1450,7 +1450,7 @@ func (a *App) ResetPasswordFromToken(userSuppliedTokenString, newPassword string if err != nil { return err } - if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME { + if model.GetMillis()-token.CreateAt >= PasswordRecoverExpiryTime { return model.NewAppError("resetPassword", "api.user.reset_password.link_expired.app_error", nil, "", http.StatusBadRequest) } @@ -1523,7 +1523,7 @@ func (a *App) CreatePasswordRecoveryToken(userId, email string) (*model.Token, * return nil, model.NewAppError("CreatePasswordRecoveryToken", "api.user.create_password_token.error", nil, "", http.StatusInternalServerError) } - token := model.NewToken(TOKEN_TYPE_PASSWORD_RECOVERY, string(jsonData)) + token := model.NewToken(TokenTypePasswordRecovery, string(jsonData)) if err := a.Srv().Store.Token().Save(token); err != nil { var appErr *model.AppError @@ -1543,7 +1543,7 @@ func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppEr if err != nil { return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.invalid_link.app_error", nil, err.Error(), http.StatusBadRequest) } - if rtoken.Type != TOKEN_TYPE_PASSWORD_RECOVERY { + if rtoken.Type != TokenTypePasswordRecovery { return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.broken_token.app_error", nil, "", http.StatusBadRequest) } return rtoken, nil @@ -1758,7 +1758,7 @@ func (a *App) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppErr if err != nil { return err } - if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME { + if model.GetMillis()-token.CreateAt >= PasswordRecoverExpiryTime { return model.NewAppError("VerifyEmailFromToken", "api.user.verify_email.link_expired.app_error", nil, "", http.StatusBadRequest) } @@ -1802,7 +1802,7 @@ func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) if err != nil { return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.bad_link.app_error", nil, err.Error(), http.StatusBadRequest) } - if rtoken.Type != TOKEN_TYPE_VERIFY_EMAIL { + if rtoken.Type != TokenTypeVerifyEmail { return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.broken_token.app_error", nil, "", http.StatusBadRequest) } return rtoken, nil @@ -2337,7 +2337,7 @@ func (a *App) ConvertBotToUser(bot *model.Bot, userPatch *model.UserPatch, sysad var nfErr *store.ErrNotFound switch { case errors.As(nErr, &nfErr): - return nil, model.NewAppError("ConvertBotToUser", MISSING_ACCOUNT_ERROR, nil, nfErr.Error(), http.StatusNotFound) + return nil, model.NewAppError("ConvertBotToUser", MissingAccountError, nil, nfErr.Error(), http.StatusNotFound) default: return nil, model.NewAppError("ConvertBotToUser", "app.user.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) } diff --git a/app/user_test.go b/app/user_test.go index 10ff5933be..9ffdaf2678 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -716,7 +716,7 @@ func TestCreateUserWithToken(t *testing.T) { t.Run("invalid token type", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_VERIFY_EMAIL, + TokenTypeVerifyEmail, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -727,10 +727,10 @@ func TestCreateUserWithToken(t *testing.T) { t.Run("expired token", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - token.CreateAt = model.GetMillis() - INVITATION_EXPIRY_TIME - 1 + token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1 require.Nil(t, th.App.Srv().Store.Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.CreateUserWithToken(&user, token) @@ -739,7 +739,7 @@ func TestCreateUserWithToken(t *testing.T) { t.Run("invalid team id", func(t *testing.T) { token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": model.NewId(), "email": user.Email}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -751,7 +751,7 @@ func TestCreateUserWithToken(t *testing.T) { t.Run("valid regular user request", func(t *testing.T) { invitationEmail := model.NewId() + "other-email@test.com" token := model.NewToken( - TOKEN_TYPE_TEAM_INVITATION, + TokenTypeTeamInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -771,7 +771,7 @@ func TestCreateUserWithToken(t *testing.T) { t.Run("valid guest request", func(t *testing.T) { invitationEmail := model.NewId() + "other-email@test.com" token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) @@ -801,11 +801,11 @@ func TestCreateUserWithToken(t *testing.T) { forbiddenInvitationEmail := model.NewId() + "other-email@test.com" grantedInvitationEmail := model.NewId() + "other-email@restricted.com" forbiddenDomainToken := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": forbiddenInvitationEmail, "channels": th.BasicChannel.Id}), ) grantedDomainToken := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": grantedInvitationEmail, "channels": th.BasicChannel.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(forbiddenDomainToken)) @@ -848,7 +848,7 @@ func TestCreateUserWithToken(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.RestrictCreationToDomains = "restricted.com" }) invitationEmail := model.NewId() + "other-email@test.com" token := model.NewToken( - TOKEN_TYPE_GUEST_INVITATION, + TokenTypeGuestInvitation, model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}), ) require.Nil(t, th.App.Srv().Store.Token().Save(token)) diff --git a/app/webhook.go b/app/webhook.go index 34e468376d..99e979daca 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -18,8 +18,8 @@ import ( ) const ( - TRIGGERWORDS_EXACT_MATCH = 0 - TRIGGERWORDS_STARTS_WITH = 1 + TriggerwordsExactMatch = 0 + TriggerwordsStartsWith = 1 MaxIntegrationResponseSize = 1024 * 1024 // Posts can be <100KB at most, so this is likely more than enough ) @@ -55,10 +55,10 @@ func (a *App) handleWebhookEvents(post *model.Post, team *model.Team, channel *m if hook.ChannelId == post.ChannelId && len(hook.TriggerWords) == 0 { relevantHooks = append(relevantHooks, hook) triggerWord = "" - } else if hook.TriggerWhen == TRIGGERWORDS_EXACT_MATCH && hook.TriggerWordExactMatch(firstWord) { + } else if hook.TriggerWhen == TriggerwordsExactMatch && hook.TriggerWordExactMatch(firstWord) { relevantHooks = append(relevantHooks, hook) triggerWord = hook.GetTriggerWord(firstWord, true) - } else if hook.TriggerWhen == TRIGGERWORDS_STARTS_WITH && hook.TriggerWordStartsWith(firstWord) { + } else if hook.TriggerWhen == TriggerwordsStartsWith && hook.TriggerWordStartsWith(firstWord) { relevantHooks = append(relevantHooks, hook) triggerWord = hook.GetTriggerWord(firstWord, false) } diff --git a/cmd/mattermost/commands/channelargs.go b/cmd/mattermost/commands/channelargs.go index 03a42e5b33..bbbc6d4eec 100644 --- a/cmd/mattermost/commands/channelargs.go +++ b/cmd/mattermost/commands/channelargs.go @@ -11,7 +11,7 @@ import ( "github.com/mattermost/mattermost-server/v5/model" ) -const CHANNEL_ARG_SEPARATOR = ":" +const ChannelArgSeparator = ":" func getChannelsFromChannelArgs(a *app.App, channelArgs []string) []*model.Channel { channels := make([]*model.Channel, 0, len(channelArgs)) @@ -23,7 +23,7 @@ func getChannelsFromChannelArgs(a *app.App, channelArgs []string) []*model.Chann } func parseChannelArg(channelArg string) (string, string) { - result := strings.SplitN(channelArg, CHANNEL_ARG_SEPARATOR, 2) + result := strings.SplitN(channelArg, ChannelArgSeparator, 2) if len(result) == 1 { return "", channelArg } diff --git a/cmd/mattermost/commands/commandargs.go b/cmd/mattermost/commands/commandargs.go index f2726507c6..49c59ab257 100644 --- a/cmd/mattermost/commands/commandargs.go +++ b/cmd/mattermost/commands/commandargs.go @@ -11,7 +11,7 @@ import ( "github.com/mattermost/mattermost-server/v5/model" ) -const COMMAND_ARGS_SEPARATOR = ":" +const CommandArgsSeparator = ":" func getCommandsFromCommandArgs(a *app.App, commandArgs []string) []*model.Command { commands := make([]*model.Command, 0, len(commandArgs)) @@ -25,7 +25,7 @@ func getCommandsFromCommandArgs(a *app.App, commandArgs []string) []*model.Comma } func parseCommandArg(commandArg string) (string, string) { - result := strings.SplitN(commandArg, COMMAND_ARGS_SEPARATOR, 2) + result := strings.SplitN(commandArg, CommandArgsSeparator, 2) if len(result) == 1 { return "", commandArg diff --git a/cmd/mattermost/commands/sampledata.go b/cmd/mattermost/commands/sampledata.go index 742ef646b6..0f86fe9600 100644 --- a/cmd/mattermost/commands/sampledata.go +++ b/cmd/mattermost/commands/sampledata.go @@ -24,8 +24,8 @@ import ( ) const ( - DEACTIVATED_USER = "deactivated" - GUEST_USER = "guest" + DeactivatedUser = "deactivated" + GuestUser = "guest" ) var SampleDataCmd = &cobra.Command{ @@ -296,12 +296,12 @@ func sampleDataCmdF(command *cobra.Command, args []string) error { allUsers = append(allUsers, *userLine.User.Username) } for i := 0; i < guests; i++ { - userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, GUEST_USER) + userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, GuestUser) encoder.Encode(userLine) allUsers = append(allUsers, *userLine.User.Username) } for i := 0; i < deactivatedUsers; i++ { - userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, DEACTIVATED_USER) + userLine := createUser(i, teamMemberships, channelMemberships, teamsAndChannels, profileImages, DeactivatedUser) encoder.Encode(userLine) allUsers = append(allUsers, *userLine.User.Username) } @@ -401,7 +401,7 @@ func createUser(idx int, teamMemberships int, channelMemberships int, teamsAndCh var email string switch userType { - case GUEST_USER: + case GuestUser: password = fmt.Sprintf("SampleGu@st-%d", idx) email = fmt.Sprintf("guest-%d@sample.mattermost.com", idx) roles = "system_guest" @@ -410,7 +410,7 @@ func createUser(idx int, teamMemberships int, channelMemberships int, teamsAndCh password = "SampleGu@st1" email = "guest@sample.mattermost.com" } - case DEACTIVATED_USER: + case DeactivatedUser: password = fmt.Sprintf("SampleDe@ctivated-%d", idx) email = fmt.Sprintf("deactivated-%d@sample.mattermost.com", idx) default: @@ -492,12 +492,12 @@ func createUser(idx int, teamMemberships int, channelMemberships int, teamsAndCh team := possibleTeams[position] possibleTeams = append(possibleTeams[:position], possibleTeams[position+1:]...) if teamChannels, err := teamsAndChannels[team]; err { - teams = append(teams, createTeamMembership(channelMemberships, teamChannels, &team, userType == GUEST_USER)) + teams = append(teams, createTeamMembership(channelMemberships, teamChannels, &team, userType == GuestUser)) } } var deleteAt int64 - if userType == DEACTIVATED_USER { + if userType == DeactivatedUser { deleteAt = model.GetMillis() } diff --git a/cmd/mattermost/commands/server_test.go b/cmd/mattermost/commands/server_test.go index 684e356dda..3f16ea713b 100644 --- a/cmd/mattermost/commands/server_test.go +++ b/cmd/mattermost/commands/server_test.go @@ -38,8 +38,8 @@ func SetupServerTest(t testing.TB) *ServerTestHelper { // Let jobs poll for termination every 0.2s (instead of every 15s by default) // Otherwise we would have to wait the whole polling duration before the test // terminates. - originalInterval := jobs.DEFAULT_WATCHER_POLLING_INTERVAL - jobs.DEFAULT_WATCHER_POLLING_INTERVAL = 200 + originalInterval := jobs.DefaultWatcherPollingInterval + jobs.DefaultWatcherPollingInterval = 200 th := &ServerTestHelper{ disableConfigWatch: true, @@ -50,7 +50,7 @@ func SetupServerTest(t testing.TB) *ServerTestHelper { } func (th *ServerTestHelper) TearDownServerTest() { - jobs.DEFAULT_WATCHER_POLLING_INTERVAL = th.originalInterval + jobs.DefaultWatcherPollingInterval = th.originalInterval } func TestRunServerSuccess(t *testing.T) { diff --git a/cmd/mattermost/commands/utils.go b/cmd/mattermost/commands/utils.go index 38012c80a9..4b7f7f0cae 100644 --- a/cmd/mattermost/commands/utils.go +++ b/cmd/mattermost/commands/utils.go @@ -17,7 +17,7 @@ import ( "github.com/spf13/cobra" ) -const CUSTOM_DEFAULTS_ENV_VAR = "MM_CUSTOM_DEFAULTS_PATH" +const CustomDefaultsEnvVar = "MM_CUSTOM_DEFAULTS_PATH" // prettyPrintStruct will return a prettyPrint version of a given struct func prettyPrintStruct(t interface{}) string { @@ -123,7 +123,7 @@ func getConfigDSN(command *cobra.Command, env map[string]string) string { } func loadCustomDefaults() (*model.Config, error) { - customDefaultsPath := os.Getenv(CUSTOM_DEFAULTS_ENV_VAR) + customDefaultsPath := os.Getenv(CustomDefaultsEnvVar) if customDefaultsPath == "" { return nil, nil } diff --git a/go.tools.mod b/go.tools.mod index e54084086f..e7deea0c94 100644 --- a/go.tools.mod +++ b/go.tools.mod @@ -4,7 +4,7 @@ go 1.14 require ( github.com/jstemmer/go-junit-report v0.9.1 // indirect - github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201013204121-e463fcd00ba8 // indirect + github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20210103185547-4c12aa739237 // indirect github.com/philhofer/fwd v1.0.0 // indirect github.com/reflog/struct2interface v0.6.1 // indirect github.com/tinylib/msgp v1.1.2 // indirect diff --git a/go.tools.sum b/go.tools.sum index 2e5d316406..793e0cd5c7 100644 --- a/go.tools.sum +++ b/go.tools.sum @@ -74,6 +74,8 @@ github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201001222518-667645 github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201001222518-66764584f346/go.mod h1:3gKozJI8n2Y/vW37GfnFWAdehGXe5yZlt+HykK6Y3DM= github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201013204121-e463fcd00ba8 h1:6wiKDdS/MMY0Jht12lRZJq1zv5eHEd4fK60SwkUVGjA= github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20201013204121-e463fcd00ba8/go.mod h1:3gKozJI8n2Y/vW37GfnFWAdehGXe5yZlt+HykK6Y3DM= +github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20210103185547-4c12aa739237 h1:w6GQs7SU6abD0QXKoqwd4bpEzNaW1xKwpeftBpIX1Do= +github.com/mattermost/mattermost-utilities/mmgotool v0.0.0-20210103185547-4c12aa739237/go.mod h1:3gKozJI8n2Y/vW37GfnFWAdehGXe5yZlt+HykK6Y3DM= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= diff --git a/jobs/jobs.go b/jobs/jobs.go index 13f16357af..48f274175f 100644 --- a/jobs/jobs.go +++ b/jobs/jobs.go @@ -15,7 +15,7 @@ import ( ) const ( - CANCEL_WATCHER_POLLING_INTERVAL = 5000 + CancelWatcherPollingInterval = 5000 ) func (srv *JobServer) CreateJob(jobType string, jobData map[string]string) (*model.Job, *model.AppError) { @@ -166,7 +166,7 @@ func (srv *JobServer) CancellationWatcher(ctx context.Context, jobId string, can case <-ctx.Done(): mlog.Debug("CancellationWatcher for Job Aborting as job has finished.", mlog.String("job_id", jobId)) return - case <-time.After(CANCEL_WATCHER_POLLING_INTERVAL * time.Millisecond): + case <-time.After(CancelWatcherPollingInterval * time.Millisecond): mlog.Debug("CancellationWatcher for Job started polling.", mlog.String("job_id", jobId)) if jobStatus, err := srv.Store.Job().Get(jobId); err == nil { if jobStatus.Status == model.JOB_STATUS_CANCEL_REQUESTED { diff --git a/jobs/jobs_watcher.go b/jobs/jobs_watcher.go index 748e9fca23..b8c507cd39 100644 --- a/jobs/jobs_watcher.go +++ b/jobs/jobs_watcher.go @@ -13,7 +13,7 @@ import ( // Default polling interval for jobs termination. // (Defining as `var` rather than `const` allows tests to lower the interval.) -var DEFAULT_WATCHER_POLLING_INTERVAL = 15000 +var DefaultWatcherPollingInterval = 15000 type Watcher struct { srv *JobServer diff --git a/jobs/workers.go b/jobs/workers.go index 1b18a94c2e..0efa5802eb 100644 --- a/jobs/workers.go +++ b/jobs/workers.go @@ -37,7 +37,7 @@ func (srv *JobServer) InitWorkers() *Workers { workers := &Workers{ ConfigService: srv.ConfigService, } - workers.Watcher = srv.MakeWatcher(workers, DEFAULT_WATCHER_POLLING_INTERVAL) + workers.Watcher = srv.MakeWatcher(workers, DefaultWatcherPollingInterval) if srv.DataRetentionJob != nil { workers.DataRetention = srv.DataRetentionJob.MakeWorker() diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go index d80c4451ac..12e42ced49 100644 --- a/manualtesting/manual_testing.go +++ b/manualtesting/manual_testing.go @@ -105,7 +105,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { user := &model.User{ Email: "success+" + model.NewId() + "simulator.amazonses.com", Nickname: username[0], - Password: slashcommands.USER_PASSWORD} + Password: slashcommands.UserPassword} user, resp := client.CreateUser(user) if resp.Error != nil { @@ -119,7 +119,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { userID = user.Id // Login as user to generate auth token - _, resp = client.LoginById(user.Id, slashcommands.USER_PASSWORD) + _, resp = client.LoginById(user.Id, slashcommands.UserPassword) if resp.Error != nil { c.Err = resp.Error return diff --git a/migrations/helper_test.go b/migrations/helper_test.go index d59d19312b..17d826336b 100644 --- a/migrations/helper_test.go +++ b/migrations/helper_test.go @@ -251,7 +251,7 @@ func (th *TestHelper) DeleteAllJobsByTypeAndMigrationKey(jobType string, migrati } for _, job := range jobs { - if key, ok := job.Data[JOB_DATA_KEY_MIGRATION]; ok && key == migrationKey { + if key, ok := job.Data[JobDataKeyMigration]; ok && key == migrationKey { if _, err = th.App.Srv().Store.Job().Delete(job.Id); err != nil { panic(err) } diff --git a/migrations/migrations.go b/migrations/migrations.go index ebe9735700..c724afd2c0 100644 --- a/migrations/migrations.go +++ b/migrations/migrations.go @@ -13,12 +13,12 @@ import ( ) const ( - MIGRATION_STATE_UNSCHEDULED = "unscheduled" - MIGRATION_STATE_IN_PROGRESS = "in_progress" - MIGRATION_STATE_COMPLETED = "completed" + MigrationStateUnscheduled = "unscheduled" + MigrationStateInProgress = "in_progress" + MigrationStateCompleted = "completed" - JOB_DATA_KEY_MIGRATION = "migration_key" - JOB_DATA_KEY_MIGRATION_LAST_DONE = "last_done" + JobDataKeyMigration = "migration_key" + JobDataKeyMigration_LAST_DONE = "last_done" ) type MigrationsJobInterfaceImpl struct { @@ -39,7 +39,7 @@ func MakeMigrationsList() []string { func GetMigrationState(migration string, store store.Store) (string, *model.Job, *model.AppError) { if _, err := store.System().GetByName(migration); err == nil { - return MIGRATION_STATE_COMPLETED, nil, nil + return MigrationStateCompleted, nil, nil } jobs, err := store.Job().GetAllByType(model.JOB_TYPE_MIGRATIONS) @@ -48,19 +48,19 @@ func GetMigrationState(migration string, store store.Store) (string, *model.Job, } for _, job := range jobs { - if key, ok := job.Data[JOB_DATA_KEY_MIGRATION]; ok { + if key, ok := job.Data[JobDataKeyMigration]; ok { if key != migration { continue } switch job.Status { case model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_PENDING: - return MIGRATION_STATE_IN_PROGRESS, job, nil + return MigrationStateInProgress, job, nil default: - return MIGRATION_STATE_UNSCHEDULED, job, nil + return MigrationStateUnscheduled, job, nil } } } - return MIGRATION_STATE_UNSCHEDULED, nil, nil + return MigrationStateUnscheduled, nil, nil } diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index 1c45345744..6fd136672e 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -50,7 +50,7 @@ func TestGetMigrationState(t *testing.T) { Id: model.NewId(), CreateAt: model.GetMillis(), Data: map[string]string{ - JOB_DATA_KEY_MIGRATION: migrationKey, + JobDataKeyMigration: migrationKey, }, Status: model.JOB_STATUS_PENDING, Type: model.JOB_TYPE_MIGRATIONS, @@ -69,7 +69,7 @@ func TestGetMigrationState(t *testing.T) { Id: model.NewId(), CreateAt: j1.CreateAt + 1, Data: map[string]string{ - JOB_DATA_KEY_MIGRATION: migrationKey, + JobDataKeyMigration: migrationKey, }, Status: model.JOB_STATUS_IN_PROGRESS, Type: model.JOB_TYPE_MIGRATIONS, @@ -88,7 +88,7 @@ func TestGetMigrationState(t *testing.T) { Id: model.NewId(), CreateAt: j2.CreateAt + 1, Data: map[string]string{ - JOB_DATA_KEY_MIGRATION: migrationKey, + JobDataKeyMigration: migrationKey, }, Status: model.JOB_STATUS_ERROR, Type: model.JOB_TYPE_MIGRATIONS, diff --git a/migrations/scheduler.go b/migrations/scheduler.go index f5bd064201..f0ca5f404e 100644 --- a/migrations/scheduler.go +++ b/migrations/scheduler.go @@ -13,7 +13,7 @@ import ( ) const ( - MIGRATION_JOB_WEDGED_TIMEOUT_MILLISECONDS = 3600000 // 1 hour + MigrationJobWedgedTimeoutMilliseconds = 3600000 // 1 hour ) type Scheduler struct { @@ -57,9 +57,9 @@ func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, las return nil, nil } - if state == MIGRATION_STATE_IN_PROGRESS { + if state == MigrationStateInProgress { // Check the migration job isn't wedged. - if job != nil && job.LastActivityAt < model.GetMillis()-MIGRATION_JOB_WEDGED_TIMEOUT_MILLISECONDS && job.CreateAt < model.GetMillis()-MIGRATION_JOB_WEDGED_TIMEOUT_MILLISECONDS { + if job != nil && job.LastActivityAt < model.GetMillis()-MigrationJobWedgedTimeoutMilliseconds && job.CreateAt < model.GetMillis()-MigrationJobWedgedTimeoutMilliseconds { mlog.Warn("Job appears to be wedged. Rescheduling another instance.", mlog.String("scheduler", scheduler.Name()), mlog.String("wedged_job_id", job.Id), mlog.String("migration_key", key)) if err := scheduler.srv.Jobs.SetJobError(job, nil); err != nil { mlog.Error("Worker: Failed to set job error", mlog.String("scheduler", scheduler.Name()), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) @@ -70,12 +70,12 @@ func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, las return nil, nil } - if state == MIGRATION_STATE_COMPLETED { + if state == MigrationStateCompleted { // This migration is done. Continue to check the next. continue } - if state == MIGRATION_STATE_UNSCHEDULED { + if state == MigrationStateUnscheduled { mlog.Debug("Scheduling a new job for migration.", mlog.String("scheduler", scheduler.Name()), mlog.String("migration_key", key)) return scheduler.createJob(key, job, scheduler.srv.Store) } @@ -94,12 +94,12 @@ func (scheduler *Scheduler) ScheduleJob(cfg *model.Config, pendingJobs bool, las func (scheduler *Scheduler) createJob(migrationKey string, lastJob *model.Job, store store.Store) (*model.Job, *model.AppError) { var lastDone string if lastJob != nil { - lastDone = lastJob.Data[JOB_DATA_KEY_MIGRATION_LAST_DONE] + lastDone = lastJob.Data[JobDataKeyMigration_LAST_DONE] } data := map[string]string{ - JOB_DATA_KEY_MIGRATION: migrationKey, - JOB_DATA_KEY_MIGRATION_LAST_DONE: lastDone, + JobDataKeyMigration: migrationKey, + JobDataKeyMigration_LAST_DONE: lastDone, } job, err := scheduler.srv.Jobs.CreateJob(model.JOB_TYPE_MIGRATIONS, data) diff --git a/migrations/worker.go b/migrations/worker.go index a4386a66d0..2c6130a046 100644 --- a/migrations/worker.go +++ b/migrations/worker.go @@ -15,7 +15,7 @@ import ( ) const ( - TIME_BETWEEN_BATCHES = 100 + TimeBetweenBatches = 100 ) type Worker struct { @@ -99,8 +99,8 @@ func (worker *Worker) DoJob(job *model.Job) { worker.setJobCanceled(job) return - case <-time.After(TIME_BETWEEN_BATCHES * time.Millisecond): - done, progress, err := worker.runMigration(job.Data[JOB_DATA_KEY_MIGRATION], job.Data[JOB_DATA_KEY_MIGRATION_LAST_DONE]) + case <-time.After(TimeBetweenBatches * time.Millisecond): + done, progress, err := worker.runMigration(job.Data[JobDataKeyMigration], job.Data[JobDataKeyMigration_LAST_DONE]) if err != nil { mlog.Error("Worker: Failed to run migration", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) worker.setJobError(job, err) @@ -110,7 +110,7 @@ func (worker *Worker) DoJob(job *model.Job) { worker.setJobSuccess(job) return } else { - job.Data[JOB_DATA_KEY_MIGRATION_LAST_DONE] = progress + job.Data[JobDataKeyMigration_LAST_DONE] = progress if err := worker.srv.Jobs.UpdateInProgressJobData(job); err != nil { mlog.Error("Worker: Failed to update migration status data for job", mlog.String("worker", worker.name), mlog.String("job_id", job.Id), mlog.String("error", err.Error())) worker.setJobError(job, err) diff --git a/plugin/client.go b/plugin/client.go index e445f9e1e0..ed3d872d79 100644 --- a/plugin/client.go +++ b/plugin/client.go @@ -8,8 +8,8 @@ import ( ) const ( - INTERNAL_KEY_PREFIX = "mmi_" - BOT_USER_KEY = INTERNAL_KEY_PREFIX + "botid" + InternalKeyPrefix = "mmi_" + BotUserKey = InternalKeyPrefix + "botid" ) // Starts the serving of a Mattermost plugin over net/rpc. gRPC is not yet supported. diff --git a/plugin/environment.go b/plugin/environment.go index ff80117ffb..f22edff4e5 100644 --- a/plugin/environment.go +++ b/plugin/environment.go @@ -504,7 +504,7 @@ func newRegisteredPlugin(bundle *model.BundleInfo) registeredPlugin { func (env *Environment) InitPluginHealthCheckJob(enable bool) { // Config is set to enable. No job exists, start a new job. if enable && env.pluginHealthCheckJob == nil { - mlog.Debug("Enabling plugin health check job", mlog.Duration("interval_s", HEALTH_CHECK_INTERVAL)) + mlog.Debug("Enabling plugin health check job", mlog.Duration("interval_s", HealthCheckInterval)) job := newPluginHealthCheckJob(env) env.pluginHealthCheckJob = job diff --git a/plugin/health_check.go b/plugin/health_check.go index a620cd1842..e8a3461e93 100644 --- a/plugin/health_check.go +++ b/plugin/health_check.go @@ -12,10 +12,10 @@ import ( ) const ( - HEALTH_CHECK_INTERVAL = 30 * time.Second // How often the health check should run - HEALTH_CHECK_DEACTIVATION_WINDOW = 60 * time.Minute // How long we wait for num fails to occur before deactivating the plugin - HEALTH_CHECK_PING_FAIL_LIMIT = 3 // How many times we call RPC ping in a row before it is considered a failure - HEALTH_CHECK_NUM_RESTARTS_LIMIT = 3 // How many times we restart a plugin before we deactivate it + HealthCheckInterval = 30 * time.Second // How often the health check should run + HealthCheckDeactivationWindow = 60 * time.Minute // How long we wait for num fails to occur before deactivating the plugin + HealthCheckPingFailLimit = 3 // How many times we call RPC ping in a row before it is considered a failure + HealthCheckNumRestartsLimit = 3 // How many times we restart a plugin before we deactivate it ) type PluginHealthCheckJob struct { @@ -31,7 +31,7 @@ func (job *PluginHealthCheckJob) run() { mlog.Debug("Plugin health check job starting.") defer close(job.cancelled) - ticker := time.NewTicker(HEALTH_CHECK_INTERVAL) + ticker := time.NewTicker(HealthCheckInterval) defer ticker.Stop() for { @@ -103,21 +103,21 @@ func (job *PluginHealthCheckJob) Cancel() { <-job.cancelled } -// shouldDeactivatePlugin determines if a plugin needs to be deactivated after the plugin has failed (HEALTH_CHECK_NUM_RESTARTS_LIMIT) times, -// within the configured time window (HEALTH_CHECK_DEACTIVATION_WINDOW). +// shouldDeactivatePlugin determines if a plugin needs to be deactivated after the plugin has failed (HealthCheckNumRestartsLimit) times, +// within the configured time window (HealthCheckDeactivationWindow). func shouldDeactivatePlugin(failedTimestamps []time.Time) bool { - if len(failedTimestamps) < HEALTH_CHECK_NUM_RESTARTS_LIMIT { + if len(failedTimestamps) < HealthCheckNumRestartsLimit { return false } - index := len(failedTimestamps) - HEALTH_CHECK_NUM_RESTARTS_LIMIT - return time.Since(failedTimestamps[index]) <= HEALTH_CHECK_DEACTIVATION_WINDOW + index := len(failedTimestamps) - HealthCheckNumRestartsLimit + return time.Since(failedTimestamps[index]) <= HealthCheckDeactivationWindow } -// removeStaleTimestamps only keeps the last HEALTH_CHECK_NUM_RESTARTS_LIMIT items in timestamps. +// removeStaleTimestamps only keeps the last HealthCheckNumRestartsLimit items in timestamps. func removeStaleTimestamps(timestamps []time.Time) []time.Time { - if len(timestamps) > HEALTH_CHECK_NUM_RESTARTS_LIMIT { - timestamps = timestamps[len(timestamps)-HEALTH_CHECK_NUM_RESTARTS_LIMIT:] + if len(timestamps) > HealthCheckNumRestartsLimit { + timestamps = timestamps[len(timestamps)-HealthCheckNumRestartsLimit:] } return timestamps diff --git a/plugin/health_check_test.go b/plugin/health_check_test.go index 7f478283b7..f19e4abb31 100644 --- a/plugin/health_check_test.go +++ b/plugin/health_check_test.go @@ -129,8 +129,8 @@ func TestShouldDeactivatePlugin(t *testing.T) { // Failures are recent enough to restart ftime = []time.Time{} - ftime = append(ftime, now.Add(-HEALTH_CHECK_DEACTIVATION_WINDOW/10*2)) - ftime = append(ftime, now.Add(-HEALTH_CHECK_DEACTIVATION_WINDOW/10)) + ftime = append(ftime, now.Add(-HealthCheckDeactivationWindow/10*2)) + ftime = append(ftime, now.Add(-HealthCheckDeactivationWindow/10)) ftime = append(ftime, now) result = shouldDeactivatePlugin(ftime) @@ -138,8 +138,8 @@ func TestShouldDeactivatePlugin(t *testing.T) { // Failures are too spaced out to warrant a restart ftime = []time.Time{} - ftime = append(ftime, now.Add(-HEALTH_CHECK_DEACTIVATION_WINDOW*2)) - ftime = append(ftime, now.Add(-HEALTH_CHECK_DEACTIVATION_WINDOW*1)) + ftime = append(ftime, now.Add(-HealthCheckDeactivationWindow*2)) + ftime = append(ftime, now.Add(-HealthCheckDeactivationWindow*1)) ftime = append(ftime, now) result = shouldDeactivatePlugin(ftime) @@ -147,7 +147,7 @@ func TestShouldDeactivatePlugin(t *testing.T) { // Not enough failures are present to warrant a restart ftime = []time.Time{} - ftime = append(ftime, now.Add(-HEALTH_CHECK_DEACTIVATION_WINDOW/10)) + ftime = append(ftime, now.Add(-HealthCheckDeactivationWindow/10)) ftime = append(ftime, now) result = shouldDeactivatePlugin(ftime) diff --git a/plugin/helpers_bots.go b/plugin/helpers_bots.go index c0e30d9983..ed30cb62fc 100644 --- a/plugin/helpers_bots.go +++ b/plugin/helpers_bots.go @@ -133,7 +133,7 @@ func (p *HelpersImpl) ShouldProcessMessage(post *model.Post, options ...ShouldPr option(messageProcessOptions) } - botIDBytes, kvGetErr := p.API.KVGet(BOT_USER_KEY) + botIDBytes, kvGetErr := p.API.KVGet(BotUserKey) if kvGetErr != nil { return false, errors.Wrap(kvGetErr, "failed to get bot") } @@ -212,7 +212,7 @@ func (p *HelpersImpl) ensureBot(bot *model.Bot) (retBotID string, retErr error) var botIDBytes []byte err = utils.ProgressiveRetry(func() error { - botIDBytes, err = p.API.KVGet(BOT_USER_KEY) + botIDBytes, err = p.API.KVGet(BotUserKey) if err != nil { return err } @@ -226,7 +226,7 @@ func (p *HelpersImpl) ensureBot(bot *model.Bot) (retBotID string, retErr error) } }() - botIDBytes, kvGetErr := p.API.KVGet(BOT_USER_KEY) + botIDBytes, kvGetErr := p.API.KVGet(BotUserKey) if kvGetErr != nil { return "", errors.Wrap(kvGetErr, "failed to get bot") } @@ -252,7 +252,7 @@ func (p *HelpersImpl) ensureBot(bot *model.Bot) (retBotID string, retErr error) // Check for an existing bot user with that username. If one exists, then use that. if user, userGetErr := p.API.GetUserByUsername(bot.Username); userGetErr == nil && user != nil { if user.IsBot { - if kvSetErr := p.API.KVSet(BOT_USER_KEY, []byte(user.Id)); kvSetErr != nil { + if kvSetErr := p.API.KVSet(BotUserKey, []byte(user.Id)); kvSetErr != nil { p.API.LogWarn("Failed to set claimed bot user id.", "userid", user.Id, "err", kvSetErr) } } else { @@ -267,7 +267,7 @@ func (p *HelpersImpl) ensureBot(bot *model.Bot) (retBotID string, retErr error) return "", errors.Wrap(createBotErr, "failed to create bot") } - if kvSetErr := p.API.KVSet(BOT_USER_KEY, []byte(createdBot.UserId)); kvSetErr != nil { + if kvSetErr := p.API.KVSet(BotUserKey, []byte(createdBot.UserId)); kvSetErr != nil { p.API.LogWarn("Failed to set created bot user id.", "userid", createdBot.UserId, "err", kvSetErr) } diff --git a/plugin/helpers_bots_test.go b/plugin/helpers_bots_test.go index 1b331ee0b3..622aa3023f 100644 --- a/plugin/helpers_bots_test.go +++ b/plugin/helpers_bots_test.go @@ -72,7 +72,7 @@ func TestEnsureBot(t *testing.T) { api := setupAPI() api.On("GetServerVersion").Return("5.10.0") - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) api.On("PatchBot", expectedBotID, &model.BotPatch{ Username: &testbot.Username, DisplayName: &testbot.DisplayName, @@ -92,7 +92,7 @@ func TestEnsureBot(t *testing.T) { t.Run("should return an error if unable to get bot", func(t *testing.T) { api := setupAPI() api.On("GetServerVersion").Return("5.10.0") - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, &model.AppError{}) + api.On("KVGet", plugin.BotUserKey).Return(nil, &model.AppError{}) defer api.AssertExpectations(t) p := &plugin.HelpersImpl{} @@ -112,7 +112,7 @@ func TestEnsureBot(t *testing.T) { testImage := filepath.Join(testsDir, "test.png") imageBytes, err := ioutil.ReadFile(testImage) - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) api.On("GetBundlePath").Return("", nil) api.On("SetProfileImage", expectedBotID, imageBytes).Return(nil) api.On("GetServerVersion").Return("5.10.0") @@ -142,7 +142,7 @@ func TestEnsureBot(t *testing.T) { imageBytes, err := ioutil.ReadFile(testImage) assert.Nil(t, err) - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) api.On("GetBundlePath").Return("", nil) api.On("SetBotIconImage", expectedBotID, imageBytes).Return(nil) api.On("GetServerVersion").Return("5.10.0") @@ -170,7 +170,7 @@ func TestEnsureBot(t *testing.T) { imageBytes, err := ioutil.ReadFile(testImage) assert.Nil(t, err) - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) api.On("GetBundlePath").Return("", nil) api.On("SetProfileImage", expectedBotID, imageBytes).Return(nil) api.On("SetBotIconImage", expectedBotID, imageBytes).Return(nil) @@ -204,7 +204,7 @@ func TestEnsureBot(t *testing.T) { api := setupAPI() api.On("GetServerVersion").Return("5.10.0") - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) api.On("GetBundlePath").Return("", nil) api.On("SetProfileImage", expectedBotID, imageBytes).Return(nil) api.On("SetBotIconImage", expectedBotID, imageBytes).Return(nil) @@ -236,12 +236,12 @@ func TestEnsureBot(t *testing.T) { api := setupAPI() api.On("GetServerVersion").Return("5.10.0") - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) api.On("GetUserByUsername", testbot.Username).Return(nil, nil) api.On("CreateBot", testbot).Return(&model.Bot{ UserId: expectedBotID, }, nil) - api.On("KVSet", plugin.BOT_USER_KEY, []byte(expectedBotID)).Return(nil) + api.On("KVSet", plugin.BotUserKey, []byte(expectedBotID)).Return(nil) defer api.AssertExpectations(t) p := &plugin.HelpersImpl{} @@ -258,12 +258,12 @@ func TestEnsureBot(t *testing.T) { api := setupAPI() api.On("GetServerVersion").Return("5.10.0") - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) api.On("GetUserByUsername", testbot.Username).Return(&model.User{ Id: expectedBotID, IsBot: true, }, nil) - api.On("KVSet", plugin.BOT_USER_KEY, []byte(expectedBotID)).Return(nil) + api.On("KVSet", plugin.BotUserKey, []byte(expectedBotID)).Return(nil) defer api.AssertExpectations(t) p := &plugin.HelpersImpl{} @@ -279,7 +279,7 @@ func TestEnsureBot(t *testing.T) { expectedBotID := model.NewId() api := setupAPI() api.On("GetServerVersion").Return("5.10.0") - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) api.On("GetUserByUsername", testbot.Username).Return(&model.User{ Id: expectedBotID, IsBot: false, @@ -299,7 +299,7 @@ func TestEnsureBot(t *testing.T) { t.Run("should fail if create bot fails", func(t *testing.T) { api := setupAPI() api.On("GetServerVersion").Return("5.10.0") - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) api.On("GetUserByUsername", testbot.Username).Return(nil, nil) api.On("CreateBot", testbot).Return(nil, &model.AppError{}) defer api.AssertExpectations(t) @@ -322,12 +322,12 @@ func TestEnsureBot(t *testing.T) { imageBytes, err := ioutil.ReadFile(testImage) assert.Nil(t, err) - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) api.On("GetUserByUsername", testbot.Username).Return(nil, nil) api.On("CreateBot", testbot).Return(&model.Bot{ UserId: expectedBotID, }, nil) - api.On("KVSet", plugin.BOT_USER_KEY, []byte(expectedBotID)).Return(nil) + api.On("KVSet", plugin.BotUserKey, []byte(expectedBotID)).Return(nil) api.On("GetBundlePath").Return("", nil) api.On("SetProfileImage", expectedBotID, imageBytes).Return(nil) api.On("GetServerVersion").Return("5.10.0") @@ -350,12 +350,12 @@ func TestEnsureBot(t *testing.T) { imageBytes, err := ioutil.ReadFile(testImage) assert.Nil(t, err) - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) api.On("GetUserByUsername", testbot.Username).Return(nil, nil) api.On("CreateBot", testbot).Return(&model.Bot{ UserId: expectedBotID, }, nil) - api.On("KVSet", plugin.BOT_USER_KEY, []byte(expectedBotID)).Return(nil) + api.On("KVSet", plugin.BotUserKey, []byte(expectedBotID)).Return(nil) api.On("GetBundlePath").Return("", nil) api.On("SetBotIconImage", expectedBotID, imageBytes).Return(nil) api.On("GetServerVersion").Return("5.10.0") @@ -378,12 +378,12 @@ func TestEnsureBot(t *testing.T) { imageBytes, err := ioutil.ReadFile(testImage) assert.Nil(t, err) - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) api.On("GetUserByUsername", testbot.Username).Return(nil, nil) api.On("CreateBot", testbot).Return(&model.Bot{ UserId: expectedBotID, }, nil) - api.On("KVSet", plugin.BOT_USER_KEY, []byte(expectedBotID)).Return(nil) + api.On("KVSet", plugin.BotUserKey, []byte(expectedBotID)).Return(nil) api.On("GetBundlePath").Return("", nil) api.On("SetProfileImage", expectedBotID, imageBytes).Return(nil) api.On("SetBotIconImage", expectedBotID, imageBytes).Return(nil) @@ -410,7 +410,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should not respond to itself", func(t *testing.T) { api := setupAPI() - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) p.API = api shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{Type: model.POST_HEADER_CHANGE, UserId: expectedBotID}, plugin.AllowSystemMessages(), plugin.AllowBots()) @@ -428,7 +428,7 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) p.API = api - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{ChannelId: channelID}, plugin.AllowSystemMessages(), plugin.AllowBots(), plugin.FilterChannelIDs([]string{"another-channel-id"})) @@ -441,7 +441,7 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() p.API = api api.On("GetUser", userID).Return(&model.User{IsBot: true}, nil) - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: userID, ChannelId: channelID}, plugin.AllowSystemMessages(), plugin.FilterUserIDs([]string{"another-user-id"})) @@ -458,7 +458,7 @@ func TestShouldProcessMessage(t *testing.T) { } api := setupAPI() api.On("GetChannel", channelID).Return(&channel, nil) - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) p.API = api shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: userID, ChannelId: channelID}, plugin.AllowSystemMessages(), plugin.AllowBots(), plugin.OnlyBotDMs()) @@ -469,7 +469,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should process the message", func(t *testing.T) { channelID := "1" api := setupAPI() - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) p.API = api shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.POST_HEADER_CHANGE, ChannelId: channelID}, @@ -481,7 +481,7 @@ func TestShouldProcessMessage(t *testing.T) { t.Run("should process the message for plugin without a bot", func(t *testing.T) { channelID := "1" api := setupAPI() - api.On("KVGet", plugin.BOT_USER_KEY).Return(nil, nil) + api.On("KVGet", plugin.BotUserKey).Return(nil, nil) p.API = api shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.POST_HEADER_CHANGE, ChannelId: channelID}, @@ -498,7 +498,7 @@ func TestShouldProcessMessage(t *testing.T) { Type: model.CHANNEL_DIRECT, } api.On("GetChannel", channelID).Return(&channel, nil) - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) p.API = api shouldProcessMessage, _ := p.ShouldProcessMessage(&model.Post{UserId: "1", Type: model.POST_HEADER_CHANGE, ChannelId: channelID}, @@ -512,7 +512,7 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) p.API = api - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) shouldProcessMessage, err := p.ShouldProcessMessage(&model.Post{ChannelId: channelID, Props: model.StringInterface{"from_webhook": "true"}}, plugin.AllowBots()) @@ -525,7 +525,7 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) p.API = api - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) shouldProcessMessage, err := p.ShouldProcessMessage(&model.Post{ChannelId: channelID, Props: model.StringInterface{"from_webhook": "true"}}, plugin.AllowBots(), plugin.AllowWebhook()) assert.Nil(t, err) @@ -538,7 +538,7 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) p.API = api - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) shouldProcessMessage, err := p.ShouldProcessMessage(&model.Post{ChannelId: channelID}, plugin.AllowBots()) assert.Nil(t, err) @@ -551,7 +551,7 @@ func TestShouldProcessMessage(t *testing.T) { api := setupAPI() api.On("GetChannel", channelID).Return(&model.Channel{Id: channelID, Type: model.CHANNEL_GROUP}, nil) p.API = api - api.On("KVGet", plugin.BOT_USER_KEY).Return([]byte(expectedBotID), nil) + api.On("KVGet", plugin.BotUserKey).Return([]byte(expectedBotID), nil) shouldProcessMessage, err := p.ShouldProcessMessage(&model.Post{ChannelId: channelID, Props: model.StringInterface{"from_webhook": "false"}}, plugin.AllowBots()) assert.Nil(t, err) diff --git a/plugin/supervisor.go b/plugin/supervisor.go index 348ea4a46f..8aef7f0a61 100644 --- a/plugin/supervisor.go +++ b/plugin/supervisor.go @@ -114,7 +114,7 @@ func (sup *supervisor) Hooks() Hooks { func (sup *supervisor) PerformHealthCheck() error { // No need for a lock here because Ping is read-locked. if pingErr := sup.Ping(); pingErr != nil { - for pingFails := 1; pingFails < HEALTH_CHECK_PING_FAIL_LIMIT; pingFails++ { + for pingFails := 1; pingFails < HealthCheckPingFailLimit; pingFails++ { pingErr = sup.Ping() if pingErr == nil { break diff --git a/services/filesstore/localstore.go b/services/filesstore/localstore.go index 2434cf95f6..04ae066605 100644 --- a/services/filesstore/localstore.go +++ b/services/filesstore/localstore.go @@ -17,7 +17,7 @@ import ( ) const ( - TEST_FILE_PATH = "/testfile" + TestFilePath = "/testfile" ) type LocalFileBackend struct { @@ -26,10 +26,10 @@ type LocalFileBackend struct { func (b *LocalFileBackend) TestConnection() error { f := bytes.NewReader([]byte("testingwrite")) - if _, err := writeFileLocally(f, filepath.Join(b.directory, TEST_FILE_PATH)); err != nil { + if _, err := writeFileLocally(f, filepath.Join(b.directory, TestFilePath)); err != nil { return errors.Wrap(err, "unable to write to the local filesystem storage") } - os.Remove(filepath.Join(b.directory, TEST_FILE_PATH)) + os.Remove(filepath.Join(b.directory, TestFilePath)) mlog.Debug("Able to write files to local storage.") return nil } diff --git a/services/mailservice/inbucket.go b/services/mailservice/inbucket.go index b0ccd138a8..08d0ce28f1 100644 --- a/services/mailservice/inbucket.go +++ b/services/mailservice/inbucket.go @@ -16,7 +16,7 @@ import ( ) const ( - INBUCKET_API = "/api/v1/mailbox/" + InbucketAPI = "/api/v1/mailbox/" ) // OutputJSONHeader holds the received Header to test sending emails (inbucket) @@ -57,7 +57,7 @@ func GetMailBox(email string) (results JSONMessageHeaderInbucket, err error) { parsedEmail := ParseEmail(email) - url := fmt.Sprintf("%s%s%s", getInbucketHost(), INBUCKET_API, parsedEmail) + url := fmt.Sprintf("%s%s%s", getInbucketHost(), InbucketAPI, parsedEmail) resp, err := http.Get(url) if err != nil { @@ -93,7 +93,7 @@ func GetMessageFromMailbox(email, id string) (JSONMessageInbucket, error) { var record JSONMessageInbucket - url := fmt.Sprintf("%s%s%s/%s", getInbucketHost(), INBUCKET_API, parsedEmail, id) + url := fmt.Sprintf("%s%s%s/%s", getInbucketHost(), InbucketAPI, parsedEmail, id) emailResponse, err := http.Get(url) if err != nil { return record, err @@ -139,7 +139,7 @@ func DeleteMailBox(email string) (err error) { parsedEmail := ParseEmail(email) - url := fmt.Sprintf("%s%s%s", getInbucketHost(), INBUCKET_API, parsedEmail) + url := fmt.Sprintf("%s%s%s", getInbucketHost(), InbucketAPI, parsedEmail) req, err := http.NewRequest("DELETE", url, nil) if err != nil { return err diff --git a/services/mfa/mfa.go b/services/mfa/mfa.go index 1738f20b60..d8bd3ce277 100644 --- a/services/mfa/mfa.go +++ b/services/mfa/mfa.go @@ -18,7 +18,7 @@ import ( const ( // This will result in 160 bits of entropy (base32 encoded), as recommended by rfc4226. - MFA_SECRET_SIZE = 20 + MFASecretSize = 20 ) type Mfa struct { @@ -58,7 +58,7 @@ func (m *Mfa) GenerateSecret(user *model.User) (string, []byte, *model.AppError) issuer := getIssuerFromUrl(*m.ConfigService.Config().ServiceSettings.SiteURL) - secret := model.NewRandomBase32String(MFA_SECRET_SIZE) + secret := model.NewRandomBase32String(MFASecretSize) authLink := fmt.Sprintf("otpauth://totp/%s:%s?secret=%s&issuer=%s", issuer, user.Email, secret, issuer) diff --git a/services/mfa/mfa_test.go b/services/mfa/mfa_test.go index 100a2b4cf1..2b03cbc7df 100644 --- a/services/mfa/mfa_test.go +++ b/services/mfa/mfa_test.go @@ -93,7 +93,7 @@ func TestGetIssuerFromUrl(t *testing.T) { func TestActivate(t *testing.T) { user := &model.User{Id: model.NewId(), Roles: "system_user"} - user.MfaSecret = model.NewRandomBase32String(MFA_SECRET_SIZE) + user.MfaSecret = model.NewRandomBase32String(MFASecretSize) token := dgoogauth.ComputeCode(user.MfaSecret, time.Now().UTC().Unix()/30) @@ -226,7 +226,7 @@ func TestDeactivate(t *testing.T) { } func TestValidateToken(t *testing.T) { - secret := model.NewRandomBase32String(MFA_SECRET_SIZE) + secret := model.NewRandomBase32String(MFASecretSize) token := dgoogauth.ComputeCode(secret, time.Now().UTC().Unix()/30) config := model.Config{} diff --git a/services/searchengine/bleveengine/bleve.go b/services/searchengine/bleveengine/bleve.go index 76ca7f6359..1d3bdf418b 100644 --- a/services/searchengine/bleveengine/bleve.go +++ b/services/searchengine/bleveengine/bleve.go @@ -22,10 +22,10 @@ import ( ) const ( - ENGINE_NAME = "bleve" - POST_INDEX = "posts" - USER_INDEX = "users" - CHANNEL_INDEX = "channels" + EngineName = "bleve" + PostIndex = "posts" + UserIndex = "users" + ChannelIndex = "channels" ) type BleveEngine struct { @@ -127,17 +127,17 @@ func (b *BleveEngine) openIndexes() *model.AppError { } var err error - b.PostIndex, err = b.createOrOpenIndex(POST_INDEX, getPostIndexMapping()) + b.PostIndex, err = b.createOrOpenIndex(PostIndex, getPostIndexMapping()) if err != nil { return model.NewAppError("Bleveengine.Start", "bleveengine.create_post_index.error", nil, err.Error(), http.StatusInternalServerError) } - b.UserIndex, err = b.createOrOpenIndex(USER_INDEX, getUserIndexMapping()) + b.UserIndex, err = b.createOrOpenIndex(UserIndex, getUserIndexMapping()) if err != nil { return model.NewAppError("Bleveengine.Start", "bleveengine.create_user_index.error", nil, err.Error(), http.StatusInternalServerError) } - b.ChannelIndex, err = b.createOrOpenIndex(CHANNEL_INDEX, getChannelIndexMapping()) + b.ChannelIndex, err = b.createOrOpenIndex(ChannelIndex, getChannelIndexMapping()) if err != nil { return model.NewAppError("Bleveengine.Start", "bleveengine.create_channel_index.error", nil, err.Error(), http.StatusInternalServerError) } @@ -204,7 +204,7 @@ func (b *BleveEngine) GetVersion() int { } func (b *BleveEngine) GetName() string { - return ENGINE_NAME + return EngineName } func (b *BleveEngine) TestConfig(cfg *model.Config) *model.AppError { @@ -212,13 +212,13 @@ func (b *BleveEngine) TestConfig(cfg *model.Config) *model.AppError { } func (b *BleveEngine) deleteIndexes() *model.AppError { - if err := os.RemoveAll(b.getIndexDir(POST_INDEX)); err != nil { + if err := os.RemoveAll(b.getIndexDir(PostIndex)); err != nil { return model.NewAppError("Bleveengine.PurgeIndexes", "bleveengine.purge_post_index.error", nil, err.Error(), http.StatusInternalServerError) } - if err := os.RemoveAll(b.getIndexDir(USER_INDEX)); err != nil { + if err := os.RemoveAll(b.getIndexDir(UserIndex)); err != nil { return model.NewAppError("Bleveengine.PurgeIndexes", "bleveengine.purge_user_index.error", nil, err.Error(), http.StatusInternalServerError) } - if err := os.RemoveAll(b.getIndexDir(CHANNEL_INDEX)); err != nil { + if err := os.RemoveAll(b.getIndexDir(ChannelIndex)); err != nil { return model.NewAppError("Bleveengine.PurgeIndexes", "bleveengine.purge_channel_index.error", nil, err.Error(), http.StatusInternalServerError) } return nil diff --git a/services/searchengine/bleveengine/bleve_test.go b/services/searchengine/bleveengine/bleve_test.go index bf9c052643..36f6b2d12f 100644 --- a/services/searchengine/bleveengine/bleve_test.go +++ b/services/searchengine/bleveengine/bleve_test.go @@ -84,7 +84,7 @@ func (s *BleveEngineTestSuite) TearDownSuite() { func (s *BleveEngineTestSuite) TestBleveSearchStoreTests() { searchTestEngine := &searchtest.SearchTestEngine{ - Driver: searchtest.ENGINE_BLEVE, + Driver: searchtest.EngineBleve, } s.Run("TestSearchChannelStore", func() { diff --git a/services/searchengine/bleveengine/indexer/indexing_job.go b/services/searchengine/bleveengine/indexer/indexing_job.go index aa695a8e8d..4644e3e45b 100644 --- a/services/searchengine/bleveengine/indexer/indexing_job.go +++ b/services/searchengine/bleveengine/indexer/indexing_job.go @@ -18,11 +18,11 @@ import ( ) const ( - BATCH_SIZE = 1000 - TIME_BETWEEN_BATCHES = 100 - ESTIMATED_POST_COUNT = 10000000 - ESTIMATED_CHANNEL_COUNT = 100000 - ESTIMATED_USER_COUNT = 10000 + BatchSize = 1000 + TimeBetweenBatches = 100 + EstimatedPostCount = 10000000 + EstimatedChannelCount = 100000 + EstimatedUserCount = 10000 ) func init() { @@ -188,7 +188,7 @@ func (worker *BleveIndexerWorker) DoJob(job *model.Job) { // on with the indexing job anyway. The only issue is that the progress % reporting will be inaccurate. if count, err := worker.jobServer.Store.Post().AnalyticsPostCount("", false, false); err != nil { mlog.Warn("Worker: Failed to fetch total post count for job. An estimated value will be used for progress reporting.", mlog.String("workername", worker.name), mlog.String("job_id", job.Id), mlog.Err(err)) - progress.TotalPostsCount = ESTIMATED_POST_COUNT + progress.TotalPostsCount = EstimatedPostCount } else { progress.TotalPostsCount = count } @@ -196,7 +196,7 @@ func (worker *BleveIndexerWorker) DoJob(job *model.Job) { // Same possible fail as above can happen when counting channels if count, err := worker.jobServer.Store.Channel().AnalyticsTypeCount("", "O"); err != nil { mlog.Warn("Worker: Failed to fetch total channel count for job. An estimated value will be used for progress reporting.", mlog.String("workername", worker.name), mlog.String("job_id", job.Id), mlog.Err(err)) - progress.TotalChannelsCount = ESTIMATED_CHANNEL_COUNT + progress.TotalChannelsCount = EstimatedChannelCount } else { progress.TotalChannelsCount = count } @@ -204,7 +204,7 @@ func (worker *BleveIndexerWorker) DoJob(job *model.Job) { // Same possible fail as above can happen when counting users if count, err := worker.jobServer.Store.User().Count(model.UserCountOptions{}); err != nil { mlog.Warn("Worker: Failed to fetch total user count for job. An estimated value will be used for progress reporting.", mlog.String("workername", worker.name), mlog.String("job_id", job.Id), mlog.Err(err)) - progress.TotalUsersCount = ESTIMATED_USER_COUNT + progress.TotalUsersCount = EstimatedUserCount } else { progress.TotalUsersCount = count } @@ -231,7 +231,7 @@ func (worker *BleveIndexerWorker) DoJob(job *model.Job) { } return - case <-time.After(TIME_BETWEEN_BATCHES * time.Millisecond): + case <-time.After(TimeBetweenBatches * time.Millisecond): var err *model.AppError if progress, err = worker.IndexBatch(progress); err != nil { mlog.Error("Worker: Failed to index batch for job", mlog.String("workername", worker.name), mlog.String("job_id", job.Id), mlog.Err(err)) @@ -284,7 +284,7 @@ func (worker *BleveIndexerWorker) IndexPostsBatch(progress IndexingProgress) (In tries := 0 for posts == nil { var err error - posts, err = worker.jobServer.Store.Post().GetPostsBatchForIndexing(progress.LastEntityTime, endTime, BATCH_SIZE) + posts, err = worker.jobServer.Store.Post().GetPostsBatchForIndexing(progress.LastEntityTime, endTime, BatchSize) if err != nil { if tries >= 10 { return progress, model.NewAppError("IndexPostsBatch", "app.post.get_posts_batch_for_indexing.get.app_error", nil, err.Error(), http.StatusInternalServerError) @@ -305,7 +305,7 @@ func (worker *BleveIndexerWorker) IndexPostsBatch(progress IndexingProgress) (In // Due to the "endTime" parameter in the store query, we might get an incomplete batch before the end. In this // case, set the "newLastMessageTime" to the endTime so we don't get stuck running the same query in a loop. - if len(posts) < BATCH_SIZE { + if len(posts) < BatchSize { newLastMessageTime = endTime } @@ -317,8 +317,8 @@ func (worker *BleveIndexerWorker) IndexPostsBatch(progress IndexingProgress) (In if progress.EndAtTime <= newLastMessageTime { progress.DonePosts = true progress.LastEntityTime = progress.StartAtTime - } else if progress.LastEntityTime == newLastMessageTime && len(posts) == BATCH_SIZE { - mlog.Error("More posts with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastMessageTime), mlog.Int("Batch Size", BATCH_SIZE)) + } else if progress.LastEntityTime == newLastMessageTime && len(posts) == BatchSize { + mlog.Error("More posts with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastMessageTime), mlog.Int("Batch Size", BatchSize)) progress.DonePosts = true progress.LastEntityTime = progress.StartAtTime } else { @@ -362,7 +362,7 @@ func (worker *BleveIndexerWorker) IndexChannelsBatch(progress IndexingProgress) tries := 0 for channels == nil { var nErr error - channels, nErr = worker.jobServer.Store.Channel().GetChannelsBatchForIndexing(progress.LastEntityTime, endTime, BATCH_SIZE) + channels, nErr = worker.jobServer.Store.Channel().GetChannelsBatchForIndexing(progress.LastEntityTime, endTime, BatchSize) if nErr != nil { if tries >= 10 { return progress, model.NewAppError("BleveIndexerWorker.IndexChannelsBatch", "app.channel.get_channels_batch_for_indexing.get.app_error", nil, nErr.Error(), http.StatusInternalServerError) @@ -383,7 +383,7 @@ func (worker *BleveIndexerWorker) IndexChannelsBatch(progress IndexingProgress) // Due to the "endTime" parameter in the store query, we might get an incomplete batch before the end. In this // case, set the "newLastChannelTime" to the endTime so we don't get stuck running the same query in a loop. - if len(channels) < BATCH_SIZE { + if len(channels) < BatchSize { newLastChannelTime = endTime } @@ -395,8 +395,8 @@ func (worker *BleveIndexerWorker) IndexChannelsBatch(progress IndexingProgress) if progress.EndAtTime <= newLastChannelTime { progress.DoneChannels = true progress.LastEntityTime = progress.StartAtTime - } else if progress.LastEntityTime == newLastChannelTime && len(channels) == BATCH_SIZE { - mlog.Error("More channels with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastChannelTime), mlog.Int("Batch Size", BATCH_SIZE)) + } else if progress.LastEntityTime == newLastChannelTime && len(channels) == BatchSize { + mlog.Error("More channels with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastChannelTime), mlog.Int("Batch Size", BatchSize)) progress.DoneChannels = true progress.LastEntityTime = progress.StartAtTime } else { @@ -439,7 +439,7 @@ func (worker *BleveIndexerWorker) IndexUsersBatch(progress IndexingProgress) (In tries := 0 for users == nil { - if usersBatch, err := worker.jobServer.Store.User().GetUsersBatchForIndexing(progress.LastEntityTime, endTime, BATCH_SIZE); err != nil { + if usersBatch, err := worker.jobServer.Store.User().GetUsersBatchForIndexing(progress.LastEntityTime, endTime, BatchSize); err != nil { if tries >= 10 { return progress, model.NewAppError("IndexUsersBatch", "app.user.get_users_batch_for_indexing.get_users.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -461,7 +461,7 @@ func (worker *BleveIndexerWorker) IndexUsersBatch(progress IndexingProgress) (In // Due to the "endTime" parameter in the store query, we might get an incomplete batch before the end. In this // case, set the "newLastUserTime" to the endTime so we don't get stuck running the same query in a loop. - if len(users) < BATCH_SIZE { + if len(users) < BatchSize { newLastUserTime = endTime } @@ -473,8 +473,8 @@ func (worker *BleveIndexerWorker) IndexUsersBatch(progress IndexingProgress) (In if progress.EndAtTime <= newLastUserTime { progress.DoneUsers = true progress.LastEntityTime = progress.StartAtTime - } else if progress.LastEntityTime == newLastUserTime && len(users) == BATCH_SIZE { - mlog.Error("More users with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastUserTime), mlog.Int("Batch Size", BATCH_SIZE)) + } else if progress.LastEntityTime == newLastUserTime && len(users) == BatchSize { + mlog.Error("More users with the same CreateAt time were detected than the permitted batch size. Aborting indexing job.", mlog.Int64("CreateAt", newLastUserTime), mlog.Int("Batch Size", BatchSize)) progress.DoneUsers = true progress.LastEntityTime = progress.StartAtTime } else { diff --git a/services/searchengine/bleveengine/search.go b/services/searchengine/bleveengine/search.go index 73759416f8..55f5e88d97 100644 --- a/services/searchengine/bleveengine/search.go +++ b/services/searchengine/bleveengine/search.go @@ -14,7 +14,7 @@ import ( "github.com/blevesearch/bleve/search/query" ) -const DELETE_POSTS_BATCH_SIZE = 500 +const DeletePostsBatchSize = 500 func (b *BleveEngine) IndexPost(post *model.Post, teamId string) *model.AppError { b.Mutex.RLock() @@ -261,7 +261,7 @@ func (b *BleveEngine) DeleteChannelPosts(channelID string) *model.AppError { query := bleve.NewTermQuery(channelID) query.SetField("ChannelId") search := bleve.NewSearchRequest(query) - deleted, err := b.deletePosts(search, DELETE_POSTS_BATCH_SIZE) + deleted, err := b.deletePosts(search, DeletePostsBatchSize) if err != nil { return model.NewAppError("Bleveengine.DeleteChannelPosts", "bleveengine.delete_channel_posts.error", nil, @@ -280,7 +280,7 @@ func (b *BleveEngine) DeleteUserPosts(userID string) *model.AppError { query := bleve.NewTermQuery(userID) query.SetField("UserId") search := bleve.NewSearchRequest(query) - deleted, err := b.deletePosts(search, DELETE_POSTS_BATCH_SIZE) + deleted, err := b.deletePosts(search, DeletePostsBatchSize) if err != nil { return model.NewAppError("Bleveengine.DeleteUserPosts", "bleveengine.delete_user_posts.error", nil, diff --git a/services/telemetry/telemetry.go b/services/telemetry/telemetry.go index 0ca08a938f..52d529ccd7 100644 --- a/services/telemetry/telemetry.go +++ b/services/telemetry/telemetry.go @@ -23,60 +23,60 @@ import ( ) const ( - DAY_MILLISECONDS = 24 * 60 * 60 * 1000 - MONTH_MILLISECONDS = 31 * DAY_MILLISECONDS + DayMilliseconds = 24 * 60 * 60 * 1000 + MonthMilliseconds = 31 * DayMilliseconds - RUDDER_KEY = "placeholder_rudder_key" - RUDDER_DATAPLANE_URL = "placeholder_rudder_dataplane_url" + RudderKey = "placeholder_rudder_key" + RudderDataplaneURL = "placeholder_rudder_dataplane_url" - ENV_VAR_INSTALL_TYPE = "MM_INSTALL_TYPE" + EnvVarInstallType = "MM_INSTALL_TYPE" - TRACK_CONFIG_SERVICE = "config_service" - TRACK_CONFIG_TEAM = "config_team" - TRACK_CONFIG_CLIENT_REQ = "config_client_requirements" - TRACK_CONFIG_SQL = "config_sql" - TRACK_CONFIG_LOG = "config_log" - TRACK_CONFIG_AUDIT = "config_audit" - TRACK_CONFIG_NOTIFICATION_LOG = "config_notifications_log" - TRACK_CONFIG_FILE = "config_file" - TRACK_CONFIG_RATE = "config_rate" - TRACK_CONFIG_EMAIL = "config_email" - TRACK_CONFIG_PRIVACY = "config_privacy" - TRACK_CONFIG_THEME = "config_theme" - TRACK_CONFIG_OAUTH = "config_oauth" - TRACK_CONFIG_LDAP = "config_ldap" - TRACK_CONFIG_COMPLIANCE = "config_compliance" - TRACK_CONFIG_LOCALIZATION = "config_localization" - TRACK_CONFIG_SAML = "config_saml" - TRACK_CONFIG_PASSWORD = "config_password" - TRACK_CONFIG_CLUSTER = "config_cluster" - TRACK_CONFIG_METRICS = "config_metrics" - TRACK_CONFIG_SUPPORT = "config_support" - TRACK_CONFIG_NATIVEAPP = "config_nativeapp" - TRACK_CONFIG_EXPERIMENTAL = "config_experimental" - TRACK_CONFIG_ANALYTICS = "config_analytics" - TRACK_CONFIG_ANNOUNCEMENT = "config_announcement" - TRACK_CONFIG_ELASTICSEARCH = "config_elasticsearch" - TRACK_CONFIG_PLUGIN = "config_plugin" - TRACK_CONFIG_DATA_RETENTION = "config_data_retention" - TRACK_CONFIG_MESSAGE_EXPORT = "config_message_export" - TRACK_CONFIG_DISPLAY = "config_display" - TRACK_CONFIG_GUEST_ACCOUNTS = "config_guest_accounts" - TRACK_CONFIG_IMAGE_PROXY = "config_image_proxy" - TRACK_CONFIG_BLEVE = "config_bleve" - TRACK_PERMISSIONS_GENERAL = "permissions_general" - TRACK_PERMISSIONS_SYSTEM_SCHEME = "permissions_system_scheme" - TRACK_PERMISSIONS_TEAM_SCHEMES = "permissions_team_schemes" - TRACK_PERMISSIONS_SYSTEM_ROLES = "permissions_system_roles" - TRACK_ELASTICSEARCH = "elasticsearch" - TRACK_GROUPS = "groups" - TRACK_CHANNEL_MODERATION = "channel_moderation" - TRACK_WARN_METRICS = "warn_metrics" + TrackConfigService = "config_service" + TrackConfigTeam = "config_team" + TrackConfigClientReq = "config_client_requirements" + TrackConfigSQL = "config_sql" + TrackConfigLog = "config_log" + TrackConfigAudit = "config_audit" + TrackConfigNotificationLog = "config_notifications_log" + TrackConfigFile = "config_file" + TrackConfigRate = "config_rate" + TrackConfigEmail = "config_email" + TrackConfigPrivacy = "config_privacy" + TrackConfigTheme = "config_theme" + TrackConfigOauth = "config_oauth" + TrackConfigLDAP = "config_ldap" + TrackConfigCompliance = "config_compliance" + TrackConfigLocalization = "config_localization" + TrackConfigSAML = "config_saml" + TrackConfigPassword = "config_password" + TrackConfigCluster = "config_cluster" + TrackConfigMetrics = "config_metrics" + TrackConfigSupport = "config_support" + TrackConfigNativeApp = "config_nativeapp" + TrackConfigExperimental = "config_experimental" + TrackConfigAnalytics = "config_analytics" + TrackConfigAnnouncement = "config_announcement" + TrackConfigElasticsearch = "config_elasticsearch" + TrackConfigPlugin = "config_plugin" + TrackConfigDataRetention = "config_data_retention" + TrackConfigMessageExport = "config_message_export" + TrackConfigDisplay = "config_display" + TrackConfigGuestAccounts = "config_guest_accounts" + TrackConfigImageProxy = "config_image_proxy" + TrackConfigBleve = "config_bleve" + TrackPermissionsGeneral = "permissions_general" + TrackPermissionsSystemScheme = "permissions_system_scheme" + TrackPermissionsTeamSchemes = "permissions_team_schemes" + TrackPermissionsSystemRoles = "permissions_system_roles" + TrackElasticsearch = "elasticsearch" + TrackGroups = "groups" + TrackChannelModeration = "channel_moderation" + TrackWarnMetrics = "warn_metrics" - TRACK_ACTIVITY = "activity" - TRACK_LICENSE = "license" - TRACK_SERVER = "server" - TRACK_PLUGINS = "plugins" + TrackActivity = "activity" + TrackLicense = "license" + TrackServer = "server" + TrackPlugins = "plugins" ) type ServerIface interface { @@ -136,10 +136,10 @@ func (ts *TelemetryService) ensureTelemetryID() { } func (ts *TelemetryService) getRudderConfig() RudderConfig { - if !strings.Contains(RUDDER_KEY, "placeholder") && !strings.Contains(RUDDER_DATAPLANE_URL, "placeholder") { - return RudderConfig{RUDDER_KEY, RUDDER_DATAPLANE_URL} - } else if os.Getenv("RUDDER_KEY") != "" && os.Getenv("RUDDER_DATAPLANE_URL") != "" { - return RudderConfig{os.Getenv("RUDDER_KEY"), os.Getenv("RUDDER_DATAPLANE_URL")} + if !strings.Contains(RudderKey, "placeholder") && !strings.Contains(RudderDataplaneURL, "placeholder") { + return RudderConfig{RudderKey, RudderDataplaneURL} + } else if os.Getenv("RudderKey") != "" && os.Getenv("RudderDataplaneURL") != "" { + return RudderConfig{os.Getenv("RudderKey"), os.Getenv("RudderDataplaneURL")} } else { return RudderConfig{} } @@ -233,14 +233,14 @@ func (ts *TelemetryService) trackActivity() { activeUsersDailyCountChan := make(chan store.StoreResult, 1) go func() { - count, err := ts.dbStore.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + count, err := ts.dbStore.User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) activeUsersDailyCountChan <- store.StoreResult{Data: count, NErr: err} close(activeUsersDailyCountChan) }() activeUsersMonthlyCountChan := make(chan store.StoreResult, 1) go func() { - count, err := ts.dbStore.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + count, err := ts.dbStore.User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) activeUsersMonthlyCountChan <- store.StoreResult{Data: count, NErr: err} close(activeUsersMonthlyCountChan) }() @@ -320,7 +320,7 @@ func (ts *TelemetryService) trackActivity() { activeUsersMonthlyCount = r.Data.(int64) } - ts.sendTelemetry(TRACK_ACTIVITY, map[string]interface{}{ + ts.sendTelemetry(TrackActivity, map[string]interface{}{ "registered_users": userCount, "bot_accounts": botAccountsCount, "guest_accounts": guestAccountsCount, @@ -344,7 +344,7 @@ func (ts *TelemetryService) trackActivity() { func (ts *TelemetryService) trackConfig() { cfg := ts.srv.Config() - ts.sendTelemetry(TRACK_CONFIG_SERVICE, map[string]interface{}{ + ts.sendTelemetry(TrackConfigService, map[string]interface{}{ "web_server_mode": *cfg.ServiceSettings.WebserverMode, "enable_security_fix_alert": *cfg.ServiceSettings.EnableSecurityFixAlert, "enable_insecure_outgoing_connections": *cfg.ServiceSettings.EnableInsecureOutgoingConnections, @@ -426,7 +426,7 @@ func (ts *TelemetryService) trackConfig() { "managed_resource_paths": isDefault(*cfg.ServiceSettings.ManagedResourcePaths, ""), }) - ts.sendTelemetry(TRACK_CONFIG_TEAM, map[string]interface{}{ + ts.sendTelemetry(TrackConfigTeam, map[string]interface{}{ "enable_user_creation": cfg.TeamSettings.EnableUserCreation, "enable_team_creation": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_EnableTeamCreation, "restrict_team_invite": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite, @@ -460,7 +460,7 @@ func (ts *TelemetryService) trackConfig() { "experimental_default_channels": len(cfg.TeamSettings.ExperimentalDefaultChannels), }) - ts.sendTelemetry(TRACK_CONFIG_CLIENT_REQ, map[string]interface{}{ + ts.sendTelemetry(TrackConfigClientReq, map[string]interface{}{ "android_latest_version": cfg.ClientRequirements.AndroidLatestVersion, "android_min_version": cfg.ClientRequirements.AndroidMinVersion, "desktop_latest_version": cfg.ClientRequirements.DesktopLatestVersion, @@ -469,7 +469,7 @@ func (ts *TelemetryService) trackConfig() { "ios_min_version": cfg.ClientRequirements.IosMinVersion, }) - ts.sendTelemetry(TRACK_CONFIG_SQL, map[string]interface{}{ + ts.sendTelemetry(TrackConfigSQL, map[string]interface{}{ "driver_name": *cfg.SqlSettings.DriverName, "trace": cfg.SqlSettings.Trace, "max_idle_conns": *cfg.SqlSettings.MaxIdleConns, @@ -481,7 +481,7 @@ func (ts *TelemetryService) trackConfig() { "disable_database_search": *cfg.SqlSettings.DisableDatabaseSearch, }) - ts.sendTelemetry(TRACK_CONFIG_LOG, map[string]interface{}{ + ts.sendTelemetry(TrackConfigLog, map[string]interface{}{ "enable_console": cfg.LogSettings.EnableConsole, "console_level": cfg.LogSettings.ConsoleLevel, "console_json": *cfg.LogSettings.ConsoleJson, @@ -493,7 +493,7 @@ func (ts *TelemetryService) trackConfig() { "advanced_logging_config": *cfg.LogSettings.AdvancedLoggingConfig != "", }) - ts.sendTelemetry(TRACK_CONFIG_AUDIT, map[string]interface{}{ + ts.sendTelemetry(TrackConfigAudit, map[string]interface{}{ "file_enabled": *cfg.ExperimentalAuditSettings.FileEnabled, "file_max_size_mb": *cfg.ExperimentalAuditSettings.FileMaxSizeMB, "file_max_age_days": *cfg.ExperimentalAuditSettings.FileMaxAgeDays, @@ -503,7 +503,7 @@ func (ts *TelemetryService) trackConfig() { "advanced_logging_config": *cfg.ExperimentalAuditSettings.AdvancedLoggingConfig != "", }) - ts.sendTelemetry(TRACK_CONFIG_NOTIFICATION_LOG, map[string]interface{}{ + ts.sendTelemetry(TrackConfigNotificationLog, map[string]interface{}{ "enable_console": *cfg.NotificationLogSettings.EnableConsole, "console_level": *cfg.NotificationLogSettings.ConsoleLevel, "console_json": *cfg.NotificationLogSettings.ConsoleJson, @@ -514,7 +514,7 @@ func (ts *TelemetryService) trackConfig() { "advanced_logging_config": *cfg.NotificationLogSettings.AdvancedLoggingConfig != "", }) - ts.sendTelemetry(TRACK_CONFIG_PASSWORD, map[string]interface{}{ + ts.sendTelemetry(TrackConfigPassword, map[string]interface{}{ "minimum_length": *cfg.PasswordSettings.MinimumLength, "lowercase": *cfg.PasswordSettings.Lowercase, "number": *cfg.PasswordSettings.Number, @@ -522,7 +522,7 @@ func (ts *TelemetryService) trackConfig() { "symbol": *cfg.PasswordSettings.Symbol, }) - ts.sendTelemetry(TRACK_CONFIG_FILE, map[string]interface{}{ + ts.sendTelemetry(TrackConfigFile, map[string]interface{}{ "enable_public_links": cfg.FileSettings.EnablePublicLink, "driver_name": *cfg.FileSettings.DriverName, "isdefault_directory": isDefault(*cfg.FileSettings.Directory, model.FILE_SETTINGS_DEFAULT_DIRECTORY), @@ -537,7 +537,7 @@ func (ts *TelemetryService) trackConfig() { "enable_mobile_download": *cfg.FileSettings.EnableMobileDownload, }) - ts.sendTelemetry(TRACK_CONFIG_EMAIL, map[string]interface{}{ + ts.sendTelemetry(TrackConfigEmail, map[string]interface{}{ "enable_sign_up_with_email": cfg.EmailSettings.EnableSignUpWithEmail, "enable_sign_in_with_email": *cfg.EmailSettings.EnableSignInWithEmail, "enable_sign_in_with_username": *cfg.EmailSettings.EnableSignInWithUsername, @@ -564,7 +564,7 @@ func (ts *TelemetryService) trackConfig() { "smtp_server_timeout": *cfg.EmailSettings.SMTPServerTimeout, }) - ts.sendTelemetry(TRACK_CONFIG_RATE, map[string]interface{}{ + ts.sendTelemetry(TrackConfigRate, map[string]interface{}{ "enable_rate_limiter": *cfg.RateLimitSettings.Enable, "vary_by_remote_address": *cfg.RateLimitSettings.VaryByRemoteAddr, "vary_by_user": *cfg.RateLimitSettings.VaryByUser, @@ -574,19 +574,19 @@ func (ts *TelemetryService) trackConfig() { "isdefault_vary_by_header": isDefault(cfg.RateLimitSettings.VaryByHeader, ""), }) - ts.sendTelemetry(TRACK_CONFIG_PRIVACY, map[string]interface{}{ + ts.sendTelemetry(TrackConfigPrivacy, map[string]interface{}{ "show_email_address": cfg.PrivacySettings.ShowEmailAddress, "show_full_name": cfg.PrivacySettings.ShowFullName, }) - ts.sendTelemetry(TRACK_CONFIG_THEME, map[string]interface{}{ + ts.sendTelemetry(TrackConfigTheme, map[string]interface{}{ "enable_theme_selection": *cfg.ThemeSettings.EnableThemeSelection, "isdefault_default_theme": isDefault(*cfg.ThemeSettings.DefaultTheme, model.TEAM_SETTINGS_DEFAULT_TEAM_TEXT), "allow_custom_themes": *cfg.ThemeSettings.AllowCustomThemes, "allowed_themes": len(cfg.ThemeSettings.AllowedThemes), }) - ts.sendTelemetry(TRACK_CONFIG_OAUTH, map[string]interface{}{ + ts.sendTelemetry(TrackConfigOauth, map[string]interface{}{ "enable_gitlab": cfg.GitLabSettings.Enable, "openid_gitlab": *cfg.GitLabSettings.Enable && strings.Contains(*cfg.GitLabSettings.Scope, model.SERVICE_OPENID), "enable_google": cfg.GoogleSettings.Enable, @@ -596,7 +596,7 @@ func (ts *TelemetryService) trackConfig() { "enable_openid": cfg.OpenIdSettings.Enable, }) - ts.sendTelemetry(TRACK_CONFIG_SUPPORT, map[string]interface{}{ + ts.sendTelemetry(TrackConfigSupport, map[string]interface{}{ "isdefault_terms_of_service_link": isDefault(*cfg.SupportSettings.TermsOfServiceLink, model.SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK), "isdefault_privacy_policy_link": isDefault(*cfg.SupportSettings.PrivacyPolicyLink, model.SUPPORT_SETTINGS_DEFAULT_PRIVACY_POLICY_LINK), "isdefault_about_link": isDefault(*cfg.SupportSettings.AboutLink, model.SUPPORT_SETTINGS_DEFAULT_ABOUT_LINK), @@ -608,7 +608,7 @@ func (ts *TelemetryService) trackConfig() { "enable_ask_community_link": *cfg.SupportSettings.EnableAskCommunityLink, }) - ts.sendTelemetry(TRACK_CONFIG_LDAP, map[string]interface{}{ + ts.sendTelemetry(TrackConfigLDAP, map[string]interface{}{ "enable": *cfg.LdapSettings.Enable, "enable_sync": *cfg.LdapSettings.EnableSync, "enable_admin_filter": *cfg.LdapSettings.EnableAdminFilter, @@ -639,18 +639,18 @@ func (ts *TelemetryService) trackConfig() { "isnotempty_private_key": !isDefault(*cfg.LdapSettings.PrivateKeyFile, ""), }) - ts.sendTelemetry(TRACK_CONFIG_COMPLIANCE, map[string]interface{}{ + ts.sendTelemetry(TrackConfigCompliance, map[string]interface{}{ "enable": *cfg.ComplianceSettings.Enable, "enable_daily": *cfg.ComplianceSettings.EnableDaily, }) - ts.sendTelemetry(TRACK_CONFIG_LOCALIZATION, map[string]interface{}{ + ts.sendTelemetry(TrackConfigLocalization, map[string]interface{}{ "default_server_locale": *cfg.LocalizationSettings.DefaultServerLocale, "default_client_locale": *cfg.LocalizationSettings.DefaultClientLocale, "available_locales": *cfg.LocalizationSettings.AvailableLocales, }) - ts.sendTelemetry(TRACK_CONFIG_SAML, map[string]interface{}{ + ts.sendTelemetry(TrackConfigSAML, map[string]interface{}{ "enable": *cfg.SamlSettings.Enable, "enable_sync_with_ldap": *cfg.SamlSettings.EnableSyncWithLdap, "enable_sync_with_ldap_include_auth": *cfg.SamlSettings.EnableSyncWithLdapIncludeAuth, @@ -679,7 +679,7 @@ func (ts *TelemetryService) trackConfig() { "isdefault_login_button_text_color": isDefault(*cfg.SamlSettings.LoginButtonTextColor, ""), }) - ts.sendTelemetry(TRACK_CONFIG_CLUSTER, map[string]interface{}{ + ts.sendTelemetry(TrackConfigCluster, map[string]interface{}{ "enable": *cfg.ClusterSettings.Enable, "network_interface": isDefault(*cfg.ClusterSettings.NetworkInterface, ""), "bind_address": isDefault(*cfg.ClusterSettings.BindAddress, ""), @@ -690,18 +690,18 @@ func (ts *TelemetryService) trackConfig() { "read_only_config": *cfg.ClusterSettings.ReadOnlyConfig, }) - ts.sendTelemetry(TRACK_CONFIG_METRICS, map[string]interface{}{ + ts.sendTelemetry(TrackConfigMetrics, map[string]interface{}{ "enable": *cfg.MetricsSettings.Enable, "block_profile_rate": *cfg.MetricsSettings.BlockProfileRate, }) - ts.sendTelemetry(TRACK_CONFIG_NATIVEAPP, map[string]interface{}{ + ts.sendTelemetry(TrackConfigNativeApp, map[string]interface{}{ "isdefault_app_download_link": isDefault(*cfg.NativeAppSettings.AppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_APP_DOWNLOAD_LINK), "isdefault_android_app_download_link": isDefault(*cfg.NativeAppSettings.AndroidAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_ANDROID_APP_DOWNLOAD_LINK), "isdefault_iosapp_download_link": isDefault(*cfg.NativeAppSettings.IosAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_IOS_APP_DOWNLOAD_LINK), }) - ts.sendTelemetry(TRACK_CONFIG_EXPERIMENTAL, map[string]interface{}{ + ts.sendTelemetry(TrackConfigExperimental, map[string]interface{}{ "client_side_cert_enable": *cfg.ExperimentalSettings.ClientSideCertEnable, "isdefault_client_side_cert_check": isDefault(*cfg.ExperimentalSettings.ClientSideCertCheck, model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH), "link_metadata_timeout_milliseconds": *cfg.ExperimentalSettings.LinkMetadataTimeoutMilliseconds, @@ -713,11 +713,11 @@ func (ts *TelemetryService) trackConfig() { "enable_shared_channels": *cfg.ExperimentalSettings.EnableSharedChannels, }) - ts.sendTelemetry(TRACK_CONFIG_ANALYTICS, map[string]interface{}{ + ts.sendTelemetry(TrackConfigAnalytics, map[string]interface{}{ "isdefault_max_users_for_statistics": isDefault(*cfg.AnalyticsSettings.MaxUsersForStatistics, model.ANALYTICS_SETTINGS_DEFAULT_MAX_USERS_FOR_STATISTICS), }) - ts.sendTelemetry(TRACK_CONFIG_ANNOUNCEMENT, map[string]interface{}{ + ts.sendTelemetry(TrackConfigAnnouncement, map[string]interface{}{ "enable_banner": *cfg.AnnouncementSettings.EnableBanner, "isdefault_banner_color": isDefault(*cfg.AnnouncementSettings.BannerColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_COLOR), "isdefault_banner_text_color": isDefault(*cfg.AnnouncementSettings.BannerTextColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_TEXT_COLOR), @@ -726,7 +726,7 @@ func (ts *TelemetryService) trackConfig() { "user_notices_enabled": *cfg.AnnouncementSettings.UserNoticesEnabled, }) - ts.sendTelemetry(TRACK_CONFIG_ELASTICSEARCH, map[string]interface{}{ + ts.sendTelemetry(TrackConfigElasticsearch, map[string]interface{}{ "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionUrl, model.ELASTICSEARCH_SETTINGS_DEFAULT_CONNECTION_URL), "isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ELASTICSEARCH_SETTINGS_DEFAULT_USERNAME), "isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ELASTICSEARCH_SETTINGS_DEFAULT_PASSWORD), @@ -750,7 +750,7 @@ func (ts *TelemetryService) trackConfig() { ts.trackPluginConfig(cfg, model.PLUGIN_SETTINGS_DEFAULT_MARKETPLACE_URL) - ts.sendTelemetry(TRACK_CONFIG_DATA_RETENTION, map[string]interface{}{ + ts.sendTelemetry(TrackConfigDataRetention, map[string]interface{}{ "enable_message_deletion": *cfg.DataRetentionSettings.EnableMessageDeletion, "enable_file_deletion": *cfg.DataRetentionSettings.EnableFileDeletion, "message_retention_days": *cfg.DataRetentionSettings.MessageRetentionDays, @@ -758,7 +758,7 @@ func (ts *TelemetryService) trackConfig() { "deletion_job_start_time": *cfg.DataRetentionSettings.DeletionJobStartTime, }) - ts.sendTelemetry(TRACK_CONFIG_MESSAGE_EXPORT, map[string]interface{}{ + ts.sendTelemetry(TrackConfigMessageExport, map[string]interface{}{ "enable_message_export": *cfg.MessageExportSettings.EnableExport, "export_format": *cfg.MessageExportSettings.ExportFormat, "daily_run_time": *cfg.MessageExportSettings.DailyRunTime, @@ -772,26 +772,26 @@ func (ts *TelemetryService) trackConfig() { "download_export_results": *cfg.MessageExportSettings.DownloadExportResults, }) - ts.sendTelemetry(TRACK_CONFIG_DISPLAY, map[string]interface{}{ + ts.sendTelemetry(TrackConfigDisplay, map[string]interface{}{ "experimental_timezone": *cfg.DisplaySettings.ExperimentalTimezone, "isdefault_custom_url_schemes": len(cfg.DisplaySettings.CustomUrlSchemes) != 0, }) - ts.sendTelemetry(TRACK_CONFIG_GUEST_ACCOUNTS, map[string]interface{}{ + ts.sendTelemetry(TrackConfigGuestAccounts, map[string]interface{}{ "enable": *cfg.GuestAccountsSettings.Enable, "allow_email_accounts": *cfg.GuestAccountsSettings.AllowEmailAccounts, "enforce_multifactor_authentication": *cfg.GuestAccountsSettings.EnforceMultifactorAuthentication, "isdefault_restrict_creation_to_domains": isDefault(*cfg.GuestAccountsSettings.RestrictCreationToDomains, ""), }) - ts.sendTelemetry(TRACK_CONFIG_IMAGE_PROXY, map[string]interface{}{ + ts.sendTelemetry(TrackConfigImageProxy, map[string]interface{}{ "enable": *cfg.ImageProxySettings.Enable, "image_proxy_type": *cfg.ImageProxySettings.ImageProxyType, "isdefault_remote_image_proxy_url": isDefault(*cfg.ImageProxySettings.RemoteImageProxyURL, ""), "isdefault_remote_image_proxy_options": isDefault(*cfg.ImageProxySettings.RemoteImageProxyOptions, ""), }) - ts.sendTelemetry(TRACK_CONFIG_BLEVE, map[string]interface{}{ + ts.sendTelemetry(TrackConfigBleve, map[string]interface{}{ "enable_indexing": *cfg.BleveSettings.EnableIndexing, "enable_searching": *cfg.BleveSettings.EnableSearching, "enable_autocomplete": *cfg.BleveSettings.EnableAutocomplete, @@ -816,7 +816,7 @@ func (ts *TelemetryService) trackLicense() { data["feature_"+featureName] = featureValue } - ts.sendTelemetry(TRACK_LICENSE, data) + ts.sendTelemetry(TrackLicense, data) } } @@ -871,7 +871,7 @@ func (ts *TelemetryService) trackPlugins() { totalDisabledCount = -1 // -1 to indicate disabled or error } - ts.sendTelemetry(TRACK_PLUGINS, map[string]interface{}{ + ts.sendTelemetry(TrackPlugins, map[string]interface{}{ "enabled_plugins": totalEnabledCount, "enabled_webapp_plugins": webappEnabledCount, "enabled_backend_plugins": backendEnabledCount, @@ -889,7 +889,7 @@ func (ts *TelemetryService) trackServer() { "version": model.CurrentVersion, "database_type": *ts.srv.Config().SqlSettings.DriverName, "operating_system": runtime.GOOS, - "installation_type": os.Getenv(ENV_VAR_INSTALL_TYPE), + "installation_type": os.Getenv(EnvVarInstallType), } if scr, err := ts.dbStore.User().AnalyticsGetSystemAdminCount(); err == nil { @@ -900,7 +900,7 @@ func (ts *TelemetryService) trackServer() { data["database_version"] = scr } - ts.sendTelemetry(TRACK_SERVER, data) + ts.sendTelemetry(TrackServer, data) } func (ts *TelemetryService) trackPermissions() { @@ -914,7 +914,7 @@ func (ts *TelemetryService) trackPermissions() { phase2Complete = true } - ts.sendTelemetry(TRACK_PERMISSIONS_GENERAL, map[string]interface{}{ + ts.sendTelemetry(TrackPermissionsGeneral, map[string]interface{}{ "phase_1_migration_complete": phase1Complete, "phase_2_migration_complete": phase2Complete, }) @@ -992,7 +992,7 @@ func (ts *TelemetryService) trackPermissions() { systemReadOnlyAdminCount = 0 } - ts.sendTelemetry(TRACK_PERMISSIONS_SYSTEM_SCHEME, map[string]interface{}{ + ts.sendTelemetry(TrackPermissionsSystemScheme, map[string]interface{}{ "system_admin_permissions": systemAdminPermissions, "system_user_permissions": systemUserPermissions, "system_manager_permissions": systemManagerPermissions, @@ -1046,7 +1046,7 @@ func (ts *TelemetryService) trackPermissions() { count, _ := ts.dbStore.Team().AnalyticsGetTeamCountForScheme(scheme.Id) - ts.sendTelemetry(TRACK_PERMISSIONS_TEAM_SCHEMES, map[string]interface{}{ + ts.sendTelemetry(TrackPermissionsTeamSchemes, map[string]interface{}{ "scheme_id": scheme.Id, "team_admin_permissions": teamAdminPermissions, "team_user_permissions": teamUserPermissions, @@ -1069,7 +1069,7 @@ func (ts *TelemetryService) trackElasticsearch() { } } - ts.sendTelemetry(TRACK_ELASTICSEARCH, data) + ts.sendTelemetry(TrackElasticsearch, data) } func (ts *TelemetryService) trackGroups() { @@ -1113,7 +1113,7 @@ func (ts *TelemetryService) trackGroups() { mlog.Error(err.Error()) } - ts.sendTelemetry(TRACK_GROUPS, map[string]interface{}{ + ts.sendTelemetry(TrackGroups, map[string]interface{}{ "group_count": groupCount, "group_team_count": groupTeamCount, "group_channel_count": groupChannelCount, @@ -1168,7 +1168,7 @@ func (ts *TelemetryService) trackChannelModeration() { mlog.Error(err.Error()) } - ts.sendTelemetry(TRACK_CHANNEL_MODERATION, map[string]interface{}{ + ts.sendTelemetry(TrackChannelModeration, map[string]interface{}{ "channel_scheme_count": channelSchemeCount, "create_post_user_disabled_count": createPostUser, @@ -1190,7 +1190,7 @@ func (ts *TelemetryService) initRudder(endpoint string, rudderKey string) { config.Logger = rudder.StdLogger(ts.log.StdLog(mlog.String("source", "rudder"))) config.Endpoint = endpoint // For testing - if endpoint != RUDDER_DATAPLANE_URL { + if endpoint != RudderDataplaneURL { config.Verbose = true config.BatchSize = 1 } @@ -1252,7 +1252,7 @@ func (ts *TelemetryService) trackWarnMetrics() { for key, value := range systemDataList { if strings.HasPrefix(key, model.WARN_METRIC_STATUS_STORE_PREFIX) { if _, ok := model.WarnMetricsTable[key]; ok { - ts.sendTelemetry(TRACK_WARN_METRICS, map[string]interface{}{ + ts.sendTelemetry(TrackWarnMetrics, map[string]interface{}{ key: value != "false", }) } @@ -1336,7 +1336,7 @@ func (ts *TelemetryService) trackPluginConfig(cfg *model.Config, marketplaceURL } } - ts.sendTelemetry(TRACK_CONFIG_PLUGIN, pluginConfigData) + ts.sendTelemetry(TrackConfigPlugin, pluginConfigData) } func (ts *TelemetryService) getAllMarketplaceplugins(marketplaceURL string) ([]*model.BaseMarketplacePlugin, error) { diff --git a/services/telemetry/telemetry_test.go b/services/telemetry/telemetry_test.go index 865282d7d1..d299c25b61 100644 --- a/services/telemetry/telemetry_test.go +++ b/services/telemetry/telemetry_test.go @@ -267,7 +267,7 @@ func TestRudderTelemetry(t *testing.T) { telemetryService := New(serverIfaceMock, storeMock, searchengine.NewBroker(cfg, nil), mlog.NewLogger(&mlog.LoggerConfiguration{})) telemetryService.TelemetryID = telemetryID telemetryService.rudderClient = nil - telemetryService.initRudder(server.URL, RUDDER_KEY) + telemetryService.initRudder(server.URL, RudderKey) assertPayload := func(t *testing.T, actual payload, event string, properties map[string]interface{}) { t.Helper() @@ -346,32 +346,32 @@ func TestRudderTelemetry(t *testing.T) { collectInfo(&info) for _, item := range []string{ - TRACK_CONFIG_SERVICE, - TRACK_CONFIG_TEAM, - TRACK_CONFIG_SQL, - TRACK_CONFIG_LOG, - TRACK_CONFIG_NOTIFICATION_LOG, - TRACK_CONFIG_FILE, - TRACK_CONFIG_RATE, - TRACK_CONFIG_EMAIL, - TRACK_CONFIG_PRIVACY, - TRACK_CONFIG_OAUTH, - TRACK_CONFIG_LDAP, - TRACK_CONFIG_COMPLIANCE, - TRACK_CONFIG_LOCALIZATION, - TRACK_CONFIG_SAML, - TRACK_CONFIG_PASSWORD, - TRACK_CONFIG_CLUSTER, - TRACK_CONFIG_METRICS, - TRACK_CONFIG_SUPPORT, - TRACK_CONFIG_NATIVEAPP, - TRACK_CONFIG_EXPERIMENTAL, - TRACK_CONFIG_ANALYTICS, - TRACK_CONFIG_PLUGIN, - TRACK_ACTIVITY, - TRACK_SERVER, - TRACK_CONFIG_MESSAGE_EXPORT, - TRACK_PLUGINS, + TrackConfigService, + TrackConfigTeam, + TrackConfigSQL, + TrackConfigLog, + TrackConfigNotificationLog, + TrackConfigFile, + TrackConfigRate, + TrackConfigEmail, + TrackConfigPrivacy, + TrackConfigOauth, + TrackConfigLDAP, + TrackConfigCompliance, + TrackConfigLocalization, + TrackConfigSAML, + TrackConfigPassword, + TrackConfigCluster, + TrackConfigMetrics, + TrackConfigSupport, + TrackConfigNativeApp, + TrackConfigExperimental, + TrackConfigAnalytics, + TrackConfigPlugin, + TrackActivity, + TrackServer, + TrackConfigMessageExport, + TrackPlugins, } { require.Contains(t, info, item) } @@ -388,32 +388,32 @@ func TestRudderTelemetry(t *testing.T) { collectInfo(&info) for _, item := range []string{ - TRACK_CONFIG_SERVICE, - TRACK_CONFIG_TEAM, - TRACK_CONFIG_SQL, - TRACK_CONFIG_LOG, - TRACK_CONFIG_NOTIFICATION_LOG, - TRACK_CONFIG_FILE, - TRACK_CONFIG_RATE, - TRACK_CONFIG_EMAIL, - TRACK_CONFIG_PRIVACY, - TRACK_CONFIG_OAUTH, - TRACK_CONFIG_LDAP, - TRACK_CONFIG_COMPLIANCE, - TRACK_CONFIG_LOCALIZATION, - TRACK_CONFIG_SAML, - TRACK_CONFIG_PASSWORD, - TRACK_CONFIG_CLUSTER, - TRACK_CONFIG_METRICS, - TRACK_CONFIG_SUPPORT, - TRACK_CONFIG_NATIVEAPP, - TRACK_CONFIG_EXPERIMENTAL, - TRACK_CONFIG_ANALYTICS, - TRACK_CONFIG_PLUGIN, - TRACK_ACTIVITY, - TRACK_SERVER, - TRACK_CONFIG_MESSAGE_EXPORT, - TRACK_PLUGINS, + TrackConfigService, + TrackConfigTeam, + TrackConfigSQL, + TrackConfigLog, + TrackConfigNotificationLog, + TrackConfigFile, + TrackConfigRate, + TrackConfigEmail, + TrackConfigPrivacy, + TrackConfigOauth, + TrackConfigLDAP, + TrackConfigCompliance, + TrackConfigLocalization, + TrackConfigSAML, + TrackConfigPassword, + TrackConfigCluster, + TrackConfigMetrics, + TrackConfigSupport, + TrackConfigNativeApp, + TrackConfigExperimental, + TrackConfigAnalytics, + TrackConfigPlugin, + TrackActivity, + TrackServer, + TrackConfigMessageExport, + TrackPlugins, } { require.Contains(t, info, item) } @@ -425,7 +425,7 @@ func TestRudderTelemetry(t *testing.T) { collectBatches(&batches) for _, b := range batches { - if b.Event == TRACK_CONFIG_PLUGIN { + if b.Event == TrackConfigPlugin { assert.Contains(t, b.Properties, "enable_testplugin") assert.Contains(t, b.Properties, "version_testplugin") @@ -443,7 +443,7 @@ func TestRudderTelemetry(t *testing.T) { collectBatches(&batches) for _, b := range batches { - if b.Event == TRACK_CONFIG_PLUGIN { + if b.Event == TrackConfigPlugin { assert.NotContains(t, b.Properties, "enable_testplugin") assert.NotContains(t, b.Properties, "version_testplugin") @@ -455,7 +455,7 @@ func TestRudderTelemetry(t *testing.T) { }) t.Run("SendDailyTelemetryNoRudderKey", func(t *testing.T) { - if !strings.Contains(RUDDER_KEY, "placeholder") { + if !strings.Contains(RudderKey, "placeholder") { t.Skipf("Skipping telemetry on production builds") } telemetryService.sendDailyTelemetry(false) @@ -469,7 +469,7 @@ func TestRudderTelemetry(t *testing.T) { }) t.Run("SendDailyTelemetryDisabled", func(t *testing.T) { - if !strings.Contains(RUDDER_KEY, "placeholder") { + if !strings.Contains(RudderKey, "placeholder") { t.Skipf("Skipping telemetry on production builds") } *cfg.LogSettings.EnableDiagnostics = false @@ -488,39 +488,39 @@ func TestRudderTelemetry(t *testing.T) { }) t.Run("TestInstallationType", func(t *testing.T) { - os.Unsetenv(ENV_VAR_INSTALL_TYPE) + os.Unsetenv(EnvVarInstallType) telemetryService.sendDailyTelemetry(true) var batches []batch collectBatches(&batches) for _, b := range batches { - if b.Event == TRACK_SERVER { + if b.Event == TrackServer { assert.Equal(t, b.Properties["installation_type"], "") } } - os.Setenv(ENV_VAR_INSTALL_TYPE, "docker") - defer os.Unsetenv(ENV_VAR_INSTALL_TYPE) + os.Setenv(EnvVarInstallType, "docker") + defer os.Unsetenv(EnvVarInstallType) batches = []batch{} collectBatches(&batches) for _, b := range batches { - if b.Event == TRACK_SERVER { + if b.Event == TrackServer { assert.Equal(t, b.Properties["installation_type"], "docker") } } }) t.Run("RudderConfigUsesConfigForValues", func(t *testing.T) { - if !strings.Contains(RUDDER_KEY, "placeholder") { + if !strings.Contains(RudderKey, "placeholder") { t.Skipf("Skipping telemetry on production builds") } - os.Setenv("RUDDER_KEY", "abc123") - os.Setenv("RUDDER_DATAPLANE_URL", "arudderstackplace") - defer os.Unsetenv("RUDDER_KEY") - defer os.Unsetenv("RUDDER_DATAPLANE_URL") + os.Setenv("RudderKey", "abc123") + os.Setenv("RudderDataplaneURL", "arudderstackplace") + defer os.Unsetenv("RudderKey") + defer os.Unsetenv("RudderDataplaneURL") config := telemetryService.getRudderConfig() diff --git a/store/constants.go b/store/constants.go index 876cb41bce..75880dcd56 100644 --- a/store/constants.go +++ b/store/constants.go @@ -4,12 +4,12 @@ package store const ( - CHANNEL_EXISTS_ERROR = "store.sql_channel.save_channel.exists.app_error" + ChannelExistsError = "store.sql_channel.save_channel.exists.app_error" - USER_SEARCH_OPTION_NAMES_ONLY = "names_only" - USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME = "names_only_no_full_name" - USER_SEARCH_OPTION_ALL_NO_FULL_NAME = "all_no_full_name" - USER_SEARCH_OPTION_ALLOW_INACTIVE = "allow_inactive" + UserSearchOptionNamesOnly = "names_only" + UserSearchOptionNamesOnlyNoFullName = "names_only_no_full_name" + UserSearchOptionAllNoFullName = "all_no_full_name" + UserSearchOptionAllowInactive = "allow_inactive" - FEATURE_TOGGLE_PREFIX = "feature_enabled_" + FeatureTogglePrefix = "feature_enabled_" ) diff --git a/store/layer_generators/main.go b/store/layer_generators/main.go index 72b6af7762..bb78ed9241 100644 --- a/store/layer_generators/main.go +++ b/store/layer_generators/main.go @@ -19,12 +19,12 @@ import ( ) const ( - OPEN_TRACING_PARAMS_MARKER = "@openTracingParams" - ERROR_TYPE = "error" + OpenTracingParamsMarker = "@openTracingParams" + ErrorType = "error" ) func isError(typeName string) bool { - return strings.Contains(typeName, ERROR_TYPE) + return strings.Contains(typeName, ErrorType) } func main() { @@ -109,8 +109,8 @@ func extractMethodMetadata(method *ast.Field, src []byte) methodData { if method.Doc != nil { for _, comment := range method.Doc.List { s := comment.Text - if idx := strings.Index(s, OPEN_TRACING_PARAMS_MARKER); idx != -1 { - for _, p := range strings.Split(s[idx+len(OPEN_TRACING_PARAMS_MARKER):], ",") { + if idx := strings.Index(s, OpenTracingParamsMarker); idx != -1 { + for _, p := range strings.Split(s[idx+len(OpenTracingParamsMarker):], ",") { paramsToTrace[strings.TrimSpace(p)] = true } } @@ -138,7 +138,7 @@ func extractMethodMetadata(method *ast.Field, src []byte) methodData { } } if !found { - log.Fatalf("Unable to find a parameter called '%s' (method '%s') that is mentioned in the '%s' comment. Maybe it was renamed?", paramName, method.Names[0].Name, OPEN_TRACING_PARAMS_MARKER) + log.Fatalf("Unable to find a parameter called '%s' (method '%s') that is mentioned in the '%s' comment. Maybe it was renamed?", paramName, method.Names[0].Name, OpenTracingParamsMarker) } } } diff --git a/store/localcachelayer/channel_layer.go b/store/localcachelayer/channel_layer.go index efa9e6de1a..f2bfdde81d 100644 --- a/store/localcachelayer/channel_layer.go +++ b/store/localcachelayer/channel_layer.go @@ -14,7 +14,7 @@ type LocalCacheChannelStore struct { } func (s *LocalCacheChannelStore) handleClusterInvalidateChannelMemberCounts(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.channelMemberCountsCache.Purge() } else { s.rootStore.channelMemberCountsCache.Remove(msg.Data) @@ -22,7 +22,7 @@ func (s *LocalCacheChannelStore) handleClusterInvalidateChannelMemberCounts(msg } func (s *LocalCacheChannelStore) handleClusterInvalidateChannelPinnedPostCount(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.channelPinnedPostCountsCache.Purge() } else { s.rootStore.channelPinnedPostCountsCache.Remove(msg.Data) @@ -30,7 +30,7 @@ func (s *LocalCacheChannelStore) handleClusterInvalidateChannelPinnedPostCount(m } func (s *LocalCacheChannelStore) handleClusterInvalidateChannelGuestCounts(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.channelGuestCountCache.Purge() } else { s.rootStore.channelGuestCountCache.Remove(msg.Data) @@ -38,7 +38,7 @@ func (s *LocalCacheChannelStore) handleClusterInvalidateChannelGuestCounts(msg * } func (s *LocalCacheChannelStore) handleClusterInvalidateChannelById(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.channelByIdCache.Purge() } else { s.rootStore.channelByIdCache.Remove(msg.Data) diff --git a/store/localcachelayer/emoji_layer.go b/store/localcachelayer/emoji_layer.go index 5c74e31f51..80eec50fe0 100644 --- a/store/localcachelayer/emoji_layer.go +++ b/store/localcachelayer/emoji_layer.go @@ -14,7 +14,7 @@ type LocalCacheEmojiStore struct { } func (es *LocalCacheEmojiStore) handleClusterInvalidateEmojiById(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { es.rootStore.emojiCacheById.Purge() } else { es.rootStore.emojiCacheById.Remove(msg.Data) @@ -22,7 +22,7 @@ func (es *LocalCacheEmojiStore) handleClusterInvalidateEmojiById(msg *model.Clus } func (es *LocalCacheEmojiStore) handleClusterInvalidateEmojiIdByName(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { es.rootStore.emojiIdCacheByName.Purge() } else { es.rootStore.emojiIdCacheByName.Remove(msg.Data) diff --git a/store/localcachelayer/file_info_layer.go b/store/localcachelayer/file_info_layer.go index a518c827bb..43d80f3b23 100644 --- a/store/localcachelayer/file_info_layer.go +++ b/store/localcachelayer/file_info_layer.go @@ -14,7 +14,7 @@ type LocalCacheFileInfoStore struct { } func (s *LocalCacheFileInfoStore) handleClusterInvalidateFileInfo(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.fileInfoCache.Purge() return } diff --git a/store/localcachelayer/layer.go b/store/localcachelayer/layer.go index e6bf1e4728..691802c588 100644 --- a/store/localcachelayer/layer.go +++ b/store/localcachelayer/layer.go @@ -14,53 +14,53 @@ import ( ) const ( - REACTION_CACHE_SIZE = 20000 - REACTION_CACHE_SEC = 30 * 60 + ReactionCacheSize = 20000 + ReactionCacheSec = 30 * 60 - ROLE_CACHE_SIZE = 20000 - ROLE_CACHE_SEC = 30 * 60 + RoleCacheSize = 20000 + RoleCacheSec = 30 * 60 - SCHEME_CACHE_SIZE = 20000 - SCHEME_CACHE_SEC = 30 * 60 + SchemeCacheSize = 20000 + SchemeCacheSec = 30 * 60 - FILE_INFO_CACHE_SIZE = 25000 - FILE_INFO_CACHE_SEC = 30 * 60 + FileInfoCacheSize = 25000 + FileInfoCacheSec = 30 * 60 - CHANNEL_GUEST_COUNT_CACHE_SIZE = model.CHANNEL_CACHE_SIZE - CHANNEL_GUEST_COUNT_CACHE_SEC = 30 * 60 + ChannelGuestCountCacheSize = model.CHANNEL_CACHE_SIZE + ChannelGuestCountCacheSec = 30 * 60 - WEBHOOK_CACHE_SIZE = 25000 - WEBHOOK_CACHE_SEC = 15 * 60 + WebhookCacheSize = 25000 + WebhookCacheSec = 15 * 60 - EMOJI_CACHE_SIZE = 5000 - EMOJI_CACHE_SEC = 30 * 60 + EmojiCacheSize = 5000 + EmojiCacheSec = 30 * 60 - CHANNEL_PINNEDPOSTS_COUNTS_CACHE_SIZE = model.CHANNEL_CACHE_SIZE - CHANNEL_PINNEDPOSTS_COUNTS_CACHE_SEC = 30 * 60 + ChannelPinnedPostsCounsCacheSize = model.CHANNEL_CACHE_SIZE + ChannelPinnedPostsCountsCacheSec = 30 * 60 - CHANNEL_MEMBERS_COUNTS_CACHE_SIZE = model.CHANNEL_CACHE_SIZE - CHANNEL_MEMBERS_COUNTS_CACHE_SEC = 30 * 60 + ChannelMembersCountsCacheSize = model.CHANNEL_CACHE_SIZE + ChannelMembersCountsCacheSec = 30 * 60 - LAST_POSTS_CACHE_SIZE = 20000 - LAST_POSTS_CACHE_SEC = 30 * 60 + LastPostsCacheSize = 20000 + LastPostsCacheSec = 30 * 60 - TERMS_OF_SERVICE_CACHE_SIZE = 20000 - TERMS_OF_SERVICE_CACHE_SEC = 30 * 60 - LAST_POST_TIME_CACHE_SIZE = 25000 - LAST_POST_TIME_CACHE_SEC = 15 * 60 + TermsOfServiceCacheSize = 20000 + TermsOfServiceCacheSec = 30 * 60 + LastPostTimeCacheSize = 25000 + LastPostTimeCacheSec = 15 * 60 - USER_PROFILE_BY_ID_CACHE_SIZE = 20000 - USER_PROFILE_BY_ID_SEC = 30 * 60 + UserProfileByIDCacheSize = 20000 + UserProfileByIDSec = 30 * 60 - PROFILES_IN_CHANNEL_CACHE_SIZE = model.CHANNEL_CACHE_SIZE - PROFILES_IN_CHANNEL_CACHE_SEC = 15 * 60 + ProfilesInChannelCacheSize = model.CHANNEL_CACHE_SIZE + PROFILES_IN_ChannelCacheSec = 15 * 60 - TEAM_CACHE_SIZE = 20000 - TEAM_CACHE_SEC = 30 * 60 + TeamCacheSize = 20000 + TeamCacheSec = 30 * 60 - CLEAR_CACHE_MESSAGE_DATA = "" + ClearCacheMessageData = "" - CHANNEL_CACHE_SEC = 15 * 60 // 15 mins + ChannelCacheSec = 15 * 60 // 15 mins ) type LocalCacheStore struct { @@ -117,9 +117,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf } // Reactions if localCacheStore.reactionCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: REACTION_CACHE_SIZE, + Size: ReactionCacheSize, Name: "Reaction", - DefaultExpiry: REACTION_CACHE_SEC * time.Second, + DefaultExpiry: ReactionCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_REACTIONS, }); err != nil { return @@ -128,9 +128,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Roles if localCacheStore.roleCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: ROLE_CACHE_SIZE, + Size: RoleCacheSize, Name: "Role", - DefaultExpiry: ROLE_CACHE_SEC * time.Second, + DefaultExpiry: RoleCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLES, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), @@ -138,9 +138,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf return } if localCacheStore.rolePermissionsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: ROLE_CACHE_SIZE, + Size: RoleCacheSize, Name: "RolePermission", - DefaultExpiry: ROLE_CACHE_SEC * time.Second, + DefaultExpiry: RoleCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_ROLE_PERMISSIONS, }); err != nil { return @@ -149,9 +149,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Schemes if localCacheStore.schemeCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: SCHEME_CACHE_SIZE, + Size: SchemeCacheSize, Name: "Scheme", - DefaultExpiry: SCHEME_CACHE_SEC * time.Second, + DefaultExpiry: SchemeCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_SCHEMES, }); err != nil { return @@ -160,9 +160,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // FileInfo if localCacheStore.fileInfoCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: FILE_INFO_CACHE_SIZE, + Size: FileInfoCacheSize, Name: "FileInfo", - DefaultExpiry: FILE_INFO_CACHE_SEC * time.Second, + DefaultExpiry: FileInfoCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_FILE_INFOS, }); err != nil { return @@ -171,9 +171,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Webhooks if localCacheStore.webhookCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: WEBHOOK_CACHE_SIZE, + Size: WebhookCacheSize, Name: "Webhook", - DefaultExpiry: WEBHOOK_CACHE_SEC * time.Second, + DefaultExpiry: WebhookCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_WEBHOOKS, }); err != nil { return @@ -182,17 +182,17 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Emojis if localCacheStore.emojiCacheById, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: EMOJI_CACHE_SIZE, + Size: EmojiCacheSize, Name: "EmojiById", - DefaultExpiry: EMOJI_CACHE_SEC * time.Second, + DefaultExpiry: EmojiCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_BY_ID, }); err != nil { return } if localCacheStore.emojiIdCacheByName, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: EMOJI_CACHE_SIZE, + Size: EmojiCacheSize, Name: "EmojiByName", - DefaultExpiry: EMOJI_CACHE_SEC * time.Second, + DefaultExpiry: EmojiCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_EMOJIS_ID_BY_NAME, }); err != nil { return @@ -201,25 +201,25 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Channels if localCacheStore.channelPinnedPostCountsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: CHANNEL_PINNEDPOSTS_COUNTS_CACHE_SIZE, + Size: ChannelPinnedPostsCounsCacheSize, Name: "ChannelPinnedPostsCounts", - DefaultExpiry: CHANNEL_PINNEDPOSTS_COUNTS_CACHE_SEC * time.Second, + DefaultExpiry: ChannelPinnedPostsCountsCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_PINNEDPOSTS_COUNTS, }); err != nil { return } if localCacheStore.channelMemberCountsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: CHANNEL_MEMBERS_COUNTS_CACHE_SIZE, + Size: ChannelMembersCountsCacheSize, Name: "ChannelMemberCounts", - DefaultExpiry: CHANNEL_MEMBERS_COUNTS_CACHE_SEC * time.Second, + DefaultExpiry: ChannelMembersCountsCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_MEMBER_COUNTS, }); err != nil { return } if localCacheStore.channelGuestCountCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: CHANNEL_GUEST_COUNT_CACHE_SIZE, + Size: ChannelGuestCountCacheSize, Name: "ChannelGuestsCount", - DefaultExpiry: CHANNEL_GUEST_COUNT_CACHE_SEC * time.Second, + DefaultExpiry: ChannelGuestCountCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL_GUEST_COUNT, }); err != nil { return @@ -227,7 +227,7 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf if localCacheStore.channelByIdCache, err = cacheProvider.NewCache(&cache.CacheOptions{ Size: model.CHANNEL_CACHE_SIZE, Name: "channelById", - DefaultExpiry: CHANNEL_CACHE_SEC * time.Second, + DefaultExpiry: ChannelCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_CHANNEL, }); err != nil { return @@ -236,17 +236,17 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Posts if localCacheStore.postLastPostsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: LAST_POSTS_CACHE_SIZE, + Size: LastPostsCacheSize, Name: "LastPost", - DefaultExpiry: LAST_POSTS_CACHE_SEC * time.Second, + DefaultExpiry: LastPostsCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POSTS, }); err != nil { return } if localCacheStore.lastPostTimeCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: LAST_POST_TIME_CACHE_SIZE, + Size: LastPostTimeCacheSize, Name: "LastPostTime", - DefaultExpiry: LAST_POST_TIME_CACHE_SEC * time.Second, + DefaultExpiry: LastPostTimeCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_LAST_POST_TIME, }); err != nil { return @@ -255,9 +255,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // TOS if localCacheStore.termsOfServiceCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: TERMS_OF_SERVICE_CACHE_SIZE, + Size: TermsOfServiceCacheSize, Name: "TermsOfService", - DefaultExpiry: TERMS_OF_SERVICE_CACHE_SEC * time.Second, + DefaultExpiry: TermsOfServiceCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TERMS_OF_SERVICE, }); err != nil { return @@ -266,9 +266,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Users if localCacheStore.userProfileByIdsCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: USER_PROFILE_BY_ID_CACHE_SIZE, + Size: UserProfileByIDCacheSize, Name: "UserProfileByIds", - DefaultExpiry: USER_PROFILE_BY_ID_SEC * time.Second, + DefaultExpiry: UserProfileByIDSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_BY_IDS, Striped: true, StripedBuckets: maxInt(runtime.NumCPU()-1, 1), @@ -276,9 +276,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf return } if localCacheStore.profilesInChannelCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: PROFILES_IN_CHANNEL_CACHE_SIZE, + Size: ProfilesInChannelCacheSize, Name: "ProfilesInChannel", - DefaultExpiry: PROFILES_IN_CHANNEL_CACHE_SEC * time.Second, + DefaultExpiry: PROFILES_IN_ChannelCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_PROFILE_IN_CHANNEL, }); err != nil { return @@ -287,9 +287,9 @@ func NewLocalCacheLayer(baseStore store.Store, metrics einterfaces.MetricsInterf // Teams if localCacheStore.teamAllTeamIdsForUserCache, err = cacheProvider.NewCache(&cache.CacheOptions{ - Size: TEAM_CACHE_SIZE, + Size: TeamCacheSize, Name: "Team", - DefaultExpiry: TEAM_CACHE_SEC * time.Second, + DefaultExpiry: TeamCacheSec * time.Second, InvalidateClusterEvent: model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_TEAMS, }); err != nil { return @@ -411,7 +411,7 @@ func (s *LocalCacheStore) doClearCacheCluster(cache cache.Cache) { msg := &model.ClusterMessage{ Event: cache.GetInvalidateClusterEvent(), SendType: model.CLUSTER_SEND_BEST_EFFORT, - Data: CLEAR_CACHE_MESSAGE_DATA, + Data: ClearCacheMessageData, } s.cluster.SendClusterMessage(msg) } diff --git a/store/localcachelayer/post_layer.go b/store/localcachelayer/post_layer.go index 47a9fdea0f..b0c4b16752 100644 --- a/store/localcachelayer/post_layer.go +++ b/store/localcachelayer/post_layer.go @@ -19,7 +19,7 @@ type LocalCachePostStore struct { } func (s *LocalCachePostStore) handleClusterInvalidateLastPostTime(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.lastPostTimeCache.Purge() } else { s.rootStore.lastPostTimeCache.Remove(msg.Data) @@ -27,7 +27,7 @@ func (s *LocalCachePostStore) handleClusterInvalidateLastPostTime(msg *model.Clu } func (s *LocalCachePostStore) handleClusterInvalidateLastPosts(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.postLastPostsCache.Purge() } else { s.rootStore.postLastPostsCache.Remove(msg.Data) diff --git a/store/localcachelayer/reaction_layer.go b/store/localcachelayer/reaction_layer.go index 6a0f914996..795112e2d8 100644 --- a/store/localcachelayer/reaction_layer.go +++ b/store/localcachelayer/reaction_layer.go @@ -14,7 +14,7 @@ type LocalCacheReactionStore struct { } func (s *LocalCacheReactionStore) handleClusterInvalidateReaction(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.reactionCache.Purge() } else { s.rootStore.reactionCache.Remove(msg.Data) diff --git a/store/localcachelayer/role_layer.go b/store/localcachelayer/role_layer.go index bc047d5a66..b3ac2dc146 100644 --- a/store/localcachelayer/role_layer.go +++ b/store/localcachelayer/role_layer.go @@ -17,7 +17,7 @@ type LocalCacheRoleStore struct { } func (s *LocalCacheRoleStore) handleClusterInvalidateRole(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.roleCache.Purge() } else { s.rootStore.roleCache.Remove(msg.Data) @@ -25,7 +25,7 @@ func (s *LocalCacheRoleStore) handleClusterInvalidateRole(msg *model.ClusterMess } func (s *LocalCacheRoleStore) handleClusterInvalidateRolePermissions(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.rolePermissionsCache.Purge() } else { s.rootStore.rolePermissionsCache.Remove(msg.Data) diff --git a/store/localcachelayer/scheme_layer.go b/store/localcachelayer/scheme_layer.go index f9a5de8362..cfee4c0dfc 100644 --- a/store/localcachelayer/scheme_layer.go +++ b/store/localcachelayer/scheme_layer.go @@ -14,7 +14,7 @@ type LocalCacheSchemeStore struct { } func (s *LocalCacheSchemeStore) handleClusterInvalidateScheme(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.schemeCache.Purge() } else { s.rootStore.schemeCache.Remove(msg.Data) diff --git a/store/localcachelayer/team_layer.go b/store/localcachelayer/team_layer.go index 94a72e8131..25de28eb51 100644 --- a/store/localcachelayer/team_layer.go +++ b/store/localcachelayer/team_layer.go @@ -14,7 +14,7 @@ type LocalCacheTeamStore struct { } func (s *LocalCacheTeamStore) handleClusterInvalidateTeam(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.teamAllTeamIdsForUserCache.Purge() } else { s.rootStore.teamAllTeamIdsForUserCache.Remove(msg.Data) diff --git a/store/localcachelayer/terms_of_service_layer.go b/store/localcachelayer/terms_of_service_layer.go index f5bbcbbc67..e688ab5b77 100644 --- a/store/localcachelayer/terms_of_service_layer.go +++ b/store/localcachelayer/terms_of_service_layer.go @@ -9,7 +9,7 @@ import ( ) const ( - LATEST_KEY = "latest" + LatestKey = "latest" ) type LocalCacheTermsOfServiceStore struct { @@ -18,7 +18,7 @@ type LocalCacheTermsOfServiceStore struct { } func (s *LocalCacheTermsOfServiceStore) handleClusterInvalidateTermsOfService(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.termsOfServiceCache.Purge() } else { s.rootStore.termsOfServiceCache.Remove(msg.Data) @@ -38,7 +38,7 @@ func (s LocalCacheTermsOfServiceStore) Save(termsOfService *model.TermsOfService if err == nil { s.rootStore.doStandardAddToCache(s.rootStore.termsOfServiceCache, tos.Id, tos) - s.rootStore.doInvalidateCacheCluster(s.rootStore.termsOfServiceCache, LATEST_KEY) + s.rootStore.doInvalidateCacheCluster(s.rootStore.termsOfServiceCache, LatestKey) } return tos, err } @@ -47,7 +47,7 @@ func (s LocalCacheTermsOfServiceStore) GetLatest(allowFromCache bool) (*model.Te if allowFromCache { if len, err := s.rootStore.termsOfServiceCache.Len(); err == nil && len != 0 { var cacheItem *model.TermsOfService - if err := s.rootStore.doStandardReadCache(s.rootStore.termsOfServiceCache, LATEST_KEY, &cacheItem); err == nil { + if err := s.rootStore.doStandardReadCache(s.rootStore.termsOfServiceCache, LatestKey, &cacheItem); err == nil { return cacheItem, nil } } @@ -57,7 +57,7 @@ func (s LocalCacheTermsOfServiceStore) GetLatest(allowFromCache bool) (*model.Te if allowFromCache && err == nil { s.rootStore.doStandardAddToCache(s.rootStore.termsOfServiceCache, termsOfService.Id, termsOfService) - s.rootStore.doStandardAddToCache(s.rootStore.termsOfServiceCache, LATEST_KEY, termsOfService) + s.rootStore.doStandardAddToCache(s.rootStore.termsOfServiceCache, LatestKey, termsOfService) } return termsOfService, err diff --git a/store/localcachelayer/user_layer.go b/store/localcachelayer/user_layer.go index 2f497c8ac1..ea427ca15f 100644 --- a/store/localcachelayer/user_layer.go +++ b/store/localcachelayer/user_layer.go @@ -14,7 +14,7 @@ type LocalCacheUserStore struct { } func (s *LocalCacheUserStore) handleClusterInvalidateScheme(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.userProfileByIdsCache.Purge() } else { s.rootStore.userProfileByIdsCache.Remove(msg.Data) @@ -22,7 +22,7 @@ func (s *LocalCacheUserStore) handleClusterInvalidateScheme(msg *model.ClusterMe } func (s *LocalCacheUserStore) handleClusterInvalidateProfilesInChannel(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.profilesInChannelCache.Purge() } else { s.rootStore.profilesInChannelCache.Remove(msg.Data) diff --git a/store/localcachelayer/webhook_layer.go b/store/localcachelayer/webhook_layer.go index a2863b09c0..4c895c54af 100644 --- a/store/localcachelayer/webhook_layer.go +++ b/store/localcachelayer/webhook_layer.go @@ -14,7 +14,7 @@ type LocalCacheWebhookStore struct { } func (s *LocalCacheWebhookStore) handleClusterInvalidateWebhook(msg *model.ClusterMessage) { - if msg.Data == CLEAR_CACHE_MESSAGE_DATA { + if msg.Data == ClearCacheMessageData { s.rootStore.webhookCache.Purge() } else { s.rootStore.webhookCache.Remove(msg.Data) diff --git a/store/searchlayer/stop_word.go b/store/searchlayer/stop_word.go index bbaf1c3572..12bcc6e68d 100644 --- a/store/searchlayer/stop_word.go +++ b/store/searchlayer/stop_word.go @@ -3,5 +3,5 @@ package searchlayer -var MYSQL_STOP_WORDS = []string{"a", "about", "an", "are", "as", "at", "be", "by", "com", "de", "en", "for", "from", "how", "i", "in", "is", "it", "la", "of", +var MySQLStopWords = []string{"a", "about", "an", "are", "as", "at", "be", "by", "com", "de", "en", "for", "from", "how", "i", "in", "is", "it", "la", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "und", "the", "www"} diff --git a/store/searchtest/channel_layer.go b/store/searchtest/channel_layer.go index bfa36554b4..cc436afab3 100644 --- a/store/searchtest/channel_layer.go +++ b/store/searchtest/channel_layer.go @@ -15,52 +15,52 @@ var searchChannelStoreTests = []searchTest{ { Name: "Should be able to autocomplete a channel by name", Fn: testAutocompleteChannelByName, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to autocomplete a channel by display name", Fn: testAutocompleteChannelByDisplayName, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to autocomplete a channel by a part of its name when has parts splitted by - character", Fn: testAutocompleteChannelByNameSplittedWithDashChar, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to autocomplete a channel by a part of its name when has parts splitted by _ character", Fn: testAutocompleteChannelByNameSplittedWithUnderscoreChar, - Tags: []string{ENGINE_MYSQL, ENGINE_ELASTICSEARCH, ENGINE_BLEVE}, + Tags: []string{EngineMySql, EngineElasticSearch, EngineBleve}, }, { Name: "Should be able to autocomplete a channel by a part of its display name when has parts splitted by whitespace character", Fn: testAutocompleteChannelByDisplayNameSplittedByWhitespaces, - Tags: []string{ENGINE_MYSQL, ENGINE_ELASTICSEARCH, ENGINE_BLEVE}, + Tags: []string{EngineMySql, EngineElasticSearch, EngineBleve}, }, { Name: "Should be able to autocomplete retrieving all channels if the term is empty", Fn: testAutocompleteAllChannelsIfTermIsEmpty, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to autocomplete channels in a case insensitive manner", Fn: testSearchChannelsInCaseInsensitiveManner, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should autocomplete only returning public channels", Fn: testSearchOnlyPublicChannels, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support to autocomplete having a hyphen as the last character", Fn: testSearchShouldSupportHavingHyphenAsLastCharacter, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support to autocomplete with archived channels", Fn: testSearchShouldSupportAutocompleteWithArchivedChannels, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, } diff --git a/store/searchtest/post_layer.go b/store/searchtest/post_layer.go index 4c20ad987d..190230b713 100644 --- a/store/searchtest/post_layer.go +++ b/store/searchtest/post_layer.go @@ -16,250 +16,250 @@ var searchPostStoreTests = []searchTest{ { Name: "Should be able to search posts including results from DMs", Fn: testSearchPostsIncludingDMs, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search posts using pagination", Fn: testSearchPostsWithPagination, - Tags: []string{ENGINE_ELASTICSEARCH, ENGINE_BLEVE}, + Tags: []string{EngineElasticSearch, EngineBleve}, }, { Name: "Should return pinned and unpinned posts", Fn: testSearchReturnPinnedAndUnpinned, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search for exact phrases in quotes", Fn: testSearchExactPhraseInQuotes, - Tags: []string{ENGINE_POSTGRES, ENGINE_MYSQL, ENGINE_ELASTICSEARCH}, + Tags: []string{EnginePostgres, EngineMySql, EngineElasticSearch}, }, { Name: "Should be able to search for email addresses with or without quotes", Fn: testSearchEmailAddresses, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should be able to search when markdown underscores are applied", Fn: testSearchMarkdownUnderscores, - Tags: []string{ENGINE_POSTGRES, ENGINE_ELASTICSEARCH}, + Tags: []string{EnginePostgres, EngineElasticSearch}, }, { Name: "Should be able to search for non-latin words", Fn: testSearchNonLatinWords, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should be able to search for alternative spellings of words", Fn: testSearchAlternativeSpellings, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should be able to search for alternative spellings of words with and without accents", Fn: testSearchAlternativeSpellingsAccents, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should be able to search or exclude messages written by a specific user", Fn: testSearchOrExcludePostsBySpecificUser, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search or exclude messages written in a specific channel", Fn: testSearchOrExcludePostsInChannel, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search or exclude messages written in a DM or GM", Fn: testSearchOrExcludePostsInDMGM, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to filter messages written after a specific date", Fn: testFilterMessagesAfterSpecificDate, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to filter messages written before a specific date", Fn: testFilterMessagesBeforeSpecificDate, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to filter messages written on a specific date", Fn: testFilterMessagesInSpecificDate, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to exclude messages that contain a serch term", Fn: testFilterMessagesWithATerm, - Tags: []string{ENGINE_MYSQL, ENGINE_POSTGRES}, + Tags: []string{EngineMySql, EnginePostgres}, }, { Name: "Should be able to search using boolean operators", Fn: testSearchUsingBooleanOperators, - Tags: []string{ENGINE_MYSQL, ENGINE_POSTGRES, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EnginePostgres, EngineElasticSearch}, }, { Name: "Should be able to search with combined filters", Fn: testSearchUsingCombinedFilters, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to ignore stop words", Fn: testSearchIgnoringStopWords, - Tags: []string{ENGINE_MYSQL, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EngineElasticSearch}, }, { Name: "Should support search stemming", Fn: testSupportStemming, - Tags: []string{ENGINE_POSTGRES, ENGINE_ELASTICSEARCH}, + Tags: []string{EnginePostgres, EngineElasticSearch}, }, { Name: "Should support search with wildcards", Fn: testSupportWildcards, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should not support search with preceding wildcards", Fn: testNotSupportPrecedingWildcards, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should discard a wildcard if it's not placed immediately by text", Fn: testSearchDiscardWildcardAlone, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support terms with dash", Fn: testSupportTermsWithDash, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, Skip: true, }, { Name: "Should support terms with underscore", Fn: testSupportTermsWithUnderscore, - Tags: []string{ENGINE_MYSQL, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EngineElasticSearch}, }, { Name: "Should search or exclude post using hashtags", Fn: testSearchOrExcludePostsWithHashtags, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support searching for hashtags surrounded by markdown", Fn: testSearchHashtagWithMarkdown, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support searching for multiple hashtags", Fn: testSearcWithMultipleHashtags, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should support searching hashtags with dots", Fn: testSearchPostsWithDotsInHashtags, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search or exclude messages with hashtags in a case insensitive manner", Fn: testSearchHashtagCaseInsensitive, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search by hashtags with dashes", Fn: testSearchHashtagWithDash, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search by hashtags with numbers", Fn: testSearchHashtagWithNumbers, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search by hashtags with dots", Fn: testSearchHashtagWithDots, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search by hashtags with underscores", Fn: testSearchHashtagWithUnderscores, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should not return system messages", Fn: testSearchShouldExcludeSytemMessages, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search matching by mentions", Fn: testSearchShouldBeAbleToMatchByMentions, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search in deleted/archived channels", Fn: testSearchInDeletedOrArchivedChannels, - Tags: []string{ENGINE_MYSQL, ENGINE_POSTGRES}, + Tags: []string{EngineMySql, EnginePostgres}, }, { Name: "Should be able to search terms with dashes", Fn: testSearchTermsWithDashes, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, Skip: true, SkipMessage: "Not working", }, { Name: "Should be able to search terms with dots", Fn: testSearchTermsWithDots, - Tags: []string{ENGINE_POSTGRES, ENGINE_ELASTICSEARCH}, + Tags: []string{EnginePostgres, EngineElasticSearch}, }, { Name: "Should be able to search terms with underscores", Fn: testSearchTermsWithUnderscores, - Tags: []string{ENGINE_MYSQL, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EngineElasticSearch}, }, { Name: "Should be able to search posts made by bot accounts", Fn: testSearchBotAccountsPosts, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to combine stemming and wildcards", Fn: testSupportStemmingAndWildcards, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should support wildcard outside quotes", Fn: testSupportWildcardOutsideQuotes, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should support hashtags with 3 or more characters", Fn: testHashtagSearchShouldSupportThreeOrMoreCharacters, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should not support slash as character separator", Fn: testSlashShouldNotBeCharSeparator, - Tags: []string{ENGINE_MYSQL, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EngineElasticSearch}, }, { Name: "Should be able to search emails without quoting them", Fn: testSearchEmailsWithoutQuotes, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should be able to search in comments", Fn: testSupportSearchInComments, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search terms within links", Fn: testSupportSearchTermsWithinLinks, - Tags: []string{ENGINE_MYSQL, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EngineElasticSearch}, }, { Name: "Should not return links that are embedded in markdown", Fn: testShouldNotReturnLinksEmbeddedInMarkdown, - Tags: []string{ENGINE_POSTGRES, ENGINE_ELASTICSEARCH}, + Tags: []string{EnginePostgres, EngineElasticSearch}, }, } diff --git a/store/searchtest/testlib.go b/store/searchtest/testlib.go index 5d0e10f275..487d8d224d 100644 --- a/store/searchtest/testlib.go +++ b/store/searchtest/testlib.go @@ -11,11 +11,11 @@ import ( ) const ( - ENGINE_ALL = "all" - ENGINE_MYSQL = "mysql" - ENGINE_POSTGRES = "postgres" - ENGINE_ELASTICSEARCH = "elasticsearch" - ENGINE_BLEVE = "bleve" + EngineAll = "all" + EngineMySql = "mysql" + EnginePostgres = "postgres" + EngineElasticSearch = "elasticsearch" + EngineBleve = "bleve" ) type SearchTestEngine struct { @@ -35,7 +35,7 @@ type searchTest struct { func filterTestsByTag(tests []searchTest, tags ...string) []searchTest { filteredTests := []searchTest{} for _, test := range tests { - if utils.StringInSlice(ENGINE_ALL, test.Tags) { + if utils.StringInSlice(EngineAll, test.Tags) { filteredTests = append(filteredTests, test) continue } diff --git a/store/searchtest/user_layer.go b/store/searchtest/user_layer.go index 2352a524f7..b4bc6abb97 100644 --- a/store/searchtest/user_layer.go +++ b/store/searchtest/user_layer.go @@ -15,141 +15,141 @@ var searchUserStoreTests = []searchTest{ { Name: "Should retrieve all users in a channel if the search term is empty", Fn: testGetAllUsersInChannelWithEmptyTerm, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should honor channel restrictions when autocompleting users", Fn: testHonorChannelRestrictionsAutocompletingUsers, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should honor team restrictions when autocompleting users", Fn: testHonorTeamRestrictionsAutocompletingUsers, - Tags: []string{ENGINE_ELASTICSEARCH, ENGINE_BLEVE}, + Tags: []string{EngineElasticSearch, EngineBleve}, }, { Name: "Should return nothing if the user can't access the channels of a given search", Fn: testShouldReturnNothingWithoutProperAccess, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, Skip: true, SkipMessage: "Failing when the ListOfAllowedChannels property is empty", }, { Name: "Should autocomplete for user using username", Fn: testAutocompleteUserByUsername, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should autocomplete user searching by first name", Fn: testAutocompleteUserByFirstName, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should autocomplete user searching by last name", Fn: testAutocompleteUserByLastName, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should autocomplete for user using nickname", Fn: testAutocompleteUserByNickName, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should autocomplete for user using email", Fn: testAutocompleteUserByEmail, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, Skip: true, SkipMessage: "Failing for multiple different reasons in the engines", }, { Name: "Should be able not to match specific queries with mail", Fn: testShouldNotMatchSpecificQueriesEmail, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to autocomplete a user by part of its username splitted by Dot", Fn: testAutocompleteUserByUsernameWithDot, - Tags: []string{ENGINE_ELASTICSEARCH, ENGINE_BLEVE}, + Tags: []string{EngineElasticSearch, EngineBleve}, }, { Name: "Should be able to autocomplete a user by part of its username splitted by underscore", Fn: testAutocompleteUserByUsernameWithUnderscore, - Tags: []string{ENGINE_ELASTICSEARCH, ENGINE_BLEVE}, + Tags: []string{EngineElasticSearch, EngineBleve}, }, { Name: "Should be able to autocomplete a user by part of its username splitted by hyphen", Fn: testAutocompleteUserByUsernameWithHyphen, - Tags: []string{ENGINE_ELASTICSEARCH, ENGINE_BLEVE}, + Tags: []string{EngineElasticSearch, EngineBleve}, }, { Name: "Should escape the percentage character", Fn: testShouldEscapePercentageCharacter, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should escape the dash character", Fn: testShouldEscapeUnderscoreCharacter, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should be able to search inactive users", Fn: testShouldBeAbleToSearchInactiveUsers, - Tags: []string{ENGINE_MYSQL, ENGINE_POSTGRES, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EnginePostgres, EngineElasticSearch}, }, { Name: "Should be able to search filtering by role", Fn: testShouldBeAbleToSearchFilteringByRole, - Tags: []string{ENGINE_MYSQL, ENGINE_POSTGRES, ENGINE_ELASTICSEARCH}, + Tags: []string{EngineMySql, EnginePostgres, EngineElasticSearch}, }, { Name: "Should ignore leading @ when searching users", Fn: testShouldIgnoreLeadingAtSymbols, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should search users in a case insensitive manner", Fn: testSearchUsersShouldBeCaseInsensitive, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support one or two character usernames and first/last names in search", Fn: testSearchOneTwoCharUsersnameAndFirstLastNames, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support Korean characters", Fn: testShouldSupportKoreanCharacters, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support search with a hyphen at the end of the term", Fn: testSearchWithHyphenAtTheEndOfTheTerm, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support search all users in a team", Fn: testSearchUsersInTeam, - Tags: []string{ENGINE_ELASTICSEARCH}, + Tags: []string{EngineElasticSearch}, }, { Name: "Should support search users by full name", Fn: testSearchUsersByFullName, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support search all users in a team with username containing a dot", Fn: testSearchUsersInTeamUsernameWithDot, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support search all users in a team with username containing a hyphen", Fn: testSearchUsersInTeamUsernameWithHyphen, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, { Name: "Should support search all users in a team with username containing a underscore", Fn: testSearchUsersInTeamUsernameWithUnderscore, - Tags: []string{ENGINE_ALL}, + Tags: []string{EngineAll}, }, } diff --git a/store/sqlstore/channel_store.go b/store/sqlstore/channel_store.go index dd4b2fa1e5..35fb2c5036 100644 --- a/store/sqlstore/channel_store.go +++ b/store/sqlstore/channel_store.go @@ -23,13 +23,13 @@ import ( ) const ( - ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_SIZE = model.SESSION_CACHE_SIZE - ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_DURATION = 15 * time.Minute // 15 mins + AllChannelMembersForUserCacheSize = model.SESSION_CACHE_SIZE + AllChannelMembersForUserCacheDuration = 15 * time.Minute // 15 mins - ALL_CHANNEL_MEMBERS_NOTIFY_PROPS_FOR_CHANNEL_CACHE_SIZE = model.SESSION_CACHE_SIZE - ALL_CHANNEL_MEMBERS_NOTIFY_PROPS_FOR_CHANNEL_CACHE_DURATION = 30 * time.Minute // 30 mins + AllChannelMembersNotifyPropsForChannelCacheSize = model.SESSION_CACHE_SIZE + AllChannelMembersNotifyPropsForChannelCacheDuration = 30 * time.Minute // 30 mins - CHANNEL_CACHE_DURATION = 15 * time.Minute // 15 mins + ChannelCacheDuration = 15 * time.Minute // 15 mins ) type SqlChannelStore struct { @@ -335,10 +335,10 @@ type publicChannel struct { } var allChannelMembersForUserCache = cache.NewLRU(cache.LRUOptions{ - Size: ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_SIZE, + Size: AllChannelMembersForUserCacheSize, }) var allChannelMembersNotifyPropsForChannelCache = cache.NewLRU(cache.LRUOptions{ - Size: ALL_CHANNEL_MEMBERS_NOTIFY_PROPS_FOR_CHANNEL_CACHE_SIZE, + Size: AllChannelMembersNotifyPropsForChannelCacheSize, }) var channelByNameCache = cache.NewLRU(cache.LRUOptions{ Size: model.CHANNEL_CACHE_SIZE, @@ -1266,7 +1266,7 @@ func (s SqlChannelStore) GetByNames(teamId string, names []string, allowFromCach return nil, errors.Wrap(err, msg) } for _, channel := range dbChannels { - channelByNameCache.SetWithExpiry(teamId+channel.Name, channel, CHANNEL_CACHE_DURATION) + channelByNameCache.SetWithExpiry(teamId+channel.Name, channel, ChannelCacheDuration) channels = append(channels, channel) } // Not all channels are in cache. Increment aggregate miss counter. @@ -1316,7 +1316,7 @@ func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bo return nil, errors.Wrapf(err, "failed to find channel with TeamId=%s and Name=%s", teamId, name) } - channelByNameCache.SetWithExpiry(teamId+name, &channel, CHANNEL_CACHE_DURATION) + channelByNameCache.SetWithExpiry(teamId+name, &channel, ChannelCacheDuration) return &channel, nil } @@ -1360,7 +1360,7 @@ func (s SqlChannelStore) GetDeleted(teamId string, offset int, limit int, userId return channels, nil } -var CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY = ` +var ChannelMembersWithSchemeSelectQuery = ` SELECT ChannelMembers.*, TeamScheme.DefaultChannelGuestRole TeamSchemeDefaultGuestRole, @@ -1586,7 +1586,7 @@ func (s SqlChannelStore) UpdateMultipleMembers(members []*model.ChannelMember) ( // TODO: Get this out of the transaction when is possible var dbMember channelMemberWithSchemeRoles - if err := transaction.SelectOne(&dbMember, CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY+"WHERE ChannelMembers.ChannelId = :ChannelId AND ChannelMembers.UserId = :UserId", map[string]interface{}{"ChannelId": member.ChannelId, "UserId": member.UserId}); err != nil { + if err := transaction.SelectOne(&dbMember, ChannelMembersWithSchemeSelectQuery+"WHERE ChannelMembers.ChannelId = :ChannelId AND ChannelMembers.UserId = :UserId", map[string]interface{}{"ChannelId": member.ChannelId, "UserId": member.UserId}); err != nil { if err == sql.ErrNoRows { return nil, store.NewErrNotFound("ChannelMember", fmt.Sprintf("channelId=%s, userId=%s", member.ChannelId, member.UserId)) } @@ -1611,7 +1611,7 @@ func (s SqlChannelStore) UpdateMember(member *model.ChannelMember) (*model.Chann func (s SqlChannelStore) GetMembers(channelId string, offset, limit int) (*model.ChannelMembers, error) { var dbMembers channelMemberWithSchemeRolesList - _, err := s.GetReplica().Select(&dbMembers, CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY+"WHERE ChannelId = :ChannelId LIMIT :Limit OFFSET :Offset", map[string]interface{}{"ChannelId": channelId, "Limit": limit, "Offset": offset}) + _, err := s.GetReplica().Select(&dbMembers, ChannelMembersWithSchemeSelectQuery+"WHERE ChannelId = :ChannelId LIMIT :Limit OFFSET :Offset", map[string]interface{}{"ChannelId": channelId, "Limit": limit, "Offset": offset}) if err != nil { return nil, errors.Wrapf(err, "failed to get ChannelMembers with channelId=%s", channelId) } @@ -1641,7 +1641,7 @@ func (s SqlChannelStore) GetChannelMembersTimezones(channelId string) ([]model.S func (s SqlChannelStore) GetMember(channelId string, userId string) (*model.ChannelMember, error) { var dbMember channelMemberWithSchemeRoles - if err := s.GetReplica().SelectOne(&dbMember, CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY+"WHERE ChannelMembers.ChannelId = :ChannelId AND ChannelMembers.UserId = :UserId", map[string]interface{}{"ChannelId": channelId, "UserId": userId}); err != nil { + if err := s.GetReplica().SelectOne(&dbMember, ChannelMembersWithSchemeSelectQuery+"WHERE ChannelMembers.ChannelId = :ChannelId AND ChannelMembers.UserId = :UserId", map[string]interface{}{"ChannelId": channelId, "UserId": userId}); err != nil { if err == sql.ErrNoRows { return nil, store.NewErrNotFound("ChannelMember", fmt.Sprintf("channelId=%s, userId=%s", channelId, userId)) } @@ -1791,7 +1791,7 @@ func (s SqlChannelStore) GetAllChannelMembersForUser(userId string, allowFromCac ids := data.ToMapStringString() if allowFromCache { - allChannelMembersForUserCache.SetWithExpiry(cache_key, ids, ALL_CHANNEL_MEMBERS_FOR_USER_CACHE_DURATION) + allChannelMembersForUserCache.SetWithExpiry(cache_key, ids, AllChannelMembersForUserCacheDuration) } return ids, nil } @@ -1838,7 +1838,7 @@ func (s SqlChannelStore) GetAllChannelMembersNotifyPropsForChannel(channelId str props[data[i].UserId] = data[i].NotifyProps } - allChannelMembersNotifyPropsForChannelCache.SetWithExpiry(channelId, props, ALL_CHANNEL_MEMBERS_NOTIFY_PROPS_FOR_CHANNEL_CACHE_DURATION) + allChannelMembersNotifyPropsForChannelCache.SetWithExpiry(channelId, props, AllChannelMembersNotifyPropsForChannelCacheDuration) return props, nil } @@ -2363,7 +2363,7 @@ func (s SqlChannelStore) AnalyticsDeletedTypeCount(teamId string, channelType st func (s SqlChannelStore) GetMembersForUser(teamId string, userId string) (*model.ChannelMembers, error) { var dbMembers channelMemberWithSchemeRolesList - _, err := s.GetReplica().Select(&dbMembers, CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY+"WHERE ChannelMembers.UserId = :UserId AND (Teams.Id = :TeamId OR Teams.Id = '' OR Teams.Id IS NULL)", map[string]interface{}{"TeamId": teamId, "UserId": userId}) + _, err := s.GetReplica().Select(&dbMembers, ChannelMembersWithSchemeSelectQuery+"WHERE ChannelMembers.UserId = :UserId AND (Teams.Id = :TeamId OR Teams.Id = '' OR Teams.Id IS NULL)", map[string]interface{}{"TeamId": teamId, "UserId": userId}) if err != nil { return nil, errors.Wrapf(err, "failed to find ChannelMembers data with teamId=%s and userId=%s", teamId, userId) } @@ -2374,7 +2374,7 @@ func (s SqlChannelStore) GetMembersForUser(teamId string, userId string) (*model func (s SqlChannelStore) GetMembersForUserWithPagination(teamId, userId string, page, perPage int) (*model.ChannelMembers, error) { var dbMembers channelMemberWithSchemeRolesList offset := page * perPage - _, err := s.GetReplica().Select(&dbMembers, CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY+"WHERE ChannelMembers.UserId = :UserId Limit :Limit Offset :Offset", map[string]interface{}{"TeamId": teamId, "UserId": userId, "Limit": perPage, "Offset": offset}) + _, err := s.GetReplica().Select(&dbMembers, ChannelMembersWithSchemeSelectQuery+"WHERE ChannelMembers.UserId = :UserId Limit :Limit Offset :Offset", map[string]interface{}{"TeamId": teamId, "UserId": userId, "Limit": perPage, "Offset": offset}) if err != nil { return nil, errors.Wrapf(err, "failed to find ChannelMembers data with teamId=%s and userId=%s", teamId, userId) @@ -2959,7 +2959,7 @@ func (s SqlChannelStore) GetMembersByIds(channelId string, userIds []string) (*m keys, props := MapStringsToQueryParams(userIds, "User") props["ChannelId"] = channelId - if _, err := s.GetReplica().Select(&dbMembers, CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY+"WHERE ChannelMembers.ChannelId = :ChannelId AND ChannelMembers.UserId IN "+keys, props); err != nil { + if _, err := s.GetReplica().Select(&dbMembers, ChannelMembersWithSchemeSelectQuery+"WHERE ChannelMembers.ChannelId = :ChannelId AND ChannelMembers.UserId IN "+keys, props); err != nil { return nil, errors.Wrapf(err, "failed to find ChannelMembers with channelId=%s and userId in %v", channelId, userIds) } @@ -2972,7 +2972,7 @@ func (s SqlChannelStore) GetMembersByChannelIds(channelIds []string, userId stri keys, props := MapStringsToQueryParams(channelIds, "Channel") props["UserId"] = userId - if _, err := s.GetReplica().Select(&dbMembers, CHANNEL_MEMBERS_WITH_SCHEME_SELECT_QUERY+"WHERE ChannelMembers.UserId = :UserId AND ChannelMembers.ChannelId IN "+keys, props); err != nil { + if _, err := s.GetReplica().Select(&dbMembers, ChannelMembersWithSchemeSelectQuery+"WHERE ChannelMembers.UserId = :UserId AND ChannelMembers.ChannelId IN "+keys, props); err != nil { return nil, errors.Wrapf(err, "failed to find ChannelMembers with userId=%s and channelId in %v", userId, channelIds) } diff --git a/store/sqlstore/post_store.go b/store/sqlstore/post_store.go index 932f46c226..ae2e012228 100644 --- a/store/sqlstore/post_store.go +++ b/store/sqlstore/post_store.go @@ -1378,8 +1378,8 @@ func (s *SqlPostStore) search(teamId string, userId string, params *model.Search } func removeMysqlStopWordsFromTerms(terms string) (string, error) { - stopWords := make([]string, len(searchlayer.MYSQL_STOP_WORDS)) - copy(stopWords, searchlayer.MYSQL_STOP_WORDS) + stopWords := make([]string, len(searchlayer.MySQLStopWords)) + copy(stopWords, searchlayer.MySQLStopWords) re, err := regexp.Compile(fmt.Sprintf(`^(%s)$`, strings.Join(stopWords, "|"))) if err != nil { return "", err diff --git a/store/sqlstore/preference_store.go b/store/sqlstore/preference_store.go index 49eecbf04a..2487b4f822 100644 --- a/store/sqlstore/preference_store.go +++ b/store/sqlstore/preference_store.go @@ -46,7 +46,7 @@ func (s SqlPreferenceStore) deleteUnusedFeatures() { WHERE Category = :Category AND Value = :Value - AND Name LIKE '` + store.FEATURE_TOGGLE_PREFIX + `%'` + AND Name LIKE '` + store.FeatureTogglePrefix + `%'` queryParams := map[string]string{ "Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, diff --git a/store/sqlstore/preference_store_test.go b/store/sqlstore/preference_store_test.go index 89725fb42b..2737f92dd0 100644 --- a/store/sqlstore/preference_store_test.go +++ b/store/sqlstore/preference_store_test.go @@ -29,25 +29,25 @@ func TestDeleteUnusedFeatures(t *testing.T) { { UserId: userId1, Category: category, - Name: store.FEATURE_TOGGLE_PREFIX + feature1, + Name: store.FeatureTogglePrefix + feature1, Value: "true", }, { UserId: userId2, Category: category, - Name: store.FEATURE_TOGGLE_PREFIX + feature1, + Name: store.FeatureTogglePrefix + feature1, Value: "false", }, { UserId: userId1, Category: category, - Name: store.FEATURE_TOGGLE_PREFIX + feature2, + Name: store.FeatureTogglePrefix + feature2, Value: "false", }, { UserId: userId2, Category: category, - Name: store.FEATURE_TOGGLE_PREFIX + feature2, + Name: store.FeatureTogglePrefix + feature2, Value: "true", }, } @@ -62,7 +62,7 @@ func TestDeleteUnusedFeatures(t *testing.T) { FROM Preferences WHERE Category = :Category AND Value = :Val - AND Name LIKE '`+store.FEATURE_TOGGLE_PREFIX+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "false"}); err != nil { + AND Name LIKE '`+store.FeatureTogglePrefix+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "false"}); err != nil { require.Nil(t, err) } else if val != 0 { require.Fail(t, "Found %d features with value 'false', expected all to be deleted", val) @@ -73,7 +73,7 @@ func TestDeleteUnusedFeatures(t *testing.T) { FROM Preferences WHERE Category = :Category AND Value = :Val - AND Name LIKE '`+store.FEATURE_TOGGLE_PREFIX+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "true"}); err != nil { + AND Name LIKE '`+store.FeatureTogglePrefix+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "true"}); err != nil { require.Nil(t, err) } else if val == 0 { require.Fail(t, "Found %d features with value 'true', expected to find at least %d features", val, 2) diff --git a/store/sqlstore/reaction_store.go b/store/sqlstore/reaction_store.go index ac929d33c9..532600c526 100644 --- a/store/sqlstore/reaction_store.go +++ b/store/sqlstore/reaction_store.go @@ -132,7 +132,7 @@ func (s *SqlReactionStore) DeleteAllWithEmojiName(emojiName string) error { for _, reaction := range reactions { reaction := reaction - _, err := s.GetMaster().Exec(UPDATE_POST_HAS_REACTIONS_ON_DELETE_QUERY, + _, err := s.GetMaster().Exec(UpdatePostHasReactionsOnDeleteQuery, map[string]interface{}{ "PostId": reaction.PostId, "UpdateAt": model.GetMillis(), @@ -191,7 +191,7 @@ func deleteReactionAndUpdatePost(transaction *gorp.Transaction, reaction *model. } const ( - UPDATE_POST_HAS_REACTIONS_ON_DELETE_QUERY = `UPDATE + UpdatePostHasReactionsOnDeleteQuery = `UPDATE Posts SET UpdateAt = :UpdateAt, @@ -202,7 +202,7 @@ const ( func updatePostForReactionsOnDelete(transaction *gorp.Transaction, postId string) error { updateAt := model.GetMillis() - _, err := transaction.Exec(UPDATE_POST_HAS_REACTIONS_ON_DELETE_QUERY, map[string]interface{}{"PostId": postId, "UpdateAt": updateAt}) + _, err := transaction.Exec(UpdatePostHasReactionsOnDeleteQuery, map[string]interface{}{"PostId": postId, "UpdateAt": updateAt}) return err } diff --git a/store/sqlstore/session_store.go b/store/sqlstore/session_store.go index d8a8b609ef..597136b811 100644 --- a/store/sqlstore/session_store.go +++ b/store/sqlstore/session_store.go @@ -17,7 +17,7 @@ import ( ) const ( - SESSIONS_CLEANUP_DELAY_MILLISECONDS = 100 + SessionsCleanupDelayMilliseconds = 100 ) type SqlSessionStore struct { @@ -304,6 +304,6 @@ func (me SqlSessionStore) Cleanup(expiryTime int64, batchSize int64) { return } - time.Sleep(SESSIONS_CLEANUP_DELAY_MILLISECONDS * time.Millisecond) + time.Sleep(SessionsCleanupDelayMilliseconds * time.Millisecond) } } diff --git a/store/sqlstore/store.go b/store/sqlstore/store.go index a2ba1594c1..3668a4d609 100644 --- a/store/sqlstore/store.go +++ b/store/sqlstore/store.go @@ -33,52 +33,52 @@ import ( ) const ( - INDEX_TYPE_FULL_TEXT = "full_text" - INDEX_TYPE_DEFAULT = "default" - PG_DUP_TABLE_ERROR_CODE = "42P07" // see https://github.com/lib/pq/blob/master/error.go#L268 - MYSQL_DUP_TABLE_ERROR_CODE = uint16(1050) // see https://dev.mysql.com/doc/mysql-errors/5.7/en/server-error-reference.html#error_er_table_exists_error - DB_PING_ATTEMPTS = 18 - DB_PING_TIMEOUT_SECS = 10 + IndexTypeFullText = "full_text" + IndexTypeDefault = "default" + PGDupTableErrorCode = "42P07" // see https://github.com/lib/pq/blob/master/error.go#L268 + MySQLDupTableErrorCode = uint16(1050) // see https://dev.mysql.com/doc/mysql-errors/5.7/en/server-error-reference.html#error_er_table_exists_error + DBPingAttempts = 18 + DBPingTimeoutSecs = 10 // This is a numerical version string by postgres. The format is // 2 characters for major, minor, and patch version prior to 10. // After 10, it's major and minor only. // 10.1 would be 100001. // 9.6.3 would be 90603. - MINIMUM_REQUIRED_POSTGRES_VERSION = 100000 + MinimumRequiredPostgresVersion = 100000 ) const ( - EXIT_GENERIC_FAILURE = 1 - EXIT_CREATE_TABLE = 100 - EXIT_DB_OPEN = 101 - EXIT_PING = 102 - EXIT_NO_DRIVER = 103 - EXIT_TABLE_EXISTS = 104 - EXIT_TABLE_EXISTS_MYSQL = 105 - EXIT_COLUMN_EXISTS = 106 - EXIT_DOES_COLUMN_EXISTS_POSTGRES = 107 - EXIT_DOES_COLUMN_EXISTS_MYSQL = 108 - EXIT_DOES_COLUMN_EXISTS_MISSING = 109 - EXIT_CREATE_COLUMN_POSTGRES = 110 - EXIT_CREATE_COLUMN_MYSQL = 111 - EXIT_CREATE_COLUMN_MISSING = 112 - EXIT_REMOVE_COLUMN = 113 - EXIT_RENAME_COLUMN = 114 - EXIT_MAX_COLUMN = 115 - EXIT_ALTER_COLUMN = 116 - EXIT_CREATE_INDEX_POSTGRES = 117 - EXIT_CREATE_INDEX_MYSQL = 118 - EXIT_CREATE_INDEX_FULL_MYSQL = 119 - EXIT_CREATE_INDEX_MISSING = 120 - EXIT_REMOVE_INDEX_POSTGRES = 121 - EXIT_REMOVE_INDEX_MYSQL = 122 - EXIT_REMOVE_INDEX_MISSING = 123 - EXIT_REMOVE_TABLE = 134 - EXIT_CREATE_INDEX_SQLITE = 135 - EXIT_REMOVE_INDEX_SQLITE = 136 - EXIT_TABLE_EXISTS_SQLITE = 137 - EXIT_DOES_COLUMN_EXISTS_SQLITE = 138 - EXIT_ALTER_PRIMARY_KEY = 139 + ExitGenericFailure = 1 + ExitCreateTable = 100 + ExitDBOpen = 101 + ExitPing = 102 + ExitNoDriver = 103 + ExitTableExists = 104 + ExitTableExistsMySQL = 105 + ExitColumnExists = 106 + ExitDoesColumnExistsPostgres = 107 + ExitDoesColumnExistsMySQL = 108 + ExitDoesColumnExistsMissing = 109 + ExitCreateColumnPostgres = 110 + ExitCreateColumnMySQL = 111 + ExitCreateColumnMissing = 112 + ExitRemoveColumn = 113 + ExitRenameColumn = 114 + ExitMaxColumn = 115 + ExitAlterColumn = 116 + ExitCreateIndexPostgres = 117 + ExitCreateIndexMySQL = 118 + ExitCreateIndexFullMySQL = 119 + ExitCreateIndexMissing = 120 + ExitRemoveIndexPostgres = 121 + ExitRemoveIndexMySQL = 122 + ExitRemoveIndexMissing = 123 + ExitRemoveTable = 134 + ExitCreateIndexSqlite = 135 + ExitRemoveIndexSqlite = 136 + ExitTableExists_SQLITE = 137 + ExitDoesColumnExistsSqlite = 138 + ExitAlterPrimaryKey = 139 ) type SqlStoreStores struct { @@ -193,7 +193,7 @@ func New(settings model.SqlSettings, metrics einterfaces.MetricsInterface) *SqlS mlog.Warn("Duplicate key error occurred; assuming table already created and proceeding.", mlog.Err(err)) } else { mlog.Critical("Error creating database tables.", mlog.Err(err)) - os.Exit(EXIT_CREATE_TABLE) + os.Exit(ExitCreateTable) } } @@ -201,7 +201,7 @@ func New(settings model.SqlSettings, metrics einterfaces.MetricsInterface) *SqlS if err != nil { mlog.Critical("Failed to upgrade database.", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) } store.stores.team.(*SqlTeamStore).createIndexesIfNotExists() @@ -244,24 +244,24 @@ func setupConnection(con_type string, dataSource string, settings *model.SqlSett if err != nil { mlog.Critical("Failed to open SQL connection to err.", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_DB_OPEN) + os.Exit(ExitDBOpen) } - for i := 0; i < DB_PING_ATTEMPTS; i++ { + for i := 0; i < DBPingAttempts; i++ { mlog.Info("Pinging SQL", mlog.String("database", con_type)) - ctx, cancel := context.WithTimeout(context.Background(), DB_PING_TIMEOUT_SECS*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), DBPingTimeoutSecs*time.Second) defer cancel() err = db.PingContext(ctx) if err == nil { break } else { - if i == DB_PING_ATTEMPTS-1 { + if i == DBPingAttempts-1 { mlog.Critical("Failed to ping DB, server will exit.", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_PING) + os.Exit(ExitPing) } else { - mlog.Error("Failed to ping DB", mlog.Err(err), mlog.Int("retrying in seconds", DB_PING_TIMEOUT_SECS)) - time.Sleep(DB_PING_TIMEOUT_SECS * time.Second) + mlog.Error("Failed to ping DB", mlog.Err(err), mlog.Int("retrying in seconds", DBPingTimeoutSecs)) + time.Sleep(DBPingTimeoutSecs * time.Second) } } } @@ -283,7 +283,7 @@ func setupConnection(con_type string, dataSource string, settings *model.SqlSett } else { mlog.Critical("Failed to create dialect specific driver") time.Sleep(time.Second) - os.Exit(EXIT_NO_DRIVER) + os.Exit(ExitNoDriver) } if settings.Trace != nil && *settings.Trace { @@ -441,7 +441,7 @@ func (ss *SqlStore) DoesTableExist(tableName string) bool { if err != nil { mlog.Critical("Failed to check if table exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_TABLE_EXISTS) + os.Exit(ExitTableExists) } return count > 0 @@ -463,7 +463,7 @@ func (ss *SqlStore) DoesTableExist(tableName string) bool { if err != nil { mlog.Critical("Failed to check if table exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_TABLE_EXISTS_MYSQL) + os.Exit(ExitTableExistsMySQL) } return count > 0 @@ -477,7 +477,7 @@ func (ss *SqlStore) DoesTableExist(tableName string) bool { if err != nil { mlog.Critical("Failed to check if table exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_TABLE_EXISTS_SQLITE) + os.Exit(ExitTableExists_SQLITE) } return count > 0 @@ -485,7 +485,7 @@ func (ss *SqlStore) DoesTableExist(tableName string) bool { } else { mlog.Critical("Failed to check if column exists because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_COLUMN_EXISTS) + os.Exit(ExitColumnExists) return false } } @@ -509,7 +509,7 @@ func (ss *SqlStore) DoesColumnExist(tableName string, columnName string) bool { mlog.Critical("Failed to check if column exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_DOES_COLUMN_EXISTS_POSTGRES) + os.Exit(ExitDoesColumnExistsPostgres) } return count > 0 @@ -532,7 +532,7 @@ func (ss *SqlStore) DoesColumnExist(tableName string, columnName string) bool { if err != nil { mlog.Critical("Failed to check if column exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_DOES_COLUMN_EXISTS_MYSQL) + os.Exit(ExitDoesColumnExistsMySQL) } return count > 0 @@ -547,7 +547,7 @@ func (ss *SqlStore) DoesColumnExist(tableName string, columnName string) bool { if err != nil { mlog.Critical("Failed to check if column exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_DOES_COLUMN_EXISTS_SQLITE) + os.Exit(ExitDoesColumnExistsSqlite) } return count > 0 @@ -555,7 +555,7 @@ func (ss *SqlStore) DoesColumnExist(tableName string, columnName string) bool { } else { mlog.Critical("Failed to check if column exists because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_DOES_COLUMN_EXISTS_MISSING) + os.Exit(ExitDoesColumnExistsMissing) return false } } @@ -574,7 +574,7 @@ func (ss *SqlStore) DoesTriggerExist(triggerName string) bool { if err != nil { mlog.Critical("Failed to check if trigger exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) } return count > 0 @@ -593,7 +593,7 @@ func (ss *SqlStore) DoesTriggerExist(triggerName string) bool { if err != nil { mlog.Critical("Failed to check if trigger exists", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) } return count > 0 @@ -601,7 +601,7 @@ func (ss *SqlStore) DoesTriggerExist(triggerName string) bool { } else { mlog.Critical("Failed to check if column exists because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) return false } } @@ -617,7 +617,7 @@ func (ss *SqlStore) CreateColumnIfNotExists(tableName string, columnName string, if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_COLUMN_POSTGRES) + os.Exit(ExitCreateColumnPostgres) } return true @@ -627,7 +627,7 @@ func (ss *SqlStore) CreateColumnIfNotExists(tableName string, columnName string, if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_COLUMN_MYSQL) + os.Exit(ExitCreateColumnMySQL) } return true @@ -635,7 +635,7 @@ func (ss *SqlStore) CreateColumnIfNotExists(tableName string, columnName string, } else { mlog.Critical("Failed to create column because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_CREATE_COLUMN_MISSING) + os.Exit(ExitCreateColumnMissing) return false } } @@ -651,7 +651,7 @@ func (ss *SqlStore) CreateColumnIfNotExistsNoDefault(tableName string, columnNam if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_COLUMN_POSTGRES) + os.Exit(ExitCreateColumnPostgres) } return true @@ -661,7 +661,7 @@ func (ss *SqlStore) CreateColumnIfNotExistsNoDefault(tableName string, columnNam if err != nil { mlog.Critical("Failed to create column", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_COLUMN_MYSQL) + os.Exit(ExitCreateColumnMySQL) } return true @@ -669,7 +669,7 @@ func (ss *SqlStore) CreateColumnIfNotExistsNoDefault(tableName string, columnNam } else { mlog.Critical("Failed to create column because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_CREATE_COLUMN_MISSING) + os.Exit(ExitCreateColumnMissing) return false } } @@ -684,7 +684,7 @@ func (ss *SqlStore) RemoveColumnIfExists(tableName string, columnName string) bo if err != nil { mlog.Critical("Failed to drop column", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_REMOVE_COLUMN) + os.Exit(ExitRemoveColumn) } return true @@ -699,7 +699,7 @@ func (ss *SqlStore) RemoveTableIfExists(tableName string) bool { if err != nil { mlog.Critical("Failed to drop table", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_REMOVE_TABLE) + os.Exit(ExitRemoveTable) } return true @@ -720,7 +720,7 @@ func (ss *SqlStore) RenameColumnIfExists(tableName string, oldColumnName string, if err != nil { mlog.Critical("Failed to rename column", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_RENAME_COLUMN) + os.Exit(ExitRenameColumn) } return true @@ -742,7 +742,7 @@ func (ss *SqlStore) GetMaxLengthOfColumnIfExists(tableName string, columnName st if err != nil { mlog.Critical("Failed to get max length of column", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_MAX_COLUMN) + os.Exit(ExitMaxColumn) } return result @@ -763,7 +763,7 @@ func (ss *SqlStore) AlterColumnTypeIfExists(tableName string, columnName string, if err != nil { mlog.Critical("Failed to alter column type", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_ALTER_COLUMN) + os.Exit(ExitAlterColumn) } return true @@ -798,7 +798,7 @@ func (ss *SqlStore) AlterColumnDefaultIfExists(tableName string, columnName stri } else { mlog.Critical("Failed to alter column default because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) return false } @@ -812,7 +812,7 @@ func (ss *SqlStore) AlterColumnDefaultIfExists(tableName string, columnName stri if err != nil { mlog.Critical("Failed to alter column", mlog.String("table", tableName), mlog.String("column", columnName), mlog.String("default value", defaultValue), mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) return false } @@ -857,7 +857,7 @@ func (ss *SqlStore) AlterPrimaryKey(tableName string, columnNames []string) bool if err != nil { mlog.Critical("Failed to get current primary key", mlog.String("table", tableName), mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_ALTER_PRIMARY_KEY) + os.Exit(ExitAlterPrimaryKey) } primaryKey := strings.Join(columnNames, ",") @@ -875,29 +875,29 @@ func (ss *SqlStore) AlterPrimaryKey(tableName string, columnNames []string) bool if err != nil { mlog.Critical("Failed to alter primary key", mlog.String("table", tableName), mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_ALTER_PRIMARY_KEY) + os.Exit(ExitAlterPrimaryKey) } return true } func (ss *SqlStore) CreateUniqueIndexIfNotExists(indexName string, tableName string, columnName string) bool { - return ss.createIndexIfNotExists(indexName, tableName, []string{columnName}, INDEX_TYPE_DEFAULT, true) + return ss.createIndexIfNotExists(indexName, tableName, []string{columnName}, IndexTypeDefault, true) } func (ss *SqlStore) CreateIndexIfNotExists(indexName string, tableName string, columnName string) bool { - return ss.createIndexIfNotExists(indexName, tableName, []string{columnName}, INDEX_TYPE_DEFAULT, false) + return ss.createIndexIfNotExists(indexName, tableName, []string{columnName}, IndexTypeDefault, false) } func (ss *SqlStore) CreateCompositeIndexIfNotExists(indexName string, tableName string, columnNames []string) bool { - return ss.createIndexIfNotExists(indexName, tableName, columnNames, INDEX_TYPE_DEFAULT, false) + return ss.createIndexIfNotExists(indexName, tableName, columnNames, IndexTypeDefault, false) } func (ss *SqlStore) CreateUniqueCompositeIndexIfNotExists(indexName string, tableName string, columnNames []string) bool { - return ss.createIndexIfNotExists(indexName, tableName, columnNames, INDEX_TYPE_DEFAULT, true) + return ss.createIndexIfNotExists(indexName, tableName, columnNames, IndexTypeDefault, true) } func (ss *SqlStore) CreateFullTextIndexIfNotExists(indexName string, tableName string, columnName string) bool { - return ss.createIndexIfNotExists(indexName, tableName, []string{columnName}, INDEX_TYPE_FULL_TEXT, false) + return ss.createIndexIfNotExists(indexName, tableName, []string{columnName}, IndexTypeFullText, false) } func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, columnNames []string, indexType string, unique bool) bool { @@ -915,10 +915,10 @@ func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, c } query := "" - if indexType == INDEX_TYPE_FULL_TEXT { + if indexType == IndexTypeFullText { if len(columnNames) != 1 { mlog.Critical("Unable to create multi column full text index") - os.Exit(EXIT_CREATE_INDEX_POSTGRES) + os.Exit(ExitCreateIndexPostgres) } columnName := columnNames[0] postgresColumnNames := convertMySQLFullTextColumnsToPostgres(columnName) @@ -931,7 +931,7 @@ func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, c if err != nil { mlog.Critical("Failed to create index", mlog.Err(errExists), mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_INDEX_POSTGRES) + os.Exit(ExitCreateIndexPostgres) } } else if ss.DriverName() == model.DATABASE_DRIVER_MYSQL { @@ -939,7 +939,7 @@ func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, c if err != nil { mlog.Critical("Failed to check index", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_INDEX_MYSQL) + os.Exit(ExitCreateIndexMySQL) } if count > 0 { @@ -947,7 +947,7 @@ func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, c } fullTextIndex := "" - if indexType == INDEX_TYPE_FULL_TEXT { + if indexType == IndexTypeFullText { fullTextIndex = " FULLTEXT " } @@ -955,19 +955,19 @@ func (ss *SqlStore) createIndexIfNotExists(indexName string, tableName string, c if err != nil { mlog.Critical("Failed to create index", mlog.String("table", tableName), mlog.String("index_name", indexName), mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_INDEX_FULL_MYSQL) + os.Exit(ExitCreateIndexFullMySQL) } } else if ss.DriverName() == model.DATABASE_DRIVER_SQLITE { _, err := ss.GetMaster().ExecNoTimeout("CREATE INDEX IF NOT EXISTS " + indexName + " ON " + tableName + " (" + strings.Join(columnNames, ", ") + ")") if err != nil { mlog.Critical("Failed to create index", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_CREATE_INDEX_SQLITE) + os.Exit(ExitCreateIndexSqlite) } } else { mlog.Critical("Failed to create index because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_CREATE_INDEX_MISSING) + os.Exit(ExitCreateIndexMissing) } return true @@ -986,7 +986,7 @@ func (ss *SqlStore) RemoveIndexIfExists(indexName string, tableName string) bool if err != nil { mlog.Critical("Failed to remove index", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_REMOVE_INDEX_POSTGRES) + os.Exit(ExitRemoveIndexPostgres) } return true @@ -996,7 +996,7 @@ func (ss *SqlStore) RemoveIndexIfExists(indexName string, tableName string) bool if err != nil { mlog.Critical("Failed to check index", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_REMOVE_INDEX_MYSQL) + os.Exit(ExitRemoveIndexMySQL) } if count <= 0 { @@ -1007,19 +1007,19 @@ func (ss *SqlStore) RemoveIndexIfExists(indexName string, tableName string) bool if err != nil { mlog.Critical("Failed to remove index", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_REMOVE_INDEX_MYSQL) + os.Exit(ExitRemoveIndexMySQL) } } else if ss.DriverName() == model.DATABASE_DRIVER_SQLITE { _, err := ss.GetMaster().ExecNoTimeout("DROP INDEX IF EXISTS " + indexName) if err != nil { mlog.Critical("Failed to remove index", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_REMOVE_INDEX_SQLITE) + os.Exit(ExitRemoveIndexSqlite) } } else { mlog.Critical("Failed to create index because of missing driver") time.Sleep(time.Second) - os.Exit(EXIT_REMOVE_INDEX_MISSING) + os.Exit(ExitRemoveIndexMissing) } return true @@ -1350,11 +1350,11 @@ func IsDuplicate(err error) bool { var mysqlErr *mysql.MySQLError switch { case errors.As(errors.Cause(err), &pqErr): - if pqErr.Code == PG_DUP_TABLE_ERROR_CODE { + if pqErr.Code == PGDupTableErrorCode { return true } case errors.As(errors.Cause(err), &mysqlErr): - if mysqlErr.Number == MYSQL_DUP_TABLE_ERROR_CODE { + if mysqlErr.Number == MySQLDupTableErrorCode { return true } } diff --git a/store/sqlstore/store_test.go b/store/sqlstore/store_test.go index 822f615f99..8a4bba07e3 100644 --- a/store/sqlstore/store_test.go +++ b/store/sqlstore/store_test.go @@ -456,11 +456,11 @@ func TestGetAllConns(t *testing.T) { func TestIsDuplicate(t *testing.T) { testErrors := map[error]bool{ - &pq.Error{Code: "42P06"}: false, - &pq.Error{Code: PG_DUP_TABLE_ERROR_CODE}: true, - &mysql.MySQLError{Number: uint16(1000)}: false, - &mysql.MySQLError{Number: MYSQL_DUP_TABLE_ERROR_CODE}: true, - errors.New("Random error"): false, + &pq.Error{Code: "42P06"}: false, + &pq.Error{Code: PGDupTableErrorCode}: true, + &mysql.MySQLError{Number: uint16(1000)}: false, + &mysql.MySQLError{Number: MySQLDupTableErrorCode}: true, + errors.New("Random error"): false, } for err, expected := range testErrors { diff --git a/store/sqlstore/team_store.go b/store/sqlstore/team_store.go index 86d8f91356..3426b48e2a 100644 --- a/store/sqlstore/team_store.go +++ b/store/sqlstore/team_store.go @@ -19,7 +19,7 @@ import ( ) const ( - TEAM_MEMBER_EXISTS_ERROR = "store.sql_team.save_member.exists.app_error" + TeamMemberExistsError = "store.sql_team.save_member.exists.app_error" ) type SqlTeamStore struct { diff --git a/store/sqlstore/upgrade.go b/store/sqlstore/upgrade.go index cdf3dd0ea9..89fd6d2e1b 100644 --- a/store/sqlstore/upgrade.go +++ b/store/sqlstore/upgrade.go @@ -19,73 +19,73 @@ import ( ) const ( - CURRENT_SCHEMA_VERSION = VERSION_5_31_0 - VERSION_5_32_0 = "5.32.0" - VERSION_5_31_0 = "5.31.0" - VERSION_5_30_0 = "5.30.0" - VERSION_5_29_0 = "5.29.0" - VERSION_5_28_1 = "5.28.1" - VERSION_5_28_0 = "5.28.0" - VERSION_5_27_0 = "5.27.0" - VERSION_5_26_0 = "5.26.0" - VERSION_5_25_0 = "5.25.0" - VERSION_5_24_0 = "5.24.0" - VERSION_5_23_0 = "5.23.0" - VERSION_5_22_0 = "5.22.0" - VERSION_5_21_0 = "5.21.0" - VERSION_5_20_0 = "5.20.0" - VERSION_5_19_0 = "5.19.0" - VERSION_5_18_0 = "5.18.0" - VERSION_5_17_0 = "5.17.0" - VERSION_5_16_0 = "5.16.0" - VERSION_5_15_0 = "5.15.0" - VERSION_5_14_0 = "5.14.0" - VERSION_5_13_0 = "5.13.0" - VERSION_5_12_0 = "5.12.0" - VERSION_5_11_0 = "5.11.0" - VERSION_5_10_0 = "5.10.0" - VERSION_5_9_0 = "5.9.0" - VERSION_5_8_0 = "5.8.0" - VERSION_5_7_0 = "5.7.0" - VERSION_5_6_0 = "5.6.0" - VERSION_5_5_0 = "5.5.0" - VERSION_5_4_0 = "5.4.0" - VERSION_5_3_0 = "5.3.0" - VERSION_5_2_0 = "5.2.0" - VERSION_5_1_0 = "5.1.0" - VERSION_5_0_0 = "5.0.0" - VERSION_4_10_0 = "4.10.0" - VERSION_4_9_0 = "4.9.0" - VERSION_4_8_1 = "4.8.1" - VERSION_4_8_0 = "4.8.0" - VERSION_4_7_2 = "4.7.2" - VERSION_4_7_1 = "4.7.1" - VERSION_4_7_0 = "4.7.0" - VERSION_4_6_0 = "4.6.0" - VERSION_4_5_0 = "4.5.0" - VERSION_4_4_0 = "4.4.0" - VERSION_4_3_0 = "4.3.0" - VERSION_4_2_0 = "4.2.0" - VERSION_4_1_0 = "4.1.0" - VERSION_4_0_0 = "4.0.0" - VERSION_3_10_0 = "3.10.0" - VERSION_3_9_0 = "3.9.0" - VERSION_3_8_0 = "3.8.0" - VERSION_3_7_0 = "3.7.0" - VERSION_3_6_0 = "3.6.0" - VERSION_3_5_0 = "3.5.0" - VERSION_3_4_0 = "3.4.0" - VERSION_3_3_0 = "3.3.0" - VERSION_3_2_0 = "3.2.0" - VERSION_3_1_0 = "3.1.0" - VERSION_3_0_0 = "3.0.0" - OLDEST_SUPPORTED_VERSION = VERSION_3_0_0 + CurrentSchemaVersion = Version5310 + Version5320 = "5.32.0" + Version5310 = "5.31.0" + Version5300 = "5.30.0" + Version5290 = "5.29.0" + Version5281 = "5.28.1" + Version5280 = "5.28.0" + Version5270 = "5.27.0" + Version5260 = "5.26.0" + Version5250 = "5.25.0" + Version5240 = "5.24.0" + Version5230 = "5.23.0" + Version5220 = "5.22.0" + Version5210 = "5.21.0" + Version5200 = "5.20.0" + Version5190 = "5.19.0" + Version5180 = "5.18.0" + Version5170 = "5.17.0" + Version5160 = "5.16.0" + Version5150 = "5.15.0" + Version5140 = "5.14.0" + Version5130 = "5.13.0" + Version5120 = "5.12.0" + Version5110 = "5.11.0" + Version5100 = "5.10.0" + Version590 = "5.9.0" + Version580 = "5.8.0" + Version570 = "5.7.0" + Version560 = "5.6.0" + Version550 = "5.5.0" + Version540 = "5.4.0" + Version530 = "5.3.0" + Version520 = "5.2.0" + Version510 = "5.1.0" + Version500 = "5.0.0" + Version4100 = "4.10.0" + Version490 = "4.9.0" + Version481 = "4.8.1" + Version480 = "4.8.0" + Version472 = "4.7.2" + Version471 = "4.7.1" + Version470 = "4.7.0" + Version460 = "4.6.0" + Version450 = "4.5.0" + Version440 = "4.4.0" + Version430 = "4.3.0" + Version420 = "4.2.0" + Version410 = "4.1.0" + Version400 = "4.0.0" + Version3100 = "3.10.0" + Version390 = "3.9.0" + Version380 = "3.8.0" + Version370 = "3.7.0" + Version360 = "3.6.0" + Version350 = "3.5.0" + Version340 = "3.4.0" + Version330 = "3.3.0" + Version320 = "3.2.0" + Version310 = "3.1.0" + Version300 = "3.0.0" + OldestSupportedVersion = Version300 ) const ( - EXIT_VERSION_SAVE = 1003 - EXIT_THEME_MIGRATION = 1004 - EXIT_TEAM_INVITEID_MIGRATION_FAILED = 1006 + ExitVersionSave = 1003 + ExitThemeMigration = 1004 + ExitTeamInviteIDMigrationFailed = 1006 ) // upgradeDatabase attempts to migrate the schema to the latest supported version. @@ -101,9 +101,9 @@ func upgradeDatabase(sqlStore *SqlStore, currentModelVersionString string) error Major: currentModelVersion.Major + 1, } - oldestSupportedVersion, err := semver.Parse(OLDEST_SUPPORTED_VERSION) + oldestSupportedVersion, err := semver.Parse(OldestSupportedVersion) if err != nil { - return errors.Wrapf(err, "failed to parse oldest supported version %s", OLDEST_SUPPORTED_VERSION) + return errors.Wrapf(err, "failed to parse oldest supported version %s", OldestSupportedVersion) } var currentSchemaVersion *semver.Version @@ -206,7 +206,7 @@ func saveSchemaVersion(sqlStore *SqlStore, version string) { if err := sqlStore.System().SaveOrUpdate(&model.System{Name: "Version", Value: version}); err != nil { mlog.Critical(err.Error()) time.Sleep(time.Second) - os.Exit(EXIT_VERSION_SAVE) + os.Exit(ExitVersionSave) } mlog.Warn("The database schema version has been upgraded", mlog.String("version", version)) @@ -223,28 +223,28 @@ func shouldPerformUpgrade(sqlStore *SqlStore, currentSchemaVersion string, expec } func upgradeDatabaseToVersion31(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_0_0, VERSION_3_1_0) { + if shouldPerformUpgrade(sqlStore, Version300, Version310) { sqlStore.CreateColumnIfNotExists("OutgoingWebhooks", "ContentType", "varchar(128)", "varchar(128)", "") - saveSchemaVersion(sqlStore, VERSION_3_1_0) + saveSchemaVersion(sqlStore, Version310) } } func upgradeDatabaseToVersion32(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_1_0, VERSION_3_2_0) { + if shouldPerformUpgrade(sqlStore, Version310, Version320) { sqlStore.CreateColumnIfNotExists("TeamMembers", "DeleteAt", "bigint(20)", "bigint", "0") - saveSchemaVersion(sqlStore, VERSION_3_2_0) + saveSchemaVersion(sqlStore, Version320) } } func themeMigrationFailed(err error) { mlog.Critical("Failed to migrate User.ThemeProps to Preferences table", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_THEME_MIGRATION) + os.Exit(ExitThemeMigration) } func upgradeDatabaseToVersion33(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_2_0, VERSION_3_3_0) { + if shouldPerformUpgrade(sqlStore, Version320, Version330) { if sqlStore.DoesColumnExist("Users", "ThemeProps") { params := map[string]interface{}{ "Category": model.PREFERENCE_CATEGORY_THEME, @@ -322,21 +322,21 @@ func upgradeDatabaseToVersion33(sqlStore *SqlStore) { sqlStore.CreateColumnIfNotExists("OutgoingWebhooks", "TriggerWhen", "tinyint", "integer", "0") - saveSchemaVersion(sqlStore, VERSION_3_3_0) + saveSchemaVersion(sqlStore, Version330) } } func upgradeDatabaseToVersion34(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_3_0, VERSION_3_4_0) { + if shouldPerformUpgrade(sqlStore, Version330, Version340) { sqlStore.CreateColumnIfNotExists("Status", "Manual", "BOOLEAN", "BOOLEAN", "0") sqlStore.CreateColumnIfNotExists("Status", "ActiveChannel", "varchar(26)", "varchar(26)", "") - saveSchemaVersion(sqlStore, VERSION_3_4_0) + saveSchemaVersion(sqlStore, Version340) } } func upgradeDatabaseToVersion35(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_4_0, VERSION_3_5_0) { + if shouldPerformUpgrade(sqlStore, Version340, Version350) { sqlStore.GetMaster().Exec("UPDATE Users SET Roles = 'system_user' WHERE Roles = ''") sqlStore.GetMaster().Exec("UPDATE Users SET Roles = 'system_user system_admin' WHERE Roles = 'system_admin'") sqlStore.GetMaster().Exec("UPDATE TeamMembers SET Roles = 'team_user' WHERE Roles = ''") @@ -354,12 +354,12 @@ func upgradeDatabaseToVersion35(sqlStore *SqlStore) { sqlStore.Session().RemoveAllSessions() - saveSchemaVersion(sqlStore, VERSION_3_5_0) + saveSchemaVersion(sqlStore, Version350) } } func upgradeDatabaseToVersion36(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_5_0, VERSION_3_6_0) { + if shouldPerformUpgrade(sqlStore, Version350, Version360) { sqlStore.CreateColumnIfNotExists("Posts", "HasReactions", "tinyint", "boolean", "0") // Create Team Description column @@ -371,51 +371,51 @@ func upgradeDatabaseToVersion36(sqlStore *SqlStore) { // Remove ActiveChannel column from Status sqlStore.RemoveColumnIfExists("Status", "ActiveChannel") - saveSchemaVersion(sqlStore, VERSION_3_6_0) + saveSchemaVersion(sqlStore, Version360) } } func upgradeDatabaseToVersion37(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_6_0, VERSION_3_7_0) { + if shouldPerformUpgrade(sqlStore, Version360, Version370) { // Add EditAt column to Posts sqlStore.CreateColumnIfNotExists("Posts", "EditAt", " bigint", " bigint", "0") - saveSchemaVersion(sqlStore, VERSION_3_7_0) + saveSchemaVersion(sqlStore, Version370) } } func upgradeDatabaseToVersion38(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_7_0, VERSION_3_8_0) { + if shouldPerformUpgrade(sqlStore, Version370, Version380) { // Add the IsPinned column to posts. sqlStore.CreateColumnIfNotExists("Posts", "IsPinned", "boolean", "boolean", "0") - saveSchemaVersion(sqlStore, VERSION_3_8_0) + saveSchemaVersion(sqlStore, Version380) } } func upgradeDatabaseToVersion39(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_8_0, VERSION_3_9_0) { + if shouldPerformUpgrade(sqlStore, Version380, Version390) { sqlStore.CreateColumnIfNotExists("OAuthAccessData", "Scope", "varchar(128)", "varchar(128)", model.DEFAULT_SCOPE) sqlStore.RemoveTableIfExists("PasswordRecovery") - saveSchemaVersion(sqlStore, VERSION_3_9_0) + saveSchemaVersion(sqlStore, Version390) } } func upgradeDatabaseToVersion310(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_9_0, VERSION_3_10_0) { - saveSchemaVersion(sqlStore, VERSION_3_10_0) + if shouldPerformUpgrade(sqlStore, Version390, Version3100) { + saveSchemaVersion(sqlStore, Version3100) } } func upgradeDatabaseToVersion40(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_3_10_0, VERSION_4_0_0) { - saveSchemaVersion(sqlStore, VERSION_4_0_0) + if shouldPerformUpgrade(sqlStore, Version3100, Version400) { + saveSchemaVersion(sqlStore, Version400) } } func upgradeDatabaseToVersion41(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_0_0, VERSION_4_1_0) { + if shouldPerformUpgrade(sqlStore, Version400, Version410) { // Increase maximum length of the Users table Roles column. if sqlStore.GetMaxLengthOfColumnIfExists("Users", "Roles") != "256" { sqlStore.AlterColumnTypeIfExists("Users", "Roles", "varchar(256)", "varchar(256)") @@ -423,52 +423,52 @@ func upgradeDatabaseToVersion41(sqlStore *SqlStore) { sqlStore.RemoveTableIfExists("JobStatuses") - saveSchemaVersion(sqlStore, VERSION_4_1_0) + saveSchemaVersion(sqlStore, Version410) } } func upgradeDatabaseToVersion42(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_1_0, VERSION_4_2_0) { - saveSchemaVersion(sqlStore, VERSION_4_2_0) + if shouldPerformUpgrade(sqlStore, Version410, Version420) { + saveSchemaVersion(sqlStore, Version420) } } func upgradeDatabaseToVersion43(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_2_0, VERSION_4_3_0) { - saveSchemaVersion(sqlStore, VERSION_4_3_0) + if shouldPerformUpgrade(sqlStore, Version420, Version430) { + saveSchemaVersion(sqlStore, Version430) } } func upgradeDatabaseToVersion44(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_3_0, VERSION_4_4_0) { + if shouldPerformUpgrade(sqlStore, Version430, Version440) { // Add the IsActive column to UserAccessToken. sqlStore.CreateColumnIfNotExists("UserAccessTokens", "IsActive", "boolean", "boolean", "1") - saveSchemaVersion(sqlStore, VERSION_4_4_0) + saveSchemaVersion(sqlStore, Version440) } } func upgradeDatabaseToVersion45(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_4_0, VERSION_4_5_0) { - saveSchemaVersion(sqlStore, VERSION_4_5_0) + if shouldPerformUpgrade(sqlStore, Version440, Version450) { + saveSchemaVersion(sqlStore, Version450) } } func upgradeDatabaseToVersion46(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_5_0, VERSION_4_6_0) { + if shouldPerformUpgrade(sqlStore, Version450, Version460) { sqlStore.CreateColumnIfNotExists("IncomingWebhooks", "Username", "varchar(64)", "varchar(64)", "") sqlStore.CreateColumnIfNotExists("IncomingWebhooks", "IconURL", "varchar(1024)", "varchar(1024)", "") - saveSchemaVersion(sqlStore, VERSION_4_6_0) + saveSchemaVersion(sqlStore, Version460) } } func upgradeDatabaseToVersion47(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_6_0, VERSION_4_7_0) { + if shouldPerformUpgrade(sqlStore, Version460, Version470) { sqlStore.AlterColumnTypeIfExists("Users", "Position", "varchar(128)", "varchar(128)") sqlStore.AlterColumnTypeIfExists("OAuthAuthData", "State", "varchar(1024)", "varchar(1024)") sqlStore.RemoveColumnIfExists("ChannelMemberHistory", "Email") sqlStore.RemoveColumnIfExists("ChannelMemberHistory", "Username") - saveSchemaVersion(sqlStore, VERSION_4_7_0) + saveSchemaVersion(sqlStore, Version470) } } @@ -476,29 +476,29 @@ func upgradeDatabaseToVersion471(sqlStore *SqlStore) { // If any new instances started with 4.7, they would have the bad Email column on the // ChannelMemberHistory table. So for those cases we need to do an upgrade between // 4.7.0 and 4.7.1 - if shouldPerformUpgrade(sqlStore, VERSION_4_7_0, VERSION_4_7_1) { + if shouldPerformUpgrade(sqlStore, Version470, Version471) { sqlStore.RemoveColumnIfExists("ChannelMemberHistory", "Email") - saveSchemaVersion(sqlStore, VERSION_4_7_1) + saveSchemaVersion(sqlStore, Version471) } } func upgradeDatabaseToVersion472(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_7_1, VERSION_4_7_2) { + if shouldPerformUpgrade(sqlStore, Version471, Version472) { sqlStore.RemoveIndexIfExists("idx_channels_displayname", "Channels") - saveSchemaVersion(sqlStore, VERSION_4_7_2) + saveSchemaVersion(sqlStore, Version472) } } func upgradeDatabaseToVersion48(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_7_2, VERSION_4_8_0) { - saveSchemaVersion(sqlStore, VERSION_4_8_0) + if shouldPerformUpgrade(sqlStore, Version472, Version480) { + saveSchemaVersion(sqlStore, Version480) } } func upgradeDatabaseToVersion481(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_8_0, VERSION_4_8_1) { + if shouldPerformUpgrade(sqlStore, Version480, Version481) { sqlStore.RemoveIndexIfExists("idx_channels_displayname", "Channels") - saveSchemaVersion(sqlStore, VERSION_4_8_1) + saveSchemaVersion(sqlStore, Version481) } } @@ -507,7 +507,7 @@ func upgradeDatabaseToVersion49(sqlStore *SqlStore) { // a number of parameters in `config.json` to a `Roles` table in the database. The migration code can be seen // in the file `app/app.go` in the function `DoAdvancedPermissionsMigration()`. - if shouldPerformUpgrade(sqlStore, VERSION_4_8_1, VERSION_4_9_0) { + if shouldPerformUpgrade(sqlStore, Version481, Version490) { sqlStore.CreateColumnIfNotExists("Teams", "LastTeamIconUpdate", "bigint", "bigint", "0") defaultTimezone := timezones.DefaultUserTimezone() defaultTimezoneValue, err := json.Marshal(defaultTimezone) @@ -516,18 +516,18 @@ func upgradeDatabaseToVersion49(sqlStore *SqlStore) { } sqlStore.CreateColumnIfNotExists("Users", "Timezone", "varchar(256)", "varchar(256)", string(defaultTimezoneValue)) sqlStore.RemoveIndexIfExists("idx_channels_displayname", "Channels") - saveSchemaVersion(sqlStore, VERSION_4_9_0) + saveSchemaVersion(sqlStore, Version490) } } func upgradeDatabaseToVersion410(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_4_9_0, VERSION_4_10_0) { + if shouldPerformUpgrade(sqlStore, Version490, Version4100) { sqlStore.RemoveIndexIfExists("Name_2", "Channels") sqlStore.RemoveIndexIfExists("Name_2", "Emoji") sqlStore.RemoveIndexIfExists("ClientId_2", "OAuthAccessData") - saveSchemaVersion(sqlStore, VERSION_4_10_0) + saveSchemaVersion(sqlStore, Version4100) sqlStore.GetMaster().Exec("UPDATE Users SET AuthData=LOWER(AuthData) WHERE AuthService = 'saml'") } } @@ -550,7 +550,7 @@ func upgradeDatabaseToVersion50(sqlStore *SqlStore) { // UPDATE ChannelMembers SET Roles = CONCAT(Roles, ' channel_admin'), SchemeAdmin = NULL where SchemeAdmin = 1; // DELETE from Systems WHERE Name = 'migration_advanced_permissions_phase_2'; - if shouldPerformUpgrade(sqlStore, VERSION_4_10_0, VERSION_5_0_0) { + if shouldPerformUpgrade(sqlStore, Version4100, Version500) { sqlStore.CreateColumnIfNotExistsNoDefault("Teams", "SchemeId", "varchar(26)", "varchar(26)") sqlStore.CreateColumnIfNotExistsNoDefault("Channels", "SchemeId", "varchar(26)", "varchar(26)") @@ -567,51 +567,51 @@ func upgradeDatabaseToVersion50(sqlStore *SqlStore) { sqlStore.RemoveIndexIfExists("idx_channels_txt", "Channels") - saveSchemaVersion(sqlStore, VERSION_5_0_0) + saveSchemaVersion(sqlStore, Version500) } } func upgradeDatabaseToVersion51(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_0_0, VERSION_5_1_0) { - saveSchemaVersion(sqlStore, VERSION_5_1_0) + if shouldPerformUpgrade(sqlStore, Version500, Version510) { + saveSchemaVersion(sqlStore, Version510) } } func upgradeDatabaseToVersion52(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_1_0, VERSION_5_2_0) { + if shouldPerformUpgrade(sqlStore, Version510, Version520) { sqlStore.CreateColumnIfNotExists("OutgoingWebhooks", "Username", "varchar(64)", "varchar(64)", "") sqlStore.CreateColumnIfNotExists("OutgoingWebhooks", "IconURL", "varchar(1024)", "varchar(1024)", "") - saveSchemaVersion(sqlStore, VERSION_5_2_0) + saveSchemaVersion(sqlStore, Version520) } } func upgradeDatabaseToVersion53(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_2_0, VERSION_5_3_0) { - saveSchemaVersion(sqlStore, VERSION_5_3_0) + if shouldPerformUpgrade(sqlStore, Version520, Version530) { + saveSchemaVersion(sqlStore, Version530) } } func upgradeDatabaseToVersion54(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_3_0, VERSION_5_4_0) { + if shouldPerformUpgrade(sqlStore, Version530, Version540) { sqlStore.AlterColumnTypeIfExists("OutgoingWebhooks", "Description", "varchar(500)", "varchar(500)") sqlStore.AlterColumnTypeIfExists("IncomingWebhooks", "Description", "varchar(500)", "varchar(500)") if err := sqlStore.Channel().MigratePublicChannels(); err != nil { mlog.Critical("Failed to migrate PublicChannels table", mlog.Err(err)) time.Sleep(time.Second) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) } - saveSchemaVersion(sqlStore, VERSION_5_4_0) + saveSchemaVersion(sqlStore, Version540) } } func upgradeDatabaseToVersion55(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_4_0, VERSION_5_5_0) { - saveSchemaVersion(sqlStore, VERSION_5_5_0) + if shouldPerformUpgrade(sqlStore, Version540, Version550) { + saveSchemaVersion(sqlStore, Version550) } } func upgradeDatabaseToVersion56(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_5_0, VERSION_5_6_0) { + if shouldPerformUpgrade(sqlStore, Version550, Version560) { sqlStore.CreateColumnIfNotExists("PluginKeyValueStore", "ExpireAt", "bigint(20)", "bigint", "0") // migrating user's accepted terms of service data into the new table @@ -625,19 +625,19 @@ func upgradeDatabaseToVersion56(sqlStore *SqlStore) { sqlStore.RemoveIndexIfExists("idx_users_lastname_lower", "lower(LastName)") } - saveSchemaVersion(sqlStore, VERSION_5_6_0) + saveSchemaVersion(sqlStore, Version560) } } func upgradeDatabaseToVersion57(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_6_0, VERSION_5_7_0) { - saveSchemaVersion(sqlStore, VERSION_5_7_0) + if shouldPerformUpgrade(sqlStore, Version560, Version570) { + saveSchemaVersion(sqlStore, Version570) } } func upgradeDatabaseToVersion58(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_7_0, VERSION_5_8_0) { + if shouldPerformUpgrade(sqlStore, Version570, Version580) { // idx_channels_txt was removed in `upgradeDatabaseToVersion50`, but merged as part of // v5.1, so the migration wouldn't apply to anyone upgrading from v5.0. Remove it again to // bring the upgraded (from v5.0) and fresh install schemas back in sync. @@ -652,30 +652,30 @@ func upgradeDatabaseToVersion58(sqlStore *SqlStore) { sqlStore.AlterColumnDefaultIfExists("OutgoingWebhooks", "IconURL", nil, model.NewString("")) sqlStore.AlterColumnDefaultIfExists("PluginKeyValueStore", "ExpireAt", model.NewString("NULL"), model.NewString("NULL")) - saveSchemaVersion(sqlStore, VERSION_5_8_0) + saveSchemaVersion(sqlStore, Version580) } } func upgradeDatabaseToVersion59(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_8_0, VERSION_5_9_0) { - saveSchemaVersion(sqlStore, VERSION_5_9_0) + if shouldPerformUpgrade(sqlStore, Version580, Version590) { + saveSchemaVersion(sqlStore, Version590) } } func upgradeDatabaseToVersion510(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_9_0, VERSION_5_10_0) { + if shouldPerformUpgrade(sqlStore, Version590, Version5100) { sqlStore.CreateColumnIfNotExistsNoDefault("Channels", "GroupConstrained", "tinyint(4)", "boolean") sqlStore.CreateColumnIfNotExistsNoDefault("Teams", "GroupConstrained", "tinyint(4)", "boolean") sqlStore.CreateIndexIfNotExists("idx_groupteams_teamid", "GroupTeams", "TeamId") sqlStore.CreateIndexIfNotExists("idx_groupchannels_channelid", "GroupChannels", "ChannelId") - saveSchemaVersion(sqlStore, VERSION_5_10_0) + saveSchemaVersion(sqlStore, Version5100) } } func upgradeDatabaseToVersion511(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_10_0, VERSION_5_11_0) { + if shouldPerformUpgrade(sqlStore, Version5100, Version5110) { // Enforce all teams have an InviteID set var teams []*model.Team if _, err := sqlStore.GetReplica().Select(&teams, "SELECT * FROM Teams WHERE InviteId = ''"); err != nil { @@ -689,12 +689,12 @@ func upgradeDatabaseToVersion511(sqlStore *SqlStore) { } } - saveSchemaVersion(sqlStore, VERSION_5_11_0) + saveSchemaVersion(sqlStore, Version5110) } } func upgradeDatabaseToVersion512(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_11_0, VERSION_5_12_0) { + if shouldPerformUpgrade(sqlStore, Version5110, Version5120) { sqlStore.CreateColumnIfNotExistsNoDefault("TeamMembers", "SchemeGuest", "boolean", "boolean") sqlStore.CreateColumnIfNotExistsNoDefault("ChannelMembers", "SchemeGuest", "boolean", "boolean") sqlStore.CreateColumnIfNotExistsNoDefault("Schemes", "DefaultTeamGuestRole", "text", "VARCHAR(64)") @@ -705,39 +705,39 @@ func upgradeDatabaseToVersion512(sqlStore *SqlStore) { // Saturday, January 24, 2065 5:20:00 AM GMT. To remove all personal access token sessions. sqlStore.GetMaster().Exec("DELETE FROM Sessions WHERE ExpiresAt > 3000000000000") - saveSchemaVersion(sqlStore, VERSION_5_12_0) + saveSchemaVersion(sqlStore, Version5120) } } func upgradeDatabaseToVersion513(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_12_0, VERSION_5_13_0) { + if shouldPerformUpgrade(sqlStore, Version5120, Version5130) { // The previous jobs ran once per minute, cluttering the Jobs table with somewhat useless entries. Clean that up. sqlStore.GetMaster().Exec("DELETE FROM Jobs WHERE Type = 'plugins'") - saveSchemaVersion(sqlStore, VERSION_5_13_0) + saveSchemaVersion(sqlStore, Version5130) } } func upgradeDatabaseToVersion514(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_13_0, VERSION_5_14_0) { - saveSchemaVersion(sqlStore, VERSION_5_14_0) + if shouldPerformUpgrade(sqlStore, Version5130, Version5140) { + saveSchemaVersion(sqlStore, Version5140) } } func upgradeDatabaseToVersion515(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_14_0, VERSION_5_15_0) { - saveSchemaVersion(sqlStore, VERSION_5_15_0) + if shouldPerformUpgrade(sqlStore, Version5140, Version5150) { + saveSchemaVersion(sqlStore, Version5150) } } func upgradeDatabaseToVersion516(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_15_0, VERSION_5_16_0) { + if shouldPerformUpgrade(sqlStore, Version5150, Version5160) { if sqlStore.DriverName() == model.DATABASE_DRIVER_POSTGRES { sqlStore.GetMaster().Exec("ALTER TABLE Tokens ALTER COLUMN Extra TYPE varchar(2048)") } else if sqlStore.DriverName() == model.DATABASE_DRIVER_MYSQL { sqlStore.GetMaster().Exec("ALTER TABLE Tokens MODIFY Extra text") } - saveSchemaVersion(sqlStore, VERSION_5_16_0) + saveSchemaVersion(sqlStore, Version5160) // Fix mismatches between the canonical and migrated schemas. sqlStore.AlterColumnTypeIfExists("TeamMembers", "SchemeGuest", "tinyint(4)", "boolean") @@ -758,25 +758,25 @@ func upgradeDatabaseToVersion516(sqlStore *SqlStore) { } func upgradeDatabaseToVersion517(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_16_0, VERSION_5_17_0) { - saveSchemaVersion(sqlStore, VERSION_5_17_0) + if shouldPerformUpgrade(sqlStore, Version5160, Version5170) { + saveSchemaVersion(sqlStore, Version5170) } } func upgradeDatabaseToVersion518(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_17_0, VERSION_5_18_0) { - saveSchemaVersion(sqlStore, VERSION_5_18_0) + if shouldPerformUpgrade(sqlStore, Version5170, Version5180) { + saveSchemaVersion(sqlStore, Version5180) } } func upgradeDatabaseToVersion519(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_18_0, VERSION_5_19_0) { - saveSchemaVersion(sqlStore, VERSION_5_19_0) + if shouldPerformUpgrade(sqlStore, Version5180, Version5190) { + saveSchemaVersion(sqlStore, Version5190) } } func upgradeDatabaseToVersion520(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_19_0, VERSION_5_20_0) { + if shouldPerformUpgrade(sqlStore, Version5190, Version5200) { sqlStore.CreateColumnIfNotExistsNoDefault("Bots", "LastIconUpdate", "bigint", "bigint") sqlStore.CreateColumnIfNotExists("GroupTeams", "SchemeAdmin", "boolean", "boolean", "0") @@ -785,18 +785,18 @@ func upgradeDatabaseToVersion520(sqlStore *SqlStore) { sqlStore.CreateColumnIfNotExists("GroupChannels", "SchemeAdmin", "boolean", "boolean", "0") sqlStore.CreateIndexIfNotExists("idx_groupchannels_schemeadmin", "GroupChannels", "SchemeAdmin") - saveSchemaVersion(sqlStore, VERSION_5_20_0) + saveSchemaVersion(sqlStore, Version5200) } } func upgradeDatabaseToVersion521(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_20_0, VERSION_5_21_0) { - saveSchemaVersion(sqlStore, VERSION_5_21_0) + if shouldPerformUpgrade(sqlStore, Version5200, Version5210) { + saveSchemaVersion(sqlStore, Version5210) } } func upgradeDatabaseToVersion522(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_21_0, VERSION_5_22_0) { + if shouldPerformUpgrade(sqlStore, Version5210, Version5220) { sqlStore.CreateIndexIfNotExists("idx_teams_scheme_id", "Teams", "SchemeId") sqlStore.CreateIndexIfNotExists("idx_channels_scheme_id", "Channels", "SchemeId") sqlStore.CreateIndexIfNotExists("idx_channels_scheme_id", "Channels", "SchemeId") @@ -804,51 +804,51 @@ func upgradeDatabaseToVersion522(sqlStore *SqlStore) { sqlStore.CreateIndexIfNotExists("idx_schemes_channel_user_role", "Schemes", "DefaultChannelUserRole") sqlStore.CreateIndexIfNotExists("idx_schemes_channel_admin_role", "Schemes", "DefaultChannelAdminRole") - saveSchemaVersion(sqlStore, VERSION_5_22_0) + saveSchemaVersion(sqlStore, Version5220) } } func upgradeDatabaseToVersion523(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_22_0, VERSION_5_23_0) { - saveSchemaVersion(sqlStore, VERSION_5_23_0) + if shouldPerformUpgrade(sqlStore, Version5220, Version5230) { + saveSchemaVersion(sqlStore, Version5230) } } func upgradeDatabaseToVersion524(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_23_0, VERSION_5_24_0) { + if shouldPerformUpgrade(sqlStore, Version5230, Version5240) { sqlStore.CreateColumnIfNotExists("UserGroups", "AllowReference", "boolean", "boolean", "0") sqlStore.GetMaster().Exec("UPDATE UserGroups SET Name = null, AllowReference = false") sqlStore.AlterPrimaryKey("Reactions", []string{"PostId", "UserId", "EmojiName"}) - saveSchemaVersion(sqlStore, VERSION_5_24_0) + saveSchemaVersion(sqlStore, Version5240) } } func upgradeDatabaseToVersion525(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_24_0, VERSION_5_25_0) { - saveSchemaVersion(sqlStore, VERSION_5_25_0) + if shouldPerformUpgrade(sqlStore, Version5240, Version5250) { + saveSchemaVersion(sqlStore, Version5250) } } func upgradeDatabaseToVersion526(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_25_0, VERSION_5_26_0) { + if shouldPerformUpgrade(sqlStore, Version5250, Version5260) { sqlStore.CreateColumnIfNotExists("Sessions", "ExpiredNotify", "boolean", "boolean", "0") - saveSchemaVersion(sqlStore, VERSION_5_26_0) + saveSchemaVersion(sqlStore, Version5260) } } func upgradeDatabaseToVersion527(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_26_0, VERSION_5_27_0) { - saveSchemaVersion(sqlStore, VERSION_5_27_0) + if shouldPerformUpgrade(sqlStore, Version5260, Version5270) { + saveSchemaVersion(sqlStore, Version5270) } } func upgradeDatabaseToVersion528(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_27_0, VERSION_5_28_0) { + if shouldPerformUpgrade(sqlStore, Version5270, Version5280) { if err := precheckMigrationToVersion528(sqlStore); err != nil { mlog.Critical("Error upgrading DB schema to 5.28.0", mlog.Err(err)) - os.Exit(EXIT_GENERIC_FAILURE) + os.Exit(ExitGenericFailure) } sqlStore.CreateColumnIfNotExistsNoDefault("Commands", "PluginId", "VARCHAR(190)", "VARCHAR(190)") @@ -859,15 +859,15 @@ func upgradeDatabaseToVersion528(sqlStore *SqlStore) { sqlStore.AlterColumnTypeIfExists("IncomingWebhooks", "Username", "varchar(255)", "varchar(255)") sqlStore.AlterColumnTypeIfExists("IncomingWebhooks", "IconURL", "text", "varchar(1024)") - saveSchemaVersion(sqlStore, VERSION_5_28_0) + saveSchemaVersion(sqlStore, Version5280) } } func upgradeDatabaseToVersion5281(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_28_0, VERSION_5_28_1) { + if shouldPerformUpgrade(sqlStore, Version5280, Version5281) { sqlStore.CreateColumnIfNotExistsNoDefault("FileInfo", "MiniPreview", "MEDIUMBLOB", "bytea") - saveSchemaVersion(sqlStore, VERSION_5_28_1) + saveSchemaVersion(sqlStore, Version5281) } } @@ -925,7 +925,7 @@ func precheckMigrationToVersion528(sqlStore *SqlStore) error { } func upgradeDatabaseToVersion529(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_28_1, VERSION_5_29_0) { + if shouldPerformUpgrade(sqlStore, Version5281, Version5290) { sqlStore.AlterColumnTypeIfExists("SidebarCategories", "Id", "VARCHAR(128)", "VARCHAR(128)") sqlStore.AlterColumnDefaultIfExists("SidebarCategories", "Id", model.NewString(""), nil) sqlStore.AlterColumnTypeIfExists("SidebarChannels", "CategoryId", "VARCHAR(128)", "VARCHAR(128)") @@ -941,30 +941,30 @@ func upgradeDatabaseToVersion529(sqlStore *SqlStore) { mlog.Error("Error updating ChannelId in Threads table", mlog.Err(err)) } - saveSchemaVersion(sqlStore, VERSION_5_29_0) + saveSchemaVersion(sqlStore, Version5290) } } func upgradeDatabaseToVersion530(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_29_0, VERSION_5_30_0) { + if shouldPerformUpgrade(sqlStore, Version5290, Version5300) { sqlStore.CreateColumnIfNotExistsNoDefault("FileInfo", "Content", "longtext", "text") sqlStore.CreateColumnIfNotExists("SidebarCategories", "Muted", "tinyint(1)", "boolean", "0") - saveSchemaVersion(sqlStore, VERSION_5_30_0) + saveSchemaVersion(sqlStore, Version5300) } } func upgradeDatabaseToVersion531(sqlStore *SqlStore) { - if shouldPerformUpgrade(sqlStore, VERSION_5_30_0, VERSION_5_31_0) { - saveSchemaVersion(sqlStore, VERSION_5_31_0) + if shouldPerformUpgrade(sqlStore, Version5300, Version5310) { + saveSchemaVersion(sqlStore, Version5310) } } func upgradeDatabaseToVersion532(sqlStore *SqlStore) { - // if shouldPerformUpgrade(sqlStore, VERSION_5_31_0, VERSION_5_32_0) { + // if shouldPerformUpgrade(sqlStore, Version5310, Version5320) { // allow 10 files per post sqlStore.AlterColumnTypeIfExists("Posts", "FileIds", "text", "varchar(300)") sqlStore.CreateColumnIfNotExistsNoDefault("Channels", "Shared", "tinyint(1)", "boolean") - // saveSchemaVersion(sqlStore, VERSION_5_32_0) + // saveSchemaVersion(sqlStore, Version5320) // } } diff --git a/store/sqlstore/upgrade_test.go b/store/sqlstore/upgrade_test.go index d27e2644b3..700e6a65e3 100644 --- a/store/sqlstore/upgrade_test.go +++ b/store/sqlstore/upgrade_test.go @@ -34,26 +34,26 @@ func TestStoreUpgrade(t *testing.T) { }) t.Run("upgrade from earliest supported version", func(t *testing.T) { - saveSchemaVersion(sqlStore, VERSION_3_0_0) - err := upgradeDatabase(sqlStore, CURRENT_SCHEMA_VERSION) + saveSchemaVersion(sqlStore, Version300) + err := upgradeDatabase(sqlStore, CurrentSchemaVersion) require.NoError(t, err) - require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion()) + require.Equal(t, CurrentSchemaVersion, sqlStore.GetCurrentSchemaVersion()) }) t.Run("upgrade from no existing version", func(t *testing.T) { saveSchemaVersion(sqlStore, "") - err := upgradeDatabase(sqlStore, CURRENT_SCHEMA_VERSION) + err := upgradeDatabase(sqlStore, CurrentSchemaVersion) require.NoError(t, err) - require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion()) + require.Equal(t, CurrentSchemaVersion, sqlStore.GetCurrentSchemaVersion()) }) t.Run("upgrade schema running earlier minor version", func(t *testing.T) { saveSchemaVersion(sqlStore, "5.1.0") err := upgradeDatabase(sqlStore, "5.8.0") require.NoError(t, err) - // Assert CURRENT_SCHEMA_VERSION, not 5.8.0, since the migrations will move + // Assert CurrentSchemaVersion, not 5.8.0, since the migrations will move // past 5.8.0 regardless of the input parameter. - require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion()) + require.Equal(t, CurrentSchemaVersion, sqlStore.GetCurrentSchemaVersion()) }) t.Run("upgrade schema running later minor version", func(t *testing.T) { @@ -65,9 +65,9 @@ func TestStoreUpgrade(t *testing.T) { t.Run("upgrade schema running earlier major version", func(t *testing.T) { saveSchemaVersion(sqlStore, "4.1.0") - err := upgradeDatabase(sqlStore, CURRENT_SCHEMA_VERSION) + err := upgradeDatabase(sqlStore, CurrentSchemaVersion) require.NoError(t, err) - require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion()) + require.Equal(t, CurrentSchemaVersion, sqlStore.GetCurrentSchemaVersion()) }) t.Run("upgrade schema running later major version", func(t *testing.T) { @@ -84,21 +84,21 @@ func TestSaveSchemaVersion(t *testing.T) { sqlStore := ss.(*SqlStore) t.Run("set earliest version", func(t *testing.T) { - saveSchemaVersion(sqlStore, VERSION_3_0_0) + saveSchemaVersion(sqlStore, Version300) props, err := ss.System().Get() require.Nil(t, err) - require.Equal(t, VERSION_3_0_0, props["Version"]) - require.Equal(t, VERSION_3_0_0, sqlStore.GetCurrentSchemaVersion()) + require.Equal(t, Version300, props["Version"]) + require.Equal(t, Version300, sqlStore.GetCurrentSchemaVersion()) }) t.Run("set current version", func(t *testing.T) { - saveSchemaVersion(sqlStore, CURRENT_SCHEMA_VERSION) + saveSchemaVersion(sqlStore, CurrentSchemaVersion) props, err := ss.System().Get() require.Nil(t, err) - require.Equal(t, CURRENT_SCHEMA_VERSION, props["Version"]) - require.Equal(t, CURRENT_SCHEMA_VERSION, sqlStore.GetCurrentSchemaVersion()) + require.Equal(t, CurrentSchemaVersion, props["Version"]) + require.Equal(t, CurrentSchemaVersion, sqlStore.GetCurrentSchemaVersion()) }) }) } diff --git a/store/sqlstore/user_store.go b/store/sqlstore/user_store.go index b82889e5f3..0254e7981b 100644 --- a/store/sqlstore/user_store.go +++ b/store/sqlstore/user_store.go @@ -20,14 +20,14 @@ import ( ) const ( - MAX_GROUP_CHANNELS_FOR_PROFILES = 50 + MaxGroupChannelsForProfiles = 50 ) var ( - USER_SEARCH_TYPE_NAMES_NO_FULL_NAME = []string{"Username", "Nickname"} - USER_SEARCH_TYPE_NAMES = []string{"Username", "FirstName", "LastName", "Nickname"} - USER_SEARCH_TYPE_ALL_NO_FULL_NAME = []string{"Username", "Nickname", "Email"} - USER_SEARCH_TYPE_ALL = []string{"Username", "FirstName", "LastName", "Nickname", "Email"} + UserSearchTypeNames_NO_FULL_NAME = []string{"Username", "Nickname"} + UserSearchTypeNames = []string{"Username", "FirstName", "LastName", "Nickname"} + UserSearchTypeAll_NO_FULL_NAME = []string{"Username", "Nickname", "Email"} + UserSearchTypeAll = []string{"Username", "FirstName", "LastName", "Nickname", "Email"} ) type SqlUserStore struct { @@ -92,10 +92,10 @@ func (us SqlUserStore) createIndexesIfNotExists() { us.CreateIndexIfNotExists("idx_users_lastname_lower_textpattern", "Users", "lower(LastName) text_pattern_ops") } - us.CreateFullTextIndexIfNotExists("idx_users_all_txt", "Users", strings.Join(USER_SEARCH_TYPE_ALL, ", ")) - us.CreateFullTextIndexIfNotExists("idx_users_all_no_full_name_txt", "Users", strings.Join(USER_SEARCH_TYPE_ALL_NO_FULL_NAME, ", ")) - us.CreateFullTextIndexIfNotExists("idx_users_names_txt", "Users", strings.Join(USER_SEARCH_TYPE_NAMES, ", ")) - us.CreateFullTextIndexIfNotExists("idx_users_names_no_full_name_txt", "Users", strings.Join(USER_SEARCH_TYPE_NAMES_NO_FULL_NAME, ", ")) + us.CreateFullTextIndexIfNotExists("idx_users_all_txt", "Users", strings.Join(UserSearchTypeAll, ", ")) + us.CreateFullTextIndexIfNotExists("idx_users_all_no_full_name_txt", "Users", strings.Join(UserSearchTypeAll_NO_FULL_NAME, ", ")) + us.CreateFullTextIndexIfNotExists("idx_users_names_txt", "Users", strings.Join(UserSearchTypeNames, ", ")) + us.CreateFullTextIndexIfNotExists("idx_users_names_no_full_name_txt", "Users", strings.Join(UserSearchTypeNames_NO_FULL_NAME, ", ")) } func (us SqlUserStore) Save(user *model.User) (*model.User, error) { @@ -936,8 +936,8 @@ type UserWithChannel struct { } func (us SqlUserStore) GetProfileByGroupChannelIdsForUser(userId string, channelIds []string) (map[string][]*model.User, error) { - if len(channelIds) > MAX_GROUP_CHANNELS_FOR_PROFILES { - channelIds = channelIds[0:MAX_GROUP_CHANNELS_FOR_PROFILES] + if len(channelIds) > MaxGroupChannelsForProfiles { + channelIds = channelIds[0:MaxGroupChannelsForProfiles] } isMemberQuery := fmt.Sprintf(` @@ -1402,15 +1402,15 @@ func (us SqlUserStore) performSearch(query sq.SelectBuilder, term string, option var searchType []string if options.AllowEmails { if options.AllowFullNames { - searchType = USER_SEARCH_TYPE_ALL + searchType = UserSearchTypeAll } else { - searchType = USER_SEARCH_TYPE_ALL_NO_FULL_NAME + searchType = UserSearchTypeAll_NO_FULL_NAME } } else { if options.AllowFullNames { - searchType = USER_SEARCH_TYPE_NAMES + searchType = UserSearchTypeNames } else { - searchType = USER_SEARCH_TYPE_NAMES_NO_FULL_NAME + searchType = UserSearchTypeNames_NO_FULL_NAME } } diff --git a/store/storetest/channel_store.go b/store/storetest/channel_store.go index f006347d3c..0f4de2f7a3 100644 --- a/store/storetest/channel_store.go +++ b/store/storetest/channel_store.go @@ -219,7 +219,7 @@ func testChannelStoreSaveDirectChannel(t *testing.T, ss store.Store, s SqlStore) returnedChannel, nErr := ss.Channel().SaveDirectChannel(&o1a, &m1, &m2) require.NotNil(t, nErr, "should've failed to save a duplicate direct channel") var cErr *store.ErrConflict - require.Truef(t, errors.As(nErr, &cErr), "should've returned CHANNEL_EXISTS_ERROR") + require.Truef(t, errors.As(nErr, &cErr), "should've returned ChannelExistsError") require.Equal(t, o1.Id, returnedChannel.Id, "should've failed to save a duplicate direct channel") // Attempt to save a non-direct channel diff --git a/store/storetest/user_store.go b/store/storetest/user_store.go index 071165ef0e..ecc6581421 100644 --- a/store/storetest/user_store.go +++ b/store/storetest/user_store.go @@ -17,8 +17,8 @@ import ( ) const ( - DAY_MILLISECONDS = 24 * 60 * 60 * 1000 - MONTH_MILLISECONDS = 31 * DAY_MILLISECONDS + DayMilliseconds = 24 * 60 * 60 * 1000 + MonthMilliseconds = 31 * DayMilliseconds ) func cleanupStatusStore(t *testing.T, s SqlStore) { @@ -3870,8 +3870,8 @@ func testUserStoreAnalyticsActiveCount(t *testing.T, ss store.Store, s SqlStore) require.Nil(t, nErr) millis := model.GetMillis() - millisTwoDaysAgo := model.GetMillis() - (2 * DAY_MILLISECONDS) - millisTwoMonthsAgo := model.GetMillis() - (2 * MONTH_MILLISECONDS) + millisTwoDaysAgo := model.GetMillis() - (2 * DayMilliseconds) + millisTwoMonthsAgo := model.GetMillis() - (2 * MonthMilliseconds) // u0 last activity status is two months ago. // u1 last activity status is two days ago. @@ -3883,27 +3883,27 @@ func testUserStoreAnalyticsActiveCount(t *testing.T, ss store.Store, s SqlStore) require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u4.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millis})) // Daily counts (without bots) - count, err := ss.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: true}) + count, err := ss.User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: true}) require.Nil(t, err) assert.Equal(t, int64(2), count) // Daily counts (with bots) - count, err = ss.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: true, IncludeDeleted: true}) + count, err = ss.User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: true, IncludeDeleted: true}) require.Nil(t, err) assert.Equal(t, int64(3), count) // Monthly counts (without bots) - count, err = ss.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: true}) + count, err = ss.User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: true}) require.Nil(t, err) assert.Equal(t, int64(3), count) // Monthly counts - (with bots) - count, err = ss.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: true, IncludeDeleted: true}) + count, err = ss.User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: true, IncludeDeleted: true}) require.Nil(t, err) assert.Equal(t, int64(4), count) // Monthly counts - (with bots, excluding deleted) - count, err = ss.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: true, IncludeDeleted: false}) + count, err = ss.User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: true, IncludeDeleted: false}) require.Nil(t, err) assert.Equal(t, int64(4), count) } @@ -3955,8 +3955,8 @@ func testUserStoreAnalyticsActiveCountForPeriod(t *testing.T, ss store.Store, s require.Nil(t, nErr) millis := model.GetMillis() - millisTwoDaysAgo := model.GetMillis() - (2 * DAY_MILLISECONDS) - millisTwoMonthsAgo := model.GetMillis() - (2 * MONTH_MILLISECONDS) + millisTwoDaysAgo := model.GetMillis() - (2 * DayMilliseconds) + millisTwoMonthsAgo := model.GetMillis() - (2 * MonthMilliseconds) // u0 last activity status is two months ago. // u1 last activity status is one month ago @@ -3965,9 +3965,9 @@ func testUserStoreAnalyticsActiveCountForPeriod(t *testing.T, ss store.Store, s // u3 last activity is within last day // u4 last activity is within last day require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u0.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoMonthsAgo})) - require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoMonthsAgo + MONTH_MILLISECONDS})) + require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u1.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoMonthsAgo + MonthMilliseconds})) require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u2.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoDaysAgo})) - require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoDaysAgo + DAY_MILLISECONDS})) + require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u3.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millisTwoDaysAgo + DayMilliseconds})) require.Nil(t, ss.Status().SaveOrUpdate(&model.Status{UserId: u4.Id, Status: model.STATUS_OFFLINE, LastActivityAt: millis})) // Two months to two days (without bots) diff --git a/utils/logger.go b/utils/logger.go index 8292d5eee6..49a63936c4 100644 --- a/utils/logger.go +++ b/utils/logger.go @@ -13,9 +13,9 @@ import ( ) const ( - LOG_ROTATE_SIZE = 10000 - LOG_FILENAME = "mattermost.log" - LOG_NOTIFICATION_FILENAME = "notifications.log" + LogRotateSize = 10000 + LogFilename = "mattermost.log" + LogNotificationFilename = "notifications.log" ) type fileLocationFunc func(string) string @@ -37,7 +37,7 @@ func GetLogFileLocation(fileLocation string) string { fileLocation, _ = fileutils.FindDir("logs") } - return filepath.Join(fileLocation, LOG_FILENAME) + return filepath.Join(fileLocation, LogFilename) } func GetNotificationsLogFileLocation(fileLocation string) string { @@ -45,7 +45,7 @@ func GetNotificationsLogFileLocation(fileLocation string) string { fileLocation, _ = fileutils.FindDir("logs") } - return filepath.Join(fileLocation, LOG_NOTIFICATION_FILENAME) + return filepath.Join(fileLocation, LogNotificationFilename) } func GetLogSettingsFromNotificationsLogSettings(notificationLogSettings *model.NotificationLogSettings) *model.LogSettings { diff --git a/utils/textgeneration.go b/utils/textgeneration.go index f2cf1181ff..db9e3af62e 100644 --- a/utils/textgeneration.go +++ b/utils/textgeneration.go @@ -14,7 +14,7 @@ const ( ) // Strings that should pass as acceptable posts -var FUZZY_STRINGS_POSTS = []string{ +var FuzzyStringsPosts = []string{ `**[1] - [Markdown Tests]** _italics_ more _italics_ @@ -367,7 +367,7 @@ This is a link to http://example.com. } // Strings that should pass as acceptable team names -var FUZZY_STRINGS_NAMES = []string{ +var FuzzyStringsNames = []string{ "*", "?", ".", @@ -426,7 +426,7 @@ var FUZZY_STRINGS_NAMES = []string{ } // Strings that should pass as acceptable emails -var FUZZY_STRINGS_EMAILS = []string{ +var FuzzyStringsEmails = []string{ "sue@thatmightbe", "sue@thatmightbe.c", "sue@thatmightbe.co", @@ -439,7 +439,7 @@ var FUZZY_STRINGS_EMAILS = []string{ } // Lovely giberish for all to use -const GIBBERISH_TEXT = ` +const GibberishText = ` Thus one besides much goodness shyly far some hyena overtook since rhinoceros nodded withdrew wombat before deserved apart a alongside the far dalmatian less ouch where yet a salmon. Then jeez far marginal hey aboard more as leaned much oversold that inside spoke showed much went crud close save so and and after and informally much lion commendably less conductive oh excepting conductive compassionate jeepers hey a much leopard alas woolly untruthful outside snug rashly one cunning past fabulous adjusted far woodchuck and and indecisive crud loving exotic less resolute ladybug sprang drank under following far the as hence passably stolidly jeez the inset spaciously more cozily fishily the hey alas petted one audible yikes dear preparatory darn goldfinch gosh a then as moth more guinea. Timid mislaid as salamander yikes alas ouch much that goldfinch shark in before instead dear one swore vivid versus one until regardless sang panther tolerable much preparatory hardily shuddered where coquettish far sheep coarsely exaggerated preparatory because cordial awesome gradually nutria that dear mocking behind off staunchly regarding a the komodo crud shrewd well jeez iguanodon strove strived and moodily and sought and and mounted gosh aboard crud spitefully boa. @@ -481,7 +481,7 @@ func RandString(l int, charset string) string { // } // func FuzzEmail() string { -// return FUZZY_STRINGS_EMAILS[RandIntFromRange(Range{0, len(FUZZY_STRINGS_EMAILS) - 1})] +// return FuzzyStringsEmails[RandIntFromRange(Range{0, len(FuzzyStringsEmails) - 1})] // } func RandomName(length Range, charset string) string { @@ -490,7 +490,7 @@ func RandomName(length Range, charset string) string { } func FuzzName() string { - return FUZZY_STRINGS_NAMES[RandIntFromRange(Range{0, len(FUZZY_STRINGS_NAMES) - 1})] + return FuzzyStringsNames[RandIntFromRange(Range{0, len(FuzzyStringsNames) - 1})] } // Random selection of text for post @@ -498,12 +498,12 @@ func RandomText(length Range, hashtags Range, mentions Range, users []string) st textLength := RandIntFromRange(length) numHashtags := RandIntFromRange(hashtags) numMentions := RandIntFromRange(mentions) - if textLength > len(GIBBERISH_TEXT) || textLength < 0 { - textLength = len(GIBBERISH_TEXT) + if textLength > len(GibberishText) || textLength < 0 { + textLength = len(GibberishText) } - startPosition := RandIntFromRange(Range{0, len(GIBBERISH_TEXT) - textLength - 1}) + startPosition := RandIntFromRange(Range{0, len(GibberishText) - textLength - 1}) - words := strings.Split(GIBBERISH_TEXT[startPosition:startPosition+textLength], " ") + words := strings.Split(GibberishText[startPosition:startPosition+textLength], " ") for i := 0; i < numHashtags; i++ { randword := RandIntFromRange(Range{0, len(words) - 1}) words = append(words, " #"+words[randword]) @@ -525,5 +525,5 @@ func RandomText(length Range, hashtags Range, mentions Range, users []string) st } func FuzzPost() string { - return FUZZY_STRINGS_POSTS[RandIntFromRange(Range{0, len(FUZZY_STRINGS_POSTS) - 1})] + return FuzzyStringsPosts[RandIntFromRange(Range{0, len(FuzzyStringsPosts) - 1})] } diff --git a/web/params.go b/web/params.go index a3baf465ff..2b8adc21c8 100644 --- a/web/params.go +++ b/web/params.go @@ -13,13 +13,13 @@ import ( ) const ( - PAGE_DEFAULT = 0 - PER_PAGE_DEFAULT = 60 - PER_PAGE_MAXIMUM = 200 - LOGS_PER_PAGE_DEFAULT = 10000 - LOGS_PER_PAGE_MAXIMUM = 10000 - LIMIT_DEFAULT = 60 - LIMIT_MAXIMUM = 200 + PageDefault = 0 + PerPageDefault = 60 + PerPageMaximum = 200 + LogsPerPageDefault = 10000 + LogsPerPageMaximum = 10000 + LimitDefault = 60 + LimitMaximum = 200 ) type Params struct { @@ -232,7 +232,7 @@ func ParamsFromRequest(r *http.Request) *Params { params.Scope = query.Get("scope") if val, err := strconv.Atoi(query.Get("page")); err != nil || val < 0 { - params.Page = PAGE_DEFAULT + params.Page = PageDefault } else { params.Page = val } @@ -248,33 +248,33 @@ func ParamsFromRequest(r *http.Request) *Params { } if val, err := strconv.Atoi(query.Get("per_page")); err != nil || val < 0 { - params.PerPage = PER_PAGE_DEFAULT - } else if val > PER_PAGE_MAXIMUM { - params.PerPage = PER_PAGE_MAXIMUM + params.PerPage = PerPageDefault + } else if val > PerPageMaximum { + params.PerPage = PerPageMaximum } else { params.PerPage = val } if val, err := strconv.Atoi(query.Get("logs_per_page")); err != nil || val < 0 { - params.LogsPerPage = LOGS_PER_PAGE_DEFAULT - } else if val > LOGS_PER_PAGE_MAXIMUM { - params.LogsPerPage = LOGS_PER_PAGE_MAXIMUM + params.LogsPerPage = LogsPerPageDefault + } else if val > LogsPerPageMaximum { + params.LogsPerPage = LogsPerPageMaximum } else { params.LogsPerPage = val } if val, err := strconv.Atoi(query.Get("limit_after")); err != nil || val < 0 { - params.LimitAfter = LIMIT_DEFAULT - } else if val > LIMIT_MAXIMUM { - params.LimitAfter = LIMIT_MAXIMUM + params.LimitAfter = LimitDefault + } else if val > LimitMaximum { + params.LimitAfter = LimitMaximum } else { params.LimitAfter = val } if val, err := strconv.Atoi(query.Get("limit_before")); err != nil || val < 0 { - params.LimitBefore = LIMIT_DEFAULT - } else if val > LIMIT_MAXIMUM { - params.LimitBefore = LIMIT_MAXIMUM + params.LimitBefore = LimitDefault + } else if val > LimitMaximum { + params.LimitBefore = LimitMaximum } else { params.LimitBefore = val }