-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsession.go
486 lines (406 loc) · 10.8 KB
/
session.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package dggchat
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
)
// A Session represents a connection to destinygg chat.
type Session struct {
sync.RWMutex
// If true, attempt to reconnect on error
attempToReconnect bool
readOnly bool
loginKey string
originHeader string
wsURL url.URL
ws *websocket.Conn
handlers handlers
state *state
dialer *websocket.Dialer
}
type messageOut struct {
Data string `json:"data"`
}
type privateMessageOut struct {
Nick string `json:"nick"`
Data string `json:"data"`
}
type muteOut struct {
Data string `json:"data"`
Duration int64 `data:"duration,omitempty"`
}
type banOut struct {
Nick string `json:"nick"`
Reason string `json:"reason,omitempty"`
Duration int64 `json:"duration,omitempty"`
Banip bool `json:"banip,omitempty"`
Ispermanent bool `json:"ispermanent"`
}
type pingOut struct {
Timestamp int64 `json:"timestamp"`
}
// ErrAlreadyOpen is thrown when attempting to open a web socket connection
// on a websocket that is already open.
var ErrAlreadyOpen = errors.New("web socket is already open")
// ErrReadOnly is thrown when attempting to send messages using a read-only session.
var ErrReadOnly = errors.New("session is read-only")
var wsURL = url.URL{Scheme: "wss", Host: "www.destiny.gg", Path: "/ws"}
// SetURL changes the url that will be used when connecting to the socket server.
// This should be done before calling *session.Open()
func (s *Session) SetURL(u url.URL) {
s.Lock()
defer s.Unlock()
s.wsURL = u
}
// SetDialer changes the websocket dialer that will be used when connecting to the socket server.
func (s *Session) SetDialer(d websocket.Dialer) {
s.Lock()
defer s.Unlock()
s.dialer = &d
}
// Open opens a websocket connection to destinygg chat.
func (s *Session) Open() error {
s.Lock()
defer s.Unlock()
// Only support a single Open() call.
if s.ws != nil {
return ErrAlreadyOpen
}
return s.open()
}
// call with locks held
func (s *Session) open() error {
// Repeatedly calling Open() acts like reconnect.
// this makes sure any old routines die.
if s.ws != nil {
_ = s.ws.Close()
s.ws = nil
}
header := http.Header{}
if strings.TrimSpace(s.originHeader) != "" {
_, err := url.ParseRequestURI(s.originHeader)
if err != nil {
return err
}
header.Add("Origin", s.originHeader)
}
if !s.readOnly {
header.Add("Cookie", fmt.Sprintf("authtoken=%s", s.loginKey))
}
ws, _, err := s.dialer.Dial(s.wsURL.String(), header)
if err != nil {
return err
}
s.ws = ws
go s.listen()
return nil
}
// Close cleanly closes the connection and stops running listeners
func (s *Session) Close() error {
s.Lock()
defer s.Unlock()
// Assume if Close() is explicitly called, we do not want reconnection behaviour
s.attempToReconnect = false
if s.ws == nil {
return nil
}
err := s.ws.Close()
if err != nil {
return err
}
s.ws = nil
return nil
}
func (s *Session) reconnect() {
wait := 1
for {
s.Lock()
err := s.open()
s.Unlock()
if err == nil {
return
}
wait *= 2
if wait > 32 {
wait = 32
}
time.Sleep(time.Duration(wait) * time.Second)
}
}
func (s *Session) listen() {
for {
_, message, err := s.ws.ReadMessage()
if err != nil {
if s.handlers.socketErrorHandler != nil {
s.handlers.socketErrorHandler(err, s)
}
if s.attempToReconnect {
s.reconnect()
}
return
}
mslice := strings.SplitN(string(message[:]), " ", 2)
if len(mslice) != 2 {
continue
}
mType := mslice[0]
mContent := mslice[1]
switch mType {
case "MSG":
m, err := parseMessage(mContent)
if s.handlers.msgHandler == nil || err != nil {
continue
}
s.handlers.msgHandler(m, s)
case "PIN":
pin, err := parsePin(mContent)
if s.handlers.pinHandler == nil || err != nil {
continue
}
s.handlers.pinHandler(pin, s)
case "SUBSCRIPTION", "GIFTSUB", "MASSGIFT":
sub, err := parseSubscription(mContent)
if s.handlers.subscriptionHandler == nil || err != nil {
continue
}
s.handlers.subscriptionHandler(sub, s)
case "DONATION":
dono, err := parseDonation(mContent)
if s.handlers.donationHandler == nil || err != nil {
continue
}
s.handlers.donationHandler(dono, s)
case "MUTE":
mute, err := parseMute(mContent, s)
if s.handlers.muteHandler == nil || err != nil {
continue
}
s.handlers.muteHandler(mute, s)
case "UNMUTE":
mute, err := parseMute(mContent, s)
if s.handlers.muteHandler == nil || err != nil {
continue
}
s.handlers.unmuteHandler(mute, s)
case "BAN":
ban, err := parseBan(mContent, s)
if s.handlers.banHandler == nil || err != nil {
continue
}
s.handlers.banHandler(ban, s)
case "UNBAN":
ban, err := parseBan(mContent, s)
if s.handlers.banHandler == nil || err != nil {
continue
}
s.handlers.unbanHandler(ban, s)
case "SUBONLY":
so, err := parseSubOnly(mContent)
if s.handlers.subOnlyHandler == nil || err != nil {
continue
}
s.handlers.subOnlyHandler(so, s)
case "BROADCAST":
b, err := parseBroadcast(mContent)
if s.handlers.broadcastHandler == nil || err != nil {
continue
}
s.handlers.broadcastHandler(b, s)
case "PRIVMSG":
pm, err := parsePrivateMessage(mContent, s)
if s.handlers.pmHandler == nil || err != nil {
continue
}
s.handlers.pmHandler(pm, s)
case "PRIVMSGSENT":
// confirms sending of a PM was successful.
// If not successful, an ERR message is sent anyways. Ignore this.
case "PING":
case "PONG":
p, err := parsePing(mContent)
if s.handlers.pingHandler == nil || err != nil {
continue
}
s.handlers.pingHandler(p, s)
case "ERR":
if s.handlers.errHandler == nil {
continue
}
errMessage := parseErrorMessage(mContent)
s.handlers.errHandler(errMessage, s)
case "NAMES":
n, err := parseNames(mContent)
if err != nil {
continue
}
s.state.Lock()
s.state.users = n.Users
s.state.Unlock()
if s.handlers.namesHandler != nil {
s.handlers.namesHandler(n, s)
}
case "JOIN":
ra, err := parseRoomAction(mContent)
if err != nil {
continue
}
s.state.addUser(ra.User)
if s.handlers.joinHandler != nil {
s.handlers.joinHandler(ra, s)
}
case "QUIT":
ra, err := parseRoomAction(mContent)
if err != nil {
continue
}
s.state.removeUser(ra.User.Nick)
if s.handlers.quitHandler != nil {
s.handlers.quitHandler(ra, s)
}
case "UPDATEUSER":
u, err := parseUpdateUser(mContent)
if err != nil {
continue
}
s.state.updateUser(u)
if s.handlers.userUpdateHandler != nil {
s.handlers.userUpdateHandler(u, s)
}
case "REFRESH":
// This message is received immediately before the server closes the
// connection because user information was changed, and we need to reinitialize.
// TODO possibly add an eventhandler here
s.reconnect()
return
}
}
}
// GetUser attempts to find the user in the chat room state.
// If the user is found, returns the user and true,
// otherwise false is returned as the second parameter.
func (s *Session) GetUser(name string) (User, bool) {
s.state.RLock()
defer s.state.RUnlock()
for _, user := range s.state.users {
if strings.EqualFold(name, user.Nick) {
return user, true
}
}
return User{}, false
}
// GetUsers returns a list of users currently online
func (s *Session) GetUsers() []User {
s.state.RLock()
defer s.state.RUnlock()
u := make([]User, len(s.state.users))
copy(u, s.state.users)
return u
}
func (s *Session) send(message interface{}, mType string) error {
if s.readOnly {
return ErrReadOnly
}
m, err := json.Marshal(message)
if err != nil {
return err
}
s.Lock()
defer s.Unlock()
// Close() might have been called for some reason, this prevents panicing in those cases
if s.ws == nil {
return errors.New("connection not established")
}
return s.ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("%s %s", mType, m)))
}
// SendMessage sends the given string as a message to chat.
// Note: a return error of nil does not guarantee successful delivery.
// Monitor for error events to ensure the message was sent with no errors.
func (s *Session) SendMessage(message string) error {
m := messageOut{Data: message}
return s.send(m, "MSG")
}
// SendMute mutes the user with the given nick.
// If duration is <= 0, the server uses its built-in default duration
func (s *Session) SendMute(nick string, duration time.Duration) error {
m := muteOut{Data: nick}
if duration > 0 {
m.Duration = int64(duration)
}
return s.send(m, "MUTE")
}
// SendUnmute unmutes the user with the given nick.
func (s *Session) SendUnmute(nick string) error {
m := messageOut{Data: nick}
return s.send(m, "UNMUTE")
}
// SendBan bans the user with the given nick.
// Bans require a ban reason to be specified.
// If duration is <= 0, the server uses its built-in default duration
func (s *Session) SendBan(nick string, reason string, duration time.Duration, banip bool) error {
b := banOut{
Nick: nick,
Reason: reason,
Banip: banip,
}
if duration > 0 {
b.Duration = int64(duration)
}
return s.send(b, "BAN")
}
// SendPermanentBan bans the user with the given nick permanently.
// Bans require a ban reason to be specified.
func (s *Session) SendPermanentBan(nick string, reason string, banip bool) error {
b := banOut{
Nick: nick,
Reason: reason,
Banip: banip,
Ispermanent: true,
}
return s.send(b, "BAN")
}
// SendUnban unbans the user with the given nick.
// Unbanning also removes mutes.
func (s *Session) SendUnban(nick string) error {
b := messageOut{Data: nick}
return s.send(b, "UNBAN")
}
// SendAction calls the SendMessage method but also adds
// "/me" in front of the message to make it a chat action
// same caveat with the returned error value applies.
func (s *Session) SendAction(message string) error {
return s.SendMessage(fmt.Sprintf("/me %s", message))
}
// SendPrivateMessage sends the given user a private message.
func (s *Session) SendPrivateMessage(nick string, message string) error {
p := privateMessageOut{
Nick: nick,
Data: message,
}
return s.send(p, "PRIVMSG")
}
// SendSubOnly modifies the chat subonly mode.
// During subonly mode, only subscribers and some other special user classes are allowed to send messages.
func (s *Session) SendSubOnly(subonly bool) error {
data := "off"
if subonly {
data = "on"
}
so := messageOut{Data: data}
return s.send(so, "SUBONLY")
}
// SendBroadcast sends a broadcast message to chat
func (s *Session) SendBroadcast(message string) error {
b := messageOut{Data: message}
return s.send(b, "BROADCAST")
}
// SendPing sends a ping to the server with the current timestamp.
func (s *Session) SendPing() error {
t := pingOut{Timestamp: timeToUnix(time.Now())}
return s.send(t, "PING")
}