/
tdapi.go
334 lines (274 loc) · 8.29 KB
/
tdapi.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
/*
Copyright 2021 Bill Nixon
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tdapi
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"golang.org/x/oauth2"
)
const (
// baseURL = "https://api.todoist.com"
// apiBase = "/rest/v2"
apiBase = "https://api.todoist.com/rest/v2"
authBase = "https://todoist.com/oauth"
authURL = authBase + "/authorize"
tokenURL = authBase + "/access_token"
redirectURL = "https://example.com/redirect"
)
// init sets default logging flags
func init() {
// log with date, time, file name, and line number
log.SetFlags(log.Lshortfile)
}
// Get executes the Todoist REST API call, returning the response body.
// Query parmeters can be included to specify and control the amount of data returned in a response.
// See https://developer.todoist.com/rest/v2/#overview
func (c *TodoistClient) Get(urlString string, query url.Values) (body []byte, err error) {
// parse the URL string
// url, err := url.Parse(c.BaseURL + apiBase + urlString)
url, err := url.Parse(apiBase + urlString)
if err != nil {
return body, err
}
// add the query parameters to the URL
url.RawQuery = query.Encode()
fmt.Println("DEBUG:", url.String())
// execute the request
resp, err := c.httpClient.Get(url.String())
if err != nil {
return body, err
}
defer resp.Body.Close()
// read the body
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return body, err
}
// check if an error occured and return a APIErrorResponse
if codeIsError(resp.StatusCode) {
resError := APIErrorResponse{}
resError.Err = string(body)
return nil, &resError
}
return body, err
}
// Put executes the Todist REST API call, returning the response body.
//
// Query parmeters can be included to specify and control the amount of data returned in a response.
//
// Exact query parameters varies from one API operation to another.
//
// More information can be found at https://docs.microsoft.com/en-us/graph/query-parameters
func (c *TodoistClient) Put(urlString string, query url.Values, data io.Reader) (body []byte, err error) {
// parse the URL string
url, err := url.Parse(apiBase + urlString)
if err != nil {
return body, err
}
// add the query parameters to the URL
url.RawQuery = query.Encode()
// fmt.Println("DEBUG:", url.String())
req, err := http.NewRequest(http.MethodPut, url.String(), data)
if err != nil {
return body, err
}
// execute the request
resp, err := c.httpClient.Do(req)
if err != nil {
// handle error
return body, err
}
defer resp.Body.Close()
// read the body
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return body, err
}
// check if an error occured and return a APIErrorResponse
if codeIsError(resp.StatusCode) {
resError := APIErrorResponse{}
err = json.Unmarshal(body, &resError)
if err != nil {
return nil, err
}
return nil, &resError
}
return body, err
}
// TodoistClient is a client connection to the Todoist REST API. See https://developer.todoist.com/rest/v2/#overview
type TodoistClient struct {
httpClient *http.Client
// BaseURL string
}
// New creates an initialized TodoistClient using the token from tokenFileName.
//
// If tokenFileName doesn't exist, then a token is requested and saved in the file.
//
// The current approach assumes the client runs on a host without a
// browser. The user is instructed to vist a URL to login and authorize the
// client. Once the login is successful, the user must copy the response
// URL and provide to the client program.
//
// The token is requested for offline access, which should include a refresh
// token to allow access for a long period of time.
//
// clientID and clientSecret must be an application registered with the Todoist App Console
func New(tokenFileName string, id string, secret string, scopes []string) *TodoistClient {
// default Context that is never canceled, has no values, and has no deadline
ctx := context.Background()
// scopes = append(scopes, "offline_access")
// OAuth2 configuration object
conf := &oauth2.Config{
ClientID: id,
ClientSecret: secret,
Scopes: scopes,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
RedirectURL: redirectURL,
}
client := &TodoistClient{}
// try to get a token from the file
token, _ := readTokenFromFile(tokenFileName)
// if token couldn't be retrived, then get a new token
if token == nil {
// generate random state to detect Cross-Site Request Forgery
state := randomBytesBase64(32)
// get authentication URL for offline access
authURL := conf.AuthCodeURL(state, oauth2.AccessTypeOffline)
// instruct the user to vist the authentication URL
fmt.Println("Visit the following URL in a browser to authenticate this application")
fmt.Println("After authentication, copy the response URL from the browser")
fmt.Println(authURL)
// read the response URL
fmt.Println("Enter the response URL:")
responseString, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
log.Fatal(err)
}
responseString = strings.TrimSpace(responseString)
// parse the response URL
responseURL, err := url.Parse(responseString)
if err != nil {
log.Fatal(err)
}
// get and compare state to prevent Cross-Site Request Forgery
responseState := responseURL.Query().Get("state")
if responseState != state {
log.Fatalln("state mismatch, potenial Cross-Site Request Forgery (CSRF)")
}
// get authorization code
code := responseURL.Query().Get("code")
// exchange authorize code for token
token, err = conf.Exchange(ctx, code)
if err != nil {
log.Fatal(err)
}
// save the token to a file
writeTokenToFile(tokenFileName, token)
}
// create HTTP client using the provided token
client.httpClient = conf.Client(ctx, token)
// client.BaseURL = baseURL
return client
}
// randomBytesBase64 returns n bytes encoded in URL friendly base64.
func randomBytesBase64(n int) string {
// buffer to store n bytes
b := make([]byte, n)
// get b random bytes
_, err := rand.Read(b)
if err != nil {
log.Fatal(err)
}
// convert to URL friendly base64
return base64.URLEncoding.EncodeToString(b)
}
// readTokenFromFile reads the json encoded token from a file.
func readTokenFromFile(filename string) (*oauth2.Token, error) {
// open file
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
// read json encoded token
token := &oauth2.Token{}
err = json.NewDecoder(file).Decode(token)
return token, err
}
// writeTokenToFile writes a josn encoded token to a file.
//
// If file already exists, it is replaced.
func writeTokenToFile(fileName string, token *oauth2.Token) {
// create file
file, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// write access token string
json.NewEncoder(file).Encode(token)
return
}
func PrettyPrintJson(src []byte) {
var out bytes.Buffer
json.Indent(&out, src, "", " ")
fmt.Println("=== BEGIN ===")
fmt.Println(out.String())
fmt.Println("=== END ===")
}
// VarToJsonString converts any varaible (interface{}) to an indented JSON string.
//
// Only public (capitalized) fields will be visible.
func VarToJsonString(v interface{}) string {
var buffer bytes.Buffer
// using Encoder rather than MarshalIndent to not escape HTML
encoder := json.NewEncoder(&buffer)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
err := encoder.Encode(v)
if err != nil {
return "ERROR"
}
return string(buffer.Bytes())
}
// WriteContent writes the []byte content to a file
func WriteContentToFile(content []byte, fileName string) (err error) {
// create file
var file *os.File
file, err = os.Create(fileName)
if err != nil {
return err
}
defer file.Close()
// write content
_, err = file.Write(content)
if err != nil {
return err
}
return nil
}