-
Notifications
You must be signed in to change notification settings - Fork 0
/
pocket_client.go
99 lines (76 loc) · 1.88 KB
/
pocket_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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"github.com/motemen/go-pocket/api"
"github.com/motemen/go-pocket/auth"
)
func GetClient() (*api.Client, error) {
accessToken, err := restoreAccessToken(consumerKey)
if err != nil {
return nil, err
}
client := api.NewClient(consumerKey, accessToken.AccessToken)
return client, nil
}
func obtainAccessToken(consumerKey string) (*auth.Authorization, error) {
ch := make(chan struct{})
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/favicon.ico" {
http.Error(w, "Not Found", 404)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Authorized.")
ch <- struct{}{}
}))
defer ts.Close()
redirectURL := ts.URL
requestToken, err := auth.ObtainRequestToken(consumerKey, redirectURL)
if err != nil {
return nil, err
}
url := auth.GenerateAuthorizationURL(requestToken, redirectURL)
fmt.Println(url)
<-ch
return auth.ObtainAccessToken(consumerKey, requestToken)
}
func restoreAccessToken(consumerKey string) (*auth.Authorization, error) {
accessToken := &auth.Authorization{}
authFile := filepath.Join(os.TempDir(), "getpocket.json")
err := loadJSONFromFile(authFile, accessToken)
if err != nil {
log.Println(err)
accessToken, err = obtainAccessToken(consumerKey)
if err != nil {
return nil, err
}
err = saveJSONToFile(authFile, accessToken)
if err != nil {
return nil, err
}
}
return accessToken, nil
}
func saveJSONToFile(path string, v interface{}) error {
w, err := os.Create(path)
if err != nil {
return err
}
defer w.Close()
return json.NewEncoder(w).Encode(v)
}
func loadJSONFromFile(path string, v interface{}) error {
r, err := os.Open(path)
if err != nil {
return err
}
defer r.Close()
return json.NewDecoder(r).Decode(v)
}