示例#1
0
    private void Convert(string path)
    {
        ConverterOptions options = GetConverterOptions();

        if (path != null)
        {
            if (File.Exists(path))
            {
                MarkdownPath = path;
                _htmlPath    = null;

                Markdown = File.ReadAllText(path).Replace("\t", "  ");
                ConvertMarkdownAndFillTextFields(Markdown, path);

                if (_useContentScanner)
                {
                    print(ContentScanner.ParseScanrResults(ContentScanner.ScanMarkdown(Markdown)));
                }

                if (_saveOutputToHtml)
                {
                    _htmlPath = DragonUtil.GetFullPathWithoutExtension(path) + ".html";
                    Converter.ConvertMarkdownFileToHtmlFile(path, _htmlPath, options);
                }

                UIManager.Instance.HideLoadingScreen();
                UIManager.Instance.SetStatusText("Converted markdown! Copy HTML on right side or start Image Linker (experimental).");
            }
        }
        else
        {
            UIManager.Instance.HideLoadingScreen();
            UIManager.Instance.SetStatusText("No valid markdown chosen!");
        }
    }
 private static GithubRelease.Asset GetAssetMatchingRunningVersion(List <GithubRelease.Asset> assets)
 {
     GithubRelease.Asset releaseAsset = null;
     if (DragonUtil.IsRunningPortable())
     {
         Console.WriteLine("Portable version");
         releaseAsset = assets.Find(asset => asset.name.Contains("Portable"));
     }
     else
     {
         if (DragonUtil.CurrentOperatingSystem.IsWindows())
         {
             releaseAsset = assets.Find(asset => asset.name.Contains("Windows"));
         }
         else if (DragonUtil.CurrentOperatingSystem.IsMacOS())
         {
             releaseAsset = assets.Find(asset => asset.name.Contains("macOS"));
         }
         else if (DragonUtil.CurrentOperatingSystem.IsLinux())
         {
             releaseAsset = assets.Find(asset => asset.name.Contains("linux"));
         }
     }
     return(releaseAsset);
 }
示例#3
0
    private string FixBrokenCode(string markdown)
    {
        string str1 = markdown;
        int    num;

        do
        {
            num = 0;
            List <string> originals    = new List <string>();
            List <string> replacements = new List <string>();
            using (StringReader stringReader = new StringReader(str1))
            {
                string str2;
                while ((str2 = stringReader.ReadLine()) != null)
                {
                    if (str2.Contains("```") && !str2.StartsWith("```"))
                    {
                        ++num;
                        originals.Add(str2.Trim());
                        replacements.Add("```\r\n");
                        string[] strArray = str2.Split(new char[] { '>' }, StringSplitOptions.None);
                        for (int index = 0; index < strArray.Length - 1; ++index)
                        {
                            string wrongCasedClass = strArray[index].Replace("<", "").Replace(">", "").Replace("/", "");
                            originals.Add("<" + wrongCasedClass + ">()");
                            string correctClassCase = FindCorrectClassCase(wrongCasedClass);
                            replacements.Add("<" + correctClassCase + ">()");
                        }
                    }
                }
            }
            str1 = DragonUtil.BatchReplaceText(str1, originals, replacements);
        }while (num > 0);
        return(str1);
    }
        private static void AdjustImages(ref string html, ConverterOptions options, string rootPath = null)
        {
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);
            HtmlNodeCollection imgNodes = doc.DocumentNode.SelectNodes("//img[@src]");
            string             size     = "full";

            if (imgNodes == null || imgNodes.Count == 0)
            {
                return;
            }

            for (var i = 0; i < imgNodes.Count; i++)
            {
                HtmlNode node = imgNodes[i];

                // If root path is known, check if images are too big for full size class
                if (rootPath != null && File.Exists(DragonUtil.GetFullFilePath(node.Attributes["src"].Value, rootPath)))
                {
                    var imageSize = ImageHelper.GetDimensions(DragonUtil.GetFullFilePath(node.Attributes["src"].Value, rootPath));

                    if (imageSize.x > 700)
                    {
                        size = "large";
                    }
                    else
                    {
                        size = "full";
                    }

                    HtmlAttribute width = doc.CreateAttribute("width", imageSize.x.ToString());
                    node.Attributes.Add(width);

                    HtmlAttribute height = doc.CreateAttribute("height", imageSize.y.ToString());
                    node.Attributes.Add(height);
                }

                if (i == 0 && options.FirstImageIsAlignedRight) // First image should be right aligned, it's the 250x250 image
                {
                    HtmlAttribute classAttribute = doc.CreateAttribute("class", "alignright size-" + size);
                    node.Attributes.Add(classAttribute);
                }
                else
                {
                    HtmlAttribute classAttribute = doc.CreateAttribute("class", "aligncenter size-" + size);
                    node.Attributes.Add(classAttribute);
                }

                if (options.AddBordersToImages)
                {
                    //HtmlAttribute attr = doc.CreateAttribute("bordered");
                    //node.Attributes.Add(attr);
                    node.Attributes["class"].Value += " bordered";
                }
            }

            html = doc.DocumentNode.OuterHtml;
        }
