PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/MalApi/MyAnimeListApi.cs

https://bitbucket.org/LHCGreg/mal-api
C# | 271 lines | 188 code | 35 blank | 48 comment | 13 complexity | 53a4ddb9a6a0ab05c1d94a9a2c6670ad MD5 | raw file
Possible License(s): Apache-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using System.Xml;
  8. using System.Xml.Linq;
  9. using System.Text.RegularExpressions;
  10. using System.Globalization;
  11. namespace MalApi
  12. {
  13. /// <summary>
  14. /// Class for accessing myanimelist.net. Methods are thread-safe. Properties are not.
  15. /// </summary>
  16. public class MyAnimeListApi : IMyAnimeListApi
  17. {
  18. private const string MalAppInfoUri = "http://myanimelist.net/malappinfo.php?status=all&type=anime";
  19. private const string RecentOnlineUsersUri = "http://myanimelist.net/users.php";
  20. /// <summary>
  21. /// What to set the user agent http header to in API requests. Null to use the default .NET user agent.
  22. /// </summary>
  23. public string UserAgent { get; set; }
  24. private int m_timeoutInMs = 15 * 1000;
  25. /// <summary>
  26. /// Timeout in milliseconds for requests to MAL. Defaults to 15000 (15s).
  27. /// </summary>
  28. public int TimeoutInMs { get { return m_timeoutInMs; } set { m_timeoutInMs = value; } }
  29. public MyAnimeListApi()
  30. {
  31. ;
  32. }
  33. private HttpWebRequest InitNewRequest(string uri, string method)
  34. {
  35. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
  36. if (UserAgent != null)
  37. {
  38. request.UserAgent = UserAgent;
  39. }
  40. request.Timeout = TimeoutInMs;
  41. request.ReadWriteTimeout = TimeoutInMs;
  42. request.Method = method;
  43. request.KeepAlive = false;
  44. // Very important optimization! Time to get an anime list of ~150 entries 2.6s -> 0.7s
  45. request.AutomaticDecompression = DecompressionMethods.GZip;
  46. return request;
  47. }
  48. private TReturn ProcessRequest<TReturn>(HttpWebRequest request, Func<string, TReturn> processingFunc, string baseErrorMessage)
  49. {
  50. return ProcessRequest(request, (string html, object dummy) => processingFunc(html), (object)null, baseErrorMessage);
  51. }
  52. private TReturn ProcessRequest<TReturn, TData>(HttpWebRequest request, Func<string, TData, TReturn> processingFunc, TData data, string baseErrorMessage)
  53. {
  54. string responseBody = null;
  55. try
  56. {
  57. Logging.Log.DebugFormat("Starting MAL request to {0}", request.RequestUri);
  58. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  59. {
  60. Logging.Log.DebugFormat("Got response. Status code = {0}.", response.StatusCode);
  61. if (response.StatusCode != HttpStatusCode.OK)
  62. {
  63. throw new MalApiRequestException(string.Format("{0} Status code was {1}.", baseErrorMessage, response.StatusCode));
  64. }
  65. using (Stream responseBodyStream = response.GetResponseStream())
  66. using (StreamReader responseBodyReader = new StreamReader(responseBodyStream, Encoding.UTF8))
  67. {
  68. // XXX: Shouldn't be hardcoding UTF-8
  69. responseBody = responseBodyReader.ReadToEnd();
  70. }
  71. }
  72. Logging.Log.Debug("Read response body.");
  73. return processingFunc(responseBody, data);
  74. }
  75. catch (MalUserNotFoundException)
  76. {
  77. throw;
  78. }
  79. catch (MalAnimeNotFoundException)
  80. {
  81. throw;
  82. }
  83. catch (MalApiException)
  84. {
  85. // Log the body of the response returned by the API server if there was an error.
  86. // Don't log it otherwise, logs could get big then.
  87. if (responseBody != null)
  88. {
  89. Logging.Log.DebugFormat("Response body:{0}{1}", Environment.NewLine, responseBody);
  90. }
  91. throw;
  92. }
  93. catch (Exception ex)
  94. {
  95. if (responseBody != null)
  96. {
  97. // Since we read the response, the error was in processing the response, not with doing the request/response.
  98. Logging.Log.DebugFormat("Response body:{0}{1}", Environment.NewLine, responseBody);
  99. throw new MalApiException(string.Format("{0} {1}", baseErrorMessage, ex.Message), ex);
  100. }
  101. else
  102. {
  103. // If we didn't read a response, then there was an error with the request/response that may be fixable with a retry.
  104. throw new MalApiRequestException(string.Format("{0} {1}", baseErrorMessage, ex.Message), ex);
  105. }
  106. }
  107. }
  108. /// <summary>
  109. ///
  110. /// </summary>
  111. /// <param name="user"></param>
  112. /// <returns></returns>
  113. /// <exception cref="MalApi.MalUserNotFoundException"></exception>
  114. /// <exception cref="MalApi.MalApiException"></exception>
  115. public MalUserLookupResults GetAnimeListForUser(string user)
  116. {
  117. string userInfoUri = MalAppInfoUri + "&u=" + Uri.EscapeDataString(user);
  118. Logging.Log.InfoFormat("Getting anime list for MAL user {0} using URI {1}", user, userInfoUri);
  119. HttpWebRequest request = InitNewRequest(userInfoUri, "GET");
  120. Func<string, MalUserLookupResults> responseProcessingFunc = (xml) =>
  121. {
  122. using (TextReader xmlTextReader = new StringReader(xml))
  123. {
  124. try
  125. {
  126. return MalAppInfoXml.Parse(xmlTextReader);
  127. }
  128. catch (MalUserNotFoundException ex)
  129. {
  130. throw new MalUserNotFoundException(string.Format("No MAL list exists for {0}.", user), ex);
  131. }
  132. }
  133. };
  134. MalUserLookupResults parsedList = ProcessRequest(request, responseProcessingFunc,
  135. baseErrorMessage: string.Format("Failed getting anime list for user {0} using url {1}", user, userInfoUri));
  136. Logging.Log.InfoFormat("Successfully retrieved anime list for user {0}", user);
  137. return parsedList;
  138. }
  139. private static Lazy<Regex> s_recentOnlineUsersRegex =
  140. new Lazy<Regex>(() => new Regex("/profile/(?<Username>[^\"]+)\">\\k<Username>",
  141. RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase));
  142. public static Regex RecentOnlineUsersRegex { get { return s_recentOnlineUsersRegex.Value; } }
  143. /// <summary>
  144. /// Gets a list of users that have been on MAL recently. This scrapes the HTML on the recent users page and therefore
  145. /// can break if MAL changes the HTML on that page.
  146. /// </summary>
  147. /// <returns></returns>
  148. public RecentUsersResults GetRecentOnlineUsers()
  149. {
  150. Logging.Log.InfoFormat("Getting list of recent online MAL users using URI {0}", RecentOnlineUsersUri);
  151. HttpWebRequest request = InitNewRequest(RecentOnlineUsersUri, "GET");
  152. RecentUsersResults recentUsers = ProcessRequest(request, ScrapeUsersFromHtml,
  153. baseErrorMessage: "Failed getting list of recent MAL users.");
  154. Logging.Log.Info("Successfully got list of recent online MAL users.");
  155. return recentUsers;
  156. }
  157. private RecentUsersResults ScrapeUsersFromHtml(string recentUsersHtml)
  158. {
  159. List<string> users = new List<string>();
  160. MatchCollection userMatches = RecentOnlineUsersRegex.Matches(recentUsersHtml);
  161. foreach (Match userMatch in userMatches)
  162. {
  163. string username = userMatch.Groups["Username"].ToString();
  164. users.Add(username);
  165. }
  166. if (users.Count == 0)
  167. {
  168. throw new MalApiException("0 users found in recent users page html.");
  169. }
  170. return new RecentUsersResults(users);
  171. }
  172. private static readonly string AnimeDetailsUrlFormat = "http://myanimelist.net/anime/{0}";
  173. private static Lazy<Regex> s_animeDetailsRegex = new Lazy<Regex>(() => new Regex(
  174. @"Genres:</span> \n.*?(?:<a href=""http://myanimelist.net/anime.php\?genre\[\]=(?<GenreId>\d+)"">(?<GenreName>.*?)</a>(?:, )?)*</div>",
  175. RegexOptions.Compiled));
  176. private static Regex AnimeDetailsRegex { get { return s_animeDetailsRegex.Value; } }
  177. /// <summary>
  178. /// Gets information from an anime's "details" page. This method uses HTML scraping and so may break if MAL changes the HTML.
  179. /// </summary>
  180. /// <param name="animeId"></param>
  181. /// <returns></returns>
  182. public AnimeDetailsResults GetAnimeDetails(int animeId)
  183. {
  184. string url = string.Format(AnimeDetailsUrlFormat, animeId);
  185. Logging.Log.InfoFormat("Getting anime details from {0}.", url);
  186. HttpWebRequest request = InitNewRequest(url, "GET");
  187. AnimeDetailsResults results = ProcessRequest(request, ScrapeAnimeDetailsFromHtml, animeId,
  188. baseErrorMessage: string.Format("Failed getting anime details for anime ID {0}.", animeId));
  189. Logging.Log.InfoFormat("Successfully got details from {0}.", url);
  190. return results;
  191. }
  192. // internal for unit testing
  193. internal AnimeDetailsResults ScrapeAnimeDetailsFromHtml(string animeDetailsHtml, int animeId)
  194. {
  195. if (animeDetailsHtml.Contains("<div class=\"badresult\">No series found, check the series id and try again.</div>"))
  196. {
  197. throw new MalAnimeNotFoundException(string.Format("No anime with id {0} exists.", animeId));
  198. }
  199. Match match = AnimeDetailsRegex.Match(animeDetailsHtml);
  200. if (!match.Success)
  201. {
  202. throw new MalApiException(string.Format("Could not extract information from {0}.", string.Format(AnimeDetailsUrlFormat, animeId)));
  203. }
  204. Group genreIds = match.Groups["GenreId"];
  205. Group genreNames = match.Groups["GenreName"];
  206. List<Genre> genres = new List<Genre>();
  207. for (int i = 0; i < genreIds.Captures.Count; i++)
  208. {
  209. string genreIdString = genreIds.Captures[i].Value;
  210. int genreId = int.Parse(genreIdString);
  211. string genreName = genreNames.Captures[i].Value;
  212. genres.Add(new Genre(genreId: genreId, name: genreName));
  213. }
  214. return new AnimeDetailsResults(genres);
  215. }
  216. public void Dispose()
  217. {
  218. ;
  219. }
  220. }
  221. }
  222. /*
  223. Copyright 2012 Greg Najda
  224. Licensed under the Apache License, Version 2.0 (the "License");
  225. you may not use this file except in compliance with the License.
  226. You may obtain a copy of the License at
  227. http://www.apache.org/licenses/LICENSE-2.0
  228. Unless required by applicable law or agreed to in writing, software
  229. distributed under the License is distributed on an "AS IS" BASIS,
  230. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  231. See the License for the specific language governing permissions and
  232. limitations under the License.
  233. */