-
Notifications
You must be signed in to change notification settings - Fork 22
/
cloudSync.go
executable file
·1408 lines (1179 loc) · 42.2 KB
/
cloudSync.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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package shuffle
import (
"bytes"
"net/url"
"context"
"io"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"path/filepath"
//"github.com/algolia/algoliasearch-client-go/v3/algolia/opt"
"github.com/algolia/algoliasearch-client-go/v3/algolia/search"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
//"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/storage/memory"
)
func executeCloudAction(action CloudSyncJob, apikey string) error {
data, err := json.Marshal(action)
if err != nil {
log.Printf("Failed cloud webhook action marshalling: %s", err)
return err
}
client := &http.Client{}
syncUrl := fmt.Sprintf("https://shuffler.io/api/v1/cloud/sync/handle_action")
req, err := http.NewRequest(
"POST",
syncUrl,
bytes.NewBuffer(data),
)
req.Header.Add("Authorization", fmt.Sprintf(`Bearer %s`, apikey))
newresp, err := client.Do(req)
if err != nil {
return err
}
defer newresp.Body.Close()
respBody, err := ioutil.ReadAll(newresp.Body)
if err != nil {
return err
}
type Result struct {
Success bool `json:"success"`
Reason string `json:"reason"`
}
//log.Printf("Data: %s", string(respBody))
responseData := Result{}
err = json.Unmarshal(respBody, &responseData)
if err != nil {
return err
}
if !responseData.Success {
return errors.New(fmt.Sprintf("Cloud error from Shuffler: %s", responseData.Reason))
}
return nil
}
func HandleAlgoliaAppSearch(ctx context.Context, appname string) (AlgoliaSearchApp, error) {
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return AlgoliaSearchApp{}, errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("appsearch")
appname = strings.TrimSpace(strings.ToLower(strings.Replace(appname, "_", " ", -1)))
res, err := algoliaIndex.Search(appname)
if err != nil {
log.Printf("[WARNING] Failed searching Algolia: %s", err)
return AlgoliaSearchApp{}, err
}
var newRecords []AlgoliaSearchApp
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia: %s", err)
return AlgoliaSearchApp{}, err
}
//log.Printf("[INFO] Algolia hits for '%s': %d", appname, len(newRecords))
for _, newRecord := range newRecords {
newApp := strings.TrimSpace(strings.ToLower(strings.Replace(newRecord.Name, "_", " ", -1)))
if newApp == appname || newRecord.ObjectID == appname {
//return newRecord.ObjectID, nil
return newRecord, nil
}
}
// Second try with contains
for _, newRecord := range newRecords {
newApp := strings.TrimSpace(strings.ToLower(strings.Replace(newRecord.Name, "_", " ", -1)))
if strings.Contains(newApp, appname) {
return newRecord, nil
}
}
return AlgoliaSearchApp{}, nil
}
func HandleAlgoliaWorkflowSearchByApp(ctx context.Context, appname string) ([]AlgoliaSearchWorkflow, error) {
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return []AlgoliaSearchWorkflow{}, errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("workflows")
appSearch := fmt.Sprintf("%s", appname)
res, err := algoliaIndex.Search(appSearch)
if err != nil {
log.Printf("[WARNING] Failed app searching Algolia for creators: %s", err)
return []AlgoliaSearchWorkflow{}, err
}
var newRecords []AlgoliaSearchWorkflow
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia with app creators: %s", err)
return []AlgoliaSearchWorkflow{}, err
}
//log.Printf("[INFO] Algolia hits for %s: %d", appSearch, len(newRecords))
allRecords := []AlgoliaSearchWorkflow{}
for _, newRecord := range newRecords {
allRecords = append(allRecords, newRecord)
}
return allRecords, nil
}
func HandleAlgoliaWorkflowSearchByUser(ctx context.Context, userId string) ([]AlgoliaSearchWorkflow, error) {
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return []AlgoliaSearchWorkflow{}, errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("workflows")
appSearch := fmt.Sprintf("%s", userId)
res, err := algoliaIndex.Search(appSearch)
if err != nil {
log.Printf("[WARNING] Failed app searching Algolia for creators: %s", err)
return []AlgoliaSearchWorkflow{}, err
}
var newRecords []AlgoliaSearchWorkflow
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia with app creators: %s", err)
return []AlgoliaSearchWorkflow{}, err
}
//log.Printf("[INFO] Algolia hits for %s: %d", appSearch, len(newRecords))
allRecords := []AlgoliaSearchWorkflow{}
for _, newRecord := range newRecords {
allRecords = append(allRecords, newRecord)
}
return allRecords, nil
}
func HandleAlgoliaAppSearchByUser(ctx context.Context, userId string) ([]AlgoliaSearchApp, error) {
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return []AlgoliaSearchApp{}, errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("appsearch")
appSearch := fmt.Sprintf("%s", userId)
res, err := algoliaIndex.Search(appSearch)
if err != nil {
log.Printf("[WARNING] Failed app searching Algolia for creators: %s", err)
return []AlgoliaSearchApp{}, err
}
var newRecords []AlgoliaSearchApp
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia with app creators: %s", err)
return []AlgoliaSearchApp{}, err
}
//log.Printf("[INFO] Algolia hits for %s: %d", appSearch, len(newRecords))
allRecords := []AlgoliaSearchApp{}
for _, newRecord := range newRecords {
newAppName := strings.TrimSpace(strings.Replace(newRecord.Name, "_", " ", -1))
newRecord.Name = newAppName
allRecords = append(allRecords, newRecord)
}
return allRecords, nil
}
func HandleAlgoliaCreatorSearch(ctx context.Context, username string) (AlgoliaSearchCreator, error) {
tmpUsername, err := url.QueryUnescape(username)
if err == nil {
username = tmpUsername
}
if strings.HasPrefix(username, "@") {
username = strings.Replace(username, "@", "", 1)
}
username = strings.ToLower(strings.TrimSpace(username))
cacheKey := fmt.Sprintf("algolia_creator_%s", username)
searchCreator := AlgoliaSearchCreator{}
cache, err := GetCache(ctx, cacheKey)
if err == nil {
cacheData := []byte(cache.([]uint8))
//log.Printf("CACHE: %d", len(cacheData))
//log.Printf("CACHEDATA: %#v", cacheData)
err = json.Unmarshal(cacheData, &searchCreator)
if err == nil {
return searchCreator, nil
}
}
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return searchCreator, errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("creators")
res, err := algoliaIndex.Search(username)
if err != nil {
log.Printf("[WARNING] Failed searching Algolia creators: %s", err)
return searchCreator, err
}
var newRecords []AlgoliaSearchCreator
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia creators: %s", err)
return searchCreator, err
}
//log.Printf("RECORDS: %d", len(newRecords))
foundUser := AlgoliaSearchCreator{}
for _, newRecord := range newRecords {
if strings.ToLower(newRecord.Username) == strings.ToLower(username) || newRecord.ObjectID == username || ArrayContainsLower(newRecord.Synonyms, username) {
foundUser = newRecord
break
}
}
// Handling search within a workflow, and in the future, within apps
if len(foundUser.ObjectID) == 0 {
if len(username) == 36 {
// Check workflows
algoliaIndex := algClient.InitIndex("workflows")
res, err := algoliaIndex.Search(username)
if err != nil {
log.Printf("[WARNING] Failed searching Algolia creator workflow: %s", err)
return searchCreator, err
}
var newRecords []AlgoliaSearchWorkflow
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia creator workflow: %s", err)
if len(newRecords) > 0 && len(newRecords[0].ObjectID) > 0 {
log.Printf("[INFO] Workflow search ID: %#v", newRecords[0].ObjectID)
} else {
return searchCreator, err
}
}
//log.Printf("[DEBUG] Got %d records for workflow sub", len(newRecords))
if len(newRecords) == 1 {
if len(newRecords[0].Creator) > 0 && username != newRecords[0].Creator {
foundCreator, err := HandleAlgoliaCreatorSearch(ctx, newRecords[0].Creator)
if err != nil {
return searchCreator, err
}
foundUser = foundCreator
} else {
return searchCreator, errors.New("User not found")
}
} else {
return searchCreator, errors.New("User not found")
}
} else {
return searchCreator, errors.New("User not found")
}
}
if project.CacheDb {
data, err := json.Marshal(foundUser)
if err != nil {
return foundUser, nil
}
err = SetCache(ctx, cacheKey, data, 30)
if err != nil {
log.Printf("[WARNING] Failed updating algolia username cache: %s", err)
}
}
return foundUser, nil
}
func HandleAlgoliaCreatorUpload(ctx context.Context, user User, overwrite bool, isOrg bool) (string, error) {
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return "", errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("creators")
res, err := algoliaIndex.Search(user.Id)
if err != nil {
log.Printf("[WARNING] Failed searching Algolia creators: %s", err)
return "", err
}
var newRecords []AlgoliaSearchCreator
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia creators: %s", err)
return "", err
}
//log.Printf("RECORDS: %d", len(newRecords))
for _, newRecord := range newRecords {
if newRecord.ObjectID == user.Id {
log.Printf("[INFO] Object %s already exists in Algolia", user.Id)
if overwrite {
break
} else {
return user.Id, errors.New("User ID already exists!")
}
}
}
timeNow := int64(time.Now().Unix())
records := []AlgoliaSearchCreator{
AlgoliaSearchCreator{
ObjectID: user.Id,
TimeEdited: timeNow,
Image: user.PublicProfile.GithubAvatar,
Username: user.PublicProfile.GithubUsername,
IsOrg: isOrg,
},
}
_, err = algoliaIndex.SaveObjects(records)
if err != nil {
log.Printf("[WARNING] Algolia Object put err: %s", err)
return "", err
}
log.Printf("[INFO] SUCCESSFULLY UPLOADED creator %s with ID %s TO ALGOLIA!", user.Username, user.Id)
return user.Id, nil
}
func HandleAlgoliaCreatorDeletion(ctx context.Context, userId string) (error) {
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("creators")
res, err := algoliaIndex.Search(userId)
if err != nil {
log.Printf("[WARNING] Failed searching Algolia creators: %s", err)
return err
}
var newRecords []AlgoliaSearchCreator
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia creators: %s", err)
return err
}
//log.Printf("RECORDS: %d", len(newRecords))
foundItem := AlgoliaSearchCreator{}
for _, newRecord := range newRecords {
if newRecord.ObjectID == userId {
foundItem = newRecord
break
}
}
// Should delete it?
if len(foundItem.ObjectID) > 0 {
_, err = algoliaIndex.DeleteObject(foundItem.ObjectID)
if err != nil {
log.Printf("[WARNING] Algolia Creator delete problem: %s", err)
return err
}
log.Printf("[INFO] Successfully removed creator %s with ID %s FROM ALGOLIA!", foundItem.Username, userId)
}
return nil
}
// Shitty temorary system
// Adding schedule to run over with another algorithm
// as well as this one, as to increase priority based on popularity:
// searches, clicks & conversions (CTR)
func GetWorkflowPriority(workflow Workflow) int {
prio := 0
if len(workflow.Tags) > 2 {
prio += 1
}
if len(workflow.Name) > 5 {
prio += 1
}
if len(workflow.Description) > 100 {
prio += 1
}
if len(workflow.WorkflowType) > 0 {
prio += 1
}
if len(workflow.UsecaseIds) > 0 {
prio += 3
}
if len(workflow.Comments) >= 2 {
prio += 2
}
return prio
}
func handleAlgoliaWorkflowUpdate(ctx context.Context, workflow Workflow) (string, error) {
log.Printf("[INFO] Should try to UPLOAD the Workflow to Algolia")
algoliaClient := os.Getenv("ALGOLIA_CLIENT")
algoliaSecret := os.Getenv("ALGOLIA_SECRET")
if len(algoliaClient) == 0 || len(algoliaSecret) == 0 {
log.Printf("[WARNING] ALGOLIA_CLIENT or ALGOLIA_SECRET not defined")
return "", errors.New("Algolia keys not defined")
}
algClient := search.NewClient(algoliaClient, algoliaSecret)
algoliaIndex := algClient.InitIndex("workflows")
//res, err := algoliaIndex.Search("%s", api.ID)
res, err := algoliaIndex.Search(workflow.ID)
if err != nil {
log.Printf("[WARNING] Failed searching Algolia: %s", err)
return "", err
}
var newRecords []AlgoliaSearchWorkflow
err = res.UnmarshalHits(&newRecords)
if err != nil {
log.Printf("[WARNING] Failed unmarshaling from Algolia workflow upload: %s", err)
return "", err
}
found := false
record := AlgoliaSearchWorkflow{}
for _, newRecord := range newRecords {
if newRecord.ObjectID == workflow.ID {
log.Printf("[INFO] Workflow Object %s already exists in Algolia", workflow.ID)
record = newRecord
found = true
break
}
}
if !found {
return "", errors.New(fmt.Sprintf("Couldn't find public workflow for ID %s", workflow.ID))
}
record.TimeEdited = int64(time.Now().Unix())
categories := []string{}
actions := []string{}
triggers := []string{}
actionRefs := []ActionReference{}
for _, action := range workflow.Actions {
if !ArrayContains(actions, action.AppName) {
// Using this API as the original is kinda stupid
foundApps, err := HandleAlgoliaAppSearchByUser(ctx, action.AppName)
if err == nil && len(foundApps) > 0 {
actionRefs = append(actionRefs, ActionReference{
Name: foundApps[0].Name,
Id: foundApps[0].ObjectID,
ImageUrl: foundApps[0].ImageUrl,
ActionName: []string{action.Name},
})
}
actions = append(actions, action.AppName)
} else {
for refIndex, ref := range actionRefs {
if ref.Name == action.AppName {
if !ArrayContains(ref.ActionName, action.Name) {
actionRefs[refIndex].ActionName = append(actionRefs[refIndex].ActionName, action.Name)
}
}
}
}
}
for _, trigger := range workflow.Triggers {
if !ArrayContains(triggers, trigger.TriggerType) {
triggers = append(triggers, trigger.TriggerType)
}
}
if workflow.WorkflowType != "" {
record.Type = workflow.WorkflowType
}
record.Name = workflow.Name
record.Description = workflow.Description
record.UsecaseIds = workflow.UsecaseIds
record.Triggers = triggers
record.Actions = actions
record.TriggerAmount = len(triggers)
record.ActionAmount = len(actions)
record.Tags = workflow.Tags
record.Categories = categories
record.ActionReferences = actionRefs
record.Priority = GetWorkflowPriority(workflow)
record.Validated = workflow.Validated
records := []AlgoliaSearchWorkflow{
record,
}
//log.Printf("[WARNING] Returning before upload with data %#v", records)
//return records[0].ObjectID, nil
//return "", errors.New("Not prepared yet!")
_, err = algoliaIndex.SaveObjects(records)
if err != nil {
log.Printf("[WARNING] Algolia Object update err: %s", err)
return "", err
}
return workflow.ID, nil
}
// Returns an error if the users' org is over quota
func ValidateExecutionUsage(ctx context.Context, orgId string) (*Org, error) {
if len(orgId) == 0 {
return nil, errors.New("Org ID is empty")
}
org, err := GetOrg(ctx, orgId)
if err != nil {
return org, errors.New(fmt.Sprintf("Failed getting the organization %s: %s", orgId, err))
}
// Allows parent & childorgs to run as much as they want. No limitations
if len(org.ChildOrgs) > 0 || len(org.ManagerOrgs) > 0 {
//log.Printf("[DEBUG] Execution for org '%s' (%s) is allowed due to being a child-or parent org. This is only accessible to customers. We're not force-stopping them.", org.Name, org.Id)
return org, nil
}
info, err := GetOrgStatistics(ctx, orgId)
if err == nil {
//log.Printf("[DEBUG] Found executions for org %s (%s): %d", org.Name, org.Id, info.MonthlyAppExecutions)
org.SyncFeatures.AppExecutions.Usage = info.MonthlyAppExecutions
if org.SyncFeatures.AppExecutions.Limit <= 10000 {
org.SyncFeatures.AppExecutions.Limit = 10000
} else {
// FIXME: Not strictly enforcing other limits yet
// Should just warn our team about them going over
org.SyncFeatures.AppExecutions.Limit = 15000000000
}
//log.Printf("[DEBUG] Org %s (%s) has values: org.LeadInfo.POV: %v, org.LeadInfo.Internal: %v", org.Name, org.Id, org.LeadInfo.POV, org.LeadInfo.Internal)
// FIXME: When inside this, check if usage should be sent to the user
// if (org.SyncFeatures.AppExecutions.Usage > org.SyncFeatures.AppExecutions.Limit) && !(org.LeadInfo.POV || org.LeadInfo.Internal) {
if (org.SyncFeatures.AppExecutions.Usage > org.SyncFeatures.AppExecutions.Limit) && !(org.LeadInfo.POV) {
return org, errors.New(fmt.Sprintf("You are above your limited usage of app executions this month (%d / %d) when running with triggers. Contact support@shuffler.io or the live chat to extend this for org %s (%s)", org.SyncFeatures.AppExecutions.Usage, org.SyncFeatures.AppExecutions.Limit, org.Name, org.Id))
}
return org, nil
} else {
//log.Printf("[WARNING] Failed finding executions for org %s (%s)", org.Name, org.Id)
}
return org, nil
}
func RunActionAI(resp http.ResponseWriter, request *http.Request) {
cors := HandleCors(resp, request)
if cors {
return
}
user, err := HandleApiAuthentication(resp, request)
if err != nil {
log.Printf("[AUDIT] Api authentication failed in get action AI: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
ctx := GetContext(request)
org, err := GetOrg(ctx, user.ActiveOrg.Id)
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed getting the organization`)))
return
}
log.Printf("[DEBUG] Running action AI for org %s (%s). Cloud sync: %#v and %#v", org.Name, org.Id, org.CloudSyncActive, org.CloudSync)
if !org.CloudSync {
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Cloud sync is not active for this organization"}`)))
return
}
// For now, just redirecting
log.Printf("[DEBUG] Redirecting Action AI request to main site handler (shuffler.io)")
// Add api-key from the org sync
if org.SyncConfig.Apikey != "" {
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", org.SyncConfig.Apikey))
// Remove cookie header after checking if it exists
if request.Header.Get("Cookie") != "" {
request.Header.Del("Cookie")
}
}
RedirectUserRequest(resp, request)
return
}
func RedirectUserRequest(w http.ResponseWriter, req *http.Request) {
proxyScheme := "https"
proxyHost := fmt.Sprintf("shuffler.io")
httpClient := &http.Client{
Timeout: 120 * time.Second,
}
//fmt.Fprint(resp, "OK")
//http.Redirect(resp, request, "https://europe-west2-shuffler.cloudfunctions.net/ShuffleSSR", 303)
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("[ERROR] Issue in SSR body proxy: %s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//req.Body = ioutil.NopCloser(bytes.NewReader(body))
url := fmt.Sprintf("%s://%s%s", proxyScheme, proxyHost, req.RequestURI)
//log.Printf("[DEBUG] Request (%s) request URL: %s. More: %s", req.Method, url, req.URL.String())
proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body))
if err != nil {
log.Printf("[ERROR] Failed handling proxy request: %s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// We may want to filter some headers, otherwise we could just use a shallow copy
proxyReq.Header = make(http.Header)
for h, val := range req.Header {
proxyReq.Header[h] = val
}
newresp, err := httpClient.Do(proxyReq)
if err != nil {
log.Printf("[ERROR] Issue in SSR newresp for %s - should retry: %s", url, err)
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer newresp.Body.Close()
urlbody, err := ioutil.ReadAll(newresp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
//log.Printf("RESP: %s", urlbody)
for key, value := range newresp.Header {
//log.Printf("%s %s", key, value)
for _, item := range value {
w.Header().Set(key, item)
}
}
w.WriteHeader(newresp.StatusCode)
w.Write(urlbody)
// Need to clear cache in case user gets updated in db
// with a new session and such. This only forces a new search,
// and shouldn't get them logged out
ctx := GetContext(req)
c, err := req.Cookie("session_token")
if err != nil {
c, err = req.Cookie("__session")
}
if err == nil {
DeleteCache(ctx, fmt.Sprintf("session_%s", c.Value))
}
}
// Checks if a specific user should have "self" access to a creator user
// A creator user can be both a user and an org, so this got a bit tricky
func CheckCreatorSelfPermission(ctx context.Context, requestUser, creatorUser User, algoliaUser *AlgoliaSearchCreator) bool {
if project.Environment != "cloud" {
return false
}
if creatorUser.Id == requestUser.Id {
return true
} else {
for _, user := range algoliaUser.Synonyms {
if user == requestUser.Id {
return true
}
}
if algoliaUser.IsOrg {
log.Printf("[AUDIT] User %s (%s) is an org. Checking if the current user should have access.", algoliaUser.Username, algoliaUser.ObjectID)
// Get the org and check
org, err := GetOrgByCreatorId(ctx, algoliaUser.ObjectID)
if err != nil {
log.Printf("[WARNING] Couldn't find org for creator %s (%s): %s", algoliaUser.Username, algoliaUser.ObjectID, err)
return false
}
log.Printf("[AUDIT] Found org %s (%s) for creator %s (%s)", org.Name, org.Id, algoliaUser.Username, algoliaUser.ObjectID)
for _, user := range org.Users {
if user.Id == requestUser.Id {
if user.Role == "admin" {
return true
}
break
}
}
}
}
return false
}
// Uploads updates for a workflow to a specific file on git
func SetGitWorkflow(ctx context.Context, workflow Workflow, org *Org) error {
if workflow.BackupConfig.UploadRepo != "" || workflow.BackupConfig.UploadBranch != "" || workflow.BackupConfig.UploadUsername != "" || workflow.BackupConfig.UploadToken != "" {
//log.Printf("\n\n\n[DEBUG] Using workflow backup config for org %s (%s)\n\n\n", org.Name, org.Id)
org.Defaults.WorkflowUploadRepo = workflow.BackupConfig.UploadRepo
org.Defaults.WorkflowUploadBranch = workflow.BackupConfig.UploadBranch
org.Defaults.WorkflowUploadUsername = workflow.BackupConfig.UploadUsername
org.Defaults.WorkflowUploadToken = workflow.BackupConfig.UploadToken
// FIXME: Decrypt here
if workflow.BackupConfig.TokensEncrypted {
log.Printf("\n\n[DEBUG] Should realtime decrypt token for org %s (%s)\n\n", org.Name, org.Id)
org.Defaults.TokensEncrypted = true
} else {
org.Defaults.TokensEncrypted = false
}
}
if org.Defaults.TokensEncrypted == true {
log.Printf("\n\n[DEBUG] Decrypting token for org %s (%s)\n\n", org.Name, org.Id)
parsedKey := fmt.Sprintf("%s_upload_token", org.Id)
newValue, err := HandleKeyDecryption([]byte(org.Defaults.WorkflowUploadToken), parsedKey)
if err != nil {
log.Printf("[ERROR] Failed decrypting token for org %s (%s): %s", org.Name, org.Id, err)
} else {
org.Defaults.WorkflowUploadToken = string(newValue)
}
parsedKey = fmt.Sprintf("%s_upload_username", org.Id)
newValue, err = HandleKeyDecryption([]byte(org.Defaults.WorkflowUploadUsername), parsedKey)
if err != nil {
log.Printf("[ERROR] Failed decrypting username for org %s (%s): %s", org.Name, org.Id, err)
} else {
org.Defaults.WorkflowUploadUsername = string(newValue)
}
parsedKey = fmt.Sprintf("%s_upload_repo", org.Id)
newValue, err = HandleKeyDecryption([]byte(org.Defaults.WorkflowUploadRepo), parsedKey)
if err != nil {
log.Printf("[ERROR] Failed decrypting repo for org %s (%s): %s", org.Name, org.Id, err)
} else {
org.Defaults.WorkflowUploadRepo = string(newValue)
}
parsedKey = fmt.Sprintf("%s_upload_branch", org.Id)
newValue, err = HandleKeyDecryption([]byte(org.Defaults.WorkflowUploadBranch), parsedKey)
if err != nil {
log.Printf("[ERROR] Failed decrypting branch for org %s (%s): %s", org.Name, org.Id, err)
} else {
org.Defaults.WorkflowUploadBranch = string(newValue)
}
log.Printf("[DEBUG] Decrypted token for org %s (%s): %s", org.Name, org.Id, newValue)
}
if len(org.Defaults.WorkflowUploadBranch) == 0 {
org.Defaults.WorkflowUploadBranch = "master"
}
if org.Defaults.WorkflowUploadRepo == "" || org.Defaults.WorkflowUploadToken == "" {
//log.Printf("[DEBUG] Missing Repo/Token during Workflow backup upload for org %s (%s)", org.Name, org.Id)
//return errors.New("Missing repo or token")
return nil
}
org.Defaults.WorkflowUploadRepo = strings.TrimSpace(org.Defaults.WorkflowUploadRepo)
if strings.HasPrefix(org.Defaults.WorkflowUploadRepo, "https://") {
org.Defaults.WorkflowUploadRepo = strings.Replace(org.Defaults.WorkflowUploadRepo, "https://", "", 1)
org.Defaults.WorkflowUploadRepo = strings.Replace(org.Defaults.WorkflowUploadRepo, "http://", "", 1)
}
if strings.HasSuffix(org.Defaults.WorkflowUploadRepo, ".git") {
org.Defaults.WorkflowUploadRepo = strings.TrimSuffix(org.Defaults.WorkflowUploadRepo, ".git")
}
//log.Printf("[DEBUG] Uploading workflow %s to repo %s for org %s (%s)", workflow.ID, org.Defaults.WorkflowUploadRepo, org.Name, org.Id)
// Remove images
workflow.Image = ""
for actionIndex, _ := range workflow.Actions {
workflow.Actions[actionIndex].LargeImage = ""
workflow.Actions[actionIndex].SmallImage = ""
}
for triggerIndex, _ := range workflow.Triggers {
workflow.Triggers[triggerIndex].LargeImage = ""
workflow.Triggers[triggerIndex].SmallImage = ""
}
// Use git to upload the workflow.
workflowData, err := json.MarshalIndent(workflow, "", " ")
if err != nil {
log.Printf("[ERROR] Failed marshalling workflow %s (%s) for git upload: %s", workflow.Name, workflow.ID, err)
return err
}
commitMessage := fmt.Sprintf("User '%s' updated workflow '%s' with status '%s'", workflow.UpdatedBy, workflow.Name, workflow.Status)
location := fmt.Sprintf("https://%s:%s@%s.git", org.Defaults.WorkflowUploadUsername, org.Defaults.WorkflowUploadToken, org.Defaults.WorkflowUploadRepo)
log.Printf("[DEBUG] Uploading workflow %s to repo: %s", workflow.ID, strings.Replace(location, org.Defaults.WorkflowUploadToken, "****", -1))
fs := memfs.New()
if len(workflow.Status) == 0 {
workflow.Status = "test"
}
//filePath := fmt.Sprintf("/%s/%s.json", workflow.Status, workflow.ID)
filePath := fmt.Sprintf("%s/%s/%s_%s.json", workflow.ExecutingOrg.Id, workflow.Status, strings.ReplaceAll(workflow.Name, " ", "-"), workflow.ID)
// Specify the file path within the repository
repo, err := git.Clone(memory.NewStorage(), fs, &git.CloneOptions{
URL: location,
})
// Initialize a new Git repository in memory
w := &git.Worktree{}
if err != nil {
log.Printf("[ERROR] Error cloning repo (workflow backup): %s", err)
return err
}
// Create a new commit with the in-memory file
w, err = repo.Worktree()
if err != nil {
log.Printf("[ERROR] Error getting worktree (2): %s", err)
return err
}
// Write the byte blob to the in-memory file system
file, err := fs.Create(filePath)
if err != nil {
log.Printf("[ERROR] Creating file: %v", err)
return err
}
defer file.Close()
//_, err = io.Copy(file, bytes.NewReader(workflowData))
_, err = io.Copy(file, bytes.NewReader(workflowData))
if err != nil {
log.Printf("[ERROR] Writing data to file: %v", err)
return err
}
// Add the file to the staging area
_, err = w.Add(filePath)
if err != nil {
log.Printf("[ERROR] Error adding file to staging area (2): %s", err)
return err
}
// Commit the changes
_, err = w.Commit(commitMessage, &git.CommitOptions{
Author: &object.Signature{
Name: org.Defaults.WorkflowUploadUsername,
Email: "",
When: time.Now(),
},
})
if err != nil {
log.Printf("[ERROR] Committing changes: %v (2)", err)
return err
}
//log.Printf("[DEBUG] Commit Hash: %s", commit)
// Push the changes to a remote repository (replace URL with your repository URL)
// fmt.Sprintf("refs/heads/%s:refs/heads/%s", org.Defaults.WorkflowUploadBranch, org.Defaults.WorkflowUploadBranch)},
ref := fmt.Sprintf("refs/heads/%s:refs/heads/%s", org.Defaults.WorkflowUploadBranch, org.Defaults.WorkflowUploadBranch)
err = repo.Push(&git.PushOptions{
RemoteName: "origin",
RefSpecs: []config.RefSpec{config.RefSpec(ref)},
RemoteURL: location,
})
if err != nil {
log.Printf("[ERROR] Change Push issue: %v (2)", err)
return err
}
log.Println("[DEBUG] File uploaded successfully!")
return nil
}
// Creates osfs from folderpath with a basepath as directory base
func CreateFs(basepath, pathname string) (billy.Filesystem, error) {
log.Printf("[INFO] MemFS base: %s, pathname: %s", basepath, pathname)
fs := memfs.New()
err := filepath.Walk(pathname,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.Contains(path, ".git") {
return nil
}
// Fix the inner path here