-
Notifications
You must be signed in to change notification settings - Fork 14
/
pocket.go
208 lines (168 loc) · 5 KB
/
pocket.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
package pocket
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
const (
host = "https://getpocket.com/v3"
authorizeUrl = "https://getpocket.com/auth/authorize?request_token=%s&redirect_uri=%s"
endpointAdd = "/add"
endpointRequestToken = "/oauth/request"
endpointAuthorize = "/oauth/authorize"
// xErrorHeader used to parse error message from Headers on non-2XX responses
xErrorHeader = "X-Error"
defaultTimeout = 5 * time.Second
)
type (
requestTokenRequest struct {
ConsumerKey string `json:"consumer_key"`
RedirectURI string `json:"redirect_uri"`
}
authorizeRequest struct {
ConsumerKey string `json:"consumer_key"`
Code string `json:"code"`
}
AuthorizeResponse struct {
AccessToken string `json:"access_token"`
Username string `json:"username"`
}
addRequest struct {
URL string `json:"url"`
Title string `json:"title,omitempty"`
Tags string `json:"tags,omitempty"`
AccessToken string `json:"access_token"`
ConsumerKey string `json:"consumer_key"`
}
// AddInput holds data necessary to create new item in Pocket list
AddInput struct {
URL string
Title string
Tags []string
AccessToken string
}
)
func (i AddInput) validate() error {
if i.URL == "" {
return errors.New("required URL values is empty")
}
if i.AccessToken == "" {
return errors.New("access token is empty")
}
return nil
}
func (i AddInput) generateRequest(consumerKey string) addRequest {
return addRequest{
URL: i.URL,
Tags: strings.Join(i.Tags, ","),
Title: i.Title,
AccessToken: i.AccessToken,
ConsumerKey: consumerKey,
}
}
// Client is a getpocket API client
type Client struct {
client *http.Client
consumerKey string
}
// NewClient creates a new client instance with your app key (to generate key visit https://getpocket.com/developer/apps/)
func NewClient(consumerKey string) (*Client, error) {
if consumerKey == "" {
return nil, errors.New("consumer key is empty")
}
return &Client{
client: &http.Client{
Timeout: defaultTimeout,
},
consumerKey: consumerKey,
}, nil
}
// GetRequestToken obtains the request token that is used to authorize user in your application
func (c *Client) GetRequestToken(ctx context.Context, redirectUrl string) (string, error) {
inp := &requestTokenRequest{
ConsumerKey: c.consumerKey,
RedirectURI: redirectUrl,
}
values, err := c.doHTTP(ctx, endpointRequestToken, inp)
if err != nil {
return "", err
}
if values.Get("code") == "" {
return "", errors.New("empty request token in API response")
}
return values.Get("code"), nil
}
// GetAuthorizationURL generates link to authorize user
func (c *Client) GetAuthorizationURL(requestToken, redirectUrl string) (string, error) {
if requestToken == "" || redirectUrl == "" {
return "", errors.New("empty params")
}
return fmt.Sprintf(authorizeUrl, requestToken, redirectUrl), nil
}
// Authorize generates access token for user, that authorized in your app via link
func (c *Client) Authorize(ctx context.Context, requestToken string) (*AuthorizeResponse, error) {
if requestToken == "" {
return nil, errors.New("empty request token")
}
inp := &authorizeRequest{
Code: requestToken,
ConsumerKey: c.consumerKey,
}
values, err := c.doHTTP(ctx, endpointAuthorize, inp)
if err != nil {
return nil, err
}
accessToken, username := values.Get("access_token"), values.Get("username")
if accessToken == "" {
return nil, errors.New("empty access token in API response")
}
return &AuthorizeResponse{
AccessToken: accessToken,
Username: username,
}, nil
}
// Add creates new item in Pocket list
func (c *Client) Add(ctx context.Context, input AddInput) error {
if err := input.validate(); err != nil {
return err
}
req := input.generateRequest(c.consumerKey)
_, err := c.doHTTP(ctx, endpointAdd, req)
return err
}
func (c *Client) doHTTP(ctx context.Context, endpoint string, body interface{}) (url.Values, error) {
b, err := json.Marshal(body)
if err != nil {
return url.Values{}, errors.WithMessage(err, "failed to marshal input body")
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, host+endpoint, bytes.NewBuffer(b))
if err != nil {
return url.Values{}, errors.WithMessage(err, "failed to create new request")
}
req.Header.Set("Content-Type", "application/json; charset=UTF8")
resp, err := c.client.Do(req)
if err != nil {
return url.Values{}, errors.WithMessage(err, "failed to send http request")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err := fmt.Sprintf("API Error: %s", resp.Header.Get(xErrorHeader))
return url.Values{}, errors.New(err)
}
respB, err := ioutil.ReadAll(resp.Body)
if err != nil {
return url.Values{}, errors.WithMessage(err, "failed to read request body")
}
values, err := url.ParseQuery(string(respB))
if err != nil {
return url.Values{}, errors.WithMessage(err, "failed to parse response body")
}
return values, nil
}