aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Services/MarkdownProcessor.cs
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2021-03-06 22:51:53 +0800
committercrupest <crupest@outlook.com>2021-03-06 22:51:53 +0800
commit8f09e3172f249a9f5d229040415a0569e9d1c01b (patch)
tree59507331750831118e7caa071a10e1cb8fc1e627 /BackEnd/Timeline/Services/MarkdownProcessor.cs
parent24c272403ba360f27acd68c2702c678a86063964 (diff)
downloadtimeline-8f09e3172f249a9f5d229040415a0569e9d1c01b.tar.gz
timeline-8f09e3172f249a9f5d229040415a0569e9d1c01b.tar.bz2
timeline-8f09e3172f249a9f5d229040415a0569e9d1c01b.zip
feat: Auto translate url in markdown post.
Diffstat (limited to 'BackEnd/Timeline/Services/MarkdownProcessor.cs')
-rw-r--r--BackEnd/Timeline/Services/MarkdownProcessor.cs52
1 files changed, 52 insertions, 0 deletions
diff --git a/BackEnd/Timeline/Services/MarkdownProcessor.cs b/BackEnd/Timeline/Services/MarkdownProcessor.cs
new file mode 100644
index 00000000..f34432cd
--- /dev/null
+++ b/BackEnd/Timeline/Services/MarkdownProcessor.cs
@@ -0,0 +1,52 @@
+using System;
+using System.IO;
+using System.Linq;
+using System.Text;
+using Markdig;
+using Markdig.Renderers.Normalize;
+using Markdig.Syntax;
+using Markdig.Syntax.Inlines;
+using Microsoft.AspNetCore.Mvc;
+using Timeline.Controllers;
+
+namespace Timeline.Services
+{
+ public class MarkdownProcessor
+ {
+ public string Process(string text, Func<long, string> urlGenerator)
+ {
+ MarkdownDocument markdown = Markdown.Parse(text);
+ foreach (var link in markdown.Descendants().Where(e => e is LinkInline).Cast<LinkInline>())
+ {
+ if (int.TryParse(link.Url, out var dataIndex))
+ {
+ link.Url = urlGenerator(dataIndex);
+ }
+ }
+
+ var writer = new StringWriter();
+ NormalizeRenderer renderer = new NormalizeRenderer(writer);
+ renderer.Render(markdown);
+
+ return writer.ToString();
+ }
+
+ /// <summary>Convert data url to true url with post id.</summary>
+ public string Process(string text, IUrlHelper url, string timeline, long post)
+ {
+ return Process(
+ text,
+ dataIndex => url.ActionLink(
+ nameof(TimelinePostController.DataGet),
+ nameof(TimelinePostController)[0..^nameof(Controller).Length],
+ new { timeline, post, data_index = dataIndex }
+ )
+ );
+ }
+
+ public byte[] Process(byte[] data, IUrlHelper url, string timeline, long post)
+ {
+ return Encoding.UTF8.GetBytes(Process(Encoding.UTF8.GetString(data), url, timeline, post));
+ }
+ }
+}