-
Notifications
You must be signed in to change notification settings - Fork 6
/
google_drive.go
294 lines (239 loc) · 6.91 KB
/
google_drive.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"path"
"time"
"github.com/fatih/color"
"github.com/toqueteos/webbrowser"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v3"
)
type GDriveStore struct {
Config oauth2.Config `json:"oauth_config"`
OAuthToken oauth2.Token `json:"oauth_token"`
UserID string `json:"user_id"`
}
// Setup GDrive
func (g *GDriveStore) Setup() bool {
config, err := getConfig()
if err != nil {
color.Red("Unable to parse client secret file to config: %v", err)
return false
}
tok, err := getGDriveTokenFromWeb(config)
if err != nil {
color.Red("Unable to get client token: %v", err)
return false
}
// set the oauth info
g.Config = *config
g.OAuthToken = *tok
ctx := context.Background()
client := config.Client(ctx, &g.OAuthToken)
svc, err := drive.New(client)
if err != nil {
color.Red("Unable to retrieve drive Client %v", err)
return false
}
account, err := svc.About.Get().Fields("user").Do()
if err != nil {
color.Red("Unable to retrieve drive information %v", err)
return false
}
userID := account.User.PermissionId
for _, gds := range preferences.GDriveStores {
if gds.UserID == userID {
color.Red("Google Drive Account for %v (%v) already exists.", account.User.DisplayName, account.User.EmailAddress)
return false
}
}
g.UserID = userID
return true
}
func (g GDriveStore) Upload(share Share) {
ctx := context.Background()
config := &g.Config
client := config.Client(ctx, &g.OAuthToken)
svc, err := drive.New(client)
if err != nil {
color.Red("Unable to retrieve drive Client %v", err)
return
}
fmt.Print(color.MagentaString("Uploading GoogleDrive/%s...", share.SID))
// delete existing share
deleteFilesForShareID(share.SID, svc)
// now create and upload share
file := drive.File{}
now, err := time.Now().MarshalText()
file.ModifiedTime = string(now)
file.Name = string(share.SID)
file.Parents = []string{"appDataFolder"}
_, err = svc.Files.Create(&file).Media(bytes.NewReader(share.Data)).Do()
if err != nil {
color.Red("GoogleDrive/%s upload failed: %v", share.SID, err)
} else {
//print check mark
fmt.Print(color.MagentaString("\u2713\n"))
}
}
func (g GDriveStore) Delete(sid ShareID) {
ctx := context.Background()
config := &g.Config
client := config.Client(ctx, &g.OAuthToken)
svc, err := drive.New(client)
if err != nil {
color.Red("Unable to retrieve drive Client %v", err)
return
}
fmt.Print(color.YellowString("Deleting GoogleDrive/%s...", sid))
// delete existing share
deleteFilesForShareID(sid, svc)
//print check mark
fmt.Print(color.YellowString("\u2713\n"))
}
//Restore downloads shares to local restore path
func (g GDriveStore) Restore() string {
ctx := context.Background()
config := &g.Config
client := config.Client(ctx, &g.OAuthToken)
svc, err := drive.New(client)
if err != nil {
color.Red("Unable to retrieve drive Client %v", err)
return ""
}
restoreDir, err := ioutil.TempDir("", "chasm_gdrive_restore")
if err != nil {
color.Red("Error cannot create temp dir: %v", err)
return ""
}
// download all files
// get all chasm files from drive
r, err := svc.Files.List().Spaces("appDataFolder").Do()
if err != nil {
color.Red("Unable to iterate names %v", err)
return ""
}
color.Yellow("Downloading shares from Google Drive...")
for _, i := range r.Files {
// export file
resp, err := svc.Files.Get(i.Id).Download()
if err != nil {
color.Yellow("Error downloading file %s: %v", i.Name, err)
continue
}
defer resp.Body.Close()
// read file bytes
fileBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
color.Yellow("Error reading downloaded bytes %s: %v", i.Name, err)
continue
}
// write file to temp dir
ioutil.WriteFile(path.Join(restoreDir, i.Name), fileBytes, 0770)
fmt.Println("\t - got share ", i.Name)
}
return restoreDir
}
func (g GDriveStore) Description() string {
ctx := context.Background()
config := &g.Config
client := config.Client(ctx, &g.OAuthToken)
label := "Google Drive Store"
svc, err := drive.New(client)
if err != nil {
color.Red("Unable to retrieve drive Client %v", err)
return label
}
// get all chasm files from drive
r, err := svc.Files.List().Spaces("appDataFolder").Do()
if err != nil {
color.Red("Unable to iterate names %v", err)
return label
}
account, err := svc.About.Get().Fields("user").Do()
if err != nil {
color.Red("Unable to retrieve drive information %v", err)
return label
}
label = fmt.Sprintf("Google Drive Store: %v (%v)", account.User.DisplayName, account.User.EmailAddress)
for _, i := range r.Files {
label += fmt.Sprintf("\n\t%s %s", color.YellowString("-"), i.Name)
}
return label
}
func (g GDriveStore) ShortDescription() string {
ctx := context.Background()
config := &g.Config
client := config.Client(ctx, &g.OAuthToken)
label := "Google Drive Store"
svc, err := drive.New(client)
if err != nil {
color.Red("Unable to retrieve drive Client %v", err)
return label
}
account, err := svc.About.Get().Fields("user").Do()
if err != nil {
color.Red("Unable to retrieve drive information %v", err)
return label
}
return fmt.Sprintf("Google Drive Store: %v (%v)", account.User.DisplayName, account.User.EmailAddress)
}
// Clean deletes all shares from the folder store
func (g GDriveStore) Clean() {
ctx := context.Background()
config := &g.Config
client := config.Client(ctx, &g.OAuthToken)
svc, err := drive.New(client)
if err != nil {
color.Red("Unable to retrieve drive Client %v", err)
return
}
r, err := svc.Files.List().Spaces("appDataFolder").Do()
if err != nil {
color.Red("Unable to search for files to delete: %v", err)
return
}
for _, i := range r.Files {
color.Yellow("Removing Google Drive: %v", i.Name)
svc.Files.Delete(i.Id).Do()
}
}
/// MARK: Helper Methods ///
func getConfig() (*oauth2.Config, error) {
clientJSON := []byte(GoogleDriveClientSecret)
return google.ConfigFromJSON(clientJSON, drive.DriveAppdataScope)
}
// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getGDriveTokenFromWeb(config *oauth2.Config) (*oauth2.Token, error) {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
webbrowser.Open(authURL)
color.Yellow("Enter Auth Code: ")
var code string
if _, err := fmt.Scan(&code); err != nil {
color.Red("Unable to read authorization code %v", err)
return nil, err
}
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
color.Red("Unable to retrieve token from web %v", err)
return tok, err
}
return tok, nil
}
func deleteFilesForShareID(sid ShareID, svc *drive.Service) {
// get all chasm files from drive
q := fmt.Sprintf("name = '%s'", string(sid))
r, err := svc.Files.List().Spaces("appDataFolder").Q(q).Do()
if err != nil {
color.Red("Unable to search for files to delete: %v", err)
return
}
for _, i := range r.Files {
svc.Files.Delete(i.Id).Do()
}
}