Created
September 4, 2012 07:03
-
-
Save kenegozi/3617851 to your computer and use it in GitHub Desktop.
Given a gist embed script tag, get the gist's content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GistsResolver { | |
public static string CreateContentForFeedFrom(string content) { | |
try { | |
return UnwrapGists(content, GetGist); | |
} | |
catch { | |
return content; | |
} | |
} | |
static readonly Regex GistsFinder = new Regex("<script src=\"https://gist.github.com/(?<gistid>\\d+).js(\\?file=(?<file>[^\"]+))?\">\\s*</script>", RegexOptions.Compiled); | |
static JObject GetGist(string gistId) { | |
try { | |
var content = | |
new WebClient().DownloadString("https://api.github.com/gists/" + gistId); | |
var gist = JObject.Parse(content); | |
return gist; | |
} | |
catch (Exception) { | |
return null; | |
} | |
} | |
private static string ContentToHtml(JObject file) { | |
var content = file["content"].Value<string>(); | |
content = content.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"); | |
content = Microsoft.Security.Application.Encoder.HtmlEncode(content, true); | |
content = content.Replace(" ", "\n").Replace(" ", "\r"); | |
content = "<pre>" + content + "</pre>"; | |
var name = file["filename"].Value<string>(); | |
if (!string.IsNullOrEmpty(name)) { | |
content = Microsoft.Security.Application.Encoder.HtmlEncode(name, true) | |
+ ":<br/>" | |
+ content; | |
} | |
return content; | |
} | |
private static string UnwrapGists(string c, Func<string, JObject> gistGetter) { | |
return GistsFinder.Replace(c, match => { | |
try { | |
var gistId = match.Groups["gistid"].Value; | |
var gistData = gistGetter(gistId); | |
var fileName = match.Groups["file"].Success | |
? match.Groups["file"].Value | |
: null; | |
var content = string.Empty; | |
var url = gistData["html_url"].Value<string>(); | |
if (fileName != null) { | |
var file = (JObject)gistData["files"][fileName]; | |
content = ContentToHtml(file); | |
} | |
else { | |
foreach (JProperty fileProp in gistData["files"]) { | |
var file = fileProp.Value.Value<JObject>(); | |
content += ContentToHtml(file); | |
} | |
} | |
content += "<br/>" | |
+ "<a href='" + Microsoft.Security.Application.Encoder.HtmlAttributeEncode(url) + "' title='I ♥ github'>" | |
+ "(see the most recent version of this gist)</a>"; | |
content = "<p>" + content + "</p>"; | |
return content; | |
} | |
catch (Exception ex) { | |
return match.ToString(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment