-
Notifications
You must be signed in to change notification settings - Fork 1
/
twitch.go
199 lines (174 loc) · 6.46 KB
/
twitch.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
log "github.com/Sirupsen/logrus"
)
// TODO: Use Helix wherever possible
// https://dev.twitch.tv/docs/api/
//
// v5 API is being removed 12/31/18
// https://dev.twitch.tv/docs/v5/
//
// Twitch API v5 (Kraken) Client
//
type KrakenClient struct {
ClientID string
}
func NewKrakenClient(clientID string) *KrakenClient {
return &KrakenClient{
ClientID: clientID,
}
}
// Request is a generic Kraken API request
func (kc KrakenClient) Request(url string) ([]byte, *http.Response, error) {
// Each client ID is granted a total of 30 queries per minute (if a Bearer token is not provided)
// or, 1 request every 2 seconds
// https://dev.twitch.tv/docs/api/guide/#rate-limits
//
// Simple method of obeying this rate limit: sleep 2 seconds before each request
// Could make this cleverer, and keep track, but this is good enough for now
time.Sleep(2 * time.Second)
// Modified from code generated by curl-to-Go: https://mholt.github.io/curl-to-go
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.WithFields(log.Fields{"url": url}).Errorf("%s", err)
return []byte{}, nil, err
}
req.Header.Set("Accept", "application/vnd.twitchtv.v5+json")
req.Header.Set("Client-Id", kc.ClientID)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.WithFields(log.Fields{"url": url}).Errorf("%s", err)
return []byte{}, resp, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.WithFields(log.Fields{"url": url}).Errorf("%s", err)
return []byte{}, resp, err
}
return body, resp, nil
}
//
// Kraken Requests
//
// https://dev.twitch.tv/docs/v5/#translating-from-user-names-to-user-ids
// Response from
// curl -s -H 'Accept: application/vnd.twitchtv.v5+json' \
// -H 'Client-ID: ${CLIENT_ID}' \
// -X GET "https://api.twitch.tv/kraken/users?login=${COMMA_SEPARATED_LIST_OF_CHANNELS}"
type KrakenUsersResponse struct {
Total int `json:"_total"`
Users []struct {
DisplayName string `json:"display_name"`
ID string `json:"_id"`
Name string `json:"name"`
Type string `json:"type"`
Bio string `json:"bio"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Logo string `json:"logo"`
} `json:"users"`
}
func (kc KrakenClient) Users(users []string) (KrakenUsersResponse, error) {
// init an empty response
response := KrakenUsersResponse{}
// body, resp, err
commaSeparatedUsers := strings.Join(users, ",")
body, resp, err := kc.Request("https://api.twitch.tv/kraken/users?login=" + commaSeparatedUsers)
if err != nil {
log.WithFields(log.Fields{"users": users}).Errorf("%s", err)
return response, err
}
if resp.StatusCode != 200 {
log.WithFields(log.Fields{"users": users}).Errorf("Error code %s, Error: %s", resp.StatusCode, err)
return response, err
}
err = json.Unmarshal(body, &response)
if err != nil {
log.WithFields(log.Fields{"users": users}).Errorf("%s", err)
return response, err
}
return response, nil
}
// https://dev.twitch.tv/docs/v5/reference/streams/#get-live-streams
// Response from
// curl -s -H 'Accept: application/vnd.twitchtv.v5+json' \
// -H "Client-ID: ${CLIENT_ID}" \
// -X GET "https://api.twitch.tv/kraken/streams/?channel=${COMMA_SEPARATED_LIST_OF_CHANNELS}"
//
// Includes only those channels which are live
// So need to query non-live channels separately
type KrakenStreamsResponse struct {
Total int `json:"_total"`
Streams []struct {
ID int64 `json:"_id"`
Game string `json:"game"`
BroadcastPlatform string `json:"broadcast_platform"`
CommunityID string `json:"community_id"`
CommunityIds []string `json:"community_ids"`
Viewers int `json:"viewers"`
VideoHeight int `json:"video_height"`
AverageFps float32 `json:"average_fps"`
Delay int `json:"delay"`
CreatedAt time.Time `json:"created_at"`
IsPlaylist bool `json:"is_playlist"`
StreamType string `json:"stream_type"`
Preview struct {
Small string `json:"small"`
Medium string `json:"medium"`
Large string `json:"large"`
Template string `json:"template"`
} `json:"preview"`
Channel struct {
Mature bool `json:"mature"`
Status string `json:"status"`
BroadcasterLanguage string `json:"broadcaster_language"`
DisplayName string `json:"display_name"`
Game string `json:"game"`
Language string `json:"language"`
ID int `json:"_id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Partner bool `json:"partner"`
Logo string `json:"logo"`
VideoBanner string `json:"video_banner"`
ProfileBanner string `json:"profile_banner"`
ProfileBannerBackgroundColor string `json:"profile_banner_background_color"`
URL string `json:"url"`
Views int `json:"views"`
Followers int `json:"followers"`
BroadcasterType string `json:"broadcaster_type"`
Description string `json:"description"`
PrivateVideo bool `json:"private_video"`
PrivacyOptionsEnabled bool `json:"privacy_options_enabled"`
} `json:"channel"`
} `json:"streams"`
}
func (kc KrakenClient) Streams(channels []string) (KrakenStreamsResponse, error) {
// init an empty response
response := KrakenStreamsResponse{}
// body, resp, err
commaSeparatedChannels := strings.Join(channels, ",")
url := "https://api.twitch.tv/kraken/streams?channel=" + commaSeparatedChannels
body, resp, err := kc.Request(url)
if err != nil {
log.WithFields(log.Fields{"channels": channels}).Errorf("%s", err)
return response, err
}
if resp.StatusCode != 200 {
log.WithFields(log.Fields{"channels": channels}).Errorf("Error code %s, Error: %s", resp.StatusCode, err)
return response, err
}
err = json.Unmarshal(body, &response)
if err != nil {
log.WithFields(log.Fields{"channels": channels}).Errorf("%s", err)
return response, err
}
return response, nil
}