dispatch/server/session.go

89 lines
1.4 KiB
Go
Raw Normal View History

package server
2015-01-17 01:37:21 +00:00
import (
"sync"
2015-06-05 22:34:13 +00:00
"github.com/khlieng/name_pending/irc"
"github.com/khlieng/name_pending/storage"
2015-01-17 01:37:21 +00:00
)
type Session struct {
2015-06-05 22:34:13 +00:00
irc map[string]*irc.Client
2015-01-17 01:37:21 +00:00
ircLock sync.Mutex
2015-06-05 22:34:13 +00:00
ws map[string]*conn
2015-01-17 01:37:21 +00:00
wsLock sync.Mutex
2015-06-07 04:32:19 +00:00
out chan WSResponse
2015-01-17 01:37:21 +00:00
user *storage.User
2015-01-17 01:37:21 +00:00
}
func NewSession() *Session {
return &Session{
2015-06-05 22:34:13 +00:00
irc: make(map[string]*irc.Client),
ws: make(map[string]*conn),
2015-06-07 04:32:19 +00:00
out: make(chan WSResponse, 32),
2015-01-17 01:37:21 +00:00
}
}
2015-06-05 22:34:13 +00:00
func (s *Session) getIRC(server string) (*irc.Client, bool) {
2015-01-17 01:37:21 +00:00
s.ircLock.Lock()
2015-06-05 22:34:13 +00:00
i, ok := s.irc[server]
s.ircLock.Unlock()
2015-06-05 22:34:13 +00:00
return i, ok
2015-01-17 01:37:21 +00:00
}
2015-06-05 22:34:13 +00:00
func (s *Session) setIRC(server string, i *irc.Client) {
2015-01-17 01:37:21 +00:00
s.ircLock.Lock()
2015-06-05 22:34:13 +00:00
s.irc[server] = i
2015-01-17 01:37:21 +00:00
s.ircLock.Unlock()
}
func (s *Session) deleteIRC(server string) {
s.ircLock.Lock()
delete(s.irc, server)
s.ircLock.Unlock()
}
func (s *Session) numIRC() int {
s.ircLock.Lock()
n := len(s.irc)
s.ircLock.Unlock()
return n
}
2015-06-05 22:34:13 +00:00
func (s *Session) setWS(addr string, w *conn) {
2015-01-17 01:37:21 +00:00
s.wsLock.Lock()
2015-06-04 00:06:17 +00:00
s.ws[addr] = w
2015-01-17 01:37:21 +00:00
s.wsLock.Unlock()
}
func (s *Session) deleteWS(addr string) {
s.wsLock.Lock()
delete(s.ws, addr)
s.wsLock.Unlock()
}
func (s *Session) sendJSON(t string, v interface{}) {
2015-06-07 04:32:19 +00:00
s.out <- WSResponse{t, v}
2015-01-17 01:37:21 +00:00
}
func (s *Session) sendError(err error, server string) {
s.sendJSON("error", Error{
Server: server,
Message: err.Error(),
})
}
2015-01-17 01:37:21 +00:00
func (s *Session) write() {
for res := range s.out {
s.wsLock.Lock()
for _, ws := range s.ws {
2015-06-05 22:34:13 +00:00
ws.out <- res
2015-01-17 01:37:21 +00:00
}
s.wsLock.Unlock()
}
}