-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
398 lines (370 loc) · 11 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// Package tvdb is a wrapper in Go for the TVDB json api version 2. With this
// package you can make http requests to https://api.thetvdb.com.
//
// You can install this package with:
//
// $ go get github.com/pioz/tvdb
//
// # See also
//
// https://api.thetvdb.com/swagger for TVDB api version 2 documentation.
package tvdb
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Client does the work of perform the REST requests to the TVDB api endpoints.
// With its methods you can run almost all the requests provided in the TVDB
// api. It is engough to specify the Apikey, if you leave the Userkey and Username as nil.
type Client struct {
// The TVDB API key, User key, Username. You can get them here http://thetvdb.com/?tab=apiregister
Apikey string
Userkey string
Username string
// The language with which you want to obtain the data (if not set english is
// used)
Language string
token string
client http.Client
}
// BaseURL where the TVDB api is accessible.
const BaseURL string = "https://api.thetvdb.com"
// Login is used to retrieve a valid token which will be used to make any other
// requests to the TVDB api. The token is stored in the Client struct.
func (c *Client) Login() error {
loginData := map[string]string{"apikey": c.Apikey}
if c.Userkey != "" {
loginData["userkey"] = c.Userkey
}
if c.Username != "" {
loginData["username"] = c.Username
}
resp, err := c.performPOSTRequest("/login", loginData)
if err != nil {
return err
}
defer resp.Body.Close()
data := new(loginAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
c.token = data.Token
return nil
}
// RefreshToken is used to refresh the current token.
func (c *Client) RefreshToken() error {
resp, err := c.performGETRequest("/refresh_token", nil)
if err != nil {
return err
}
defer resp.Body.Close()
data := new(loginAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
c.token = data.Token
return nil
}
// GetLanguages returns all avaiable languages, a slice of Language.
func (c *Client) GetLanguages() ([]Language, error) {
resp, err := c.performGETRequest("/languages", nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data := new(languagesAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return nil, err
}
return data.Data, nil
}
// SearchByName allows to search for a series based on the series name. Returns
// the slice of the series found.
func (c *Client) SearchByName(q string) ([]Series, error) {
return c.search(url.Values{"name": {q}})
}
// SearchByImdbID allows to search for a series based on the IMDB id
// (https://www.imdb.com). Returns the slice of the series found.
func (c *Client) SearchByImdbID(q string) ([]Series, error) {
return c.search(url.Values{"imdbId": {q}})
}
// SearchByZap2itID allows to search for a series based on the Zap2it id
// (http://zap2it.com). Returns the slice of the series found.
func (c *Client) SearchByZap2itID(q string) ([]Series, error) {
return c.search(url.Values{"zap2itId": {q}})
}
// BestSearch returns the best Series based on the name (q).
func (c *Client) BestSearch(q string) (Series, error) {
res, err := c.SearchByName(q)
if err != nil {
return Series{}, err
}
for _, series := range res {
if strings.ToLower(series.SeriesName) == strings.ToLower(q) {
return series, nil
}
}
for _, serie := range res {
for _, alias := range serie.Aliases {
if strings.ToLower(alias) == strings.ToLower(q) {
return serie, nil
}
}
}
return res[0], nil
}
// GetSeries retrieve all series's fields. If a series is returned from a search
// method it will not have all fields filled. This method fills all fields of
// the series passed by reference as parameter.
func (c *Client) GetSeries(s *Series) error {
if s.Empty() {
return errors.New("the serie is empty")
}
resp, err := c.performGETRequest(fmt.Sprintf("/series/%d", s.ID), nil)
if err != nil {
return err
}
defer resp.Body.Close()
data := new(seriesAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
*s = data.Data
return nil
}
// GetUpdates returns a map of show identifiers updated since epoch
func (c *Client) GetUpdates(epoch int) ([]Update, error) {
resp, err := c.performGETRequest("/updated/query", url.Values{"fromTime": {strconv.Itoa(epoch)}})
if err != nil {
return nil, err
}
defer resp.Body.Close()
data := new(updatesAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return nil, err
}
return data.Data, nil
}
// GetSeriesActors retrieve all series's actors. Actors slice is accessible from
// series.Actors struct field.
func (c *Client) GetSeriesActors(s *Series) error {
if s.Empty() {
return errors.New("the serie is empty")
}
resp, err := c.performGETRequest(fmt.Sprintf("/series/%d/actors", s.ID), nil)
if err != nil {
return err
}
defer resp.Body.Close()
data := new(actorsAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
s.Actors = data.Data
return nil
}
// GetSeriesEpisodes retrieve series's episodes. Episodes slice is accessible
// from series.Episodes struct field but is better obtain episodes using the
// series's methods GetEpisodes and GetEpisode. The parameter params is the
// parameters used to perform the request to the api. Valid params are:
// absoluteNumber, airedSeason, airedEpisode, dvdSeason, dvdEpisode, imdbId,
// page (100 episodes per page, if page is not passed retrieve all episodes).
func (c *Client) GetSeriesEpisodes(s *Series, params url.Values) error {
if s.Empty() {
return errors.New("the serie is empty")
}
episodes := make([]Episode, 0)
var (
data episodesAPIResponse
resp *http.Response
err error
)
if params == nil {
params = url.Values{"page": {"1"}}
}
for page := 1; ; page++ {
params.Set("page", strconv.Itoa(page))
resp, err = c.performGETRequest(fmt.Sprintf("/series/%d/episodes/query", s.ID), params)
if err != nil {
return err
}
defer resp.Body.Close()
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
episodes = append(episodes, data.Data...)
if len(data.Data) < 100 {
break
}
}
s.Episodes = episodes
return nil
}
// GetSeriesSummary retrieve the summary of the episodes and seasons available
// for the series. Summary is accessible from series.Summary struct field.
func (c *Client) GetSeriesSummary(s *Series) error {
if s.Empty() {
return errors.New("the serie is empty")
}
resp, err := c.performGETRequest(fmt.Sprintf("/series/%d/episodes/summary", s.ID), nil)
if err != nil {
return err
}
defer resp.Body.Close()
data := new(summaryAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
s.Summary = data.Data
return nil
}
// GetEpisode retrieve all episode's fields. If an episode is returned from the
// GetEpisodes method it will not have all fields filled. This method fills all
// fields of the episode passed by reference as parameter.
func (c *Client) GetEpisode(e *Episode) error {
if e.Empty() {
return errors.New("the episode is empty")
}
resp, err := c.performGETRequest(fmt.Sprintf("/episodes/%d", e.ID), nil)
if err != nil {
return err
}
defer resp.Body.Close()
data := new(episodeAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
*e = data.Data
return nil
}
// GetSeriesFanartImages retrieve fanart images of the series. These images are
// accessible from series.Images struct field.
func (c *Client) GetSeriesFanartImages(s *Series) error {
return c.getSeriesImages(s, "fanart")
}
// GetSeriesPosterImages retrieve poster images of the series. These images are
// accessible from series.Images struct field.
func (c *Client) GetSeriesPosterImages(s *Series) error {
return c.getSeriesImages(s, "poster")
}
// GetSeriesSeasonImages retrieve season images of the series. These images are
// accessible from series.Images struct field.
func (c *Client) GetSeriesSeasonImages(s *Series) error {
return c.getSeriesImages(s, "season")
}
// GetSeriesSeasonwideImages retrieve season wide images of the series. These images are
// accessible from series.Images struct field.
func (c *Client) GetSeriesSeasonwideImages(s *Series) error {
return c.getSeriesImages(s, "seasonwide")
}
// GetSeriesSeriesImages retrieve series images of the series. These images are
// accessible from series.Images struct field.
func (c *Client) GetSeriesSeriesImages(s *Series) error {
return c.getSeriesImages(s, "series")
}
func (c *Client) getSeriesImages(s *Series, keyType string) error {
if s.Empty() {
return errors.New("the serie is empty")
}
resp, err := c.performGETRequest(fmt.Sprintf("/series/%d/images/query", s.ID), url.Values{"keyType": {keyType}})
if err != nil {
return err
}
defer resp.Body.Close()
data := new(imagesAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return err
}
s.Images = data.Data
return nil
}
func (c *Client) search(params url.Values) ([]Series, error) {
resp, err := c.performGETRequest("/search/series", params)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data := new(searchAPIResponse)
err = parseResponse(resp.Body, &data)
if err != nil {
return nil, err
}
return data.Data, nil
}
func (c *Client) performGETRequest(path string, params url.Values) (*http.Response, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s%s", BaseURL, path), nil)
req.URL.RawQuery = params.Encode()
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", c.Language)
if c.token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token))
}
resp, err := c.client.Do(req)
if err == nil && resp.StatusCode != 200 {
return nil, &RequestError{resp.StatusCode}
}
return resp, err
}
func (c *Client) performPOSTRequest(path string, params map[string]string) (*http.Response, error) {
jsonMarshal, _ := json.Marshal(params)
req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", BaseURL, path), bytes.NewBuffer(jsonMarshal))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", c.Language)
if c.token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token))
}
resp, err := c.client.Do(req)
if err == nil && resp.StatusCode != 200 {
return nil, &RequestError{resp.StatusCode}
}
return resp, err
}
func parseResponse(body io.ReadCloser, data interface{}) error {
// b, err := ioutil.ReadAll(body)
// if err != nil {
// return err
// }
// fmt.Println(string(b))
// err = json.Unmarshal(b, &data)
err := json.NewDecoder(body).Decode(data)
if err != nil {
return err
}
return nil
}
// func arrangeEpisodes(episodes []Episode) Episodes {
// m := make(Episodes)
// for _, ep := range episodes {
// if m[ep.AiredSeason] == nil {
// m[ep.AiredSeason] = map[int]Episode{ep.AiredEpisodeNumber: ep}
// } else {
// m[ep.AiredSeason][ep.AiredEpisodeNumber] = ep
// }
// }
// return m
// }