/
gcp.go
784 lines (674 loc) · 21.9 KB
/
gcp.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
/*
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 gcp is the Google Cloud Print API client.
package gcp
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/oauth2"
"github.com/POTION4/cloud-print-connector/cdd"
"github.com/POTION4/cloud-print-connector/lib"
"github.com/POTION4/cloud-print-connector/log"
)
const (
// This prefix tickles a magic spell in GCP so that, for example,
// the GCP UI shows location as the string found in the
// printer-location CUPS attribute.
gcpTagPrefix = "__cp__"
// OAuth constants.
RedirectURL = "oob"
ScopeCloudPrint = "https://www.googleapis.com/auth/cloudprint"
ScopeGoogleTalk = "https://www.googleapis.com/auth/googletalk"
AccessType = "offline"
// Printer Notification channel constants.
FCP_CHANNEL = "FCM_CHANNEL"
XMPP_CHANNEL = "XMPP_CHANNEL"
)
// GoogleCloudPrint is the interface between Go and the Google Cloud Print API.
type GoogleCloudPrint struct {
baseURL string
robotClient *http.Client
userClient *http.Client
proxyName string
useFcm bool
jobs chan<- *lib.Job
downloadSemaphore *lib.Semaphore
}
// NewGoogleCloudPrint establishes a connection with GCP, returns a new GoogleCloudPrint object.
func NewGoogleCloudPrint(baseURL, robotRefreshToken, userRefreshToken, proxyName, oauthClientID, oauthClientSecret, oauthAuthURL, oauthTokenURL string, maxConcurrentDownload uint, jobs chan<- *lib.Job, useFcm bool) (*GoogleCloudPrint, error) {
robotClient, err := newClient(oauthClientID, oauthClientSecret, oauthAuthURL, oauthTokenURL, robotRefreshToken, ScopeCloudPrint, ScopeGoogleTalk)
if err != nil {
return nil, err
}
var userClient *http.Client
if userRefreshToken != "" {
userClient, err = newClient(oauthClientID, oauthClientSecret, oauthAuthURL, oauthTokenURL, userRefreshToken, ScopeCloudPrint)
if err != nil {
return nil, err
}
}
gcp := &GoogleCloudPrint{
baseURL: baseURL,
robotClient: robotClient,
userClient: userClient,
proxyName: proxyName,
useFcm: useFcm,
jobs: jobs,
downloadSemaphore: lib.NewSemaphore(maxConcurrentDownload),
}
return gcp, nil
}
func (gcp *GoogleCloudPrint) GetRobotAccessToken() (string, error) {
token, err := gcp.robotClient.Transport.(*oauth2.Transport).Source.Token()
if err != nil {
return "", err
}
return token.AccessToken, nil
}
// CanShare answers the question "can we share printers when they are registered?"
func (gcp *GoogleCloudPrint) CanShare() bool {
return gcp.userClient != nil
}
// Control calls google.com/cloudprint/control to set the state of a
// GCP print job.
func (gcp *GoogleCloudPrint) Control(jobID string, state *cdd.PrintJobStateDiff) error {
semanticState, err := json.Marshal(state)
if err != nil {
return err
}
form := url.Values{}
form.Set("jobid", jobID)
form.Set("semantic_state_diff", string(semanticState))
if _, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"control", form); err != nil {
return err
}
return nil
}
// Delete calls google.com/cloudprint/delete to delete a printer from GCP.
func (gcp *GoogleCloudPrint) Delete(gcpID string) error {
form := url.Values{}
form.Set("printerid", gcpID)
if _, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"delete", form); err != nil {
return err
}
return nil
}
// DeleteJob calls google.com/cloudprint/deletejob to delete a print job.
func (gcp *GoogleCloudPrint) DeleteJob(gcpJobID string) error {
form := url.Values{}
form.Set("jobid", gcpJobID)
if _, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"deletejob", form); err != nil {
return err
}
return nil
}
// Fetch calls google.com/cloudprint/fetch to get the outstanding print jobs for
// a GCP printer.
func (gcp *GoogleCloudPrint) Fetch(gcpID string) ([]Job, error) {
form := url.Values{}
form.Set("printerid", gcpID)
responseBody, errorCode, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"fetch", form)
if err != nil {
if errorCode == 413 {
log.Debugf("No jobs returned by fetch (413 error)")
// 413 means "Zero print jobs returned", which isn't really an error.
return []Job{}, nil
}
return nil, err
}
var jobsData struct {
Jobs []struct {
ID string
Title string
FileURL string
OwnerID string
}
}
if err = json.Unmarshal(responseBody, &jobsData); err != nil {
return nil, err
}
jobs := make([]Job, len(jobsData.Jobs))
for i, jobData := range jobsData.Jobs {
jobs[i] = Job{
GCPPrinterID: gcpID,
GCPJobID: jobData.ID,
FileURL: jobData.FileURL,
OwnerID: jobData.OwnerID,
Title: jobData.Title,
}
}
log.Debugf("Fetched jobs: %+v", jobs)
return jobs, nil
}
// Jobs calls google.com/cloudprint/jobs to get print jobs for a GCP printer.
func (gcp *GoogleCloudPrint) Jobs(gcpID string) ([]Job, error) {
form := url.Values{}
form.Set("printerid", gcpID)
responseBody, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"jobs", form)
if err != nil {
return nil, err
}
var jobsData struct {
Jobs []struct {
ID string
Title string
OwnerID string
SemanticState *cdd.PrintJobState
}
}
if err = json.Unmarshal(responseBody, &jobsData); err != nil {
return nil, err
}
jobs := make([]Job, len(jobsData.Jobs))
for i, jobData := range jobsData.Jobs {
jobs[i] = Job{
GCPPrinterID: gcpID,
GCPJobID: jobData.ID,
OwnerID: jobData.OwnerID,
Title: jobData.Title,
SemanticState: jobData.SemanticState,
}
}
return jobs, nil
}
// List calls google.com/cloudprint/list to get all GCP printers assigned
// to this connector.
//
// Returns map of GCPID => printer name. GCPID is unique to GCP; printer name
// should be unique to CUPS. Use Printer to get details about each printer.
func (gcp *GoogleCloudPrint) List() (map[string]string, error) {
form := url.Values{}
form.Set("proxy", gcp.proxyName)
form.Set("extra_fields", "-tags")
responseBody, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"list", form)
if err != nil {
return nil, err
}
var listData struct {
Printers []struct {
ID string `json:"id"`
Name string `json:"name"`
}
}
if err = json.Unmarshal(responseBody, &listData); err != nil {
return nil, err
}
printers := make(map[string]string, len(listData.Printers))
for _, p := range listData.Printers {
printers[p.ID] = p.Name
}
return printers, nil
}
// Register calls google.com/cloudprint/register to register a GCP printer.
//
// Sets the GCPID field in the printer arg.
func (gcp *GoogleCloudPrint) Register(printer *lib.Printer) error {
capabilities, err := marshalCapabilities(printer.Description)
if err != nil {
return err
}
semanticState, err := json.Marshal(cdd.CloudDeviceState{Printer: printer.State})
if err != nil {
return err
}
form := url.Values{}
form.Set("name", printer.Name)
form.Set("default_display_name", printer.DefaultDisplayName)
form.Set("proxy", gcp.proxyName)
form.Set("uuid", printer.UUID)
form.Set("manufacturer", printer.Manufacturer)
form.Set("model", printer.Model)
form.Set("gcp_version", printer.GCPVersion)
form.Set("setup_url", printer.SetupURL)
form.Set("support_url", printer.SupportURL)
form.Set("update_url", printer.UpdateURL)
form.Set("firmware", printer.ConnectorVersion)
form.Set("semantic_state", string(semanticState))
form.Set("use_cdd", "true")
form.Set("capabilities", capabilities)
form.Set("capsHash", printer.CapsHash)
if gcp.useFcm {
form.Set("notification_channel", FCP_CHANNEL)
} else {
form.Set("notification_channel", XMPP_CHANNEL)
}
sortedKeys := make([]string, 0, len(printer.Tags))
for key := range printer.Tags {
sortedKeys = append(sortedKeys, key)
}
sort.Strings(sortedKeys)
for _, key := range sortedKeys {
form.Add("tag", fmt.Sprintf("%s%s=%s", gcpTagPrefix, key, printer.Tags[key]))
}
responseBody, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"register", form)
if err != nil {
return err
}
var registerData struct {
Printers []struct {
ID string
}
}
if err = json.Unmarshal(responseBody, ®isterData); err != nil {
return err
}
printer.GCPID = registerData.Printers[0].ID
return nil
}
// Update calls google.com/cloudprint/update to update a GCP printer.
func (gcp *GoogleCloudPrint) Update(diff *lib.PrinterDiff) error {
// Ignores Name field because it never changes.
form := url.Values{}
form.Set("printerid", diff.Printer.GCPID)
form.Set("proxy", gcp.proxyName)
if diff.DefaultDisplayNameChanged {
form.Set("default_display_name", diff.Printer.DefaultDisplayName)
}
if diff.ManufacturerChanged {
form.Set("manufacturer", diff.Printer.Manufacturer)
}
if diff.ModelChanged {
form.Set("model", diff.Printer.Model)
}
if diff.GCPVersionChanged {
form.Set("gcp_version", diff.Printer.GCPVersion)
}
if diff.SetupURLChanged {
form.Set("setup_url", diff.Printer.SetupURL)
}
if diff.SupportURLChanged {
form.Set("support_url", diff.Printer.SupportURL)
}
if diff.UpdateURLChanged {
form.Set("update_url", diff.Printer.UpdateURL)
}
if diff.ConnectorVersionChanged {
form.Set("firmware", diff.Printer.ConnectorVersion)
}
if diff.NotificationChannelChanged {
form.Set("notification_channel", diff.Printer.NotificationChannel)
}
if diff.StateChanged || diff.DescriptionChanged || diff.GCPVersionChanged {
semanticState, err := json.Marshal(cdd.CloudDeviceState{Printer: diff.Printer.State})
if err != nil {
return err
}
form.Set("semantic_state", string(semanticState))
}
if diff.CapsHashChanged || diff.DescriptionChanged || diff.GCPVersionChanged {
capabilities, err := marshalCapabilities(diff.Printer.Description)
if err != nil {
return err
}
form.Set("use_cdd", "true")
form.Set("capabilities", capabilities)
form.Set("capsHash", diff.Printer.CapsHash)
}
if diff.TagsChanged {
sortedKeys := make([]string, 0, len(diff.Printer.Tags))
for key := range diff.Printer.Tags {
sortedKeys = append(sortedKeys, key)
}
sort.Strings(sortedKeys)
for _, key := range sortedKeys {
form.Add("tag", fmt.Sprintf("%s%s=%s", gcpTagPrefix, key, diff.Printer.Tags[key]))
}
form.Set("remove_tag", gcpTagPrefix+".*")
}
if diff.QuotaEnabledChanged {
form.Set("quota_enabled", strconv.FormatBool(diff.Printer.QuotaEnabled))
}
if diff.DailyQuotaChanged {
form.Set("daily_quota", strconv.Itoa(diff.Printer.DailyQuota))
}
if _, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"update", form); err != nil {
return err
}
return nil
}
// Printer gets the printer identified by it's GCPID.
//
// The second return value is queued print job quantity.
func (gcp *GoogleCloudPrint) Printer(gcpID string) (*lib.Printer, uint, error) {
form := url.Values{}
form.Set("printerid", gcpID)
form.Set("use_cdd", "true")
form.Set("extra_fields", "queuedJobsCount,semanticState")
responseBody, _, _, err := postWithRetry(gcp.robotClient, gcp.baseURL+"printer", form)
if err != nil {
return nil, 0, err
}
var printersData struct {
Printers []struct {
ID string `json:"id"`
Name string `json:"name"`
DefaultDisplayName string `json:"defaultDisplayName"`
UUID string `json:"uuid"`
Manufacturer string `json:"manufacturer"`
Model string `json:"model"`
GCPVersion string `json:"gcpVersion"`
SetupURL string `json:"setupUrl"`
SupportURL string `json:"supportUrl"`
UpdateURL string `json:"updateUrl"`
Firmware string `json:"firmware"`
Capabilities cdd.CloudDeviceDescription `json:"capabilities"`
CapsHash string `json:"capsHash"`
Tags []string `json:"tags"`
QueuedJobsCount uint `json:"queuedJobsCount"`
SemanticState cdd.CloudDeviceState `json:"semanticState"`
NotificationChannel string `json:"notificationChannel"`
}
}
if err = json.Unmarshal(responseBody, &printersData); err != nil {
return nil, 0, err
}
p := printersData.Printers[0] // If the slice were empty, postWithRetry would have returned an error.
tags := make(map[string]string)
for _, tag := range p.Tags {
s := strings.SplitN(tag[len(gcpTagPrefix):], "=", 2)
key := s[0]
var value string
if len(s) > 1 {
value = s[1]
}
tags[key] = value
}
printer := &lib.Printer{
GCPID: p.ID,
Name: p.Name,
DefaultDisplayName: p.DefaultDisplayName,
UUID: p.UUID,
Manufacturer: p.Manufacturer,
Model: p.Model,
GCPVersion: p.GCPVersion,
SetupURL: p.SetupURL,
SupportURL: p.SupportURL,
UpdateURL: p.UpdateURL,
ConnectorVersion: p.Firmware,
State: p.SemanticState.Printer,
Description: p.Capabilities.Printer,
CapsHash: p.CapsHash,
Tags: tags,
NotificationChannel: p.NotificationChannel,
}
return printer, p.QueuedJobsCount, err
}
func marshalCapabilities(description *cdd.PrinterDescriptionSection) (string, error) {
capabilities := cdd.CloudDeviceDescription{
Version: "1.0",
Printer: description,
}
cdd, err := json.Marshal(capabilities)
if err != nil {
return "", fmt.Errorf("Failed to remarshal translated CDD: %s", err)
}
return string(cdd), nil
}
// Role is the role a user or group is granted when sharing a printer.
type Role string
const (
User Role = "USER"
Manager Role = "MANAGER"
Owner Role = "OWNER"
)
// Share calls google.com/cloudprint/share to share a registered GCP printer.
func (gcp *GoogleCloudPrint) Share(gcpID, shareScope string, role Role, skip_notification bool, public bool) error {
if gcp.userClient == nil {
return errors.New("Cannot share because user OAuth credentials not provided.")
}
form := url.Values{}
form.Set("printerid", gcpID)
if public {
form.Set("public", "true")
} else {
form.Set("skip_notification", strconv.FormatBool(skip_notification))
form.Set("role", string(role))
form.Set("scope", shareScope)
}
if _, _, _, err := postWithRetry(gcp.userClient, gcp.baseURL+"share", form); err != nil {
return err
}
return nil
}
// Unshare calls google.com/cloudprint/unshare to unshare a registered GCP printer.
func (gcp *GoogleCloudPrint) Unshare(gcpID, shareScope string, public bool) error {
if gcp.userClient == nil {
return errors.New("Cannot unshare because user OAuth credentials not provided.")
}
form := url.Values{}
form.Set("printerid", gcpID)
if public {
form.Set("public", "true")
} else {
form.Set("scope", shareScope)
}
if _, _, _, err := postWithRetry(gcp.userClient, gcp.baseURL+"unshare", form); err != nil {
return err
}
return nil
}
// Download downloads a URL (a print job data file) directly to a Writer.
func (gcp *GoogleCloudPrint) Download(dst io.Writer, url string) error {
response, err := getWithRetry(gcp.robotClient, url)
if err != nil {
return err
}
defer response.Body.Close()
_, err = io.Copy(dst, response.Body)
if err != nil {
return err
}
return nil
}
// FCM Subscribe.
func (gcp *GoogleCloudPrint) FcmSubscribe(subscribeUrl string) (interface{}, error) {
response, err := getWithRetry(gcp.robotClient, fmt.Sprintf("%s%s", gcp.baseURL, subscribeUrl))
if err != nil {
return nil, fmt.Errorf("failed to get Fcm Token: %s", err)
}
defer response.Body.Close()
if response.StatusCode == 200 {
data, _ := ioutil.ReadAll(response.Body)
var f interface{}
json.Unmarshal(data, &f)
return f, nil
} else {
return nil, fmt.Errorf("failed to get Fcm Token: %d", response.StatusCode)
}
}
// Ticket gets a ticket, aka print job options.
func (gcp *GoogleCloudPrint) Ticket(gcpJobID string) (*cdd.CloudJobTicket, error) {
form := url.Values{}
form.Set("jobid", gcpJobID)
form.Set("use_cjt", "true")
responseBody, _, httpStatusCode, err := postWithRetry(gcp.robotClient, gcp.baseURL+"ticket", form)
// The /ticket API is different than others, because it only returns the
// standard GCP error information on success=false.
if httpStatusCode != http.StatusOK {
return nil, err
}
d := json.NewDecoder(bytes.NewReader(responseBody))
d.UseNumber() // Force large numbers not to be formatted with scientific notation.
var ticket cdd.CloudJobTicket
err = d.Decode(&ticket)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal ticket: %s", err)
}
return &ticket, nil
}
// ProximityToken gets a proximity token for Privet users to access a printer
// through the cloud.
//
// Returns byte array of raw JSON to preserve any/all returned fields
// and returned HTTP status code.
func (gcp *GoogleCloudPrint) ProximityToken(gcpID, user string) ([]byte, int, error) {
form := url.Values{}
form.Set("printerid", gcpID)
form.Set("user", user)
responseBody, _, httpStatus, err := postWithRetry(gcp.robotClient, gcp.baseURL+"proximitytoken", form)
return responseBody, httpStatus, err
}
// ListPrinters calls gcp.List, then calls gcp.Printer, one goroutine per
// printer. This is a fast way to fetch all printers with corresponding CDD
// info, which the List API does not provide.
//
// The second return value is a map of GCPID -> queued print job quantity.
func (gcp *GoogleCloudPrint) ListPrinters() ([]lib.Printer, map[string]uint, error) {
ids, err := gcp.List()
if err != nil {
return nil, nil, err
}
type response struct {
printer *lib.Printer
queuedJobsCount uint
err error
}
ch := make(chan response)
for id := range ids {
go func(id string) {
printer, queuedJobsCount, err := gcp.Printer(id)
ch <- response{printer, queuedJobsCount, err}
}(id)
}
errs := make([]error, 0)
printers := make([]lib.Printer, 0, len(ids))
queuedJobsCount := make(map[string]uint)
for _ = range ids {
r := <-ch
if r.err != nil {
errs = append(errs, r.err)
continue
}
printers = append(printers, *r.printer)
if r.queuedJobsCount > 0 {
queuedJobsCount[r.printer.GCPID] = r.queuedJobsCount
}
}
if len(errs) == 0 {
return printers, queuedJobsCount, nil
} else if len(errs) == 1 {
return nil, nil, errs[0]
} else {
// Return an error that is somewhat human-readable.
b := bytes.NewBufferString(fmt.Sprintf("%d errors: ", len(errs)))
for i, err := range errs {
if i > 0 {
b.WriteString(", ")
}
b.WriteString(err.Error())
}
return nil, nil, errors.New(b.String())
}
}
// HandleJobs gets and processes jobs waiting on a printer.
func (gcp *GoogleCloudPrint) HandleJobs(printer *lib.Printer, reportJobFailed func()) {
jobs, err := gcp.Fetch(printer.GCPID)
if err != nil {
log.Errorf("Failed to fetch jobs for GCP printer %s: %s", printer.GCPID, err)
} else {
for i := range jobs {
go gcp.processJob(&jobs[i], printer, reportJobFailed)
}
}
}
// processJob performs these steps:
//
// 1) Assembles the job resources (printer, ticket, data)
// 2) Creates a new job in CUPS.
// 3) Follows up with the job state until done or error.
// 4) Deletes temporary file.
//
// Nothing is returned; intended for use as goroutine.
func (gcp *GoogleCloudPrint) processJob(job *Job, printer *lib.Printer, reportJobFailed func()) {
log.InfoJobf(job.GCPJobID, "Received from cloud")
ticket, filename, message, state := gcp.assembleJob(job)
if message != "" {
reportJobFailed()
log.ErrorJob(job.GCPJobID, message)
if err := gcp.Control(job.GCPJobID, state); err != nil {
log.ErrorJob(job.GCPJobID, err)
}
return
}
gcp.jobs <- &lib.Job{
NativePrinterName: printer.Name,
Filename: filename,
Title: job.Title,
User: job.OwnerID,
JobID: job.GCPJobID,
Ticket: ticket,
UpdateJob: gcp.Control,
}
}
// assembleJob prepares for printing a job by fetching the job's ticket and payload.
//
// The caller is responsible to remove the returned file.
//
// Errors are returned as a string (last return value), for reporting
// to GCP and local log.
func (gcp *GoogleCloudPrint) assembleJob(job *Job) (*cdd.CloudJobTicket, string, string, *cdd.PrintJobStateDiff) {
ticket, err := gcp.Ticket(job.GCPJobID)
if err != nil {
return nil, "",
fmt.Sprintf("Failed to get a ticket: %s", err),
&cdd.PrintJobStateDiff{
State: &cdd.JobState{
Type: cdd.JobStateAborted,
DeviceActionCause: &cdd.DeviceActionCause{ErrorCode: cdd.DeviceActionCauseInvalidTicket},
},
}
}
file, err := ioutil.TempFile("", "cloud-print-connector-")
if err != nil {
return nil, "",
fmt.Sprintf("Failed to create a temporary file: %s", err),
&cdd.PrintJobStateDiff{
State: &cdd.JobState{
Type: cdd.JobStateAborted,
DeviceActionCause: &cdd.DeviceActionCause{ErrorCode: cdd.DeviceActionCauseOther},
},
}
}
gcp.downloadSemaphore.Acquire()
t := time.Now()
downloadUrl := job.FileURL
if !strings.HasPrefix(downloadUrl, "http") {
// test env url need to prefix with http
downloadUrl = "http://" + job.FileURL
}
// Do not check err until semaphore is released and timer is stopped.
err = gcp.Download(file, downloadUrl)
dt := time.Since(t)
gcp.downloadSemaphore.Release()
if err != nil {
// Clean up this temporary file so the caller doesn't need extra logic.
os.Remove(file.Name())
return nil, "",
fmt.Sprintf("Failed to download data: %s", err),
&cdd.PrintJobStateDiff{
State: &cdd.JobState{
Type: cdd.JobStateAborted,
DeviceActionCause: &cdd.DeviceActionCause{ErrorCode: cdd.DeviceActionCauseDownloadFailure},
},
}
}
log.InfoJobf(job.GCPJobID, "Downloaded in %s", dt.String())
defer file.Close()
log.DebugJobf(job.GCPJobID, "Assembled with file %s: %+v", file.Name(), ticket.Print.Color)
return ticket, file.Name(), "", &cdd.PrintJobStateDiff{}
}