示例#5
0
        private void CreateReport(string markdownPath)
        {
            Console.WriteLine("Creating report...");
            string text = DragonUtil.QuickReadFile(markdownPath);

            string report   = ContentScanner.ParseScanrResults(ContentScanner.ScanMarkdown(text, markdownPath));
            string savePath = Path.GetDirectoryName(markdownPath) + Path.GetFileNameWithoutExtension(markdownPath) +
                              "_REPORT.txt";

            DragonUtil.QuickWriteFile(savePath, report);
            Console.WriteLine("Saved report to " + savePath);
        }
示例#6
0
        public static string GetExistingFilePath()
        {
            string path = DragonUtil.RemoveAllQuotes(Console.ReadLine());

            if (File.Exists(path))
            {
                return(path);
            }

            ColoredConsole.WriteLineWithColor("File " + path + " doesn't exist!", ConsoleColor.Red);
            Console.WriteLine("");
            return(null);
        }
    public IEnumerator DownloadImagesRoutine()
    {
        CancelButton.SetActive(false);
        DownloadButton.SetActive(false);

        string imageDirectory = Path.GetDirectoryName(ConvMaster.HtmlFilePath) + "/images";

        Directory.CreateDirectory(imageDirectory);
        List <string> imageUrls       = Converter.FindAllImageLinksInHtml(ConvMaster.OriginalHTML);
        List <string> localImagePaths = new List <string>();

        _downloadDictionary.Clear();
        ConsoleText.text = "";
        HtmlToMarkdownUIManager.Instance.SetProgressMaxValue(imageUrls.Count);
        HtmlToMarkdownUIManager.Instance.SetProgress(0);

        foreach (string fileUrl in imageUrls)
        {
            _downloadDictionary.Add(fileUrl, false);
            string fileName = Path.GetFileName(new Uri(fileUrl).LocalPath);
            localImagePaths.Add("images/" + fileName);

            //DragonUtil.DownloadFile(str, imageDirectory + "/" + fileName, null, 0, null);
            StartCoroutine(DownloadFile(fileUrl, imageDirectory + "/" + fileName));
        }

        yield return(new WaitUntil(() => _amountOfImagesDownloaded == imageUrls.Count));

        int failedDownloads = 0;

        foreach (var link in _downloadDictionary)
        {
            if (link.Value) // Image found
            {
                WriteToLinkConsole("[OK] " + link.Key);
            }
            else
            {
                WriteToLinkConsole("<color=#FF0000>[DOWNLOAD FAILED!] " + link.Key + "</color>");
                failedDownloads++;
            }
        }

        ConvMaster.OriginalHTML = DragonUtil.BatchReplaceText(ConvMaster.OriginalHTML, imageUrls, localImagePaths);
        ConvMaster.Markdown     = DragonUtil.BatchReplaceText(ConvMaster.Markdown, imageUrls, localImagePaths);

        CancelButton.SetActive(true);
        HtmlToMarkdownUIManager.Instance.LoadHtmlPage(0);
        HtmlToMarkdownUIManager.Instance.LoadMarkdownPage(0);
        //Console.WriteLine("Downloads complete!");
    }
        private static void ReplaceImageSources(ref string html, string folder)
        {
            var imageData = Converter.FindAllImageLinksInHtml(html, folder);

            List <string> localPaths = new List <string>();
            List <string> fullPaths  = new List <string>();

            foreach (ImageLinkData data in imageData)
            {
                localPaths.Add(data.LocalImagePath);
                fullPaths.Add(data.FullImagePath);
            }

            html = DragonUtil.BatchReplaceText(html, localPaths, fullPaths);
        }
