-
Notifications
You must be signed in to change notification settings - Fork 71
/
api.go
226 lines (185 loc) · 5.1 KB
/
api.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package api
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"runtime"
"sort"
"strings"
"time"
"github.com/twitchdev/twitch-cli/internal/login"
"github.com/twitchdev/twitch-cli/internal/models"
"github.com/twitchdev/twitch-cli/internal/util"
"github.com/TylerBrock/colorjson"
"github.com/fatih/color"
"github.com/spf13/viper"
)
var baseURL = "https://api.twitch.tv/helix"
type clientInformation struct {
ClientID string
Token string
}
// NewRequest is used to request data from the Twitch API using a HTTP GET request- this function is a wrapper for the apiRequest function that handles the network call
func NewRequest(method string, path string, queryParameters []string, body []byte, prettyPrint bool, autopaginate bool) {
var data models.APIResponse
var err error
var cursor string
data.Data = make([]interface{}, 0)
client, err := GetClientInformation()
if viper.GetString("BASE_URL") != "" {
baseURL = viper.GetString("BASE_URL")
}
if err != nil {
fmt.Println("Error fetching client information", err.Error())
}
for {
var apiResponse models.APIResponse
u, err := url.Parse(baseURL + path)
if err != nil {
fmt.Printf("Error getting url: %v", err)
return
}
q := u.Query()
for _, paramStr := range queryParameters {
var value string
param := strings.Split(paramStr, "=")
if len(param) == 2 {
value = param[1]
}
q.Add(param[0], value)
}
if cursor != "" {
q.Set("after", cursor)
}
if autopaginate == true {
first := "100"
// since channel points custom rewards endpoints only support 50, capping that here
if strings.Contains(u.String(), "custom_rewards") {
first = "50"
}
q.Set("first", first)
}
u.RawQuery = q.Encode()
resp, err := apiRequest(strings.ToUpper(method), u.String(), body, apiRequestParameters{
ClientID: client.ClientID,
Token: client.Token,
})
if err != nil {
fmt.Printf("Error reading body: %v", err)
return
}
if resp.StatusCode == http.StatusNoContent {
fmt.Println("Endpoint responded with status 204")
return
}
err = json.Unmarshal(resp.Body, &apiResponse)
if err != nil {
fmt.Printf("Error unmarshalling body: %v", err)
return
}
if resp.StatusCode > 299 || resp.StatusCode < 200 {
data = apiResponse
break
}
d := data.Data.([]interface{})
if strings.Contains(path, "schedule") || apiResponse.Data == nil {
data.Data = append(d, apiResponse.Data)
} else {
data.Data = append(d, apiResponse.Data.([]interface{})...)
}
if apiResponse.Pagination == nil || *&apiResponse.Pagination.Cursor == "" {
break
}
if autopaginate == false {
data.Pagination = &models.APIPagination{
Cursor: apiResponse.Pagination.Cursor,
}
break
}
if apiResponse.Pagination.Cursor == cursor {
break
}
cursor = apiResponse.Pagination.Cursor
}
if data.Data == nil {
data.Data = make([]interface{}, 0)
}
// handle json marshalling better; returns empty slice vs. null
if len(data.Data.([]interface{})) == 0 && data.Error == "" {
data.Data = make([]interface{}, 0)
}
d, err := json.Marshal(data)
if err != nil {
log.Printf("Error marshalling json: %v", err)
return
}
if prettyPrint == true {
var obj map[string]interface{}
json.Unmarshal(d, &obj)
// since Command Prompt/Powershell don't support coloring, will pretty print without colors
if runtime.GOOS == "windows" {
s, _ := json.MarshalIndent(obj, "", " ")
fmt.Println(string(s))
return
}
f := colorjson.NewFormatter()
f.Indent = 2
f.KeyColor = color.New(color.FgBlue).Add(color.Bold)
s, err := f.Marshal(obj)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(s))
return
}
fmt.Println(string(d))
return
}
// ValidOptions returns a list of supported endpoints given a specified method as noted in the map endpointMethodSupports, which is located in resources.go of this package.
func ValidOptions(method string) []string {
names := []string{}
for n, m := range endpointMethodSupports {
if m[method] {
names = append(names, n)
}
}
sort.Strings(names)
return names
}
func GetClientInformation() (clientInformation, error) {
clientID := viper.GetString("clientID")
expiration := viper.GetString("tokenexpiration")
token := viper.GetString("accessToken")
// Handle legacy nonexpiring tokens
if expiration == "0" {
return clientInformation{
Token: token,
ClientID: clientID,
}, nil
}
ex, _ := time.Parse(time.RFC3339Nano, expiration)
if ex.Before(util.GetTimestamp()) {
refreshToken := viper.GetString("refreshToken")
if refreshToken == "" {
log.Fatal("Please run twitch token")
}
clientSecret := viper.GetString("clientSecret")
var err error
r, err := login.RefreshUserToken(login.RefreshParameters{
RefreshToken: refreshToken,
ClientID: clientID,
ClientSecret: clientSecret,
URL: login.RefreshTokenURL,
})
if err != nil {
return clientInformation{}, err
}
token = r.Response.AccessToken
}
return clientInformation{Token: token, ClientID: clientID}, nil
}