コード例 #1
0
        private OAuth2Token GetBearerAuthenticationToken(APIClient apiClient)
        {
            OAuth2Token receivedOAuth2Token = new OAuth2Token();

            FormUrlEncodedContent requestContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>(APIConf.BlizzardAPIWowClientIDParameter, apiClient.ClientID),
                new KeyValuePair <string, string>(APIConf.BlizzardAPIWowClientSecretParameter, apiClient.ClientSecret),
                new KeyValuePair <string, string>(APIConf.BlizzardAPIWowGrantTypeParameter, APIConf.BlizzardAPIWowClientCredentialsParameter)
            });

            using (HttpClient httpClient = new HttpClient())
            {
                var response = httpClient.PostAsync(APIConf.BlizzardAPIWowOAuthTokenAdress, requestContent);
                response.Wait();

                if (response.Result.IsSuccessStatusCode)
                {
                    var responseResult = response.Result.Content.ReadAsStringAsync().Result;
                    receivedOAuth2Token = JsonProcessing.DeserializeJsonData <OAuth2Token>(responseResult);
                }
                else
                {
                    throw new Exception($"{InternalMessages.BearerAuthFailed }. {response.Result.ReasonPhrase}");
                }
            }

            return(receivedOAuth2Token);
        }
        internal async Task <List <string> > GetRealmListByRegion(Region region)
        {
            List <string> realmsNames      = new List <string>();
            string        regionCoreAdress = string.Empty;

            try
            {
                if (APIConf.BlizzadAPIAddressWrapper.TryGetValue(region, out regionCoreAdress) == false)
                {
                    throw new KeyNotFoundException($"Cannot find region in {APIConf.BlizzadAPIAddressWrapper.GetType().Name} dictionary");
                }

                var requestLocalization = new RequestLocalization()
                {
                    CoreRegionUrlAddress = regionCoreAdress,
                };

                RealmsRequests realmsRequests = new RealmsRequests(_comparerDatabaseContext);

                var         parameters    = new List <KeyValuePair <string, string> >();
                Uri         uriAddress    = RequestLinkFormater.GenerateAPIRequestLink(BlizzardAPIProfiles.Realm, requestLocalization, parameters, "status"); //TODO replace string
                var         realmResponse = await new APIDataRequestManager(_comparerDatabaseContext).GetDataByHttpRequest <BlizzardAPIResponse>(uriAddress);
                RealmStatus realmStatus   = JsonProcessing.DeserializeJsonData <RealmStatus>(realmResponse.Data);

                foreach (Realm realmsData in realmStatus.Realms)
                {
                    realmsNames.Add(realmsData.Name);
                }
            }
            catch (Exception)
            {
                realmsNames = new List <string>();
            }

            return(realmsNames);
        }
        public async Task <IActionResult> CompareCharacters(ExtendedCharacterModel firstCharacter, ExtendedCharacterModel secondCharacter)
        {
            var charactersToCompare = new List <ExtendedCharacterModel>()
            {
                firstCharacter, secondCharacter
            };
            var processedCharacterData = new List <ProcessedCharacterViewModel>();

            foreach (ExtendedCharacterModel character in charactersToCompare)
            {
                RequestLocalization requestLocalization = new RequestLocalization()
                {
                    CoreRegionUrlAddress = APIConf.BlizzadAPIAddressWrapper.ContainsKey(EnumDictionaryWrapper.viewRegionsWrapper.ContainsKey(character.Region) ?
                                                                                        EnumDictionaryWrapper.viewRegionsWrapper[character.Region]
                                            : throw new NotSupportedException("Region not supported")) ?
                                           APIConf.BlizzadAPIAddressWrapper[EnumDictionaryWrapper.viewRegionsWrapper[character.Region]]
                                                : throw new NotSupportedException("Core region url not supported"),

                                                 Realm = new Realm()
                                                 {
                                                     Slug   = character.ServerName.ToLower().Replace(" ", "-"),
                                                     Locale = StringDictionaryWrapper.viewLocaleWrapper.ContainsKey(character.Region) ?
                                                              StringDictionaryWrapper.viewLocaleWrapper[character.Region]
                                    : throw new NotSupportedException("Locale not supported"),
                                                 }
                };

                var selectedCharacterFields = new List <CharacterFields>();

                //TODO find better way to process it
                if (character.ItemsField)
                {
                    selectedCharacterFields.Add(CharacterFields.Items);
                }
                if (character.AchievementsField)
                {
                    selectedCharacterFields.Add(CharacterFields.Achievements);
                }
                if (character.ProgressionField)
                {
                    selectedCharacterFields.Add(CharacterFields.Progression);
                }
                if (character.PVPField)
                {
                    selectedCharacterFields.Add(CharacterFields.PVP);
                }
                if (character.ReputationField)
                {
                    selectedCharacterFields.Add(CharacterFields.Reputation);
                }
                if (character.StatisticsField)
                {
                    selectedCharacterFields.Add(CharacterFields.Statistics);
                }
                if (character.TalentsField)
                {
                    selectedCharacterFields.Add(CharacterFields.Talents);
                }

                var result = await new CharacterRequests(_iAPIDataRequestManager).GetCharacterDataAsJsonAsync(character.Name, requestLocalization, selectedCharacterFields);

                if (result.Exception != null)
                {
                    return(View("CompareResult", result.Exception.Message));
                }

                ExtendedCharacterModel       currentCharacter     = JsonProcessing.DeserializeJsonData <ExtendedCharacterModel>(result.Data);
                CharacterExtendedDataManager characterDataManager = new CharacterExtendedDataManager(_comparerDatabaseContext);

                processedCharacterData.Add(new ProcessedCharacterViewModel()
                {
                    BasicCharacterData = new BasicCharacterViewModel
                    {
                        Name  = currentCharacter.Name,
                        Class = IntDictionaryWrapper.characterClassWrapper.ContainsKey(currentCharacter.CharacterClass) ?
                                IntDictionaryWrapper.characterClassWrapper[currentCharacter.CharacterClass] : string.Empty,
                        Race = IntDictionaryWrapper.characterRaceWrapper.ContainsKey(currentCharacter.Race) ?
                               IntDictionaryWrapper.characterRaceWrapper[currentCharacter.Race] : string.Empty,
                        Level               = currentCharacter.Level,
                        AchievementPoints   = currentCharacter.AchievementPoints,
                        Thumbnail           = currentCharacter.Thumbnail,
                        Faction             = currentCharacter.Faction.ToString(),
                        TotalHonorableKills = currentCharacter.TotalHonorableKills
                    },

                    AchievementsData = characterDataManager.MatchCompletedPlayerAchievement(currentCharacter),
                    Items            = characterDataManager.MatchItemsBonusStatistics(currentCharacter.Items),
                    Progression      = currentCharacter.Progression ?? new Models.CharacterProfile.ProgressionModels.Progression(),
                    Pvp        = currentCharacter.Pvp ?? new Models.CharacterProfile.PvpModels.Pvp(),
                    Reputation = currentCharacter.Reputation ?? new List <Reputation>().ToArray(),
                    Statistics = currentCharacter.Statistics ?? new Models.CharacterProfile.StatisticsModels.Statistics(),
                    Talents    = currentCharacter.Talents ?? new List <Models.CharacterProfile.TalentsModels.Talents>().ToArray(),
                    CharStats  = currentCharacter.Stats ?? new Stats(),
                    Mounts     = currentCharacter.Mounts ?? new Models.CharacterProfile.MountsModels.Mounts(),
                    Pets       = currentCharacter.Pets ?? new Models.CharacterProfile.PetsModels.Pets()
                });
            }

            //TODO: Maybe those whole compilers object should be moved to 1 class ?
            compareResultViewModel = new CompareResultViewModel()
            {
                ProcessedCharacterViewModel    = processedCharacterData,
                AchievementPointsCompareResult = new AchievementPointsComparer().CompareAchievementPoints(processedCharacterData),
                ArenaRatingsCompareResult      = new RatingComparer().CompareRating(processedCharacterData),
                HeartOfAzerothCompareResult    = new HeartOfAzerothComparer().CompareHeartOfAzerothLevel(processedCharacterData),
                HonorableKillsCompareResult    = new HonorableKillsComparer().CompareHonorableKills(processedCharacterData),
                ItemLevelCompareResult         = new ItemLevelComparer().CompareCharactersItemLevel(processedCharacterData),
                MiniPetsCompareResult          = new MiniPetsComparer().CompareMiniPets(processedCharacterData),
                MountsCompareResult            = new MountsComparer().CompareMounts(processedCharacterData),
                StatisticsCompareResult        = new StatisticsComparer().CompareCharacterStatistics(processedCharacterData)
            };

            return(Json(new
            {
                message = "success",
                url = Url.Action(nameof(RedirectToComparatorResult), GetType().Name.Remove(GetType().Name.Length - "Controller".Length))
            }));
        }