-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.go
92 lines (75 loc) · 2 KB
/
websocket.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
package lanyard
import (
"encoding/json"
"strings"
)
const (
WS_URL = "wss://api.lanyard.rest/socket"
)
func singlePresenceUpdate(client WSClient, message string) (*LanyardData, error) {
var data LanyardWSResponse
err := json.Unmarshal([]byte(message), &data)
if err != nil {
return &LanyardData{}, err
}
return data.D, nil
}
func multiplePresenceUpdate(client WSClient, message string) ([]*LanyardData, error) {
var data map[string]json.RawMessage
err := json.Unmarshal([]byte(message), &data)
if err != nil {
return []*LanyardData{}, err
}
var userMap map[string]json.RawMessage
err = json.Unmarshal([]byte(data["d"]), &userMap)
if err != nil {
return []*LanyardData{}, err
}
var userDatas []*LanyardData
for _, item := range userMap {
var userData *LanyardData
err := json.Unmarshal(item, &userData)
if err != nil {
return []*LanyardData{}, err
}
userDatas = append(userDatas, userData)
}
return userDatas, nil
}
func ListenUser(userId string, presenceUpdate func(data *LanyardData)) WSClient {
client := clientFactory("subscribe_to_id", "\"" + userId + "\"", func(client WSClient, message string) {
data, err := singlePresenceUpdate(client, message)
if err != nil {
client.Destroy()
return
}
presenceUpdate(data)
})
return *client
}
func ListenMultipleUsers(userIds []string, presenceUpdate func(data *LanyardData)) WSClient {
var formattedIds []string
for _, id := range userIds {
formattedIds = append(formattedIds, "\""+id+"\"")
}
client := clientFactory("subscribe_to_ids", "[" + strings.Join(formattedIds, ",") + "]", func(client WSClient, message string) {
if (strings.Contains(message, "INIT_STATE")) {
userDatas, err := multiplePresenceUpdate(client, message)
if err != nil {
client.Destroy()
return
}
for _, data := range userDatas {
presenceUpdate(data)
}
} else {
data, err := singlePresenceUpdate(client, message)
if err != nil {
client.Destroy()
return
}
presenceUpdate(data)
}
})
return *client
}