603 lines
14 KiB
Go
Raw Normal View History

2016-09-25 22:34:02 +02:00
package service
import (
"errors"
2016-09-25 22:34:02 +02:00
"fmt"
"log"
2017-07-21 14:04:16 +02:00
"regexp"
2018-09-08 21:16:25 +02:00
"sort"
2016-09-27 22:05:44 +02:00
"strconv"
2017-07-22 14:36:55 +02:00
"strings"
2018-03-31 10:58:37 +02:00
"sync"
2016-09-27 22:05:44 +02:00
"time"
2016-09-25 22:34:02 +02:00
"github.com/nlopes/slack"
2017-07-21 14:04:16 +02:00
"github.com/erroneousboat/slack-term/components"
2017-07-21 14:04:16 +02:00
"github.com/erroneousboat/slack-term/config"
2016-09-25 22:34:02 +02:00
)
type SlackService struct {
2017-12-16 22:54:00 +01:00
Config *config.Config
2017-12-01 12:05:27 +01:00
Client *slack.Client
RTM *slack.RTM
Conversations []slack.Channel
2017-12-01 12:05:27 +01:00
UserCache map[string]string
CurrentUserID string
CurrentUsername string
2016-09-25 22:34:02 +02:00
}
2016-10-02 16:07:35 +02:00
// NewSlackService is the constructor for the SlackService and will initialize
// the RTM and a Client
2017-12-16 22:54:00 +01:00
func NewSlackService(config *config.Config) (*SlackService, error) {
2016-09-29 21:19:09 +02:00
svc := &SlackService{
2017-12-16 22:54:00 +01:00
Config: config,
Client: slack.New(config.SlackToken),
2016-09-29 21:19:09 +02:00
UserCache: make(map[string]string),
}
2016-09-25 22:34:02 +02:00
// Get user associated with token, mainly
// used to identify user when new messages
// arrives
authTest, err := svc.Client.AuthTest()
if err != nil {
return nil, errors.New("not able to authorize client, check your connection and if your slack-token is set correctly")
}
svc.CurrentUserID = authTest.UserID
2016-09-25 22:34:02 +02:00
// Create RTM
svc.RTM = svc.Client.NewRTM()
2016-09-25 22:34:02 +02:00
go svc.RTM.ManageConnection()
2016-10-02 16:07:35 +02:00
// Creation of user cache this speeds up
// the uncovering of usernames of messages
2016-09-30 11:22:40 +02:00
users, _ := svc.Client.GetUsers()
for _, user := range users {
// only add non-deleted users
if !user.Deleted {
svc.UserCache[user.ID] = user.Name
}
2016-09-30 11:22:40 +02:00
}
2017-12-01 12:05:27 +01:00
// Get name of current user
currentUser, err := svc.Client.GetUserInfo(svc.CurrentUserID)
if err != nil {
svc.CurrentUsername = "slack-term"
}
svc.CurrentUsername = currentUser.Name
return svc, nil
2016-09-25 22:34:02 +02:00
}
func (s *SlackService) GetChannels() []components.ChannelItem {
2018-08-26 14:12:23 +02:00
slackChans := make([]slack.Channel, 0)
// Initial request
initChans, initCur, err := s.Client.GetConversations(
&slack.GetConversationsParameters{
ExcludeArchived: "true",
Limit: 10,
Types: []string{
"public_channel",
"private_channel",
"im",
"mpim",
},
},
)
if err != nil {
log.Fatal(err) // FIXME
}
slackChans = append(slackChans, initChans...)
// Paginate over additional channels
nextCur := initCur
for nextCur != "" {
channels, cursor, err := s.Client.GetConversations(
&slack.GetConversationsParameters{
Cursor: nextCur,
ExcludeArchived: "true",
Limit: 10,
Types: []string{
"public_channel",
"private_channel",
"im",
"mpim",
},
},
)
if err != nil {
log.Fatal(err) // FIXME
}
slackChans = append(slackChans, channels...)
nextCur = cursor
}
2018-09-08 21:16:25 +02:00
type tempChan struct {
channelItem components.ChannelItem
slackChannel slack.Channel
}
2018-09-08 21:16:25 +02:00
buckets := make(map[string][]tempChan)
for _, chn := range slackChans {
// TODO: shared channels?
2018-09-08 21:16:25 +02:00
chanItem := s.createChannelItem(chn)
2018-08-26 14:12:23 +02:00
if chn.IsChannel {
if !chn.IsMember {
continue
}
2018-09-08 21:16:25 +02:00
chanItem.Type = components.ChannelTypeChannel
buckets["channel"] = append(
buckets["channel"],
tempChan{
channelItem: chanItem,
slackChannel: chn,
},
)
2018-08-26 14:12:23 +02:00
}
if chn.IsGroup {
if !chn.IsMember {
continue
}
2018-09-08 21:16:25 +02:00
chanItem.Type = components.ChannelTypeGroup
buckets["group"] = append(
buckets["group"],
tempChan{
channelItem: chanItem,
slackChannel: chn,
},
)
2018-08-26 14:12:23 +02:00
}
if chn.IsMpIM {
// TODO: does it have an IsMember?
// TODO: same api as im?
2018-09-08 21:16:25 +02:00
chanItem.Type = components.ChannelTypeMpIM
buckets["mpim"] = append(
buckets["mpim"],
tempChan{
channelItem: chanItem,
slackChannel: chn,
},
)
2018-08-26 14:12:23 +02:00
}
if chn.IsIM {
2018-09-01 18:59:00 +02:00
// Check if user is deleted, we do this by checking the user id,
// and see if we have the user in the UserCache
name, ok := s.UserCache[chn.User]
if !ok {
continue
}
2018-09-08 21:16:25 +02:00
chanItem.Name = name
chanItem.Type = components.ChannelTypeIM
2018-09-02 10:14:34 +02:00
// TODO: way to speed this up? see SetPresenceChannels
2018-09-02 10:14:34 +02:00
// TODO: err
2018-09-08 21:16:25 +02:00
presence, _ := s.GetUserPresence(chn.User)
chanItem.Presence = presence
buckets["im"] = append(
buckets["im"],
tempChan{
channelItem: chanItem,
slackChannel: chn,
},
)
2018-08-26 14:12:23 +02:00
}
2018-09-08 21:16:25 +02:00
}
2018-08-26 14:12:23 +02:00
2018-09-08 21:16:25 +02:00
var chans []components.ChannelItem
for bucket := range buckets {
// Sort channels in every bucket
sort.Slice(buckets[bucket], func(i, j int) bool {
return buckets[bucket][i].channelItem.Name < buckets[bucket][j].channelItem.Name
})
for _, c := range buckets[bucket] {
chans = append(chans, c.channelItem)
s.Conversations = append(s.Conversations, c.slackChannel)
}
}
2018-03-31 10:58:37 +02:00
return chans
}
// TODO:
// We set presence of IM channels here because we need to separately
// issue an API call for every channel, this will speed up that process
2018-03-31 10:58:37 +02:00
// SetPresence will set presence for all IM channels
func (s *SlackService) SetPresenceChannels() {
var wg sync.WaitGroup
for i, channel := range s.Conversations {
if channel.IsIM {
2018-03-31 10:58:37 +02:00
wg.Add(1)
go func(i int) {
// presence, _ := s.GetUserPresence(channel.User)
// s.Channels[i].Presence = presence
2018-03-31 10:58:37 +02:00
wg.Done()
}(i)
}
}
wg.Wait()
}
// GetUserPresence will get the presence of a specific user
func (s *SlackService) GetUserPresence(userID string) (string, error) {
presence, err := s.Client.GetUserPresence(userID)
if err != nil {
return "", err
}
return presence.Presence, nil
}
// MarkAsRead will set the channel as read
func (s *SlackService) MarkAsRead(channelID string) {
// TODO: does this work with other channel types? See old one below
s.Client.SetChannelReadMark(
channelID, fmt.Sprintf("%f",
float64(time.Now().Unix())),
)
// switch channel.Type {
// case ChannelTypeChannel:
// s.Client.SetChannelReadMark(
// channel.ID, fmt.Sprintf("%f",
// float64(time.Now().Unix())),
// )
// case ChannelTypeGroup:
// s.Client.SetGroupReadMark(
// channel.ID, fmt.Sprintf("%f",
// float64(time.Now().Unix())),
// )
// case ChannelTypeIM:
// s.Client.MarkIMChannel(
// channel.ID, fmt.Sprintf("%f",
// float64(time.Now().Unix())),
// )
// }
2018-04-01 13:03:28 +02:00
}
2016-10-29 23:59:16 +02:00
// SendMessage will send a message to a particular channel
func (s *SlackService) SendMessage(channelID string, message string) error {
2016-09-27 22:05:44 +02:00
// https://godoc.org/github.com/nlopes/slack#PostMessageParameters
2016-09-28 22:10:04 +02:00
postParams := slack.PostMessageParameters{
AsUser: true,
Username: s.CurrentUsername,
LinkNames: 1,
2016-09-28 22:10:04 +02:00
}
2016-09-27 22:05:44 +02:00
// https://godoc.org/github.com/nlopes/slack#Client.PostMessage
_, _, err := s.Client.PostMessage(channelID, message, postParams)
if err != nil {
return err
}
return nil
2016-09-27 22:05:44 +02:00
}
2016-09-25 22:34:02 +02:00
2016-10-29 23:59:16 +02:00
// GetMessages will get messages for a channel, group or im channel delimited
// by a count.
func (s *SlackService) GetMessages(channelID string, count int) []components.Message {
// TODO: check other parameters
// https://godoc.org/github.com/nlopes/slack#GetConversationHistoryParameters
historyParams := slack.GetConversationHistoryParameters{
ChannelID: channelID,
Limit: count,
2016-09-30 23:52:26 +02:00
Inclusive: false,
}
history, err := s.Client.GetConversationHistory(&historyParams)
if err != nil {
log.Fatal(err) // FIXME
2016-09-30 23:52:26 +02:00
}
// Construct the messages
2017-12-03 21:43:33 +01:00
var messages []components.Message
2016-09-30 23:52:26 +02:00
for _, message := range history.Messages {
msg := s.CreateMessage(message)
2016-10-09 14:19:28 +02:00
messages = append(messages, msg...)
2016-09-25 22:34:02 +02:00
}
2016-10-11 09:33:56 +02:00
// Reverse the order of the messages, we want the newest in
// the last place
2017-12-03 21:43:33 +01:00
var messagesReversed []components.Message
2016-10-11 09:33:56 +02:00
for i := len(messages) - 1; i >= 0; i-- {
messagesReversed = append(messagesReversed, messages[i])
}
return messagesReversed
2016-09-25 22:34:02 +02:00
}
2016-09-29 21:19:09 +02:00
// CreateMessage will create a string formatted message that can be rendered
// in the Chat pane.
//
// [23:59] <erroneousboat> Hello world!
//
2016-10-09 14:19:28 +02:00
// This returns an array of string because we will try to uncover attachments
// associated with messages.
2017-12-03 21:43:33 +01:00
func (s *SlackService) CreateMessage(message slack.Message) []components.Message {
var msgs []components.Message
2016-09-29 21:19:09 +02:00
var name string
// Get username from cache
name, ok := s.UserCache[message.User]
// Name not in cache
if !ok {
2016-09-30 11:22:40 +02:00
if message.BotID != "" {
2016-09-29 21:19:09 +02:00
// Name not found, perhaps a bot, use Username
2016-09-30 11:22:40 +02:00
name, ok = s.UserCache[message.BotID]
if !ok {
// Not found in cache, add it
name = message.Username
s.UserCache[message.BotID] = message.Username
}
} else {
// Not a bot, not in cache, get user info
user, err := s.Client.GetUserInfo(message.User)
if err != nil {
name = "unknown"
s.UserCache[message.User] = name
} else {
name = user.Name
s.UserCache[message.User] = user.Name
2016-09-29 21:19:09 +02:00
}
}
}
if name == "" {
name = "unknown"
}
2016-10-09 14:19:28 +02:00
// When there are attachments append them
if len(message.Attachments) > 0 {
msgs = append(msgs, s.CreateMessageFromAttachments(message.Attachments)...)
2016-10-09 14:19:28 +02:00
}
2016-09-29 21:19:09 +02:00
// Parse time
floatTime, err := strconv.ParseFloat(message.Timestamp, 64)
if err != nil {
floatTime = 0.0
}
intTime := int64(floatTime)
// Format message
msg := components.Message{
Time: time.Unix(intTime, 0),
Name: name,
Content: parseMessage(s, message.Text),
StyleTime: s.Config.Theme.Message.Time,
StyleName: s.Config.Theme.Message.Name,
StyleText: s.Config.Theme.Message.Text,
FormatTime: s.Config.Theme.Message.TimeFormat,
}
2016-09-29 21:19:09 +02:00
2017-12-03 21:43:33 +01:00
msgs = append(msgs, msg)
2016-10-09 14:19:28 +02:00
2016-10-11 09:33:56 +02:00
return msgs
2016-09-29 21:19:09 +02:00
}
2018-03-24 13:56:55 +01:00
func (s *SlackService) CreateMessageFromMessageEvent(message *slack.MessageEvent) ([]components.Message, error) {
2016-09-29 21:19:09 +02:00
2017-12-03 21:43:33 +01:00
var msgs []components.Message
2016-09-29 21:19:09 +02:00
var name string
2018-03-24 13:56:55 +01:00
switch message.SubType {
case "message_changed":
// Append (edited) when an edited message is received
2016-10-30 15:38:13 +01:00
message = &slack.MessageEvent{Msg: *message.SubMessage}
message.Text = fmt.Sprintf("%s (edited)", message.Text)
2018-03-24 13:56:55 +01:00
case "message_replied":
// Ignore reply events
return nil, errors.New("ignoring reply events")
2016-10-30 15:38:13 +01:00
}
2016-09-29 21:19:09 +02:00
// Get username from cache
name, ok := s.UserCache[message.User]
// Name not in cache
if !ok {
2016-09-30 11:22:40 +02:00
if message.BotID != "" {
2016-09-29 21:19:09 +02:00
// Name not found, perhaps a bot, use Username
2016-09-30 11:22:40 +02:00
name, ok = s.UserCache[message.BotID]
if !ok {
// Not found in cache, add it
name = message.Username
s.UserCache[message.BotID] = message.Username
}
} else {
// Not a bot, not in cache, get user info
user, err := s.Client.GetUserInfo(message.User)
if err != nil {
name = "unknown"
s.UserCache[message.User] = name
} else {
name = user.Name
s.UserCache[message.User] = user.Name
2016-09-29 21:19:09 +02:00
}
}
}
if name == "" {
name = "unknown"
}
2016-10-09 14:19:28 +02:00
// When there are attachments append them
if len(message.Attachments) > 0 {
msgs = append(msgs, s.CreateMessageFromAttachments(message.Attachments)...)
2016-10-09 14:19:28 +02:00
}
2016-09-29 21:19:09 +02:00
// Parse time
floatTime, err := strconv.ParseFloat(message.Timestamp, 64)
if err != nil {
floatTime = 0.0
}
intTime := int64(floatTime)
// Format message
msg := components.Message{
Time: time.Unix(intTime, 0),
Name: name,
Content: parseMessage(s, message.Text),
StyleTime: s.Config.Theme.Message.Time,
StyleName: s.Config.Theme.Message.Name,
StyleText: s.Config.Theme.Message.Text,
FormatTime: s.Config.Theme.Message.TimeFormat,
}
2017-12-03 21:43:33 +01:00
msgs = append(msgs, msg)
2016-10-09 14:19:28 +02:00
2018-03-24 13:56:55 +01:00
return msgs, nil
2016-10-09 14:19:28 +02:00
}
2017-07-22 14:36:55 +02:00
// parseMessage will parse a message string and find and replace:
// - emoji's
// - mentions
2017-07-22 14:36:55 +02:00
func parseMessage(s *SlackService, msg string) string {
2018-08-11 13:19:58 +02:00
if s.Config.Emoji {
msg = parseEmoji(msg)
}
2017-07-22 14:36:55 +02:00
msg = parseMentions(s, msg)
return msg
}
// parseMentions will try to find mention placeholders in the message
// string and replace them with the correct username with and @ symbol
//
// Mentions have the following format:
// <@U12345|erroneousboat>
// <@U12345>
2017-07-22 14:36:55 +02:00
func parseMentions(s *SlackService, msg string) string {
r := regexp.MustCompile(`\<@(\w+\|*\w+)\>`)
return r.ReplaceAllStringFunc(
msg, func(str string) string {
2017-12-01 13:24:02 +01:00
rs := r.FindStringSubmatch(str)
if len(rs) < 1 {
return str
}
2017-07-22 14:36:55 +02:00
var userID string
split := strings.Split(rs[1], "|")
if len(split) > 0 {
userID = split[0]
} else {
userID = rs[1]
}
name, ok := s.UserCache[userID]
if !ok {
user, err := s.Client.GetUserInfo(userID)
if err != nil {
name = "unknown"
s.UserCache[userID] = name
} else {
name = user.Name
s.UserCache[userID] = user.Name
}
}
if name == "" {
name = "unknown"
}
return "@" + name
},
)
}
// parseEmoji will try to find emoji placeholders in the message
// string and replace them with the correct unicode equivalent
func parseEmoji(msg string) string {
r := regexp.MustCompile("(:\\w+:)")
return r.ReplaceAllStringFunc(
msg, func(str string) string {
code, ok := config.EmojiCodemap[str]
if !ok {
return str
}
return code
},
)
}
// CreateMessageFromAttachments will construct a array of string of the Field
2016-10-09 14:19:28 +02:00
// values of Attachments from a Message.
func (s *SlackService) CreateMessageFromAttachments(atts []slack.Attachment) []components.Message {
2017-12-03 21:43:33 +01:00
var msgs []components.Message
2016-10-09 14:19:28 +02:00
for _, att := range atts {
for i := len(att.Fields) - 1; i >= 0; i-- {
2017-12-03 21:43:33 +01:00
msgs = append(msgs, components.Message{
Content: fmt.Sprintf(
2016-10-09 14:19:28 +02:00
"%s %s",
att.Fields[i].Title,
att.Fields[i].Value,
),
StyleTime: s.Config.Theme.Message.Time,
StyleName: s.Config.Theme.Message.Name,
StyleText: s.Config.Theme.Message.Text,
FormatTime: s.Config.Theme.Message.TimeFormat,
2017-12-03 21:43:33 +01:00
},
2016-10-09 14:19:28 +02:00
)
}
if att.Text != "" {
2017-12-03 21:43:33 +01:00
msgs = append(
msgs,
components.Message{
Content: fmt.Sprintf("%s", att.Text),
StyleTime: s.Config.Theme.Message.Time,
StyleName: s.Config.Theme.Message.Name,
StyleText: s.Config.Theme.Message.Text,
FormatTime: s.Config.Theme.Message.TimeFormat,
},
2017-12-03 21:43:33 +01:00
)
}
if att.Title != "" {
2017-12-03 21:43:33 +01:00
msgs = append(
msgs,
components.Message{
Content: fmt.Sprintf("%s", att.Title),
StyleTime: s.Config.Theme.Message.Time,
StyleName: s.Config.Theme.Message.Name,
StyleText: s.Config.Theme.Message.Text,
FormatTime: s.Config.Theme.Message.TimeFormat,
},
2017-12-03 21:43:33 +01:00
)
}
2016-10-09 14:19:28 +02:00
}
2016-10-09 14:19:28 +02:00
return msgs
2016-09-29 21:19:09 +02:00
}
2018-09-08 21:16:25 +02:00
func (s *SlackService) createChannelItem(chn slack.Channel) components.ChannelItem {
return components.ChannelItem{
ID: chn.ID,
Name: chn.Name,
Topic: chn.Topic.Value,
UserID: chn.User,
StylePrefix: s.Config.Theme.Channel.Prefix,
StyleIcon: s.Config.Theme.Channel.Icon,
StyleText: s.Config.Theme.Channel.Text,
}
}