-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
231 lines (207 loc) · 6.42 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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package instagramclient
import (
"context"
"fmt"
"io"
"time"
log "github.com/golang/glog"
"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/footprintai/shrimping/components/grpc/client"
"github.com/footprintai/shrimping/components/grpc/compression"
errors "github.com/footprintai/shrimping/components/grpc/errors"
pb "github.com/footprintai/shrimping/components/grpc/proto/pb"
"github.com/footprintai/shrimping/components/grpc/version"
)
func NewClient(serverAddr string, apiKey string, timeout time.Duration, callOptions ...grpc.CallOption) (*Client, error) {
clientConn, err := client.NewGrpcClient(serverAddr)
if err != nil {
return nil, err
}
return &Client{
pbClient: pb.NewShritagramClient(clientConn),
verClient: pb.NewVersioningClient(clientConn),
crudClient: pb.NewWebhookCRUDClient(clientConn),
callOpts: callOptions,
conn: clientConn,
apiKey: apiKey,
timeout: timeout,
}, nil
}
type Client struct {
pbClient pb.ShritagramClient
verClient pb.VersioningClient
crudClient pb.WebhookCRUDClient
callOpts []grpc.CallOption
conn *client.GrpcClient
timeout time.Duration
apiKey string
}
func (c *Client) TestWebhook() error {
ctx := context.Background()
_, err := c.crudClient.TestWebhook(ctx, &pb.TestWebhookRequest{})
return err
}
func (c *Client) VerifySignature(host, hmackey string, bodydigest string, createdTs *int32) (signStr string, signature string, headers string, err error) {
ctx := context.Background()
resp, err := c.crudClient.VerifySignature(c.ctxWithToken(ctx), &pb.VerifySignatureRequest{
Host: host,
Hmackey: hmackey,
BodyDigest: bodydigest,
CreatedTs: createdTs,
})
if err != nil {
return "", "", "", err
}
return resp.SignStr, resp.Signature, resp.HttpHeaders, nil
}
func (c *Client) SubscribeWebhook(webhookHost string, forceHttps bool) (apikey, secret, host string, err error) {
ctx := context.Background()
resp, err := c.crudClient.SubscribeWebhook(c.ctxWithToken(ctx), &pb.SubscribeWebhookRequest{
WebhookAddress: webhookHost,
ForceHttps: &forceHttps,
})
if err != nil {
return "", "", "", err
}
return resp.Data.ApiKey, resp.Data.SecretKey, resp.Data.Address, nil
}
type WebhookResponse struct {
ApiKey string
ApiSecret string
WebhookAddress string
}
func (c *Client) ListWebhook() ([]*WebhookResponse, error) {
ctx := context.Background()
resp, err := c.crudClient.ListWebhook(c.ctxWithToken(ctx), &pb.ListWebhookRequest{})
if err != nil {
return nil, err
}
var respList []*WebhookResponse
for _, data := range resp.List {
respList = append(respList, &WebhookResponse{
ApiKey: data.ApiKey,
ApiSecret: data.SecretKey,
WebhookAddress: data.Address,
})
}
return respList, nil
}
func (c *Client) DeleteWebhook(apikeys []string) error {
ctx := context.Background()
_, err := c.crudClient.DeleteWebhook(c.ctxWithToken(ctx), &pb.DeleteWebhookRequest{ApiKeys: apikeys})
if err != nil {
return err
}
return nil
}
func (c *Client) Callback(cb func(*pb.ShritagramResponse) error) error {
ctx := context.Background()
for {
stream, err := c.pbClient.Callback(c.ctxWithToken(ctx), &pb.CallbackRequest{}, c.callOpts...)
if err != nil {
log.Errorf("get pbclient failed, err:%s", err)
return errors.ParseError(err)
}
for {
resp, err := stream.Recv()
if err == io.EOF {
log.Info("callback: got eof, reconnecting")
break
} else if err != nil {
log.Infof("callback: got err:%+v, reconnecting", err)
break
}
if err := cb(decompress(resp)); err != nil {
log.Errorf("callback failed, err:%+s\n", err)
return errors.ParseError(err)
}
}
if err := c.conn.WaitForReconnect(ctx); err != nil {
return err
}
}
}
func (c *Client) Profile(usernames []string, cachePolicy string, priority string) ([]*pb.ShritagramResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
resp, err := c.pbClient.Profile(c.ctxWithToken(ctx), &pb.ProfileRequest{
Usernames: usernames,
CacheControl: cachePolicy,
Priority: priority,
}, c.callOpts...)
if err != nil {
return nil, errors.ParseError(err)
}
return []*pb.ShritagramResponse{decompress(resp)}, nil
}
func decompress(out *pb.ShritagramResponse) *pb.ShritagramResponse {
if out.Compression != pb.ObjectCompressionAlgorithm_GZIP {
return out
}
compressor := &compression.GzipEncodeDecoder{}
for _, rawProfile := range out.RawProfiles {
if rawProfile != nil {
rawProfile.RawBytes, _ = compressor.Decode(rawProfile.RawBytes)
}
}
for _, rawPost := range out.RawPosts {
if rawPost != nil {
rawPost.RawBytes, _ = compressor.Decode(rawPost.RawBytes)
}
}
for _, rawSearch := range out.RawTopSearchs {
if rawSearch != nil {
rawSearch.RawBytes, _ = compressor.Decode(rawSearch.RawBytes)
}
}
return out
}
func (c *Client) ctxWithToken(ctx context.Context) context.Context {
md := metadata.Pairs("authorization", fmt.Sprintf("X-API-Key %v", c.apiKey))
nCtx := metautils.NiceMD(md).ToOutgoing(ctx)
return nCtx
}
func (c *Client) Posts(shortcodes []string, cachePolicy string, priority string) ([]*pb.ShritagramResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
resp, err := c.pbClient.Posts(c.ctxWithToken(ctx), &pb.PostRequest{
Shortcodes: shortcodes,
CacheControl: cachePolicy,
Priority: priority,
}, c.callOpts...)
if err != nil {
return nil, errors.ParseError(err)
}
return []*pb.ShritagramResponse{decompress(resp)}, nil
}
func (c *Client) TopSearch(hashtags []string, priority string) ([]*pb.ShritagramResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
out, err := c.pbClient.TopSearch(c.ctxWithToken(ctx), &pb.TopSearchRequest{
Hashtags: hashtags,
Priority: priority,
}, c.callOpts...)
if err != nil {
return nil, errors.ParseError(err)
}
return []*pb.ShritagramResponse{decompress(out)}, nil
}
func (c *Client) Version() (serverVersion string, isVersionCompatible bool, err error) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
resp, err := c.verClient.Version(
c.ctxWithToken(ctx),
&pb.VersionRequest{
ClientVersion: version.GetVersion(),
},
)
if err != nil {
return "", false, err
}
return resp.ServerVersion, resp.Compatible, nil
}
func (c *Client) Close() error {
return c.conn.Close()
}