-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsapi.go
94 lines (72 loc) · 1.23 KB
/
wsapi.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
package regolt
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
const WS_URL = "wss://ws.revolt.chat"
type Session struct {
sync.RWMutex
ws *websocket.Conn
wsMutex sync.RWMutex
http *http.Client
handlers map[string][]eventHandler
Token string
}
func (s *Session) Open() error {
var err error
if s.Token == "" {
return fmt.Errorf("no token")
}
s.Lock()
defer s.Unlock()
if s.ws != nil {
return fmt.Errorf("ws open already")
}
s.ws, _, err = websocket.DefaultDialer.Dial(WS_URL, nil)
if err != nil {
return err
}
s.authenticate()
close := make(chan struct{})
go s.listener(close)
go s.heartbeat(close)
return nil
}
func (s *Session) listener(close <-chan struct{}) {
for {
_, message, err := s.ws.ReadMessage()
if err != nil {
return
}
select {
case <-close:
return
default:
go s.handler(message)
}
}
}
func (s *Session) heartbeat(close <-chan struct{}) {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
h := struct {
Type string `json:"type"`
Data int `json:"data"`
}{
Type: "Ping",
Data: 0,
}
for {
s.wsMutex.Lock()
s.ws.WriteJSON(h)
s.wsMutex.Unlock()
select {
case <-ticker.C:
case <-close:
return
}
}
}