cwtch/peer/connections/connectionsmanager.go

76 lines
1.6 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()
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()
psc := NewPeerServerConnection(host)
go psc.Run()
2018-03-30 21:16:51 +00:00
psc.GroupMessageHandler = handler
m.serverConnections[host] = psc
m.lock.Unlock()
}
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()
}