示例#9
0
        public static bool DownloadFileMonoLinux(string fileToDownload, string savePath, string userAgent = "")
        {
            Console.WriteLine("Downloading " + fileToDownload);
            string userAgentFormatted =
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";

            if (userAgent != "")
            {
                userAgentFormatted = '"' + userAgent + '"';
            }

            ReadProcessOutput("wget",
                              @"--user-agent=" + userAgentFormatted + " -O " + DragonUtil.SurroundWithQuotes(savePath) + " " + fileToDownload);

            return(File.Exists(savePath));
        }
示例#10
0
        public static string GetNewFilePath()
        {
            string path = DragonUtil.RemoveAllQuotes(Console.ReadLine());

            var directoryName = Path.GetDirectoryName(path);

            if (Directory.Exists(directoryName) &&
                DragonUtil.CheckFolderWritePermission(directoryName))
            {
                return(path);
            }

            ColoredConsole.WriteLineWithColor("Invalid folder, can't write to to: " + directoryName, ConsoleColor.Red);

            Console.WriteLine("");
            return(null);
        }
示例#11
0
        private static void AddClassToImages(ref string html, bool firstImageRightAligned, string rootPath = null)
        {
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);
            HtmlNodeCollection imgNodes = doc.DocumentNode.SelectNodes("//img[@src]");
            string             size     = "full";

            if (imgNodes == null || imgNodes.Count == 0)
            {
                return;
            }

            for (var i = 0; i < imgNodes.Count; i++)
            {
                HtmlNode node = imgNodes[i];

                // If root path is known, check if images are too big for full size class
                if (rootPath != null)
                {
                    var imageSize = ImageHelper.GetDimensions(DragonUtil.GetFullFilePath(node.Attributes["src"].Value, rootPath));

                    if (imageSize.Width > 700)
                    {
                        size = "large";
                    }
                    else
                    {
                        size = "full";
                    }
                }

                if (i == 0 && firstImageRightAligned) // First image should be right aligned, it's the 250x250 image
                {
                    HtmlAttribute classAttribute = doc.CreateAttribute("class", "alignright size-" + size);
                    node.Attributes.Add(classAttribute);
                }
                else
                {
                    HtmlAttribute classAttribute = doc.CreateAttribute("class", "aligncenter size-" + size);
                    node.Attributes.Add(classAttribute);
                }
            }

            html = doc.DocumentNode.OuterHtml;
        }
示例#12
0
        private static void StartAppUpdate(GithubRelease newestRelease)
        {
            // Copy updater.exe  to folder above
            // Run updater.exe on folder above
            // Updater gets current folder & path to zip as arguments & starts
            // This app exists

            // Preparation
            Console.WriteLine("Downloading new release...");

            string downloadUrl  = "";
            string downloadName = "";

            foreach (GithubRelease.Asset asset in newestRelease.assets)
            {
                if (asset.name.Contains("GUI"))
                {
                    downloadName = asset.name;
                    downloadUrl  = asset.browser_download_url;
                }
            }

            string zipPath        = Directory.GetParent(Application.StartupPath) + "/" + downloadName;
            string newUpdaterPath = Directory.GetParent(Application.StartupPath) + "/RWUpdater.exe";

            //Download update
            MonoHelper.DownloadFile(downloadUrl, zipPath,
                                    "MarkdownToRW_Converter");


            // Copy updater to folder above
            if (File.Exists(newUpdaterPath))
            {
                File.Delete(newUpdaterPath);
            }

            File.Copy(Application.StartupPath + "/RWUpdater.exe", newUpdaterPath);
            File.Copy(Application.StartupPath + "/DotNetZip.dll",
                      Directory.GetParent(Application.StartupPath) + "/DotNetZip.dll");

            // Run updater & quit
            Process.Start(newUpdaterPath,
                          DragonUtil.SurroundWithQuotes(Application.StartupPath) + " " + DragonUtil.SurroundWithQuotes(zipPath));
            Environment.Exit(0);
        }
        private static void RunCoreUpdater(string updaterFolder, string zipPath)
        {
            Console.WriteLine("Starting updater process...");

            ProcessStartInfo processInfo = new ProcessStartInfo()
            {
                ErrorDialog     = true,
                UseShellExecute = true
            };

            if (DragonUtil.IsRunningPortable())
            {
                processInfo.FileName = "dotnet";
                //processInfo.Arguments = "dotnet'";
                processInfo.Arguments += DragonUtil.SurroundWithQuotes(updaterFolder + "/CoreUpdater.dll");
            }
            else
            {
                if (DragonUtil.CurrentOperatingSystem.IsWindows())
                {
                    processInfo.FileName = DragonUtil.SurroundWithQuotes(updaterFolder + "/CoreUpdater.exe");
                }
                else if (DragonUtil.CurrentOperatingSystem.IsMacOS())
                {
                    processInfo.FileName = DragonUtil.SurroundWithQuotes(updaterFolder + "/CoreUpdater");
                }
                else if (DragonUtil.CurrentOperatingSystem.IsLinux())
                {
                    processInfo.FileName = DragonUtil.SurroundWithQuotes(updaterFolder + "/CoreUpdater");
                }
            }

            processInfo.Arguments += " " + DragonUtil.SurroundWithQuotes(DragonUtil.CurrentDirectory) + " " +
                                     DragonUtil.SurroundWithQuotes(zipPath);

            Console.WriteLine(processInfo.FileName + processInfo.Arguments);

            Process process = new Process {
                StartInfo = processInfo
            };

            process.Start();
        }
