-
Notifications
You must be signed in to change notification settings - Fork 10
/
component.go
105 lines (85 loc) · 2.05 KB
/
component.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package xco
import (
"encoding/xml"
"log"
"net"
"github.com/pkg/errors"
"context"
)
type stateFn func() (stateFn, error)
// A Component is an instance of a Jabber Component (XEP-0114)
type Component struct {
MessageHandler MessageHandler
DiscoInfoHandler DiscoInfoHandler
PresenceHandler PresenceHandler
IqHandler IqHandler
UnknownHandler UnknownElementHandler
ctx context.Context
cancelFn context.CancelFunc
conn net.Conn
dec *xml.Decoder
enc *xml.Encoder
log *log.Logger
stateFn stateFn
sharedSecret string
name string
}
func (c *Component) init(o Options) error {
conn, err := net.Dial("tcp", o.Address)
if err != nil {
return err
}
c.MessageHandler = noOpMessageHandler
c.DiscoInfoHandler = noOpDiscoInfoHandler
c.PresenceHandler = noOpPresenceHandler
c.IqHandler = noOpIqHandler
c.UnknownHandler = noOpUnknownHandler
c.conn = conn
c.name = o.Name
c.sharedSecret = o.SharedSecret
if o.Logger == nil {
c.dec = xml.NewDecoder(conn)
c.enc = xml.NewEncoder(conn)
} else {
c.log = o.Logger
c.dec = xml.NewDecoder(newReadLogger(c.log, conn))
c.enc = xml.NewEncoder(newWriteLogger(c.log, conn))
}
c.stateFn = c.handshakeState
return nil
}
// Close closes the Component
func (c *Component) Close() {
if c == nil {
return
}
c.cancelFn()
}
// Run runs the component handlers loop and waits for it to finish
func (c *Component) Run() (err error) {
defer func() {
c.conn.Close()
}()
for {
if c.stateFn == nil {
return nil
}
c.stateFn, err = c.stateFn()
if err != nil {
return err
}
}
}
// A Sender is an interface which allows sending of arbitrary objects
// as XML to an XMPP server.
type Sender interface {
Send(i interface{}) error
}
// Send sends the given pointer struct by serializing it to XML.
func (c *Component) Send(i interface{}) error {
return errors.Wrap(c.enc.Encode(i), "Error encoding object to XML")
}
// Write implements the io.Writer interface to allow direct writing to the XMPP connection
func (c *Component) Write(b []byte) (int, error) {
return c.conn.Write(b)
}