This repository has been archived by the owner on Jan 12, 2019. It is now read-only.
/
bus.go
77 lines (69 loc) · 1.72 KB
/
bus.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
package main
import (
"github.com/mikefaraponov/chatum"
"github.com/satori/go.uuid"
"sync"
)
type (
Bus interface {
BroadcastExceptUUID(uuid.UUID, *chatum.ServerSideEvent)
BroadcastExceptUsername(string, *chatum.ServerSideEvent)
Add(string, uuid.UUID, chatum.Chatum_CommunicateServer)
Remove(string, uuid.UUID)
}
bus struct {
sync.Mutex
numberOfClientsByUsername map[string]int
clientsById map[uuid.UUID]Client
}
)
type Client struct {
Srv chatum.Chatum_CommunicateServer
Username string
}
func NewBus() Bus {
return &bus{
numberOfClientsByUsername: make(map[string]int),
clientsById: make(map[uuid.UUID]Client),
}
}
func (b *bus) BroadcastExceptUsername(username string, msg *chatum.ServerSideEvent) {
for _, v := range b.clientsById {
if v.Username == username {
continue
}
go v.Srv.Send(msg)
}
}
func (b *bus) BroadcastExceptUUID(uid uuid.UUID, msg *chatum.ServerSideEvent) {
for k, v := range b.clientsById {
if k == uid {
continue
}
go v.Srv.Send(msg)
}
}
func (b *bus) Add(username string, uid uuid.UUID, srv chatum.Chatum_CommunicateServer) {
b.Lock()
defer b.Unlock()
if b.numberOfClientsByUsername[username] == 0 {
b.BroadcastExceptUsername(username, &chatum.ServerSideEvent{
Username: username,
Message: "I am online!",
})
}
b.numberOfClientsByUsername[username] += 1
b.clientsById[uid] = Client{srv, username}
}
func (b *bus) Remove(username string, uid uuid.UUID) {
b.Lock()
defer b.Unlock()
b.numberOfClientsByUsername[username] -= 1
if b.numberOfClientsByUsername[username] == 0 {
b.BroadcastExceptUsername(username, &chatum.ServerSideEvent{
Username: username,
Message: "I am offline!",
})
}
delete(b.clientsById, uid)
}