-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathnotion_page.py
More file actions
1424 lines (1169 loc) · 52.8 KB
/
notion_page.py
File metadata and controls
1424 lines (1169 loc) · 52.8 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
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
import os
import re
import typing
import urllib
from slugify import slugify
from notion_client import Client
from config import Config
from utils.utils import Utils
from utils.notion_utils import NotionUtils
class PageBaseBlock:
def __init__(self):
self.id = 'unknown'
self.type = 'unknown'
self.children: typing.List[PageBaseBlock] = None
def write_block(self):
return """<!-- unsupported page block
type: {}
{}
-->""".format(self.type, self._wip_msg())
def _wip_msg(self):
return "notion id: " + self.id
def is_group(self):
return self.children is not None
class PageGroupBlock(PageBaseBlock):
def __init__(self):
super().__init__()
self.type = 'group_block'
self.group = 'Group'
self.name = ''
self.children: typing.List[PageBaseBlock] = []
self.on_write_children_handler: typing.Callable[[typing.List[PageBaseBlock]], str] = None
def on_write_children(self, handler: typing.Callable[[typing.List[PageBaseBlock]], str]):
self.on_write_children_handler = handler
pass
def write_block(self):
if not self.on_write_children_handler:
def handler(blocks: typing.List[PageBaseBlock])->str:
lines = [it.write_block() for it in blocks]
return "\n".join(lines)
self.on_write_children_handler = handler
text = self.on_write_children_handler(self.children)
return "{}\n{}\n{}".format(self.write_begin(), text, self.write_end())
def write_begin(self):
return "<!-- {} BGN{} -->".format(self.group, '' if len(self.name) == 0 else ' ' + self.name)
def write_end(self):
return "<!-- {} END{} -->".format(self.group, '' if len(self.name) == 0 else ' ' + self.name)
class PageSyncedSourceBlock(PageGroupBlock):
def __init__(self):
super().__init__()
self.type = 'transclusion_container'
self.group = 'SyncedSourceBlock'
self.children: typing.List[PageBaseBlock] = []
def write_block(self):
if not self.on_write_children_handler:
def handler(blocks: typing.List[PageBaseBlock])->str:
lines = [it.write_block() for it in blocks]
return "\n".join(lines)
self.on_write_children_handler = handler
text = self.on_write_children_handler(self.children)
return text
class PageSyncedCopyBlock(PageGroupBlock):
def __init__(self):
super().__init__()
self.type = 'transclusion_reference'
self.group = 'SyncedCopyBlock'
self.children: typing.List[PageBaseBlock] = []
def write_block(self):
lines = [it.write_block() for it in self.children]
return "<!-- SyncedBlock: {}\nThis is a reference block. {}\n-->".format(self.name, "\n".join(lines))
class PageShortCodeBlock(PageGroupBlock):
def __init__(self):
super().__init__()
self.type = 'short_code_block'
self.group = 'ShortCode'
self.children: typing.List[PageBaseBlock] = []
def write_block(self):
lines = [it.write_block() for it in self.children]
return "<!-- ShortCode: {}\n{}\n-->".format(self.name, "\n".join(lines))
class PageChannelBlock(PageGroupBlock):
def __init__(self):
super().__init__()
self.type = 'channel_block'
self.group = 'Channel'
self.channel = ''
def write_begin(self):
return "<!-- For {} only BGN: {} -->".format(self.group, self.channel)
def write_end(self):
return "<!-- For {} only END: {} -->".format(self.group, self.channel)
class PageColumnListBlock(PageGroupBlock):
def __init__(self):
super().__init__()
self.type = 'column_list'
self.group = 'ColumnList'
self.children: typing.List[PageColumnBlock] = []
def write_block(self):
if not self.on_write_children_handler:
def handler(blocks: typing.List[PageBaseBlock])->str:
column_lines = []
for idx, column_block in enumerate(blocks):
column_lines.append(
"{}<!-- Column {} start -->\n{}\n<!-- Column end -->".format(
"\n" if idx > 0 else "",
idx,
column_block.write_block()
)
)
return "\n".join(column_lines)
self.on_write_children_handler = handler
return super().write_block()
class PageColumnBlock(PageGroupBlock):
def __init__(self):
super().__init__()
self.type = 'column'
self.group = 'Column'
self.children: typing.List[PageBaseBlock] = []
self.block_joiner: PageBlockJoiner = PageBlockJoiner()
def write_block(self):
if not self.on_write_children_handler:
def handler(blocks: typing.List[PageBaseBlock])->str:
lines = []
for idx in range(len(blocks)):
block = self.children[idx]
if self.block_joiner.should_add_separator_before(self.children, idx):
lines.append("")
lines.append(block.write_block())
if self.block_joiner.should_add_separator_after(self.children, idx):
lines.append("")
return "\n".join(lines)
text = self.on_write_children_handler(self.children)
return text
class PageTocBlock(PageBaseBlock):
def __init__(self):
super().__init__()
self.type = 'table_of_contents'
self.page_blocks = []
def write_block(self):
'''
# Table of Contents
-. [Example](#example)
-. [Example2](#example2)
-. [Third Example](#third-example)
-. [Fourth Example](#fourth-examplehttpwwwfourthexamplecom)
'''
block_lines = []
for block in self.page_blocks:
if block.type == "header":
block_lines.append(" * [{}](#{})".format(block.text, str(block.text).lower().replace(" ", "-")))
if block.type == "sub_header":
block_lines.append(" * {}[{}](#{})".format(' ' * 4, block.text, str(block.text).lower().replace(" ", "-")))
if block.type == "sub_sub_header":
block_lines.append(" * {}[{}](#{})".format(' ' * 8, block.text, str(block.text).lower().replace(" ", "-")))
return ("\n".join(block_lines)) if len(block_lines) > 0 else ""
# noinspection DuplicatedCode,PyMethodMayBeStatic
class PageTableBlock(PageBaseBlock):
def __init__(self):
super().__init__()
self.type = 'collection_view'
self.headers = [] # List of column names
self.rows = [] # List of rows (each row is a list of cell values)
def write_block(self):
if not self.headers:
return ''
block_lines = []
# Header
block_lines.append("{}".format(" | ".join([str(h).replace('|', '|') for h in self.headers])))
# Separator
block_lines.append("{}".format(" | ".join([':---:' for _ in self.headers])))
# Rows
for row in self.rows:
# Ensure row has same length as headers
cells = row + [''] * (len(self.headers) - len(row))
block_lines.append("{}".format(" | ".join([str(c).replace('|', '|') for c in cells[:len(self.headers)]])))
return "\n".join(block_lines)
def set_data(self, headers, rows):
self.headers = headers
self.rows = rows
class PageTextBlock(PageBaseBlock):
def __init__(self):
super().__init__()
self.type = 'text'
self.text = ''
def write_block(self):
# Check obfuscated links or images
pattern = re.compile("\[.*\]\(\[.*\]\(.*\)\)")
if pattern.search(self.text) is not None:
# parse obfuscated blocks
obfuscated_links = []
try:
p = pattern
for m in p.finditer(self.text):
obfuscated_link = m.group()
prefix = obfuscated_link[:obfuscated_link.find("]([")] + "]"
link = obfuscated_link[obfuscated_link.rfind("](") + len("]("):obfuscated_link.rfind("))")]
obfuscated_links.append("{}({})".format(prefix, link))
intermediate_text = re.sub(pattern, '{}', self.text)
return intermediate_text.format(*obfuscated_links)
except Exception as e:
print("Parse obfuscated links block error: text = {}\t\n".format(self.text))
raise e
return self.text
class PageEnterBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'enter'
self.text = ''
def write_block(self):
return self.text
class PageDividerBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'divider'
self.text = '---'
def write_block(self):
return self.text
class PageNumberedListBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'numbered_list'
self.text = ''
self.level = 0
def write_block(self):
return '{}1. {}'.format(" " * 4 * self.level, self.text)
class PageBulletedListBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'bulleted_list'
self.text = ''
self.level = 0
def write_block(self):
return '{}- {}'.format(" " * 4 * self.level, self.text)
class PageQuoteBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'quote'
self.text = ''
def write_block(self):
return '> {}'.format(self.text)
class PageCalloutBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'callout'
self.text = ''
def write_block(self):
lines = str(self.text).split("\n")
return '> ' + "> ".join(lines)
class PageHeaderBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'header'
self.text = ''
def write_block(self):
return '# {}'.format(self.text)
class PageSubHeaderBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'sub_header'
self.text = ''
def write_block(self):
return '## {}'.format(self.text)
class PageSubSubHeaderBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'sub_sub_header'
self.text = ''
def write_block(self):
return '### {}'.format(self.text)
class PageCodeBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'code'
self.text = ''
self.lang = ''
def write_block(self):
return """```{}
{}
```
""".format(self.lang, self.text)
class PageImageBlock(PageBaseBlock):
def __init__(self):
super().__init__()
self.type = 'image'
self.image_caption = ''
self.image_url = ''
self.image_file = ''
def write_block(self):
return self.write_image_block(self.image_url)
def write_image_block(self, image_source):
return "".format(self.image_caption, image_source)
class PageToggleBlock(PageTextBlock):
def __init__(self):
super().__init__()
self.type = 'image'
self.text = ''
self.children = []
self.status = 'details' # or 'details open'
def write_block(self):
return '''<{}>
<summary>{}</summary>
<pre><code>{}
</code></pre>
</details>'''.format(self.status, self.text, "\n".join(self.children))
def is_group(self):
# Flatt ToggleBlock as NonGroupBlock, because its writing is simple and no need to traversal.
return False
# noinspection PyBroadException,PyMethodMayBeStatic
class NotionPage:
"""
relative_path = None
title = ''
date = ''
properties = {}
blocks = []
"""
def __init__(self):
self.id = ''
self.title = ''
self.cover = ''
self.blocks = []
self.properties = {}
self.mapping = {
"paragraph": self._parse_text,
"heading_1": self._parse_header,
"heading_2": self._parse_sub_header,
"heading_3": self._parse_sub_sub_header,
"bulleted_list_item": self._parse_bulleted_list,
"numbered_list_item": self._parse_numbered_list,
"to_do": self._parse_to_do,
"toggle": self._parse_toggle,
"child_page": self._parse_sub_page,
"child_database": self._parse_collection,
"linked_database": self._parse_collection,
"embed": self._parse_embed,
"image": self._parse_image,
"video": self._parse_video,
"file": self._parse_file,
"pdf": self._parse_pdf,
"bookmark": self._parse_bookmark,
"callout": self._parse_callout,
"quote": self._parse_quote,
"equation": self._parse_equation,
"divider": self._parse_divider,
"table_of_contents": self._parse_toc,
"column_list": self._parse_column_list,
"column": self._parse_column,
"code": self._parse_code,
"synced_block": self._parse_synced_block,
}
def is_markdown_able(self):
return self.get_title() is not None # and self.get_date() is not None
def is_output_able(self):
return self.get_file_name() is not None
def get_identify(self):
return "[{}]{}".format(self.id, self.get_title())
def get_title(self):
if 'Title' in self.properties:
try:
value = str(self.properties['Title'])
if len(value) > 0:
return value
except Exception as e:
print(e)
if len(self.title) > 0:
return self.title
return None
def get_date(self):
if 'Date' in self.properties:
try:
value = str(self.properties['Date'])
if len(value) > 0:
return value
except Exception as e:
print(e)
return None
def get_category(self):
if 'Category' in self.properties:
try:
return str(self.properties['Category'])
except Exception as e:
print(e)
return None
def get_tag(self):
if 'Tag' in self.properties:
try:
return str(self.properties['Tag'])
except Exception as e:
print(e)
return None
def is_published(self):
if 'Published' in self.properties:
try:
return str(self.properties['Published']) in [
'true',
'1',
't',
'y',
'yes',
'yeah',
'yup',
'certainly',
'uh-huh'
]
except Exception as e:
print(e)
return False
def get_file_dir(self):
if 'FileLocate' in self.properties:
try:
value = str(self.properties['FileLocate'])
if len(value) > 0:
return value
except Exception as e:
print(e)
return None
def get_file_name(self):
if 'FileName' in self.properties:
try:
value = str(self.properties['FileName'])
if len(value) > 0:
return value
except Exception as e:
print(e)
if len(self.get_title()) > 0:
return slugify(self.get_title(), separator='_')
if len(self.id) > 0:
return self.id
return None
def parse(self, page):
self.id = page.get('id')
# Title extraction depends on whether it's a page or a block, but usually page
self.title = self._get_title(page)
cover = page.get('cover')
if cover:
if cover.get('type') == 'external':
self.cover = cover.get('external', {}).get('url')
elif cover.get('type') == 'file':
self.cover = cover.get('file', {}).get('url')
# parse page blocks
# We need to fetch children blocks
children = self._get_children(self.id)
self.blocks = self._parse_page_blocks(children)
# Parse properties (for Hexo front-matter)
# In official API, properties are in page['properties']
# But we also support [notion-down-properties] in code blocks.
# We should check for that during block parsing.
self._parse_page_properties(page)
def _get_title(self, page):
properties = page.get('properties', {})
for key, value in properties.items():
if value.get('type') == 'title':
return NotionUtils.get_plain_text(value.get('title', []))
return "Untitled"
def _get_children(self, block_id):
# TODO: Reuse client from NotionReader or create new?
# Creating new for now to avoid circular import issues
client = Client(auth=Config.notion_token())
children = []
has_more = True
start_cursor = None
while has_more:
response = client.blocks.children.list(block_id=block_id, start_cursor=start_cursor)
children.extend(response.get('results', []))
has_more = response.get('has_more')
start_cursor = response.get('next_cursor')
return children
def _parse_page_properties(self, page):
# Parse native Notion properties
properties = page.get('properties', {})
for key, value in properties.items():
# Map Notion properties to self.properties
# This is different from [notion-down-properties] which are custom overrides
# But we might want to use them as defaults?
# For now, let's just store them if needed, but the original code
# relied on [notion-down-properties] block or page properties.
# The original code:
# if 'Title' in self.properties: ...
# Let's try to extract some common ones.
if value.get('type') == 'date':
date = value.get('date')
if date:
self.properties['Date'] = date.get('start')
elif value.get('type') == 'multi_select':
options = value.get('multi_select', [])
self.properties['Tag'] = [opt.get('name') for opt in options]
elif value.get('type') == 'select':
opt = value.get('select')
if opt:
self.properties['Category'] = opt.get('name')
elif value.get('type') == 'checkbox':
self.properties['Published'] = str(value.get('checkbox')).lower()
pass
def _parse_page_blocks(self, blocks):
page_blocks: typing.List[PageBaseBlock] = []
# parse page blocks
idx = 0
while idx < len(blocks):
block = blocks[idx]
# Channel Block START
if self._is_short_code_start(block):
idx_end = self._parse_short_code_chunks(page_blocks, blocks, idx)
if idx_end > idx:
idx = idx_end
continue
# Basic Parsing
self._parse_page_blocks_flatt(page_blocks, block)
idx += 1
return page_blocks
def _parse_page_blocks_flatt(self, page_blocks: typing.List[PageBaseBlock], block):
'''
Only parse non-group block here.
'''
block_type = block.get('type')
# Mapping for parse
if block_type in self.mapping:
self.mapping[block_type].__call__(page_blocks, block)
else:
# Basic Block Parsing
self._parse_basic(page_blocks, block)
return page_blocks
def _is_short_code_start(self, block):
if block.get('type') == "paragraph":
text = NotionUtils.get_plain_text(block.get('paragraph', {}).get('rich_text', []))
if str(text).startswith("<!-- SHORT_CODE_"):
return True
return False
def _is_short_code_end(self, block):
if block.get('type') == "paragraph":
text = NotionUtils.get_plain_text(block.get('paragraph', {}).get('rich_text', []))
if str(text).startswith("SHORT_CODE_END -->"):
return True
return False
def _parse_short_code_chunks(self, page_blocks: typing.List[PageBaseBlock], blocks, idx_start):
if idx_start < 0 or idx_start >= len(blocks) - 1:
return -1
if not self._is_short_code_start(blocks[idx_start]):
return -1
start_line = NotionUtils.get_plain_text(blocks[idx_start].get('paragraph', {}).get('rich_text', []))
block_id = blocks[idx_start].get('id')
group_block: PageGroupBlock = PageGroupBlock()
group_block.id = block_id
symbol = 'SHORT_CODE_'
if symbol in start_line:
group_block = PageShortCodeBlock()
group_block.id = block_id
name = start_line[start_line.rfind(symbol) + len(symbol):].strip()
symbol_end = "="
if symbol_end in name:
name = name[:name.find(symbol_end)]
group_block.name = name
pass
symbol = 'SHORT_CODE_CHANNEL='
if symbol in start_line:
group_block = PageChannelBlock()
group_block.id = block_id
group_block.name = 'CHANNEL'
channel = start_line[start_line.rfind(symbol) + len(symbol):].strip()
group_block.channel = channel
pass
channel_blocks: typing.List[PageBaseBlock] = []
end_found = False
idx = idx_start + 1
while idx < len(blocks):
block = blocks[idx]
# Channel Block END
if self._is_short_code_end(block):
end_found = True
break
# Mapping for parse
block_type = block.get('type')
if block_type in self.mapping:
self.mapping[block_type].__call__(channel_blocks, block)
idx += 1
continue
# Basic Block Parsing
idx += 1
self._parse_basic(channel_blocks, block)
if end_found:
group_block.children = channel_blocks
page_blocks.append(group_block)
return idx + 1
return -1
def _parse_basic(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageBaseBlock()
page_block.id = block.get('id')
page_block.type = block.get('type')
page_blocks.append(page_block)
def _parse_text(self, page_blocks: typing.List[PageBaseBlock], block):
text = NotionUtils.get_markdown_text(block.get('paragraph', {}).get('rich_text', []))
if len(str(text).strip()) == 0:
page_blocks.append(PageEnterBlock())
return
page_block = PageTextBlock()
page_block.id = block.get('id')
page_block.type = 'text' # internal type
page_block.text = text
page_blocks.append(page_block)
pass
def _parse_image(self, page_blocks: typing.List[PageBaseBlock], block):
image_id = block.get('id')
image_info = block.get('image', {})
# Caption
image_caption = NotionUtils.get_plain_text(image_info.get('caption', []))
# URL
image_url = ""
if image_info.get('type') == 'external':
image_url = image_info.get('external', {}).get('url')
elif image_info.get('type') == 'file':
image_url = image_info.get('file', {}).get('url')
temp_file = os.path.join(Config.output(), "assets/image", image_id + "_" + image_caption, ".jpg")
page_block = PageImageBlock()
page_block.id = image_id
page_block.type = 'image'
page_block.image_caption = image_caption
page_block.image_url = image_url
page_block.image_file = temp_file
page_blocks.append(page_block)
def _parse_divider(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageDividerBlock()
page_block.id = block.get('id')
page_block.type = 'divider'
page_blocks.append(page_block)
def _parse_properties(self, block):
# Properties in code block [notion-down-properties]
content = NotionUtils.get_plain_text(block.get('code', {}).get('rich_text', []))
symbol = '[notion-down-properties]'
if symbol in content:
content_properties = content[content.rfind(symbol) + len(symbol):]
lines = str(content_properties).split("\n")
for line in lines:
if '=' in line:
idx = line.find('=')
key = line[:idx].strip()
value = line[idx + len('='):].strip()
if ',' in value:
# list
self.properties[key] = [it.strip() for it in value.split(',')]
continue
self.properties[key] = value
def _parse_code(self, page_blocks: typing.List[PageBaseBlock], block):
content = NotionUtils.get_plain_text(block.get('code', {}).get('rich_text', []))
symbol = '[notion-down-properties]'
if symbol in content:
self._parse_properties(block)
return
page_block = PageCodeBlock()
page_block.id = block.get('id')
page_block.type = 'code'
page_block.text = content
page_block.lang = block.get('code', {}).get('language', 'plain text')
page_blocks.append(page_block)
def _parse_numbered_list(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageNumberedListBlock()
page_block.id = block.get('id')
page_block.type = 'numbered_list'
page_block.text = NotionUtils.get_markdown_text(block.get('numbered_list_item', {}).get('rich_text', []))
page_block.level = 0
page_blocks.append(page_block)
if block.get('has_children'):
children = self._get_children(block.get('id'))
self.__recursive_parse_numbered_list(page_blocks, children, page_block.level + 1)
pass
def __recursive_parse_numbered_list(self, page_blocks: typing.List[PageBaseBlock], blocks, level):
for block in blocks:
page_block = PageNumberedListBlock()
page_block.id = block.get('id')
page_block.type = 'numbered_list'
# Check if it's actually a numbered list item, otherwise treat as text or whatever
# But usually nested list items are same type.
if block.get('type') == 'numbered_list_item':
page_block.text = NotionUtils.get_markdown_text(block.get('numbered_list_item', {}).get('rich_text', []))
else:
# Handle mixed content in list? For now just try to extract text if possible or ignore
# Or maybe we should parse it properly?
# The original code assumed children are list items.
# Let's try to get text if it's a paragraph or list item.
type_ = block.get('type')
if type_ in ['paragraph', 'bulleted_list_item', 'numbered_list_item']:
page_block.text = NotionUtils.get_markdown_text(block.get(type_, {}).get('rich_text', []))
else:
page_block.text = f"[{type_}]"
page_block.level = level
page_blocks.append(page_block)
if block.get('has_children'):
children = self._get_children(block.get('id'))
self.__recursive_parse_numbered_list(page_blocks, children, level + 1)
pass
def _parse_bulleted_list(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageBulletedListBlock()
page_block.id = block.get('id')
page_block.type = 'bulleted_list'
page_block.text = NotionUtils.get_markdown_text(block.get('bulleted_list_item', {}).get('rich_text', []))
page_block.level = 0
page_blocks.append(page_block)
if block.get('has_children'):
children = self._get_children(block.get('id'))
self.__recursive_parse_bulleted_list(page_blocks, children, page_block.level + 1)
pass
def __recursive_parse_bulleted_list(self, page_blocks: typing.List[PageBaseBlock], blocks, level):
for block in blocks:
page_block = PageBulletedListBlock()
page_block.id = block.get('id')
page_block.type = 'bulleted_list'
type_ = block.get('type')
if type_ == 'bulleted_list_item':
page_block.text = NotionUtils.get_markdown_text(block.get('bulleted_list_item', {}).get('rich_text', []))
elif type_ in ['paragraph', 'numbered_list_item']:
page_block.text = NotionUtils.get_markdown_text(block.get(type_, {}).get('rich_text', []))
else:
page_block.text = f"[{type_}]"
page_block.level = level
page_blocks.append(page_block)
if block.get('has_children'):
children = self._get_children(block.get('id'))
self.__recursive_parse_bulleted_list(page_blocks, children, level + 1)
pass
def _parse_quote(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageQuoteBlock()
page_block.id = block.get('id')
page_block.type = 'quote'
page_block.text = NotionUtils.get_markdown_text(block.get('quote', {}).get('rich_text', []))
page_blocks.append(page_block)
def _parse_callout(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageCalloutBlock()
page_block.id = block.get('id')
page_block.type = 'callout'
page_block.text = NotionUtils.get_markdown_text(block.get('callout', {}).get('rich_text', []))
page_blocks.append(page_block)
def _parse_header(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageHeaderBlock()
page_block.id = block.get('id')
page_block.type = 'header'
page_block.text = NotionUtils.get_markdown_text(block.get('heading_1', {}).get('rich_text', []))
page_blocks.append(page_block)
def _parse_sub_header(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageSubHeaderBlock()
page_block.id = block.get('id')
page_block.type = 'sub_header'
page_block.text = NotionUtils.get_markdown_text(block.get('heading_2', {}).get('rich_text', []))
page_blocks.append(page_block)
def _parse_sub_sub_header(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageSubSubHeaderBlock()
page_block.id = block.get('id')
page_block.type = 'sub_sub_header'
page_block.text = NotionUtils.get_markdown_text(block.get('heading_3', {}).get('rich_text', []))
page_blocks.append(page_block)
def _parse_to_do(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageBaseBlock() # Use generic for now or create PageToDoBlock
# We can reuse PageBulletedListBlock or similar if we don't have a specific class
# Or just treat as text with checkbox.
# Let's create a simple text representation for now: "[ ] Task" or "[x] Task"
checked = block.get('to_do', {}).get('checked', False)
text = NotionUtils.get_markdown_text(block.get('to_do', {}).get('rich_text', []))
prefix = "[x] " if checked else "[ ] "
page_block.id = block.get('id')
page_block.type = 'to_do' # internal type
# We don't have PageToDoBlock, so let's use PageTextBlock but with modified text?
# Or just append to page_blocks as a text block.
# Actually, let's use PageBulletedListBlock but change type to 'to_do' if we want specific rendering,
# but for Markdown, it's `- [ ]`.
# Let's use PageTextBlock and format it manually for now.
page_block = PageTextBlock()
page_block.id = block.get('id')
page_block.type = 'to_do'
page_block.text = prefix + text
page_blocks.append(page_block)
def _parse_embed(self, page_blocks: typing.List[PageBaseBlock], block):
# Generic embed
url = block.get('embed', {}).get('url', '')
page_block = PageTextBlock()
page_block.id = block.get('id')
page_block.type = 'embed'
page_block.text = f"<{url}>"
page_blocks.append(page_block)
def _parse_video(self, page_blocks: typing.List[PageBaseBlock], block):
# Video
video = block.get('video', {})
url = ""
if video.get('type') == 'external':
url = video.get('external', {}).get('url')
elif video.get('type') == 'file':
url = video.get('file', {}).get('url')
page_block = PageTextBlock()
page_block.id = block.get('id')
page_block.type = 'video'
page_block.text = f"Video: <{url}>"
page_blocks.append(page_block)
def _parse_file(self, page_blocks: typing.List[PageBaseBlock], block):
file_info = block.get('file', {})
url = ""
if file_info.get('type') == 'external':
url = file_info.get('external', {}).get('url')
elif file_info.get('type') == 'file':
url = file_info.get('file', {}).get('url')
caption = NotionUtils.get_markdown_text(file_info.get('caption', []))
text = caption if caption else "File"
page_block = PageTextBlock()
page_block.id = block.get('id')
page_block.type = 'file'
page_block.text = f"[{text}]({url})"
page_blocks.append(page_block)
def _parse_pdf(self, page_blocks: typing.List[PageBaseBlock], block):
self._parse_file(page_blocks, block)
def _parse_bookmark(self, page_blocks: typing.List[PageBaseBlock], block):
url = block.get('bookmark', {}).get('url', '')
page_block = PageTextBlock()
page_block.id = block.get('id')
page_block.type = 'bookmark'
page_block.text = f"<{url}>"
page_blocks.append(page_block)
def _parse_equation(self, page_blocks: typing.List[PageBaseBlock], block):
expression = block.get('equation', {}).get('expression', '')
page_block = PageTextBlock()
page_block.id = block.get('id')
page_block.type = 'equation'
page_block.text = f"$$ {expression} $$"
page_blocks.append(page_block)
def _parse_toc(self, page_blocks: typing.List[PageBaseBlock], block):
page_block = PageTocBlock()
page_block.id = block.get('id')
page_block.type = 'table_of_contents'
page_block.page_blocks = page_blocks
page_blocks.append(page_block)
# noinspection PyUnusedLocal
def _parse_sub_page(self, page_blocks: typing.List[PageBaseBlock], block):
print("Ignore subpage block within page")
# In official API, child_page is a block.
# We might want to link to it?