105 lines
1.6 KiB
Go
105 lines
1.6 KiB
Go
|
package notifier
|
||
|
import (
|
||
|
"errors"
|
||
|
"sync"
|
||
|
)
|
||
|
|
||
|
type Clients struct {
|
||
|
m sync.Map
|
||
|
}
|
||
|
|
||
|
func NewClients() *Clients {
|
||
|
c := &Clients{
|
||
|
m: sync.Map{},
|
||
|
}
|
||
|
return c
|
||
|
}
|
||
|
|
||
|
func (c *Clients) Get(id string) (*Sessions, error) {
|
||
|
v, ok := c.m.Load(id)
|
||
|
if !ok {
|
||
|
return nil, errors.New("not found")
|
||
|
}
|
||
|
if ret, ok := v.(*Sessions); ok {
|
||
|
return ret, nil
|
||
|
}
|
||
|
return nil, errors.New("value not a comsumer")
|
||
|
}
|
||
|
|
||
|
func (c *Clients) SetSession(user string, s *Session) {
|
||
|
ss, err := c.Get(user)
|
||
|
if err != nil {
|
||
|
ss = NewSessions()
|
||
|
}
|
||
|
ss.Set(s.ID(), s)
|
||
|
c.m.Store(user, ss)
|
||
|
}
|
||
|
|
||
|
func (c *Clients) Set(id string, sessions *Sessions) *Sessions {
|
||
|
ss, ok := c.m.Swap(id, sessions)
|
||
|
if !ok {
|
||
|
return nil
|
||
|
}
|
||
|
old, ok := ss.(*Sessions)
|
||
|
if ok {
|
||
|
return old
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (c *Clients) Range(f func(string,* Sessions) bool) {
|
||
|
c.m.Range(func(k, v any) bool {
|
||
|
i, ok := k.(string)
|
||
|
if !ok {
|
||
|
return false
|
||
|
}
|
||
|
ss, ok := v.(*Sessions)
|
||
|
if !ok {
|
||
|
return false
|
||
|
}
|
||
|
return f(i, ss)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func (c *Clients) List() []*Sessions {
|
||
|
ret := []*Sessions{}
|
||
|
c.m.Range(func(key, value any) bool {
|
||
|
ss, ok := value.(*Sessions)
|
||
|
if !ok {
|
||
|
return false
|
||
|
}
|
||
|
ret = append(ret, ss)
|
||
|
return true
|
||
|
})
|
||
|
return ret
|
||
|
}
|
||
|
|
||
|
func (c *Clients) Map() map[string]*Sessions {
|
||
|
ret := make(map[string]*Sessions)
|
||
|
c.m.Range(func(key, value any) bool {
|
||
|
id, ok := key.(string)
|
||
|
if !ok {
|
||
|
return false
|
||
|
}
|
||
|
ss, ok := key.(*Sessions)
|
||
|
if !ok {
|
||
|
return false
|
||
|
}
|
||
|
ret[id] = ss
|
||
|
return true
|
||
|
})
|
||
|
return ret
|
||
|
}
|
||
|
|
||
|
func (c *Clients) Delete(user string) {
|
||
|
c.m.Delete(user)
|
||
|
}
|
||
|
|
||
|
func (c *Clients) DeleteSession(user, id string) {
|
||
|
ss, err := c.Get(user)
|
||
|
if err != nil {
|
||
|
return
|
||
|
}
|
||
|
ss.Delete(id)
|
||
|
}
|