-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdrive.go
75 lines (61 loc) · 2.04 KB
/
gdrive.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
package gdrive
import (
"context"
"fmt"
"io/ioutil"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
// Service is an abstraction object for the Google Drive service.
// It is intended to satisfy `stationery.Service` interface.
type Service struct {
service *drive.Service
}
// ExportFile exports the file in the first argument, returning the content in the specified MIME type, as the second argument.
func (s *Service) ExportFile(file *drive.File, MIMEType string) (content string, err error) {
fe := s.service.Files.Export(file.Id, MIMEType)
resp, err := fe.Download()
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
// GetFiles receives a query parameter and returns a list of `drive.File`s or an error.
func (s *Service) GetFiles(q string) (files []*drive.File, err error) {
fl, err := s.service.Files.List().Fields("nextPageToken, files(id, name)").Q(q).Do()
if err != nil {
return nil, err
}
return fl.Files, nil
}
// GetService creates a new `drive.Service` from a credentials file.
// The argument is just the path to a credentials file, which are expected to identify a service account.
// If the argument is empty, and on any other error, an error is returned.
func GetService(credentialsFile string) (*Service, error) {
if credentialsFile == "" {
return nil, fmt.Errorf("no credentials file specified")
}
ctx := context.Background()
b, err := ioutil.ReadFile(credentialsFile)
if err != nil {
return nil, fmt.Errorf("unable to read client secret file: %v", err)
}
config, err := google.JWTConfigFromJSON(b, drive.DriveMetadataReadonlyScope, drive.DriveReadonlyScope)
if err != nil {
return nil, fmt.Errorf("invalid client secret file: %v", err)
}
client := config.Client(ctx)
svc, err := drive.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
return nil, fmt.Errorf("invalid credentials: %v", err)
}
return &Service{
service: svc,
}, nil
}