-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriveapi.go
279 lines (248 loc) · 6.89 KB
/
driveapi.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
// Package driveapi provides basic functionality to work with Google Drive API.
package driveapi
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
const (
MimeTypeGoogleDoc = iota
MimeTypeGoogleDrawing
MimeTypeGoogleDriveFile
MimeTypeGoogleDriveFolder
MimeTypeGoogleForm
MimeTypeGoogleFusionTable
MimeTypeGoogleMyMap
MimeTypeGoogleSlide
MimeTypeGoogleAppsScript
MimeTypeShortcut
MimeTypeGoogleSite
MimeTypeGoogleSpreadsheet
)
// See https://developers.google.com/drive/api/v3/mime-types
var googleAppsMimeTypes = map[int]string{
MimeTypeGoogleDoc: "application/vnd.google-apps.document",
MimeTypeGoogleDrawing: "application/vnd.google-apps.drawing",
MimeTypeGoogleDriveFile: "application/vnd.google-apps.file",
MimeTypeGoogleDriveFolder: "application/vnd.google-apps.folder",
MimeTypeGoogleForm: "application/vnd.google-apps.form",
MimeTypeGoogleFusionTable: "application/vnd.google-apps.fusiontable",
MimeTypeGoogleMyMap: "application/vnd.google-apps.map",
MimeTypeGoogleSlide: "application/vnd.google-apps.presentation",
MimeTypeGoogleAppsScript: "application/vnd.google-apps.script",
MimeTypeShortcut: "application/vnd.google-apps.shortcut",
MimeTypeGoogleSite: "application/vnd.google-apps.site",
MimeTypeGoogleSpreadsheet: "application/vnd.google-apps.spreadsheet",
}
func GoogleAppsMimeTypeText(code int) string {
return googleAppsMimeTypes[code]
}
func InitWithConfigJSON(
ctx context.Context, b []byte, tokenPath string) *drive.Service {
config, err := google.ConfigFromJSON(b, drive.DriveScope)
if err != nil {
log.Fatalf("Unable to parse config from json: %v", err)
}
client := getClient(config, tokenPath)
service, err := drive.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to create Drive service: %v", err)
}
return service
}
func RootFolder(ctx context.Context, drv *drive.Service) (File, error) {
root, err := drv.Files.Get("root").Context(ctx).
Fields("id, name").Do()
if err != nil {
log.Fatalf("Error fetching root folder: %v", err)
return nil, err
}
return &file{
GD: drv,
id: root.Id,
name: root.Name,
files: nil,
mimeType: GoogleAppsMimeTypeText(MimeTypeGoogleDriveFolder),
}, nil
}
func tokenFromFile(path string) (*oauth2.Token, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
tok := &oauth2.Token{}
err = json.NewDecoder(f).Decode(tok)
return tok, err
}
func tokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("token-state", oauth2.AccessTypeOffline)
fmt.Printf("Open the below link in your browser and "+
"then type/paste the authorization code here:\n%v\n", authURL)
var authzCode string
if _, err := fmt.Scan(&authzCode); err != nil {
log.Fatalf("Unable to read authorization code :%v", err)
}
tok, err := config.Exchange(context.TODO(), authzCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok
}
func saveToken(path string, token *oauth2.Token) {
fmt.Printf("Saving token to file %v", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to save token to %v: %v\n", path, err)
}
defer f.Close()
if err := json.NewEncoder(f).Encode(token); err != nil {
log.Fatalf("Unable to write token to file %v: %v\n", path, err)
}
}
func getClient(config *oauth2.Config, tokenPath string) *http.Client {
tok, err := tokenFromFile(tokenPath)
if err != nil {
tok = tokenFromWeb(config)
saveToken(tokenPath, tok)
}
return config.Client(context.Background(), tok)
}
type file struct {
GD *drive.Service
id, name, mimeType, parentID, parentName string
size uint64
content []byte
files []File
lsTime time.Time
contentDownloaded bool
}
type File interface {
String() string
IsDir() bool
IsGoogleAppsFile() bool
ListFiles(ctx context.Context) ([]File, error)
Size() uint64
Name() string
MimeType() string
ParentID() string
ParentName() string
Content() []byte
Files() []File
ID() string
Download(ctx context.Context) (io.ReadCloser, error)
}
func (f *file) ListFiles(
ctx context.Context) ([]File, error) {
if !f.IsDir() {
return nil, errors.New("not a directory")
}
log.Printf("Listing files for %s", f.Name())
if time.Since(f.lsTime).Minutes() < 60 {
return f.files, nil
}
var nextPageToken string
var files []File
for {
res, err := f.GD.Files.List().Context(ctx).
Fields("nextPageToken, files(id, name, size, parents, mimeType)").
PageToken(nextPageToken).
Q(fmt.Sprintf("'%s' in parents", f.id)).
Do()
if err != nil {
return files, err
}
for _, e := range res.Files {
files = append(files, &file{
id: e.Id,
name: e.Name,
parentID: f.ID(),
parentName: f.Name(),
size: uint64(e.Size),
mimeType: e.MimeType,
GD: f.GD,
})
}
if len(res.NextPageToken) == 0 {
break
}
nextPageToken = res.NextPageToken
}
f.files = files
f.lsTime = time.Now()
return files, nil
}
func (f *file) String() string {
return fmt.Sprintf(
"%s/%s => mime type: %s, ID: %s, size: %d KB",
f.parentName, f.name, f.mimeType, f.id, f.size/1024)
}
func (f *file) IsDir() bool {
return f.mimeType == GoogleAppsMimeTypeText(MimeTypeGoogleDriveFolder)
}
func (f *file) IsGoogleAppsFile() bool {
return strings.HasPrefix(f.mimeType, "application/vnd.google-apps")
}
func (f *file) Size() uint64 {
return f.size
}
func (f *file) Name() string {
return f.name
}
func (f *file) ID() string {
return f.id
}
func (f *file) MimeType() string {
return f.mimeType
}
func (f *file) ParentName() string {
return f.parentName
}
func (f *file) ParentID() string {
return f.parentID
}
func (f *file) Content() []byte {
return f.content
}
func (f *file) Files() []File {
return f.files
}
func (f *file) Download(ctx context.Context) (io.ReadCloser, error) {
if f.contentDownloaded { // TODO: add TTL logic here
return f.contentReader(), nil
}
r, err := f.GD.Files.Get(f.id).
Context(ctx).
Download()
if err != nil {
fmt.Printf("error downloading %s: %v\n", f.name, err)
return nil, err
}
defer r.Body.Close()
fmt.Printf("file download started for %s\n", f.name)
data, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
f.content = make([]byte, f.size)
f.content = data
f.contentDownloaded = true
fmt.Printf("total downloaded bytes: %d, reported size: %d\n", len(data), f.size)
return f.contentReader(), nil
}
func (f *file) contentReader() io.ReadCloser {
return io.NopCloser(bufio.NewReader(bytes.NewReader(f.content)))
}