Skip to content

Instantly share code, notes, and snippets.

@kenegozi
Created September 4, 2012 07:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenegozi/3617851 to your computer and use it in GitHub Desktop.
Save kenegozi/3617851 to your computer and use it in GitHub Desktop.
Given a gist embed script tag, get the gist's content
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("&#10;", "\n").Replace("&#13;", "\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 &hearts; 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