golang-lib/websocket/session.go

96 lines
2.2 KiB
Go
Raw Normal View History

2017-10-25 18:42:44 +02:00
package websocket
import (
"sync"
"github.com/google/uuid"
)
// SessionMessageInit subject in messages
2017-10-25 18:42:44 +02:00
const SessionMessageInit = "session_init"
// SessionManager to handle reconnected websocket
2017-10-25 18:42:44 +02:00
type SessionManager struct {
sessionToClient map[uuid.UUID]map[string]*Client
clientToSession map[string]uuid.UUID
sync.Mutex
}
// NewSessionManager to get a new SessionManager
2017-10-25 18:42:44 +02:00
func NewSessionManager() *SessionManager {
return &SessionManager{
sessionToClient: make(map[uuid.UUID]map[string]*Client),
clientToSession: make(map[string]uuid.UUID),
}
}
// Init Session for given Client
2017-10-25 18:42:44 +02:00
func (s *SessionManager) Init(c *Client) {
c.Write(&Message{
From: c,
Subject: SessionMessageInit,
})
2017-10-25 18:42:44 +02:00
}
// HandleMessage of client for Session
2017-10-25 18:42:44 +02:00
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
}
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
}
delete(s.sessionToClient, session)
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
}
// Send a message to a specific Session (and all his Websocket clients)
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)
}
}