generated from blakewilliamson1980/cloud-print-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcp-cups-connector-util.go
536 lines (489 loc) · 12.5 KB
/
gcp-cups-connector-util.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
/*
Copyright 2015 Google Inc. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
*/
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"strings"
"sync"
"github.com/google/cloud-print-connector/cdd"
"github.com/google/cloud-print-connector/gcp"
"github.com/google/cloud-print-connector/lib"
"github.com/urfave/cli"
)
var commonCommands = []*cli.Command{
&cli.Command{
Name: "delete-all-gcp-printers",
Usage: "Delete all printers associated with this connector",
Action: deleteAllGCPPrinters,
},
&cli.Command{
Name: "backfill-config-file",
Usage: "Add all keys, with default values, to the config file",
Action: backfillConfigFile,
},
&cli.Command{
Name: "sparse-config-file",
Usage: "Remove all keys, with non-default values, from the config file",
Action: sparseConfigFile,
},
&cli.Command{
Name: "delete-gcp-job",
Usage: "Deletes one GCP job",
Action: deleteGCPJob,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "job-id",
},
},
},
&cli.Command{
Name: "cancel-gcp-job",
Usage: "Cancels one GCP job",
Action: cancelGCPJob,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "job-id",
},
},
},
&cli.Command{
Name: "delete-all-gcp-printer-jobs",
Usage: "Delete all queued jobs associated with a printer",
Action: deleteAllGCPPrinterJobs,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "printer-id",
},
},
},
&cli.Command{
Name: "cancel-all-gcp-printer-jobs",
Usage: "Cancels all queued jobs associated with a printer",
Action: cancelAllGCPPrinterJobs,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "printer-id",
},
},
},
&cli.Command{
Name: "show-gcp-printer-status",
Usage: "Shows the current status of a printer and its jobs",
Action: showGCPPrinterStatus,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "printer-id",
},
},
},
&cli.Command{
Name: "share-gcp-printer",
Usage: "Shares a printer with user or group",
Action: shareGCPPrinter,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "printer-id",
Usage: "Printer to share",
},
&cli.StringFlag{
Name: "email",
Usage: "Group or user to share with",
},
&cli.StringFlag{
Name: "role",
Value: "USER",
Usage: "Role granted. user or manager",
},
&cli.BoolFlag{
Name: "skip-notification",
Usage: "Skip sending email notice. Defaults to true",
DefaultText: "1",
},
&cli.BoolFlag{
Name: "public",
Usage: "Make the printer public (anyone can print)",
},
},
},
&cli.Command{
Name: "unshare-gcp-printer",
Usage: "Removes user or group access to printer",
Action: unshareGCPPrinter,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "printer-id",
Usage: "Printer to unshare",
},
&cli.StringFlag{
Name: "email",
Usage: "Group or user to remove",
},
&cli.BoolFlag{
Name: "public",
Usage: "Remove public printer access",
},
},
},
&cli.Command{
Name: "update-gcp-printer",
Usage: "Modifies settings for a printer",
Action: updateGCPPrinter,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "printer-id",
Usage: "Printer to update",
},
&cli.BoolFlag{
Name: "enable-quota",
Usage: "Set a daily per-user quota",
},
&cli.BoolFlag{
Name: "disable-quota",
Usage: "Disable daily per-user quota",
},
&cli.IntFlag{
Name: "daily-quota",
Usage: "Pages per-user per-day",
},
},
},
}
// getConfig returns a config object
func getConfig(context *cli.Context) (*lib.Config, error) {
config, _, err := lib.GetConfig(context)
if err != nil {
return nil, err
}
return config, nil
}
// getGCP returns a GoogleCloudPrint object
func getGCP(config *lib.Config) (*gcp.GoogleCloudPrint, error) {
return gcp.NewGoogleCloudPrint(config.GCPBaseURL, config.RobotRefreshToken,
config.UserRefreshToken, config.ProxyName, config.GCPOAuthClientID,
config.GCPOAuthClientSecret, config.GCPOAuthAuthURL, config.GCPOAuthTokenURL,
0, nil, false)
}
// backfillConfigFile opens the config file, adds all missing keys
// and default values, then writes the config file back.
func backfillConfigFile(context *cli.Context) error {
config, cfBefore, err := lib.GetConfig(context)
if err != nil {
return err
}
if cfBefore == "" {
return fmt.Errorf("Could not find a config file to backfill")
}
// Same config in []byte format.
configRaw, err := ioutil.ReadFile(cfBefore)
if err != nil {
return err
}
// Same config in map format so that we can detect missing keys.
var configMap map[string]interface{}
if err = json.Unmarshal(configRaw, &configMap); err != nil {
return err
}
if cfWritten, err := config.Backfill(configMap).ToFile(context); err != nil {
return fmt.Errorf("Failed to write config file: %s", err)
} else {
fmt.Printf("Wrote %s\n", cfWritten)
}
return nil
}
// sparseConfigFile opens the config file, removes most keys
// that have default values, then writes the config file back.
func sparseConfigFile(context *cli.Context) error {
config, cfBefore, err := lib.GetConfig(context)
if err != nil {
return err
}
if cfBefore == "" {
return errors.New("Could not find a config file to sparse")
}
if cfWritten, err := config.Sparse(context).ToFile(context); err != nil {
return fmt.Errorf("Failed to write config file: %s\n", err)
} else {
fmt.Printf("Wrote %s\n", cfWritten)
}
return nil
}
// deleteAllGCPPrinters finds all GCP printers associated with this
// connector, deletes them from GCP.
func deleteAllGCPPrinters(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcp, err := getGCP(config)
if err != nil {
return err
}
printers, err := gcp.List()
if err != nil {
return err
}
var wg sync.WaitGroup
for gcpID, name := range printers {
wg.Add(1)
go func(gcpID, name string) {
defer wg.Done()
err := gcp.Delete(gcpID)
if err != nil {
fmt.Printf("Failed to delete %s \"%s\": %s\n", gcpID, name, err)
} else {
fmt.Printf("Deleted %s \"%s\" from GCP\n", gcpID, name)
}
}(gcpID, name)
}
wg.Wait()
return nil
}
// deleteGCPJob deletes one GCP job
func deleteGCPJob(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcp, err := getGCP(config)
if err != nil {
return err
}
err = gcp.DeleteJob(context.String("job-id"))
if err != nil {
return fmt.Errorf("Failed to delete GCP job %s: %s\n", context.String("job-id"), err)
}
fmt.Printf("Deleted GCP job %s\n", context.String("job-id"))
return nil
}
// cancelGCPJob cancels one GCP job
func cancelGCPJob(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcp, err := getGCP(config)
if err != nil {
return err
}
cancelState := cdd.PrintJobStateDiff{
State: &cdd.JobState{
Type: cdd.JobStateAborted,
UserActionCause: &cdd.UserActionCause{ActionCode: cdd.UserActionCauseCanceled},
},
}
err = gcp.Control(context.String("job-id"), &cancelState)
if err != nil {
return fmt.Errorf("Failed to cancel GCP job %s: %s", context.String("job-id"), err)
}
fmt.Printf("Canceled GCP job %s\n", context.String("job-id"))
return nil
}
// deleteAllGCPPrinterJobs finds all GCP printer jobs associated with a
// a given printer id and deletes them.
func deleteAllGCPPrinterJobs(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcp, err := getGCP(config)
if err != nil {
return err
}
jobs, err := gcp.Fetch(context.String("printer-id"))
if err != nil {
return err
}
if len(jobs) == 0 {
fmt.Printf("No queued jobs\n")
}
ch := make(chan bool)
for _, job := range jobs {
go func(gcpJobID string) {
err := gcp.DeleteJob(gcpJobID)
if err != nil {
fmt.Printf("Failed to delete GCP job %s: %s\n", gcpJobID, err)
} else {
fmt.Printf("Deleted GCP job %s\n", gcpJobID)
}
ch <- true
}(job.GCPJobID)
}
for _ = range jobs {
<-ch
}
return nil
}
// cancelAllGCPPrinterJobs finds all GCP printer jobs associated with a
// a given printer id and cancels them.
func cancelAllGCPPrinterJobs(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcp, err := getGCP(config)
if err != nil {
return err
}
jobs, err := gcp.Fetch(context.String("printer-id"))
if err != nil {
return err
}
if len(jobs) == 0 {
fmt.Printf("No queued jobs\n")
}
cancelState := cdd.PrintJobStateDiff{
State: &cdd.JobState{
Type: cdd.JobStateAborted,
UserActionCause: &cdd.UserActionCause{ActionCode: cdd.UserActionCauseCanceled},
},
}
ch := make(chan bool)
for _, job := range jobs {
go func(gcpJobID string) {
err := gcp.Control(gcpJobID, &cancelState)
if err != nil {
fmt.Printf("Failed to cancel GCP job %s: %s\n", gcpJobID, err)
} else {
fmt.Printf("Cancelled GCP job %s\n", gcpJobID)
}
ch <- true
}(job.GCPJobID)
}
for _ = range jobs {
<-ch
}
return nil
}
// showGCPPrinterStatus shows the current status of a GCP printer and it's jobs
func showGCPPrinterStatus(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcp, err := getGCP(config)
if err != nil {
return err
}
printer, _, err := gcp.Printer(context.String("printer-id"))
if err != nil {
return err
}
fmt.Println("Name:", printer.DefaultDisplayName)
fmt.Println("State:", printer.State.State)
jobs, err := gcp.Jobs(context.String("printer-id"))
if err != nil {
return err
}
// Only init common states. Unusual states like DRAFT will only be shown
// if there are jobs in that state.
jobStateCounts := map[string]int{
"DONE": 0,
"ABORTED": 0,
"QUEUED": 0,
"STOPPED": 0,
"IN_PROGRESS": 0,
}
for _, job := range jobs {
jobState := string(job.SemanticState.State.Type)
jobStateCounts[jobState]++
}
fmt.Println("Printer jobs:")
for state, count := range jobStateCounts {
fmt.Println(" ", state, ":", count)
}
return nil
}
// shareGCPPrinter shares a GCP printer
func shareGCPPrinter(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcpConn, err := getGCP(config)
if err != nil {
return err
}
var role gcp.Role
switch strings.ToUpper(context.String("role")) {
case "USER":
role = gcp.User
case "MANAGER":
role = gcp.Manager
default:
return fmt.Errorf("role should be user or manager.")
}
err = gcpConn.Share(context.String("printer-id"), context.String("email"),
role, context.Bool("skip-notification"), context.Bool("public"))
var sharedWith string
if context.Bool("public") {
sharedWith = "public"
} else {
sharedWith = context.String("email")
}
if err != nil {
return fmt.Errorf("Failed to share GCP printer %s with %s: %s\n", context.String("printer-id"), sharedWith, err)
}
fmt.Printf("Shared GCP printer %s with %s\n", context.String("printer-id"), sharedWith)
return nil
}
// unshareGCPPrinter unshares a GCP printer.
func unshareGCPPrinter(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcpConn, err := getGCP(config)
if err != nil {
return err
}
err = gcpConn.Unshare(context.String("printer-id"), context.String("email"), context.Bool("public"))
var sharedWith string
if context.Bool("public") {
sharedWith = "public"
} else {
sharedWith = context.String("email")
}
if err != nil {
return fmt.Errorf("Failed to unshare GCP printer %s with %s: %s\n", context.String("printer-id"), sharedWith, err)
}
fmt.Printf("Unshared GCP printer %s with %s\n", context.String("printer-id"), sharedWith)
return nil
}
// updateGCPPrinter updates settings for a GCP printer.
func updateGCPPrinter(context *cli.Context) error {
config, err := getConfig(context)
if err != nil {
return err
}
gcpConn, err := getGCP(config)
if err != nil {
return err
}
var diff lib.PrinterDiff
diff.Printer = lib.Printer{GCPID: context.String("printer-id")}
if context.Bool("enable-quota") {
diff.Printer.QuotaEnabled = true
diff.QuotaEnabledChanged = true
} else if context.Bool("disable-quota") {
diff.Printer.QuotaEnabled = false
diff.QuotaEnabledChanged = true
}
if context.Int("daily-quota") > 0 {
diff.Printer.DailyQuota = context.Int("daily-quota")
diff.DailyQuotaChanged = true
}
err = gcpConn.Update(&diff)
if err != nil {
return fmt.Errorf("Failed to update GCP printer %s: %s", context.String("printer-id"), err)
} else {
fmt.Printf("Updated GCP printer %s", context.String("printer-id"))
}
return nil
}