-
Notifications
You must be signed in to change notification settings - Fork 4
/
hub.go
97 lines (83 loc) · 2.05 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
package main
import "log"
type message struct {
data []byte
room string
sender *connection
}
type subscription struct {
conn *connection
room string
}
// hub maintains the set of active connections and broadcasts messages to the
// connections.
type hub struct {
// Registered connections.
rooms map[string]map[*connection]bool
// Inbound messages from the connections.
broadcast chan message
// Register requests from the connections.
register chan subscription
// Unregister requests from connections.
unregister chan subscription
}
var h = hub{
broadcast: make(chan message),
register: make(chan subscription),
unregister: make(chan subscription),
rooms: make(map[string]map[*connection]bool),
}
func (h *hub) run() {
for {
select {
case s := <-h.register:
connections := h.rooms[s.room]
if connections == nil {
connections = make(map[*connection]bool)
h.rooms[s.room] = connections
}
h.rooms[s.room][s.conn] = true
log.Printf("Registered room: %s", s.room)
// Send a warning to the connections of the room if there are more than two connections
if len(h.rooms[s.room]) > 2 {
log.Printf("Warning! More than 2 connections in room %s", s.room)
m := message{[]byte(
"{\"command\": \"showWarning\", " +
"\"msg\": \"More than 2 connections are using this token! Are multiple instances of QOwnNotes active?\"}"),
s.room, nil}
sendMessage(m)
}
case s := <-h.unregister:
connections := h.rooms[s.room]
if connections != nil {
if _, ok := connections[s.conn]; ok {
delete(connections, s.conn)
close(s.conn.send)
if len(connections) == 0 {
delete(h.rooms, s.room)
}
}
}
case m := <-h.broadcast:
sendMessage(m)
}
}
}
func sendMessage(m message) {
connections := h.rooms[m.room]
for c := range connections {
// Don't send sender the message back
if c == m.sender {
continue
}
select {
case c.send <- m.data:
default:
close(c.send)
delete(connections, c)
if len(connections) == 0 {
delete(h.rooms, m.room)
}
}
}
}