sum7
/
yaja
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
yaja/client/client.go

81 lines
1.7 KiB
Go
Raw Normal View History

package client
import (
"encoding/xml"
"fmt"
"net"
"strings"
2018-02-11 09:07:07 +01:00
"time"
2018-02-11 22:03:58 +01:00
log "github.com/sirupsen/logrus"
"dev.sum7.eu/genofire/yaja/xmpp"
"dev.sum7.eu/genofire/yaja/xmpp/base"
)
// Client holds XMPP connection opitons
type Client struct {
2018-02-11 22:03:58 +01:00
Protocol string // tcp tcp4 tcp6 are supported
Timeout time.Duration
conn net.Conn // connection to server
out *xml.Encoder
in *xml.Decoder
Logging *log.Entry
JID *xmppbase.JID
2018-02-13 20:05:18 +01:00
SkipError bool
msg chan interface{}
reply map[string]chan *xmpp.IQClient
}
func NewClient(jid *xmppbase.JID, password string) (*Client, error) {
2018-02-11 22:03:58 +01:00
client := &Client{
2018-03-03 09:28:24 +01:00
JID: jid,
Logging: log.New().WithField("jid", jid.String()),
2018-02-11 22:03:58 +01:00
}
return client, client.Connect(password)
2018-02-11 09:07:07 +01:00
2018-02-11 22:03:58 +01:00
}
func (client *Client) Connect(password string) error {
_, srvEntries, err := net.LookupSRV("xmpp-client", "tcp", client.JID.Domain)
2018-03-03 09:28:24 +01:00
addr := client.JID.Domain
2018-02-10 13:34:42 +01:00
if err == nil && len(srvEntries) > 0 {
bestSrv := srvEntries[0]
for _, srv := range srvEntries {
if srv.Priority <= bestSrv.Priority && srv.Weight >= bestSrv.Weight {
bestSrv = srv
addr = fmt.Sprintf("%s:%d", srv.Target, srv.Port)
}
}
}
2018-03-03 09:28:24 +01:00
if strings.LastIndex(addr, ":") <= strings.LastIndex(addr, "]") {
2018-02-10 13:34:42 +01:00
addr += ":5222"
}
2018-02-11 22:03:58 +01:00
if client.Protocol == "" {
client.Protocol = "tcp"
}
2018-03-03 09:28:24 +01:00
client.Logging.Debug("try tcp connect")
2018-02-11 22:03:58 +01:00
conn, err := net.DialTimeout(client.Protocol, addr, client.Timeout)
if err != nil {
return err
}
2018-03-03 09:28:24 +01:00
client.Logging.Debug("tcp connected")
client.setConnection(conn)
if err = client.connect(password); err != nil {
client.Close()
2018-02-11 22:03:58 +01:00
return err
}
2018-02-11 22:03:58 +01:00
return nil
}
// Close closes the XMPP connection
func (c *Client) Close() error {
2018-03-03 09:28:24 +01:00
if c.conn != nil {
return c.conn.Close()
}
return nil
}