2017-10-25 18:42:44 +02:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
|
|
|
|
|
|
|
const SessionMessageInit = "session_init"
|
|
|
|
|
|
|
|
type SessionManager struct {
|
|
|
|
sessionToClient map[uuid.UUID]map[string]*Client
|
|
|
|
clientToSession map[string]uuid.UUID
|
|
|
|
sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSessionManager() *SessionManager {
|
|
|
|
return &SessionManager{
|
|
|
|
sessionToClient: make(map[uuid.UUID]map[string]*Client),
|
|
|
|
clientToSession: make(map[string]uuid.UUID),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionManager) Init(c *Client) {
|
|
|
|
c.Write(&Message{Subject: SessionMessageInit})
|
|
|
|
}
|
|
|
|
func (s *SessionManager) HandleMessage(msg *Message) bool {
|
|
|
|
if msg == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if msg.ID != uuid.Nil && msg.Subject == SessionMessageInit && msg.From != nil {
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
|
|
|
list := s.sessionToClient[msg.ID]
|
|
|
|
if list == nil {
|
|
|
|
list = make(map[string]*Client)
|
|
|
|
}
|
|
|
|
id := msg.From.GetID()
|
|
|
|
list[id] = msg.From
|
|
|
|
s.clientToSession[id] = msg.ID
|
|
|
|
s.sessionToClient[msg.ID] = list
|
|
|
|
return true
|
2017-10-27 19:40:42 +02:00
|
|
|
} else if msg.From != nil {
|
2017-10-25 18:42:44 +02:00
|
|
|
id := msg.From.GetID()
|
|
|
|
msg.Session = s.clientToSession[id]
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
2017-10-27 19:40:42 +02:00
|
|
|
|
|
|
|
// Remove clients from SessionManagerer
|
|
|
|
// - 1. result: clients removed from session manager
|
|
|
|
// - 2. result: session closed and all clients removed
|
|
|
|
func (s *SessionManager) Remove(c *Client) (client bool, session bool) {
|
2017-10-25 18:42:44 +02:00
|
|
|
if c == nil {
|
2017-10-27 19:40:42 +02:00
|
|
|
return false, false
|
2017-10-25 18:42:44 +02:00
|
|
|
}
|
|
|
|
if id := c.GetID(); id != "" {
|
|
|
|
session := s.clientToSession[id]
|
2017-10-27 19:40:42 +02:00
|
|
|
defer delete(s.clientToSession, id)
|
2017-10-25 18:42:44 +02:00
|
|
|
if session != uuid.Nil {
|
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2017-10-27 19:40:42 +02:00
|
|
|
clients := s.sessionToClient[session]
|
|
|
|
delete(clients, id)
|
|
|
|
if len(clients) > 0 {
|
|
|
|
s.sessionToClient[session] = clients
|
|
|
|
return true, false
|
2017-10-25 18:42:44 +02:00
|
|
|
} else {
|
|
|
|
delete(s.sessionToClient, session)
|
2017-10-27 19:40:42 +02:00
|
|
|
return true, true
|
2017-10-25 18:42:44 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-10-27 19:40:42 +02:00
|
|
|
return false, false
|
2017-10-25 18:42:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionManager) Send(id uuid.UUID, msg *Message) {
|
2018-03-22 22:10:05 +01:00
|
|
|
s.Lock()
|
|
|
|
defer s.Unlock()
|
2017-10-27 19:40:42 +02:00
|
|
|
clients := s.sessionToClient[id]
|
|
|
|
for _, c := range clients {
|
2017-10-25 18:42:44 +02:00
|
|
|
c.Write(msg)
|
|
|
|
}
|
|
|
|
}
|