This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
generated from beyondstorage/go-service-example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils_drives.go
331 lines (269 loc) · 8.34 KB
/
utils_drives.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
package onedrive
// the refactor of github.com/goh-chunlin/go-onedrive/onedrive upper layer functions since its internal implementation does not meet our needs.
// 1. refactor all URL to support path(instead of item id).
// 2. basic onedrive item struct, add we needed information like etag and so on.
// 3. refactor list to support pagination.
// 4. refactor write/read function with io.reader.
// 5. add new upload functions with `upload session`.
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/goh-chunlin/go-onedrive/onedrive"
)
const MB = 1024 * 1024
const OneTimeUploadedSizeLimit = int64(60 * MB)
type onedriveClient struct {
client *onedrive.Client
}
// Item is the basic definition of onedrive item.
type Item struct {
ID string `json:"id"`
Name string `json:"name"`
Etag string `json:"eTag"`
LastModifiedDateTime time.Time `json:"lastModifiedDateTime"`
DownloadURL string `json:"@microsoft.graph.downloadUrl"`
Size int64 `json:"size"`
CreatedBy CreatedBy `json:"createdBy"`
File *onedrive.DriveItemFile `json:"file"`
Folder *onedrive.DriveItemFolder `json:"folder"`
}
type CreatedBy struct {
User onedrive.User `json:"user"`
}
type ItemList struct {
ODataContext string `json:"@odata.context"`
Count int `json:"@odata.count"`
NextLink string `json:"@odata.nextLink"`
Items []*Item `json:"value"`
}
// GetItem gets item from onedrive.
func (o *onedriveClient) GetItem(ctx context.Context, absPath string) (*Item, error) {
if !path.IsAbs(absPath) {
return nil, errors.New(fmt.Sprintf("%s not an absolute path", absPath))
}
var apiURL string
if isRoot(absPath) {
apiURL = "me/drive/root"
} else {
apiURL = "me/drive/root:" + url.PathEscape(absPath)
}
req, err := o.client.NewRequest("GET", apiURL, nil)
if err != nil {
return nil, err
}
var driveItem *Item
err = o.client.Do(ctx, req, false, &driveItem)
if err != nil {
return nil, err
}
return driveItem, nil
}
// DownloadItem download onedrive item from download url.
func (o *onedriveClient) DownloadItem(ctx context.Context, absPath string) (rc io.ReadCloser, n int64, err error) {
i, err := o.GetItem(ctx, absPath)
if err != nil {
return
}
var body io.Reader
req, err := http.NewRequestWithContext(ctx, "GET", i.DownloadURL, body)
if err != nil {
return
}
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return
}
if resp.StatusCode != 200 && resp.StatusCode != 201 {
errContent, _ := ioutil.ReadAll(resp.Body)
err = fmt.Errorf("upload resource failed, cause %s:%s", resp.Status, string(errContent))
return
}
return resp.Body, i.Size, nil
}
// DeleteItem delete an item from one drive.
func (o *onedriveClient) DeleteItem(ctx context.Context, absPath string) error {
if !path.IsAbs(absPath) {
return errors.New("not an absoulute path")
}
var apiURL string
if isRoot(absPath) {
apiURL = "me/drive/root"
} else {
apiURL = "me/drive/root:" + url.PathEscape(absPath)
}
req, err := o.client.NewRequest("DELETE", apiURL, nil)
if err != nil {
return err
}
err = o.client.Do(ctx, req, false, nil)
if err != nil {
return err
}
return err
}
type CreateUploadSessionRequest struct {
ConflictBehavior string `json:"@microsoft.graph.conflictBehavior"`
FileSize int64 `json:"fileSize"`
Description string `json:"description"`
}
type CreateUploadSessionResponse struct {
UploadURL string `json:"uploadUrl"`
}
// createUploadSession create an upload session
// ref: https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession#create-an-upload-session
func (o *onedriveClient) createUploadSession(ctx context.Context, absPath string, size int64, description string) (uploadUrl string, err error) {
reqBody := CreateUploadSessionRequest{
ConflictBehavior: "replace",
FileSize: size,
Description: description,
}
apiURL := "me/drive/root:" + url.PathEscape(absPath) + ":/createUploadSession"
req, err := o.client.NewRequest("POST", apiURL, reqBody)
if err != nil {
return
}
var response *CreateUploadSessionResponse
err = o.client.Do(ctx, req, false, &response)
if err != nil {
return
}
uploadUrl = response.UploadURL
return
}
// cancelUploadSession cancel an upload session.
// ref: https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession#cancel-the-upload-session
func (o *onedriveClient) cancelUploadSession(ctx context.Context, uploadUrl string) error {
req, err := http.NewRequest("DELETE", uploadUrl, nil)
if err != nil {
return err
}
err = o.client.Do(ctx, req, false, nil)
return err
}
// Upload uploads file in multipart(each within 60MB).
// ref: https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession#upload-bytes-to-the-upload-session
func (o *onedriveClient) Upload(ctx context.Context, absPath string, fileSize int64, r io.Reader, description string) (n int64, err error) {
if !path.IsAbs(absPath) {
return 0, errors.New("please provide the abspath")
}
// get onedrive upload url
uploadUrl, err := o.createUploadSession(ctx, absPath, fileSize, description)
if err != nil {
return
}
defer func() {
if err != nil {
// cancel current upload session when error occurred
_ = o.cancelUploadSession(ctx, uploadUrl)
}
}()
// init upload size
// max 60MB one time
oneTimeUploadedSize := OneTimeUploadedSizeLimit
if fileSize < oneTimeUploadedSize {
oneTimeUploadedSize = fileSize
}
for n < fileSize {
// upload segment
// make minimum needed length, avoid memory waste
segment := make([]byte, minInt64(oneTimeUploadedSize, fileSize-n))
nowSize, err := r.Read(segment)
if err != nil && err != io.EOF {
return n, err
}
bn := bytes.NewReader(segment)
req, err := http.NewRequestWithContext(ctx, "PUT", uploadUrl, bn)
if err != nil {
return n, err
}
req.Header.Add("Content-Length", strconv.Itoa(nowSize))
req.Header.Add("Content-Range", fmt.Sprintf("bytes %d-%d/%d", n, n+int64(nowSize)-1, fileSize))
// needn't authentication, so use plain http client
// ref: https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession#remarks
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return n, err
}
if res.StatusCode != 202 && res.StatusCode != 201 && res.StatusCode != 200 {
errContent, _ := ioutil.ReadAll(res.Body)
err = fmt.Errorf("upload resource failed, cause %s:%s", res.Status, string(errContent))
return n, err
}
// close body
res.Body.Close()
n += int64(nowSize)
}
return
}
// List list items based of the absPath, with skipToken opts.
// ref: https://docs.microsoft.com/en-us/graph/api/driveitem-list-children
// https://docs.microsoft.com/en-us/graph/query-parameters
func (o *onedriveClient) List(ctx context.Context, absPath string, skipToken string, limit uint32) (items []*Item, nextSkipToken string, err error) {
if !path.IsAbs(absPath) {
err = errors.New("please provide the abspath")
return
}
var apiURL string
if isRoot(absPath) {
apiURL = fmt.Sprintf("me/drive/root/children?$top=%d&$skiptoken=%s", limit, skipToken)
} else {
apiURL = fmt.Sprintf("me/drive/root:%s:/children?$top=%d&$skiptoken=%s", url.PathEscape(absPath), limit, skipToken)
}
req, err := o.client.NewRequest("GET", apiURL, nil)
if err != nil {
return
}
var response ItemList
err = o.client.Do(ctx, req, false, &response)
if err != nil {
return
}
if response.NextLink != "" {
index := strings.Index(response.NextLink, "skiptoken")
if index != -1 && index+9 < len(response.NextLink) {
// parse skiptoken=xxx
nextSkipToken = response.NextLink[index+9:]
}
}
items = response.Items
return
}
func isRoot(path string) bool {
if filepath.Join("/", path) == "/" {
return true
}
return false
}
// isFile judge file type(file)
func isFile(item *Item) bool {
if item.File != nil {
return true
}
return false
}
func minInt64(a, b int64) int64 {
if a < b {
return a
}
return b
}
// isNotFoundError check onedrive error whether is itemNotFound
func isNotFoundError(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), "itemNotFound")
}