cwtch/client/connections/peerserverconnection.go

80 lines
2.3 KiB
Go
Raw Normal View History

package connections
import (
"github.com/s-rah/go-ricochet"
"github.com/s-rah/go-ricochet/connection"
"github.com/s-rah/go-ricochet/channels"
"github.com/s-rah/go-ricochet/identity"
"github.com/s-rah/go-ricochet/utils"
"git.mascherari.press/cwtch/client/send"
"git.mascherari.press/cwtch/protocol"
"time"
)
type PeerServerConnection struct {
connection.AutoConnectionHandler
Server string
state ConnectionState
connection connection.Connection
}
func NewPeerServerConnection(serverhostname string) *PeerServerConnection {
psc := new(PeerServerConnection)
psc.Server = serverhostname
psc.Init()
return psc
}
// GetState returns the current connection state
func (psc *PeerServerConnection) GetState() ConnectionState {
return psc.state
}
// Run manages the setup and teardown of a peer server connection
func (psc *PeerServerConnection) Run() error {
rc, err := goricochet.Open(psc.Server)
if err == nil {
psc.connection = *rc
psc.state = CONNECTED
pk, err := utils.GeneratePrivateKey()
if err == nil {
_, err := connection.HandleOutboundConnection(&psc.connection).ProcessAuthAsClient(identity.Initialize("cwtchpeer", pk))
if err == nil {
psc.state = AUTHENTICATED
psc.connection.Process(psc)
}
}
}
return err
}
// Break makes Run() return and prevents processing, but doesn't close the connection.
func (psc *PeerServerConnection) Break() error {
return psc.connection.Break()
}
func (psc *PeerServerConnection) SendGroupMessage(gm *protocol.GroupMessage) {
psc.connection.Do(func() error {
psc.connection.RequestOpenChannel("im.cwtch.server.send", &send.CwtchPeerSendChannel{})
return nil
})
// TODO We have to wait to receive the channel result before we can continue
// We should have a better mechanism for this kindof interaction
time.Sleep(time.Second * 1)
psc.connection.Do(func() error {
channel := psc.connection.Channel("im.cwtch.server.send", channels.Outbound)
if channel != nil {
sendchannel, ok := channel.Handler.(*send.CwtchPeerSendChannel)
if ok {
sendchannel.SendGroupMessage(gm)
}
}
return nil
})
}
func (psc *PeerServerConnection) HandleGroupMessage(*protocol.GroupMessage) {
}