This repository has been archived by the owner on May 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
347 lines (288 loc) · 8.25 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
package main
import (
"encoding/json"
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"io"
"io/ioutil"
"math"
"net/http"
"net/url"
"strconv"
"time"
)
const MAX_STREAMS = 100
// StreamData represents the data a single stream
type StreamData struct {
ID string `json:"id"`
UserID string `json:"user_id"`
UserLogin string `json:"user_login"`
UserName string `json:"user_name"`
GameID string `json:"game_id"`
GameName string `json:"game_name"`
Type string `json:"type"`
Title string `json:"title"`
ViewerCount int `json:"viewer_count"`
StartedAt time.Time `json:"started_at"`
Language string `json:"language"`
ThumbnailURL string `json:"thumbnail_url"`
TagIDs []string `json:"tag_ids"`
}
// UserData struct represents a user as defined by the twitch api
type UserData struct {
ID string `json:"id"`
Login string `json:"login"`
DisplayName string `json:"display_name"`
Type string `json:"type"`
BroadcasterType string `json:"broadcaster_type"`
Description string `json:"description"`
ProfileImageURL string `json:"profile_image_url"`
OfflineImageURL string `json:"offline_image_url"`
ViewCount int `json:"view_count"`
Email string `json:"email"`
CreatedAt string `json:"created_at"`
}
type UserFollow struct {
Total int `json:"total"`
}
type Streams struct {
Data []StreamData `json:"data"`
}
type Users struct {
Data []UserData `json:"data"`
}
// Token represents a token used by client to interact with the twitch API
type Token struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RenewDate time.Time
TokenType string `json:"token_type"`
}
// Client represents a client to interact with the twitch API
type Client struct {
ClientID string
ClientSecret string
Token Token
httpClient *http.Client
}
// NewClient will initialize a new client for the twitch api
func NewClient(clientID, clientSecret string) (*Client, error) {
c := &Client{
ClientID: clientID,
ClientSecret: clientSecret,
httpClient: &http.Client{},
}
err := c.GetToken()
if err != nil {
return nil, err
}
return c, nil
}
func (c Client) doRequest(method, uri string, header http.Header, body io.Reader) (*http.Response, error) {
r, err := http.NewRequest(method, uri, body)
if err != nil {
return nil, err
}
r.Header = header
res, err := c.httpClient.Do(r)
if err != nil {
return nil, err
}
if res.StatusCode == 401 {
return nil, errors.New("server returned 401. likely caused due to an invalid client id")
} else if res.StatusCode != 200 {
return nil, fmt.Errorf("server returned non 200 status code. status code: %v", res.StatusCode)
}
return res, nil
}
// GetToken will get a Twitch API Bearer Token
func (c *Client) GetToken() error {
var uri *url.URL
// set url
uri, err := url.Parse(baseAuthURL + getToken)
if err != nil {
return err
}
query := uri.Query()
query.Add("client_id", c.ClientID)
query.Add("client_secret", c.ClientSecret)
query.Add("grant_type", "client_credentials")
query.Add("scope", "")
uri.RawQuery = query.Encode()
log.Debug("URI: ", uri.String())
res, err := c.doRequest(http.MethodPost, uri.String(), http.Header{}, nil)
if err != nil {
log.Error("Error while querying", err)
return err
}
log.Debug("Status code:", res.StatusCode)
defer res.Body.Close()
t := Token{}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error("Error while reading json", err)
return err
}
json.Unmarshal(body, &t)
var expireDate = time.Now().Add(time.Second * time.Duration(t.ExpiresIn))
var diffDate = expireDate.Sub(time.Now())
t.RenewDate = time.Now().Add(diffDate / 2)
c.Token = t
return nil
}
// GetStreams is a wrapper to handle more than 100 Streams
// The url query parameter are defined by the GetStreamsInput struct
func (c Client) GetStreams(streamsList []string) ([]StreamData, int, error) {
var s []StreamData
var token int
slices := int(math.Ceil(float64(len(streamsList)) / MAX_STREAMS))
for i := 0; i < slices; i++ {
end := i*MAX_STREAMS + MAX_STREAMS
if len(streamsList) < end {
end = len(streamsList)
}
r, query_token, err := c.get100Streams(streamsList[i*MAX_STREAMS : end])
// Prevent shadow
token = query_token
if err != nil {
log.Error("Error while getting stream ", err)
return s, token, nil
}
s = append(s, r...)
}
return s, token, nil
}
// get100Streams will get a list of live Streams, limited to 100 users
// The url query parameter are defined by the GetStreamsInput struct
func (c Client) get100Streams(streamsList []string) ([]StreamData, int, error) {
if len(streamsList) > MAX_STREAMS {
return nil, 0, errors.New("can't get more than 100 users")
}
var uri *url.URL
var header = http.Header{}
// set url
uri, err := url.Parse(baseURL + getStreamsEndpoint)
if err != nil {
return nil, 0, err
}
// set header
header.Add("Client-ID", c.ClientID)
header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
query := uri.Query()
for _, stream := range streamsList {
query.Add("user_login", stream)
}
uri.RawQuery = query.Encode()
log.Debug("Streams query URL: ", uri.String())
res, err := c.doRequest(http.MethodGet, uri.String(), header, nil)
if err != nil {
log.Error("Error while getting 100 stream ", err)
return nil, 0, err
}
defer res.Body.Close()
s := Streams{}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error("Error while reading body ", err)
return nil, 0, err
}
var token int
strToken, ok := res.Header["Ratelimit-Remaining"]
if ok {
if len(strToken) > 0 {
token, err = strconv.Atoi(strToken[0])
if err != nil {
log.Error("Cant convert: ", err)
token = 0
}
}
} else {
token = 0
}
log.Debugf("Stream remaining tokens: %d", token)
json.Unmarshal(body, &s)
return s.Data, token, nil
}
// GetUsers is a wrapper to handle more than 100 Users
// The url query parameter are defined by the GetStreamsInput struct
func (c Client) GetUsers(usersList []string) ([]UserData, error) {
var s []UserData
for i := 0; i < int(math.Ceil(float64(len(usersList))/MAX_STREAMS)); i++ {
end := i*MAX_STREAMS + MAX_STREAMS
if len(usersList) < end {
end = len(usersList)
}
r, err := c.get100Users(usersList[i*MAX_STREAMS : end])
if err != nil {
log.Error("Error while reggint str: ", err)
return s, nil
}
s = append(s, r...)
// log.Debug("Streams: ", s)
}
return s, nil
}
// get100Users will get a list of users information, limited to 100 users
// The url query parameter are defined by the GetStreamsInput struct
func (c Client) get100Users(usersList []string) ([]UserData, error) {
var uri *url.URL
var header = http.Header{}
// set url
uri, err := url.Parse(baseURL + getUsersEndpoint)
if err != nil {
return nil, err
}
// set header
header.Add("Client-ID", c.ClientID)
header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
query := uri.Query()
for _, user := range usersList {
query.Add("login", user)
}
uri.RawQuery = query.Encode()
res, err := c.doRequest(http.MethodGet, uri.String(), header, nil)
if err != nil {
log.Error("Error while getting streams info", err)
return nil, err
}
defer res.Body.Close()
s := Users{}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Error("Error while getting streams json", err)
return nil, err
}
json.Unmarshal(body, &s)
return s.Data, nil
}
// GetFollows will get the number of followers for a user
// The url query parameter are defined by the GetStreamsInput struct
func (c Client) GetFollows(userID string) (int, error) {
var uri *url.URL
var header = http.Header{}
// set url
uri, err := url.Parse(baseURL + getUserFollow)
if err != nil {
return 0, err
}
// set header
header.Add("Client-ID", c.ClientID)
header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token.AccessToken))
query := uri.Query()
query.Add("to_id", userID)
uri.RawQuery = query.Encode()
log.Debug("Follow URI: ", uri.String())
res, err := c.doRequest(http.MethodGet, uri.String(), header, nil)
if err != nil {
return 0, err
}
defer res.Body.Close()
s := UserFollow{}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return 0, err
}
json.Unmarshal(body, &s)
return s.Total, nil
}