-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
268 lines (235 loc) · 7.99 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
package ydfs
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
const (
// base URL
urlBase string = "https://cloud-api.yandex.net/v1/disk"
// URLs for resource manipulations
urlResources = urlBase + "/resources" // get resources metainfo
urlResourcesDownload = urlResources + "/download" // download resources
urlResourcesUpload = urlResources + "/upload" // upload resources
urlResourcesPublish = urlResources + "/publish" // publish resources
urlResourcesCopy = urlResources + "/copy" // copy resources
urlResourcesMove = urlResources + "/move" // move resources
urlResourcesFiles = urlResources + "/files" // list files sorted alphabetically
urlResourcesLastUploaded = urlResources + "/last-uploaded" // list files by upload date
urlResourcesPublic = urlResources + "/public" // list published files
// URLs for manipulations with public resources
urlPublicResources = urlBase + "/public/resources"
urlPublicResourcesDownload = urlPublicResources + "/download"
urlPublicResourcesSaveToDisk = urlPublicResources + "/save-to-disk"
// URLs for manipulations with trashed resources
urlTrashResources = urlBase + "/trash/resources"
urlTrashResourcesRestore = urlTrashResources + "/restore"
// Async operations status
urlOperations = urlBase + "/operations"
)
var minimalFields = []string{"name", "path", "type", "size", "modified"}
var (
ErrNetwork = errors.New("network error")
ErrAPI = errors.New("API error")
ErrNotFound = errors.New("resource not found")
ErrUnknown = errors.New("unknown error")
ErrInternal = errors.New("internal error")
)
type apiclient struct {
header http.Header
client *http.Client
}
// newApiClient createst Yandex Disk API client, which uses
// the provided http.Client.
func newApiClient(token string, c *http.Client) *apiclient {
h := make(http.Header)
h.Add("Authorization", "OAuth "+token)
h.Add("Accept", "application/json")
h.Add("Content-Type", "application/json")
return &apiclient{header: h, client: c}
}
// processes request returns response body bytes and error
// if we're getting status not equal to the requiredcode the method tries to unmarshal
// response to errAPI struct which imlements error interface.
func (c *apiclient) do(ctx context.Context, r *http.Request, requiredcode int) ([]byte, error) {
r.Header = c.header
var (
resp *http.Response
err error
data []byte
)
if ctx != nil {
r = r.WithContext(ctx)
}
resp, err = c.client.Do(r)
if err != nil {
return []byte{}, fmt.Errorf("%w: %v", ErrNetwork, err)
}
defer resp.Body.Close()
data, err = io.ReadAll(resp.Body)
if err != nil {
return []byte{}, fmt.Errorf("%w: %v", ErrNetwork, err)
}
// checking if we've got correct result code
if resp.StatusCode != requiredcode {
var e errAPI
if err = json.Unmarshal(data, &e); err != nil {
return []byte{}, fmt.Errorf("%w: unknown response with code %d from API: %s", ErrUnknown, resp.StatusCode, string(data))
}
if e.NotFound() {
err = fmt.Errorf("%w, %v", ErrNotFound, e)
} else {
err = fmt.Errorf("%w, %v", ErrAPI, e)
}
return []byte{}, err
}
return data, nil
}
// requestInterface performs some of the weight lifting with API. If result argument it non-nil
// then the method tries to unmarshal response into the passed interface.
// If no body is expected in response or the body needs to be thrown away,
// result must be nil.
func (c *apiclient) requestInterface(method string, respcode int, url string, body io.Reader, result interface{}) (err error) {
var (
r *http.Request
data []byte
)
r, err = http.NewRequest(method, url, body)
if err != nil {
return
}
if data, err = c.do(context.TODO(), r, respcode); err != nil {
return
}
// If nil result argument is passed, we don't want
// the resp body unmarshalled. returning.
if result == nil {
return
}
// If non-nil result argument is passed we'll try to
// unmarshal resp body into the interface provided.
if err = json.Unmarshal(data, &result); err != nil {
err = fmt.Errorf("%w: %v", ErrInternal, err)
}
return
}
// getDiskInfo fetches information about user's Disk.
func (c *apiclient) getDiskInfo() (info diskInfo, err error) {
err = c.requestInterface(http.MethodGet, http.StatusOK, urlBase, nil, &info)
return
}
// getFile fetches single file bytes.
func (c *apiclient) getFile(name string) ([]byte, error) {
// first we need to fetch the download url
v := make(url.Values)
v.Add("path", name)
url, _ := url.Parse(urlResourcesDownload)
url.RawQuery = v.Encode()
var l = &link{}
if err := c.requestInterface(http.MethodGet, http.StatusOK, url.String(), nil, l); err != nil {
return []byte{}, err
}
if l.Templated {
// TODO: deal with templated links (I haven't seen one yet)
}
// performing the actual download
r, err := http.NewRequest(l.Method, l.Href, nil)
if err != nil {
return []byte{}, fmt.Errorf("%w: %v", ErrInternal, err)
}
return c.do(context.TODO(), r, http.StatusOK)
}
func (c *apiclient) putFile(name string, overwrite bool, data []byte) error {
v := make(url.Values)
v.Add("path", name)
if overwrite {
v.Add("overwrite", "true")
}
url, _ := url.Parse(urlResourcesUpload)
url.RawQuery = v.Encode()
var l = &link{}
if err := c.requestInterface(http.MethodGet, http.StatusOK, url.String(), nil, l); err != nil {
return err
}
if l.Templated {
// TODO: deal with templated links (I haven't seen one yet)
}
// performing the actual upload
r, err := http.NewRequest(l.Method, l.Href, bytes.NewReader(data))
if err != nil {
return fmt.Errorf("%w: %v", ErrInternal, err)
}
_, err = c.do(context.TODO(), r, http.StatusCreated)
return err
}
func (c *apiclient) putFileTruncate(name string, data []byte) error {
return c.putFile(name, true, data)
}
func (c *apiclient) putFileNoTruncate(name string, data []byte) error {
return c.putFile(name, false, data)
}
func (c *apiclient) mkdir(name string) error {
v := make(url.Values)
v.Add("path", name)
url, _ := url.Parse(urlResources)
url.RawQuery = v.Encode()
var l = link{}
return c.requestInterface(http.MethodPut, http.StatusCreated, url.String(), nil, &l)
}
// getResource fetches Resource identified by name from the API.
// if limit == 0 then embedded resources will not be requested not included
// if limit > 0 then len(Resource.Embedded.Items) will not exceed limit.
func (c *apiclient) getResource(name string, limit int, fields ...string) (r resource, err error) {
v := make(url.Values)
v.Add("path", name)
v.Add("limit", strconv.Itoa(limit))
if len(fields) > 0 {
v.Add("fields", strings.Join(fields, ","))
}
url, _ := url.Parse(urlResources)
url.RawQuery = v.Encode()
fmt.Printf("URL: %s\n", url)
err = c.requestInterface(http.MethodGet, http.StatusOK, url.String(), nil, &r)
return
}
// getResourceSingle fetches resource without embedded resources
func (c *apiclient) getResourceSingle(name string) (resource, error) {
return c.getResource(name, 0)
}
// getResourceMinTraffic fetches resource only requesting minimum
// required info for FS to function. minimalFields is globally declared.
func (c *apiclient) getResourceMinTraffic(name string) (resource, error) {
return c.getResource(name, 0, minimalFields...)
}
// getResourceWithEmbedded fetches resource with embedded resources
func (c *apiclient) getResourceWithEmbedded(name string) (resource, error) {
return c.getResource(name, (1<<31)-1)
}
func (c *apiclient) delResource(name string, permanently bool) error {
u, _ := url.Parse(urlResources)
v := make(url.Values)
v.Add("path", name)
if permanently {
v.Add("permanently", "true")
}
u.RawQuery = v.Encode()
r, err := http.NewRequest(http.MethodDelete, u.String(), nil)
if err != nil {
return err
}
_, err = c.do(context.TODO(), r, http.StatusNoContent)
return err
}
func (c *apiclient) delResourcePermanently(name string) error {
return c.delResource(name, true)
}
func (c *apiclient) delResourceTrash(name string) error {
return c.delResource(name, false)
}