This repository has been archived by the owner on Jul 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgdriver.go
601 lines (524 loc) · 15.5 KB
/
gdriver.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package gdriver
import (
"errors"
"fmt"
"io"
"net/http"
"path"
"strings"
drive "google.golang.org/api/drive/v3"
"google.golang.org/api/googleapi"
)
// GDriver can be used to access google drive in a traditional file-folder-path pattern
type GDriver struct {
srv *drive.Service
rootNode *FileInfo
}
// HashMethod is the hashing method to use for GetFileHash
type HashMethod int
const (
// HashMethodMD5 sets the method to MD5
HashMethodMD5 HashMethod = 0
)
const (
mimeTypeFolder = "application/vnd.google-apps.folder"
mimeTypeFile = "application/octet-stream"
)
var (
fileInfoFields []googleapi.Field
listFields []googleapi.Field
)
func init() {
fileInfoFields = []googleapi.Field{
"createdTime",
"id",
"mimeType",
"modifiedTime",
"name",
"size",
}
listFields = []googleapi.Field{
googleapi.Field(fmt.Sprintf("files(%s)", googleapi.CombineFields(fileInfoFields))),
}
}
// New creates a new Google Drive Driver, client must me an authenticated instance for google drive
func New(client *http.Client, opts ...Option) (*GDriver, error) {
driver := &GDriver{}
var err error
driver.srv, err = drive.New(client)
if err != nil {
return nil, fmt.Errorf("Unable to retrieve Drive client: %v", err)
}
if _, err = driver.SetRootDirectory(""); err != nil {
return nil, err
}
for _, opt := range opts {
if err = opt(driver); err != nil {
return nil, err
}
}
return driver, nil
}
// SetRootDirectory changes the working root directory
// use this if you want to do certian operations in a special directory
// path should always be the absolute real path
func (d *GDriver) SetRootDirectory(path string) (*FileInfo, error) {
rootNode, err := getRootNode(d.srv)
if err != nil {
return nil, fmt.Errorf("Unable to retrieve Drive root: %v", err)
}
file, err := d.getFile(rootNode, path, listFields...)
if err != nil {
return nil, err
}
if !file.IsDir() {
return nil, FileIsNotDirectoryError{Path: path}
}
d.rootNode = file
return file, nil
}
// Stat gives a FileInfo for a file or directory
func (d *GDriver) Stat(path string) (*FileInfo, error) {
return d.getFile(d.rootNode, path, listFields...)
}
// ListDirectory will get all contents of a directory, calling fileFunc with the collected file information
func (d *GDriver) ListDirectory(path string, fileFunc func(*FileInfo) error) error {
file, err := d.getFile(d.rootNode, path, "files(id,name,mimeType)")
if err != nil {
return err
}
if !file.IsDir() {
return FileIsNotDirectoryError{Path: path}
}
var pageToken string
for {
call := d.srv.Files.List().Q(fmt.Sprintf("'%s' in parents and trashed = false", file.item.Id)).Fields(append(listFields, "nextPageToken")...)
if pageToken != "" {
call = call.PageToken(pageToken)
}
descendants, err := call.Do()
if err != nil {
return err
}
if descendants == nil {
return fmt.Errorf("no file information present (in `%s')", path)
}
for i := 0; i < len(descendants.Files); i++ {
if err = fileFunc(&FileInfo{
item: descendants.Files[i],
parentPath: file.Path(),
}); err != nil {
return CallbackError{NestedError: err}
}
}
if pageToken = descendants.NextPageToken; pageToken == "" {
break
}
}
return nil
}
// MakeDirectory creates a directory for the specified path, it will create non existent directores automatically
//
// Examples:
// MakeDirectory("Pictures/Holidays") // will create Pictures and Holidays
func (d *GDriver) MakeDirectory(path string) (*FileInfo, error) {
return d.makeDirectoryByParts(strings.FieldsFunc(path, isPathSeperator))
}
func (d *GDriver) makeDirectoryByParts(pathParts []string) (*FileInfo, error) {
parentNode := d.rootNode
for i := 0; i < len(pathParts); i++ {
query := fmt.Sprintf("'%s' in parents and name='%s' and trashed = false", parentNode.item.Id, sanitizeName(pathParts[i]))
files, err := d.srv.Files.List().Q(query).Fields(listFields...).Do()
if err != nil {
return nil, err
}
if files == nil {
return nil, fmt.Errorf("no file information present (in `%s')", path.Join(pathParts[:i+1]...))
}
if len(files.Files) <= 0 {
// file not found => create directory
if !parentNode.IsDir() {
return nil, fmt.Errorf("unable to create directory in `%s': `%s' is not a directory", path.Join(pathParts[:i]...), parentNode.Name())
}
var createdDir *drive.File
createdDir, err = d.srv.Files.Create(&drive.File{
Name: sanitizeName(pathParts[i]),
MimeType: mimeTypeFolder,
Parents: []string{
parentNode.item.Id,
},
}).Fields(fileInfoFields...).Do()
if err != nil {
return nil, err
}
parentNode = &FileInfo{
item: createdDir,
parentPath: path.Join(pathParts[:i]...),
}
} else if len(files.Files) > 1 {
return nil, fmt.Errorf("multiple entries found for `%s'", path.Join(pathParts[:i+1]...))
} else { // if len(files.Files) == 1
parentNode = &FileInfo{
item: files.Files[0],
parentPath: path.Join(pathParts[:i]...),
}
}
}
return parentNode, nil
}
// DeleteDirectory will delete a directory and its descendants
func (d *GDriver) DeleteDirectory(path string) error {
file, err := d.getFile(d.rootNode, path, "files(id,mimeType)")
if err != nil {
return err
}
if !file.IsDir() {
return FileIsNotDirectoryError{Path: path}
}
if file == d.rootNode {
return errors.New("root cannot be deleted")
}
return d.srv.Files.Delete(file.item.Id).Do()
}
// Delete will delete a file or directory, if directory it will also delete its descendants
func (d *GDriver) Delete(path string) error {
file, err := d.getFile(d.rootNode, path)
if err != nil {
return err
}
if file == d.rootNode {
return errors.New("root cannot be deleted")
}
return d.srv.Files.Delete(file.item.Id).Do()
}
// GetFile gets a file and returns a ReadCloser that can consume the body of the file
func (d *GDriver) GetFile(path string) (*FileInfo, io.ReadCloser, error) {
file, err := d.getFile(d.rootNode, path, listFields...)
if err != nil {
return nil, nil, err
}
if file.IsDir() {
return nil, nil, FileIsDirectoryError{Path: path}
}
response, err := d.srv.Files.Get(file.item.Id).Download()
if err != nil {
return nil, nil, err
}
return file, response.Body, nil
}
// GetFileHash returns the hash of a file with the present method
func (d *GDriver) GetFileHash(path string, method HashMethod) (*FileInfo, []byte, error) {
switch method {
case HashMethodMD5:
default:
return nil, nil, fmt.Errorf("Unknown method %d", method)
}
file, err := d.getFile(d.rootNode, path, "files(id, md5Checksum)")
if err != nil {
return nil, nil, err
}
if file.IsDir() {
return nil, nil, FileIsDirectoryError{Path: path}
}
return file, []byte(file.item.Md5Checksum), nil
}
// PutFile uploads a file to the specified path
// it creates non existing directories
func (d *GDriver) PutFile(filePath string, r io.Reader) (*FileInfo, error) {
pathParts := strings.FieldsFunc(filePath, isPathSeperator)
amountOfParts := len(pathParts)
if amountOfParts <= 0 {
return nil, errors.New("path cannot be empty")
}
// check if there is already a file
existentFile, err := d.getFileByParts(d.rootNode, pathParts, listFields...)
if err != nil {
if !IsNotExist(err) {
return nil, err
}
existentFile = nil
}
if existentFile == d.rootNode {
return nil, errors.New("root cannot be uploaded")
}
// we found a file, just update this file
if existentFile != nil {
if err = d.updateFileContents(existentFile.item.Id, r); err != nil {
return nil, err
}
return existentFile, nil
}
// create a new file
parentNode := d.rootNode
if amountOfParts > 1 {
dir, err := d.makeDirectoryByParts(pathParts[:amountOfParts-1])
if err != nil {
return nil, err
}
parentNode = dir
if !parentNode.IsDir() {
return nil, fmt.Errorf("unable to create file in `%s': `%s' is not a directory", path.Join(pathParts[:amountOfParts-1]...), parentNode.Name())
}
}
file, err := d.srv.Files.Create(
&drive.File{
Name: sanitizeName(pathParts[amountOfParts-1]),
MimeType: mimeTypeFile,
Parents: []string{
parentNode.item.Id,
},
},
).Fields(fileInfoFields...).Media(r).Do()
if err != nil {
return nil, err
}
return &FileInfo{
item: file,
parentPath: path.Join(pathParts[:amountOfParts-1]...),
}, nil
}
func (d *GDriver) updateFileContents(id string, r io.Reader) error {
// update file
_, err := d.srv.Files.Update(id, nil).Fields(fileInfoFields...).Media(r).Do()
if err != nil {
return err
}
return nil
}
// Rename renames a file or directory to a new name in the same folder
func (d *GDriver) Rename(path string, newName string) (*FileInfo, error) {
newNameParts := strings.FieldsFunc(newName, isPathSeperator)
amountOfParts := len(newNameParts)
if amountOfParts <= 0 {
return nil, errors.New("new name cannot be empty")
}
file, err := d.getFile(d.rootNode, path)
if err != nil {
return nil, err
}
if file == d.rootNode {
return nil, errors.New("root cannot be renamed")
}
newFile, err := d.srv.Files.Update(file.item.Id, &drive.File{
Name: sanitizeName(newNameParts[amountOfParts-1]),
}).Fields(fileInfoFields...).Do()
return &FileInfo{
item: newFile,
parentPath: file.parentPath,
}, nil
}
// Move moves a file or directory to a new path, note that move also renames the target if necessary and creates non existing directories
//
// Examples:
// Move("Folder1/File1", "Folder2/File2") // File1 in Folder1 will be moved to Folder2/File2
// Move("Folder1/File1", "Folder2/File1") // File1 in Folder1 will be moved to Folder2/File1
func (d *GDriver) Move(oldPath, newPath string) (*FileInfo, error) {
pathParts := strings.FieldsFunc(newPath, isPathSeperator)
amountOfParts := len(pathParts)
if amountOfParts <= 0 {
return nil, errors.New("new path cannot be empty")
}
file, err := d.getFile(d.rootNode, oldPath, "files(id,parents)")
if err != nil {
return nil, err
}
if file == d.rootNode {
return nil, errors.New("root cannot be moved")
}
parentNode := d.rootNode
if amountOfParts > 1 {
dir, err := d.makeDirectoryByParts(pathParts[:amountOfParts-1])
if err != nil {
return nil, err
}
parentNode = dir
if !parentNode.IsDir() {
return nil, fmt.Errorf("unable to create file in `%s': `%s' is not a directory", path.Join(pathParts[:amountOfParts-1]...), parentNode.Name())
}
}
newFile, err := d.srv.Files.Update(file.item.Id, &drive.File{
Name: sanitizeName(pathParts[amountOfParts-1]),
}).
AddParents(parentNode.item.Id).
RemoveParents(path.Join(file.item.Parents...)).
Fields(fileInfoFields...).Do()
if err != nil {
return nil, err
}
return &FileInfo{
item: newFile,
parentPath: path.Join(pathParts[:amountOfParts-1]...),
}, nil
}
// Trash trashes a file or directory
func (d *GDriver) Trash(path string) error {
file, err := d.getFile(d.rootNode, path, "files(id)")
if err != nil {
return err
}
if file == d.rootNode {
return errors.New("root cannot be trashed")
}
_, err = d.srv.Files.Update(file.item.Id, &drive.File{
Trashed: true,
}).Do()
return err
}
// ListTrash lists the contents of the trash, if you specify directories it will only list the trash contents of the specified directories
func (d *GDriver) ListTrash(filePath string, fileFunc func(f *FileInfo) error) error {
file, err := d.getFile(d.rootNode, filePath, "files(id,name)")
if err != nil {
return err
}
// no directories specified
files, err := d.srv.Files.List().Q("trashed = true").Fields(googleapi.Field(fmt.Sprintf("files(%s,parents)", googleapi.CombineFields(fileInfoFields)))).Do()
if err != nil {
return err
}
for i := 0; i < len(files.Files); i++ {
// determinate the parent of this file
inRoot, parentPath, err := isInRoot(d.srv, file.item.Id, files.Files[i], "")
if err != nil {
return err
}
if inRoot {
if err = fileFunc(&FileInfo{
item: files.Files[i],
parentPath: path.Join(file.Path(), parentPath),
}); err != nil {
return CallbackError{NestedError: err}
}
}
}
return nil
}
func getRootNode(srv *drive.Service) (*FileInfo, error) {
root, err := srv.Files.Get("root").Fields(fileInfoFields...).Do()
if err != nil {
return nil, err
}
return &FileInfo{
item: root,
parentPath: "",
}, nil
}
// isInRoot checks if a file is a descendant of root, if so it will return the parent path of the file
func isInRoot(srv *drive.Service, rootID string, file *drive.File, basePath string) (bool, string, error) {
for _, parentID := range file.Parents {
if parentID == rootID {
return true, basePath, nil
}
parent, err := srv.Files.Get(parentID).Fields("id,name,parents").Do()
if err != nil {
return false, "", err
}
if inRoot, parentPath, err := isInRoot(srv, rootID, parent, path.Join(parent.Name, basePath)); err != nil || inRoot {
return inRoot, parentPath, err
}
}
return false, "", nil
}
func (d *GDriver) getFile(rootNode *FileInfo, path string, fields ...googleapi.Field) (*FileInfo, error) {
return d.getFileByParts(rootNode, strings.FieldsFunc(path, isPathSeperator), fields...)
}
func (d *GDriver) getFileByParts(rootNode *FileInfo, pathParts []string, fields ...googleapi.Field) (*FileInfo, error) {
amountOfParts := len(pathParts)
if amountOfParts == 0 {
// get root directory if we have no parts
return rootNode, nil
}
lastID := rootNode.item.Id
lastPart := amountOfParts - 1
var lastFile *drive.File
for i := 0; i < amountOfParts; i++ {
query := fmt.Sprintf("'%s' in parents and name='%s' and trashed = false", lastID, sanitizeName(pathParts[i]))
// log.Println(query)
call := d.srv.Files.List().Q(query)
// if we are not at the last part
if i == lastPart {
if len(fields) <= 0 {
call = call.Fields("files(id)")
} else {
call = call.Fields(fields...)
}
} else {
call = call.Fields("files(id)")
}
files, err := call.Do()
if err != nil {
return nil, err
}
if files == nil || len(files.Files) <= 0 {
return nil, FileNotExistError{Path: path.Join(pathParts[:i+1]...)}
}
if len(files.Files) > 1 {
return nil, fmt.Errorf("multiple entries found for `%s'", path.Join(pathParts[:i+1]...))
}
lastFile = files.Files[0]
lastID = lastFile.Id
// log.Printf("=>%s = %s\n", path.Join(pathParts[:i+1]...), lastID)
}
return &FileInfo{
item: lastFile,
parentPath: path.Join(pathParts[:amountOfParts-1]...),
}, nil
}
type OpenFlag int
const (
O_RDONLY OpenFlag = 1 << iota
O_WRONLY OpenFlag = 1 << iota
O_CREATE OpenFlag = 1 << iota
)
// Open opens a file in the traditional os.Open way
func (d *GDriver) Open(path string, flag OpenFlag) (File, error) {
// plausibility check
if flag&O_RDONLY != 0 && flag&O_WRONLY != 0 {
return nil, errors.New("unable to open a file read and write at the same time")
}
// determinate existent status
file, err := d.getFile(d.rootNode, path)
fileExists := false
if err == nil {
fileExists = true
if file.IsDir() {
return nil, FileIsDirectoryError{Path: path}
}
} else if IsNotExist(err) {
fileExists = false
} else {
return nil, err
}
// if we are not allowed to create a file
// and the file does not exist, fail
if flag&O_CREATE == 0 {
if !fileExists {
return nil, FileNotExistError{Path: path}
}
}
if flag&O_RDONLY != 0 {
// file must exist
if !fileExists {
return nil, FileNotExistError{Path: path}
}
return &readFile{
Driver: d,
FileInfo: file,
}, nil
}
if flag&O_WRONLY != 0 {
// file can exist
if !fileExists {
// if file not exists, and we can not create the file
if flag&O_CREATE == 0 {
return nil, FileNotExistError{Path: path}
}
}
// file exists
return &writeFile{
Driver: d,
Path: path,
FileInfo: file,
}, nil
}
return nil, fmt.Errorf("unknown flag: %d", flag)
}