forked from cwtch.im/cwtch
1
0
Fork 0
cwtch/peer/connections/connectionsmanager.go

106 lines
2.2 KiB
Go
Raw Normal View History

package connections
import (
"git.mascherari.press/cwtch/model"
2018-03-30 21:16:51 +00:00
"git.mascherari.press/cwtch/protocol"
"sync"
2018-03-30 21:16:51 +00:00
"time"
)
type Manager struct {
peerConnections map[string]*PeerPeerConnection
serverConnections map[string]*PeerServerConnection
2018-03-30 21:16:51 +00:00
lock sync.Mutex
}
func NewConnectionsManager() *Manager {
m := new(Manager)
m.peerConnections = make(map[string]*PeerPeerConnection)
m.serverConnections = make(map[string]*PeerServerConnection)
2018-03-30 21:16:51 +00:00
return m
}
func (m *Manager) ManagePeerConnection(host string, profile *model.Profile) {
m.lock.Lock()
2018-05-03 04:12:45 +00:00
_,exists := m.peerConnections[host]
if !exists {
ppc := NewPeerPeerConnection(host, profile)
go ppc.Run()
m.peerConnections[host] = ppc
}
m.lock.Unlock()
}
2018-03-30 21:16:51 +00:00
func (m *Manager) ManageServerConnection(host string, handler func(string, *protocol.GroupMessage)) {
m.lock.Lock()
2018-05-03 04:12:45 +00:00
_,exists := m.serverConnections[host]
if !exists {
psc := NewPeerServerConnection(host)
go psc.Run()
psc.GroupMessageHandler = handler
m.serverConnections[host] = psc
}
m.lock.Unlock()
}
func (m *Manager) GetPeers() map[string]ConnectionState {
rm := make(map[string]ConnectionState)
m.lock.Lock()
for onion, ppc := range m.peerConnections {
rm[onion] = ppc.GetState()
}
m.lock.Unlock()
return rm
}
2018-05-03 04:12:45 +00:00
func (m *Manager) GetServers() map[string]ConnectionState {
rm := make(map[string]ConnectionState)
m.lock.Lock()
for onion, psc := range m.serverConnections {
rm[onion] = psc.GetState()
}
m.lock.Unlock()
return rm
}
func (m *Manager) GetPeerPeerConnectionForOnion(host string) (ppc *PeerPeerConnection) {
m.lock.Lock()
2018-03-30 21:16:51 +00:00
ppc = m.peerConnections[host]
m.lock.Unlock()
return
}
func (m *Manager) GetPeerServerConnectionForOnion(host string) (psc *PeerServerConnection) {
m.lock.Lock()
psc = m.serverConnections[host]
m.lock.Unlock()
return
}
func (m *Manager) AttemptReconnections() {
m.lock.Lock()
for _, ppc := range m.peerConnections {
if ppc.GetState() == FAILED {
go ppc.Run()
}
}
m.lock.Unlock()
m.lock.Lock()
for _, psc := range m.serverConnections {
if psc.GetState() == FAILED {
go psc.Run()
}
}
m.lock.Unlock()
// Launch Another Run In 30 Seconds
time.Sleep(time.Second * 30)
go m.AttemptReconnections()
}