示例#14
0
        private void btnShowPreview_Click(object sender, EventArgs e)
        {
            if (_markdownPath == null)
            {
                MessageBox.Show("No markdown loaded! Please open a markdown file first.", "No markdown");
                return;
            }

            string htmlPath = CreatePreviewHtml();


            if (MonoHelper.IsRunningOnMono)
            {
                Process.Start(htmlPath);
            }
            else
            {
                DragonUtil.OpenFileInDefaultApplication(htmlPath);
            }
        }
        public static async Task UpdateApp(GithubRelease release, IProgress <SimpleTaskProgress> taskProgress)
        {
            Console.WriteLine("Starting update...");
            List <GithubRelease.Asset> assets = release.assets.Where(asset => asset.name.Contains("GUI")).ToList();

            GithubRelease.Asset downloadAsset = GetAssetMatchingRunningVersion(assets);

            string downloadUrl   = downloadAsset.browser_download_url;
            string zipPath       = Directory.GetParent(DragonUtil.CurrentDirectory).FullName + "/" + downloadAsset.name;
            string updaterFolder = Directory.GetParent(DragonUtil.CurrentDirectory).FullName + "/CoreUpdater";

            if (downloadUrl == null)
            {
                return;
            }

            if (File.Exists(zipPath))
            {
                File.Delete(zipPath);
            }

            Console.WriteLine("Downloading " + downloadUrl + "...");
            var progress = new Progress <SimpleTaskProgress>();

            progress.ProgressChanged += (sender, simpleTaskProgress) => taskProgress.Report(simpleTaskProgress);
            await DragonUtil.DownloadFile(downloadUrl, zipPath, "MarkdownToRW_Converter", downloadAsset.size / 1024, progress);

            // extract updater zip to parent folder
            ExtractZipToFolder(DragonUtil.CurrentDirectory + "/CoreUpdater.zip", updaterFolder);

            // run updater, point to this folder & downloaded zip
            if (DragonUtil.CurrentOperatingSystem.IsMacOS() || DragonUtil.CurrentOperatingSystem.IsLinux())
            {
                await DragonUtil.TryToMakeExecutable(updaterFolder + "/CoreUpdater");
            }

            RunCoreUpdater(updaterFolder, zipPath);

            // close app
            Environment.Exit(0);
        }
示例#16
0
        public string ConvertToHtml(string markdownPath, string htmlPath, ConverterOptions options)
        {
            Console.WriteLine("Converting " + markdownPath + " to RW WordPress ready HTML...");

            if (htmlPath == null)
            {
                htmlPath = DragonUtil.GetFullPathWithoutExtension(markdownPath) + ".html";
            }

            if (DragonUtil.CheckFolderWritePermission(Path.GetDirectoryName(htmlPath)))
            {
                Converter.ConvertMarkdownFileToHtmlFile(markdownPath, htmlPath, options);
                Console.WriteLine("Saved HTML to custom location: " + htmlPath);
            }
            else
            {
                ColoredConsole.WriteLineWithColor("Conversion aborted, can't write to " + htmlPath, ConsoleColor.Red);
            }

            return(htmlPath);
        }
