diff Agendas/trunk/src/Agendas.Twitter/oAuthTwitter.cs @ 107:1ee5711256db

Utilizando Twitterizer en adapter a Twitter
author Nelo@Kenia.neluz.int
date Tue, 07 Jun 2011 21:03:56 -0300
parents db4b1e2cae49
children a456eb519e23
line wrap: on
line diff
--- a/Agendas/trunk/src/Agendas.Twitter/oAuthTwitter.cs	Sat Jun 04 19:41:40 2011 -0300
+++ b/Agendas/trunk/src/Agendas.Twitter/oAuthTwitter.cs	Tue Jun 07 21:03:56 2011 -0300
@@ -1,257 +1,51 @@
-using System;
+using System;
 using System.Configuration;
-using System.Web;
-using System.Net;
-using System.IO;
-using System.Collections.Specialized;
+using Twitterizer;
 
 namespace AltNetHispano.Agendas.Twitter
 {
-    public class OAuthTwitter : OAuthBase
-    {
-        public enum Method { GET, POST, DELETE };
-        public const string REQUEST_TOKEN = "http://twitter.com/oauth/request_token";
-        public const string AUTHORIZE = "http://twitter.com/oauth/authorize";
-        public const string ACCESS_TOKEN = "http://twitter.com/oauth/access_token";
-
-        private string _consumerKey = "";
-        private string _consumerSecret = "";
-        private string _token = "";
-        private string _tokenSecret = "";
-        private string _callBackUrl = "oob";
-        private string _oauthVerifier = "";
-
-    	private string ConsumerKey 
-        {
-            get
-            {
-                if (_consumerKey.Length == 0)
-                {
-                    _consumerKey = ConfigurationManager.AppSettings["consumerKey"];
-                }
-                return _consumerKey; 
-            }
-        }
-
-    	private string ConsumerSecret { 
-            get {
-                if (_consumerSecret.Length == 0)
-                {
-                    _consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
-                }
-                return _consumerSecret; 
-            } 
-        }
-
-        public string Token { get { return _token; } set { _token = value; } }
-        public string TokenSecret { get { return _tokenSecret; } set { _tokenSecret = value; } }
-        public string CallBackUrl { get { return _callBackUrl; } set { _callBackUrl = value; } }
-        public string OAuthVerifier { get { return _oauthVerifier; } set { _oauthVerifier = value; } }
-
-        /// <summary>
-        /// Get the link to Twitter's authorization page for this application.
-        /// </summary>
-        /// <returns>The url with a valid request token, or a null string.</returns>
-        public string AuthorizationLinkGet()
-        {
-            string ret = null;
-
-            string response = OAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty);
-            if (response.Length > 0)
-            {
-                //response contains token and token secret.  We only need the token.
-                NameValueCollection qs = HttpUtility.ParseQueryString(response);
+	public class OAuthTwitter
+	{
+		private string ConsumerKey
+		{
+			get { return ConfigurationManager.AppSettings["consumerKey"]; }
+		}
 
-                if (qs["oauth_callback_confirmed"] != null)
-                {
-                    if (qs["oauth_callback_confirmed"] != "true")
-                    {
-                        throw new Exception("OAuth callback not confirmed.");
-                    }
-                }
-
-                if (qs[OAuthTokenKey] != null)
-                {
-					ret = AUTHORIZE + "?" + OAuthTokenKey + "=" + qs[OAuthTokenKey];
-                }
-            }
-            return ret;
-        }
-
-        /// <summary>
-        /// Exchange the request token for an access token.
-        /// </summary>
-        /// <param name="authToken">The oauth_token is supplied by Twitter's authorization page following the callback.</param>
-        /// <param name="oauthVerifier">An oauth_verifier parameter is provided to the client either in the pre-configured callback URL</param>
-        public void AccessTokenGet(string authToken, string oauthVerifier)
-        {
-            Token = authToken;
-            OAuthVerifier = oauthVerifier;
-
-            string response = OAuthWebRequest(Method.GET, ACCESS_TOKEN, String.Empty);
+		private string ConsumerSecret
+		{
+			get { return ConfigurationManager.AppSettings["consumerSecret"]; }
+		}
 
-            if (response.Length > 0)
-            {
-                //Store the Token and Token Secret
-                NameValueCollection qs = HttpUtility.ParseQueryString(response);
-                if (qs[OAuthTokenKey] != null)
-                {
-					Token = qs[OAuthTokenKey];
-                }
-				if (qs[OAuthTokenSecretKey] != null)
-                {
-					TokenSecret = qs[OAuthTokenSecretKey];
-                }
-            }
-        }
-        
-        /// <summary>
-        /// Submit a web request using oAuth.
-        /// </summary>
-        /// <param name="method">GET or POST</param>
-        /// <param name="url">The full url, including the querystring.</param>
-        /// <param name="postData">Data to post (querystring format)</param>
-        /// <returns>The web server response.</returns>
-        public string OAuthWebRequest(Method method, string url, string postData)
-        {
-            string outUrl;
-            string querystring;
-            string ret;
+		public Uri AuthorizationLinkGet(string callbackAddress)
+		{
+			// Obtain a request token
+			OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, callbackAddress);
 
+			// Direct or instruct the user to the following address:
+			Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);
+
+			return authorizationUri;
+		}
 
-            //Setup postData for signing.
-            //Add the postData to the querystring.
-            if (method == Method.POST || method == Method.DELETE)
-            {
-                if (postData.Length > 0)
-                {
-                    //Decode the parameters and re-encode using the oAuth UrlEncode method.
-                    NameValueCollection qs = HttpUtility.ParseQueryString(postData);
-                    postData = "";
-                    foreach (string key in qs.AllKeys)
-                    {
-                        if (postData.Length > 0)
-                        {
-                            postData += "&";
-                        }
-                        qs[key] = HttpUtility.UrlDecode(qs[key]);
-                        qs[key] = UrlEncode(qs[key]);
-                        postData += key + "=" + qs[key];
-
-                    }
-                    if (url.IndexOf("?") > 0)
-                    {
-                        url += "&";
-                    }
-                    else
-                    {
-                        url += "?";
-                    }
-                    url += postData;
-                }
-            }
-
-            var uri = new Uri(url);
-            
-            string nonce = GenerateNonce();
-            string timeStamp = GenerateTimeStamp();
-
-            //Generate Signature
-            string sig = GenerateSignature(uri,
-                ConsumerKey,
-                ConsumerSecret,
-                Token,
-                TokenSecret,
-                CallBackUrl,
-                OAuthVerifier,
-                method.ToString(),
-                timeStamp,
-                nonce,
-                out outUrl,
-                out querystring);
-
-        	querystring += "&" + OAuthSignatureKey + "=" + UrlEncode(sig);
-
-            //Convert the querystring to postData
-            if (method == Method.POST || method == Method.DELETE)
-            {
-                postData = querystring;
-                querystring = "";
-            }
-
-            if (querystring.Length > 0)
-            {
-                outUrl += "?";
-            }
-
-            ret = WebRequest(method, outUrl +  querystring, postData);
+		public string AccessTokenGet(string requestToken, string verifier)
+		{
+			OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken, verifier);
+			if (accessToken!=null)
+			{
+				var tokens = new OAuthTokens
+				             	{
+				             		AccessToken = accessToken.Token,
+				             		AccessTokenSecret = accessToken.TokenSecret,
+				             		ConsumerKey = ConsumerKey,
+				             		ConsumerSecret = ConsumerSecret
+				             	};
 
-            return ret;
-        }
-
-        /// <summary>
-        /// Web Request Wrapper
-        /// </summary>
-        /// <param name="method">Http Method</param>
-        /// <param name="url">Full url to the web resource</param>
-        /// <param name="postData">Data to post in querystring format</param>
-        /// <returns>The web server response.</returns>
-        public string WebRequest(Method method, string url, string postData)
-        {
-            HttpWebRequest webRequest;
-            StreamWriter requestWriter;
-            string responseData;
-
-            webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
-            webRequest.Method = method.ToString();
-            webRequest.ServicePoint.Expect100Continue = false;
-            //webRequest.UserAgent  = "Identify your application please.";
-            //webRequest.Timeout = 20000;
-
-            if (method == Method.POST || method == Method.DELETE)
-            {
-                webRequest.ContentType = "application/x-www-form-urlencoded";
-
-                //POST the data.
-                requestWriter = new StreamWriter(webRequest.GetRequestStream());
-                try
-                {
-                    requestWriter.Write(postData);
-                }
-                finally
-                {
-                    requestWriter.Close();
-                }
-            }
-
-            responseData = WebResponseGet(webRequest);
-
-        	return responseData;
-
-        }
-
-        /// <summary>
-        /// Process the web response.
-        /// </summary>
-        /// <param name="webRequest">The request object.</param>
-        /// <returns>The response data.</returns>
-        public string WebResponseGet(HttpWebRequest webRequest)
-        {
-            StreamReader responseReader = null;
-            string responseData;
-
-            try
-            {
-                responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
-                responseData = responseReader.ReadToEnd();
-            }
-            finally
-            {
-                webRequest.GetResponse().GetResponseStream().Close();
-                responseReader.Close();
-            }
-
-            return responseData;
-        }
-    }
+				TwitterResponse<TwitterUser> showUserResponse = TwitterUser.Show(tokens, accessToken.UserId);
+				if (showUserResponse.Result == RequestResult.Success)
+					return showUserResponse.Content;
+				return showUserResponse.ErrorMessage;
+			}
+			return string.Empty;
+		}
+	}
 }