/
hub.go
140 lines (112 loc) · 2.27 KB
/
hub.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
package belt
import (
"encoding/json"
"log"
"sync/atomic"
"vallon.me/blstr"
)
type Hub struct {
userID *int64
hub *blstr.ByteHub
beltHolder *int64
// chatLog []*ChatMsg
}
func NewHub() *Hub {
var no int64 = -1
return &Hub{
userID: new(int64),
hub: blstr.New(),
beltHolder: &no,
}
}
func (h *Hub) BeltHolder() int64 {
return atomic.LoadInt64(h.beltHolder)
}
func (h *Hub) SetHolder(id int64) {
atomic.SwapInt64(h.beltHolder, id)
}
func (h *Hub) Subscribe(ch chan []byte) (int, error) {
id := int(atomic.AddInt64(h.userID, 1))
if err := h.hub.Subscribe(id, ch); err != nil {
return 0, err
}
return id, nil
}
func (h *Hub) Unsubscribe(id int) {
h.hub.Unsubscribe(id)
}
type pingMsg struct {
Type string `json:"type"`
Count uint64 `json:"count"`
}
var pingCount uint64
func (h *Hub) Ping() {
b, err := json.Marshal(pingMsg{"ping", atomic.AddUint64(&pingCount, 1)})
if err != nil {
log.Println("[app.Ping]", err)
}
if n := h.hub.Flood(-1, b); 0 < n {
log.Printf("[INFO] %d skipped\n", n)
}
}
type beltUpdateMsg struct {
Type string `json:"type"`
OptionID int64 `json:"optionid"`
}
const (
mute = iota
voice
belt
)
func (h *Hub) sendBeltUpdate(opt Option) error {
b, err := json.Marshal(beltUpdateMsg{"beltUpdate", int64(opt.ID)})
if err != nil {
return err
}
if n := h.hub.Flood(-1, b); 0 < n {
log.Printf("[INFO] %d skipped\n", n)
}
return nil
}
func (h *Hub) sendBeltUnset() error {
b, err := json.Marshal(beltUpdateMsg{"beltUpdate", -1})
if err != nil {
return err
}
if n := h.hub.Flood(-1, b); 0 < n {
log.Printf("[INFO] %d skipped\n", n)
}
return nil
}
type newBetMsg struct {
Type string `json:"type"`
OptionID int64 `json:"optionid"`
Tx BetTx `json:"tx"`
}
func (h *Hub) notifyBet(opt uint, btx BetTx) error {
b, err := json.Marshal(newBetMsg{
Type: "newBet",
OptionID: int64(opt),
Tx: btx,
})
if err != nil {
return err
}
if n := h.hub.Flood(-1, b); 0 < n {
log.Printf("[INFO] %d skipped\n", n)
}
return nil
}
func (h *Hub) notifyVote(opt uint) error {
b, err := json.Marshal(newBetMsg{
Type: "newVote",
OptionID: int64(opt),
})
if err != nil {
return err
}
if n := h.hub.Flood(-1, b); 0 < n {
log.Printf("[INFO] %d skipped\n", n)
}
return nil
}