This repository has been archived by the owner on Apr 1, 2024. It is now read-only.
forked from peckjon/github-to-guru
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1267 lines (1161 loc) · 38.9 KB
/
index.js
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
"use strict";
const axios = require(`axios`);
const fs = require(`fs-extra`);
const tmp = require(`tmp`);
const yaml = require("yaml");
const core = require(`@actions/core`);
const exec = require("@actions/exec");
const github = require(`@actions/github`);
const querystring = require("querystring");
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const { Z_ASCII } = require("zlib");
async function getCollection(auth, collectionId) {
console.log(`collection: ${collectionId}`);
return axios.get(
`https://api.getguru.com/api/v1/collections/` + collectionId,
{
auth: auth
}
);
}
async function apiSendSynchedCollection(sourceDir, auth, collectionId) {
let options = {};
options.cwd = sourceDir;
await exec.exec(`zip`, [`-r`, `guru_collection.zip`, `./`], options);
if (process.env.DEBUG) {
console.log(
`DEBUG mode: not deploying ${sourceDir}/guru_collection.zip to https://api.getguru.com/app/contentsyncupload?collectionId=${collectionId}`
);
} else {
await exec.exec(
`curl -u ${auth.username}:${auth.password} https://api.getguru.com/app/contentsyncupload?collectionId=${collectionId} -F "file=@${sourceDir}/guru_collection.zip" -D -`
);
}
}
function getInclusiveRange(array) {
// Exit early if there's nothing to get a range for
if (array.length === 0 || array == undefined) {
return
}
// Validate edge/start
let start = array[0]
let edge = array[1];
let step = 1;
// Create array of numbers, stopping before the edge
let arr = [];
for (arr; (edge - start) * step > 0; start += step) {
arr.push(start);
}
// Include the tail-edge of the array
arr.push(edge);
return arr;
}
function getCodeBlockLinesToSkip(splitContentArray) {
let codeBlockRegex = /^`{3}$/
let inclusiveArrayRanges = []
// get all the indices where we see triple-backticks at the start of a line
// eg. [13, 19, 45, 47, 99, 103]
let codeBlockIndices = splitContentArray.map((line, index) => {
if (codeBlockRegex.test(line)) {
return index
}
}).filter(index => Number.isInteger(index));
// exit function if nothing found
if (codeBlockIndices.length === undefined || codeBlockIndices.length === 0) {
return
}
// create an array of arrays consisting of index pairs, demarking the start of a code block and its end
// eg. [[13, 19], [45, 47], [99 - 103]]
let indexPairsToSkip = codeBlockIndices.reduce((result, value, index, array) => {
if (index % 2 === 0)
result.push(array.slice(index, index + 2));
return result;
}, []);
// create an array of arrays consisting of the ranges based on the index pairs
// eg. [[13, 14, 15, 16, 17, 18, 19], [45, 46, 47], [99, 100, 101, 102, 103]]
for (let i = 0; i < indexPairsToSkip.length; i++) {
let inclusiveRange = getInclusiveRange(indexPairsToSkip[i])
inclusiveArrayRanges.push(inclusiveRange)
}
return inclusiveArrayRanges
}
function arrayIncludesElement(array, element) {
// checks if an element is inside of an array and returns true if found
// eg. [[13, 14, 15, 16, 17, 18, 19], [45, 46, 47], [99, 100, 101, 102, 103]]
return array.some(row => row.includes(element))
}
function getH2ContentKeyMap(content) {
// take the content and split it off into sub-content based on the H2 tag
let h2ContentKeyMap = []
let tagAndContentIndicesList = []
let contentIndexAndTagList = []
let contentIndexAndH2TitleMap = []
let splitContentArray = content.split(/\r?\n/);
let lastContentLineNumber
let h2Regex = /^## \w+/;
let skipIndex
let codeBlockLinesToSkip = getCodeBlockLinesToSkip(splitContentArray)
console.log("CODE BLOCK LINES TO SKIP", codeBlockLinesToSkip)
splitContentArray.map((line, index) => {
// if there are code blocks in the content, we'll want to skip over their lines when getting the H2ContentKeyMap
if (codeBlockLinesToSkip !== undefined) {
skipIndex = arrayIncludesElement(codeBlockLinesToSkip, index)
}
console.log("Skip index", skipIndex)
if (h2Regex.test(line) && (skipIndex == false)) {
console.log("MAP")
// if we run into an H2, map line number to the h2 content eg. [{83: "## Title"}, {98: "## Title2"}]
contentIndexAndH2TitleMap.push({
[index]: line
})
// also map corresponding unique tag to line number eg. [{84: "aljd1j312412j3421"}, {99: "10293daf210adg9124"}]
let h2Tag = splitContentArray[index + 1].split(" ").slice(-1)[0]
contentIndexAndTagList.push({
[index + 1]: h2Tag
})
}
// store the last line in the content that is not the parent UUID and breakline
if (splitContentArray.length - 3 === index) {
lastContentLineNumber = index
}
})
// map h2 tag to content line numbers eg. x = [{ ["10293daf210adg9124"]: [83: 97]}, {["aljd1j312412j3421"]: [98: 101]}]
contentIndexAndTagList.map((lineAndTag, index) => {
let tag = Object.values(lineAndTag)
let firstLineNumber = parseInt(Object.keys(contentIndexAndH2TitleMap[index]))
let lastLineNumber
if (index !== contentIndexAndTagList.length - 1) {
lastLineNumber = Object.keys(contentIndexAndTagList[index+1]) - 1
tagAndContentIndicesList.push({
[tag]: [firstLineNumber, lastLineNumber]
})
} else {
tagAndContentIndicesList.push({
[tag]: [firstLineNumber, lastContentLineNumber]
})
}
})
// then we want to create a map of the actual content to the ky
// eg. y = [{ 10293daf210adg9124: "i am the content" }, {aljd1j312412j3421: "I am some more content"}]
tagAndContentIndicesList.map((tagAndLines, index) => {
let tag = Object.keys(tagAndLines)
let h2Indices = Object.values(tagAndLines)
let h2Content = splitContentArray.slice(h2Indices[0][0], h2Indices[0][1]).join('\n')
let tagMap = {}
tagMap[tag] = h2Content
h2ContentKeyMap.push(tagMap)
})
return {
h2ContentKeyMap: h2ContentKeyMap,
contentIndexAndH2TitleMap: contentIndexAndH2TitleMap
}
}
function getH2ContentForKey(h2ContentKeyMap, uniqueTagValue) {
for (let i = 0; i < h2ContentKeyMap.length; i++) {
let tag = Object.keys(h2ContentKeyMap[i])
if (tag.includes(uniqueTagValue)){
return h2ContentKeyMap[i][uniqueTagValue]
}
}
}
function splitCardFilename(cardFilename) {
// given a cardFilename, split it into
// board group, board, board section, card name
// depending on the number of slashes
console.log(`Splitting the cardFilename ${cardFilename} by slash...`)
let cardPathArray = cardFilename.split("/")
let cardPaths = {}
switch (cardPathArray.length) {
case 1:
console.log(`Only found a cardName ${cardPathArray[0]}`)
cardPaths[`cardName`] = cardPathArray[0]
return cardPaths
case 2:
console.log(`Found boardName ${cardPathArray[1]} and cardName ${cardPathArray[0]}`)
cardPaths[`boardName`] = cardPathArray[0]
cardPaths[`cardName`] = cardPathArray[1]
return cardPaths
case 3:
console.log(`Found boardGroupName ${cardPathArray[0]}, boardName ${cardPathArray[1]} and cardName ${cardPathArray[2]}`)
cardPaths[`boardGroupName`] = cardPathArray[0]
cardPaths[`boardName`] = cardPathArray[1]
cardPaths[`cardName`] = cardPathArray[2]
return cardPaths
case 4:
console.log(`Found boardGroupName ${cardPathArray[0]}, boardName ${cardPathArray[1]}, boardSectionName ${cardPathArray[2]} and cardName ${cardPathArray[3]}`)
cardPaths[`boardGroupName`] = cardPathArray[0]
cardPaths[`boardName`] = cardPathArray[1]
cardPaths[`boardSectionName`] = cardPathArray[2]
cardPaths[`cardName`] = cardPathArray[3]
return cardPaths
}
}
async function apiCreateCard(
headers,
title,
content,
collectionId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
utcDate
) {
try {
let cardData = {
preferredPhrase: title,
content: content,
boards: [
{
// TODO - figure out how to dynamically get/create board id
id: "c422a42b-891f-4537-988e-2ed7a1c39237",
action: {
// TODO - using board id, figure out how to dynmaically get/create board sectionId
// This can be done by making a capp to '/api/v1/boards/{id}'
sectionId: "3d7801a3-61c3-45f4-a681-1f2110d9c782",
actionType: "add",
// if prevSiblingItem is same as board id, card will be added to top of section
prevSiblingItem: "3d7801a3-61c3-45f4-a681-1f2110d9c782"
}
}
],
htmlContent: false,
collection: {
id: collectionId
},
shareStatus: "TEAM",
// tags: [response.data],
tags: tags,
verificationState: "NEEDS_VERIFICATION",
verificationInterval: verificationInterval,
verifiers: [
{
type: "user",
user: {
status: "ACTIVE",
email: verificationEmail,
firstName: verificationFirstName,
lastName: verificationLastName
},
id: verificationEmail,
dateCreated: utcDate
}
],
// verifiers: [
// {
// "type": "user-group",
// "userGroup": {
// "id": "35725837-184a-4f83-8774-778a8a84f967",
// "dateCreated": "2020-07-07T17:33:52.218+0000",
// "groupIdentifier": "team",
// "expertIdRank": 1,
// "numberOfCardsAsVerifier": 0,
// "numberOfMembers": 0,
// "modifiable": false,
// "name": "All Members"
// }
// }
// ],
verificationInitiator: {
status: "ACTIVE",
email: "[email protected]",
firstName: "Althea",
lastName: "Yi"
},
verificationReason: "NEW_VERIFIER"
};
console.log(`Making the card create request to Guru now with ${JSON.stringify(cardData)}`)
return await axios.post(
`https://api.getguru.com/api/v1/facts/extended`,
cardData,
headers
).then((response) => {
console.log("Response", response);
}).catch((error) => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
throw `A card create request was made, but received a bad response...\n Status: ${error.response.status} \n Response data: ${error.response.data}; \n Response headers: ${error.response.headers}`
} else if (error.request) {
throw `A card create request was made but no response was received: ${error.request}`
} else {
// Something happened in setting up the request that triggered an Error
throw `There was an issue with setting up the card create request: ${error.request}`
}
})
} catch (error) {
core.setFailed(
`Unable to create card: ${error}`
);
}
}
async function getOrCreateBoardsAndCards(
cardPaths,
headers,
title,
content,
collectionId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
utcDate
) {
try {
console.log(`Getting/creating boards and cards now... cardPaths contains ${Object.keys(cardPaths).length} elements`)
let boardGroupName
let boardName
let boardSectionName
let cardName
switch (Object.keys(cardPaths).length) {
case 1:
// create a top-level card in the collection
console.log("Creating/Getting top-level Card")
await apiCreateCard(
headers,
title,
content,
collectionId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
utcDate
)
break;
case 2:
// get/create a board and add card to the board
boardName = cardPaths.boardName
cardName = cardPaths.cardName
console.log("Creating/Getting Board and Card")
await apiCreateCard(
headers,
title,
content,
collectionId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
utcDate
)
break;
case 3:
// get/create a board group
// get/created a nested board
// add card to nested board
console.log("Creating/Getting Board Group, Board and Card")
boardGroupName = cardPaths.boardGroupName
boardName = cardPaths.boardName
cardName = cardPaths.cardName
await apiCreateCard(
headers,
title,
content,
collectionId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
utcDate
)
break;
case 4:
console.log("Creating/Getting Board Group, Board, Board Section and Card")
// get/create board group
// get/create a nested board
// get/create nested board section
// add card to nested board section
boardGroupName = cardPaths.boardGroupName
boardName = cardPaths.boardName
boardSectionName = cardPaths.boardSectionName
cardName = cardPaths.cardName
try {
await apiCreateCard(
headers,
title,
content,
collectionId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
utcDate
)
break;
} catch (error) {
core.setFailed(
`Creating the card for case 4 Failed: ${error.message}`
);
}
}
} catch (error) {
core.setFailed(
`Unable to create boards and cards: ${error.message}`
);
}
}
async function apiGetTagIdByTagValue(auth, teamId, tagCategoryName, uniqueTagValue) {
// 1. get all tag categories
let uniqueTagId
try {
await apiGetAllTagCategories(
auth,
teamId
).then((response) => {
if (response.data !== undefined) {
let tagCategoryIndex = getTagCategoryIndexByName(response.data, tagCategoryName)
if (tagCategoryIndex !== -1) {
console.log("Found a tag category with the target name", tagCategoryName)
let tagsInCategory = getTagsInCategory(response.data, tagCategoryIndex)
let desiredTag = getTagByValue(tagsInCategory, uniqueTagValue)
if (desiredTag !== undefined) {
uniqueTagId = desiredTag.id
} else {
uniqueTagId = null
}
}
}
})
console.log("unique tag id:", uniqueTagId)
return uniqueTagId
} catch (error) {
core.setFailed(`Unable to get Tag Id by Tag Value: ${error.message}`);
}
}
async function apiCreateTags(headers, teamId, tagData) {
try {
return await axios.post(
`https://api.getguru.com/api/v1/teams/${teamId}/tagcategories/tags/`,
tagData,
headers
)
} catch (error) {
core.setFailed(`Unable to create tags: ${error.message}`);
}
}
async function apiUnverifyCard(headers, cardId, postData) {
try {
console.log(`Unverifying updated card.`);
return await axios.post(
`https://api.getguru.com/api/v1/cards/${cardId}/unverify`,
{ postData },
headers
);
} catch (error) {
core.setFailed(`Could not unverify card: ${error.message}`);
}
}
async function apiDeleteStandardCard(
auth,
teamId,
tagCategoryName,
uniqueCardTagToDelete
) {
// Find card by unique Tag go get Id
let uniqueTagId = await apiGetTagIdByTagValue(auth, teamId, tagCategoryName, uniqueCardTagToDelete)
console.log("EXISTING UNIQUE TAG VALUE's TAG ID", uniqueTagId)
try {
await apiSearchCardByTagId(
auth,
uniqueTagId
).then((response) => {
// 1a. If existing tag found (and therefore card exists), call to Delete existing card by id (not by tag value).
if (response.data.length >= 1) {
let cardId = response.data[0].id
let headers = {
auth: auth,
"content-type": `application / json`
};
try {
console.log(
`Found existing card with uniqueTagId ${uniqueTagId} and cardId ${cardId}... Deleting`
);
fetch(`https://api.getguru.com/api/v1/cards/${cardId}`, {
"method": "DELETE",
"headers": headers
})
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
});
} catch (error) {
core.setFailed(`Unable to update card by Id: ${error.message}`);
}
}
// 2. Delete the tag
})
} catch (error) {
core.setFailed(`Unable to find card: ${error.message}`);
}
}
async function apiSendStandardCard(
auth,
collectionId,
title,
teamId,
tagCategoryName,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
cardFilename,
) {
console.log(`Creating or Updating card in ${collectionId}: ${title}`);
let headers = {
auth: auth,
"content-type": `application / json`
};
// 0. Parse file to see if it has tags... if it doesn't, create some and add to file
let file = fs.readFileSync(path.resolve(`${cardFilename}`), "utf8")
let arr = file.split(/\r?\n/);
var existingTag
let h2Regex = /^## \w+/
var linesThatNeedH2Tags = []
var existingH2TagLines = []
var uniqueH2Tags = []
var existingTag
var lineArray
let codeBlockLinesToSkip = getCodeBlockLinesToSkip(arr)
// index - zero-indexed file line number
// line - content of a given file line number (aka index)
arr.forEach((line, index) => {
if (line.includes("UUID Guru Tag -**")) {
lineArray = line.split(" ")
existingTag = lineArray[lineArray.length - 1]
return true
} else if (line.indexOf("**UUID H2 Guru Tag -** ") == 0) {
console.log("This line is an existing H2 Tag...")
// add file line number to list
existingH2TagLines.push(index)
// add tag to list of unqiue h2 tags
lineArray = line.split(" ")
uniqueH2Tags.push(lineArray[lineArray.length - 1])
console.log("Exising H2 Tag Lines", existingH2TagLines)
return true
} else if (h2Regex.test(line)) {
// TODO - fix this so it doesn't include H3s
console.log("This line maybe needs an H2 Tag...", index + 1)
console.log("CODE BLOCK LINES TO SKIP", codeBlockLinesToSkip)
let skipIndex
if (codeBlockLinesToSkip !== undefined) {
skipIndex = arrayIncludesElement(codeBlockLinesToSkip, index + 1)
}
console.log("SKIP INDEX", skipIndex)
if (skipIndex == false) {
console.log("This line definitely needs an H2 Tag", index + 1)
linesThatNeedH2Tags.push(index + 1)
return true
} else {
console.log("This line does not need an H2 Tag")
return false
}
} else {
return false
}
});
if (linesThatNeedH2Tags.length !== 0) {
linesThatNeedH2Tags = linesThatNeedH2Tags.filter(lineThatNeedsH2 => !existingH2TagLines.includes(lineThatNeedsH2))
console.log("These lines will have new H2 tags...", linesThatNeedH2Tags)
for (let i = 0; i < linesThatNeedH2Tags.length; i++) {
if (!existingH2TagLines.includes(linesThatNeedH2Tags[i])) {
console.log(`Generating H2 Tag for line ${linesThatNeedH2Tags[i]} `)
let uniqueH2TagValue = uuidv4()
let uniqueH2TagValueToWrite = `**UUID H2 Guru Tag -** ${uniqueH2TagValue}`
arr.splice(linesThatNeedH2Tags[i] + i, 0, uniqueH2TagValueToWrite); // insert new tag into file lines array
uniqueH2Tags.push(uniqueH2TagValue) // add the newly created H2 tag into list of all H2 tags
// add file line number to list
existingH2TagLines.push(linesThatNeedH2Tags[i] + i)
}
}
let newFileData = arr.join("\n"); // create the new file
let file = fs.writeFileSync(path.resolve(`${cardFilename}`), newFileData, { encoding: "utf8" }); // save it
console.log(`Added new unique tags to H2s`, uniqueH2Tags);
}
let uniqueTagValue
let content
if (!existingTag) {
console.log(`${cardFilename} has no existing Tag. Generating... `)
uniqueTagValue = uuidv4()
let uniqueTagValueToWrite = `\n***\n**UUID Guru Tag -** ${uniqueTagValue}`
let stream = fs.createWriteStream(path.resolve(`${cardFilename}`), { flags: 'as' })
stream.write(`${uniqueTagValueToWrite}`)
stream.end()
file = fs.readFileSync(path.resolve(`${cardFilename}`), "utf8")
console.log(`Appended a unique tag to ${cardFilename}: ${uniqueTagValueToWrite}`);
content = file
} else {
console.log(`${cardFilename} has an existingTag: `, existingTag)
uniqueTagValue = existingTag
content = file
}
// CREATE THE "PARENT" CARD
if (process.env.GURU_CARD_YAML && uniqueTagValue) {
// 0. Get all tags and get the tag id of the tag whose value is uniqueTagValue and pass it along to `apiSearchCardByTagId`
let uniqueTagId = await apiGetTagIdByTagValue(auth, teamId, tagCategoryName, uniqueTagValue)
console.log("EXISTING UNIQUE TAG VALUE's TAG ID", uniqueTagId)
// 1a. If unique tag exists in Guru, find related card using the tag id and update.
if (uniqueTagId !== null) {
await findAndUpdateCard(
uniqueTagId,
auth,
title,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content,
headers,
collectionId
)
} else {
// 1b. If unique tag does not exist in Guru, call to create a new unique tag and then a new card with said tag.
console.log("Creating a new unique tag with team id", teamId);
createTagAndCard(
uniqueTagValue,
auth,
title,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content,
headers,
teamId,
tagCategoryName,
cardFilename,
collectionId
)
}
}
// CREATE THE "CHILDREN" CARD BASED ON H2s IN THE PARENT CARD
// TODO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// For each unique H2 Tag, create a brand new card.
// Use only the `content` from the H2 tag up until the next H2 tag
// (or until it's the end of the file - figure out the OR logic)
// make a `getH2ContentKeyMap` function to serve this purpose
// content = getH2ContentKeyMap(content, uniqueH2Tags, existingH2TagLines)
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (process.env.GURU_CARD_YAML && uniqueH2Tags) {
let {h2ContentKeyMap, contentIndexAndH2TitleMap} = getH2ContentKeyMap(content)
for (let i = 0; i < uniqueH2Tags.length; i++) {
let uniqueTagValue = uniqueH2Tags[i]
console.log("uniqueTagValue", uniqueTagValue)
content = getH2ContentForKey(h2ContentKeyMap, uniqueTagValue)
console.log("\n\n\nH2 CHILD CARD CONTENT", content + "\n\n\n")
let updatedH2Title = title + " - " + Object.values(contentIndexAndH2TitleMap[i])[0]
console.log("UPDATED TITLE", updatedH2Title)
let uniqueTagId = await apiGetTagIdByTagValue(auth, teamId, tagCategoryName, uniqueTagValue)
console.log("Existing unique H2 tag ID", uniqueTagId)
// 1a. If unique tag exists in Guru, find related 'child' card using the tag id and update.
if (uniqueTagId !== null) {
await findAndUpdateCard(
uniqueTagId,
auth,
updatedH2Title,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content,
headers,
collectionId
)
} else {
// 1b. If unique tag does not exist in Guru, call to create a new unique tag and then a new 'child' card with said tag.
console.log("Creating a new unique tag with team id", teamId);
createTagAndCard(
uniqueTagValue,
auth,
updatedH2Title,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content,
headers,
teamId,
tagCategoryName,
cardFilename,
collectionId
)
}
}
}
}
function createTagAndCard(
uniqueTagValue,
auth,
title,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content,
headers,
teamId,
tagCategoryName,
cardFilename,
collectionId) {
try {
apiGetAllTagCategories(
auth,
uniqueTagValue,
teamId,
tagCategoryName
).then((response) => {
try {
let tagCategoryId = getTagCategoryIdByName(response.data, tagCategoryName)
console.log("tag category id????", tagCategoryId);
let tagData = {
categoryId: tagCategoryId,
value: uniqueTagValue
};
console.log("Set tag data", tagData);
try {
apiCreateTags(headers, teamId, tagData).then((response) => {
if (response.status !== 200) {
throw `Request to create tags failed: ${response}`
}
console.log("Going to get or create new Boards and Cards");
let date = new Date();
let utcDate = date.getUTCDate();
let cardPaths = splitCardFilename(cardFilename)
let tags = [response.data]
console.log(`Retrieved cardFilename paths: ${cardPaths}`)
try {
// TODO - parse cardPaths... make calls to make board group/board/board section accordingly
getOrCreateBoardsAndCards(
cardPaths,
headers,
title,
content,
collectionId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
utcDate
)
} catch (error) {
core.setFailed(`Unable to getorCreateBoardsAndCards: ${error.message}`);
}
});
} catch (error) {
core.setFailed(`Unable to create tags: ${error.message}`);
}
} catch (error) {
core.setFailed(`Unable to get category id: ${error.message}`);
}
});
} catch (error) {
core.setFailed(`Unable to get all tag categories: ${error.message}`);
}
}
async function findAndUpdateCard(
uniqueTagId,
auth,
title,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content,
headers,
collectionId) {
try {
await apiSearchCardByTagId(
auth,
uniqueTagId
).then((response) => {
// 1a. If existing tag found (and therefore card exists), call to update existing card by id (not by tag value).
if (response.data.length >= 1) {
let cardId = response.data[0].id
let cardTags = response.data[0].tags
try {
console.log(
`Found existing card with uniqueTagId ${uniqueTagId}`
);
apiUpdateStandardCardById(
auth,
collectionId,
title,
cardId,
cardTags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content
).then((response) => {
console.log(`Updated card`);
try {
let postData = {};
// need to pass in empty post body or else request will fail
apiUnverifyCard(headers, cardId, postData)
} catch (error) {
core.setFailed(`Unable to unverify card: ${error.message}`);
}
});
} catch (error) {
core.setFailed(`Unable to update card by Id: ${error.message}`);
}
}
})
} catch (error) {
core.setFailed(`Unable to find card: ${error.message}`);
}
}
function getTagByValue(tags, tagValue) {
let desiredTag = tags.find(tag => tag.value == tagValue)
return desiredTag
}
function getTagsInCategory(data, tagCategoryIndex) {
console.log("Getting all Tags in Category")
let tagsInCategory = data[tagCategoryIndex].tags.map(tag => tag);
return tagsInCategory
}
function getTagCategoryIndexByName(data, tagCategoryName) {
// if the tagCategoryIndex is -1, it means that no tag with tagCategoryName was found
console.log(`Getting Tag Category Index by Category Name`, tagCategoryName);
let tagCategoryIndex = data.findIndex(tagCategory => tagCategory.name === tagCategoryName)
return tagCategoryIndex
}
function getTagCategoryIdByName(data, tagCategoryName) {
console.log(`Getting Tag Category Id by Category Name`, tagCategoryName);
let tagCategoryIndex = getTagCategoryIndexByName(data, tagCategoryName)
if (tagCategoryIndex !== -1) {
return data[tagCategoryIndex].id
} else {
return null
}
}
async function apiGetAllTagCategories(auth, teamId) {
try {
console.log(`Getting all tag categories by team id`);
return await axios.get(
`https://api.getguru.com/api/v1/teams/${teamId}/tagcategories`,
{
auth: auth
}
);
} catch (error) {
core.setFailed(`Unable to get tag categories by team Id: ${error.message}`);
}
}
async function apiSearchCardByTagId(
auth,
tagId
) {
try {
console.log(
`Searching for card with Tag ID: ${tagId}`
);
return await axios.get(
`https://api.getguru.com/api/v1/search/query?q=tag-${tagId}%20exists`,
{
auth: auth
}
);
} catch (error) {
core.setFailed(
`Unable to find card with tagId ${tagId}: ${error.message}`
);
}
}
async function apiUpdateStandardCardById(
auth,
collectionId,
title,
cardId,
tags,
verificationInterval,
verificationEmail,
verificationFirstName,
verificationLastName,
content
) {
console.log(`Updating card with ID ${cardId}`);
let headers = {
auth: auth,
"content-type": `application/json`
};
let date = new Date();
let utcDate = date.getUTCDate();
let data = {
preferredPhrase: title,
content: content,
htmlContent: false,
collection: {
id: collectionId
},
shareStatus: "TEAM",
id: cardId,
verificationState: "NEEDS_VERIFICATION",
verificationInterval: verificationInterval,
verifiers: [
{
type: "user",
user: {
status: "ACTIVE",