Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.