forked from bpicode/fritzctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
74 lines (63 loc) · 2.04 KB
/
client.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
package cmd
import (
"io/ioutil"
"net/url"
"github.com/bpicode/fritzctl/assert"
"github.com/bpicode/fritzctl/config"
"github.com/bpicode/fritzctl/fritz"
"github.com/bpicode/fritzctl/logger"
)
func clientLogin() *fritz.Client {
configFile, err := config.FindConfigFile()
assert.NoError(err, "unable to create FRITZ!Box client:", err)
client, err := fritz.NewClient(configFile)
assert.NoError(err, "unable to create FRITZ!Box client:", err)
err = client.Login()
assert.NoError(err, "unable to login:", err)
return client
}
func homeAutoClient() fritz.HomeAuto {
opts := findOptions(config.FindConfigFile)
h := fritz.NewHomeAuto(opts...)
err := h.Login()
assert.NoError(err, "unable to login:", err)
return h
}
type cfgFileFinder func() (string, error)
func findOptions(finder cfgFileFinder) []fritz.Option {
path, err := finder()
if err != nil {
logger.Warn("Using default configuration because no config file could be inferred:", err)
return make([]fritz.Option, 0)
}
return fromFile(path)
}
func fromFile(path string) []fritz.Option {
opts := make([]fritz.Option, 0)
cfg, err := config.New(path)
assert.NoError(err, "cannot apply configuration:", err)
opts = networkOptions(opts, cfg.Net)
opts = certificateOptions(opts, cfg.Pki)
opts = loginOptions(opts, cfg.Login)
return opts
}
func networkOptions(opts []fritz.Option, net *config.Net) []fritz.Option {
return append(opts, fritz.URL(&url.URL{Host: net.Host + ":" + net.Port, Scheme: net.Protocol}))
}
func certificateOptions(opts []fritz.Option, pki *config.Pki) []fritz.Option {
if pki.SkipTLSVerify {
opts = append(opts, fritz.SkipTLSVerify())
return opts
}
if pki.CertificateFile != "" {
bs, err := ioutil.ReadFile(pki.CertificateFile)
assert.NoError(err, "cannot read certificate file:", err)
opts = append(opts, fritz.Certificate(bs))
}
return opts
}
func loginOptions(opts []fritz.Option, login *config.Login) []fritz.Option {
opts = append(opts, fritz.Credentials(login.Username, login.Password))
opts = append(opts, fritz.AuthEndpoint(login.LoginURL))
return opts
}