public bool RefreshToken() { WebCache_SessionInfo ws = WrapAuthentication((token) => cclient.RefreshSession(token)); if (ws != null) { ServerSettings.Instance.WebCache.Session = ws; ServerSettings.Instance.SaveSettings(); return(true); } return(false); }
private string Authenticate() { string token = GetToken(); if (token == null) { if (ServerSettings.Instance.WebCache.BannedExpiration.HasValue && ServerSettings.Instance.WebCache.BannedExpiration.HasValue && ServerSettings.Instance.WebCache.BannedExpiration.Value > DateTime.UtcNow) { return(null); } CookieContainer cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler { CookieContainer = cookieContainer }) using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16241"); Uri uri = new Uri("http://anidb.net/perl-bin/animedb.pl"); //MOVE TO Properties string post = $"show=userpage&xuser={HttpUtility.UrlEncode(ServerSettings.Instance.AniDb.Username)}&xpass={HttpUtility.UrlEncode(ServerSettings.Instance.AniDb.Password)}&do.auth=login"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri); request.Headers.Referrer = uri; request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(post)); Uri host = new Uri(uri.Scheme + "://" + uri.Host); HttpResponseMessage response = Task.Run(async() => await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)).GetAwaiter().GetResult(); if (response.IsSuccessStatusCode) { List <Cookie> cookies = cookieContainer.GetCookies(host).Cast <Cookie>().ToList(); if (!cookies.Any(a => a.Name == "adbsess" && !string.IsNullOrEmpty(a.Value))) { return(null); } WebCache_AniDBLoggedInfo logged = new WebCache_AniDBLoggedInfo(); logged.Cookies = cookies.ToDictionary(a => a.Name, a => a.Value); logged.UserName = ServerSettings.Instance.AniDb.Username; try { WebCache_SessionInfo session = cclient.Verify(logged); ServerSettings.Instance.WebCache.Session = session; ServerSettings.Instance.SaveSettings(); return(GetToken()); } catch (SwaggerException e) { if (e.StatusCode == 403) { ServerSettings.Instance.WebCache.BannedReason = "Unable to login to AniDB"; ServerSettings.Instance.WebCache.BannedExpiration = DateTime.UtcNow.AddHours(1); logger.Error("Unable to login to AniDB, waiting for 1 hour. Error:" + e); return(null); } logger.Error("Unable to login to AniDB. Error: " + e); return(null); } } ServerSettings.Instance.WebCache.BannedReason = "Unable to login to AniDB"; ServerSettings.Instance.WebCache.BannedExpiration = DateTime.UtcNow.AddHours(1); logger.Error("Unable to login to AniDB, waiting for 1 hour"); } return(null); } return(token); }