Last active
August 15, 2016 18:03
-
-
Save abjerner/82b5b87ddb0e506c122a to your computer and use it in GitHub Desktop.
Formatting entities in a Twitter status message (tweet)
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
private string FormatStatusMessageText(TwitterStatusMessage tweet) { | |
// Normally we should be able to call tweet.Entities.GetAllReversed() but that method | |
// will throw an exception if the array of media entities is NULL (which it is if there | |
// are no media attached to the tweet). | |
List<TwitterBaseEntity> entities = new List<TwitterBaseEntity>(); | |
entities.AddRange(tweet.Entities.HashTags); | |
entities.AddRange(tweet.Entities.Urls); | |
entities.AddRange(tweet.Entities.Mentions); | |
if (tweet.Entities.Media != null) entities.AddRange(tweet.Entities.Media); | |
// Get the original text | |
string text = tweet.Text; | |
// We read the entities from back to front so we don't break the indices while manipulating the string | |
foreach (var entity in entities.OrderByDescending(x => x.StartIndex)) { | |
string before = text.Substring(0, entity.StartIndex); | |
string current = text.Substring(entity.StartIndex, entity.EndIndex - entity.StartIndex); | |
string after = text.Substring(entity.EndIndex); | |
if (entity is TwitterHashTagEntity) { | |
TwitterHashTagEntity tag = (TwitterHashTagEntity) entity; | |
text = before + "<a href=\"https://twitter.com/hashtag/" + tag.Text + "?src=hash\">#" + tag.Text + "</a>" + after; | |
} else if (entity is TwitterUrlEntity) { | |
TwitterUrlEntity url = (TwitterUrlEntity) entity; | |
text = before + "<a href=\"" + url.Url + "\">" + url.DisplayUrl + "</a>" + after; | |
} else if (entity is TwitterMentionEntity) { | |
TwitterMentionEntity mention = (TwitterMentionEntity) entity; | |
text = before + "<a href=\"https://twitter.com/" + mention.ScreenName + "\">@" + mention.ScreenName + "</a>" + after; | |
} else if (entity is TwitterMediaEntity) { | |
TwitterMediaEntity media = (TwitterMediaEntity) entity; | |
text = before + "<a href=\"" + media.MediaUrl + "\">" + current + "</a>" + after; | |
} | |
} | |
return text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment