-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
856 lines (712 loc) · 24.2 KB
/
main.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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
package main
import (
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"sync"
"time"
"github.com/TwiN/go-color"
"github.com/go-echarts/go-echarts/v2/components"
tpls "github.com/go-echarts/go-echarts/v2/templates"
scribble "github.com/nanobox-io/golang-scribble"
"github.com/schollz/progressbar/v3"
)
var (
done chan struct{}
ch = make(chan int)
wg sync.WaitGroup
debug bool
cfg Configuration
pb progressbar.ProgressBar
ConsoleText bool
StatusRequested string
PrimaryGroup bool
)
var r, _ = regexp.Compile("\\\\|\\||-|\"|/|:|\\*|\\?|<|>|\\s+")
// MakeFilenameWindowsFriendly removes characters not permitted in file/directory names on Windows
func MakeFilenameWindowsFriendly(name string) string {
return r.ReplaceAllString(name, " ")
}
func main() {
logFile, err := os.OpenFile("log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
if err != nil {
panic(err)
}
mw := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(mw)
er := io.MultiWriter(os.Stderr, logFile)
log.SetOutput(er)
bCache := flag.Bool("cache", false, "Make Cache Data")
bConsoleText := flag.Bool("console", false, "output console text")
bDebug := flag.Bool("debug", false, "Explain whats happening while program runs")
bChart := flag.Bool("chart", false, "Generate charts and tables")
iMaxJobs := flag.Int("max", 40, "Max number of downloads concurrently")
sStatusReq := flag.String("status", "SIGNED", "Document Status")
bVerify := flag.Bool("verify", false, "Verify that files have been downloaded")
bPrimaryGroup := flag.Bool("primarygroup", false, "Download documents only for primary user group")
sHttpProxy := flag.String("proxyaddr", "", "set proxy server")
flag.Parse()
//Set Env
if len(*sHttpProxy) > 0 {
fmt.Println("Set Http Proxy to:", *sHttpProxy)
os.Setenv("HTTP_PROXY", *sHttpProxy)
os.Setenv("HTTPs_PROXY", *sHttpProxy)
os.Setenv("http_proxy", *sHttpProxy)
os.Setenv("https_proxy", *sHttpProxy)
}
fmt.Fprintf(os.Stdout, "\nAdobe Sign Document Downloader by Daniel.Rapp@Kontract.se\n")
fmt.Fprintf(os.Stdout, "\nSource: https://github.com/BilboTheGreedy/AdobeSignDocDownloader\n")
fmt.Fprintf(os.Stdout, "\nCache mode set? %v\n", *bCache)
debug = *bDebug
ConsoleText = *bConsoleText
StatusRequested = *sStatusReq
PrimaryGroup = *bPrimaryGroup
cfg = LoadConfiguration("config.json")
cfg.QueryEndpoint()
if *bVerify == true {
VerifyPaths(StatusRequested)
return
}
if *bChart == true {
GenerateStatusTable()
VerifyTable()
f, err := os.Create("charts.html")
if err != nil {
fmt.Println(err)
}
tpls.PageTpl = `
{{- define "page" }}
<!DOCTYPE html>
<html>
{{- template "header" . }}
<body>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change the link color to #111 (black) on hover */
li a:hover {
background-color: #111;
}
</style>
<ul class="nav">
<li class="nav-item">
<a class="nav-link" href="./charts.html">Charts</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./table.html">Downloaded</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./Status.html">Status</a>
</li>
</ul>
{{ if eq .Layout "none" }}
{{- range .Charts }} {{ template "base" . }} {{- end }}
{{ end }}
{{ if eq .Layout "center" }}
<style> .container {display: flex;justify-content: center;align-items: center;} .item {margin: auto;} </style>
{{- range .Charts }} {{ template "base" . }} {{- end }}
{{ end }}
{{ if eq .Layout "flex" }}
<style> .box { justify-content:center; display:flex; flex-wrap:wrap } </style>
<div class="box"> {{- range .Charts }} {{ template "base" . }} {{- end }} </div>
{{ end }}
</body>
</html>
{{ end }}
`
page := components.NewPage()
page.Theme = "vintage"
page.PageTitle = "Adobe Sign Graphs"
page.SetLayout(components.PageCenterLayout)
page.AddCharts(
GetADInfo(),
GetPieData(),
)
page.Render(io.MultiWriter(f))
return
}
cfg.QueryEndpoint()
if *bCache == true {
// create a new scribble database, providing a destination for the database to live
db, _ := scribble.New("./Data", nil)
//Query endpoint for API URI
cfg.QueryEndpoint()
//Struct to store data in
data := Data{}
//Query All groups
data.QueryGroups(cfg)
//Set up for goroutines: GROUPS/Members
groupCount := len(data.Groups.GroupInfoList)
fmt.Println("Main :", groupCount, "groups to collect data from in config")
groups := make(chan *GroupInfoList, groupCount)
done := make(chan bool, groupCount)
fmt.Println("Main : Submitting job to workers")
for i, _ := range data.Groups.GroupInfoList {
go GetGroupMembersWorker(i, cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint, groups, done)
}
for _, group := range data.Groups.GroupInfoList {
groups <- group
}
close(groups)
for i := 0; i < groupCount; i++ {
<-done
}
//Goroutine done for: GROUP/Members
//Set up for goroutines: GROUPS/Members/PRIMARY GROUP
for _, group := range data.Groups.GroupInfoList {
memberCount := len(group.GroupMembers.UserInfoList)
members := make(chan *UserInfoList, memberCount)
done := make(chan bool, groupCount)
for i, _ := range group.GroupMembers.UserInfoList {
go GetPrimaryGroupWorker(i, cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint, members, done)
}
for _, member := range group.GroupMembers.UserInfoList {
members <- member
}
close(members)
for i := 0; i < memberCount; i++ {
<-done
}
}
//Goroutine done for: GROUP/Members/PRIMARY GROUP
//Goroutine start for: USER/Agreements
for _, group := range data.Groups.GroupInfoList {
if len(group.GroupMembers.UserInfoList) != 0 {
memberCount := len(group.GroupMembers.UserInfoList)
members := make(chan *UserInfoList, memberCount)
done := make(chan bool, groupCount)
fmt.Println("Main :", memberCount, "user to collect data from in config")
for i, _ := range group.GroupMembers.UserInfoList {
//member.QueryUseAgreement(cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint)
go GetUserAgreementsWorker(i, cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint, members, done)
}
for _, member := range group.GroupMembers.UserInfoList {
members <- member
}
close(members)
for i := 0; i < memberCount; i++ {
<-done
}
}
}
for _, g := range data.Groups.GroupInfoList {
//for each member
for _, m := range g.GroupMembers.UserInfoList {
var ma = m
//Maximum of concurrent downloads at one time
//So Adobe don't lock us out
maxGoroutines := *iMaxJobs
sem := make(chan int, maxGoroutines)
//for each agreement
for i, a := range m.Agreements.UserAgreementList {
var ag = a
if a.Status == StatusRequested {
if ConsoleText != true {
pb.Add(1)
}
sem <- 1
go func(i int) {
ag.GetDocuments(ma.ID)
<-sem // removes an int from sem, allowing another to proceed
}(i)
}
}
}
}
//Save Cache to fs
for _, item := range data.Groups.GroupInfoList {
db.Write("Groups", item.GroupName, item)
}
wg.Wait()
} else { //Read from cache
db, _ := scribble.New("./Data", nil)
// Read from the cache database
groups, _ := db.ReadAll("Groups")
// iterate
c_data := Data{}
for _, group := range groups {
f := GroupInfoList{}
json.Unmarshal([]byte(group), &f)
c_data.Groups.GroupInfoList = append(c_data.Groups.GroupInfoList, &f)
}
data_agreementCount := c_data.CountAgreements(StatusRequested)
fmt.Println("Number of agreements to process:", data_agreementCount)
//bar := progressbar.Default(int64(data_agreementCount))
if ConsoleText != true {
pb = *progressbar.Default(int64(data_agreementCount))
pb.ChangeMax(data_agreementCount)
}
//for each group
for _, g := range c_data.Groups.GroupInfoList {
var ga = g
//for each member
for _, m := range g.GroupMembers.UserInfoList {
var ma = m
//Maximum of concurrent downloads at one time
//So Adobe don't lock us out
maxGoroutines := *iMaxJobs
sem := make(chan int, maxGoroutines)
//for each agreement
for i, a := range m.Agreements.UserAgreementList {
var ag = a
//Get all documents with given status and only from primary group
if a.Status == StatusRequested && ma.PrimaryGroupID == ag.GroupID && PrimaryGroup == true {
if ConsoleText != true {
pb.Add(1)
}
sem <- 1
go func(i int) {
DownloadWorker(i, cfg, ga, ma, ag, false)
<-sem // removes an int from sem, allowing another to proceed
}(i)
//Get all documents with given Status
} else if a.Status == StatusRequested && PrimaryGroup != true {
if ConsoleText != true {
pb.Add(1)
}
sem <- 1
go func(i int) {
DownloadWorker(i, cfg, ga, ma, ag, false)
<-sem // removes an int from sem, allowing another to proceed
}(i)
}
}
}
}
}
logFile.Close()
}
// Init download of document
func DownloadWorker(id int, cfg Configuration, group *GroupInfoList, User *UserInfoList, agreement *UserAgreementList, debug bool) {
if ConsoleText == true {
println(color.Colorize(color.Yellow, "Worker "+strconv.Itoa(id)+": Received job to download document:"+agreement.Name))
}
agreement.DownloadUserAgreement(cfg, group.GroupName, User.ID, User.Email)
agreement.DownloadAgreementDocuments(cfg, group.GroupName, User.ID, User.Email)
}
// Get Agreement Documents for given userID
func (data *UserAgreementList) GetDocuments(UserID string) {
GetAgreementDocuments(cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint, &data, UserID, data.ID, true)
}
// Counts the number of agreements for given Status
func (data *Data) CountAgreements(StatusRequested string) int {
var count int
for _, g := range data.Groups.GroupInfoList {
for _, m := range g.GroupMembers.UserInfoList {
for _, a := range m.Agreements.UserAgreementList {
if a.Status == StatusRequested {
count++
}
}
}
}
return count
}
// Checks if Agreement is already downloaded
func (data *UserAgreementList) IsAgreementDownloaded(cfg Configuration, GroupName string, UserID string, UserEmail string) bool {
name := MakeFilenameWindowsFriendly(data.Name) + "-Combined.pdf"
//fullPath := cfg.DownloadLocation + "\\" + GroupName + "\\" + UserEmail + "\\" + MakeFilenameWindowsFriendly(data.Name) + "(" + data.ID + ")\\"
p := filepath.Join(cfg.DownloadLocation, GroupName, UserEmail, MakeFilenameWindowsFriendly(data.Name)+" ("+data.ID+")")
completePath := filepath.Join(p, name)
if _, err := os.Stat(completePath); err == nil {
return true
} else if errors.Is(err, os.ErrNotExist) {
// path/to/whatever does *not* exist
return false
}
return false
}
// Returns path to agreement
func (data *UserAgreementList) GetAgreementPath(cfg Configuration, GroupName string, UserID string, UserEmail string) string {
name := MakeFilenameWindowsFriendly(data.Name) + "-Combined.pdf"
//fullPath := cfg.DownloadLocation + "\\" + GroupName + "\\" + UserEmail + "\\" + MakeFilenameWindowsFriendly(data.Name) + "(" + data.ID + ")\\"
p := filepath.Join(cfg.DownloadLocation, GroupName, UserEmail, MakeFilenameWindowsFriendly(data.Name)+" ("+data.ID+")")
completePath := filepath.Join(p, name)
if _, err := os.Stat(completePath); err == nil {
return completePath
} else if errors.Is(err, os.ErrNotExist) {
// path/to/whatever does *not* exist
return ""
}
return ""
}
// check if agreement is already downloaded or starts it.
func (data *UserAgreementList) DownloadUserAgreement(cfg Configuration, GroupName string, UserID string, UserEmail string) {
name := MakeFilenameWindowsFriendly(data.Name) + "-Combined.pdf"
//fullPath := cfg.DownloadLocation + "\\" + GroupName + "\\" + UserEmail + "\\" + MakeFilenameWindowsFriendly(data.Name) + "(" + data.ID + ")\\"
p := filepath.Join(cfg.DownloadLocation, GroupName, UserEmail, MakeFilenameWindowsFriendly(data.Name)+" ("+data.ID+")")
completePath := filepath.Join(p, name)
if _, err := os.Stat(completePath); err == nil {
if ConsoleText == true {
println(color.Colorize(color.Cyan, "File already exists: "+completePath))
}
} else if errors.Is(err, os.ErrNotExist) {
// path/to/whatever does *not* exist
err := DownloadAgreement(cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint, data.ID, UserID, p, name, debug)
if err != nil {
if ConsoleText == true {
println(color.Colorize(color.Red, "Download Failed: "+completePath))
}
return
} else {
if ConsoleText == true {
println(color.Colorize(color.Green, "Download Success: "+name))
}
}
} else {
// file may or may not exist. See err for details.
fmt.Println(err)
// Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence
}
}
// Download user agreement documents. Checks if they are already downloaded.
func (data *UserAgreementList) DownloadAgreementDocuments(cfg Configuration, GroupName string, UserID string, UserEmail string) {
for _, document := range data.Documents {
var completePath string
var name string
name = MakeFilenameWindowsFriendly(document.Name)
//fullPath := cfg.DownloadLocation + "\\" + GroupName + "\\" + UserEmail + "\\" + MakeFilenameWindowsFriendly(data.Name) + "(" + data.ID + ")\\"
p := filepath.Join(cfg.DownloadLocation, GroupName, UserEmail, MakeFilenameWindowsFriendly(data.Name)+" ("+data.ID+")")
extension := filepath.Ext(document.Name)
if extension == "" {
name = name + ".pdf"
}
completePath = filepath.Join(p, name)
if _, err := os.Stat(completePath); err == nil {
if ConsoleText == true {
println(color.Colorize(color.Cyan, "File already exists: "+completePath))
}
} else if errors.Is(err, os.ErrNotExist) {
// path/to/whatever does *not* exist
err := DownloadDocuments(cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint, data.ID, document.ID, UserID, p, name, debug)
if err != nil {
if ConsoleText == true {
println(color.Colorize(color.Red, "Download Failed: "+completePath))
}
return
} else {
if ConsoleText == true {
println(color.Colorize(color.Green, "Download Success: "+name))
}
}
} else {
// file may or may not exist. See err for details.
fmt.Println(err)
// Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence
}
}
}
// HTTP Get download document
func DownloadDocuments(ACCESSTOKEN string, baseUri string, AgreementID string, DocumentID string, UserID string, filePath string, fileName string, debug bool) error {
path := filePath
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
log.Println(err)
}
// Create the file
out, err := os.Create(filepath.Join(filePath, fileName))
if err != nil {
return err
}
defer out.Close()
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS10, MaxVersion: tls.VersionTLS13},
}
url := baseUri + "api/rest/v6/agreements/" + AgreementID + "/documents/" + DocumentID
if debug == true {
fmt.Println("URL:>", url)
}
for i := 0; i < 3; i++ { // try 3 times
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-user", "userid:"+UserID)
req.Header.Add("Authorization", "Bearer "+ACCESSTOKEN)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
// error occurred
println(color.Colorize(color.Yellow, "\nRetry Download Count: "+strconv.Itoa(i)) + " : " + fileName)
time.Sleep(time.Second * 10) // wait for 10 seconds
continue // retry request
}
defer resp.Body.Close()
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
break // no error or other error
}
return nil
}
// HTTP Download Agreement Combined Document
func DownloadAgreement(ACCESSTOKEN string, baseUri string, AgreementID string, UserID string, filePath string, fileName string, debug bool) error {
path := filePath
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
log.Println(err)
}
// Create the file
out, err := os.Create(filepath.Join(filePath, fileName))
if err != nil {
return err
}
defer out.Close()
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS10, MaxVersion: tls.VersionTLS13},
}
url := baseUri + "api/rest/v6/agreements/" + AgreementID + "/combinedDocument"
if debug == true {
fmt.Println("URL:>", url)
}
for i := 0; i < 3; i++ { // try 3 times
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-user", "userid:"+UserID)
req.Header.Add("Authorization", "Bearer "+ACCESSTOKEN)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
// error occurred
println(color.Colorize(color.Yellow, "\nRetry Download Count: "+strconv.Itoa(i)) + " : " + fileName)
time.Sleep(time.Second * 10) // wait for 10 seconds
continue // retry request
}
defer resp.Body.Close()
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
break // no error or other error
}
return nil
}
// Query given user for Agreements and saves them to data struct
func (data *UserInfoList) QueryUseAgreement(AccessToken string, URI string) {
GetUserAgreements(AccessToken, URI, &data.Agreements, data.ID, debug)
for _, a := range data.Agreements.UserAgreementList {
fmt.Println("Found Agreement", a.ID, "On user:", data.ID)
}
}
// Worker for getting Agreements
func GetUserAgreementsWorker(id int, AccessToken string, URI string, members <-chan *UserInfoList, done chan<- bool) {
for member := range members {
if debug != true {
fmt.Println("Worker", id, ": Received job", member.Email)
}
member.QueryUseAgreement(AccessToken, URI)
done <- true
}
}
// Gets User Documents
func GetUserDocuments(id int, AccessToken string, URI string, MemberID string, agreements <-chan *UserAgreementList, done chan<- bool) {
for agreement := range agreements {
if debug != true {
fmt.Println("Worker", id, ": Received job", MemberID)
}
agreement.GetDocuments(MemberID)
done <- true
}
}
// HTTP GET: Get Agreement Documents
func GetAgreementDocuments(ACCESSTOKEN string, baseUri string, target interface{}, UserID string, agreementID string, debug bool) error {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
url := baseUri + "api/rest/v6/agreements/" + agreementID + "/documents?pageSize=10000"
if debug == true {
fmt.Println("URL:>", url)
}
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-user", "userid:"+UserID)
req.Header.Add("Authorization", "Bearer "+ACCESSTOKEN)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(&target)
}
// HTTP GET: Get User Agreements
func GetUserAgreements(ACCESSTOKEN string, baseUri string, target interface{}, UserID string, debug bool) error {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
url := baseUri + "api/rest/v6/agreements?pageSize=10000"
if debug == true {
fmt.Println("URL:>", url)
}
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-user", "userid:"+UserID)
req.Header.Add("Authorization", "Bearer "+ACCESSTOKEN)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(&target)
}
// HTTP GET: Query Adobe Sign Endpoint
func (cfg *Configuration) QueryEndpoint() {
//GetEndpoint(cfg.Session.AccessToken, cfg)
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
url := "https://api.na1.adobesign.com/api/rest/v6/baseUris"
if debug == true {
fmt.Println("URL:>", url)
}
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+cfg.Session.AccessToken)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
json.NewDecoder(resp.Body).Decode(&cfg.Session.baseURI)
}
// HTTP GET: Query groups in Adobe Sign
func (data *Data) QueryGroups(cfg Configuration) {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
url := cfg.Session.baseURI.APIAccessPoint + "api/rest/v6/groups?pageSize=10000"
if debug == true {
fmt.Println("URL:>", url)
}
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+cfg.Session.AccessToken)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
json.NewDecoder(resp.Body).Decode(&data.Groups)
}
// Get Group members for given Group
func (data *GroupInfoList) QueryGroupMembers(AccessToken string, URI string) {
GetGroupMembers(AccessToken, URI, data.GroupID, data.GroupName, &data.GroupMembers, debug)
}
// Get Group members for given Group
func (data *UserInfoList) QueryPrimaryGroup(AccessToken string, URI string) {
res := GetPrimaryGroup(cfg.Session.AccessToken, cfg.Session.baseURI.APIAccessPoint, data.ID, false)
for _, r := range res.GroupInfoList {
if r.IsPrimaryGroup {
data.PrimaryGroupID = r.ID
}
}
}
// HTTP GET: Get Group member
func GetPrimaryGroup(AccessToken string, URI string, UserID string, debug bool) Result {
result := Result{}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
url := URI + "api/rest/v6/users/" + UserID + "/groups"
if debug == true {
fmt.Println("URL:>", url)
}
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+AccessToken)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
json.NewDecoder(resp.Body).Decode(&result)
return result
}
// HTTP GET: Get Group member
func GetGroupMembers(AccessToken string, URI string, GroupID string, GroupName string, target interface{}, debug bool) error {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
url := URI + "api/rest/v6/groups/" + GroupID + "/users?pageSize=10000"
if debug == true {
fmt.Println("URL:>", url)
}
req, err := http.NewRequest("GET", url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+AccessToken)
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(&target)
}
// GO Routine Worker func: Get Group Member
func GetGroupMembersWorker(id int, AccessToken string, URI string, groups <-chan *GroupInfoList, done chan<- bool) {
for group := range groups {
if debug != true {
fmt.Println("Worker", id, ": Received job", group.GroupName)
}
group.QueryGroupMembers(AccessToken, URI)
done <- true
}
}
func GetPrimaryGroupWorker(id int, AccessToken string, URI string, users <-chan *UserInfoList, done chan<- bool) {
for user := range users {
if debug != true {
fmt.Println("Worker", id, ": Received job PRIMARY GROUP", user.Email)
}
user.QueryPrimaryGroup(AccessToken, URI)
done <- true
}
}
// Load config.json
func LoadConfiguration(file string) Configuration {
var config Configuration
configFile, err := os.Open(file)
defer configFile.Close()
if err != nil {
fmt.Println(err.Error())
}
jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)
return config
}