2018-09-18 18:07:40 +02:00
|
|
|
package reach
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"forge.cadoles.com/Pyxis/golang-socketio"
|
|
|
|
"forge.cadoles.com/Pyxis/golang-socketio/transport"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2018-09-19 17:13:45 +02:00
|
|
|
type client struct {
|
2018-09-18 18:07:40 +02:00
|
|
|
opts *Options
|
|
|
|
conn *gosocketio.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
// Connect connects the client to the ReachView endpoint
|
|
|
|
// This method is not safe to call by different coroutines
|
2018-09-19 17:13:45 +02:00
|
|
|
func (c *client) Connect() error {
|
2018-09-18 18:07:40 +02:00
|
|
|
|
|
|
|
var err error
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
|
|
|
wg.Add(1)
|
|
|
|
|
|
|
|
transport := &transport.WebsocketTransport{
|
|
|
|
PingInterval: c.opts.PingInterval,
|
|
|
|
PingTimeout: c.opts.PingTimeout,
|
|
|
|
ReceiveTimeout: c.opts.ReceiveTimeout,
|
|
|
|
SendTimeout: c.opts.SendTimeout,
|
|
|
|
BufferSize: c.opts.BufferSize,
|
|
|
|
}
|
|
|
|
|
|
|
|
c.logf("connecting to '%s'", c.opts.Endpoint)
|
|
|
|
conn, err := gosocketio.Dial(c.opts.Endpoint, transport)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "error while connecting to endpoint")
|
|
|
|
}
|
|
|
|
|
|
|
|
c.conn = conn
|
|
|
|
|
|
|
|
err = conn.On(gosocketio.OnConnection, func(h *gosocketio.Channel) {
|
2018-09-20 15:44:34 +02:00
|
|
|
conn.Off(gosocketio.OnError)
|
2018-09-18 18:07:40 +02:00
|
|
|
c.logf("connected with sid '%s'", h.Id())
|
|
|
|
err = c.sendBrowserConnected()
|
|
|
|
wg.Done()
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "error while attaching to connection event")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = conn.On(gosocketio.OnError, func(h *gosocketio.Channel) {
|
|
|
|
c.logf("error")
|
|
|
|
err = errors.Errorf("an unknown error occured")
|
|
|
|
c.conn = nil
|
|
|
|
wg.Done()
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "error while attaching to error event")
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the current connection to the ReachView endpoint
|
2018-09-19 17:13:45 +02:00
|
|
|
func (c *client) Close() {
|
2018-09-18 18:07:40 +02:00
|
|
|
if c.conn == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.conn.Close()
|
|
|
|
c.conn = nil
|
|
|
|
}
|
|
|
|
|
2018-09-19 17:13:45 +02:00
|
|
|
func (c *client) logf(format string, args ...interface{}) {
|
2018-09-18 18:07:40 +02:00
|
|
|
if c.opts.Logger == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.opts.Logger.Printf(format, args...)
|
|
|
|
}
|
|
|
|
|
2018-09-19 17:13:45 +02:00
|
|
|
func newClient(opts ...OptionFunc) *client {
|
2018-09-18 18:07:40 +02:00
|
|
|
options := DefaultOptions()
|
|
|
|
for _, o := range opts {
|
|
|
|
o(options)
|
|
|
|
}
|
2018-09-19 17:13:45 +02:00
|
|
|
return &client{
|
2018-09-18 18:07:40 +02:00
|
|
|
opts: options,
|
|
|
|
}
|
|
|
|
}
|