2019-10-06 11:15:26 -07:00
|
|
|
package xmpp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"net"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"nhooyr.io/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type WebsocketTransport struct {
|
2019-10-10 21:41:15 -07:00
|
|
|
Config TransportConfiguration
|
2019-10-06 11:15:26 -07:00
|
|
|
wsConn *websocket.Conn
|
|
|
|
netConn net.Conn
|
|
|
|
ctx context.Context
|
|
|
|
}
|
|
|
|
|
2019-10-10 21:41:15 -07:00
|
|
|
func (t *WebsocketTransport) Connect() error {
|
2019-10-06 11:15:26 -07:00
|
|
|
t.ctx = context.Background()
|
|
|
|
|
2019-10-10 21:41:15 -07:00
|
|
|
ctx, cancel := context.WithTimeout(t.ctx, time.Duration(t.Config.ConnectTimeout)*time.Second)
|
2019-10-06 11:15:26 -07:00
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
if !c.Insecure && strings.HasPrefix(address, "wss:") {
|
|
|
|
return errors.New("Websocket address is not secure")
|
|
|
|
}
|
2019-10-10 21:41:15 -07:00
|
|
|
wsConn, _, err := websocket.Dial(ctx, t.Config.Address, nil)
|
2019-10-06 11:15:26 -07:00
|
|
|
if err != nil {
|
|
|
|
t.wsConn = wsConn
|
|
|
|
t.netConn = websocket.NetConn(t.ctx, t.wsConn, websocket.MessageText)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t WebsocketTransport) DoesStartTLS() bool {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t WebsocketTransport) Read(p []byte) (n int, err error) {
|
|
|
|
return t.netConn.Read(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t WebsocketTransport) Write(p []byte) (n int, err error) {
|
|
|
|
return t.netConn.Write(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t WebsocketTransport) Close() error {
|
|
|
|
return t.netConn.Close()
|
|
|
|
}
|