-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
191 lines (151 loc) · 4.88 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
package gotidal
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"unicode"
)
const (
contentType = "application/vnd.tidal.v1+json"
environment = "https://openapi.tidal.com"
oauthURI = "https://auth.tidal.com/v1/oauth2/token"
)
var ErrUnexpectedResponseCode = errors.New("returned an unexpected status code")
// HTTPClient provides an interface to make HTTP requests.
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// Client defines the parameters needed to create a TIDAL API client.
type Client struct {
httpClient HTTPClient
ContentType string
Environment string
Token string
CountryCode string
}
// PaginationParams defines the limit and offset for pagination functions.
type PaginationParams struct {
Limit int
Offset int
}
// NewClient returns an API client based on a users credentials and location.
func NewClient(clientID string, clientSecret string, countryCode string) (*Client, error) {
ctx := context.Background()
httpClient := &http.Client{}
token, err := getAccessToken(ctx, httpClient, clientID, clientSecret)
if err != nil {
return nil, err
}
return &Client{
httpClient: httpClient,
ContentType: contentType,
Environment: environment,
Token: token,
CountryCode: countryCode,
}, nil
}
type authResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
}
func getAccessToken(ctx context.Context, httpClient HTTPClient, clientID string, clientSecret string) (string, error) {
basicAuth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", clientID, clientSecret)))
requestBody := []byte(`grant_type=client_credentials`)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, oauthURI, bytes.NewBuffer(requestBody))
if err != nil {
return "", fmt.Errorf("failed to create OAuth request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", concat("Basic ", basicAuth))
responseBody, err := processRequest(httpClient, req)
if err != nil {
return "", fmt.Errorf("failed to process the request: %w", err)
}
var authResponse authResponse
err = json.Unmarshal(responseBody, &authResponse)
if err != nil {
return "", fmt.Errorf("failed to unmarshal the OAuth response body: %w", err)
}
return authResponse.AccessToken, nil
}
func processRequest(httpClient HTTPClient, req *http.Request) ([]byte, error) {
response, err := httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to process request: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusMultiStatus {
return nil, fmt.Errorf("%w: %d", ErrUnexpectedResponseCode, response.StatusCode)
}
responseBody, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed to read the OAuth response body: %w", err)
}
return responseBody, nil
}
// nolint:unparam
func (c *Client) request(ctx context.Context, method string, path string, params any) ([]byte, error) {
uri := fmt.Sprintf("%s%s?%s", c.Environment, path, toURLParams(params, c.CountryCode))
req, err := http.NewRequestWithContext(ctx, method, uri, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request for %s: %w", uri, err)
}
req.Header.Set("Content-Type", c.ContentType)
req.Header.Set("Authorization", concat("Bearer ", c.Token))
req.Header.Set("accept", c.ContentType)
return processRequest(c.httpClient, req)
}
func toURLParams(input interface{}, countryCode string) string {
var params []string
params = append(params, fmt.Sprintf("%s=%s", "countryCode", countryCode))
if input == nil {
return strings.Join(params, "&")
}
v := reflect.ValueOf(input)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
field := t.Field(i)
value := v.Field(i)
if value.IsValid() {
var paramValue string
switch value.Kind() {
case reflect.String:
paramValue = value.String()
case reflect.Int:
paramValue = strconv.FormatInt(value.Int(), 10)
default:
continue
}
if paramValue != "" && paramValue != "0" {
paramName := url.QueryEscape(lowercaseFirstLetter(field.Name))
paramValue = url.QueryEscape(paramValue)
params = append(params, fmt.Sprintf("%s=%s", paramName, paramValue))
}
}
}
return strings.Join(params, "&")
}
// lowercaseFirstLetter converts the first letter of a string the lowercase to match the camel-casing of the TIDAL
// API URL parameters.
func lowercaseFirstLetter(str string) string {
if len(str) == 0 {
return str
}
firstChar := []rune(str)[0]
lowerFirstChar := unicode.ToLower(firstChar)
return string(lowerFirstChar) + str[1:]
}
// concat joins strings together in a more efficient way than fmt.Sprintf.
func concat(strs ...string) string {
return strings.Join(strs, "")
}