public static async Task <string> TryGetHighlightedCodeAsync([NotNull] string code, [NotNull] string path, SyntaxHighlightStyleEnum style, bool lineNumbers, CancellationToken token) { // Check if the code is possibly invalid const int threshold = 50, length = 1000; if (code.Substring(0, length > code.Length ? code.Length : length).Count( c => char.IsControl(c) && c != '\n' && c != '\r' && c != '\t') > threshold) { return(null); } // Try to extract the code language var match = Regex.Match(path, @".*([.]\w+)"); if (!match.Success || match.Groups.Count != 2) { return(null); } string extension = match.Groups[1].Value.ToLowerInvariant(), lexer = UncommonExtensions.ContainsKey(extension) ? UncommonExtensions[extension] : extension.Substring(1); // Remove the leading '.' // Prepare the POST request content var values = new Dictionary <string, string> { { "code", code }, // The code to highlight { "lexer", lexer }, // The code language { "style", style.ToString().ToLowerInvariant() }, // The requested syntax highlight style { "divstyles", "border:solid gray;border-width:.0em .0em .0em .0em;padding:.2em .6em;" }, // Default CSS properties { "linenos", lineNumbers ? "pls" : string.Empty } // Includes the line numbers if not empty }; // Make the POST var result = await HTTPHelper.POSTWithCacheSupportAsync(APIUrl, values, token); // Check if the lexer is unsupported if (result.StatusCode == HttpStatusCode.InternalServerError) { #if DEBUG //For debugging, inform if an unsupported extesion is found System.Diagnostics.Debug.WriteLine($"Possible unsupported extension: {extension} > {lexer}"); #endif // Retry with the fallback lexer values["lexer"] = FallbackLexer; return((await HTTPHelper.POSTWithCacheSupportAsync(APIUrl, values, token)).Result); } // Return the result return(result.Result); }
/// <summary> /// /// </summary> /// <param name="repoPath">Tuple with Repository, path and branch</param> /// <returns></returns> public async Task Load(Tuple <Repository, string, string> repoPath) { IsSupportedFile = true; Repository = repoPath.Item1; Path = repoPath.Item2; if (!GlobalHelper.IsInternet()) { //Sending NoInternet message to all viewModels Messenger.Default.Send(new GlobalHelper.LocalNotificationMessageType { Message = "No Internet", Glyph = "\uE704" }); } else { isLoading = true; if (string.IsNullOrWhiteSpace(repoPath.Item3)) { SelectedBranch = await RepositoryUtility.GetDefaultBranch(Repository.Id); } else { SelectedBranch = repoPath.Item3; } IsImage = false; if ((Path.ToLower().EndsWith(".exe")) || (Path.ToLower().EndsWith(".pdf")) || (Path.ToLower().EndsWith(".ttf")) || (Path.ToLower().EndsWith(".suo")) || (Path.ToLower().EndsWith(".mp3")) || (Path.ToLower().EndsWith(".mp4")) || (Path.ToLower().EndsWith(".avi"))) { /* * Unsupported file types */ IsSupportedFile = false; isLoading = false; return; } if ((Path.ToLower()).EndsWith(".png") || (Path.ToLower()).EndsWith(".jpg") || (Path.ToLower()).EndsWith(".jpeg") || (Path.ToLower().EndsWith(".gif"))) { /* * Image file types */ IsImage = true; String uri = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.DownloadUrl; if (!string.IsNullOrWhiteSpace(uri)) { ImageFile = new BitmapImage(new Uri(uri)); } isLoading = false; return; } if ((Path.ToLower()).EndsWith(".md")) { /* * Files with .md extension */ TextContent = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.Content; isLoading = false; return; } /* * Code files */ String content = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.Content; if (content == null) { IsSupportedFile = false; isLoading = false; return; } SyntaxHighlightStyleEnum style = (SyntaxHighlightStyleEnum)SettingsService.Get <int>(SettingsKeys.HighlightStyleIndex); bool lineNumbers = SettingsService.Get <bool>(SettingsKeys.ShowLineNumbers); HTMLContent = await HiliteAPI.TryGetHighlightedCodeAsync(content, Path, style, lineNumbers, CancellationToken.None); if (HTMLContent == null) { /* * Plain text files (Getting HTML for syntax highlighting failed) */ RepositoryContent result = await RepositoryUtility.GetRepositoryContentTextByPath(Repository, Path, SelectedBranch); if (result != null) { TextContent = result.Content; } } if (HTMLContent == null && TextContent == null) { IsSupportedFile = false; } isLoading = false; } }