/
connect.go
224 lines (197 loc) · 6.28 KB
/
connect.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package gatewaySlack
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"time"
"github.com/1egoman/slick/gateway"
"golang.org/x/net/websocket"
)
const pingFrequency = 30 // In seconds
// Connect to the slack persistent socket.
func (c *SlackConnection) Connect() error {
c.connectionStatus = gateway.CONNECTING
// Create buffered channels to listen and send messages on
c.incoming = make(chan gateway.Event, 10)
c.outgoing = make(chan gateway.Event, 10)
// Request a connection url with the token in the struct
log.Println("Requesting slack team connection url...")
var err error
err = c.requestConnectionUrl()
if err != nil {
log.Println("Error getting connection url", err)
c.connectionStatus = gateway.DISCONNECTED
return err
}
log.Printf("Got slack connection url for team %s: %s", c.Team().Name, c.url)
// FIXME: what does this mean?
origin := "http://localhost/"
// Create a connection to the websocket
c.conn, err = websocket.Dial(c.url, "", origin)
if err != nil {
c.connectionStatus = gateway.DISCONNECTED
return err // Panic when cannot talk to messaging servers
}
log.Printf("Slack connection %s made!", c.Team().Name)
// When messages are received, add them to the incoming buffer.
go func(incoming chan gateway.Event) {
var msgRaw = make([]byte, 512)
var n int
var messageBuffer []byte
for {
// Listen for messages, and when some are received, write them to a channel.
if n, err = c.conn.Read(msgRaw); err != nil {
if c.Status() != gateway.DISCONNECTED {
log.Println("Error reading from slack socket", err.Error())
c.connectionStatus = gateway.FAILED
// Try to recover!
// If we were disconnected from the slack socket, then attempt to reconnect.
// This can happen beacause of rate limiting, timeouts, etc...
err = c.requestConnectionUrl()
if err != nil {
log.Println("Error getting connection url", err)
return
}
c.conn, err = websocket.Dial(c.url, "", origin)
if err != nil {
log.Println("Error reading from slack socket for second time", err.Error())
return
} else {
log.Println("Was able to reconnect to slack socket!")
if n, err = c.conn.Read(msgRaw); err != nil {
log.Println("Error reading from slack socket for second time", err.Error())
return
} else {
log.Println("Successful read, recovered from socket error!")
c.connectionStatus = gateway.CONNECTED
}
}
}
}
// Add the latest packet to the message buffer
messageBuffer = append(messageBuffer, msgRaw[:n]...)
// Decode message buffer into a struct so that we can check message type later
var msg map[string]interface{}
err = json.Unmarshal(messageBuffer, &msg)
if err == nil {
// Clear the message buffer after unpacking
messageBuffer = []byte{}
log.Printf("INCOMING %s: %s", c.Team().Name, msgRaw[:n])
if typ, ok := msg["type"].(string); ok {
incoming <- gateway.Event{
Direction: "incoming",
Type: typ,
Data: msg,
}
}
}
}
}(c.incoming)
// When messages are in the outgoing buffer waiting to be sent, send them.
go func(outgoing chan gateway.Event) {
// Add a sequential message id to each message sent, so replies can later be tracked.
messageId := 0
var event gateway.Event
for {
// Assemble the message to send.
event = <-outgoing
event.Data["type"] = event.Type
messageId++
event.Data["id"] = messageId
// Marshal to json
data, err := json.Marshal(event.Data)
if err != nil {
log.Fatal(err)
}
log.Printf("OUTGOING %s: %s", c.Team().Name, data)
// Send it.
if _, err = c.conn.Write(data); err != nil {
if c.Status() != gateway.DISCONNECTED {
log.Println("Error writing to slack socket", err.Error())
c.connectionStatus = gateway.FAILED
// Try to recover!
// If we were disconnected from the slack socket, then attempt to reconnect.
// This can happen beacause of rate limiting, timeouts, etc...
err = c.requestConnectionUrl()
if err != nil {
log.Println("Error getting connection url", err)
return
}
c.conn, err = websocket.Dial(c.url, "", origin)
if err != nil {
log.Println("Error connecting to slack socket for second time", err.Error())
return
} else {
log.Println("Was able to reconnect to slack socket!")
if _, err = c.conn.Write(data); err != nil {
log.Println("Error writing to slack socket for second time", err.Error())
return
} else {
log.Println("Successful write, recovered from socket error!")
c.connectionStatus = gateway.CONNECTED
}
}
}
}
}
}(c.outgoing)
// Periodically ping slack
// This is to ensure slack doesn't think we stopped listening on the socket
go func(outgoing chan gateway.Event) {
pingCount := 0
for {
time.Sleep(pingFrequency * time.Second)
if c.Status() == gateway.CONNECTED {
// Send a ping
outgoing <- gateway.Event{
Type: "ping",
Data: map[string]interface{}{"count": pingCount},
}
pingCount++
} else if c.Status() == gateway.DISCONNECTED {
// If the gateway disconnected, then return
break
}
}
}(c.outgoing)
c.connectionStatus = gateway.CONNECTED
return nil
}
func (c *SlackConnection) requestConnectionUrl() error {
// Make request to slack's api to get websocket credentials
resp, err := httpClient.Get("https://slack.com/api/rtm.start?token=" + c.token)
if err != nil {
return err
}
// Decode json body.
body, _ := ioutil.ReadAll(resp.Body)
var connectionBuffer struct {
Ok bool `json:"ok"`
Url string `json:"url"`
Team gateway.Team `json:"team"`
Self gateway.User `json:"self"`
Users []struct {
Id string `json:"id"`
Presence string `json:"presence"`
} `json:"users"`
}
err = json.Unmarshal(body, &connectionBuffer)
if err != nil {
log.Println("Slack response: " + string(body))
return errors.New("Slack connection error: " + string(body))
}
// Add response data to struct
c.url = connectionBuffer.Url
c.self = connectionBuffer.Self
c.team = connectionBuffer.Team
// Add online statuses for each user
for _, user := range connectionBuffer.Users {
if user.Presence == "away" {
c.userPresence[user.Id] = false
} else {
c.userPresence[user.Id] = true
}
}
return nil
}