-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
272 lines (229 loc) · 6.89 KB
/
api.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
package shimo_openapi
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
"time"
"github.com/wuhan-support/shimo-openapi/transform"
)
const Endpoint = "https://api.shimo.im"
const TokenTTL = time.Hour
var client = http.Client{
Timeout: time.Minute,
}
// NewClient initializes a new Client
func NewClient(clientId string, clientSecret string, username string, password string, scope string) *Client {
client := &Client{
clientId: clientId,
clientSecret: clientSecret,
username: username,
password: password,
scope: scope,
asyncSign: make(chan sign, 10),
cache: make(map[string]*Cache),
}
go client.receiveSign()
return client
}
// doOAuth receives oauth parameters, sends an OAuth request to the server, and returns the access key it got
func (c *Client) doOAuth(v url.Values) (string, error) {
buf := bytes.NewBufferString(v.Encode())
req, err := http.NewRequest("POST", Endpoint+"/oauth/token", buf)
if err != nil {
return "", nil
}
basic := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.clientId, c.clientSecret)))
//spew.Dump(basic)
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", basic))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
//spew.Dump(req)
response, err := client.Do(req)
if err != nil {
return "", err
}
defer response.Body.Close()
// spew.Dump(response.Body)
if response.StatusCode != 200 {
i, _ := ioutil.ReadAll(response.Body)
return "", fmt.Errorf("non-200 response received when getting token: %v", string(i))
}
var oauthCredentials oAuthResponse
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&oauthCredentials)
if err != nil {
return "", err
}
// spew.Dump(oauthCredentials)
c.credential.accessToken = oauthCredentials.AccessToken
c.credential.accessTokenExpiresAt = time.Now().Add(TokenTTL)
c.credential.refreshToken = oauthCredentials.RefreshToken
return oauthCredentials.AccessToken, nil
}
// getAccessToken uses the credentials to get a new token from server
func (c *Client) getAccessToken() (string, error) {
v := url.Values{}
v.Add("grant_type", "password")
v.Add("scope", c.scope)
v.Add("username", c.username)
v.Add("password", c.password)
return c.doOAuth(v)
}
// refreshToken uses the existing refreshToken to refresh a token
func (c *Client) refreshToken() (string, error) {
// if there's no refreshtoken we will get the access token again
if c.credential.refreshToken == "" {
return c.getAccessToken()
}
v := url.Values{}
v.Add("grant_type", "refresh_token")
v.Add("scope", c.scope)
v.Add("refresh_token", c.credential.refreshToken)
return c.doOAuth(v)
}
// token returns an access token, which such token will be refreshed if it has expired, or it will be
// asked for authorization if there's no access token at all
func (c *Client) token() (string, error) {
if c.credential.accessToken != "" {
// have access token; expiration unknown
if c.credential.accessTokenExpiresAt.After(time.Now()) {
// have access token && not expired
return c.credential.accessToken, nil
} else {
// have access token && expired
return c.refreshToken()
}
} else {
// dont have access token
return c.getAccessToken()
}
}
// request sends request with token
func (c *Client) request(r *http.Request) ([]byte, error) {
token, err := c.token()
if err != nil {
return nil, err
}
r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
response, err := client.Do(r)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK &&
response.StatusCode != http.StatusNoContent {
i, _ := ioutil.ReadAll(response.Body)
return nil, fmt.Errorf("request error: %d, %v", response.StatusCode, string(i))
}
b, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("read response failed:%v", err)
}
return b, nil
}
func (c *Client) getFileFromAPI(fileID string, opts Opts) ([]byte, error) {
u := path.Join("/files", fileID, "sheets/values")
u = fmt.Sprintf("%s%s?range=%s!A1:%s%d", Endpoint, u, url.PathEscape(opts.SheetName), opts.EndCol, opts.EndRow)
request, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
resp, err := c.request(request)
if err != nil {
return nil, err
}
return transform.Transform(resp, opts.HeaderSuffix)
}
func (c *Client) UpdateFileFromAPI(fileID string, opts WriteOpts) error {
return c.writeFileFromAPI("POST", fileID, opts)
}
func (c *Client) AppendFileFromAPI(fileID string, opts WriteOpts) error {
return c.writeFileFromAPI("PUT", fileID, opts)
}
func (c *Client) writeFileFromAPI(method string, fileID string, opts WriteOpts) error {
u := path.Join("/files", fileID, "sheets/values")
u = fmt.Sprintf("%s%s", Endpoint, u)
jsonStr, err := json.Marshal(opts)
if err != nil {
return err
}
request, err := http.NewRequest(method, u, bytes.NewReader(jsonStr))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
_, err = c.request(request)
if err != nil {
return err
}
return nil
}
func (c *Client) receiveSign() {
for sign := range c.asyncSign {
c.updateHandle(sign.FileID, sign.Opts)
}
}
func (c *Client) updateHandle(fileID string, opts Opts) error {
c.l.RLock()
cache, ok := c.cache[fileID]
c.l.RUnlock()
if ok &&
cache.expire.After(time.Now()) &&
opts.SheetName == cache.SheetName &&
opts.EndRow == cache.EndRow &&
opts.EndCol == cache.EndCol &&
opts.HeaderSuffix == cache.HeaderSuffix {
fmt.Println("updateHandle repeat")
return nil
}
_, err := c.updateOrCreateCache(fileID, opts)
return err
}
func (c *Client) updateOrCreateCache(fileID string, opts Opts) (*Cache, error) {
r, err := c.getFileFromAPI(fileID, opts)
if err != nil {
return nil, err
}
cache := &Cache{
expire: time.Now().Add(opts.CacheTTL),
Opts: opts,
result: r,
}
c.l.Lock()
defer c.l.Unlock()
c.cache[fileID] = cache
return cache, nil
}
// GetFileWithOpts gets a file from shimo.im with the specified fileID and Opts. It returns the response io.Reader which can be used to stream responses. The one using this method SHOULD cache the file content response from this method due to the limitation of shimo.im's API.
func (c *Client) GetFileWithOpts(fileID string, opts Opts) ([]byte, error) {
c.l.RLock()
cache, ok := c.cache[fileID]
c.l.RUnlock()
if !ok {
cache, err := c.updateOrCreateCache(fileID, opts)
if err != nil {
return nil, err
}
return cache.result, nil
}
if cache.expire.After(time.Now()) &&
opts.SheetName == cache.SheetName &&
opts.EndRow == cache.EndRow &&
opts.EndCol == cache.EndCol &&
opts.HeaderSuffix == cache.HeaderSuffix {
return cache.result, nil
}
select {
case c.asyncSign <- sign{FileID: fileID, Opts: opts}:
case <-time.After(time.Millisecond * 10):
fmt.Println("send async update sign timeout")
}
return cache.result, nil
}
func (c *Client) Close() {
close(c.asyncSign)
}