forked from pcarleton/sheets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
318 lines (259 loc) · 7.21 KB
/
client.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
package sheets
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"strings"
"time"
retry "github.com/avast/retry-go"
"github.com/pkg/errors"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
drive "google.golang.org/api/drive/v3"
"google.golang.org/api/googleapi"
sheets "google.golang.org/api/sheets/v4"
)
type Client struct {
JWTConfig *jwt.Config
Sheets *sheets.Service
Drive *drive.Service
options []googleapi.CallOption
}
func NewServiceAccountClientFromReader(creds io.Reader) (*Client, error) {
jwtJSON, err := ioutil.ReadAll(creds)
if err != nil {
return nil, errors.Wrap(err, "unable to read credentials")
}
config, err := google.JWTConfigFromJSON(jwtJSON, sheets.SpreadsheetsScope, drive.DriveScope)
if err != nil {
return nil, errors.Wrap(err, "unable to parse JWT config")
}
return NewClientFromConfig(config)
}
func NewImpersonatingServiceAccountClient(creds io.Reader, userEmail string) (*Client, error) {
jwtJSON, err := ioutil.ReadAll(creds)
if err != nil {
return nil, errors.Wrap(err, "unable to read credentials")
}
config, err := google.JWTConfigFromJSON(jwtJSON, sheets.SpreadsheetsScope, drive.DriveScope)
if err != nil {
return nil, errors.Wrap(err, "unable to parse JWT config")
}
config.Subject = userEmail
return NewClientFromConfig(config)
}
func NewClientFromConfig(config *jwt.Config) (*Client, error) {
client := config.Client(context.Background())
sheetsSrv, err := sheets.New(client)
if err != nil {
return nil, errors.Wrap(err, "couldn't initialize sheets client")
}
driveSrv, err := drive.New(client)
if err != nil {
return nil, errors.Wrap(err, "couldn't initialize drive client")
}
return &Client{
JWTConfig: config,
Sheets: sheetsSrv,
Drive: driveSrv,
}, nil
}
func (c *Client) AddOptions(opts ...googleapi.CallOption) {
c.options = append(c.options, opts...)
}
func (c *Client) ListFiles(query string) ([]*drive.File, error) {
var resp *drive.FileList
err := googleRetry(func() error {
var rerr error
resp, rerr = c.Drive.Files.List().PageSize(10).
Q(query).
Fields("nextPageToken, files(id, name, mimeType)").Do(c.options...)
return rerr
})
if err != nil {
return nil, err
}
return resp.Files, nil
}
func (c *Client) CopySpreadsheetFrom(fileID, newName string) (*Spreadsheet, error) {
var file *drive.File
err := googleRetry(func() error {
var rerr error
file, rerr = c.Drive.Files.Copy(fileID, &drive.File{
Name: newName,
}).Do(c.options...)
return rerr
})
if err != nil {
return nil, err
}
return c.GetSpreadsheet(file.Id)
}
func (c *Client) CreateSpreadsheetFromTsv(title string, reader io.Reader) (*Spreadsheet, error) {
arr := TsvToArr(reader, "\t")
return c.CreateSpreadsheetWithData(title, arr)
}
func (c *Client) CreateSpreadsheetFromCsv(title string, reader io.Reader, delimiter string) (*Spreadsheet, error) {
arr := TsvToArr(reader, delimiter)
return c.CreateSpreadsheetWithData(title, arr)
}
func (c *Client) CreateSpreadsheet(title string) (*Spreadsheet, error) {
ssProps := &sheets.Spreadsheet{
Properties: &sheets.SpreadsheetProperties{Title: title},
}
var ssInfo *sheets.Spreadsheet
err := googleRetry(func() error {
var rerr error
ssInfo, rerr = c.Sheets.Spreadsheets.Create(ssProps).Do(c.options...)
return rerr
})
if err != nil {
return nil, err
}
ss := &Spreadsheet{
Client: c,
Spreadsheet: ssInfo,
}
return ss, nil
}
func (c *Client) CreateSpreadsheetWithData(title string, data [][]string) (*Spreadsheet, error) {
ss, err := c.CreateSpreadsheet(title)
if err != nil {
return nil, err
}
sheetname := "Sheet1"
sheet := ss.GetSheet(sheetname)
if sheet == nil {
return nil, fmt.Errorf("Couldn't find sheet %s for %s", sheetname, ss.Id())
}
err = sheet.Update(data)
return ss, err
}
func (c *Client) GetSpreadsheet(spreadsheetId string) (*Spreadsheet, error) {
var ssInfo *sheets.Spreadsheet
err := googleRetry(func() error {
var rerr error
ssInfo, rerr = c.Sheets.Spreadsheets.Get(spreadsheetId).Do(c.options...)
return rerr
})
if err != nil {
return nil, err
}
return &Spreadsheet{c, ssInfo}, nil
}
func (c *Client) GetSpreadsheetWithData(spreadsheetId string) (*Spreadsheet, error) {
var ssInfo *sheets.Spreadsheet
err := googleRetry(func() error {
var rerr error
ssInfo, rerr = c.Sheets.Spreadsheets.Get(spreadsheetId).IncludeGridData(true).Do(c.options...)
return rerr
})
if err != nil {
return nil, err
}
return &Spreadsheet{c, ssInfo}, nil
}
func (c *Client) Delete(fileId string) error {
req := c.Drive.Files.Delete(fileId)
return googleRetry(func() error {
return req.Do(c.options...)
})
}
func (c *Client) ShareFile(fileID, email string) error {
return c.shareFile(fileID, email, false)
}
func (c *Client) ShareFileNotify(fileID, email string) error {
return c.shareFile(fileID, email, true)
}
func (c *Client) ShareWithAnyone(fileID string) error {
perm := drive.Permission{
Role: "writer",
Type: "anyone",
AllowFileDiscovery: false,
}
return googleRetry(func() error {
_, err := c.Drive.Permissions.Create(fileID, &perm).Do(c.options...)
return err
})
}
func (c *Client) shareFile(fileID, email string, notify bool) error {
perm := drive.Permission{
EmailAddress: email,
Role: "writer",
Type: "user",
}
req := c.Drive.Permissions.Create(fileID, &perm).SendNotificationEmail(notify)
return googleRetry(func() error {
_, err := req.Do(c.options...)
return err
})
}
func (c *Client) Revoke(fileID, email string) error {
var permissions *drive.PermissionList
err := googleRetry(func() error {
var rerr error
permissions, rerr = c.Drive.Permissions.List(fileID).Fields("nextPageToken, permissions(id, emailAddress, type, role)").Do(c.options...)
return rerr
})
if err != nil {
return errors.Wrapf(err, "couldn't list permissions for %s", fileID)
}
for _, p := range permissions.Permissions {
if p.EmailAddress != email {
continue
}
return googleRetry(func() error {
return c.Drive.Permissions.Delete(fileID, p.Id).Do(c.options...)
})
}
return nil
}
// Transfer ownership of the file
func (c *Client) TransferOwnership(fileID, email string) error {
perm := drive.Permission{
EmailAddress: email,
Role: "owner",
Type: "user",
}
req := c.Drive.Permissions.Create(fileID, &perm).TransferOwnership(true)
return googleRetry(func() error {
_, err := req.Do(c.options...)
return err
})
}
func googleRetry(f func() error) error {
return retry.Do(
f,
retry.Delay(15*time.Second),
retry.Attempts(5),
retry.RetryIf(func(err error) bool {
// Retry network errors, sometimes Google's API craps out
if _, ok := err.(*net.OpError); ok {
return true
}
if strings.Contains(err.Error(), "connection reset by peer") {
return true
}
if err == io.EOF {
return true
}
// Retry more specific Google API errors
if gerr, ok := err.(*googleapi.Error); ok {
switch {
// Too many requests
case gerr.Code == 429:
return true
// Too many requests as a 403
case gerr.Code == 403 && gerr.Message == "Rate Limit Exceeded":
return true
// Server error. This may lead to duplicates, calling code must check for that
case (gerr.Code >= 500 && gerr.Code <= 599):
return true
}
}
return false
}),
)
}