示例#17
0
        public static MarkdownAndHtml ReplaceLocalImageLinksWithUrls(string markdownPath, string markdownText, string htmlPath, string htmlText, bool onlyUpdateHtml, List <string> localImagePaths, List <string> imageUrls)
        {
            markdownText = DragonUtil.BatchReplaceText(markdownText, localImagePaths, imageUrls);
            htmlText     = DragonUtil.BatchReplaceText(htmlText, localImagePaths, imageUrls);
            //var htmlText = ConvertMarkdownStringToHtml(markdownText,);

            if (htmlPath != null)
            {
                DragonUtil.QuickWriteFile(htmlPath, htmlText);
                Console.WriteLine("Replaced HTML!");
            }

            if (!onlyUpdateHtml)
            {
                DragonUtil.QuickWriteFile(markdownPath, markdownText);
                Console.WriteLine("Replaced Markdown!");
            }

            return(new MarkdownAndHtml {
                Markdown = markdownText, Html = htmlText
            });
        }
        public static void StartInteractive()
        {
            Console.WriteLine(" +-------------------------------------+");
            Console.WriteLine(" |                                     |");
            Console.WriteLine(" |          Interactive Wizard         |");
            Console.WriteLine(" |                                     |");
            Console.WriteLine(" +-------------------------------------+");

            string markdownPath = null;
            string htmlPath     = null;

            while (markdownPath == null)
            {
                Console.WriteLine("Please provide the path to the markdown file:");
                markdownPath = CoreConsoleShared.GetExistingFilePath();
            }

            string firstImageRight = null;

            while (firstImageRight != "y" && firstImageRight != "n")
            {
                Console.WriteLine(
                    "Should the first image be right aligned? This is useful for the 250x250 image at the top of tutorials. (y/n)");
                firstImageRight = Console.ReadLine();
            }

            string convertImagesWithAlt = null;

            while (convertImagesWithAlt != "y" && convertImagesWithAlt != "n")
            {
                Console.WriteLine(
                    "Should all images with an alt text be converted to captions? (y/n)");
                convertImagesWithAlt = Console.ReadLine();
            }

            string sameFolder = null;

            while (sameFolder != "y" && sameFolder != "n")
            {
                Console.WriteLine(
                    "Do you want to output the HTML file containing the WordPress ready code to the same folder as the markdown file? (y/n)");
                sameFolder = Console.ReadLine();
            }

            if (sameFolder == "y")
            {
                htmlPath = DragonUtil.GetFullPathWithoutExtension(markdownPath) + ".html";
            }
            else
            {
                while (htmlPath == null || htmlPath == markdownPath)
                {
                    if (htmlPath == markdownPath)
                    {
                        Console.WriteLine(
                            "Output file can't be the same as the input file! This WILL lead to data loss.");
                    }

                    Console.WriteLine("Please provide the location and name for the output html file:");
                    Console.WriteLine("(e.g. C:\\MyNewFile.html)");
                    htmlPath = CoreConsoleShared.GetNewFilePath();
                }
            }

            string uploadImages = null;

            while (uploadImages != "y" && uploadImages != "n" && uploadImages != "only html")
            {
                Console.WriteLine(
                    "Do you want to upload all images and update the links in both the markdown file and the generated html? (y/only html/n)");
                uploadImages = Console.ReadLine();
            }

            string ready = null;

            while (ready != "y" && ready != "n")
            {
                Console.WriteLine("Ready to start the conversion!");
                Console.WriteLine("");
                Console.WriteLine("Parameters:");
                Console.WriteLine("Markdown file path (input): " + markdownPath);
                Console.WriteLine("Generated HTML file path (output): " + htmlPath);
                Console.WriteLine("Upload images and update markdown and generated HTML file: " + uploadImages);
                Console.WriteLine("");
                Console.WriteLine("Are these parameters correct? (y/n)");
                ready = Console.ReadLine();
            }

            if (ready == "n")
            {
                Console.WriteLine("Conversion aborted.");
                return;
            }

            ConverterOptions options = new ConverterOptions
            {
                FirstImageIsAlignedRight = CoreConsoleShared.YesNoToBool(firstImageRight)
            };

            switch (uploadImages)
            {
            case "y":
                DoConversion(markdownPath, htmlPath, true, false, options);
                break;

            case "only html":
                DoConversion(markdownPath, htmlPath, true, true, options);
                break;

            case "n":
                DoConversion(markdownPath, htmlPath, false, false, options);
                break;
            }
        }
示例#19
0
 public static void OpenHtmlResult(string generatedHtmlPath)
 {
     Console.WriteLine("Opening HTML file in default application...");
     DragonUtil.OpenFileInDefaultApplication(generatedHtmlPath);
 }