2018-03-15 20:53:22 +00:00
|
|
|
package connections
|
|
|
|
|
|
|
|
import (
|
|
|
|
"git.mascherari.press/cwtch/model"
|
2018-03-30 21:16:51 +00:00
|
|
|
"git.mascherari.press/cwtch/protocol"
|
2018-03-15 20:53:22 +00:00
|
|
|
"sync"
|
2018-03-30 21:16:51 +00:00
|
|
|
"time"
|
2018-03-15 20:53:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Manager struct {
|
|
|
|
peerConnections map[string]*PeerPeerConnection
|
|
|
|
serverConnections map[string]*PeerServerConnection
|
2018-03-30 21:16:51 +00:00
|
|
|
lock sync.Mutex
|
2018-03-15 20:53:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2018-03-15 20:53:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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)) {
|
2018-03-15 20:53:22 +00:00
|
|
|
m.lock.Lock()
|
|
|
|
psc := NewPeerServerConnection(host)
|
|
|
|
go psc.Run()
|
2018-03-30 21:16:51 +00:00
|
|
|
psc.GroupMessageHandler = handler
|
2018-03-15 20:53:22 +00:00
|
|
|
m.serverConnections[host] = psc
|
|
|
|
m.lock.Unlock()
|
|
|
|
}
|
|
|
|
|
2018-05-01 20:44:45 +00:00
|
|
|
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-03-15 20:53:22 +00:00
|
|
|
func (m *Manager) GetPeerPeerConnectionForOnion(host string) (ppc *PeerPeerConnection) {
|
|
|
|
m.lock.Lock()
|
2018-03-30 21:16:51 +00:00
|
|
|
ppc = m.peerConnections[host]
|
2018-03-15 20:53:22 +00:00
|
|
|
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()
|
|
|
|
}
|