This repository was archived by the owner on Mar 29, 2018. It is now read-only.
forked from mrhenry/go-getstream
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathclient.go
423 lines (364 loc) · 10.3 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package getstream
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"gopkg.in/LeisureLink/httpsig.v1"
)
// Client is used to connect to getstream.io
type Client struct {
HTTP *http.Client
BaseURL *url.URL // https://api.getstream.io/api/
Config *Config
Signer *Signer
}
/**
* New returns a GetStream client.
*
* Params:
* cfg, pointer to a Config structure which takes the API credentials, Location, etc
* Returns:
* Client struct
*/
func New(cfg *Config) (*Client, error) {
var (
timeout int64
)
if cfg.APIKey == "" {
return nil, errors.New("Required API Key was not set")
}
if cfg.APISecret == "" && cfg.Token == "" {
return nil, errors.New("API Secret or Token was not set, one or the other is required")
}
if cfg.TimeoutInt <= 0 {
timeout = 3
} else {
timeout = cfg.TimeoutInt
}
cfg.SetTimeout(timeout)
if cfg.Version == "" {
cfg.Version = "v1.0"
}
location := "api"
port := ""
secure := "s"
if cfg.Location != "" {
location = cfg.Location + "-api"
if cfg.Location == "qa" {
secure = ""
}
if cfg.Location == "localhost" {
port = ":8000"
secure = ""
}
}
baseURL, err := url.Parse("http" + secure + "://" + location + ".getstream.io" + port + "/api/" + cfg.Version + "/")
if err != nil {
return nil, err
}
cfg.SetBaseURL(baseURL)
var signer *Signer
if cfg.Token != "" {
// build the Signature mechanism based on a Token value passed to the client setup
cfg.SetAPISecret("")
signer = &Signer{
Secret: cfg.Token,
}
} else {
// build the Signature based on the API Secret
cfg.SetToken("")
signer = &Signer{
Secret: cfg.APISecret,
}
}
client := &Client{
HTTP: &http.Client{
Transport: GETSTREAM_TRANSPORT,
Timeout: cfg.TimeoutDuration,
},
BaseURL: baseURL,
Config: cfg,
Signer: signer,
}
return client, nil
}
// FlatFeed returns a getstream feed
// Slug is the FlatFeed Group name
// id is the Specific FlatFeed inside a FlatFeed Group
// to get the feed for Bob you would pass something like "user" as slug and "bob" as the id
func (c *Client) FlatFeed(feedSlug string, userID string) (*FlatFeed, error) {
var err error
feedSlug, err = ValidateFeedSlug(feedSlug)
if err != nil {
return nil, err
}
userID, err = ValidateUserID(userID)
if err != nil {
return nil, err
}
feed := &FlatFeed{
Client: c,
FeedSlug: feedSlug,
UserID: userID,
}
feed.SignFeed(c.Signer)
return feed, nil
}
// NotificationFeed returns a getstream feed
// Slug is the NotificationFeed Group name
// id is the Specific NotificationFeed inside a NotificationFeed Group
// to get the feed for Bob you would pass something like "user" as slug and "bob" as the id
func (c *Client) NotificationFeed(feedSlug string, userID string) (*NotificationFeed, error) {
var err error
feedSlug, err = ValidateFeedSlug(feedSlug)
if err != nil {
return nil, err
}
userID, err = ValidateUserID(userID)
if err != nil {
return nil, err
}
feed := &NotificationFeed{
Client: c,
FeedSlug: feedSlug,
UserID: userID,
}
feed.SignFeed(c.Signer)
return feed, nil
}
// AggregatedFeed returns a getstream feed
// Slug is the AggregatedFeed Group name
// id is the Specific AggregatedFeed inside a AggregatedFeed Group
// to get the feed for Bob you would pass something like "user" as slug and "bob" as the id
func (c *Client) AggregatedFeed(feedSlug string, userID string) (*AggregatedFeed, error) {
var err error
feedSlug, err = ValidateFeedSlug(feedSlug)
if err != nil {
return nil, err
}
userID, err = ValidateUserID(userID)
if err != nil {
return nil, err
}
feed := &AggregatedFeed{
Client: c,
FeedSlug: feedSlug,
UserID: userID,
}
feed.SignFeed(c.Signer)
return feed, nil
}
// absoluteUrl create a url.URL instance and sets query params (bad!!!)
func (c *Client) AbsoluteURL(path string) (*url.URL, error) {
result, err := url.Parse(path)
if err != nil {
return nil, err
}
// DEBUG: Use this line to send stuff to a proxy instead.
// c.baseURL, _ = url.Parse("http://0.0.0.0:8000/")
result = c.BaseURL.ResolveReference(result)
qs := result.Query()
qs.Set("api_key", c.Config.APIKey)
if c.Config.Location == "" || c.Config.Location == "localhost" {
qs.Set("location", "unspecified")
} else {
qs.Set("location", c.Config.Location)
}
result.RawQuery = qs.Encode()
return result, nil
}
// ConvertUUIDToWord replaces - with _
// It is used by go-getstream to convert UUID to a string that matches the word regex
// You can use it to convert UUID's to match go-getstream internals.
func ConvertUUIDToWord(uuid string) string {
return strings.Replace(uuid, "-", "_", -1)
}
// get request helper
func (c *Client) get(f Feed, path string, payload []byte, params map[string]string) ([]byte, error) {
// we force an empty body payload because GET requests cannot have a body with our API
return c.request(f, "GET", path, []byte{}, params)
}
// post request helper
func (c *Client) post(f Feed, path string, payload []byte, params map[string]string) ([]byte, error) {
return c.request(f, "POST", path, payload, params)
}
// delete request helper
func (c *Client) del(f Feed, path string, payload []byte, params map[string]string) error {
_, err := c.request(f, "DELETE", path, payload, params)
return err
}
// request helper
func (c *Client) request(f Feed, method string, path string, payload []byte, params map[string]string) ([]byte, error) {
apiUrl, err := url.Parse(path)
if err != nil {
return nil, err
}
apiUrl = c.BaseURL.ResolveReference(apiUrl)
query := apiUrl.Query()
query = c.setStandardParams(query)
query = c.setRequestParams(query, params)
apiUrl.RawQuery = query.Encode()
// create a new http request
req, err := http.NewRequest(method, apiUrl.String(), bytes.NewBuffer(payload))
if err != nil {
return nil, err
}
// set the Auth headers for the http request
c.setBaseHeaders(req)
auth := ""
sig := ""
switch {
case path == "follow_many/": // one feed follows many feeds
auth = "app"
sig = "sig"
case path == "activities/": // batch activities methods
// feed auth
auth = "feed"
sig = "jwt"
case path == "feed/add_to_many/": // add activity to many feeds
// application auth
auth = "app"
sig = "sig"
case path[:5] == "feed": // add activity to many feeds
// feed auth
auth = "feed"
sig = "jwt"
default: // everything else sig/httpsig and feed auth
auth = "feed"
sig = "sig"
}
c.setAuthSigAndHeaders(req, f, auth, sig, path)
// perform the http request
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// read the response
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// handle the response
switch {
case resp.StatusCode/100 == 2: // SUCCESS
return body, nil
default:
var respErr Error
err = json.Unmarshal(body, &respErr)
if err != nil {
return nil, err
}
return nil, &respErr
}
}
func (c *Client) setStandardParams(query url.Values) url.Values {
query.Set("api_key", c.Config.APIKey)
if c.Config.Location == "" || c.Config.Location == "localhost" {
query.Set("location", "unspecified")
} else {
query.Set("location", c.Config.Location)
}
return query
}
func (c *Client) setRequestParams(query url.Values, params map[string]string) url.Values {
for key, value := range params {
query.Set(key, value)
}
return query
}
/* setBaseHeaders - set common headers for every request
* params:
* request, pointer to http.Request
*/
func (c *Client) setBaseHeaders(request *http.Request) {
request.Header.Set("X-Stream-Client", "stream-go-client-"+VERSION)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Api-Key", c.Config.APIKey)
t := time.Now()
request.Header.Set("Date", t.Format("Mon, 2 Jan 2006 15:04:05 MST"))
}
func (c *Client) setAuthSigAndHeaders(request *http.Request, f Feed, auth string, sig string, path string) error {
if sig == "jwt" {
request.Header.Set("stream-auth-type", "jwt")
if f == nil {
request.Header.Set("Authorization", c.Config.Token)
} else {
if path == "activities/" {
token, err := c.Signer.GenerateFeedScopeToken(ScopeContextActivities, ScopeActionWrite, "*")
if err != nil {
return err
}
request.Header.Set("Authorization", token)
} else {
request.Header.Set("Authorization", f.Token())
}
}
return nil
}
if sig == "sig" {
if auth == "feed" {
if f.Token() == "" {
f.GenerateToken(c.Signer)
}
request.Header.Set("Authorization", f.Signature())
} else if auth == "app" {
signer, _ := httpsig.NewRequestSigner(c.Config.APIKey, c.Config.APISecret, "hmac-sha256")
signer.SignRequest(request, []string{}, nil)
}
return nil
}
return errors.New("No API Secret or config/feed Token")
}
type PostFlatFeedFollowingManyInput struct {
Source string `json:"source"`
Target string `json:"target"`
}
/** PrepFollowFlatFeed - prepares JSON needed for one feed to follow another
Params:
targetFeed, FlatFeed which wants to follow another
sourceFeed, FlatFeed which is to be followed
Returns:
[]byte, array of bytes of JSON suitable for API consumption
*/
func (c *Client) PrepFollowFlatFeed(targetFeed *FlatFeed, sourceFeed *FlatFeed) *PostFlatFeedFollowingManyInput {
return &PostFlatFeedFollowingManyInput{
Source: sourceFeed.FeedSlug + ":" + sourceFeed.UserID,
Target: targetFeed.FeedSlug + ":" + targetFeed.UserID,
}
}
func (c *Client) PrepFollowAggregatedFeed(targetFeed *FlatFeed, sourceFeed *AggregatedFeed) *PostFlatFeedFollowingManyInput {
return &PostFlatFeedFollowingManyInput{
Source: sourceFeed.FeedSlug + ":" + sourceFeed.UserID,
Target: targetFeed.FeedSlug + ":" + targetFeed.UserID,
}
}
func (c *Client) PrepFollowNotificationFeed(targetFeed *FlatFeed, sourceFeed *NotificationFeed) *PostFlatFeedFollowingManyInput {
return &PostFlatFeedFollowingManyInput{
Source: sourceFeed.FeedSlug + ":" + sourceFeed.UserID,
Target: targetFeed.FeedSlug + ":" + targetFeed.UserID,
}
}
type PostActivityToManyInput struct {
Activity Activity `json:"activity"`
FeedIDs []string `json:"feeds"`
}
func (c *Client) AddActivityToMany(activity Activity, feeds []string) error {
payload := &PostActivityToManyInput{
Activity: activity,
FeedIDs: feeds,
}
final_payload, err := json.Marshal(payload)
if err != nil {
return err
}
endpoint := "feed/add_to_many/"
params := map[string]string{}
_, err = c.post(nil, endpoint, final_payload, params)
return err
}