-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
208 lines (174 loc) · 4.32 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
package kDrive
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strconv"
"time"
)
const (
apiURL = "https://api.infomaniak.com/"
apiVersion = "2"
kDriveVersion = "2022-06-28"
maxRetries = 3
)
type Token string
func (it Token) String() string {
return string(it)
}
type DriveId string
func (it DriveId) String() string {
return string(it)
}
// ClientOption to configure API client
type ClientOption func(*Client)
type Client struct {
httpClient *http.Client
baseUrl *url.URL
apiVersion string
kDriveVersion string
driveId DriveId
maxRetries int
Token Token
Activity ActivityService
//Files FilesService
//HtmlPage HtmlPageService
//Invitations InvitationsService
//SharedLink SharedLinkService
//Settings SettingsService
//Statistics StatisticsService
//Users UsersService
}
func NewClient(token Token, opts ...ClientOption) *Client {
u, err := url.Parse(apiURL)
if err != nil {
panic(err)
}
c := &Client{
httpClient: http.DefaultClient,
Token: token,
baseUrl: u,
apiVersion: apiVersion,
kDriveVersion: kDriveVersion,
maxRetries: maxRetries,
}
c.Activity = &ActivityClient{apiClient: c}
//c.Files = &FilesClient{apiClient: c}
//c.HtmlPage = &HtmlPageClient{apiClient: c}
//c.Invitations = &InvitationsClient{apiClient: c}
//c.SharedLink = &SharedLinkClient{apiClient: c}
//c.Settings = &SettingsClient{apiClient: c}
//c.Statistics = &StatisticsClient{apiClient: c}
//c.Users = &UsersClient{apiClient: c}
for _, opt := range opts {
opt(c)
}
return c
}
// WithHTTPClient overrides the default http.Client
func WithHTTPClient(client *http.Client) ClientOption {
return func(c *Client) {
c.httpClient = client
}
}
// WithVersion overrides the kDrive API version
func WithVersion(version string) ClientOption {
return func(c *Client) {
c.kDriveVersion = version
}
}
// WithRetry overrides the default number of max retry attempts on 429 errors
func WithRetry(retries int) ClientOption {
return func(c *Client) {
c.maxRetries = retries
}
}
func (c *Client) request(ctx context.Context, method string, urlStr string, queryParams map[string]string, requestBody interface{}) (*http.Response, error) {
u, err := c.baseUrl.Parse(fmt.Sprintf("%s/%s", c.apiVersion, urlStr))
if err != nil {
return nil, err
}
var buf io.ReadWriter
if requestBody != nil && !reflect.ValueOf(requestBody).IsNil() {
body, err := json.Marshal(requestBody)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(body)
}
if len(queryParams) > 0 {
q := u.Query()
for k, v := range queryParams {
q.Add(k, v)
}
u.RawQuery = q.Encode()
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token.String()))
req.Header.Add("kDrive-Version", c.kDriveVersion)
req.Header.Add("Content-Type", "application/json")
failedAttempts := 0
var res *http.Response
for {
var err error
res, err = c.httpClient.Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusTooManyRequests {
break
}
failedAttempts++
if failedAttempts == c.maxRetries {
return nil, &RateLimitedError{Message: fmt.Sprintf("Retry request with 429 response failed after %d retries", failedAttempts)}
}
retryAfterHeader := res.Header["Retry-After"]
if len(retryAfterHeader) == 0 {
return nil, &RateLimitedError{Message: "Retry-After header missing from kDrive API response headers for 429 response"}
}
retryAfter := retryAfterHeader[0]
waitSeconds, err := strconv.Atoi(retryAfter)
if err != nil {
break // should not happen
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(time.Duration(waitSeconds) * time.Second):
}
}
if res.StatusCode != http.StatusOK {
var apiErr Error
err = json.NewDecoder(res.Body).Decode(&apiErr)
if err != nil {
return nil, err
}
return nil, &apiErr
}
return res, nil
}
type Pagination struct {
StartCursor Cursor
PageSize int
}
func (p *Pagination) ToQuery() map[string]string {
if p == nil {
return nil
}
r := map[string]string{}
if p.StartCursor != "" {
r["start_cursor"] = p.StartCursor.String()
}
if p.PageSize != 0 {
r["page_size"] = strconv.Itoa(p.PageSize)
}
return r
}