forked from bearyinnovative/bearychat-go
/
rtm_message.go
128 lines (100 loc) · 2.76 KB
/
rtm_message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package bearychat
import "regexp"
type RTMMessageType string
const (
RTMMessageTypeUnknown RTMMessageType = "unknown"
RTMMessageTypePing = "ping"
RTMMessageTypePong = "pong"
RTMMessageTypeReply = "reply"
RTMMessageTypeOk = "ok"
RTMMessageTypeP2PMessage = "message"
RTMMessageTypeP2PTyping = "typing"
RTMMessageTypeChannelMessage = "channel_message"
RTMMessageTypeChannelTyping = "channel_typing"
RTMMessageTypeUpdateUserConnection = "update_user_connection"
)
// RTMMessage represents a message entity send over RTM protocol.
type RTMMessage map[string]interface{}
func (m RTMMessage) Type() RTMMessageType {
if t, present := m["type"]; present {
if mtype, ok := t.(string); ok {
return RTMMessageType(mtype)
}
if mtype, ok := t.(RTMMessageType); ok {
return mtype
}
}
return RTMMessageTypeUnknown
}
// Reply a message (with copying type, vchannel_id)
func (m RTMMessage) Reply(text string) RTMMessage {
reply := RTMMessage{
"text": text,
"vchannel_id": m["vchannel_id"],
}
if m.IsP2P() {
reply["type"] = RTMMessageTypeP2PMessage
reply["to_uid"] = m["uid"]
} else {
reply["type"] = RTMMessageTypeChannelMessage
reply["channel_id"] = m["channel_id"]
}
return reply
}
// Refer a message
func (m RTMMessage) Refer(text string) RTMMessage {
refer := m.Reply(text)
refer["refer_key"] = m["key"]
return refer
}
func (m RTMMessage) IsP2P() bool {
mt := m.Type()
if mt == RTMMessageTypeP2PMessage || mt == RTMMessageTypeP2PTyping {
return true
}
return false
}
func (m RTMMessage) IsChatMessage() bool {
mt := m.Type()
if mt == RTMMessageTypeP2PMessage || mt == RTMMessageTypeChannelMessage {
return true
}
return false
}
func (m RTMMessage) IsFromUser(u User) bool {
return m.IsFromUID(u.Id)
}
func (m RTMMessage) IsFromUID(uid string) bool {
return m["uid"] == uid
}
func (m RTMMessage) Text() string {
if text, ok := m["text"].(string); ok {
return text
}
return ""
}
func (m RTMMessage) ParseMentionUser(u User) (bool, string) {
return m.ParseMentionUID(u.Id)
}
var mentionUserRegex = regexp.MustCompile("@<=(=[A-Za-z0-9]+)=> ")
func (m RTMMessage) ParseMentionUID(uid string) (bool, string) {
text := m.Text()
if m.IsP2P() {
return true, text
}
if text == "" {
return false, text
}
locs := mentionUserRegex.FindAllStringSubmatchIndex(text, -1)
if len(locs) == 0 {
return false, text
}
for _, loc := range locs {
// "@<==1=> xxx" -> [0 8 3 5]
// [3:5] "=1" [8:] "xxx"
if text[loc[2]:loc[3]] == uid {
return true, text[loc[1]:]
}
}
return false, text
}