/
profile.go
89 lines (78 loc) · 1.62 KB
/
profile.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
package bot
import (
"context"
"encoding/json"
"io"
"net"
"net/url"
"golang.org/x/net/proxy"
)
const defaultRateMs = 1000
type Profile struct {
ProfileLogin
Chans []string
RateMs int
Verbosity int
// Id is the way to reference this bot.
Id string
Patterns []Pattern
PatternsRaw []Pattern
}
type ProfileLogin struct {
ServerURL string
ProxyURL string `json:",omitempty"`
Nick string
User string
Pass string `json:",omitempty"`
}
func DecodeProfiles(r io.Reader) (ret []*Profile, err error) {
d := json.NewDecoder(r)
for {
p := &Profile{}
if err = d.Decode(p); err != nil {
if err == io.EOF {
return ret, nil
}
return nil, err
}
if p.RateMs == 0 {
p.RateMs = defaultRateMs
}
ret = append(ret, p)
}
}
func UnmarshalProfile(b []byte) (*Profile, error) {
var p Profile
if err := json.Unmarshal(b, &p); err != nil {
return nil, err
}
if p.RateMs == 0 {
p.RateMs = defaultRateMs
}
return &p, nil
}
type ctxDialer struct {
ctx context.Context
fwd net.Dialer
}
func (d *ctxDialer) Dial(network, address string) (net.Conn, error) {
return d.fwd.DialContext(d.ctx, network, address)
}
func (p *Profile) Dial(ctx context.Context) (c net.Conn, err error) {
servURL, err := url.Parse(p.ServerURL)
if err != nil {
return nil, err
}
fwd := &ctxDialer{ctx: ctx}
var dialer proxy.Dialer
dialer = fwd
proxyURL, err := url.Parse(p.ProxyURL)
if len(p.ProxyURL) != 0 && err != nil {
return nil, err
} else if len(p.ProxyURL) != 0 {
if dialer, err = proxy.FromURL(proxyURL, fwd); err != nil {
return nil, err
}
}
return dialer.Dial("tcp", servURL.Host)
}