/
subscribe.go
122 lines (105 loc) · 2.38 KB
/
subscribe.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package commands
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"net/http/cookiejar"
"net/url"
"os"
v1 "github.com/bitum-project/politeia/politeiawww/api/www/v1"
"github.com/bitum-project/politeia/util"
"github.com/gorilla/websocket"
"golang.org/x/net/publicsuffix"
)
// SubscribeCmd opens a websocket connect to politeiawww.
type SubscribeCmd struct {
Close bool `long:"close" optional:"true"` // Do not keep connetion alive
}
// Execute executes the subscribe command.
func (cmd *SubscribeCmd) Execute(args []string) error {
// Parse args
route := v1.RouteUnauthenticatedWebSocket
subscribe := make([]string, 0, len(args))
for _, v := range args {
if v == "auth" {
route = v1.RouteAuthenticatedWebSocket
continue
}
subscribe = append(subscribe, v)
}
// Set cookies
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if err != nil {
return err
}
u, err := url.Parse(cfg.Host)
if err != nil {
return err
}
jar.SetCookies(u, cfg.Cookies)
// Setup websocket
d := websocket.Dialer{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: cfg.SkipVerify,
},
Jar: jar,
}
uu := url.URL{
Scheme: "wss",
Host: u.Host,
Path: v1.PoliteiaWWWAPIRoute + route,
}
fmt.Printf("connecting to %s\n", uu.String())
ws, _, err := d.Dial(uu.String(), nil)
if err != nil {
return err
}
defer ws.Close()
err = printJSON(v1.WSHeader{Command: v1.WSCSubscribe, ID: "1"})
if err != nil {
return err
}
err = printJSON(v1.WSSubscribe{RPCS: subscribe})
if err != nil {
return err
}
// Send subscribe command
err = util.WSWrite(ws, v1.WSCSubscribe, "1", v1.WSSubscribe{
RPCS: subscribe,
})
if err != nil {
return err
}
if cmd.Close {
return nil
}
for {
_, message, err := ws.ReadMessage()
if err != nil {
return err
}
var out bytes.Buffer
err = json.Indent(&out, message, "", " ")
if err != nil {
return err
}
out.WriteTo(os.Stdout)
}
// not reached
}
// subscribeHelpMsg is the output of the help command when 'subscribe' is
// specified.
const subscribeHelpMsg = `subscribe [auth] <ping...>
Connect and subcribe to www websocket. If auth is provided the connection will
be made to the authenticated websocket (must be logged in).
Flags:
--close (bool, optional) Do not keep the websocket connection alive
Supported commands:
- ping (does not require authentication)
Request:
{
}
`