cwtch/peer/connections/peerpeerconnection.go

93 lines
2.5 KiB
Go
Raw Normal View History

package connections
import (
2018-03-11 19:05:35 +00:00
"git.mascherari.press/cwtch/peer/peer"
"git.mascherari.press/cwtch/protocol"
"github.com/s-rah/go-ricochet"
2018-03-11 19:05:35 +00:00
"github.com/s-rah/go-ricochet/channels"
"github.com/s-rah/go-ricochet/connection"
2018-03-11 19:05:35 +00:00
"github.com/s-rah/go-ricochet/identity"
//"github.com/s-rah/go-ricochet/utils"
2018-03-11 19:05:35 +00:00
"git.mascherari.press/cwtch/model"
2018-03-14 22:23:35 +00:00
"time"
)
type PeerPeerConnection struct {
connection.AutoConnectionHandler
PeerHostname string
state ConnectionState
connection connection.Connection
2018-03-14 22:23:35 +00:00
profile *model.Profile
}
2018-03-11 19:05:35 +00:00
func NewPeerPeerConnection(peerhostname string, profile *model.Profile) *PeerPeerConnection {
ppc := new(PeerPeerConnection)
ppc.PeerHostname = peerhostname
2018-03-11 19:05:35 +00:00
ppc.profile = profile
ppc.Init()
return ppc
}
// GetState returns the current connection state
func (ppc *PeerPeerConnection) GetState() ConnectionState {
return ppc.state
}
2018-03-11 19:05:35 +00:00
func (ppc *PeerPeerConnection) ClientIdentity(ci *protocol.CwtchIdentity) {
2018-03-14 22:23:35 +00:00
ppc.profile.AddCwtchIdentity(ppc.PeerHostname, ci)
2018-03-11 19:05:35 +00:00
}
2018-03-12 18:43:51 +00:00
func (ppc *PeerPeerConnection) HandleGroupInvite(gci *protocol.GroupChatInvite) {
ppc.profile.ProcessInvite(gci, ppc.PeerHostname)
2018-03-12 18:43:51 +00:00
}
func (ppc *PeerPeerConnection) SendGroupInvite(invite []byte) {
2018-03-14 22:23:35 +00:00
ppc.connection.Do(func() error {
channel := ppc.connection.Channel("im.cwtch.peer", channels.Outbound)
if channel != nil {
peerchannel, ok := channel.Handler.(*peer.CwtchPeerChannel)
if ok {
peerchannel.SendMessage(invite)
}
}
return nil
})
2018-03-11 19:05:35 +00:00
}
// Run manages the setup and teardown of a peer->peer connection
func (ppc *PeerPeerConnection) Run() error {
rc, err := goricochet.Open(ppc.PeerHostname)
if err == nil {
rc.TraceLog(true)
ppc.connection = *rc
ppc.state = CONNECTED
2018-03-11 19:05:35 +00:00
_, err := connection.HandleOutboundConnection(&ppc.connection).ProcessAuthAsClient(identity.Initialize(ppc.profile.Name, ppc.profile.OnionPrivateKey))
if err == nil {
ppc.state = AUTHENTICATED
go func() {
ppc.connection.Do(func() error {
ppc.connection.RequestOpenChannel("im.cwtch.peer", &peer.CwtchPeerChannel{Handler: ppc})
return nil
})
2018-03-14 22:23:35 +00:00
time.Sleep(time.Second * 1)
ppc.connection.Do(func() error {
channel := ppc.connection.Channel("im.cwtch.peer", channels.Outbound)
if channel != nil {
peerchannel, ok := channel.Handler.(*peer.CwtchPeerChannel)
if ok {
peerchannel.SendMessage(ppc.profile.GetCwtchIdentityPacket())
}
}
return nil
})
2018-03-11 19:05:35 +00:00
}()
ppc.connection.Process(ppc)
}
}
ppc.state = FAILED
return err
}