-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
75 lines (66 loc) · 1.8 KB
/
sync.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
package trakt
import (
"bytes"
"context"
"encoding/json"
"net/http"
"path"
"github.com/pkg/errors"
)
const (
syncBasePath = "/sync"
collectionPath = "/collection"
)
var _ Sync = (*Client)(nil)
type Sync interface {
Collection(context.Context, *CollectionBody) (*CollectionResult, error)
}
type CollectionBody struct {
Movies []Movie `json:"movies,omitempty"`
Shows []Show `json:"shows,omitempty"`
Seasons []Season `json:"seasons,omitempty"`
Episodes []Episode `json:"episodes,omitempty"`
}
type Collection struct {
Movies int `json:"movies,omitempty"`
Episodes int `json:"episodes,omitempty"`
}
type CollectionResult struct {
Added Collection `json:"added,omitempty"`
Updated Collection `json:"updated,omitempty"`
Existing Collection `json:"existing,omitempty"`
NotFound struct {
Movies []Movie `json:"movies,omitempty"`
Shows []Show `json:"shows,omitempty"`
Seasons []Season `json:"seasons,omitempty"`
Episodes []Episode `json:"episode,omitempty"`
} `json:"not_found,omitempty"`
}
func (c *Client) Collection(ctx context.Context, collectionBody *CollectionBody) (*CollectionResult, error) {
postBody, err := json.Marshal(collectionBody)
if err != nil {
return nil, err
}
uri := *c.BaseURL
uri.Path = path.Join(uri.Path, syncBasePath, collectionPath)
req, err := http.NewRequest(http.MethodPost, uri.String(), bytes.NewReader(postBody))
if err != nil {
return nil, err
}
c.SetHeaders(req)
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
return nil, errors.Errorf("error updating collection: %d", resp.StatusCode)
}
result := &CollectionResult{}
err = json.NewDecoder(resp.Body).Decode(result)
if err != nil {
return nil, err
}
return result, nil
}