forked from cyruzin/golang-tmdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmdb.go
293 lines (268 loc) · 7.05 KB
/
tmdb.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
// Copyright (c) 2019 Cyro Dubeux. License MIT.
// Package tmdb is a wrapper for working with TMDb API.
package tmdb
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
jsoniter "github.com/json-iterator/go"
)
var json = jsoniter.ConfigFastest
// TMDb constants
const (
defaultBaseURL = "https://api.themoviedb.org/3"
alternateBaseURL = "https://api.tmdb.org/3"
permissionURL = "https://www.themoviedb.org/authenticate/"
authenticationURL = "/authentication/"
movieURL = "/movie/"
tvURL = "/tv/"
tvSeasonURL = "/season/"
tvEpisodeURL = "/episode/"
personURL = "/person/"
searchURL = "/search/"
collectionURL = "/collection/"
companyURL = "/company/"
configurationURL = "/configuration/"
creditURL = "/credit/"
discoverURL = "/discover/"
networkURL = "/network/"
keywordURL = "/keyword/"
genreURL = "/genre/"
guestSessionURL = "/guest_session/"
listURL = "/list/"
accountURL = "/account/"
watchProvidersURL = "/watch/providers/"
)
var baseURL = defaultBaseURL
// Client type is a struct to instantiate this pkg.
type Client struct {
// TMDb apiKey to use the client.
apiKey string
// bearerToken will be used for v4 requests.
bearerToken string
// sessionId to use the client.
sessionID string
// Auto retry flag to indicates if the client
// should retry the previous operation.
autoRetry bool
// http.Client for custom configuration.
http http.Client
}
// Response type is a struct for http responses.
type Response struct {
StatusCode int `json:"status_code"`
StatusMessage string `json:"status_message"`
}
// Init setups the Client with an apiKey.
func Init(apiKey string) (*Client, error) {
if apiKey == "" {
return nil, errors.New("api key is empty")
}
return &Client{apiKey: apiKey}, nil
}
// InitV4 setups the Client with an bearer token.
func InitV4(bearerToken string) (*Client, error) {
if bearerToken == "" {
return nil, errors.New("bearer token is empty")
}
return &Client{bearerToken: bearerToken}, nil
}
// SetSessionID will set the session id.
func (c *Client) SetSessionID(sid string) error {
if sid == "" {
return errors.New("the session id is empty")
}
c.sessionID = sid
return nil
}
// SetClientConfig sets a custom configuration for the http.Client.
func (c *Client) SetClientConfig(httpClient http.Client) {
c.http = httpClient
}
// SetClientAutoRetry sets autoRetry flag to true.
func (c *Client) SetClientAutoRetry() {
c.autoRetry = true
}
// Auto retry default duration.
const defaultRetryDuration = time.Second * 5
// retryDuration calculates the retry duration time.
func retryDuration(resp *http.Response) time.Duration {
retryTime := resp.Header.Get("Retry-After")
if retryTime == "" {
return defaultRetryDuration
}
seconds, err := strconv.ParseInt(retryTime, 10, 32)
if err != nil {
return defaultRetryDuration
}
return time.Duration(seconds) * time.Second
}
// shouldRetry determines whether the status code indicates that the
// previous operation should be retried at a later time.
func shouldRetry(status int) bool {
return status == http.StatusAccepted || status == http.StatusTooManyRequests
}
func (c *Client) get(url string, data interface{}) error {
if url == "" {
return errors.New("url field is empty")
}
if c.http.Timeout == 0 {
c.http.Timeout = time.Second * 10
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("could not fetch the url: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req = req.WithContext(ctx)
req.Header.Add("content-type", "application/json;charset=utf-8")
if c.bearerToken != "" {
req.Header.Add("Authorization", "Bearer "+c.bearerToken)
}
for {
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode == http.StatusTooManyRequests && c.autoRetry {
time.Sleep(retryDuration(res))
continue
}
if res.StatusCode == http.StatusNoContent {
return nil
}
if res.StatusCode != http.StatusOK {
return c.decodeError(res)
}
if err = json.NewDecoder(res.Body).Decode(data); err != nil {
return fmt.Errorf("could not decode the data: %s", err)
}
break
}
return nil
}
func (c *Client) request(
url string,
body interface{},
method string,
data interface{},
) error {
if url == "" {
return errors.New("url field is empty")
}
if c.http.Timeout == 0 {
c.http.Timeout = time.Second * 10
}
bodyBytes := new(bytes.Buffer)
json.NewEncoder(bodyBytes).Encode(body)
req, err := http.NewRequest(
method,
url,
bytes.NewBuffer(bodyBytes.Bytes()),
)
if err != nil {
return fmt.Errorf("could not fetch the url: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req = req.WithContext(ctx)
req.Header.Add("content-type", "application/json;charset=utf-8")
if c.bearerToken != "" {
req.Header.Add("Authorization", "Bearer "+c.bearerToken)
}
for {
res, err := c.http.Do(req)
if err != nil {
return errors.New(err.Error())
}
defer res.Body.Close()
if c.autoRetry && shouldRetry(res.StatusCode) {
time.Sleep(retryDuration(res))
continue
}
// Checking if the response is greater or equal
// to 300 or less than 200.
if res.StatusCode >= http.StatusMultipleChoices ||
res.StatusCode < http.StatusOK ||
res.StatusCode == http.StatusNoContent {
return c.decodeError(res)
}
if err = json.NewDecoder(res.Body).Decode(data); err != nil {
return fmt.Errorf("could not decode the data: %s", err)
}
break
}
return nil
}
func (c *Client) fmtOptions(
urlOptions map[string]string,
) string {
options := ""
if len(urlOptions) > 0 {
for key, value := range urlOptions {
options += fmt.Sprintf(
"&%s=%s",
key,
url.QueryEscape(value),
)
}
}
return options
}
// SetAlternateBaseURL sets an alternate base url.
func (c *Client) SetAlternateBaseURL() {
baseURL = alternateBaseURL
}
// SetCustomBaseURL sets an custom base url.
func (c *Client) SetCustomBaseURL(url string) {
baseURL = url
}
// GetBaseURL gets the current base url.
func (c *Client) GetBaseURL() string {
return baseURL
}
// Error type represents an error returned by the TMDB API.
type Error struct {
StatusMessage string `json:"status_message,omitempty"`
Success bool `json:"success,omitempty"`
StatusCode int `json:"status_code,omitempty"`
}
func (e Error) Error() string {
return fmt.Sprintf(
"code: %d | success: %t | message: %s",
e.StatusCode,
e.Success,
e.StatusMessage,
)
}
func (c *Client) decodeError(r *http.Response) error {
resBody, err := io.ReadAll(r.Body)
if err != nil {
return fmt.Errorf("could not read body response: %s", err)
}
if len(resBody) == 0 {
return fmt.Errorf(
"[%d]: empty body %s",
r.StatusCode,
http.StatusText(r.StatusCode),
)
}
buf := bytes.NewBuffer(resBody)
var clientError Error
if err := json.NewDecoder(buf).Decode(&clientError); err != nil {
return fmt.Errorf(
"couldn't decode error: (%d) [%s]",
len(resBody),
resBody,
)
}
return clientError
}