-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
543 lines (478 loc) · 16.3 KB
/
Program.cs
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
using Notion.Client;
using System.Net;
using System.Security.Cryptography;
using System.Text;
var notionTitlePropertyName = "Title";
var notionTypePropertyName = "Type";
var notionPublishedAtPropertyName = "PublishedAt";
var notionRequestPublisingPropertyName = "RequestPublishing";
var notionCrawledAtPropertyName = "_SystemCrawledAt";
var notionTagsPropertyName = "Tags";
var notionDescriptionPropertyName = "Description";
var notionSlugPropertyName = "Slug";
var frontMatterTitleName = "title";
var frontMatterTypeName = "type";
var frontMatterPublishedName = "date";
var frontMatterDescriptionName = "description";
var frontMatterTagsName = "tags";
var frontMatterEyecatch = "eyecatch";
if (args.Length != 3)
{
throw new ArgumentException("args length should be three.");
}
// from CLI
var notionAuthToken = args[0];
var notionDatabaseId = args[1];
var outputDirectoryPathTemplate = args[2];
var filter = new CheckboxFilter(notionRequestPublisingPropertyName, true);
var pagination = await CreateNotionClient().Databases.QueryAsync(notionDatabaseId, new DatabasesQueryParameters()
{
Filter = filter,
});
var now = DateTime.Now;
var exportedCount = 0;
do
{
foreach (var page in pagination.Results)
{
if (await ExportPageToMarkdownAsync(page, now))
{
await CreateNotionClient().Pages.UpdateAsync(page.Id, new PagesUpdateParameters()
{
Properties = new Dictionary<string, PropertyValue>()
{
[notionCrawledAtPropertyName] = new DatePropertyValue()
{
Date = new Date()
{
Start = now,
}
},
[notionRequestPublisingPropertyName] = new CheckboxPropertyValue()
{
Checkbox = false,
},
}
});
exportedCount++;
}
}
if (!pagination.HasMore)
{
break;
}
pagination = await CreateNotionClient().Databases.QueryAsync(notionDatabaseId, new DatabasesQueryParameters
{
Filter = filter,
StartCursor = pagination.NextCursor,
});
} while (true);
Console.WriteLine($"::set-output name=exported_count::{exportedCount}");
NotionClient CreateNotionClient()
{
return NotionClientFactory.Create(new ClientOptions
{
AuthToken = notionAuthToken,
});
}
async Task<bool> ExportPageToMarkdownAsync(Page page, DateTime now, bool forceExport = false)
{
bool requestPublishing = false;
string title = string.Empty;
string type = string.Empty;
string slug = page.Id;
string description = string.Empty;
List<string>? tags = null;
DateTime? publishedDateTime = null;
DateTime? lastSystemCrawledDateTime = null;
// build frontmatter
foreach (var property in page.Properties)
{
if (property.Key == notionPublishedAtPropertyName)
{
if (TryParsePropertyValueAsDateTime(property.Value, out var parsedPublishedAt))
{
publishedDateTime = parsedPublishedAt;
}
}
else if (property.Key == notionCrawledAtPropertyName)
{
if (TryParsePropertyValueAsDateTime(property.Value, out var parsedCrawledAt))
{
lastSystemCrawledDateTime = parsedCrawledAt;
}
}
else if (property.Key == notionSlugPropertyName)
{
if (TryParsePropertyValueAsPlainText(property.Value, out var parsedSlug))
{
slug = parsedSlug;
}
}
else if (property.Key == notionTitlePropertyName)
{
if (TryParsePropertyValueAsPlainText(property.Value, out var parsedTitle))
{
title = parsedTitle;
}
}
else if (property.Key == notionDescriptionPropertyName)
{
if (TryParsePropertyValueAsPlainText(property.Value, out var parsedDescription))
{
description = parsedDescription;
}
}
else if (property.Key == notionTagsPropertyName)
{
if (TryParsePropertyValueAsStringSet(property.Value, out var parsedTags))
{
tags = parsedTags.Select(tag => $"\"{tag}\"").ToList();
}
}
else if (property.Key == notionTypePropertyName)
{
if (TryParsePropertyValueAsPlainText(property.Value, out var parsedType))
{
type = parsedType;
}
}
else if (property.Key == notionRequestPublisingPropertyName)
{
if (TryParsePropertyValueAsBoolean(property.Value, out var parsedBoolean))
{
requestPublishing = parsedBoolean;
}
}
}
if (!requestPublishing)
{
Console.WriteLine($"{page.Id}(title = {title}): No request publishing.");
return false;
}
if (!publishedDateTime.HasValue)
{
Console.WriteLine($"{page.Id}(title = {title}): Skip updating becase this page don't have publish ate.");
return false;
}
if (!forceExport)
{
if (now < publishedDateTime.Value)
{
Console.WriteLine($"{page.Id}(title = {title}): Skip updating because the publication date have not been reached");
return false;
}
}
slug = string.IsNullOrEmpty(slug) ? page.Id : slug;
var outputDirectory = BuildOutputDirectory(publishedDateTime.Value, title, slug);
if (!Directory.Exists(outputDirectory))
{
Directory.CreateDirectory(outputDirectory);
}
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("---");
if (!string.IsNullOrWhiteSpace(type)) stringBuilder.AppendLine($"{frontMatterTypeName}: \"{type}\"");
stringBuilder.AppendLine($"{frontMatterTitleName}: \"{title}\"");
if (!string.IsNullOrWhiteSpace(description)) stringBuilder.AppendLine($"{frontMatterDescriptionName}: \"{description}\"");
if (tags != null) stringBuilder.AppendLine($"{frontMatterTagsName}: [{string.Join(',', tags)}]");
stringBuilder.AppendLine($"{frontMatterPublishedName}: \"{publishedDateTime.Value.ToString("s")}\"");
if (page.Cover != null && page.Cover is UploadedFile uploadedFile)
{
var (fileName, _) = await DownloadImage(uploadedFile.File.Url, outputDirectory);
stringBuilder.AppendLine($"{frontMatterEyecatch}: \"./{fileName}\"");
}
stringBuilder.AppendLine("");
stringBuilder.AppendLine("---");
stringBuilder.AppendLine("");
// page content
var pagination = await CreateNotionClient().Blocks.RetrieveChildrenAsync(page.Id);
do
{
foreach (Block block in pagination.Results)
{
await AppendBlockLineAsync(block, string.Empty, outputDirectory, stringBuilder);
}
if (!pagination.HasMore)
{
break;
}
pagination = await CreateNotionClient().Blocks.RetrieveChildrenAsync(page.Id, new BlocksRetrieveChildrenParameters
{
StartCursor = pagination.NextCursor,
});
} while (true);
using (var fileStream = File.OpenWrite($"{outputDirectory}/index.markdown"))
{
using (var streamWriter = new StreamWriter(fileStream, new UTF8Encoding(false)))
{
await streamWriter.WriteAsync(stringBuilder.ToString());
}
}
return true;
}
string BuildOutputDirectory(DateTime publishedDate, string title, string slug)
{
var template = Scriban.Template.Parse(outputDirectoryPathTemplate);
return template.Render(new
{
publish = publishedDate,
title = title,
slug = slug,
});
}
bool TryParsePropertyValueAsDateTime(PropertyValue value, out DateTime dateTime)
{
dateTime = default;
switch (value)
{
case DatePropertyValue dateProperty:
if (dateProperty.Date == null) return false;
if (!dateProperty.Date.Start.HasValue) return false;
dateTime = dateProperty.Date.Start.Value;
break;
case CreatedTimePropertyValue createdTimeProperty:
if (!DateTime.TryParse(createdTimeProperty.CreatedTime, out dateTime))
{
return false;
}
break;
case LastEditedTimePropertyValue lastEditedTimeProperty:
if (!DateTime.TryParse(lastEditedTimeProperty.LastEditedTime, out dateTime))
{
return false;
}
break;
default:
if (!TryParsePropertyValueAsPlainText(value, out var plainText))
{
return false;
}
if (!DateTime.TryParse(plainText, out dateTime))
{
return false;
}
break;
}
return true;
}
bool TryParsePropertyValueAsPlainText(PropertyValue value, out string text)
{
text = string.Empty;
switch (value)
{
case RichTextPropertyValue richTextProperty:
foreach (var richText in richTextProperty.RichText)
{
text += richText.PlainText;
}
break;
case TitlePropertyValue titleProperty:
foreach (var richText in titleProperty.Title)
{
text += richText.PlainText;
}
break;
case SelectPropertyValue selectPropertyValue:
text = selectPropertyValue.Select.Name;
break;
default:
return false;
}
return true;
}
bool TryParsePropertyValueAsStringSet(PropertyValue value, out List<string> set)
{
set = new List<string>();
switch (value)
{
case MultiSelectPropertyValue multiSelectProperty:
foreach (var selectValue in multiSelectProperty.MultiSelect)
{
set.Add(selectValue.Name);
}
break;
default:
return false;
}
return true;
}
bool TryParsePropertyValueAsBoolean(PropertyValue value, out bool boolean)
{
boolean = false;
switch (value)
{
case CheckboxPropertyValue checkboxProperty:
boolean = checkboxProperty.Checkbox;
break;
default:
return false;
}
return true;
}
async Task AppendBlockLineAsync(Block block, string indent, string outputDirectory, StringBuilder stringBuilder)
{
switch (block)
{
case ParagraphBlock paragraphBlock:
foreach (var text in paragraphBlock.Paragraph.Text)
{
AppendRichText(text, stringBuilder);
}
stringBuilder.AppendLine(string.Empty);
break;
case HeadingOneBlock h1:
stringBuilder.Append($"{indent}# ");
foreach (var text in h1.Heading_1.Text)
{
AppendRichText(text, stringBuilder);
}
stringBuilder.AppendLine(string.Empty);
break;
case HeadingTwoBlock h2:
stringBuilder.Append($"{indent}## ");
foreach (var text in h2.Heading_2.Text)
{
AppendRichText(text, stringBuilder);
}
stringBuilder.AppendLine(string.Empty);
break;
case HeadingThreeeBlock h3:
stringBuilder.Append($"{indent}### ");
foreach (var text in h3.Heading_3.Text)
{
AppendRichText(text, stringBuilder);
}
stringBuilder.AppendLine(string.Empty);
break;
case ImageBlock imageBlock:
await AppendImageAsync(imageBlock, indent, outputDirectory, stringBuilder);
stringBuilder.AppendLine(string.Empty);
break;
case CodeBlock codeBlock:
AppendCode(codeBlock, indent, stringBuilder);
stringBuilder.AppendLine(string.Empty);
break;
case BulletedListItemBlock bulletListItemBlock:
AppendBulletListItem(bulletListItemBlock, indent, stringBuilder);
break;
case NumberedListItemBlock numberedListItemBlock:
AppendNumberedListItem(numberedListItemBlock, indent, stringBuilder);
break;
}
stringBuilder.AppendLine(string.Empty);
if (block.HasChildren)
{
var pagination = await CreateNotionClient().Blocks.RetrieveChildrenAsync(block.Id);
do
{
foreach (Block childBlock in pagination.Results)
{
await AppendBlockLineAsync(childBlock, $" {indent}", outputDirectory, stringBuilder);
}
if (!pagination.HasMore)
{
break;
}
pagination = await CreateNotionClient().Blocks.RetrieveChildrenAsync(block.Id, new BlocksRetrieveChildrenParameters
{
StartCursor = pagination.NextCursor,
});
} while (true);
}
}
void AppendRichText(RichTextBase richText, StringBuilder stringBuilder)
{
var text = richText.PlainText;
if (!string.IsNullOrEmpty(richText.Href))
{
text = $"[{text}]({richText.Href})";
}
if (richText.Annotations.IsCode)
{
text = $"`{text}`";
}
if (richText.Annotations.IsItalic && richText.Annotations.IsBold)
{
text = $"***{text}***";
}
else if (richText.Annotations.IsBold)
{
text = $"**{text}**";
}
else if (richText.Annotations.IsItalic)
{
text = $"*{text}*";
}
if (richText.Annotations.IsStrikeThrough)
{
text = $"~{text}~";
}
stringBuilder.Append(text);
}
async Task AppendImageAsync(ImageBlock imageBlock, string indent, string outputDirectory, StringBuilder stringBuilder)
{
var url = string.Empty;
switch (imageBlock.Image)
{
case ExternalFile externalFile:
url = externalFile.External.Url;
break;
case UploadedFile uploadedFile:
url = uploadedFile.File.Url;
break;
}
if (!string.IsNullOrEmpty(url))
{
var (fileName, _) = await DownloadImage(url, outputDirectory);
stringBuilder.Append($"{indent}![](./{fileName})");
}
}
async Task<(string, string)> DownloadImage(string url, string outputDirectory)
{
var uri = new Uri(url);
using (var md5 = MD5.Create())
{
var input = Encoding.UTF8.GetBytes(uri.LocalPath);
var fileName = $"{Convert.ToHexString(md5.ComputeHash(input))}{Path.GetExtension(uri.LocalPath)}";
var filePath = $"{outputDirectory}/{fileName}";
// TODO: WebClient is not recommended
var client = new WebClient();
await client.DownloadFileTaskAsync(uri, filePath);
return (fileName, filePath);
}
}
void AppendCode(CodeBlock codeBlock, string indent, StringBuilder stringBuilder)
{
stringBuilder.AppendLine($"{indent}```{NotionCodeLanguageToMarkdownCodeLanguage(codeBlock.Code.Language)}");
foreach (var richText in codeBlock.Code.Text)
{
stringBuilder.Append(indent);
AppendRichText(richText, stringBuilder);
stringBuilder.AppendLine(string.Empty);
}
stringBuilder.AppendLine($"{indent}```");
}
string NotionCodeLanguageToMarkdownCodeLanguage(string language)
{
return language switch
{
"c#" => "csharp",
_ => language,
};
}
void AppendBulletListItem(BulletedListItemBlock bulletedListItemBlock, string indent, StringBuilder stringBuilder)
{
stringBuilder.Append($"{indent}* ");
foreach (var item in bulletedListItemBlock.BulletedListItem.Text)
{
AppendRichText(item, stringBuilder);
}
}
void AppendNumberedListItem(NumberedListItemBlock numberedListItemBlock, string indent, StringBuilder stringBuilder)
{
stringBuilder.Append($"{indent}1. ");
foreach (var item in numberedListItemBlock.NumberedListItem.Text)
{
AppendRichText(item, stringBuilder);
}
}