This repository has been archived by the owner on Oct 28, 2020. It is now read-only.
/
client.go
341 lines (307 loc) · 9.45 KB
/
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
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
335
336
337
338
339
340
341
package intra
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"reflect"
"regexp"
"strconv"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
func ClientCredentialsTokenSource(ctx context.Context, uid, secret string, scopes ...string) oauth2.TokenSource {
c := clientcredentials.Config{
ClientID: uid,
ClientSecret: secret,
TokenURL: "https://api.intra.42.fr/oauth/token",
Scopes: scopes,
}
return c.TokenSource(ctx)
}
type Helper struct {
*http.Client
}
func Client(ctx context.Context, toksource oauth2.TokenSource) *Helper {
return &Helper{
Client: oauth2.NewClient(ctx, toksource),
}
}
// GetJSON returns a http.Response with a closed body, the body having been json-unmarshaled into v.
// Method should be something along the lines of "/v2/me".
func (h *Helper) getJSON(ctx context.Context, uri *url.URL, httpMethod string, v interface{}) (*http.Response, error) {
uri.Scheme = "https"
uri.Host = "api.intra.42.fr"
req, err := http.NewRequest(httpMethod, uri.String(), nil)
if err != nil {
return nil, errors.Wrapf(err, "intra: bad request URI [%s]", uri.RequestURI())
}
fmt.Fprintln(os.Stderr, "intra: doing GET", req.URL.String())
req = req.WithContext(ctx)
resp, err := h.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "intra: failed GET %s", uri.RequestURI())
}
if resp.StatusCode == 401 {
resp, err = h.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "intra: failed GET %s", uri.RequestURI())
}
}
bytes, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, errors.Wrapf(err, "intra: failed read for GET %s", uri.RequestURI())
}
err = json.Unmarshal(bytes, v)
resp.Body.Close()
if err != nil {
return nil, errors.Wrapf(err, "intra: failed json decode for GET %s, %s", uri.RequestURI(), string(bytes))
}
return resp, err
}
func (h *Helper) DoGetFormJSON(ctx context.Context, path string, params url.Values, v interface{}) (*http.Response, error) {
reqURI, httpMethod, err := methodFormToFinalURL(path, params)
if err != nil {
return nil, err
}
return h.getJSON(ctx, reqURI, httpMethod, v)
}
type PaginatedSingleResult struct {
OK bool
Error error
Value interface{}
}
// PaginatedGet loads all pages of Intra's response to the given query.
// Entries in params are overridden by query parameters contained in `method`.
// receiverType should be a pointer to the type of values you want in the result channel, but will not actually be used to store the result.
//
// Any errors encountered will be the last value sent over the returned channel, and the returned channel will always be closed once all results have been sent.
func (h *Helper) PaginatedGet(ctx context.Context, method string, _form url.Values, receiverType interface{}) <-chan PaginatedSingleResult {
uri, form, err := methodFormToUriForm(method, _form)
if err != nil {
ch := make(chan PaginatedSingleResult, 1)
ch <- PaginatedSingleResult{OK: false, Error: err}
close(ch)
return ch
}
httpMethod := "GET"
if form.Get("_method") != "" {
httpMethod = form.Get("_method")
form.Del("_method")
}
typ := reflect.TypeOf(receiverType)
pointedToType := typ.Elem()
resultCh := make(chan PaginatedSingleResult)
go func() {
defer func(ch chan PaginatedSingleResult) {
close(ch)
}(resultCh)
defer func() {
if rErr := recover(); rErr != nil {
var qErr error
if err, ok := rErr.(error); ok {
qErr = err
} else {
qErr = errors.Errorf("Panic: %v", rErr)
}
fmt.Fprintln(os.Stderr, qErr)
resultCh <- PaginatedSingleResult{OK: false, Error: qErr}
}
}()
for page := 1; ; page++ {
form.Set("page", strconv.Itoa(page))
uri.RawQuery = form.Encode()
aryPtr := reflect.New(reflect.SliceOf(pointedToType))
resp, err := h.getJSON(ctx, uri, httpMethod, aryPtr.Interface())
if err != nil {
resultCh <- PaginatedSingleResult{OK: false, Error: errors.Wrapf(err, "intra GET %s", uri.RequestURI())}
return
}
ary := aryPtr.Elem()
l := ary.Len()
for i := 0; i < l; i++ {
resultCh <- PaginatedSingleResult{
OK: true,
Value: ary.Index(i).Addr().Interface(),
}
continue
}
h := resp.Header
perPage, err := strconv.Atoi(h.Get("X-Per-Page"))
if err != nil {
resultCh <- PaginatedSingleResult{OK: false, Error: errors.Errorf("intra GET %s: X-Per-Page not a number", uri.RequestURI())}
return
}
total, err := strconv.Atoi(h.Get("X-Total"))
if err != nil {
resultCh <- PaginatedSingleResult{OK: false, Error: errors.Errorf("intra GET %s: X-Per-Page not a number", uri.RequestURI())}
return
}
if page*perPage > total {
// All done!
return
}
select {
case <-ctx.Done(): // cancelled
resultCh <- PaginatedSingleResult{Error: ctx.Err(), OK: false}
return
default:
// page++, loop
}
}
}()
return resultCh
}
// PaginatedGet loads all pages of Intra's response to the given query.
// Entries in params are overridden by query parameters contained in `method`.
// receiverType should be a pointer to the type of values you want in the result channel, but will not actually be used to store the result.
//
// Any errors encountered will be the last value sent over the returned channel, and the returned channel will always be closed once all results have been sent.
//
// This works for endpoints that return data as {"data": [...], "links": {...}} .
func (h *Helper) PaginatedGetLinkStyle(ctx context.Context, method string, _form url.Values, receiverType interface{}) <-chan PaginatedSingleResult {
uri, form, err := methodFormToUriForm(method, _form)
if err != nil {
ch := make(chan PaginatedSingleResult, 1)
ch <- PaginatedSingleResult{OK: false, Error: err}
close(ch)
return ch
}
httpMethod := "GET"
if form.Get("_method") != "" {
httpMethod = form.Get("_method")
form.Del("_method")
}
typ := reflect.TypeOf(receiverType)
pointedToType := typ.Elem()
resultCh := make(chan PaginatedSingleResult)
go func() {
defer func(ch chan PaginatedSingleResult) {
close(ch)
}(resultCh)
defer func() {
if rErr := recover(); rErr != nil {
var qErr error
if err, ok := rErr.(error); ok {
qErr = err
} else {
qErr = errors.Errorf("Panic: %v", rErr)
}
fmt.Fprintln(os.Stderr, qErr)
resultCh <- PaginatedSingleResult{OK: false, Error: qErr}
}
}()
var decode struct {
Data json.RawMessage
Links struct {
Self string
Next string
Last string
}
}
for page := 1; ; page++ {
form.Set("page", strconv.Itoa(page))
uri.RawQuery = form.Encode()
resp, err := h.getJSON(ctx, uri, httpMethod, &decode)
if err != nil {
resultCh <- PaginatedSingleResult{OK: false, Error: errors.Wrapf(err, "intra GET %s", uri.RequestURI())}
return
}
aryPtr := reflect.New(reflect.SliceOf(pointedToType))
err = json.Unmarshal([]byte(decode.Data), aryPtr.Interface())
if err != nil {
resultCh <- PaginatedSingleResult{OK: false, Error: errors.Wrapf(err, "json unmarshal %s", string(decode.Data))}
return
}
ary := aryPtr.Elem()
l := ary.Len()
for i := 0; i < l; i++ {
resultCh <- PaginatedSingleResult{
OK: true,
Value: ary.Index(i).Addr().Interface(),
}
continue
}
h := resp.Header
perPage, err := strconv.Atoi(h.Get("X-Per-Page"))
if err != nil {
resultCh <- PaginatedSingleResult{OK: false, Error: errors.Errorf("intra GET %s: X-Per-Page not a number", uri.RequestURI())}
return
}
total, err := strconv.Atoi(h.Get("X-Total"))
if err != nil {
resultCh <- PaginatedSingleResult{OK: false, Error: errors.Errorf("intra GET %s: X-Per-Page not a number", uri.RequestURI())}
return
}
if page*perPage > total {
// All done!
return
}
select {
case <-ctx.Done(): // cancelled
resultCh <- PaginatedSingleResult{Error: ctx.Err(), OK: false}
return
default:
// page++, loop
}
}
}()
return resultCh
}
const luahelp = `
intra.campus.paris = 1
intra.campus.fremont = 7
intra.project.get_next_line.id
`
type errUrlFormMissing struct{ ParamName string }
func (e errUrlFormMissing) Error() string {
return fmt.Sprintf("missing mandatory URL parameter: %s", e.ParamName)
}
var rgxUrlParam = regexp.MustCompile(`:([a-zA-Z_]+)`)
func subPathPlaceholders(path string, params url.Values) (string, error) {
var m = rgxUrlParam.FindStringIndex(path)
for ; m != nil; m = rgxUrlParam.FindStringIndex(path) {
paramName := path[m[0]+1 : m[1]]
if params.Get(paramName) == "" {
return "", errUrlFormMissing{ParamName: paramName}
}
path = path[0:m[0]] + params.Get(paramName) + path[m[1]:]
params.Del(paramName)
}
return path, nil
}
func methodFormToUriForm(method string, form url.Values) (*url.URL, url.Values, error) {
uri, err := url.Parse(fmt.Sprintf("https://api.intra.42.fr%s", method))
if err != nil {
return nil, nil, errors.Wrap(err, "intra: bad request URI")
}
uri.Path, err = subPathPlaceholders(uri.Path, form)
if err != nil {
return nil, nil, errors.Wrap(err, "intra: bad request URI")
}
for k, v := range uri.Query() {
form[k] = v
}
return uri, form, nil
}
func methodFormToFinalURL(method string, form url.Values) (*url.URL, string, error) {
uri, f, err := methodFormToUriForm(method, form)
if err != nil {
return nil, "", err
}
httpMethod := "GET"
if form.Get("_method") != "" {
httpMethod = form.Get("_method")
form.Del("_method")
}
uri.RawQuery = f.Encode()
return uri, httpMethod, nil
}