-
Notifications
You must be signed in to change notification settings - Fork 1
/
ws_2.go
178 lines (139 loc) · 3.38 KB
/
ws_2.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
package guildedgo
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
type RawEvent2 struct {
OP int `json:"op"`
T string `json:"t"`
S string `json:"s"`
Data json.RawMessage `json:"d"`
}
type WelcomeOP struct {
HeartbeatInterval int `json:"heartbeatIntervalMs"`
}
var (
newline = []byte{'\n'}
space = []byte{' '}
)
func (c *Client) Open() {
var err error
c.Lock()
defer c.Unlock()
if c.conn != nil {
return
}
header := http.Header{}
header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token))
c.conn, _, err = websocket.DefaultDialer.Dial("wss://www.guilded.gg/websocket/v1", header)
if err != nil {
log.Fatalln("Failed to connect to websocket: ", err.Error())
}
c.conn.SetCloseHandler(func(code int, text string) error {
return nil
})
defer func() {
if err != nil {
c.conn.Close()
c.conn = nil
}
}()
// Get the welcome message from Guilded
_, m, err := c.conn.ReadMessage()
if err != nil {
log.Fatalln("Failed to read message: ", err.Error())
}
m = bytes.TrimSpace(bytes.Replace(m, newline, space, -1))
event := c.onWelcomeMessage(m)
if event == nil {
return
}
c.listening = make(chan struct{})
go c.heartbeat(c.conn, c.listening, event.HeartbeatInterval)
go c.listen(c.conn, c.listening)
log.Println("Listening for messages in main")
}
func (c *Client) listen(wsConn *websocket.Conn, listening <-chan struct{}) {
for {
select {
case <-listening:
return
default:
_, msg, err := wsConn.ReadMessage()
if err != nil {
log.Println("Failed to read message: ", err.Error())
return
}
msg = bytes.TrimSpace(bytes.Replace(msg, newline, space, -1))
c.onEvent(msg)
}
}
}
func (c *Client) heartbeat(wsConn *websocket.Conn, listening <-chan struct{}, intervalMs int) {
ticker := time.NewTicker(time.Duration(intervalMs) * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
log.Println("Sending heartbeat")
err := wsConn.WriteMessage(websocket.TextMessage, []byte(""))
if err != nil {
log.Println("Failed to send heartbeat: ", err.Error())
}
case <-listening:
return
}
}
}
func (c *Client) Close() {
c.Lock()
if c.listening != nil {
log.Println("Closing listening channel")
close(c.listening)
c.listening = nil
}
if c.conn != nil {
log.Println("Closing websocket connection")
c.wsMutex.Lock()
err := c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
c.wsMutex.Unlock()
if err != nil {
log.Println("Failed to write close message: ", err.Error())
}
time.Sleep(1 * time.Second)
log.Println("Closing websocket connection")
err = c.conn.Close()
if err != nil {
log.Println("Failed to close websocket connection: ", err.Error())
}
c.conn = nil
}
c.Unlock()
log.Println("Closed websocket connection")
return
}
func (c *Client) onWelcomeMessage(msg []byte) *WelcomeOP {
var err error
reader := bytes.NewBuffer(msg)
var re RawEvent2
decoder := json.NewDecoder(reader)
err = decoder.Decode(&re)
if err != nil {
log.Println("Failed to decode raw event")
}
if re.OP != 1 {
log.Println("Expected OP code 1, got", re.OP)
return nil
}
var h WelcomeOP
err = json.Unmarshal(re.Data, &h)
if err != nil {
log.Printf("Failed to unmarshal event data for %q. Error: %s", re.T, err.Error())
}
return &h
}