-
Notifications
You must be signed in to change notification settings - Fork 181
/
chat-hb.go
81 lines (74 loc) · 1.58 KB
/
chat-hb.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
package websocket
import (
"context"
"sync"
"time"
"github.com/pydio/cells/common/proto/chat"
)
var (
hbb map[string]*heartBeater
hbbLocks *sync.Mutex
)
type heartBeater struct {
remove func()
rooms map[string]*chat.ChatRoom
ping chan *chat.ChatRoom
stop chan bool
}
func (h *heartBeater) Start() {
go func() {
defer close(h.ping)
defer close(h.stop)
for {
select {
case r := <-h.ping:
h.rooms[r.Uuid] = r
case <-time.After(20 * time.Second):
h.remove()
return
case <-h.stop:
return
}
}
}()
}
func init() {
hbb = make(map[string]*heartBeater)
hbbLocks = &sync.Mutex{}
}
func (c *ChatHandler) heartbeat(username string, room *chat.ChatRoom) {
hbbLocks.Lock()
defer hbbLocks.Unlock()
var heartbeater *heartBeater
if hb, ok := hbb[username]; ok {
heartbeater = hb
} else {
heartbeater = &heartBeater{
remove: func() {
hbbLocks.Lock()
defer hbbLocks.Unlock()
for _, roomChat := range heartbeater.rooms {
if f, e := c.findOrCreateRoom(context.Background(), roomChat, false); e == nil && f != nil {
if save := c.removeUserFromRoom(f, username); save {
c.getChatClient().PutRoom(context.Background(), &chat.PutRoomRequest{Room: f})
}
}
}
delete(hbb, username)
},
ping: make(chan *chat.ChatRoom),
stop: make(chan bool),
rooms: make(map[string]*chat.ChatRoom),
}
heartbeater.Start()
hbb[username] = heartbeater
}
go func() {
defer func() {
if r := recover(); r != nil {
// avoid send on close channel if ever it happens
}
}()
heartbeater.ping <- room
}()
}