Skip to content

Commit

Permalink
Add MD2HTML Tool
Browse files Browse the repository at this point in the history
  • Loading branch information
sm6srw committed Nov 17, 2020
1 parent d5a84fc commit 71509da
Show file tree
Hide file tree
Showing 6 changed files with 289 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Dynamo.All.sln
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PythonMigrationViewExtensio
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NodeAutoCompleteViewExtension", "NodeAutoCompleteViewExtension\NodeAutoCompleteViewExtension.csproj", "{51511AFD-F326-4995-8E27-5D711419EF6F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MD2HTML", "Tools\MD2HTML\MD2HTML.csproj", "{0893F745-CB1A-427A-8E87-CA927273039A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -859,6 +861,14 @@ Global
{51511AFD-F326-4995-8E27-5D711419EF6F}.Release|Any CPU.Build.0 = Release|Any CPU
{51511AFD-F326-4995-8E27-5D711419EF6F}.Release|x64.ActiveCfg = Release|x64
{51511AFD-F326-4995-8E27-5D711419EF6F}.Release|x64.Build.0 = Release|x64
{0893F745-CB1A-427A-8E87-CA927273039A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0893F745-CB1A-427A-8E87-CA927273039A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0893F745-CB1A-427A-8E87-CA927273039A}.Debug|x64.ActiveCfg = Debug|Any CPU
{0893F745-CB1A-427A-8E87-CA927273039A}.Debug|x64.Build.0 = Debug|Any CPU
{0893F745-CB1A-427A-8E87-CA927273039A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0893F745-CB1A-427A-8E87-CA927273039A}.Release|Any CPU.Build.0 = Release|Any CPU
{0893F745-CB1A-427A-8E87-CA927273039A}.Release|x64.ActiveCfg = Release|Any CPU
{0893F745-CB1A-427A-8E87-CA927273039A}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -935,6 +945,7 @@ Global
{182FCA4E-B6EF-451F-9EC4-7BF2C622F4F7} = {88D45B00-E564-41DB-B57C-9509646CAA49}
{10AF430D-0D3A-49CE-A63D-848912959745} = {88D45B00-E564-41DB-B57C-9509646CAA49}
{51511AFD-F326-4995-8E27-5D711419EF6F} = {88D45B00-E564-41DB-B57C-9509646CAA49}
{0893F745-CB1A-427A-8E87-CA927273039A} = {D114C59C-CF66-4CC2-980F-9301FB4EA4E1}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {89CB19C6-BF0A-4E6A-BFDA-79D143EAB59D}
Expand Down
6 changes: 6 additions & 0 deletions src/Tools/MD2HTML/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
62 changes: 62 additions & 0 deletions src/Tools/MD2HTML/MD2HTML.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0893F745-CB1A-427A-8E87-CA927273039A}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>MD2HTML</RootNamespace>
<AssemblyName>MD2HTML</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\bin\AnyCPU\Debug\MD2HTML\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\..\bin\AnyCPU\Release\MD2HTML\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="MarkdownHandler.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="HtmlSanitizer">
<Version>5.0.355</Version>
</PackageReference>
<PackageReference Include="Markdig">
<Version>0.22.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
109 changes: 109 additions & 0 deletions src/Tools/MD2HTML/MarkdownHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System;
using System.IO;
using System.Linq;
using Ganss.XSS;
using Markdig;
using Markdig.Parsers;
using Markdig.Renderers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;

namespace MD2HTML
{
/// <summary>
/// Handles markdown files by converting them to Html, so they can display in a browser
/// </summary>
internal class MarkdownHandler
{
private readonly MarkdownPipeline pipeline;


private static MarkdownHandler instance;
internal static MarkdownHandler Instance
{
get
{
if (instance is null) { instance = new MarkdownHandler(); }
return instance;
}
}

private MarkdownHandler()
{
var pipelineBuilder = new MarkdownPipelineBuilder();
pipeline = pipelineBuilder
.UseAdvancedExtensions()
.Build();
}

/// <summary>
/// Converts a markdown string into Html.
/// </summary>
/// <param name="writer"></param>
/// <param name="mdString"></param>
/// <returns>Returns true if any script tags was removed from the string</returns>
internal void ParseToHtml(ref StringWriter writer, string mdString, string mdPath)
{
if (writer is null)
throw new ArgumentNullException(nameof(writer));

if (string.IsNullOrWhiteSpace(mdString))
return;

// Remove scripts from user content for security reasons.
RemoveScriptTagsFromString(ref mdString);

var renderer = new HtmlRenderer(writer);
pipeline.Setup(renderer);

var document = MarkdownParser.Parse(mdString, pipeline);
ConvertRelativeLocalImagePathsToAbsolute(mdPath, document);

renderer.Render(document);
}

/// <summary>
/// For markdown local images needs to be in the same folder as the md file
/// referencing it with a relative path "./image.png", when we convert to html
/// we need the full path. This method finds relative image paths and converts them to absolute paths.
/// </summary>
private static void ConvertRelativeLocalImagePathsToAbsolute(string mdFilePath, MarkdownDocument document)
{
var imageLinks = document.Descendants<ParagraphBlock>()
.SelectMany(x => x.Inline.Descendants<LinkInline>())
.Where(x => x.IsImage)
.Select(x => x).ToList();

foreach (var image in imageLinks)
{
if (!image.Url.StartsWith("./"))
continue;

var imageName = image.Url.Split(new string[] { "./" }, StringSplitOptions.None);
var dir = Path.GetDirectoryName(mdFilePath);

var htmlImagePathPrefix = @"file:///";
var absoluteImagePath = Path.Combine(dir, imageName.Last());

image.Url = $"{htmlImagePathPrefix}{absoluteImagePath}";
}
}

private static HtmlSanitizer htmlSanitizer = new HtmlSanitizer();

/// <summary>
/// Clean up possible dangerous HTML content from the content string.
/// </summary>
/// <param name="content"></param>
/// <returns>Returns true if any content was removed from the content string</returns>
internal static bool RemoveScriptTagsFromString(ref string content)
{
var sanitizedContent = htmlSanitizer.Sanitize(content);
if (content.Equals(sanitizedContent))
return false;

content = sanitizedContent;
return true;
}
}
}
65 changes: 65 additions & 0 deletions src/Tools/MD2HTML/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.IO;

namespace MD2HTML
{
static class Program
{
static void Main(string[] args)
{
Console.WriteLine("");

while (true)
{
var line = Console.ReadLine();
if (line == "<<<<<Sanitize>>>>>")
{
Sanitize();
}
else if (line == "<<<<<Convert>>>>>")
{
Convert();
}
Console.WriteLine("<<<<<Eod>>>>>");
}
}

static void Sanitize()
{
StringWriter data = new StringWriter();
GetData(ref data);

string output = data.ToString();
MarkdownHandler.RemoveScriptTagsFromString(ref output);

Console.WriteLine(output);
}

static void Convert()
{
var mdPath = Console.ReadLine();

StringWriter data = new StringWriter();
GetData(ref data);

var instance = MarkdownHandler.Instance;
StringWriter output = new StringWriter();
instance.ParseToHtml(ref output, data.ToString(), mdPath);

Console.WriteLine(output.ToString());
}

static void GetData(ref StringWriter data)
{
while (true)
{
var line = Console.ReadLine();
if (line == "<<<<<Eod>>>>>")
{
break;
}
data.WriteLine(line);
}
}
}
}
36 changes: 36 additions & 0 deletions src/Tools/MD2HTML/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MD2HTML")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MD2HTML")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0893f745-cb1a-427a-8e87-ca927273039a")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

0 comments on commit 71509da

Please sign in to comment.