20100326

Listing your Twitter messages by RSS

Frequently it's useful to list your Twitter messages on web other website or process them in some other way. There are billions of plugins that will allow you to do it but if you need to download them manually it's best to use RSS. You don't need to use API so you don't need to register. Only disadvantage is that you need user ID not his name. You can obtain it from user page - there is a RSS link in right hand column - number in that link is user ID that needs to be passed to the code.

Code below consists of three classes that will get twitts for you. There is also caching so remember that new messages will be fetched only every UPDATE_EVERY_MINUTES minutes.

Single message:

public class TwitterCacheItem
    {
        public string Title {get;set;}
        public string Link {get;set;}
        public string Description {get;set;}
    }

All of them:

public class TwitterCacheChannel : TwitterCacheItem
    {
        public TwitterCacheChannel()
        {
            Items = new List();
            Loaded = false;
        }

        public DateTime NextUpdateTime { get; set; }
        public bool Loaded { get; set; }
        public List Items { get; private set; }
    }

And finally the code:

public class TwitterCache
    {
        private const int UPDATE_EVERY_MINUTES = 60;

        private static SortedList cache = new SortedList();
        private static object cacheLock = new object();


        public static TwitterCacheChannel GetTwitts(int id)
        {
            TwitterCacheChannel result = null;
            lock (cacheLock)
            {
                if (cache.ContainsKey(id))
                {
                    result = cache[id];
                }
            }
            if ((result==null)||
                (result.NextUpdateTime<DateTime.Now))
            {
                result = FetchTwitts(id);
            }
            return result;
        }

        private static string FetchTwittsUrl(int id)
        {
            return String.Format("http://twitter.com/statuses/user_timeline/{0}.rss", id);
        }

        private static TwitterCacheChannel FetchTwitts(int id)
        {
            TwitterCacheChannel result = new TwitterCacheChannel();
            if (id > 0)
            {
                try
                {
                    string url = FetchTwittsUrl(id);
                    string rssText = DownloadWebPage(url);
                    XmlDocument rss = new XmlDocument();
                    rss.LoadXml(rssText);
                    XmlElement channel = rss["rss"]["channel"];
                    result.Title = channel["title"].InnerText;
                    result.Link = channel["link"].InnerText;
                    result.Description = channel["description"].InnerText;
                    foreach (XmlElement node in channel.SelectNodes("item"))
                    {
                        TwitterCacheItem item = new TwitterCacheItem();
                        item.Title = node["title"].InnerText;
                        item.Link = node["link"].InnerText;
                        item.Description = node["description"].InnerText;
                        result.Items.Add(item);
                    }
                    result.Loaded = true;
                }
                catch
                {
                }
            }
            result.NextUpdateTime = DateTime.Now.AddMinutes(UPDATE_EVERY_MINUTES);
            lock (cacheLock)
            {
                if (cache.ContainsKey(id))
                {
                    cache[id] = result;
                }
                else
                {
                    cache.Add(id, result);
                }
            }
            return result;
        }

        private static string DownloadWebPage(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.UserAgent = ".NET Framework/2.0";
            request.Referer = "http://www.example.com/";
            WebResponse response = request.GetResponse();
            Stream webStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(webStream);
            string result = reader.ReadToEnd();
            reader.Close();
            webStream.Close();
            response.Close();
            return result;
        }
    }

No comments: