package connections import ( "cwtch.im/tapir" "cwtch.im/tapir/applications" "git.openprivacy.ca/openprivacy/libricochet-go/log" ) // PeerApp encapsulates the behaviour of a Cwtch Peer type PeerApp struct { applications.AuthApp connection *tapir.Connection MessageHandler func(string, []byte) OnAuth func(string) OnClose func(string) } // NewInstance should always return a new instantiation of the application. func (pa PeerApp) NewInstance() tapir.Application { newApp := new(PeerApp) newApp.MessageHandler = pa.MessageHandler newApp.OnAuth = pa.OnAuth newApp.OnClose = pa.OnClose return newApp } // Init is run when the connection is first started. func (pa *PeerApp) Init(connection *tapir.Connection) { // First run the Authentication App pa.AuthApp.Init(connection) if connection.HasCapability(applications.AuthCapability) { pa.connection = connection pa.OnAuth(connection.Hostname) go pa.listen() } else { pa.OnClose(connection.Hostname) } } func (pa PeerApp) listen() { for { message := pa.connection.Expect() if len(message) == 0 { log.Errorf("0 byte read, socket has likely failed. Closing the listen goroutine") return } pa.MessageHandler(pa.connection.Hostname, message) } } // SendMessage sends the peer a preformatted message // NOTE: This is a stub, we will likely want to extend this to better reflect the desired protocol func (pa PeerApp) SendMessage(message []byte) { pa.connection.Send(message) }