Esempio n. 1
0
        public static void Initialize(CocApi cocApi, CocApiConfiguration cfg, IEnumerable <string> tokens)
        {
            _cocApi = cocApi;

            _cfg = cfg;

            ApiClient.DefaultRequestHeaders.Accept.Clear();

            ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            foreach (string token in tokens)
            {
                TokenObject tokenObject = new TokenObject(cocApi, token, _cfg.TokenTimeOut);

                _tokenObjects.Add(tokenObject);
            }

            _jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        }
Esempio n. 2
0
        internal static async Task <IDownloadable> GetWebResponse <T>(EndPoint endPoint, string encodedUrl, CancellationTokenSource?cancellationTokenSource = null) where T : class, IDownloadable, new()
        {
            Stopwatch stopwatch = new Stopwatch();

            try
            {
                _cocApi.Logger?.LogDebug("{source} {encodedUrl}", _source, encodedUrl.Replace("https://api.clashofclans.com/v1", ""));

                TokenObject token = await GetTokenAsync(endPoint, encodedUrl);

                using CancellationTokenSource cts = new CancellationTokenSource(_cfg.TimeToWaitForWebRequests);

                cancellationTokenSource?.Token.Register(() => cts?.Cancel());

                ApiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);

                stopwatch.Start();

                using HttpResponseMessage response = await ApiClient.GetAsync(encodedUrl, cts.Token);

                stopwatch.Stop();

                DateTime?cacheExpires = GetCacheExpirationDate(response);

                string responseText = response.Content.ReadAsStringAsync().Result;

                if (response.IsSuccessStatusCode)
                {
                    _cocApi.IsAvailable = true;

                    T result = JsonSerializer.Deserialize <T>(responseText, _jsonSerializerOptions);

                    if (result != null)
                    {
                        if (result is CurrentWarApiModel currentWar && currentWar.PreparationStartTimeUtc == DateTime.MinValue)
                        {
                            var notInWar = new NotInWar();

                            PrepareResult(notInWar, endPoint, stopwatch, response, encodedUrl);

                            return(notInWar);
                        }
                        else
                        {
                            PrepareResult(result, endPoint, stopwatch, response, encodedUrl);

                            return(result);
                        }



                        //WebResponseTimers.Add(new WebResponseTimer(endPoint, stopwatch.Elapsed, response.StatusCode));

                        //if (result is IInitialize process)
                        //{
                        //    process.Initialize();
                        //}

                        //SetIDownloadableProperties(result, encodedUrl);

                        //SetRelationalProperties(result);

                        //if (cacheExpires.HasValue)
                        //{
                        //    result.CacheExpiresAtUtc = cacheExpires;
                        //}

                        //return result;
                    }
                    else
                    {
                        throw new CocApiException("The response could not be parsed.");
                    }
                }
                else
                {
                    ResponseMessageApiModel ex = JsonSerializer.Deserialize <ResponseMessageApiModel>(responseText, _jsonSerializerOptions);

                    WebResponseTimers.Add(new WebResponseTimer(endPoint, stopwatch.Elapsed, response.StatusCode));

                    if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) //400
                    {
                        throw new BadRequestException(ex, response.StatusCode);
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.Forbidden) //403
                    {
                        throw new ForbiddenException(ex, response.StatusCode);
                    }

                    else if (response.StatusCode == System.Net.HttpStatusCode.NotFound && endPoint == EndPoint.LeagueGroup)
                    {
                        var leagueGroupNotFound = new LeagueGroupNotFound
                        {
                            CacheExpiresAtUtc = GetCacheExpirationDate(response)
                        };

                        SetIDownloadableProperties(leagueGroupNotFound, encodedUrl);

                        return(leagueGroupNotFound);
                    }

                    else if (response.StatusCode == System.Net.HttpStatusCode.NotFound) //404
                    {
                        throw new NotFoundException(ex, response.StatusCode);
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests) //429
                    {
                        token.IsRateLimited = true;

                        throw new TooManyRequestsException(ex, response.StatusCode);
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError) //500
                    {
                        throw new InternalServerErrorException(ex, response.StatusCode);
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway) //502
                    {
                        _cocApi.IsAvailable = false;

                        throw new BadGateWayException(ex, response.StatusCode);
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable) //503
                    {
                        _cocApi.IsAvailable = false;

                        throw new ServiceUnavailableException(ex, response.StatusCode);
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.GatewayTimeout)  //504
                    {
                        _cocApi.IsAvailable = false;

                        throw new GatewayTimeoutException(ex, response.StatusCode);
                    }

                    throw new ServerResponseException(ex, response.StatusCode);
                }
            }