-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmdToNotion.js
More file actions
949 lines (869 loc) · 34.9 KB
/
mdToNotion.js
File metadata and controls
949 lines (869 loc) · 34.9 KB
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
const path = require("path")
const {NotionObject, Block, Property} = require("./notionObject");
const fs = require("fs");
const imgur = require("imgur");
module.exports = class MdToNotion{
#notion
#databaseId;
#pageIcon;
#backlinkType;
#backlinkList;
#imgurEmail;
#imgurPassword;
#imgurClientId;
#imgPath;
#waitUploadImage;
constructor(notionToken) {
this.#notion = notionToken;
this.#pageIcon = "🔗";
this.#databaseId = null;
this.#backlinkType = null;
this.#backlinkList = [];
this.#imgurEmail = null;
this.#imgurPassword = null;
this.#imgurClientId = null;
this.#imgPath = null;
}
//findPage indatabase with specific title, return title and id.
//if no page have found return id = null.
#findPage = async (pageTitle) => {
const response = await this.#notion.databases.query({
database_id: this.#databaseId,
filter: {
or: [{
property: 'Name',
text: {
contains: pageTitle
},
}, ],
},
});
const arrOfResult = response.results;
//Get only page that are in current Database only and checking for repeat page.
const getOnlyPage = arrOfResult.filter(e => e.object == "page");
const pageInCurentDataBase = getOnlyPage.filter(e => e.parent.database_id.replace(/-/g, "") == this.#databaseId)
const page = pageInCurentDataBase.filter(e => e.properties.Name.title[0].plain_text == pageTitle)
if (page.length == 0) {
console.log("No page is found")
return {
title: pageTitle,
id: null
};
} else if (page.length > 1) {
console.log(`You have a repeat page `)
return {
title: pageTitle,
id: null
};
} else {
console.log(`Found "${page[0].properties.Name.title[0].plain_text} in database"`)
return {
title: pageTitle,
id: page[0].id
};
}
}
//this make annotaion and mention happend.
#parserToRichTextObj = async (text) => {
const regex = {
highlight: /(?<!┆)==[^┆\=\s].*?==(?!┆)/,
bold: /(?<!┆)\*\*[^(┆\*\s)].+?\*\*(?!┆)/,
code: /(?<!┆)`[^(┆\`\s)].+?`(?!┆)/,
strikethrough: /(?<!┆)~.[^┆\s]*?~~(?!┆)/,
italic: /(?<!┆|\*)\*[^(┆\*\s)].+?\*(?!┆|\*)/,
backLink: /(?<!┆)\[\[[^(┆\]\])].+?\]\](?!┆)/,
equation: /(?<!┆)\$[^(┆\`\s)].+?\$(?!┆)/,
link: /(?<!┆)\[[^┆].*?\]\([^(┆)].*?\)(?!┆)/
}
const isNotMention = /\.pdf|\.gif|\.png|\.jpg|\.jpeg|\.bmp|\.svg/;
//checking the annotation of content, seperate them with ┆.
for (let i in regex) {
while (text.match(regex[i]) !== null) {
const index = text.match(regex[i]).index
const lastSlice = index + text.match(regex[i])[0].length
const textInside = text.slice(index, lastSlice)
const newReplce = text.replace(regex[i], "┆" + textInside + "┆")
text = newReplce
}
}
//split normal text and anotation in to array.
const listOfText = text.split("┆");
let modifiedText = [];
for (let i = 0; i < listOfText.length; i++) {
if (regex.bold.test(listOfText[i])) {
const content = listOfText[i].replace(/\*/g, "")
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.annotations["bold"] = true;
richTextObj.text.content = content;
modifiedText.push(richTextObj);
} else if (regex.code.test(listOfText[i])) {
const content = listOfText[i].replace(/`/g, "")
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.annotations["code"] = true;
richTextObj.annotations["color"] = "red";
richTextObj.text.content = content;
modifiedText.push(richTextObj);
} else if (regex.highlight.test(listOfText[i])) {
const content = listOfText[i].replace(/==/g, "")
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.annotations["code"] = true;
richTextObj.annotations["color"] = "red";
richTextObj.text.content = content;
modifiedText.push(richTextObj);
} else if (regex.strikethrough.test(listOfText[i])) {
const content = listOfText[i].replace(/~~/g, "")
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.annotations["strikethrough"] = true;
richTextObj.text.content = content;
modifiedText.push(richTextObj);
} else if (regex.italic.test(listOfText[i])) {
const content = listOfText[i].replace(/\*/g, "")
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.annotations["italic"] = true;
richTextObj.text.content = content;
modifiedText.push(richTextObj);
} else if (regex.link.test(listOfText[i])) {
const content = listOfText[i].match(/(?<=\[).*(?=\])/)[0];
const link = listOfText[i].match(/(?<=\]\().*?(?=\))/)[0];
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.text.content = content;
richTextObj.text.link = {
url: link
};
modifiedText.push(richTextObj);
} else if (regex.backLink.test(listOfText[i]) && !isNotMention.test(listOfText[i])) {
let content = listOfText[i].replace(/\[\[|\]\]/g, "")
let link = content;
//check if mention have block reference or not, if true, mention to page of that block
const isBlockReference = /#\^\w*/;
if (isBlockReference.test(content)) {
link = content.match(/.*(?=#\^)/)[0];
}
//check if content have | (text after | will be content and before will be link).
const isModifeid = /(?<=.)\|(?=.)/
if (isModifeid.test(content)) {
content = content.match(/(?<=\|).*/)[0];
}
if (isModifeid.test(link)) {
link = link.match(/.*(?=\|)/)[0];
}
if (this.#databaseId !== null && this.#backlinkType !== null) {
console.log("Mentioning...")
//if text match [[]] -> find the page that match with content inside
const pageId = await this.#findPage(link);
if (this.#backlinkType == "mention") { //user input "mention"
const mentionObj = new NotionObject().mentionObj;
if (pageId.id != null) { //turn matched page into mention notion style
mentionObj.mention.page.id = pageId.id;
modifiedText.push(mentionObj);
console.log(`Mention to ${link} complete`)
} else { //if page not found create new one in current database instead
const addNewPage = await this.#createPage(link)
const newPageId = addNewPage.response.id;
mentionObj.mention.page.id = newPageId;
modifiedText.push(mentionObj);
console.log(`Mention to ${link} complete`)
}
} else if (this.#backlinkType == "link") { //user input "link"
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.text.content = content;
if (pageId.id != null) { //turn matched page into mention notion style
richTextObj.text.link = {
url: `/${pageId.id.replace(/-/g,"")}`
}
this.#backlinkList.push(pageId.id);
console.log(`Link to ${link} complete`)
} else { //if page not found create new one in current database instead
const addNewPage = await this.#createPage(link)
const newPageId = addNewPage.response.id;
richTextObj.text.link = {
url: `/${newPageId.replace(/-/g,"")}`
}
this.#backlinkList.push(newPageId);
console.log(`Link to ${link} complete`)
}
modifiedText.push(richTextObj);
}
} else {
//if database id or type of backlink is not specifythen
//put backlink into normal text instead
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = content;
richTextObj.text.content = content;
modifiedText.push(richTextObj);
}
} else if (regex.equation.test(listOfText[i])) {
const content = listOfText[i].replace(/\$/g, "")
const equation = new NotionObject().equationObj;
equation.plain_text = content;
equation.equation.expression = content
modifiedText.push(equation);
} else {
const richTextObj = new NotionObject().richTextObj;
richTextObj.plain_text = listOfText[i];
richTextObj.text.content = listOfText[i];
modifiedText.push(richTextObj);
}
}
return modifiedText;
}
//paser md to notion block.
//every line in the page content is represented by notion block object.
#parserMdToNotionObj = async (text) => {
//notion block object style with level of tab.
let blockObj = [
//blockObj[0] is empty now, we will add in next step.
,
{
isChild: false,
level: 0
}
]
//check level of child object
const tabRegex = /^\t|(?<=\t)\t/g
if (tabRegex.test(text)) {
const levelOfnestedChild = text.match(tabRegex).length;
text = text.replace(tabRegex, "");
blockObj[1].isChild = true;
blockObj[1].level = levelOfnestedChild;
}
//check if text have a --- this gonnabe a divider
const dividerRegex = /^---/
if (dividerRegex.test(text)) {
blockObj[0] = new Block().divider;
return blockObj;
}
//check type of block
const heading_1 = /^#\s/;
if (heading_1.test(text)) {
blockObj[0] = new Block().heading_1;
const content = text.replace(heading_1, "");
blockObj[0].heading_1.text = await this.#parserToRichTextObj(content);
return blockObj;
}
const heading_2 = /^##\s/;
if (heading_2.test(text)) {
blockObj[0] = new Block().heading_2;
const content = text.replace(heading_2, "");
blockObj[0].heading_2.text = await this.#parserToRichTextObj(content);
return blockObj;
}
const heading_3 = /^###\s/;
if (heading_3.test(text)) {
blockObj[0] = new Block().heading_3;
const content = text.replace(heading_3, "");
blockObj[0].heading_3.text = await this.#parserToRichTextObj(content);
return blockObj;
}
const heading_456 = /^####+\s/;
if (heading_456.test(text)) {
const content = text.replace(heading_456, "");
blockObj[0] = new Block().paragraph;
const richTextObj = new NotionObject().richTextObj;
richTextObj.annotations.bold = true;
richTextObj.plain_text = content;
richTextObj.text.content = content;
blockObj[0].paragraph.text = [richTextObj];
return blockObj;
}
const todo = /^-\s\[[x\s]\]\s/;
if (todo.test(text)) {
blockObj[0] = new Block().todo;
const content = text.replace(todo, "");
blockObj[0].to_do.text = await this.#parserToRichTextObj(content);
const isChecked = text.match(/(?<=-\s\[).(?=\])/)[0];
if (isChecked == "x") {
blockObj[0].to_do.checked = true;
} else {
blockObj[0].to_do.checked = false;
}
return blockObj;
}
const image = /!*\[\[.*?\.(png|jpg|gif|jpeg).*?\]\]/;
if (image.test(text)) {
const imgFileName = text.match(/!*(?<=\[\[).*?\.(png|jpg|gif|jpeg)/)[0];
const imgPath = this.#searchImg(imgFileName)
if (imgPath !== null) {
blockObj[0] = new Block().image;
const imageUrl = await this.#uploadImg(imgPath);
if (imageUrl) {
blockObj[0].image.external.url = imageUrl;
return blockObj;
}
}
}
const linkImage = /!*\[[^┆\[\]]*?\]\([^┆\[\]]*?\.(?=png\)|jpg\)|gif\)|jpeg\))/;
if(linkImage.test(text)){
const imgPath = text.match(/(?<=\]\().*?(?<=png|jpg|gif|jpeg)(?=\))/)
if(imgPath !== null) {
blockObj[0] = new Block().image;
blockObj[0].image.external.url = imgPath[0];
return blockObj;
}
}
const bulleted_list_item = /^-\s/;
if (bulleted_list_item.test(text)) {
blockObj[0] = new Block().bulleted_list_item;
const content = text.replace(bulleted_list_item, "");
blockObj[0].bulleted_list_item.text = await this.#parserToRichTextObj(content);
return blockObj;
}
const numbered_list_item = /^\d\.\s/;
if (numbered_list_item.test(text)) {
blockObj[0] = new Block().numbered_list_item;
const content = text.replace(numbered_list_item, "");
blockObj[0].numbered_list_item.text = await this.#parserToRichTextObj(content);
return blockObj;
}
const quote = /^\s*>/;
if (quote.test(text)) {
blockObj[0] = new Block().callout;
const content = text.replace(quote, "");
blockObj[0].callout.text = await this.#parserToRichTextObj(content);
return blockObj;
}
const table = /(?<=\|)\s*-+\s*(?=\|)/g
if (table.test(text)) {
const splitColumn = text.split(/\r\n|(?<!\r)\n/g);
//remove |---|
const removeHyphen = splitColumn.filter(e => e.match(/\|.+\|/) && !e.match(/(?<=\|)\s*-+\s*(?=\|)/g))
let tableContent = "";
//add Latex sytax -> textsf{someContent} and merge them together to tabelContent.
for (let i = 0; i < removeHyphen.length; i++) {
const modifiedContent = removeHyphen[i].match(/(?<=\|).*?(?=\|)/g)
let newText = "";
for (let j = 0; j < modifiedContent.length; j++) {
let text = `\\textsf{${modifiedContent[j]}}`
if (i == 0) {
text = `\\textsf{\\textbf{${modifiedContent[j]}}}`;
}
if (j == modifiedContent.length - 1) {
text = text + " \\\\\\hline\n"
} else {
text = text + " & "
}
newText = newText + text;
}
tableContent = tableContent + newText;
}
//count column of table form |---|
const column = splitColumn.filter(e => e.match(/\|\s*[-\|\s]+\s*\|/g))
const countColumn = column[0].match(/(?<=\|)\s*-+\s*(?=\|)/g).length;
let tableColumn = ""
for (let i = 0; i < countColumn; i++) {
tableColumn += "|c"
}
//Merge header and tabel content together and add to notion Block object
const addTable = `\\def\\arraystretch{1.4}\\begin{array}{${tableColumn}|}\\hline\n${tableContent}\\end{array}`
blockObj[0] = new Block().equation;
blockObj[0].equation.expression = addTable;
return blockObj;
}
const code = /^\!\`\`\`/;
if (code.test(text)) {
const notionCode = new NotionObject().NotionCodeLanguage;
const content = text.replace(/\!\`\`\`.*\n|\n\`\`\`\n*/g, "")
blockObj[0] = new Block().codeBlock;
blockObj[0].code.text[0].text.content = content;
const codeLanguage = text.match(/(?<=\!\`\`\`).*(?=\n)/);
if (codeLanguage.length !== null) {
const matchedLanguage = notionCode.filter(e => e == codeLanguage[0]);
if (matchedLanguage.length !== 0) {
blockObj[0].code.language = matchedLanguage[0];
} else {
blockObj[0].code.language = "plain text"
}
}
return blockObj;
}
const blockEquation = /\$\$.*?\$\$/;
if (blockEquation.test(text)) {
const content = text.replace(/\$\$/g, "");
blockObj[0] = new Block().equation;
blockObj[0].equation.expression = content;
return blockObj;
}
const iframe = /<iframe.*?<\/iframe>/;
if (iframe.test(text)) {
let link;
const isLink = text.match(/(?<=src=").*(?=">)/);
if (isLink) {
link = isLink[0];
blockObj[0] = new Block().embed;
blockObj[0].embed.url = link;
return blockObj;
}
}
//if doesn't match anything then covert to paragraph block.
blockObj[0] = new Block().paragraph;
blockObj[0].paragraph.text = await this.#parserToRichTextObj(text);
return blockObj;
}
#sameLevelCompress = async (listOfText) => {
let compressObj = [];
let currentLevel;
let currentArr = [];
let notionObj
//check if input is multiple line -> make the same level line in the same array
if (listOfText.length > 1) {
for (let i = 0; i < listOfText.length; i++) {
notionObj = await this.#parserMdToNotionObj(listOfText[i]);
if (i == 0) { //fist round
currentLevel = notionObj[1].level;
currentArr.push(notionObj[0]);
}
if (i !== 0) { //After fist round
if (notionObj[1].level == currentLevel) {
currentArr.push(notionObj[0]);
if (i == listOfText.length - 1) { //Push in last round
compressObj.push({
notionObj: currentArr,
level: currentLevel
});
}
}
if (notionObj[1].level !== currentLevel) {
compressObj.push({
notionObj: currentArr,
level: currentLevel
});
currentLevel = notionObj[1].level;
currentArr = [notionObj[0]]
}
}
}
} else { //if input is just one line of text do this instead
notionObj = await this.#parserMdToNotionObj(listOfText[0])
compressObj.push({
notionObj: [notionObj[0]],
level: notionObj[1].level
})
}
return compressObj;
}
//this fuction loop througt every level to find the furthest level, then put itself into previous level as child.
//the loop sitll going untill all of the level nested into level 0.
#nestedChildCompress = (compressObj) => {
let previous = 0;
let i = 0;
const noChild = ["equation", "heading_1", "heading_2",
"heading_3", "callout", "quote", "divider", "image", "code", "embed"
];
//if the file have only level 0 then compress them to one object.
if (compressObj.length == 1) {
let finishedCompress = [];
for (let y in compressObj) {
finishedCompress.push(...compressObj[y].notionObj)
}
return finishedCompress;
} else {
//loop througth every level and repeat untill all of the level nested into level 0.
for (let i = 0; i < compressObj.length;) {
//compare current with previos level.
if (compressObj[i].level - previous < 0) {
const postion = compressObj[i - 2].notionObj.length - 1;
const type = compressObj[i - 2].notionObj[postion]["type"];
//check target block can have child or can not, before append as child
const isNoChild = noChild.filter(e => e == type);
//if previos is the furthest level and it can have child, put it in previous level of it (parent of previous).
if (compressObj[i - 1].level !== compressObj[i - 2].level && isNoChild.length == 0) {
compressObj[i - 2].notionObj[postion][type]["children"] = compressObj[i - 1].notionObj;
compressObj.splice(i - 1, 1);
} else { //if previous is the same level of its parent or the parent can't have child, put them together.
compressObj[i - 2].notionObj.push(...compressObj[i - 1].notionObj)
compressObj.splice(i - 1, 1);
}
//set this for start checking again from level 0.
i = 0;
previous = 0;
} else if (i == compressObj.length - 1) {
//if this is the last round, the loop still repeat to find last child and break the code,
//so we need to stop if this is the last round.
const postion = compressObj[i - 1].notionObj.length - 1;
const type = compressObj[i - 1].notionObj[postion]["type"];
//check target block can have child or can not, before append as child
const isNoChild = noChild.filter(e => e == type);
if (isNoChild.length !== 0) {
compressObj[i - 2].notionObj.push(...compressObj[i - 1].notionObj)
compressObj.splice(i - 1, 1);
} else {
compressObj[i - 1].notionObj[postion][type]["children"] = compressObj[i].notionObj;
compressObj.splice(i, 1);
}
let finishedCompress = [];
for (let y in compressObj) {
finishedCompress.push(...compressObj[y].notionObj)
}
return finishedCompress;
} else {
previous = compressObj[i].level
i++;
}
//Check if compress finished or not
//if sumamation of all level is more thea 0 the loop still going.
let sum = 0;
for (let x in compressObj) {
sum = sum + compressObj[x]["level"]
}
if (sum == 0) {
let finishedCompress = [];
for (let y in compressObj) {
finishedCompress.push(...compressObj[y].notionObj)
}
return finishedCompress;
}
}
}
}
#findFurthestLevle = (compressObj) => {
let furthest = 0;
for (let i = 0; i < compressObj.length - 1; i++) {
if (compressObj[i].level > furthest) {
furthest = compressObj[i].level
}
}
return furthest;
}
//return block object for appending to page
#childObject = (blockId, listOfChild) => {
const blockObj = {
block_id: blockId,
children: listOfChild
}
return blockObj;
}
//find last child id in the specific level
#findLastChild = async (parentPageId) => {
const getChildlist = await this.#notion.blocks.children.list({
block_id: parentPageId,
page_size: 50,
});
const lastChildId = getChildlist.results[getChildlist.results.length - 1].id;
const lastChildType = getChildlist.results[getChildlist.results.length - 1].type;
return {
id: lastChildId,
type: lastChildType
};
}
//set new aligment of inline code block
#modifiedInlineCodeBlock = (listOfString) => {
let indexOfCode = [];
let i = 0;
for (i; i < listOfString.length; i++) {
const codeRegex = /^\`\`\`/;
if (codeRegex.test(listOfString[i])) {
indexOfCode.push(i)
}
if (indexOfCode.length == 2) {
const fistIndex = indexOfCode[0];
const lastIndex = indexOfCode[1];
const codeSplit = listOfString.splice(fistIndex, lastIndex - fistIndex + 1);
let mergeSplit = codeSplit.reduce((pre, now) => pre + "\n" + now)
mergeSplit = "!" + mergeSplit
listOfString.splice(fistIndex, 0, mergeSplit);
i = 0;
indexOfCode = [];
}
}
return listOfString;
}
//this exclude metadata that present in obsidain note
#modifiedMetadata = (listOfString) => {
if (/^---/.test(listOfString[0])) {
for (let i = 1; i < listOfString.length; i++) {
if (/^---/.test(listOfString[i])) {
listOfString.splice(0, i + 1);
return listOfString
}
}
}
return listOfString;
}
//set new aligment of inline img
#modifiedInlineImg = (listOfString) => {
const regex = {
image: /(?<!┆)\t*-*\s{1}!*\[\[[^┆]*?\.(png|gif|jpg|jpeg)\]\](?!┆)/,
linkImage: /(?<!┆)!*\[[^┆\[\]]*?\]\([^┆\[\]]*?\.(png|gif|jpg|jpeg)\)(?!┆)/,
}
for (let j = 0; j < listOfString.length; j++) {
for (let i in regex) {
while (listOfString[j].match(regex[i]) !== null) {
const index = listOfString[j].match(regex[i]).index
const lastSlice = index + listOfString[j].match(regex[i])[0].length
const textInside = listOfString[j].slice(index, lastSlice)
const newReplce = listOfString[j].replace(regex[i], "┆" + textInside + "┆")
listOfString[j] = newReplce
}
if (/┆/.test(listOfString[j])) {
const seperated = listOfString[j].split(/┆/);
listOfString.splice(j, 1)
listOfString.splice(j, 0, ...seperated);
j += seperated.length;
}
}
}
return listOfString;
}
#getText = (filePath) => {
let listOfString = fs.readFileSync(filePath, {
encoding: 'utf8',
flag: 'r'
}).toString()
//exclude html tag and ^reference number
listOfString = listOfString.replace(/<!--.*-->|\^[A-Za-z0-9]*?(?=\s|\n)/g, "");
//spit line with \n \r or latex equation to array
listOfString = listOfString.split(/(?<!\|)\r\n|\n(?!\|)|\s(?=\$\$)|(?<=\$\$)\s/g);
listOfString = this.#modifiedInlineCodeBlock(listOfString); //set new aligment of inline code block
listOfString = this.#modifiedInlineImg(listOfString); //set new aligment of inline img
listOfString = this.#modifiedMetadata(listOfString); //exclude metadata
listOfString = listOfString.filter(e => e !== "" && !/^\s+(?!.[^\s]*)/g.test(e)) //remove blank line
return listOfString;
}
uploadToPage = async (filePath, pageId) => {
//change url to pageId
if (/[a-z0-9]{32}/.test(pageId)) {
pageId = pageId.match(/[a-z0-9]{32}/)[0];
} else if (/([a-z0-9]|-)*?/.test(pageId)) {
pageId = pageId.replace(/-/g, "");
} else {
console.log("❗Page URL not match")
}
//get text --> spilt text --> return to array of split string
const listOfString = this.#getText(filePath)
if (listOfString.length == 0) {
return console.log("Content is empty")
}
const compressObj = await this.#sameLevelCompress(listOfString);
const furthestLevel = this.#findFurthestLevle(compressObj);
let uploadResponse;
//if furthest levle of child > 2 use this method
if (furthestLevel > 2) {
let previousLevel;
let arrOfEachLevelId = [];
//upload each block object in different level (the same leval will upload at once, this make upload faster)
for (let i = 0; i < compressObj.length; i++) {
let Level = compressObj[i]["level"];
if (Level == 0) {
uploadResponse = await this.#notion.blocks.children.append(this.#childObject(pageId, compressObj[i]["notionObj"]));
arrOfEachLevelId = [pageId];
previousLevel = 0;
} else if (Level - previousLevel == 1) {
const lastChildIdToAppend = await this.#findLastChild(arrOfEachLevelId[Level - 1]);
const lastChildId = lastChildIdToAppend.id;
//check target block can have child or can not, before append as child
const noChild = ["equation", "heading_1", "heading_2",
"heading_3", "callout", "quote", "divider", "image", "code", "embed"
];
const isNoChild = noChild.filter(e => e == lastChildIdToAppend.type);
if (isNoChild.length == 0) {
uploadResponse = await this.#notion.blocks.children.append(this.#childObject(lastChildId, compressObj[i]["notionObj"]));
arrOfEachLevelId.push(lastChildId);
previousLevel = Level;
} else { //if target block can not have chile, append to previous parent.
uploadResponse = await this.#notion.blocks.children.append(this.#childObject(arrOfEachLevelId[previousLevel], compressObj[i]["notionObj"]));
}
} else if (Level - previousLevel < 0) {
uploadResponse = await this.#notion.blocks.children.append(this.#childObject(arrOfEachLevelId[Level], compressObj[i]["notionObj"]));
}
}
} else {
//if furthest level of child lesser or equal to 2 use this method
//faster than above because upload the nested child at once
//notion only support nested 2 level child upload, so if nested child more than 2 -> using above method to upload instead
const nestedObj = this.#nestedChildCompress(compressObj);
uploadResponse = await this.#notion.blocks.children.append(this.#childObject(pageId, nestedObj));
}
//Checking after upload each file
//if there are link to another page in content, then update backlink property for every page that link to this.
if (this.#backlinkList.length !== 0 && this.#databaseId != null) {
const pageTitle = path.basename(filePath, path.extname(filePath));
const updateBacklink = await this.#updateBacklink(pageId, pageTitle);
}
const fileName = path.basename(filePath, path.extname(filePath))
return console.log(`------ Upload ${fileName} success\n`);
}
uploadToDatabase = async (filePath) => {
let pageId;
let pageTitle;
const fileName = path.basename(filePath, path.extname(filePath))
console.log(`Current file is ${fileName}`)
//checking if there are a page that already exit in the database, then upload content to that page instead.
const findPageId = await this.#findPage(fileName);
pageId = findPageId.id;
pageTitle = findPageId.title
if (pageId == null) { //if no page have found, then create new one, and upload the content.
const createPageResponse = await this.#createPage(fileName);
pageId = createPageResponse.response.id;
await this.uploadToPage(filePath, pageId);
} else {
console.log("You already have this page, upload to this page instead...")
await this.uploadToPage(filePath, pageId);
}
}
#createPage = async (pageName) => {
console.log(`Creating page as ${pageName}`)
const page = new NotionObject().pageObj;
page.parent.database_id = this.#databaseId;
page.icon.emoji = this.#pageIcon;
page.properties.Name.title[0].text.content = pageName;
const response = await this.#notion.pages.create(page);
console.log(`Create page ${pageName} success.`);
return {
title: pageName,
response: response
}
}
pageSetIcon = (icon) => {
this.#pageIcon = icon
console.log(`🔑 Set page icon with ${this.#pageIcon}`)
}
setBacklink = (typeOfBacklink) => {
this.#backlinkType = typeOfBacklink;
console.log("🔑 Set type of backing with " + this.#backlinkType)
}
dataBaseSetId = (url) => {
if (/(?<=\/)[a-z0-9]{32}(?=\?)/.test(url)) {
const id = url.match(/(?<=\/)[a-z0-9]{32}(?=\?)/)[0];
this.#databaseId = id;
console.log(`🔑 Set database id with ${this.#databaseId}`)
} else {
console.log("❗URL not match")
}
}
setImgPath = (imagePath) => {
this.#imgPath = imagePath;
console.log(`🔑 Set image path with ${this.#imgPath}`)
}
#createDatabaseProperty = async (propertyTitle, propertyType) => {
console.log("Create Page property")
const type = {};
type[propertyType] = [];
const title = {};
title[propertyTitle] = type;
const property = new NotionObject().dataBaseProperty;
property.database_id = this.#databaseId;
property.properties = title;
const response = await this.#notion.databases.update(property);
return response;
}
#updateBacklink = async (currentPageId, pageTitle) => {
//Variable #backlinkList is assigned from parserToRichText function,
//if the content have a link to another page then push that link page id to this variable.
//remove duplicate (recurrent mention in the same page will make backlink duplicate)
this.#backlinkList = [...new Set(this.#backlinkList)]
//Loop througt each linked page id and add the backlink property to them.
for (let i in this.#backlinkList) {
//find backlink property in linked page
let response = await this.#notion.pages.retrieve({
page_id: this.#backlinkList[i]
});
const isBacklink = response.properties["Backlink"];
let backLinkContent = [];
//if linked page dosen't have backlink property then create new one.
//Notice that page property is also the same as database property,
//so create backlink property in database of linked page instead.
if (!isBacklink) {
console.log("Not found Backlink property")
response = await this.#createDatabaseProperty("Backlink", "rich_text");
} else { //get backlink property content
backLinkContent = response.properties["Backlink"].rich_text;
}
//if the content already have some linked page, then add \n, so new content will add in newline.
if (backLinkContent.length !== 0) {
const newLineRichText = new NotionObject().richTextObj;
newLineRichText.text.content = "\n";
newLineRichText.plain_text = "\n";
backLinkContent.push(newLineRichText);
}
//adding new content of linked page that link to current page.
const backlinkToPage = new NotionObject().richTextObj;
backlinkToPage.text.link = {
url: `/${currentPageId.replace(/-/g,"")}`
};
backlinkToPage.plain_text = pageTitle;
backlinkToPage.text.content = pageTitle;
backLinkContent.push(backlinkToPage);
//create property object for updating with notion update method
const updateContent = new Property().rich_text;
updateContent.rich_text = backLinkContent;
const title = {};
title["Backlink"] = updateContent;
const pageProperty = new NotionObject().pageProperty;
pageProperty.page_id = this.#backlinkList[i];
pageProperty.properties = title;
const updateBacklink = await this.#notion.pages.update(pageProperty);
}
this.#backlinkList = []; //Clear array after adding all of the backlink.
}
uploadFolder = async (folderPath) => {
if (this.#backlinkType == null) {
fs.readdir(folderPath, (err, files) => {
files.forEach(file => {
if (fs.lstatSync(path.resolve(folderPath, file)).isFile() && (file.includes(".txt") || file.includes(".md"))) {
this.uploadToDatabase(folderPath + "/" + file, this.#databaseId)
}
});
});
} else {
let files = fs.readdirSync(folderPath);
for (let i in files) {
if (fs.lstatSync(path.resolve(folderPath, files[i])).isFile() && (files[i].includes(".txt") || files[i].includes(".md"))) {
const upload = await this.uploadToDatabase(folderPath + "/" + files[i], this.#databaseId);
}
}
}
}
//upload image via imgur api and get url for uploaded image
#uploadImg = async (filePath) => {
const stats = fs.statSync(filePath);
if (stats.size / (1024 * 1024) < 1) {
try {
if (this.#imgurClientId !== null) {
imgur.setCredentials(this.#imgurEmail, this.#imgurPassword, this.#imgurClientId);
}
const uploadImg = await imgur.uploadFile(filePath)
return uploadImg.link;
} catch (error) {
if (error.message.match(/(?<=Response\scode\s)\w\w\w/)[0] == "417") {
console.log("❗Can not upload large file.")
} else if (error.message.match(/(?<=Response\scode\s)\w\w\w/)[0] == "429") {
console.log("❗Hit Rate limit: Too many upload image.\n")
}
return null;
}
} else {
console.log("❗Cannote upload large image");
return null;
}
}
#searchImg = (imgFileName) => {
if (this.#imgPath == null) {
return null;
}
const path = this.#imgPath;
const myfile = imgFileName
let imgPath = "";
let files = fs.readdirSync(path);
for (let i in files) {
if (files[i] == myfile) {
console.log(`Found image : ${myfile}`);
imgPath = path + "/" + files[i]
return imgPath;
}
}
console.log(`Not found image : ${myfile}`)
return null;
}
loginImgur = (email, password, clientId) => {
this.#imgurEmail = email;
this.#imgurPassword = password;
this.#imgurClientId = clientId
}
}