comparison 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
comparison
equal deleted inserted replaced
97:2434c2323f3d 107:1ee5711256db
1 using System; 1 using System;
2 using System.Configuration; 2 using System.Configuration;
3 using System.Web; 3 using Twitterizer;
4 using System.Net;
5 using System.IO;
6 using System.Collections.Specialized;
7 4
8 namespace AltNetHispano.Agendas.Twitter 5 namespace AltNetHispano.Agendas.Twitter
9 { 6 {
10 public class OAuthTwitter : OAuthBase 7 public class OAuthTwitter
11 { 8 {
12 public enum Method { GET, POST, DELETE }; 9 private string ConsumerKey
13 public const string REQUEST_TOKEN = "http://twitter.com/oauth/request_token"; 10 {
14 public const string AUTHORIZE = "http://twitter.com/oauth/authorize"; 11 get { return ConfigurationManager.AppSettings["consumerKey"]; }
15 public const string ACCESS_TOKEN = "http://twitter.com/oauth/access_token"; 12 }
16 13
17 private string _consumerKey = ""; 14 private string ConsumerSecret
18 private string _consumerSecret = ""; 15 {
19 private string _token = ""; 16 get { return ConfigurationManager.AppSettings["consumerSecret"]; }
20 private string _tokenSecret = ""; 17 }
21 private string _callBackUrl = "oob";
22 private string _oauthVerifier = "";
23 18
24 private string ConsumerKey 19 public Uri AuthorizationLinkGet(string callbackAddress)
25 { 20 {
26 get 21 // Obtain a request token
27 { 22 OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, callbackAddress);
28 if (_consumerKey.Length == 0)
29 {
30 _consumerKey = ConfigurationManager.AppSettings["consumerKey"];
31 }
32 return _consumerKey;
33 }
34 }
35 23
36 private string ConsumerSecret { 24 // Direct or instruct the user to the following address:
37 get { 25 Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);
38 if (_consumerSecret.Length == 0)
39 {
40 _consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
41 }
42 return _consumerSecret;
43 }
44 }
45 26
46 public string Token { get { return _token; } set { _token = value; } } 27 return authorizationUri;
47 public string TokenSecret { get { return _tokenSecret; } set { _tokenSecret = value; } } 28 }
48 public string CallBackUrl { get { return _callBackUrl; } set { _callBackUrl = value; } }
49 public string OAuthVerifier { get { return _oauthVerifier; } set { _oauthVerifier = value; } }
50 29
51 /// <summary> 30 public string AccessTokenGet(string requestToken, string verifier)
52 /// Get the link to Twitter's authorization page for this application. 31 {
53 /// </summary> 32 OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, requestToken, verifier);
54 /// <returns>The url with a valid request token, or a null string.</returns> 33 if (accessToken!=null)
55 public string AuthorizationLinkGet() 34 {
56 { 35 var tokens = new OAuthTokens
57 string ret = null; 36 {
37 AccessToken = accessToken.Token,
38 AccessTokenSecret = accessToken.TokenSecret,
39 ConsumerKey = ConsumerKey,
40 ConsumerSecret = ConsumerSecret
41 };
58 42
59 string response = OAuthWebRequest(Method.GET, REQUEST_TOKEN, String.Empty); 43 TwitterResponse<TwitterUser> showUserResponse = TwitterUser.Show(tokens, accessToken.UserId);
60 if (response.Length > 0) 44 if (showUserResponse.Result == RequestResult.Success)
61 { 45 return showUserResponse.Content;
62 //response contains token and token secret. We only need the token. 46 return showUserResponse.ErrorMessage;
63 NameValueCollection qs = HttpUtility.ParseQueryString(response); 47 }
64 48 return string.Empty;
65 if (qs["oauth_callback_confirmed"] != null) 49 }
66 { 50 }
67 if (qs["oauth_callback_confirmed"] != "true")
68 {
69 throw new Exception("OAuth callback not confirmed.");
70 }
71 }
72
73 if (qs[OAuthTokenKey] != null)
74 {
75 ret = AUTHORIZE + "?" + OAuthTokenKey + "=" + qs[OAuthTokenKey];
76 }
77 }
78 return ret;
79 }
80
81 /// <summary>
82 /// Exchange the request token for an access token.
83 /// </summary>
84 /// <param name="authToken">The oauth_token is supplied by Twitter's authorization page following the callback.</param>
85 /// <param name="oauthVerifier">An oauth_verifier parameter is provided to the client either in the pre-configured callback URL</param>
86 public void AccessTokenGet(string authToken, string oauthVerifier)
87 {
88 Token = authToken;
89 OAuthVerifier = oauthVerifier;
90
91 string response = OAuthWebRequest(Method.GET, ACCESS_TOKEN, String.Empty);
92
93 if (response.Length > 0)
94 {
95 //Store the Token and Token Secret
96 NameValueCollection qs = HttpUtility.ParseQueryString(response);
97 if (qs[OAuthTokenKey] != null)
98 {
99 Token = qs[OAuthTokenKey];
100 }
101 if (qs[OAuthTokenSecretKey] != null)
102 {
103 TokenSecret = qs[OAuthTokenSecretKey];
104 }
105 }
106 }
107
108 /// <summary>
109 /// Submit a web request using oAuth.
110 /// </summary>
111 /// <param name="method">GET or POST</param>
112 /// <param name="url">The full url, including the querystring.</param>
113 /// <param name="postData">Data to post (querystring format)</param>
114 /// <returns>The web server response.</returns>
115 public string OAuthWebRequest(Method method, string url, string postData)
116 {
117 string outUrl;
118 string querystring;
119 string ret;
120
121
122 //Setup postData for signing.
123 //Add the postData to the querystring.
124 if (method == Method.POST || method == Method.DELETE)
125 {
126 if (postData.Length > 0)
127 {
128 //Decode the parameters and re-encode using the oAuth UrlEncode method.
129 NameValueCollection qs = HttpUtility.ParseQueryString(postData);
130 postData = "";
131 foreach (string key in qs.AllKeys)
132 {
133 if (postData.Length > 0)
134 {
135 postData += "&";
136 }
137 qs[key] = HttpUtility.UrlDecode(qs[key]);
138 qs[key] = UrlEncode(qs[key]);
139 postData += key + "=" + qs[key];
140
141 }
142 if (url.IndexOf("?") > 0)
143 {
144 url += "&";
145 }
146 else
147 {
148 url += "?";
149 }
150 url += postData;
151 }
152 }
153
154 var uri = new Uri(url);
155
156 string nonce = GenerateNonce();
157 string timeStamp = GenerateTimeStamp();
158
159 //Generate Signature
160 string sig = GenerateSignature(uri,
161 ConsumerKey,
162 ConsumerSecret,
163 Token,
164 TokenSecret,
165 CallBackUrl,
166 OAuthVerifier,
167 method.ToString(),
168 timeStamp,
169 nonce,
170 out outUrl,
171 out querystring);
172
173 querystring += "&" + OAuthSignatureKey + "=" + UrlEncode(sig);
174
175 //Convert the querystring to postData
176 if (method == Method.POST || method == Method.DELETE)
177 {
178 postData = querystring;
179 querystring = "";
180 }
181
182 if (querystring.Length > 0)
183 {
184 outUrl += "?";
185 }
186
187 ret = WebRequest(method, outUrl + querystring, postData);
188
189 return ret;
190 }
191
192 /// <summary>
193 /// Web Request Wrapper
194 /// </summary>
195 /// <param name="method">Http Method</param>
196 /// <param name="url">Full url to the web resource</param>
197 /// <param name="postData">Data to post in querystring format</param>
198 /// <returns>The web server response.</returns>
199 public string WebRequest(Method method, string url, string postData)
200 {
201 HttpWebRequest webRequest;
202 StreamWriter requestWriter;
203 string responseData;
204
205 webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
206 webRequest.Method = method.ToString();
207 webRequest.ServicePoint.Expect100Continue = false;
208 //webRequest.UserAgent = "Identify your application please.";
209 //webRequest.Timeout = 20000;
210
211 if (method == Method.POST || method == Method.DELETE)
212 {
213 webRequest.ContentType = "application/x-www-form-urlencoded";
214
215 //POST the data.
216 requestWriter = new StreamWriter(webRequest.GetRequestStream());
217 try
218 {
219 requestWriter.Write(postData);
220 }
221 finally
222 {
223 requestWriter.Close();
224 }
225 }
226
227 responseData = WebResponseGet(webRequest);
228
229 return responseData;
230
231 }
232
233 /// <summary>
234 /// Process the web response.
235 /// </summary>
236 /// <param name="webRequest">The request object.</param>
237 /// <returns>The response data.</returns>
238 public string WebResponseGet(HttpWebRequest webRequest)
239 {
240 StreamReader responseReader = null;
241 string responseData;
242
243 try
244 {
245 responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
246 responseData = responseReader.ReadToEnd();
247 }
248 finally
249 {
250 webRequest.GetResponse().GetResponseStream().Close();
251 responseReader.Close();
252 }
253
254 return responseData;
255 }
256 }
257 } 51 }