Official cwtch.im peer and server implementations.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connectionsmanager.go 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package connections
  2. import (
  3. "git.mascherari.press/cwtch/model"
  4. "git.mascherari.press/cwtch/protocol"
  5. "sync"
  6. "time"
  7. )
  8. type Manager struct {
  9. peerConnections map[string]*PeerPeerConnection
  10. serverConnections map[string]*PeerServerConnection
  11. lock sync.Mutex
  12. }
  13. func NewConnectionsManager() *Manager {
  14. m := new(Manager)
  15. m.peerConnections = make(map[string]*PeerPeerConnection)
  16. m.serverConnections = make(map[string]*PeerServerConnection)
  17. return m
  18. }
  19. func (m *Manager) ManagePeerConnection(host string, profile *model.Profile) {
  20. m.lock.Lock()
  21. ppc := NewPeerPeerConnection(host, profile)
  22. go ppc.Run()
  23. m.peerConnections[host] = ppc
  24. m.lock.Unlock()
  25. }
  26. func (m *Manager) ManageServerConnection(host string, handler func(string, *protocol.GroupMessage)) {
  27. m.lock.Lock()
  28. psc := NewPeerServerConnection(host)
  29. go psc.Run()
  30. psc.GroupMessageHandler = handler
  31. m.serverConnections[host] = psc
  32. m.lock.Unlock()
  33. }
  34. func (m *Manager) GetPeerPeerConnectionForOnion(host string) (ppc *PeerPeerConnection) {
  35. m.lock.Lock()
  36. ppc = m.peerConnections[host]
  37. m.lock.Unlock()
  38. return
  39. }
  40. func (m *Manager) GetPeerServerConnectionForOnion(host string) (psc *PeerServerConnection) {
  41. m.lock.Lock()
  42. psc = m.serverConnections[host]
  43. m.lock.Unlock()
  44. return
  45. }
  46. func (m *Manager) AttemptReconnections() {
  47. m.lock.Lock()
  48. for _, ppc := range m.peerConnections {
  49. if ppc.GetState() == FAILED {
  50. go ppc.Run()
  51. }
  52. }
  53. m.lock.Unlock()
  54. m.lock.Lock()
  55. for _, psc := range m.serverConnections {
  56. if psc.GetState() == FAILED {
  57. go psc.Run()
  58. }
  59. }
  60. m.lock.Unlock()
  61. // Launch Another Run In 30 Seconds
  62. time.Sleep(time.Second * 30)
  63. go m.AttemptReconnections()
  64. }