From 092e53ace2cf80794e12a38daebe54829c32a22c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jes=C3=BAs=20Espino?= Date: Tue, 7 Jan 2020 10:47:03 +0100 Subject: [PATCH] Fix inconsistencies in variable names for struct methods (#13561) --- app/notification.go | 26 +-- app/slack.go | 14 +- app/web_conn.go | 198 ++++++++++----------- go.mod | 4 +- model/access.go | 6 +- model/compliance.go | 56 +++--- model/config.go | 270 ++++++++++++++--------------- model/file_info.go | 52 +++--- model/guest_invite.go | 10 +- model/job.go | 8 +- model/post.go | 12 +- model/role.go | 30 ++-- model/team.go | 18 +- model/team_search.go | 4 +- model/user.go | 12 +- model/websocket_message.go | 10 +- plugin/client_rpc.go | 6 +- store/sqlstore/compliance_store.go | 8 +- store/sqlstore/file_info_store.go | 10 +- store/sqlstore/supplier.go | 20 +-- store/sqlstore/team_store.go | 4 +- store/sqlstore/user_store.go | 4 +- 22 files changed, 391 insertions(+), 391 deletions(-) diff --git a/app/notification.go b/app/notification.go index d18b8b0ee2..925b9c239e 100644 --- a/app/notification.go +++ b/app/notification.go @@ -738,31 +738,31 @@ func (n *PostNotification) GetSenderName(userNameFormat string, overridesAllowed } // checkForMention checks if there is a mention to a specific user or to the keywords here / channel / all -func (e *ExplicitMentions) checkForMention(word string, keywords map[string][]string) bool { +func (m *ExplicitMentions) checkForMention(word string, keywords map[string][]string) bool { var mentionType MentionType switch strings.ToLower(word) { case "@here": - e.HereMentioned = true + m.HereMentioned = true mentionType = ChannelMention case "@channel": - e.ChannelMentioned = true + m.ChannelMentioned = true mentionType = ChannelMention case "@all": - e.AllMentioned = true + m.AllMentioned = true mentionType = ChannelMention default: mentionType = KeywordMention } if ids, match := keywords[strings.ToLower(word)]; match { - e.addMentions(ids, mentionType) + m.addMentions(ids, mentionType) return true } // Case-sensitive check for first name if ids, match := keywords[word]; match { - e.addMentions(ids, mentionType) + m.addMentions(ids, mentionType) return true } @@ -791,7 +791,7 @@ func isKeywordMultibyte(keywords map[string][]string, word string) ([]string, bo } // Processes text to filter mentioned users and other potential mentions -func (e *ExplicitMentions) processText(text string, keywords map[string][]string) { +func (m *ExplicitMentions) processText(text string, keywords map[string][]string) { systemMentions := map[string]bool{"@here": true, "@channel": true, "@all": true} for _, word := range strings.FieldsFunc(text, func(c rune) bool { @@ -805,7 +805,7 @@ func (e *ExplicitMentions) processText(text string, keywords map[string][]string word = strings.TrimLeft(word, ":.-_") - if e.checkForMention(word, keywords) { + if m.checkForMention(word, keywords) { continue } @@ -814,7 +814,7 @@ func (e *ExplicitMentions) processText(text string, keywords map[string][]string for len(wordWithoutSuffix) > 0 && strings.LastIndexAny(wordWithoutSuffix, ".-:_") == (len(wordWithoutSuffix)-1) { wordWithoutSuffix = wordWithoutSuffix[0 : len(wordWithoutSuffix)-1] - if e.checkForMention(wordWithoutSuffix, keywords) { + if m.checkForMention(wordWithoutSuffix, keywords) { foundWithoutSuffix = true break } @@ -825,7 +825,7 @@ func (e *ExplicitMentions) processText(text string, keywords map[string][]string } if _, ok := systemMentions[word]; !ok && strings.HasPrefix(word, "@") { - e.OtherPotentialMentions = append(e.OtherPotentialMentions, word[1:]) + m.OtherPotentialMentions = append(m.OtherPotentialMentions, word[1:]) } else if strings.ContainsAny(word, ".-:") { // This word contains a character that may be the end of a sentence, so split further splitWords := strings.FieldsFunc(word, func(c rune) bool { @@ -833,17 +833,17 @@ func (e *ExplicitMentions) processText(text string, keywords map[string][]string }) for _, splitWord := range splitWords { - if e.checkForMention(splitWord, keywords) { + if m.checkForMention(splitWord, keywords) { continue } if _, ok := systemMentions[splitWord]; !ok && strings.HasPrefix(splitWord, "@") { - e.OtherPotentialMentions = append(e.OtherPotentialMentions, splitWord[1:]) + m.OtherPotentialMentions = append(m.OtherPotentialMentions, splitWord[1:]) } } } if ids, match := isKeywordMultibyte(keywords, word); match { - e.addMentions(ids, KeywordMention) + m.addMentions(ids, KeywordMention) } } } diff --git a/app/slack.go b/app/slack.go index 68987e1efe..61878c414b 100644 --- a/app/slack.go +++ b/app/slack.go @@ -24,17 +24,17 @@ func (a *App) ProcessSlackText(text string) string { // can be found in the text attribute, or in the pretext, text, title and value // attributes of the attachment structure. The Slack attachment structure is // documented here: https://api.slack.com/docs/attachments -func (app *App) ProcessSlackAttachments(a []*model.SlackAttachment) []*model.SlackAttachment { - var nonNilAttachments = model.StringifySlackFieldValue(a) - for _, attachment := range a { - attachment.Pretext = app.ProcessSlackText(attachment.Pretext) - attachment.Text = app.ProcessSlackText(attachment.Text) - attachment.Title = app.ProcessSlackText(attachment.Title) +func (a *App) ProcessSlackAttachments(attachments []*model.SlackAttachment) []*model.SlackAttachment { + var nonNilAttachments = model.StringifySlackFieldValue(attachments) + for _, attachment := range attachments { + attachment.Pretext = a.ProcessSlackText(attachment.Pretext) + attachment.Text = a.ProcessSlackText(attachment.Text) + attachment.Title = a.ProcessSlackText(attachment.Title) for _, field := range attachment.Fields { if field.Value != nil { // Ensure the value is set to a string if it is set - field.Value = app.ProcessSlackText(fmt.Sprintf("%v", field.Value)) + field.Value = a.ProcessSlackText(fmt.Sprintf("%v", field.Value)) } } } diff --git a/app/web_conn.go b/app/web_conn.go index b19905aac2..a605f3f151 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -80,60 +80,60 @@ func (wc *WebConn) Close() { <-wc.pumpFinished } -func (c *WebConn) GetSessionExpiresAt() int64 { - return atomic.LoadInt64(&c.sessionExpiresAt) +func (wc *WebConn) GetSessionExpiresAt() int64 { + return atomic.LoadInt64(&wc.sessionExpiresAt) } -func (c *WebConn) SetSessionExpiresAt(v int64) { - atomic.StoreInt64(&c.sessionExpiresAt, v) +func (wc *WebConn) SetSessionExpiresAt(v int64) { + atomic.StoreInt64(&wc.sessionExpiresAt, v) } -func (c *WebConn) GetSessionToken() string { - return c.sessionToken.Load().(string) +func (wc *WebConn) GetSessionToken() string { + return wc.sessionToken.Load().(string) } -func (c *WebConn) SetSessionToken(v string) { - c.sessionToken.Store(v) +func (wc *WebConn) SetSessionToken(v string) { + wc.sessionToken.Store(v) } -func (c *WebConn) GetSession() *model.Session { - return c.session.Load().(*model.Session) +func (wc *WebConn) GetSession() *model.Session { + return wc.session.Load().(*model.Session) } -func (c *WebConn) SetSession(v *model.Session) { +func (wc *WebConn) SetSession(v *model.Session) { if v != nil { v = v.DeepCopy() } - c.session.Store(v) + wc.session.Store(v) } -func (c *WebConn) Pump() { +func (wc *WebConn) Pump() { ch := make(chan struct{}) go func() { - c.writePump() + wc.writePump() close(ch) }() - c.readPump() - c.closeOnce.Do(func() { - close(c.endWritePump) + wc.readPump() + wc.closeOnce.Do(func() { + close(wc.endWritePump) }) <-ch - c.App.HubUnregister(c) - close(c.pumpFinished) + wc.App.HubUnregister(wc) + close(wc.pumpFinished) } -func (c *WebConn) readPump() { +func (wc *WebConn) readPump() { defer func() { - c.WebSocket.Close() + wc.WebSocket.Close() }() - c.WebSocket.SetReadLimit(model.SOCKET_MAX_MESSAGE_SIZE_KB) - c.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) - c.WebSocket.SetPongHandler(func(string) error { - c.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) - if c.IsAuthenticated() { - c.App.Srv.Go(func() { - c.App.SetStatusAwayIfNeeded(c.UserId, false) + wc.WebSocket.SetReadLimit(model.SOCKET_MAX_MESSAGE_SIZE_KB) + wc.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) + wc.WebSocket.SetPongHandler(func(string) error { + wc.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) + if wc.IsAuthenticated() { + wc.App.Srv.Go(func() { + wc.App.SetStatusAwayIfNeeded(wc.UserId, false) }) } return nil @@ -141,49 +141,49 @@ func (c *WebConn) readPump() { for { var req model.WebSocketRequest - if err := c.WebSocket.ReadJSON(&req); err != nil { + if err := wc.WebSocket.ReadJSON(&req); err != nil { // browsers will appear as CloseNoStatusReceived if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseNoStatusReceived) { - mlog.Debug("websocket.read: client side closed socket", mlog.String("user_id", c.UserId)) + mlog.Debug("websocket.read: client side closed socket", mlog.String("user_id", wc.UserId)) } else { - mlog.Debug("websocket.read: closing websocket", mlog.String("user_id", c.UserId), mlog.Err(err)) + mlog.Debug("websocket.read: closing websocket", mlog.String("user_id", wc.UserId), mlog.Err(err)) } return } - c.App.Srv.WebSocketRouter.ServeWebSocket(c, &req) + wc.App.Srv.WebSocketRouter.ServeWebSocket(wc, &req) } } -func (c *WebConn) writePump() { +func (wc *WebConn) writePump() { ticker := time.NewTicker(PING_PERIOD) authTicker := time.NewTicker(AUTH_TIMEOUT) defer func() { ticker.Stop() authTicker.Stop() - c.WebSocket.Close() + wc.WebSocket.Close() }() for { select { - case msg, ok := <-c.Send: + case msg, ok := <-wc.Send: if !ok { - c.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT)) - c.WebSocket.WriteMessage(websocket.CloseMessage, []byte{}) + wc.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT)) + wc.WebSocket.WriteMessage(websocket.CloseMessage, []byte{}) return } evt, evtOk := msg.(*model.WebSocketEvent) skipSend := false - if len(c.Send) >= SEND_SLOW_WARN { + if len(wc.Send) >= SEND_SLOW_WARN { // When the pump starts to get slow we'll drop non-critical messages if msg.EventType() == model.WEBSOCKET_EVENT_TYPING || msg.EventType() == model.WEBSOCKET_EVENT_STATUS_CHANGE || msg.EventType() == model.WEBSOCKET_EVENT_CHANNEL_VIEWED { mlog.Info( "websocket.slow: dropping message", - mlog.String("user_id", c.UserId), + mlog.String("user_id", wc.UserId), mlog.String("type", msg.EventType()), mlog.String("channel_id", evt.GetBroadcast().ChannelId), ) @@ -194,18 +194,18 @@ func (c *WebConn) writePump() { if !skipSend { var msgBytes []byte if evtOk { - cpyEvt := evt.SetSequence(c.Sequence) + cpyEvt := evt.SetSequence(wc.Sequence) msgBytes = []byte(cpyEvt.ToJson()) - c.Sequence++ + wc.Sequence++ } else { msgBytes = []byte(msg.ToJson()) } - if len(c.Send) >= SEND_DEADLOCK_WARN { + if len(wc.Send) >= SEND_DEADLOCK_WARN { if evtOk { mlog.Warn( "websocket.full", - mlog.String("user_id", c.UserId), + mlog.String("user_id", wc.UserId), mlog.String("type", msg.EventType()), mlog.String("channel_id", evt.GetBroadcast().ChannelId), mlog.Int("size", len(msg.ToJson())), @@ -213,49 +213,49 @@ func (c *WebConn) writePump() { } else { mlog.Warn( "websocket.full", - mlog.String("user_id", c.UserId), + mlog.String("user_id", wc.UserId), mlog.String("type", msg.EventType()), mlog.Int("size", len(msg.ToJson())), ) } } - c.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT)) - if err := c.WebSocket.WriteMessage(websocket.TextMessage, msgBytes); err != nil { + wc.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT)) + if err := wc.WebSocket.WriteMessage(websocket.TextMessage, msgBytes); err != nil { // browsers will appear as CloseNoStatusReceived if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseNoStatusReceived) { - mlog.Debug("websocket.send: client side closed socket", mlog.String("user_id", c.UserId)) + mlog.Debug("websocket.send: client side closed socket", mlog.String("user_id", wc.UserId)) } else { - mlog.Debug("websocket.send: closing websocket", mlog.String("user_id", c.UserId), mlog.Err(err)) + mlog.Debug("websocket.send: closing websocket", mlog.String("user_id", wc.UserId), mlog.Err(err)) } return } - if c.App.Metrics != nil { - c.App.Srv.Go(func() { - c.App.Metrics.IncrementWebSocketBroadcast(msg.EventType()) + if wc.App.Metrics != nil { + wc.App.Srv.Go(func() { + wc.App.Metrics.IncrementWebSocketBroadcast(msg.EventType()) }) } } case <-ticker.C: - c.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT)) - if err := c.WebSocket.WriteMessage(websocket.PingMessage, []byte{}); err != nil { + wc.WebSocket.SetWriteDeadline(time.Now().Add(WRITE_WAIT)) + if err := wc.WebSocket.WriteMessage(websocket.PingMessage, []byte{}); err != nil { // browsers will appear as CloseNoStatusReceived if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseNoStatusReceived) { - mlog.Debug("websocket.ticker: client side closed socket", mlog.String("user_id", c.UserId)) + mlog.Debug("websocket.ticker: client side closed socket", mlog.String("user_id", wc.UserId)) } else { - mlog.Debug("websocket.ticker: closing websocket", mlog.String("user_id", c.UserId), mlog.Err(err)) + mlog.Debug("websocket.ticker: closing websocket", mlog.String("user_id", wc.UserId), mlog.Err(err)) } return } - case <-c.endWritePump: + case <-wc.endWritePump: return case <-authTicker.C: - if c.GetSessionToken() == "" { - mlog.Debug("websocket.authTicker: did not authenticate", mlog.Any("ip_address", c.WebSocket.RemoteAddr())) + if wc.GetSessionToken() == "" { + mlog.Debug("websocket.authTicker: did not authenticate", mlog.Any("ip_address", wc.WebSocket.RemoteAddr())) return } authTicker.Stop() @@ -263,43 +263,43 @@ func (c *WebConn) writePump() { } } -func (webCon *WebConn) InvalidateCache() { - webCon.AllChannelMembers = nil - webCon.LastAllChannelMembersTime = 0 - webCon.SetSession(nil) - webCon.SetSessionExpiresAt(0) +func (wc *WebConn) InvalidateCache() { + wc.AllChannelMembers = nil + wc.LastAllChannelMembersTime = 0 + wc.SetSession(nil) + wc.SetSessionExpiresAt(0) } -func (webCon *WebConn) IsAuthenticated() bool { +func (wc *WebConn) IsAuthenticated() bool { // Check the expiry to see if we need to check for a new session - if webCon.GetSessionExpiresAt() < model.GetMillis() { - if webCon.GetSessionToken() == "" { + if wc.GetSessionExpiresAt() < model.GetMillis() { + if wc.GetSessionToken() == "" { return false } - session, err := webCon.App.GetSession(webCon.GetSessionToken()) + session, err := wc.App.GetSession(wc.GetSessionToken()) if err != nil { mlog.Error("Invalid session.", mlog.Err(err)) - webCon.SetSessionToken("") - webCon.SetSession(nil) - webCon.SetSessionExpiresAt(0) + wc.SetSessionToken("") + wc.SetSession(nil) + wc.SetSessionExpiresAt(0) return false } - webCon.SetSession(session) - webCon.SetSessionExpiresAt(session.ExpiresAt) + wc.SetSession(session) + wc.SetSessionExpiresAt(session.ExpiresAt) } return true } -func (webCon *WebConn) SendHello() { - msg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_HELLO, "", "", webCon.UserId, nil) - msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, webCon.App.ClientConfigHash(), webCon.App.License() != nil)) - webCon.Send <- msg +func (wc *WebConn) SendHello() { + msg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_HELLO, "", "", wc.UserId, nil) + msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, wc.App.ClientConfigHash(), wc.App.License() != nil)) + wc.Send <- msg } -func (webCon *WebConn) shouldSendEventToGuest(msg *model.WebSocketEvent) bool { +func (wc *WebConn) shouldSendEventToGuest(msg *model.WebSocketEvent) bool { var userId string var canSee bool @@ -312,7 +312,7 @@ func (webCon *WebConn) shouldSendEventToGuest(msg *model.WebSocketEvent) bool { return true } - canSee, err := webCon.App.UserCanSeeOtherUser(webCon.UserId, userId) + canSee, err := wc.App.UserCanSeeOtherUser(wc.UserId, userId) if err != nil { mlog.Error("webhub.shouldSendEvent.", mlog.Err(err)) return false @@ -321,9 +321,9 @@ func (webCon *WebConn) shouldSendEventToGuest(msg *model.WebSocketEvent) bool { return canSee } -func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { +func (wc *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { // IMPORTANT: Do not send event if WebConn does not have a session - if !webCon.IsAuthenticated() { + if !wc.IsAuthenticated() { return false } @@ -331,7 +331,7 @@ func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { // see sensitive data. Prevents admin clients from receiving events with bad data var hasReadPrivateDataPermission *bool if msg.GetBroadcast().ContainsSanitizedData { - hasReadPrivateDataPermission = model.NewBool(webCon.App.RolesGrantPermission(webCon.GetSession().GetUserRoles(), model.PERMISSION_MANAGE_SYSTEM.Id)) + hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PERMISSION_MANAGE_SYSTEM.Id)) if *hasReadPrivateDataPermission { return false @@ -341,7 +341,7 @@ func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { // If the event contains sensitive data, only send to users with permission to see it if msg.GetBroadcast().ContainsSensitiveData { if hasReadPrivateDataPermission == nil { - hasReadPrivateDataPermission = model.NewBool(webCon.App.RolesGrantPermission(webCon.GetSession().GetUserRoles(), model.PERMISSION_MANAGE_SYSTEM.Id)) + hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PERMISSION_MANAGE_SYSTEM.Id)) } if !*hasReadPrivateDataPermission { @@ -351,34 +351,34 @@ func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { // If the event is destined to a specific user if len(msg.GetBroadcast().UserId) > 0 { - return webCon.UserId == msg.GetBroadcast().UserId + return wc.UserId == msg.GetBroadcast().UserId } // if the user is omitted don't send the message if len(msg.GetBroadcast().OmitUsers) > 0 { - if _, ok := msg.GetBroadcast().OmitUsers[webCon.UserId]; ok { + if _, ok := msg.GetBroadcast().OmitUsers[wc.UserId]; ok { return false } } // Only report events to users who are in the channel for the event if len(msg.GetBroadcast().ChannelId) > 0 { - if model.GetMillis()-webCon.LastAllChannelMembersTime > WEBCONN_MEMBER_CACHE_TIME { - webCon.AllChannelMembers = nil - webCon.LastAllChannelMembersTime = 0 + if model.GetMillis()-wc.LastAllChannelMembersTime > WEBCONN_MEMBER_CACHE_TIME { + wc.AllChannelMembers = nil + wc.LastAllChannelMembersTime = 0 } - if webCon.AllChannelMembers == nil { - result, err := webCon.App.Srv.Store.Channel().GetAllChannelMembersForUser(webCon.UserId, true, false) + if wc.AllChannelMembers == nil { + result, err := wc.App.Srv.Store.Channel().GetAllChannelMembersForUser(wc.UserId, true, false) if err != nil { mlog.Error("webhub.shouldSendEvent.", mlog.Err(err)) return false } - webCon.AllChannelMembers = result - webCon.LastAllChannelMembersTime = model.GetMillis() + wc.AllChannelMembers = result + wc.LastAllChannelMembersTime = model.GetMillis() } - if _, ok := webCon.AllChannelMembers[msg.GetBroadcast().ChannelId]; ok { + if _, ok := wc.AllChannelMembers[msg.GetBroadcast().ChannelId]; ok { return true } return false @@ -386,26 +386,26 @@ func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { // Only report events to users who are in the team for the event if len(msg.GetBroadcast().TeamId) > 0 { - return webCon.IsMemberOfTeam(msg.GetBroadcast().TeamId) + return wc.IsMemberOfTeam(msg.GetBroadcast().TeamId) } - if webCon.GetSession().Props[model.SESSION_PROP_IS_GUEST] == "true" { - return webCon.shouldSendEventToGuest(msg) + if wc.GetSession().Props[model.SESSION_PROP_IS_GUEST] == "true" { + return wc.shouldSendEventToGuest(msg) } return true } -func (webCon *WebConn) IsMemberOfTeam(teamId string) bool { - currentSession := webCon.GetSession() +func (wc *WebConn) IsMemberOfTeam(teamId string) bool { + currentSession := wc.GetSession() if currentSession == nil || len(currentSession.Token) == 0 { - session, err := webCon.App.GetSession(webCon.GetSessionToken()) + session, err := wc.App.GetSession(wc.GetSessionToken()) if err != nil { mlog.Error("Invalid session.", mlog.Err(err)) return false } - webCon.SetSession(session) + wc.SetSession(session) currentSession = session } diff --git a/go.mod b/go.mod index 06318a418d..9b974ef4ce 100644 --- a/go.mod +++ b/go.mod @@ -39,7 +39,7 @@ require ( github.com/icrowley/fake v0.0.0-20180203215853-4178557ae428 github.com/jaytaylor/html2text v0.0.0-20190408195923-01ec452cbe43 github.com/jmoiron/sqlx v1.2.0 - github.com/jonboulle/clockwork v0.1.0 // indirect + github.com/jonboulle/clockwork v0.1.0 github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect github.com/lib/pq v1.2.0 github.com/magiconair/properties v1.8.1 // indirect @@ -68,7 +68,7 @@ require ( github.com/prometheus/common v0.7.0 // indirect github.com/prometheus/procfs v0.0.5 // indirect github.com/rs/cors v1.7.0 - github.com/russellhaering/goxmldsig v0.0.0-20180430223755-7acd5e4a6ef7 // indirect + github.com/russellhaering/goxmldsig v0.0.0-20180430223755-7acd5e4a6ef7 github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd github.com/segmentio/analytics-go v3.1.0+incompatible github.com/segmentio/backo-go v0.0.0-20160424052352-204274ad699c // indirect diff --git a/model/access.go b/model/access.go index 896cdc3f82..bbac36016d 100644 --- a/model/access.go +++ b/model/access.go @@ -60,13 +60,13 @@ func (ad *AccessData) IsValid() *AppError { return nil } -func (me *AccessData) IsExpired() bool { +func (ad *AccessData) IsExpired() bool { - if me.ExpiresAt <= 0 { + if ad.ExpiresAt <= 0 { return false } - if GetMillis() > me.ExpiresAt { + if GetMillis() > ad.ExpiresAt { return true } diff --git a/model/compliance.go b/model/compliance.go index 4b031b90ab..cf1077e2e7 100644 --- a/model/compliance.go +++ b/model/compliance.go @@ -37,61 +37,61 @@ type Compliance struct { type Compliances []Compliance -func (o *Compliance) ToJson() string { - b, _ := json.Marshal(o) +func (c *Compliance) ToJson() string { + b, _ := json.Marshal(c) return string(b) } -func (me *Compliance) PreSave() { - if me.Id == "" { - me.Id = NewId() +func (c *Compliance) PreSave() { + if c.Id == "" { + c.Id = NewId() } - if me.Status == "" { - me.Status = COMPLIANCE_STATUS_CREATED + if c.Status == "" { + c.Status = COMPLIANCE_STATUS_CREATED } - me.Count = 0 - me.Emails = NormalizeEmail(me.Emails) - me.Keywords = strings.ToLower(me.Keywords) + c.Count = 0 + c.Emails = NormalizeEmail(c.Emails) + c.Keywords = strings.ToLower(c.Keywords) - me.CreateAt = GetMillis() + c.CreateAt = GetMillis() } -func (me *Compliance) JobName() string { - jobName := me.Type - if me.Type == COMPLIANCE_TYPE_DAILY { - jobName += "-" + me.Desc +func (c *Compliance) JobName() string { + jobName := c.Type + if c.Type == COMPLIANCE_TYPE_DAILY { + jobName += "-" + c.Desc } - jobName += "-" + me.Id + jobName += "-" + c.Id return jobName } -func (me *Compliance) IsValid() *AppError { +func (c *Compliance) IsValid() *AppError { - if len(me.Id) != 26 { + if len(c.Id) != 26 { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.id.app_error", nil, "", http.StatusBadRequest) } - if me.CreateAt == 0 { + if c.CreateAt == 0 { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.create_at.app_error", nil, "", http.StatusBadRequest) } - if len(me.Desc) > 512 || len(me.Desc) == 0 { + if len(c.Desc) > 512 || len(c.Desc) == 0 { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.desc.app_error", nil, "", http.StatusBadRequest) } - if me.StartAt == 0 { + if c.StartAt == 0 { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.start_at.app_error", nil, "", http.StatusBadRequest) } - if me.EndAt == 0 { + if c.EndAt == 0 { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.end_at.app_error", nil, "", http.StatusBadRequest) } - if me.EndAt <= me.StartAt { + if c.EndAt <= c.StartAt { return NewAppError("Compliance.IsValid", "model.compliance.is_valid.start_end_at.app_error", nil, "", http.StatusBadRequest) } @@ -99,13 +99,13 @@ func (me *Compliance) IsValid() *AppError { } func ComplianceFromJson(data io.Reader) *Compliance { - var o *Compliance - json.NewDecoder(data).Decode(&o) - return o + var c *Compliance + json.NewDecoder(data).Decode(&c) + return c } -func (o Compliances) ToJson() string { - if b, err := json.Marshal(o); err != nil { +func (c Compliances) ToJson() string { + if b, err := json.Marshal(c); err != nil { return "[]" } else { return string(b) diff --git a/model/config.go b/model/config.go index 8597b98417..f23c9ba653 100644 --- a/model/config.go +++ b/model/config.go @@ -2417,36 +2417,36 @@ type ImageProxySettings struct { RemoteImageProxyOptions *string } -func (ips *ImageProxySettings) SetDefaults(ss ServiceSettings) { - if ips.Enable == nil { +func (s *ImageProxySettings) SetDefaults(ss ServiceSettings) { + if s.Enable == nil { if ss.DEPRECATED_DO_NOT_USE_ImageProxyType == nil || *ss.DEPRECATED_DO_NOT_USE_ImageProxyType == "" { - ips.Enable = NewBool(false) + s.Enable = NewBool(false) } else { - ips.Enable = NewBool(true) + s.Enable = NewBool(true) } } - if ips.ImageProxyType == nil { + if s.ImageProxyType == nil { if ss.DEPRECATED_DO_NOT_USE_ImageProxyType == nil || *ss.DEPRECATED_DO_NOT_USE_ImageProxyType == "" { - ips.ImageProxyType = NewString(IMAGE_PROXY_TYPE_LOCAL) + s.ImageProxyType = NewString(IMAGE_PROXY_TYPE_LOCAL) } else { - ips.ImageProxyType = ss.DEPRECATED_DO_NOT_USE_ImageProxyType + s.ImageProxyType = ss.DEPRECATED_DO_NOT_USE_ImageProxyType } } - if ips.RemoteImageProxyURL == nil { + if s.RemoteImageProxyURL == nil { if ss.DEPRECATED_DO_NOT_USE_ImageProxyURL == nil { - ips.RemoteImageProxyURL = NewString("") + s.RemoteImageProxyURL = NewString("") } else { - ips.RemoteImageProxyURL = ss.DEPRECATED_DO_NOT_USE_ImageProxyURL + s.RemoteImageProxyURL = ss.DEPRECATED_DO_NOT_USE_ImageProxyURL } } - if ips.RemoteImageProxyOptions == nil { + if s.RemoteImageProxyOptions == nil { if ss.DEPRECATED_DO_NOT_USE_ImageProxyOptions == nil { - ips.RemoteImageProxyOptions = NewString("") + s.RemoteImageProxyOptions = NewString("") } else { - ips.RemoteImageProxyOptions = ss.DEPRECATED_DO_NOT_USE_ImageProxyOptions + s.RemoteImageProxyOptions = ss.DEPRECATED_DO_NOT_USE_ImageProxyOptions } } } @@ -2650,168 +2650,168 @@ func (o *Config) IsValid() *AppError { return nil } -func (ts *TeamSettings) isValid() *AppError { - if *ts.MaxUsersPerTeam <= 0 { +func (s *TeamSettings) isValid() *AppError { + if *s.MaxUsersPerTeam <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.max_users.app_error", nil, "", http.StatusBadRequest) } - if *ts.MaxChannelsPerTeam <= 0 { + if *s.MaxChannelsPerTeam <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.max_channels.app_error", nil, "", http.StatusBadRequest) } - if *ts.MaxNotificationsPerChannel <= 0 { + if *s.MaxNotificationsPerChannel <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.max_notify_per_channel.app_error", nil, "", http.StatusBadRequest) } - if !(*ts.RestrictDirectMessage == DIRECT_MESSAGE_ANY || *ts.RestrictDirectMessage == DIRECT_MESSAGE_TEAM) { + if !(*s.RestrictDirectMessage == DIRECT_MESSAGE_ANY || *s.RestrictDirectMessage == DIRECT_MESSAGE_TEAM) { return NewAppError("Config.IsValid", "model.config.is_valid.restrict_direct_message.app_error", nil, "", http.StatusBadRequest) } - if !(*ts.TeammateNameDisplay == SHOW_FULLNAME || *ts.TeammateNameDisplay == SHOW_NICKNAME_FULLNAME || *ts.TeammateNameDisplay == SHOW_USERNAME) { + if !(*s.TeammateNameDisplay == SHOW_FULLNAME || *s.TeammateNameDisplay == SHOW_NICKNAME_FULLNAME || *s.TeammateNameDisplay == SHOW_USERNAME) { return NewAppError("Config.IsValid", "model.config.is_valid.teammate_name_display.app_error", nil, "", http.StatusBadRequest) } - if len(*ts.SiteName) == 0 { + if len(*s.SiteName) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.sitename_empty.app_error", nil, "", http.StatusBadRequest) } - if len(*ts.SiteName) > SITENAME_MAX_LENGTH { + if len(*s.SiteName) > SITENAME_MAX_LENGTH { return NewAppError("Config.IsValid", "model.config.is_valid.sitename_length.app_error", map[string]interface{}{"MaxLength": SITENAME_MAX_LENGTH}, "", http.StatusBadRequest) } return nil } -func (ss *SqlSettings) isValid() *AppError { - if *ss.AtRestEncryptKey != "" && len(*ss.AtRestEncryptKey) < 32 { +func (s *SqlSettings) isValid() *AppError { + if *s.AtRestEncryptKey != "" && len(*s.AtRestEncryptKey) < 32 { return NewAppError("Config.IsValid", "model.config.is_valid.encrypt_sql.app_error", nil, "", http.StatusBadRequest) } - if !(*ss.DriverName == DATABASE_DRIVER_MYSQL || *ss.DriverName == DATABASE_DRIVER_POSTGRES) { + if !(*s.DriverName == DATABASE_DRIVER_MYSQL || *s.DriverName == DATABASE_DRIVER_POSTGRES) { return NewAppError("Config.IsValid", "model.config.is_valid.sql_driver.app_error", nil, "", http.StatusBadRequest) } - if *ss.MaxIdleConns <= 0 { + if *s.MaxIdleConns <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.sql_idle.app_error", nil, "", http.StatusBadRequest) } - if *ss.ConnMaxLifetimeMilliseconds < 0 { + if *s.ConnMaxLifetimeMilliseconds < 0 { return NewAppError("Config.IsValid", "model.config.is_valid.sql_conn_max_lifetime_milliseconds.app_error", nil, "", http.StatusBadRequest) } - if *ss.QueryTimeout <= 0 { + if *s.QueryTimeout <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.sql_query_timeout.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.DataSource) == 0 { + if len(*s.DataSource) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.sql_data_src.app_error", nil, "", http.StatusBadRequest) } - if *ss.MaxOpenConns <= 0 { + if *s.MaxOpenConns <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.sql_max_conn.app_error", nil, "", http.StatusBadRequest) } return nil } -func (fs *FileSettings) isValid() *AppError { - if *fs.MaxFileSize <= 0 { +func (s *FileSettings) isValid() *AppError { + if *s.MaxFileSize <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.max_file_size.app_error", nil, "", http.StatusBadRequest) } - if !(*fs.DriverName == IMAGE_DRIVER_LOCAL || *fs.DriverName == IMAGE_DRIVER_S3) { + if !(*s.DriverName == IMAGE_DRIVER_LOCAL || *s.DriverName == IMAGE_DRIVER_S3) { return NewAppError("Config.IsValid", "model.config.is_valid.file_driver.app_error", nil, "", http.StatusBadRequest) } - if *fs.PublicLinkSalt != "" && len(*fs.PublicLinkSalt) < 32 { + if *s.PublicLinkSalt != "" && len(*s.PublicLinkSalt) < 32 { return NewAppError("Config.IsValid", "model.config.is_valid.file_salt.app_error", nil, "", http.StatusBadRequest) } return nil } -func (es *EmailSettings) isValid() *AppError { - if !(*es.ConnectionSecurity == CONN_SECURITY_NONE || *es.ConnectionSecurity == CONN_SECURITY_TLS || *es.ConnectionSecurity == CONN_SECURITY_STARTTLS || *es.ConnectionSecurity == CONN_SECURITY_PLAIN) { +func (s *EmailSettings) isValid() *AppError { + if !(*s.ConnectionSecurity == CONN_SECURITY_NONE || *s.ConnectionSecurity == CONN_SECURITY_TLS || *s.ConnectionSecurity == CONN_SECURITY_STARTTLS || *s.ConnectionSecurity == CONN_SECURITY_PLAIN) { return NewAppError("Config.IsValid", "model.config.is_valid.email_security.app_error", nil, "", http.StatusBadRequest) } - if *es.EmailBatchingBufferSize <= 0 { + if *s.EmailBatchingBufferSize <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.email_batching_buffer_size.app_error", nil, "", http.StatusBadRequest) } - if *es.EmailBatchingInterval < 30 { + if *s.EmailBatchingInterval < 30 { return NewAppError("Config.IsValid", "model.config.is_valid.email_batching_interval.app_error", nil, "", http.StatusBadRequest) } - if !(*es.EmailNotificationContentsType == EMAIL_NOTIFICATION_CONTENTS_FULL || *es.EmailNotificationContentsType == EMAIL_NOTIFICATION_CONTENTS_GENERIC) { + if !(*s.EmailNotificationContentsType == EMAIL_NOTIFICATION_CONTENTS_FULL || *s.EmailNotificationContentsType == EMAIL_NOTIFICATION_CONTENTS_GENERIC) { return NewAppError("Config.IsValid", "model.config.is_valid.email_notification_contents_type.app_error", nil, "", http.StatusBadRequest) } return nil } -func (rls *RateLimitSettings) isValid() *AppError { - if *rls.MemoryStoreSize <= 0 { +func (s *RateLimitSettings) isValid() *AppError { + if *s.MemoryStoreSize <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.rate_mem.app_error", nil, "", http.StatusBadRequest) } - if *rls.PerSec <= 0 { + if *s.PerSec <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.rate_sec.app_error", nil, "", http.StatusBadRequest) } - if *rls.MaxBurst <= 0 { + if *s.MaxBurst <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.max_burst.app_error", nil, "", http.StatusBadRequest) } return nil } -func (ls *LdapSettings) isValid() *AppError { - if !(*ls.ConnectionSecurity == CONN_SECURITY_NONE || *ls.ConnectionSecurity == CONN_SECURITY_TLS || *ls.ConnectionSecurity == CONN_SECURITY_STARTTLS) { +func (s *LdapSettings) isValid() *AppError { + if !(*s.ConnectionSecurity == CONN_SECURITY_NONE || *s.ConnectionSecurity == CONN_SECURITY_TLS || *s.ConnectionSecurity == CONN_SECURITY_STARTTLS) { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_security.app_error", nil, "", http.StatusBadRequest) } - if *ls.SyncIntervalMinutes <= 0 { + if *s.SyncIntervalMinutes <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_sync_interval.app_error", nil, "", http.StatusBadRequest) } - if *ls.MaxPageSize < 0 { + if *s.MaxPageSize < 0 { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_max_page_size.app_error", nil, "", http.StatusBadRequest) } - if *ls.Enable { - if *ls.LdapServer == "" { + if *s.Enable { + if *s.LdapServer == "" { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_server", nil, "", http.StatusBadRequest) } - if *ls.BaseDN == "" { + if *s.BaseDN == "" { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_basedn", nil, "", http.StatusBadRequest) } - if *ls.EmailAttribute == "" { + if *s.EmailAttribute == "" { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_email", nil, "", http.StatusBadRequest) } - if *ls.UsernameAttribute == "" { + if *s.UsernameAttribute == "" { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_username", nil, "", http.StatusBadRequest) } - if *ls.IdAttribute == "" { + if *s.IdAttribute == "" { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_id", nil, "", http.StatusBadRequest) } - if *ls.LoginIdAttribute == "" { + if *s.LoginIdAttribute == "" { return NewAppError("Config.IsValid", "model.config.is_valid.ldap_login_id", nil, "", http.StatusBadRequest) } - if *ls.UserFilter != "" { - if _, err := ldap.CompileFilter(*ls.UserFilter); err != nil { + if *s.UserFilter != "" { + if _, err := ldap.CompileFilter(*s.UserFilter); err != nil { return NewAppError("ValidateFilter", "ent.ldap.validate_filter.app_error", nil, err.Error(), http.StatusBadRequest) } } - if *ls.GuestFilter != "" { - if _, err := ldap.CompileFilter(*ls.GuestFilter); err != nil { + if *s.GuestFilter != "" { + if _, err := ldap.CompileFilter(*s.GuestFilter); err != nil { return NewAppError("LdapSettings.isValid", "ent.ldap.validate_guest_filter.app_error", nil, err.Error(), http.StatusBadRequest) } } @@ -2820,60 +2820,60 @@ func (ls *LdapSettings) isValid() *AppError { return nil } -func (ss *SamlSettings) isValid() *AppError { - if *ss.Enable { - if len(*ss.IdpUrl) == 0 || !IsValidHttpUrl(*ss.IdpUrl) { +func (s *SamlSettings) isValid() *AppError { + if *s.Enable { + if len(*s.IdpUrl) == 0 || !IsValidHttpUrl(*s.IdpUrl) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_url.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.IdpDescriptorUrl) == 0 || !IsValidHttpUrl(*ss.IdpDescriptorUrl) { + if len(*s.IdpDescriptorUrl) == 0 || !IsValidHttpUrl(*s.IdpDescriptorUrl) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_descriptor_url.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.IdpCertificateFile) == 0 { + if len(*s.IdpCertificateFile) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.saml_idp_cert.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.EmailAttribute) == 0 { + if len(*s.EmailAttribute) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.UsernameAttribute) == 0 { + if len(*s.UsernameAttribute) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.saml_username_attribute.app_error", nil, "", http.StatusBadRequest) } - if *ss.Verify { - if len(*ss.AssertionConsumerServiceURL) == 0 || !IsValidHttpUrl(*ss.AssertionConsumerServiceURL) { + if *s.Verify { + if len(*s.AssertionConsumerServiceURL) == 0 || !IsValidHttpUrl(*s.AssertionConsumerServiceURL) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_assertion_consumer_service_url.app_error", nil, "", http.StatusBadRequest) } } - if *ss.Encrypt { - if len(*ss.PrivateKeyFile) == 0 { + if *s.Encrypt { + if len(*s.PrivateKeyFile) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.saml_private_key.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.PublicCertificateFile) == 0 { + if len(*s.PublicCertificateFile) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.saml_public_cert.app_error", nil, "", http.StatusBadRequest) } } - if len(*ss.EmailAttribute) == 0 { + if len(*s.EmailAttribute) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.saml_email_attribute.app_error", nil, "", http.StatusBadRequest) } - if !(*ss.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA1 || *ss.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA256 || *ss.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA512) { + if !(*s.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA1 || *s.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA256 || *s.SignatureAlgorithm == SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA512) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_signature_algorithm.app_error", nil, "", http.StatusBadRequest) } - if !(*ss.CanonicalAlgorithm == SAML_SETTINGS_CANONICAL_ALGORITHM_C14N || *ss.CanonicalAlgorithm == SAML_SETTINGS_CANONICAL_ALGORITHM_C14N11) { + if !(*s.CanonicalAlgorithm == SAML_SETTINGS_CANONICAL_ALGORITHM_C14N || *s.CanonicalAlgorithm == SAML_SETTINGS_CANONICAL_ALGORITHM_C14N11) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_canonical_algorithm.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.GuestAttribute) > 0 { - if !(strings.Contains(*ss.GuestAttribute, "=")) { + if len(*s.GuestAttribute) > 0 { + if !(strings.Contains(*s.GuestAttribute, "=")) { return NewAppError("Config.IsValid", "model.config.is_valid.saml_guest_attribute.app_error", nil, "", http.StatusBadRequest) } - if len(strings.Split(*ss.GuestAttribute, "=")) != 2 { + if len(strings.Split(*s.GuestAttribute, "=")) != 2 { return NewAppError("Config.IsValid", "model.config.is_valid.saml_guest_attribute.app_error", nil, "", http.StatusBadRequest) } } @@ -2882,66 +2882,66 @@ func (ss *SamlSettings) isValid() *AppError { return nil } -func (ss *ServiceSettings) isValid() *AppError { - if !(*ss.ConnectionSecurity == CONN_SECURITY_NONE || *ss.ConnectionSecurity == CONN_SECURITY_TLS) { +func (s *ServiceSettings) isValid() *AppError { + if !(*s.ConnectionSecurity == CONN_SECURITY_NONE || *s.ConnectionSecurity == CONN_SECURITY_TLS) { return NewAppError("Config.IsValid", "model.config.is_valid.webserver_security.app_error", nil, "", http.StatusBadRequest) } - if *ss.ConnectionSecurity == CONN_SECURITY_TLS && !*ss.UseLetsEncrypt { + if *s.ConnectionSecurity == CONN_SECURITY_TLS && !*s.UseLetsEncrypt { appErr := NewAppError("Config.IsValid", "model.config.is_valid.tls_cert_file.app_error", nil, "", http.StatusBadRequest) - if *ss.TLSCertFile == "" { + if *s.TLSCertFile == "" { return appErr - } else if _, err := os.Stat(*ss.TLSCertFile); os.IsNotExist(err) { + } else if _, err := os.Stat(*s.TLSCertFile); os.IsNotExist(err) { return appErr } appErr = NewAppError("Config.IsValid", "model.config.is_valid.tls_key_file.app_error", nil, "", http.StatusBadRequest) - if *ss.TLSKeyFile == "" { + if *s.TLSKeyFile == "" { return appErr - } else if _, err := os.Stat(*ss.TLSKeyFile); os.IsNotExist(err) { + } else if _, err := os.Stat(*s.TLSKeyFile); os.IsNotExist(err) { return appErr } } - if len(ss.TLSOverwriteCiphers) > 0 { - for _, cipher := range ss.TLSOverwriteCiphers { + if len(s.TLSOverwriteCiphers) > 0 { + for _, cipher := range s.TLSOverwriteCiphers { if _, ok := ServerTLSSupportedCiphers[cipher]; !ok { return NewAppError("Config.IsValid", "model.config.is_valid.tls_overwrite_cipher.app_error", map[string]interface{}{"name": cipher}, "", http.StatusBadRequest) } } } - if *ss.ReadTimeout <= 0 { + if *s.ReadTimeout <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.read_timeout.app_error", nil, "", http.StatusBadRequest) } - if *ss.WriteTimeout <= 0 { + if *s.WriteTimeout <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.write_timeout.app_error", nil, "", http.StatusBadRequest) } - if *ss.TimeBetweenUserTypingUpdatesMilliseconds < 1000 { + if *s.TimeBetweenUserTypingUpdatesMilliseconds < 1000 { return NewAppError("Config.IsValid", "model.config.is_valid.time_between_user_typing.app_error", nil, "", http.StatusBadRequest) } - if *ss.MaximumLoginAttempts <= 0 { + if *s.MaximumLoginAttempts <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.login_attempts.app_error", nil, "", http.StatusBadRequest) } - if len(*ss.SiteURL) != 0 { - if _, err := url.ParseRequestURI(*ss.SiteURL); err != nil { + if len(*s.SiteURL) != 0 { + if _, err := url.ParseRequestURI(*s.SiteURL); err != nil { return NewAppError("Config.IsValid", "model.config.is_valid.site_url.app_error", nil, "", http.StatusBadRequest) } } - if len(*ss.WebsocketURL) != 0 { - if _, err := url.ParseRequestURI(*ss.WebsocketURL); err != nil { + if len(*s.WebsocketURL) != 0 { + if _, err := url.ParseRequestURI(*s.WebsocketURL); err != nil { return NewAppError("Config.IsValid", "model.config.is_valid.websocket_url.app_error", nil, "", http.StatusBadRequest) } } - host, port, _ := net.SplitHostPort(*ss.ListenAddress) + host, port, _ := net.SplitHostPort(*s.ListenAddress) var isValidHost bool if host == "" { isValidHost = true @@ -2953,72 +2953,72 @@ func (ss *ServiceSettings) isValid() *AppError { return NewAppError("Config.IsValid", "model.config.is_valid.listen_address.app_error", nil, "", http.StatusBadRequest) } - if *ss.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DISABLED && - *ss.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DEFAULT_ON && - *ss.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DEFAULT_OFF { + if *s.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DISABLED && + *s.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DEFAULT_ON && + *s.ExperimentalGroupUnreadChannels != GROUP_UNREAD_CHANNELS_DEFAULT_OFF { return NewAppError("Config.IsValid", "model.config.is_valid.group_unread_channels.app_error", nil, "", http.StatusBadRequest) } return nil } -func (ess *ElasticsearchSettings) isValid() *AppError { - if *ess.EnableIndexing { - if len(*ess.ConnectionUrl) == 0 { +func (s *ElasticsearchSettings) isValid() *AppError { + if *s.EnableIndexing { + if len(*s.ConnectionUrl) == 0 { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.connection_url.app_error", nil, "", http.StatusBadRequest) } } - if *ess.EnableSearching && !*ess.EnableIndexing { + if *s.EnableSearching && !*s.EnableIndexing { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.enable_searching.app_error", nil, "", http.StatusBadRequest) } - if *ess.EnableAutocomplete && !*ess.EnableIndexing { + if *s.EnableAutocomplete && !*s.EnableIndexing { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.enable_autocomplete.app_error", nil, "", http.StatusBadRequest) } - if *ess.AggregatePostsAfterDays < 1 { + if *s.AggregatePostsAfterDays < 1 { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.aggregate_posts_after_days.app_error", nil, "", http.StatusBadRequest) } - if _, err := time.Parse("15:04", *ess.PostsAggregatorJobStartTime); err != nil { + if _, err := time.Parse("15:04", *s.PostsAggregatorJobStartTime); err != nil { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.posts_aggregator_job_start_time.app_error", nil, err.Error(), http.StatusBadRequest) } - if *ess.LiveIndexingBatchSize < 1 { + if *s.LiveIndexingBatchSize < 1 { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.live_indexing_batch_size.app_error", nil, "", http.StatusBadRequest) } - if *ess.BulkIndexingTimeWindowSeconds < 1 { + if *s.BulkIndexingTimeWindowSeconds < 1 { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.bulk_indexing_time_window_seconds.app_error", nil, "", http.StatusBadRequest) } - if *ess.RequestTimeoutSeconds < 1 { + if *s.RequestTimeoutSeconds < 1 { return NewAppError("Config.IsValid", "model.config.is_valid.elastic_search.request_timeout_seconds.app_error", nil, "", http.StatusBadRequest) } return nil } -func (drs *DataRetentionSettings) isValid() *AppError { - if *drs.MessageRetentionDays <= 0 { +func (s *DataRetentionSettings) isValid() *AppError { + if *s.MessageRetentionDays <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.data_retention.message_retention_days_too_low.app_error", nil, "", http.StatusBadRequest) } - if *drs.FileRetentionDays <= 0 { + if *s.FileRetentionDays <= 0 { return NewAppError("Config.IsValid", "model.config.is_valid.data_retention.file_retention_days_too_low.app_error", nil, "", http.StatusBadRequest) } - if _, err := time.Parse("15:04", *drs.DeletionJobStartTime); err != nil { + if _, err := time.Parse("15:04", *s.DeletionJobStartTime); err != nil { return NewAppError("Config.IsValid", "model.config.is_valid.data_retention.deletion_job_start_time.app_error", nil, err.Error(), http.StatusBadRequest) } return nil } -func (ls *LocalizationSettings) isValid() *AppError { - if len(*ls.AvailableLocales) > 0 { - if !strings.Contains(*ls.AvailableLocales, *ls.DefaultClientLocale) { +func (s *LocalizationSettings) isValid() *AppError { + if len(*s.AvailableLocales) > 0 { + if !strings.Contains(*s.AvailableLocales, *s.DefaultClientLocale) { return NewAppError("Config.IsValid", "model.config.is_valid.localization.available_locales.app_error", nil, "", http.StatusBadRequest) } } @@ -3026,35 +3026,35 @@ func (ls *LocalizationSettings) isValid() *AppError { return nil } -func (mes *MessageExportSettings) isValid(fs FileSettings) *AppError { - if mes.EnableExport == nil { +func (s *MessageExportSettings) isValid(fs FileSettings) *AppError { + if s.EnableExport == nil { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.enable.app_error", nil, "", http.StatusBadRequest) } - if *mes.EnableExport { - if mes.ExportFromTimestamp == nil || *mes.ExportFromTimestamp < 0 || *mes.ExportFromTimestamp > GetMillis() { + if *s.EnableExport { + if s.ExportFromTimestamp == nil || *s.ExportFromTimestamp < 0 || *s.ExportFromTimestamp > GetMillis() { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.export_from.app_error", nil, "", http.StatusBadRequest) - } else if mes.DailyRunTime == nil { + } else if s.DailyRunTime == nil { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.daily_runtime.app_error", nil, "", http.StatusBadRequest) - } else if _, err := time.Parse("15:04", *mes.DailyRunTime); err != nil { + } else if _, err := time.Parse("15:04", *s.DailyRunTime); err != nil { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.daily_runtime.app_error", nil, err.Error(), http.StatusBadRequest) - } else if mes.BatchSize == nil || *mes.BatchSize < 0 { + } else if s.BatchSize == nil || *s.BatchSize < 0 { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.batch_size.app_error", nil, "", http.StatusBadRequest) - } else if mes.ExportFormat == nil || (*mes.ExportFormat != COMPLIANCE_EXPORT_TYPE_ACTIANCE && *mes.ExportFormat != COMPLIANCE_EXPORT_TYPE_GLOBALRELAY && *mes.ExportFormat != COMPLIANCE_EXPORT_TYPE_CSV) { + } else if s.ExportFormat == nil || (*s.ExportFormat != COMPLIANCE_EXPORT_TYPE_ACTIANCE && *s.ExportFormat != COMPLIANCE_EXPORT_TYPE_GLOBALRELAY && *s.ExportFormat != COMPLIANCE_EXPORT_TYPE_CSV) { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.export_type.app_error", nil, "", http.StatusBadRequest) } - if *mes.ExportFormat == COMPLIANCE_EXPORT_TYPE_GLOBALRELAY { - if mes.GlobalRelaySettings == nil { + if *s.ExportFormat == COMPLIANCE_EXPORT_TYPE_GLOBALRELAY { + if s.GlobalRelaySettings == nil { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.config_missing.app_error", nil, "", http.StatusBadRequest) - } else if mes.GlobalRelaySettings.CustomerType == nil || (*mes.GlobalRelaySettings.CustomerType != GLOBALRELAY_CUSTOMER_TYPE_A9 && *mes.GlobalRelaySettings.CustomerType != GLOBALRELAY_CUSTOMER_TYPE_A10) { + } else if s.GlobalRelaySettings.CustomerType == nil || (*s.GlobalRelaySettings.CustomerType != GLOBALRELAY_CUSTOMER_TYPE_A9 && *s.GlobalRelaySettings.CustomerType != GLOBALRELAY_CUSTOMER_TYPE_A10) { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.customer_type.app_error", nil, "", http.StatusBadRequest) - } else if mes.GlobalRelaySettings.EmailAddress == nil || !strings.Contains(*mes.GlobalRelaySettings.EmailAddress, "@") { + } else if s.GlobalRelaySettings.EmailAddress == nil || !strings.Contains(*s.GlobalRelaySettings.EmailAddress, "@") { // validating email addresses is hard - just make sure it contains an '@' sign // see https://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.email_address.app_error", nil, "", http.StatusBadRequest) - } else if mes.GlobalRelaySettings.SmtpUsername == nil || *mes.GlobalRelaySettings.SmtpUsername == "" { + } else if s.GlobalRelaySettings.SmtpUsername == nil || *s.GlobalRelaySettings.SmtpUsername == "" { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.smtp_username.app_error", nil, "", http.StatusBadRequest) - } else if mes.GlobalRelaySettings.SmtpPassword == nil || *mes.GlobalRelaySettings.SmtpPassword == "" { + } else if s.GlobalRelaySettings.SmtpPassword == nil || *s.GlobalRelaySettings.SmtpPassword == "" { return NewAppError("Config.IsValid", "model.config.is_valid.message_export.global_relay.smtp_password.app_error", nil, "", http.StatusBadRequest) } } @@ -3062,11 +3062,11 @@ func (mes *MessageExportSettings) isValid(fs FileSettings) *AppError { return nil } -func (ds *DisplaySettings) isValid() *AppError { - if len(ds.CustomUrlSchemes) != 0 { +func (s *DisplaySettings) isValid() *AppError { + if len(s.CustomUrlSchemes) != 0 { validProtocolPattern := regexp.MustCompile(`(?i)^\s*[A-Za-z][A-Za-z0-9.+-]*\s*$`) - for _, scheme := range ds.CustomUrlSchemes { + for _, scheme := range s.CustomUrlSchemes { if !validProtocolPattern.MatchString(scheme) { return NewAppError( "Config.IsValid", @@ -3082,17 +3082,17 @@ func (ds *DisplaySettings) isValid() *AppError { return nil } -func (ips *ImageProxySettings) isValid() *AppError { - if *ips.Enable { - switch *ips.ImageProxyType { +func (s *ImageProxySettings) isValid() *AppError { + if *s.Enable { + switch *s.ImageProxyType { case IMAGE_PROXY_TYPE_LOCAL: // No other settings to validate case IMAGE_PROXY_TYPE_ATMOS_CAMO: - if *ips.RemoteImageProxyURL == "" { + if *s.RemoteImageProxyURL == "" { return NewAppError("Config.IsValid", "model.config.is_valid.atmos_camo_image_proxy_url.app_error", nil, "", http.StatusBadRequest) } - if *ips.RemoteImageProxyOptions == "" { + if *s.RemoteImageProxyOptions == "" { return NewAppError("Config.IsValid", "model.config.is_valid.atmos_camo_image_proxy_options.app_error", nil, "", http.StatusBadRequest) } default: diff --git a/model/file_info.go b/model/file_info.go index 94595ded7b..4e528ed0ba 100644 --- a/model/file_info.go +++ b/model/file_info.go @@ -34,19 +34,19 @@ type FileInfo struct { HasPreviewImage bool `json:"has_preview_image,omitempty"` } -func (info *FileInfo) ToJson() string { - b, _ := json.Marshal(info) +func (fi *FileInfo) ToJson() string { + b, _ := json.Marshal(fi) return string(b) } func FileInfoFromJson(data io.Reader) *FileInfo { decoder := json.NewDecoder(data) - var info FileInfo - if err := decoder.Decode(&info); err != nil { + var fi FileInfo + if err := decoder.Decode(&fi); err != nil { return nil } else { - return &info + return &fi } } @@ -66,50 +66,50 @@ func FileInfosFromJson(data io.Reader) []*FileInfo { } } -func (o *FileInfo) PreSave() { - if o.Id == "" { - o.Id = NewId() +func (fi *FileInfo) PreSave() { + if fi.Id == "" { + fi.Id = NewId() } - if o.CreateAt == 0 { - o.CreateAt = GetMillis() + if fi.CreateAt == 0 { + fi.CreateAt = GetMillis() } - if o.UpdateAt < o.CreateAt { - o.UpdateAt = o.CreateAt + if fi.UpdateAt < fi.CreateAt { + fi.UpdateAt = fi.CreateAt } } -func (o *FileInfo) IsValid() *AppError { - if len(o.Id) != 26 { +func (fi *FileInfo) IsValid() *AppError { + if len(fi.Id) != 26 { return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.id.app_error", nil, "", http.StatusBadRequest) } - if len(o.CreatorId) != 26 && o.CreatorId != "nouser" { - return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.user_id.app_error", nil, "id="+o.Id, http.StatusBadRequest) + if len(fi.CreatorId) != 26 && fi.CreatorId != "nouser" { + return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.user_id.app_error", nil, "id="+fi.Id, http.StatusBadRequest) } - if len(o.PostId) != 0 && len(o.PostId) != 26 { - return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.post_id.app_error", nil, "id="+o.Id, http.StatusBadRequest) + if len(fi.PostId) != 0 && len(fi.PostId) != 26 { + return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.post_id.app_error", nil, "id="+fi.Id, http.StatusBadRequest) } - if o.CreateAt == 0 { - return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.create_at.app_error", nil, "id="+o.Id, http.StatusBadRequest) + if fi.CreateAt == 0 { + return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.create_at.app_error", nil, "id="+fi.Id, http.StatusBadRequest) } - if o.UpdateAt == 0 { - return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.update_at.app_error", nil, "id="+o.Id, http.StatusBadRequest) + if fi.UpdateAt == 0 { + return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.update_at.app_error", nil, "id="+fi.Id, http.StatusBadRequest) } - if o.Path == "" { - return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.path.app_error", nil, "id="+o.Id, http.StatusBadRequest) + if fi.Path == "" { + return NewAppError("FileInfo.IsValid", "model.file_info.is_valid.path.app_error", nil, "id="+fi.Id, http.StatusBadRequest) } return nil } -func (o *FileInfo) IsImage() bool { - return strings.HasPrefix(o.MimeType, "image") +func (fi *FileInfo) IsImage() bool { + return strings.HasPrefix(fi.MimeType, "image") } func NewInfo(name string) *FileInfo { diff --git a/model/guest_invite.go b/model/guest_invite.go index 575d9a58b6..3cdd4893c5 100644 --- a/model/guest_invite.go +++ b/model/guest_invite.go @@ -42,12 +42,12 @@ func (i *GuestsInvite) IsValid() *AppError { // GuestsInviteFromJson will decode the input and return a GuestsInvite func GuestsInviteFromJson(data io.Reader) *GuestsInvite { - var invite *GuestsInvite - json.NewDecoder(data).Decode(&invite) - return invite + var i *GuestsInvite + json.NewDecoder(data).Decode(&i) + return i } -func (invite *GuestsInvite) ToJson() string { - b, _ := json.Marshal(invite) +func (i *GuestsInvite) ToJson() string { + b, _ := json.Marshal(i) return string(b) } diff --git a/model/job.go b/model/job.go index 36c5c1e024..aa267a67d0 100644 --- a/model/job.go +++ b/model/job.go @@ -74,8 +74,8 @@ func (j *Job) IsValid() *AppError { return nil } -func (js *Job) ToJson() string { - b, _ := json.Marshal(js) +func (j *Job) ToJson() string { + b, _ := json.Marshal(j) return string(b) } @@ -102,8 +102,8 @@ func JobsFromJson(data io.Reader) []*Job { } } -func (js *Job) DataToJson() string { - b, _ := json.Marshal(js.Data) +func (j *Job) DataToJson() string { + b, _ := json.Marshal(j.Data) return string(b) } diff --git a/model/post.go b/model/post.go index ab638628a9..948ac11497 100644 --- a/model/post.go +++ b/model/post.go @@ -364,25 +364,25 @@ func (o *Post) IsJoinLeaveMessage() bool { o.Type == POST_REMOVE_FROM_TEAM } -func (p *Post) Patch(patch *PostPatch) { +func (o *Post) Patch(patch *PostPatch) { if patch.IsPinned != nil { - p.IsPinned = *patch.IsPinned + o.IsPinned = *patch.IsPinned } if patch.Message != nil { - p.Message = *patch.Message + o.Message = *patch.Message } if patch.Props != nil { - p.Props = *patch.Props + o.Props = *patch.Props } if patch.FileIds != nil { - p.FileIds = *patch.FileIds + o.FileIds = *patch.FileIds } if patch.HasReactions != nil { - p.HasReactions = *patch.HasReactions + o.HasReactions = *patch.HasReactions } } diff --git a/model/role.go b/model/role.go index 0a41daa729..b1483f640c 100644 --- a/model/role.go +++ b/model/role.go @@ -49,15 +49,15 @@ type RolePatch struct { Permissions *[]string `json:"permissions"` } -func (role *Role) ToJson() string { - b, _ := json.Marshal(role) +func (r *Role) ToJson() string { + b, _ := json.Marshal(r) return string(b) } func RoleFromJson(data io.Reader) *Role { - var role *Role - json.NewDecoder(data).Decode(&role) - return role + var r *Role + json.NewDecoder(data).Decode(&r) + return r } func RoleListToJson(r []*Role) string { @@ -82,9 +82,9 @@ func RolePatchFromJson(data io.Reader) *RolePatch { return rolePatch } -func (o *Role) Patch(patch *RolePatch) { +func (r *Role) Patch(patch *RolePatch) { if patch.Permissions != nil { - o.Permissions = *patch.Permissions + r.Permissions = *patch.Permissions } } @@ -123,28 +123,28 @@ func PermissionsChangedByPatch(role *Role, patch *RolePatch) []string { return result } -func (role *Role) IsValid() bool { - if len(role.Id) != 26 { +func (r *Role) IsValid() bool { + if len(r.Id) != 26 { return false } - return role.IsValidWithoutId() + return r.IsValidWithoutId() } -func (role *Role) IsValidWithoutId() bool { - if !IsValidRoleName(role.Name) { +func (r *Role) IsValidWithoutId() bool { + if !IsValidRoleName(r.Name) { return false } - if len(role.DisplayName) == 0 || len(role.DisplayName) > ROLE_DISPLAY_NAME_MAX_LENGTH { + if len(r.DisplayName) == 0 || len(r.DisplayName) > ROLE_DISPLAY_NAME_MAX_LENGTH { return false } - if len(role.Description) > ROLE_DESCRIPTION_MAX_LENGTH { + if len(r.Description) > ROLE_DESCRIPTION_MAX_LENGTH { return false } - for _, permission := range role.Permissions { + for _, permission := range r.Permissions { permissionValidated := false for _, p := range ALL_PERMISSIONS { if permission == p.Id { diff --git a/model/team.go b/model/team.go index 2f57b83ff2..137a8f0b8a 100644 --- a/model/team.go +++ b/model/team.go @@ -271,34 +271,34 @@ func (o *Team) Sanitize() { o.InviteId = "" } -func (t *Team) Patch(patch *TeamPatch) { +func (o *Team) Patch(patch *TeamPatch) { if patch.DisplayName != nil { - t.DisplayName = *patch.DisplayName + o.DisplayName = *patch.DisplayName } if patch.Description != nil { - t.Description = *patch.Description + o.Description = *patch.Description } if patch.CompanyName != nil { - t.CompanyName = *patch.CompanyName + o.CompanyName = *patch.CompanyName } if patch.AllowedDomains != nil { - t.AllowedDomains = *patch.AllowedDomains + o.AllowedDomains = *patch.AllowedDomains } if patch.AllowOpenInvite != nil { - t.AllowOpenInvite = *patch.AllowOpenInvite + o.AllowOpenInvite = *patch.AllowOpenInvite } if patch.GroupConstrained != nil { - t.GroupConstrained = patch.GroupConstrained + o.GroupConstrained = patch.GroupConstrained } } -func (t *Team) IsGroupConstrained() bool { - return t.GroupConstrained != nil && *t.GroupConstrained +func (o *Team) IsGroupConstrained() bool { + return o.GroupConstrained != nil && *o.GroupConstrained } func (t *TeamPatch) ToJson() string { diff --git a/model/team_search.go b/model/team_search.go index b4c4a44f89..b8b1fe3055 100644 --- a/model/team_search.go +++ b/model/team_search.go @@ -19,8 +19,8 @@ func (t *TeamSearch) IsPaginated() bool { } // ToJson convert a TeamSearch to json string -func (c *TeamSearch) ToJson() string { - b, err := json.Marshal(c) +func (t *TeamSearch) ToJson() string { + b, err := json.Marshal(t) if err != nil { return "" } diff --git a/model/user.go b/model/user.go index 9474f761d4..6092afb9a2 100644 --- a/model/user.go +++ b/model/user.go @@ -398,24 +398,24 @@ func (u *User) SetDefaultNotifications() { u.NotifyProps[FIRST_NAME_NOTIFY_PROP] = "false" } -func (user *User) UpdateMentionKeysFromUsername(oldUsername string) { +func (u *User) UpdateMentionKeysFromUsername(oldUsername string) { nonUsernameKeys := []string{} - for _, key := range user.GetMentionKeys() { + for _, key := range u.GetMentionKeys() { if key != oldUsername && key != "@"+oldUsername { nonUsernameKeys = append(nonUsernameKeys, key) } } - user.NotifyProps[MENTION_KEYS_NOTIFY_PROP] = user.Username + ",@" + user.Username + u.NotifyProps[MENTION_KEYS_NOTIFY_PROP] = u.Username + ",@" + u.Username if len(nonUsernameKeys) > 0 { - user.NotifyProps[MENTION_KEYS_NOTIFY_PROP] += "," + strings.Join(nonUsernameKeys, ",") + u.NotifyProps[MENTION_KEYS_NOTIFY_PROP] += "," + strings.Join(nonUsernameKeys, ",") } } -func (user *User) GetMentionKeys() []string { +func (u *User) GetMentionKeys() []string { var keys []string - for _, key := range strings.Split(user.NotifyProps[MENTION_KEYS_NOTIFY_PROP], ",") { + for _, key := range strings.Split(u.NotifyProps[MENTION_KEYS_NOTIFY_PROP], ",") { trimmedKey := strings.TrimSpace(key) if trimmedKey == "" { diff --git a/model/websocket_message.go b/model/websocket_message.go index cd2720a5fa..cb0a801d28 100644 --- a/model/websocket_message.go +++ b/model/websocket_message.go @@ -221,16 +221,16 @@ func NewWebSocketError(seqReply int64, err *AppError) *WebSocketResponse { return &WebSocketResponse{Status: STATUS_FAIL, SeqReply: seqReply, Error: err} } -func (o *WebSocketResponse) IsValid() bool { - return o.Status != "" +func (m *WebSocketResponse) IsValid() bool { + return m.Status != "" } -func (o *WebSocketResponse) EventType() string { +func (m *WebSocketResponse) EventType() string { return WEBSOCKET_EVENT_RESPONSE } -func (o *WebSocketResponse) ToJson() string { - b, _ := json.Marshal(o) +func (m *WebSocketResponse) ToJson() string { + b, _ := json.Marshal(m) return string(b) } diff --git a/plugin/client_rpc.go b/plugin/client_rpc.go index cb7ac386d0..710069ef4b 100644 --- a/plugin/client_rpc.go +++ b/plugin/client_rpc.go @@ -753,15 +753,15 @@ func (g *apiRPCClient) InstallPlugin(file io.Reader, replace bool) (*model.Manif return _returns.A, _returns.B } -func (g *apiRPCServer) InstallPlugin(args *Z_InstallPluginArgs, returns *Z_InstallPluginReturns) error { - hook, ok := g.impl.(interface { +func (s *apiRPCServer) InstallPlugin(args *Z_InstallPluginArgs, returns *Z_InstallPluginReturns) error { + hook, ok := s.impl.(interface { InstallPlugin(file io.Reader, replace bool) (*model.Manifest, *model.AppError) }) if !ok { return encodableError(fmt.Errorf("API InstallPlugin called but not implemented.")) } - receivePluginConnection, err := g.muxBroker.Dial(args.PluginStreamID) + receivePluginConnection, err := s.muxBroker.Dial(args.PluginStreamID) if err != nil { fmt.Fprintf(os.Stderr, "[ERROR] Can't connect to remote plugin stream, error: %v", err.Error()) return err diff --git a/store/sqlstore/compliance_store.go b/store/sqlstore/compliance_store.go index 3ec46fb565..d737c9eea8 100644 --- a/store/sqlstore/compliance_store.go +++ b/store/sqlstore/compliance_store.go @@ -48,12 +48,12 @@ func (s SqlComplianceStore) Save(compliance *model.Compliance) (*model.Complianc return compliance, nil } -func (us SqlComplianceStore) Update(compliance *model.Compliance) (*model.Compliance, *model.AppError) { +func (s SqlComplianceStore) Update(compliance *model.Compliance) (*model.Compliance, *model.AppError) { if err := compliance.IsValid(); err != nil { return nil, err } - if _, err := us.GetMaster().Update(compliance); err != nil { + if _, err := s.GetMaster().Update(compliance); err != nil { return nil, model.NewAppError("SqlComplianceStore.Update", "store.sql_compliance.save.saving.app_error", nil, err.Error(), http.StatusInternalServerError) } return compliance, nil @@ -69,8 +69,8 @@ func (s SqlComplianceStore) GetAll(offset, limit int) (model.Compliances, *model return compliances, nil } -func (us SqlComplianceStore) Get(id string) (*model.Compliance, *model.AppError) { - obj, err := us.GetReplica().Get(model.Compliance{}, id) +func (s SqlComplianceStore) Get(id string) (*model.Compliance, *model.AppError) { + obj, err := s.GetReplica().Get(model.Compliance{}, id) if err != nil { return nil, model.NewAppError("SqlComplianceStore.Get", "store.sql_compliance.get.finding.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/store/sqlstore/file_info_store.go b/store/sqlstore/file_info_store.go index 1f4eed7ca2..dd4d7cf65a 100644 --- a/store/sqlstore/file_info_store.go +++ b/store/sqlstore/file_info_store.go @@ -254,15 +254,15 @@ func (fs SqlFileInfoStore) PermanentDelete(fileId string) *model.AppError { return nil } -func (s SqlFileInfoStore) PermanentDeleteBatch(endTime int64, limit int64) (int64, *model.AppError) { +func (fs SqlFileInfoStore) PermanentDeleteBatch(endTime int64, limit int64) (int64, *model.AppError) { var query string - if s.DriverName() == "postgres" { + if fs.DriverName() == "postgres" { query = "DELETE from FileInfo WHERE Id = any (array (SELECT Id FROM FileInfo WHERE CreateAt < :EndTime LIMIT :Limit))" } else { query = "DELETE from FileInfo WHERE CreateAt < :EndTime LIMIT :Limit" } - sqlResult, err := s.GetMaster().Exec(query, map[string]interface{}{"EndTime": endTime, "Limit": limit}) + sqlResult, err := fs.GetMaster().Exec(query, map[string]interface{}{"EndTime": endTime, "Limit": limit}) if err != nil { return 0, model.NewAppError("SqlFileInfoStore.PermanentDeleteBatch", "store.sql_file_info.permanent_delete_batch.app_error", nil, ""+err.Error(), http.StatusInternalServerError) } @@ -275,10 +275,10 @@ func (s SqlFileInfoStore) PermanentDeleteBatch(endTime int64, limit int64) (int6 return rowsAffected, nil } -func (s SqlFileInfoStore) PermanentDeleteByUser(userId string) (int64, *model.AppError) { +func (fs SqlFileInfoStore) PermanentDeleteByUser(userId string) (int64, *model.AppError) { query := "DELETE from FileInfo WHERE CreatorId = :CreatorId" - sqlResult, err := s.GetMaster().Exec(query, map[string]interface{}{"CreatorId": userId}) + sqlResult, err := fs.GetMaster().Exec(query, map[string]interface{}{"CreatorId": userId}) if err != nil { return 0, model.NewAppError("SqlFileInfoStore.PermanentDeleteByUser", "store.sql_file_info.PermanentDeleteByUser.app_error", nil, ""+err.Error(), http.StatusInternalServerError) } diff --git a/store/sqlstore/supplier.go b/store/sqlstore/supplier.go index e5ee4a18ed..d48285c97f 100644 --- a/store/sqlstore/supplier.go +++ b/store/sqlstore/supplier.go @@ -263,20 +263,20 @@ func setupConnection(con_type string, dataSource string, settings *model.SqlSett return dbmap } -func (s *SqlSupplier) initConnection() { - s.master = setupConnection("master", *s.settings.DataSource, s.settings) +func (ss *SqlSupplier) initConnection() { + ss.master = setupConnection("master", *ss.settings.DataSource, ss.settings) - if len(s.settings.DataSourceReplicas) > 0 { - s.replicas = make([]*gorp.DbMap, len(s.settings.DataSourceReplicas)) - for i, replica := range s.settings.DataSourceReplicas { - s.replicas[i] = setupConnection(fmt.Sprintf("replica-%v", i), replica, s.settings) + if len(ss.settings.DataSourceReplicas) > 0 { + ss.replicas = make([]*gorp.DbMap, len(ss.settings.DataSourceReplicas)) + for i, replica := range ss.settings.DataSourceReplicas { + ss.replicas[i] = setupConnection(fmt.Sprintf("replica-%v", i), replica, ss.settings) } } - if len(s.settings.DataSourceSearchReplicas) > 0 { - s.searchReplicas = make([]*gorp.DbMap, len(s.settings.DataSourceSearchReplicas)) - for i, replica := range s.settings.DataSourceSearchReplicas { - s.searchReplicas[i] = setupConnection(fmt.Sprintf("search-replica-%v", i), replica, s.settings) + if len(ss.settings.DataSourceSearchReplicas) > 0 { + ss.searchReplicas = make([]*gorp.DbMap, len(ss.settings.DataSourceSearchReplicas)) + for i, replica := range ss.settings.DataSourceSearchReplicas { + ss.searchReplicas[i] = setupConnection(fmt.Sprintf("search-replica-%v", i), replica, ss.settings) } } } diff --git a/store/sqlstore/team_store.go b/store/sqlstore/team_store.go index 06870f4593..2e7a676388 100644 --- a/store/sqlstore/team_store.go +++ b/store/sqlstore/team_store.go @@ -834,8 +834,8 @@ func (s SqlTeamStore) RemoveAllMembersByUser(userId string) *model.AppError { return nil } -func (us SqlTeamStore) UpdateLastTeamIconUpdate(teamId string, curTime int64) *model.AppError { - if _, err := us.GetMaster().Exec("UPDATE Teams SET LastTeamIconUpdate = :Time, UpdateAt = :Time WHERE Id = :teamId", map[string]interface{}{"Time": curTime, "teamId": teamId}); err != nil { +func (s SqlTeamStore) UpdateLastTeamIconUpdate(teamId string, curTime int64) *model.AppError { + if _, err := s.GetMaster().Exec("UPDATE Teams SET LastTeamIconUpdate = :Time, UpdateAt = :Time WHERE Id = :teamId", map[string]interface{}{"Time": curTime, "teamId": teamId}); err != nil { return model.NewAppError("SqlTeamStore.UpdateLastTeamIconUpdate", "store.sql_team.update_last_team_icon_update.app_error", nil, "team_id="+teamId, http.StatusInternalServerError) } return nil diff --git a/store/sqlstore/user_store.go b/store/sqlstore/user_store.go index a00ab06831..9e11f73754 100644 --- a/store/sqlstore/user_store.go +++ b/store/sqlstore/user_store.go @@ -490,8 +490,8 @@ func applyTeamGroupConstrainedFilter(query sq.SelectBuilder, teamId string) sq.S )`, teamId) } -func (s SqlUserStore) GetEtagForProfiles(teamId string) string { - updateAt, err := s.GetReplica().SelectInt("SELECT UpdateAt FROM Users, TeamMembers WHERE TeamMembers.TeamId = :TeamId AND Users.Id = TeamMembers.UserId ORDER BY UpdateAt DESC LIMIT 1", map[string]interface{}{"TeamId": teamId}) +func (us SqlUserStore) GetEtagForProfiles(teamId string) string { + updateAt, err := us.GetReplica().SelectInt("SELECT UpdateAt FROM Users, TeamMembers WHERE TeamMembers.TeamId = :TeamId AND Users.Id = TeamMembers.UserId ORDER BY UpdateAt DESC LIMIT 1", map[string]interface{}{"TeamId": teamId}) if err != nil { return fmt.Sprintf("%v.%v", model.CurrentVersion, model.GetMillis()) }