diff options
author | Duco van Amstel <duco.vanamstel@gmail.com> | 2018-10-13 00:02:14 +0100 |
---|---|---|
committer | Wim <wim@42.be> | 2018-10-13 01:02:14 +0200 |
commit | 498377a230b8712792a47a61ad63ab746f7379d1 (patch) | |
tree | de2cc5756dd7dd64a36c41d413eceb5e6d4691b3 /bridge/slack/handlers.go | |
parent | 3dd4ec57ff0d9503d10c15944c4704cc6620c552 (diff) | |
download | matterbridge-msglm-498377a230b8712792a47a61ad63ab746f7379d1.tar.gz matterbridge-msglm-498377a230b8712792a47a61ad63ab746f7379d1.tar.bz2 matterbridge-msglm-498377a230b8712792a47a61ad63ab746f7379d1.zip |
Clean up code and strengthening (slack) (#519)
Changes include:
- Refactor of strings into package-wide constants.
- Predeclaration of regexps to be instantiated at package load time.
- Checking of unchecked errors.
- Structural changes:
- Adding verifications to type-casting code.
- Remove unnecessary 'len(X) > 0' checks before iterating over X.
- Remove unnecessary 'else' clause after 'if' with 'return'.
- Unexporting of public fields of Bridge struct.
- Formatting:
- One-field-per-line struct definitions.
Diffstat (limited to 'bridge/slack/handlers.go')
-rw-r--r-- | bridge/slack/handlers.go | 128 |
1 files changed, 72 insertions, 56 deletions
diff --git a/bridge/slack/handlers.go b/bridge/slack/handlers.go index 1ef2d614..56fd7026 100644 --- a/bridge/slack/handlers.go +++ b/bridge/slack/handlers.go @@ -14,7 +14,7 @@ import ( func (b *Bslack) handleSlack() { messages := make(chan *config.Message) - if b.GetString("WebhookBindAddress") != "" { + if b.GetString(incomingWebhookConfig) != "" { b.Log.Debugf("Choosing webhooks based receiving") go b.handleMatterHook(messages) } else { @@ -43,7 +43,7 @@ func (b *Bslack) handleSlack() { func (b *Bslack) handleSlackClient(messages chan *config.Message) { for msg := range b.rtm.IncomingEvents { - if msg.Type != "user_typing" && msg.Type != "latency_report" { + if msg.Type != sUserTyping && msg.Type != sLatencyReport { b.Log.Debugf("== Receiving event %#v", msg.Data) } switch ev := msg.Data.(type) { @@ -61,17 +61,25 @@ func (b *Bslack) handleSlackClient(messages chan *config.Message) { case *slack.OutgoingErrorEvent: b.Log.Debugf("%#v", ev.Error()) case *slack.ChannelJoinedEvent: - b.Users, _ = b.sc.GetUsers() - b.Usergroups, _ = b.sc.GetUserGroups() + var err error + b.users, err = b.sc.GetUsers() + if err != nil { + b.Log.Errorf("Could not reload users: %#v", err) + } case *slack.ConnectedEvent: var err error - b.channels, _, err = b.sc.GetConversations(&slack.GetConversationsParameters{Limit: 1000, Types: []string{"public_channel,private_channel,mpim,im"}}) + b.channels, _, err = b.sc.GetConversations(&slack.GetConversationsParameters{ + Limit: 1000, + Types: []string{"public_channel,private_channel,mpim,im"}, + }) if err != nil { b.Log.Errorf("Channel list failed: %#v", err) } b.si = ev.Info - b.Users, _ = b.sc.GetUsers() - b.Usergroups, _ = b.sc.GetUserGroups() + b.users, err = b.sc.GetUsers() + if err != nil { + b.Log.Errorf("Could not reload users: %#v", err) + } case *slack.InvalidAuthEvent: b.Log.Fatalf("Invalid Token %#v", ev) case *slack.ConnectionErrorEvent: @@ -88,16 +96,22 @@ func (b *Bslack) handleMatterHook(messages chan *config.Message) { if message.UserName == "slackbot" { continue } - messages <- &config.Message{Username: message.UserName, Text: message.Text, Channel: message.ChannelName} + messages <- &config.Message{ + Username: message.UserName, + Text: message.Text, + Channel: message.ChannelName, + } } } +var commentRE = regexp.MustCompile(`.*?commented: (.*)`) + // handleDownloadFile handles file download func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) error { // if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra // limit to 1MB for now comment := "" - results := regexp.MustCompile(`.*?commented: (.*)`).FindAllStringSubmatch(rmsg.Text, -1) + results := commentRE.FindAllStringSubmatch(rmsg.Text, -1) if len(results) > 0 { comment = results[0][1] } @@ -106,7 +120,7 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro return err } // actually download the file - data, err := helper.DownloadFileAuth(file.URLPrivateDownload, "Bearer "+b.GetString("Token")) + data, err := helper.DownloadFileAuth(file.URLPrivateDownload, "Bearer "+b.GetString(tokenConfig)) if err != nil { return fmt.Errorf("download %s failed %#v", file.URLPrivateDownload, err) } @@ -116,7 +130,7 @@ func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File) erro } // handleUploadFile handles native upload of files -func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) (string, error) { +func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) { for _, f := range msg.Extra["file"] { fi := f.(config.FileInfo) if msg.Text == fi.Comment { @@ -141,37 +155,46 @@ func (b *Bslack) handleUploadFile(msg *config.Message, channelID string) (string b.Log.Errorf("uploadfile %#v", err) } } - return "", nil } // handleMessageEvent handles the message events func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, error) { + var err error + // update the userlist on a channel_join - if ev.SubType == "channel_join" { - b.Users, _ = b.sc.GetUsers() + if ev.SubType == sChannelJoin { + if b.users, err = b.sc.GetUsers(); err != nil { + return nil, err + } } // Edit message - if !b.GetBool("EditDisable") && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp { + if !b.GetBool(editDisableConfig) && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp { b.Log.Debugf("SubMessage %#v", ev.SubMessage) ev.User = ev.SubMessage.User - ev.Text = ev.SubMessage.Text + b.GetString("EditSuffix") + ev.Text = ev.SubMessage.Text + b.GetString(editSuffixConfig) } // use our own func because rtm.GetChannelInfo doesn't work for private channels - channel, err := b.getChannelByID(ev.Channel) + channelInfo, err := b.getChannelByID(ev.Channel) if err != nil { return nil, err } - rmsg := config.Message{Text: ev.Text, Channel: channel.Name, Account: b.Account, ID: "slack " + ev.Timestamp, Extra: make(map[string][]interface{})} + rmsg := config.Message{ + Text: ev.Text, + Channel: channelInfo.Name, + Account: b.Account, + ID: "slack " + ev.Timestamp, + Extra: map[string][]interface{}{}, + } - if b.UseChannelID { - rmsg.Channel = "ID:" + channel.ID + if b.useChannelID { + rmsg.Channel = "ID:" + channelInfo.ID } // find the user id and name - if ev.User != "" && ev.SubType != messageDeleted && ev.SubType != "file_comment" { + if ev.User != "" && ev.SubType != sMessageDeleted && ev.SubType != sFileComment { user, err := b.rtm.GetUserInfo(ev.User) if err != nil { return nil, err @@ -198,7 +221,7 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er } // when using webhookURL we can't check if it's our webhook or not for now - if rmsg.Username == "" && ev.BotID != "" && b.GetString("WebhookURL") == "" { + if rmsg.Username == "" && ev.BotID != "" && b.GetString(outgoingWebhookConfig) == "" { bot, err := b.rtm.GetBotInfo(ev.BotID) if err != nil { return nil, err @@ -226,18 +249,18 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er } // file comments are set by the system (because there is no username given) - if ev.SubType == "file_comment" { - rmsg.Username = "system" + if ev.SubType == sFileComment { + rmsg.Username = sSystemUser } // do we have a /me action - if ev.SubType == "me_message" { + if ev.SubType == sMeMessage { rmsg.Event = config.EVENT_USER_ACTION } // Handle join/leave - if ev.SubType == "channel_leave" || ev.SubType == "channel_join" { - rmsg.Username = "system" + if ev.SubType == sChannelLeave || ev.SubType == sChannelJoin { + rmsg.Username = sSystemUser rmsg.Event = config.EVENT_JOIN_LEAVE } @@ -247,19 +270,19 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er } // deleted message event - if ev.SubType == messageDeleted { + if ev.SubType == sMessageDeleted { rmsg.Text = config.EVENT_MSG_DELETE rmsg.Event = config.EVENT_MSG_DELETE rmsg.ID = "slack " + ev.DeletedTimestamp } // topic change event - if ev.SubType == "channel_topic" || ev.SubType == "channel_purpose" { + if ev.SubType == sChannelTopic || ev.SubType == sChannelPurpose { rmsg.Event = config.EVENT_TOPIC_CHANGE } // Only deleted messages can have a empty username and text - if (rmsg.Text == "" || rmsg.Username == "") && ev.SubType != messageDeleted && len(ev.Files) == 0 { + if (rmsg.Text == "" || rmsg.Username == "") && ev.SubType != sMessageDeleted && len(ev.Files) == 0 { // this is probably a webhook we couldn't resolve if ev.BotID != "" { return nil, fmt.Errorf("probably an incoming webhook we couldn't resolve (maybe ourselves)") @@ -269,16 +292,14 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er // save the attachments, so that we can send them to other slack (compatible) bridges if len(ev.Attachments) > 0 { - rmsg.Extra["slack_attachment"] = append(rmsg.Extra["slack_attachment"], ev.Attachments) + rmsg.Extra[sSlackAttachment] = append(rmsg.Extra[sSlackAttachment], ev.Attachments) } // if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra - if len(ev.Files) > 0 { - for _, f := range ev.Files { - err := b.handleDownloadFile(&rmsg, &f) - if err != nil { - b.Log.Errorf("download failed: %s", err) - } + for _, f := range ev.Files { + err := b.handleDownloadFile(&rmsg, &f) + if err != nil { + b.Log.Errorf("download failed: %s", err) } } @@ -287,17 +308,17 @@ func (b *Bslack) handleMessageEvent(ev *slack.MessageEvent) (*config.Message, er // skipMessageEvent skips event that need to be skipped :-) func (b *Bslack) skipMessageEvent(ev *slack.MessageEvent) bool { - if ev.SubType == "channel_leave" || ev.SubType == "channel_join" { - return b.GetBool("nosendjoinpart") + if ev.SubType == sChannelLeave || ev.SubType == sChannelJoin { + return b.GetBool(noSendJoinConfig) } // ignore pinned items - if ev.SubType == "pinned_item" || ev.SubType == "unpinned_item" { + if ev.SubType == sPinnedItem || ev.SubType == sUnpinnedItem { return true } // do not send messages from ourself - if b.GetString("WebhookURL") == "" && b.GetString("WebhookBindAddress") == "" && ev.Username == b.si.User.Name { + if b.GetString(outgoingWebhookConfig) == "" && b.GetString(incomingWebhookConfig) == "" && ev.Username == b.si.User.Name { return true } @@ -308,7 +329,7 @@ func (b *Bslack) skipMessageEvent(ev *slack.MessageEvent) bool { } } - if !b.GetBool("EditDisable") && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp { + if !b.GetBool(editDisableConfig) && ev.SubMessage != nil && ev.SubMessage.ThreadTimestamp != ev.SubMessage.Timestamp { // it seems ev.SubMessage.Edited == nil when slack unfurls // do not forward these messages #266 if ev.SubMessage.Edited == nil { @@ -316,21 +337,16 @@ func (b *Bslack) skipMessageEvent(ev *slack.MessageEvent) bool { } } - if len(ev.Files) > 0 { - for _, f := range ev.Files { - // if the file is in the cache and isn't older then a minute, skip it - if ts, ok := b.cache.Get("file" + f.ID); ok && time.Since(ts.(time.Time)) < time.Minute { - b.Log.Debugf("Not downloading file id %s which we uploaded", f.ID) - return true - } else { - if ts, ok := b.cache.Get("filename" + f.Name); ok && time.Since(ts.(time.Time)) < time.Second*10 { - b.Log.Debugf("Not downloading file name %s which we uploaded", f.Name) - return true - } else { - b.Log.Debugf("Not skipping %s %s", f.Name, time.Now().String()) - } - } + for _, f := range ev.Files { + // if the file is in the cache and isn't older then a minute, skip it + if ts, ok := b.cache.Get("file" + f.ID); ok && time.Since(ts.(time.Time)) < time.Minute { + b.Log.Debugf("Not downloading file id %s which we uploaded", f.ID) + return true + } else if ts, ok := b.cache.Get("filename" + f.Name); ok && time.Since(ts.(time.Time)) < 10*time.Second { + b.Log.Debugf("Not downloading file name %s which we uploaded", f.Name) + return true } + b.Log.Debugf("Not skipping %s %s", f.Name, time.Now().String()) } return false |