PageRenderTime 41ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/Libraries/ThirdParty/TweetSharp/TweetSharp.Twitter/Fluent/Services/ShortenUrlService.cs

#
C# | 217 lines | 155 code | 24 blank | 38 comment | 18 complexity | 50e5c09c0b817cf32bd653d1c0e1c6dd MD5 | raw file
  1. #region License
  2. // TweetSharp
  3. // Copyright (c) 2010 Daniel Crenna and Jason Diller
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. #endregion
  24. using System;
  25. using System.Collections.Generic;
  26. using Hammock.Web;
  27. using TweetSharp.Core.Attributes;
  28. using TweetSharp.Core.Extensions;
  29. using Newtonsoft.Json;
  30. namespace TweetSharp.Twitter.Fluent.Twitter.Services
  31. {
  32. #if !SILVERLIGHT
  33. [Serializable]
  34. internal static class ShortenUrlService
  35. {
  36. public static string ShortenUrl(ShortenUrlServiceProvider provider, IEnumerable<string> words, string text)
  37. {
  38. return ShortenUrl(provider, words, text, null, null, null);
  39. }
  40. public static string ShortenUrl(ShortenUrlServiceProvider provider, IEnumerable<string> words, string text, string username, string password, string apiKey)
  41. {
  42. if(provider.RequiresAuthentication(true) && (username.IsNullOrBlank() || password.IsNullOrBlank()))
  43. {
  44. throw new TweetSharpException("Expected credentials for the shortening service {0}".FormatWith(provider));
  45. }
  46. var hasAuth = provider.RequiresAuthentication(false) && (!username.IsNullOrBlank() && !password.IsNullOrBlank());
  47. var hasApiKey = provider.RequiresApiKey() && (!apiKey.IsNullOrBlank());
  48. var scheme = provider.GetScheme();
  49. switch (provider)
  50. {
  51. case ShortenUrlServiceProvider.Tomato:
  52. text = ExecuteGet(text, words, "http://to.m8.to/api/shortenLink?url={0}");
  53. break;
  54. case ShortenUrlServiceProvider.Trim:
  55. {
  56. var result = text;
  57. var function = new Func<string, string, string>((response, word) =>
  58. {
  59. var data = new {url = String.Empty};
  60. data = JsonConvert.DeserializeAnonymousType(response, data);
  61. if (!data.url.IsNullOrBlank())
  62. {
  63. result = result.Replace(word, data.url);
  64. }
  65. return result;
  66. });
  67. text = hasApiKey
  68. ? ExecuteGet(text, words, "http://tr.im/api/trim_url.json?api_key={0}&url={{0}}".FormatWith(apiKey), function)
  69. : hasAuth
  70. ? ExecuteGet(text, words, "http://tr.im/api/trim_url.json?url={0}", function, username, password, scheme)
  71. : ExecuteGet(text, words, "http://tr.im/api/trim_url.json?url={0}", function);
  72. break;
  73. }
  74. case ShortenUrlServiceProvider.Bitly:
  75. {
  76. /* {
  77. "errorCode": 0,
  78. "errorMessage": "",
  79. "results": {
  80. "http://www.dimebrain.com": {
  81. "hash": "wzJq",
  82. "shortKeywordUrl": "",
  83. "shortUrl": "http://bit.ly/5Dch",
  84. "userHash": "5Dch"
  85. }
  86. },
  87. "statusCode": "OK"
  88. }*/
  89. var result = text;
  90. var function = new Func<string, string, string>((response, word) =>
  91. {
  92. response = response.Replace("\"", "");
  93. response = response.Replace(word, "");
  94. response = response.Replace(",", "");
  95. var url = word;
  96. foreach (var token in response.Split(' '))
  97. {
  98. if (!token.IsValidUrl())
  99. {
  100. continue;
  101. }
  102. url = token;
  103. break;
  104. }
  105. if (!url.IsNullOrBlank())
  106. {
  107. result = result.Replace(word, url);
  108. }
  109. return result;
  110. });
  111. text = ExecuteGet(text, words,
  112. "http://api.bit.ly/shorten?version=2.0.1&longUrl={0}&login={1}&apiKey={2}",
  113. function, username, password, scheme);
  114. break;
  115. }
  116. case ShortenUrlServiceProvider.IsGd:
  117. {
  118. text = ExecuteGet(text, words, "http://is.gd/api.php?longurl={0}");
  119. break;
  120. }
  121. case ShortenUrlServiceProvider.TinyUrl:
  122. {
  123. text = ExecuteGet(text, words, "http://tinyurl.com/api-create.php?url={0}");
  124. break;
  125. }
  126. default:
  127. throw new TweetSharpException("Unknown service provider for URL shortening");
  128. }
  129. return text;
  130. }
  131. private static string ExecuteGet(string text, IEnumerable<string> words, string query, Func<string, string, string> function)
  132. {
  133. return ExecuteGet(text, words, query, function, null, null, AuthenticationScheme.None);
  134. }
  135. private static string ExecuteGet(string text, IEnumerable<string> words, string query)
  136. {
  137. return ExecuteGet(text, words, query, null);
  138. }
  139. private static string ExecuteGet(string text, IEnumerable<string> words, string query, Func<string, string, string> function, string username, string password, AuthenticationScheme scheme)
  140. {
  141. foreach (var word in words)
  142. {
  143. if (!word.IsValidUrl())
  144. {
  145. // not valid
  146. continue;
  147. }
  148. if (word.IsShortenedUrl())
  149. {
  150. // already shortened
  151. continue;
  152. }
  153. var hasAuth = !username.IsNullOrBlank() && !password.IsNullOrBlank();
  154. string url;
  155. string response;
  156. if(hasAuth)
  157. {
  158. switch(scheme)
  159. {
  160. case AuthenticationScheme.Http:
  161. url = query.FormatWith(word.UrlEncodeRelaxed());
  162. response = WebQuery.QuickGet(url, username, password);
  163. break;
  164. case AuthenticationScheme.Parameters:
  165. url = query.FormatWith(word.UrlEncodeRelaxed(), username, password);
  166. response = WebQuery.QuickGet(url);
  167. break;
  168. default:
  169. throw new ArgumentException(
  170. "Authentication was provided to shortening service call with no valid scheme.");
  171. }
  172. }
  173. else
  174. {
  175. url = query.FormatWith(word.UrlEncodeRelaxed());
  176. response = WebQuery.QuickGet(url);
  177. }
  178. if(function != null)
  179. {
  180. // post-process the http response
  181. return function.Invoke(response, word);
  182. }
  183. if (response != null)
  184. {
  185. // the response is the shortened url
  186. text = text.Replace(word, response);
  187. }
  188. }
  189. return text;
  190. }
  191. }
  192. #endif
  193. }