Advertisement
Guest User

Untitled

a guest
Apr 9th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.85 KB | None | 0 0
  1. using MrSilkBot;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Threading.Tasks;
  11.  
  12. namespace BananaLib.RestService
  13. {
  14. public class LoginQueue
  15. {
  16. private readonly LoLHttpClient _httpClient = new LoLHttpClient();
  17. public const string ACCOUNT_BANNED = "account_banned";
  18. public const string ACCOUNT_TRANSFERRED = "account_transferred";
  19. public const string INVALID_CREDENTIALS = "invalid_credentials";
  20. public const string SERVER_FULL = "server_full";
  21. public const string ACCOUNT_INACTIVE = "account_inactive";
  22. public const string ATTEMPT_RATE_TOO_FAST = "attempt_rate_too_fast";
  23. public const string FAILED_STATUS = "FAILED";
  24. public const string BUSY_STATUS = "BUSY";
  25. public const string LOGIN_STATUS = "LOGIN";
  26. public const string QUEUE_STATUS = "QUEUE";
  27. private string _authUrl;
  28. private string _tickerUrl;
  29. private string _tokenUrl;
  30. private Region _region;
  31. private int _timeoutSeconds;
  32. private int _authRetries;
  33.  
  34. public string Username { get; set; }
  35.  
  36. public string Password { get; set; }
  37.  
  38. public string User { get; set; }
  39. public long UserId { get; set; }
  40. public string Token { get; set; }
  41.  
  42. public Region Region
  43. {
  44. get
  45. {
  46. return this._region;
  47. }
  48. set
  49. {
  50. this._region = value;
  51. string str = value.LoginQueueServer() + "login-queue/rest/queues/lol/";
  52. this._authUrl = str + "authenticate/";
  53. this._tickerUrl = str + "ticker/";
  54. this._tokenUrl = str + "token/";
  55. }
  56. }
  57.  
  58. public int TimeoutSeconds
  59. {
  60. get
  61. {
  62. return this._timeoutSeconds;
  63. }
  64. set
  65. {
  66. this._timeoutSeconds = value < 20 ? 60 : value;
  67. }
  68. }
  69.  
  70. public int AuthRetries
  71. {
  72. get
  73. {
  74. return this._authRetries;
  75. }
  76. set
  77. {
  78. this._authRetries = value < 1 ? 5 : value;
  79. }
  80. }
  81.  
  82. public AuthResult AuthResult { get; private set; }
  83.  
  84. public string AuthToken { get; private set; }
  85.  
  86. public event LoginQueue.OnAuthFailedHandler OnAuthFailed;
  87.  
  88. public event LoginQueue.OnLoginQueueUpdateHandler OnLoginQueueUpdate;
  89.  
  90. public event LoginQueue.StatusMessageUpdateHandler OnUpdateStatusMessage;
  91.  
  92. public LoginQueue(int timeoutSeconds = 60, int retries = 5)
  93. {
  94. this.TimeoutSeconds = timeoutSeconds;
  95. this.AuthRetries = retries;
  96. }
  97.  
  98. public LoginQueue(string username, string password, Region region)
  99. : this(60, 5)
  100. {
  101. this.SetUserCredentials(username, password, region);
  102. }
  103.  
  104. public void SetUserCredentials(string username, string password, Region region)
  105. {
  106. this.Username = username;
  107. this.Password = password;
  108. this.Region = region;
  109. }
  110.  
  111. private string reToken(string s)
  112. {
  113. return s.Replace("/", "%2F").Replace("+", "%2B").Replace("=", "%3D");
  114. }
  115.  
  116. public async Task<AuthResult> GetAuthResult()
  117. {
  118. string payload = WebUtility.UrlEncode(string.Format("user={0},password={1}", this.Username, this.Password));
  119. string query = "payload=" + payload;
  120. string str = await (await this._httpClient.PostAsync(this._authUrl, query, false).ConfigureAwait(false)).Content.ReadAsStringAsync().ConfigureAwait(false);
  121.  
  122. if (str.Contains("Access denied") && str.Contains("banned your IP"))
  123. throw new IpBannedException();
  124. return JsonConvert.DeserializeObject<AuthResult>(str);
  125. }
  126.  
  127. public async Task<bool> GetAuthToken()
  128. {
  129. Stopwatch sw = new Stopwatch();
  130. sw.Start();
  131. int retriesRemaining = AuthRetries;
  132. try
  133. {
  134. while (sw.ElapsedMilliseconds / 1000L <= TimeoutSeconds)
  135. {
  136. int num = 0;
  137. try
  138. {
  139. AuthResult = await GetAuthResult().ConfigureAwait(false);
  140. User = AuthResult.User;
  141. Token = AuthResult.Lqt.PartnerToken;
  142. //await GetToken();
  143. //this.UserId = this.AuthResult.Lqt.AccountId;
  144. }
  145. catch (IpBannedException ex)
  146. {
  147. Tools.Log(ex.StackTrace);
  148. OnAuthFailed?.Invoke("Your IP has been banned due to too many requests.");
  149. return false;
  150. }
  151. catch (JsonReaderException ex)
  152. {
  153. Tools.Log(ex.StackTrace);
  154. num = 1;
  155. }
  156. catch (Exception ex)
  157. {
  158. Tools.Log(ex.StackTrace);
  159. Console.WriteLine(ex.StackTrace);
  160. }
  161. if (num == 1)
  162. await Task.Delay(1000).ConfigureAwait(false);
  163. else
  164. {
  165. string reason = this.AuthResult.Reason;
  166. if (!(reason == "attempt_rate_too_fast"))
  167. {
  168. if (!(reason == "invalid_credentials"))
  169. {
  170. if (!(reason == "account_banned"))
  171. {
  172. if (!(reason == "account_transferred"))
  173. {
  174. if (!(reason == "account_inactive"))
  175. {
  176. if (reason == "server_full")
  177. {
  178. OnAuthFailed?.Invoke("Server is full. Try again later.");
  179. return false;
  180. }
  181. if (AuthResult.Status == "QUEUE" && this.AuthResult.Tickers != null)
  182. {
  183. await WaitInQueue().ConfigureAwait(false);
  184. AuthResult.Lqt.Resources = null;
  185. AuthResult.Lqt.Other = null;
  186. HttpResponseMessage httpResponseMessage = await _httpClient.PostAsync(_tokenUrl, AuthResult.Lqt.ToString(), true).ConfigureAwait(false);
  187. if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
  188. {
  189. AuthToken = JsonConvert.DeserializeObject<AuthResult>(await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false)).Lqt.ToString();
  190. return true;
  191. }
  192. }
  193. if (AuthResult.Status == "LOGIN")
  194. {
  195. AuthToken = AuthResult.Lqt.ToString();
  196. return true;
  197. }
  198. await Task.Delay(1000).ConfigureAwait(false);
  199. }
  200. else
  201. {
  202. OnAuthFailed?.Invoke("Account currently inactive.");
  203. return false;
  204. }
  205. }
  206. else
  207. {
  208. OnAuthFailed?.Invoke(string.Format("Account transferred {0}", AuthResult.Destination).Trim());
  209. return false;
  210. }
  211. }
  212. else
  213. {
  214. DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(AuthResult.Banned);
  215. OnAuthFailed?.Invoke(string.Format("Account banned {0}", dateTime.ToString("d", (IFormatProvider)CultureInfo.CurrentCulture)));
  216. return false;
  217. }
  218. }
  219. else
  220. {
  221. OnAuthFailed?.Invoke("Incorrect username or password.");
  222. return false;
  223. }
  224. }
  225. else
  226. {
  227. OnUpdateStatusMessage?.Invoke(this, string.Format("Login rate too fast. Waiting {0} s.", AuthResult.RetryWait));
  228. await Task.Delay(TimeSpan.FromSeconds(AuthResult.RetryWait)).ConfigureAwait(false);
  229. sw.Restart();
  230. }
  231. }
  232. }
  233. sw.Stop();
  234. throw new TimeoutException();
  235. }
  236. catch (TimeoutException ex)
  237. {
  238. Tools.Log(ex.StackTrace);
  239. OnAuthFailed?.Invoke("Timeout: queue time too long.");
  240. }
  241. finally
  242. {
  243. sw.Stop();
  244. }
  245. return false;
  246. }
  247.  
  248. private async Task WaitInQueue()
  249. {
  250. int id = -1;
  251. int current = -1;
  252. using (IEnumerator<Ticker> enumerator = AuthResult.Tickers.Where(ticker => ticker.Node == AuthResult.Node).GetEnumerator())
  253. {
  254. if (enumerator.MoveNext())
  255. {
  256. Ticker current1 = enumerator.Current;
  257. id = current1.Id;
  258. current = current1.Current;
  259. }
  260. }
  261. int cycleNum = 1;
  262. double averageMillisPerCycle = 0.0;
  263. while (id - current > 0)
  264. {
  265. DateTime cycleStartTime = DateTime.Now;
  266. HttpResponseMessage httpResponseMessage = await _httpClient.GetAsync(_tickerUrl + AuthResult.Champ).ConfigureAwait(false);
  267. if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
  268. {
  269. try
  270. {
  271. current = int.Parse((string)JsonConvert.DeserializeObject<Dictionary<string, object>>(await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false))[AuthResult.Node.ToString()], NumberStyles.HexNumber);
  272. int num = Math.Max(0, id - current);
  273. if (num == 0)
  274. break;
  275. OnLoginQueueUpdate?.Invoke(num);
  276. OnUpdateStatusMessage?.Invoke(this, string.Format("In login queue at position {0}", num));
  277. }
  278. catch (Exception ex)
  279. {
  280. Tools.Log(ex.StackTrace);
  281. }
  282. await Task.Delay(this.AuthResult.Delay).ConfigureAwait(false);
  283. }
  284. double totalMilliseconds = (DateTime.Now - cycleStartTime).TotalMilliseconds;
  285. averageMillisPerCycle = averageMillisPerCycle > 0.0 ? (averageMillisPerCycle + totalMilliseconds) / 2.0 : totalMilliseconds;
  286. if (cycleNum == 2)
  287. {
  288. double num = averageMillisPerCycle / (1 / AuthResult.Rate * 60);
  289. if ((int)(averageMillisPerCycle * (num / (1.0 - num)) * ((1.0 + Math.Pow(1.333, 2.0)) / 2.0) / 1000.0) > this.TimeoutSeconds)
  290. throw new TimeoutException();
  291. }
  292. ++cycleNum;
  293. }
  294. }
  295.  
  296. public delegate void OnAuthFailedHandler(string message);
  297.  
  298. public delegate void OnLoginQueueUpdateHandler(int positionInLine);
  299.  
  300. public delegate void StatusMessageUpdateHandler(object sender, string e);
  301. }
  302. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement