Advertisement
Guest User

Untitled

a guest
Apr 29th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Http;
  6. using Newtonsoft.Json;
  7. using T412;
  8.  
  9. namespace T411
  10. {
  11. public class T411Client
  12. {
  13. private const string BaseAddress = "https://api.t411.ch";
  14.  
  15. private readonly string _username;
  16. private readonly string _password;
  17.  
  18. private readonly string _token;
  19.  
  20. private int _userId = -1;
  21. public int UserId
  22. {
  23. get
  24. {
  25. if (_userId == -1)
  26. {
  27. if (_token == null)
  28. throw new InvalidOperationException("Null token");
  29. string[] part = _token.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  30. if (part.Length != 3)
  31. throw new InvalidOperationException("Invalide token format");
  32.  
  33. if (!int.TryParse(part[0], out _userId))
  34. throw new InvalidOperationException("Invalide token user id format");
  35. }
  36. return _userId;
  37. }
  38. }
  39.  
  40.  
  41. public T411Client(string username, string password)
  42. {
  43. _username = username;
  44. _password = password;
  45. _token = GetToken();
  46. }
  47.  
  48. private string GetToken()
  49. {
  50. using (var handler = new HttpClientHandler())
  51. {
  52. if (handler.SupportsAutomaticDecompression)
  53. {
  54. handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  55. }
  56. using (var client = new HttpClient(handler) { BaseAddress = new Uri(BaseAddress) })
  57. {
  58. Dictionary<string, string> dico = new Dictionary<string, string>();
  59. dico.Add("username", _username);
  60. dico.Add("password", _password);
  61.  
  62. HttpResponseMessage response = client.PostAsync("/auth", new FormUrlEncodedContent(dico)).Result;
  63. var tokResult = response.Content.ReadAsStringAsync().Result;
  64. var tokObj = JsonConvert.DeserializeObject<AuthResult>(tokResult);
  65. string token = tokObj.Token;
  66.  
  67. if(token != null)
  68. {
  69. Globals.AuthCheck = true;
  70. }
  71. else
  72. {
  73. Globals.AuthCheck = false;
  74. }
  75.  
  76. return token;
  77. }
  78. }
  79. }
  80.  
  81. public List<Torrent> GetTop100()
  82. {
  83. return GetTorrents("/torrents/top/100");
  84. }
  85.  
  86. public List<Torrent> GetTopToday()
  87. {
  88. return GetTorrents("/torrents/top/today");
  89. }
  90.  
  91. public List<Torrent> GetTopWeek()
  92. {
  93. return GetTorrents("/torrents/top/week");
  94. }
  95.  
  96. public List<Torrent> GetTopMonth()
  97. {
  98. return GetTorrents("/torrents/top/month");
  99. }
  100.  
  101. private List<Torrent> GetTorrents(string uri)
  102. {
  103. return GetResponse<List<Torrent>>(new Uri(uri, UriKind.Relative));
  104. }
  105.  
  106. public TorrentDetails GetTorrentDetails(int id)
  107. {
  108. string uri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/torrents/details/{0}", id);
  109. return GetResponse<TorrentDetails>(new Uri(uri, UriKind.Relative));
  110. }
  111.  
  112. public Stream DownloadTorrent(int id)
  113. {
  114. string uri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/torrents/download/{0}", id);
  115.  
  116. using (var handler = new HttpClientHandler())
  117. {
  118. if (handler.SupportsAutomaticDecompression)
  119. {
  120. handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  121. }
  122. using (var client = new HttpClient(handler) { BaseAddress = new Uri(BaseAddress) })
  123. using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, uri))
  124. {
  125. requestMessage.Headers.TryAddWithoutValidation("Authorization", _token);
  126.  
  127. using (var response = client.SendAsync(requestMessage).Result)
  128. {
  129. MemoryStream ms = null;
  130. try
  131. {
  132. ms = new MemoryStream();
  133.  
  134. using (var msLocal = new MemoryStream())
  135. {
  136. response.Content.CopyToAsync(msLocal).Wait();
  137. msLocal.Position = 0;
  138. StreamReader sr = new StreamReader(msLocal);
  139.  
  140. string data = sr.ReadToEnd();
  141. if (data.StartsWith("{\"error\":"))
  142. {
  143. ErrorResult error = JsonConvert.DeserializeObject<ErrorResult>(data);
  144. throw ErrorCodeException.CreateFromErrorCode(error);
  145. }
  146. msLocal.Position = 0;
  147. msLocal.CopyTo(ms);
  148. }
  149.  
  150. ms.Position = 0;
  151. return ms;
  152. }
  153. catch
  154. {
  155. if (ms != null)
  156. {
  157. ms.Dispose();
  158. }
  159. throw;
  160. }
  161. }
  162. }
  163. }
  164. }
  165.  
  166. public UserDetails GetUserDetails(int id)
  167. {
  168. string uri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/users/profile/{0}", id);
  169. return GetResponse<UserDetails>(new Uri(uri, UriKind.Relative));
  170. }
  171.  
  172. public QueryResult GetQuery(string query)
  173. {
  174. if (query == null)
  175. throw new ArgumentNullException("query");
  176. string uri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/torrents/search/{0}", query);
  177. return GetResponse<QueryResult>(new Uri(uri, UriKind.Relative));
  178. }
  179.  
  180. public QueryResult GetQuery(string query, QueryOptions options)
  181. {
  182. if (query == null)
  183. throw new ArgumentNullException("query");
  184. if (options == null)
  185. throw new ArgumentNullException("options");
  186.  
  187. string uri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/torrents/search/{0}?{1}", query.Replace(" ", "%20"), options.QueryString);
  188. return GetResponse<QueryResult>(new Uri(uri, UriKind.Relative));
  189. }
  190.  
  191. public Dictionary<int, Category> GetCategory()
  192. {
  193. string uri = "/categories/tree";
  194. return GetResponse<Dictionary<int, Category>>(new Uri(uri, UriKind.Relative));
  195. }
  196.  
  197. public List<TermCategory> GetTerms()
  198. {
  199. string uri = "/terms/tree";
  200. var result = GetResponse<Dictionary<int, Dictionary<int, TermType>>>(new Uri(uri, UriKind.Relative));
  201.  
  202. List<TermCategory> list = new List<TermCategory>();
  203. foreach (var categoryItem in result)
  204. {
  205. TermCategory termCategory = new TermCategory();
  206. termCategory.Id = categoryItem.Key;
  207. termCategory.TermTypes = new List<TermType>();
  208. foreach (var termItem in categoryItem.Value)
  209. {
  210. TermType termType = termItem.Value;
  211. termType.Id = termItem.Key;
  212. termCategory.TermTypes.Add(termType);
  213. }
  214. list.Add(termCategory);
  215. }
  216.  
  217. return list;
  218. }
  219.  
  220. private T GetResponse<T>(Uri uri)
  221. {
  222. string data = GetRawResponse(uri);
  223.  
  224. if (data.StartsWith("{\"error\":"))
  225. {
  226. ErrorResult error = JsonConvert.DeserializeObject<ErrorResult>(data);
  227. throw ErrorCodeException.CreateFromErrorCode(error);
  228. }
  229.  
  230. T torrents = JsonConvert.DeserializeObject<T>(data);
  231. return torrents;
  232. }
  233.  
  234. private string GetRawResponse(Uri uri)
  235. {
  236. using (var handler = new HttpClientHandler())
  237. {
  238. if (handler.SupportsAutomaticDecompression)
  239. {
  240. handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  241. }
  242. using (var client = new HttpClient(handler) { BaseAddress = new Uri(BaseAddress) })
  243. using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, uri))
  244. {
  245. requestMessage.Headers.TryAddWithoutValidation("Authorization", _token);
  246.  
  247. using (var response = client.SendAsync(requestMessage).Result)
  248. {
  249. var result = response.Content.ReadAsStringAsync().Result;
  250. return result;
  251. }
  252. }
  253. }
  254. }
  255.  
  256. public List<Torrent> GetBookmarks()
  257. {
  258. return GetResponse<List<Torrent>>(new Uri("/bookmarks", UriKind.Relative));
  259. }
  260.  
  261. public int CreateBookmark(int id)
  262. {
  263. string uri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/bookmarks/save/{0}", id);
  264. return GetResponse<int>(new Uri(uri, UriKind.Relative));
  265. }
  266.  
  267. public int DeleteBookmark(IEnumerable<int> bookmarkIds)
  268. {
  269. string ids = string.Join(",", bookmarkIds);
  270. string uri = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/bookmarks/delete/{0}", ids);
  271. return GetResponse<int>(new Uri(uri, UriKind.Relative));
  272. }
  273. }
  274. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement